SkiaShader.cpp revision a0ed6f03f6f06eb41cbcc15c0a99b4a78fd91bef
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 "SkiaShader.h"
18
19#include "Caches.h"
20#include "Extensions.h"
21#include "Layer.h"
22#include "Matrix.h"
23#include "Texture.h"
24#include "hwui/Bitmap.h"
25
26#include <SkMatrix.h>
27#include <utils/Log.h>
28
29namespace android {
30namespace uirenderer {
31
32///////////////////////////////////////////////////////////////////////////////
33// Support
34///////////////////////////////////////////////////////////////////////////////
35
36static constexpr GLenum gTileModes[] = {
37        GL_CLAMP_TO_EDGE,   // == SkShader::kClamp_TileMode
38        GL_REPEAT,          // == SkShader::kRepeat_Mode
39        GL_MIRRORED_REPEAT  // == SkShader::kMirror_TileMode
40};
41
42static_assert(gTileModes[SkShader::kClamp_TileMode] == GL_CLAMP_TO_EDGE,
43        "SkShader TileModes have changed");
44static_assert(gTileModes[SkShader::kRepeat_TileMode] == GL_REPEAT,
45        "SkShader TileModes have changed");
46static_assert(gTileModes[SkShader::kMirror_TileMode] == GL_MIRRORED_REPEAT,
47        "SkShader TileModes have changed");
48
49/**
50 * This function does not work for n == 0.
51 */
52static inline bool isPowerOfTwo(unsigned int n) {
53    return !(n & (n - 1));
54}
55
56static inline void bindUniformColor(int slot, FloatColor color) {
57    glUniform4fv(slot, 1, reinterpret_cast<const float*>(&color));
58}
59
60static inline void bindTexture(Caches* caches, Texture* texture, GLenum wrapS, GLenum wrapT) {
61    caches->textureState().bindTexture(texture->target(), texture->id());
62    texture->setWrapST(wrapS, wrapT);
63}
64
65/**
66 * Compute the matrix to transform to screen space.
67 * @param screenSpace Output param for the computed matrix.
68 * @param unitMatrix The unit matrix for gradient shaders, as returned by SkShader::asAGradient,
69 *      or identity.
70 * @param localMatrix Local matrix, as returned by SkShader::getLocalMatrix().
71 * @param modelViewMatrix Model view matrix, as supplied by the OpenGLRenderer.
72 */
73static void computeScreenSpaceMatrix(mat4& screenSpace, const SkMatrix& unitMatrix,
74        const SkMatrix& localMatrix, const mat4& modelViewMatrix) {
75    mat4 shaderMatrix;
76    // uses implicit construction
77    shaderMatrix.loadInverse(localMatrix);
78    // again, uses implicit construction
79    screenSpace.loadMultiply(unitMatrix, shaderMatrix);
80    screenSpace.multiply(modelViewMatrix);
81}
82
83///////////////////////////////////////////////////////////////////////////////
84// Gradient shader matrix helpers
85///////////////////////////////////////////////////////////////////////////////
86
87static void toLinearUnitMatrix(const SkPoint pts[2], SkMatrix* matrix) {
88    SkVector vec = pts[1] - pts[0];
89    const float mag = vec.length();
90    const float inv = mag ? 1.0f / mag : 0;
91
92    vec.scale(inv);
93    matrix->setSinCos(-vec.fY, vec.fX, pts[0].fX, pts[0].fY);
94    matrix->postTranslate(-pts[0].fX, -pts[0].fY);
95    matrix->postScale(inv, inv);
96}
97
98static void toCircularUnitMatrix(const float x, const float y, const float radius,
99        SkMatrix* matrix) {
100    const float inv = 1.0f / radius;
101    matrix->setTranslate(-x, -y);
102    matrix->postScale(inv, inv);
103}
104
105static void toSweepUnitMatrix(const float x, const float y, SkMatrix* matrix) {
106    matrix->setTranslate(-x, -y);
107}
108
109///////////////////////////////////////////////////////////////////////////////
110// Common gradient code
111///////////////////////////////////////////////////////////////////////////////
112
113static bool isSimpleGradient(const SkShader::GradientInfo& gradInfo) {
114    return gradInfo.fColorCount == 2 && gradInfo.fTileMode == SkShader::kClamp_TileMode;
115}
116
117///////////////////////////////////////////////////////////////////////////////
118// Store / apply
119///////////////////////////////////////////////////////////////////////////////
120
121bool tryStoreGradient(Caches& caches, const SkShader& shader, const Matrix4 modelViewMatrix,
122        GLuint* textureUnit, ProgramDescription* description,
123        SkiaShaderData::GradientShaderData* outData) {
124    SkShader::GradientInfo gradInfo;
125    gradInfo.fColorCount = 0;
126    gradInfo.fColors = nullptr;
127    gradInfo.fColorOffsets = nullptr;
128
129    SkMatrix unitMatrix;
130    switch (shader.asAGradient(&gradInfo)) {
131        case SkShader::kLinear_GradientType:
132            description->gradientType = ProgramDescription::kGradientLinear;
133
134            toLinearUnitMatrix(gradInfo.fPoint, &unitMatrix);
135            break;
136        case SkShader::kRadial_GradientType:
137            description->gradientType = ProgramDescription::kGradientCircular;
138
139            toCircularUnitMatrix(gradInfo.fPoint[0].fX, gradInfo.fPoint[0].fY,
140                    gradInfo.fRadius[0], &unitMatrix);
141            break;
142        case SkShader::kSweep_GradientType:
143            description->gradientType = ProgramDescription::kGradientSweep;
144
145            toSweepUnitMatrix(gradInfo.fPoint[0].fX, gradInfo.fPoint[0].fY, &unitMatrix);
146            break;
147        default:
148            // Do nothing. This shader is unsupported.
149            return false;
150    }
151    description->hasGradient = true;
152    description->isSimpleGradient = isSimpleGradient(gradInfo);
153
154    computeScreenSpaceMatrix(outData->screenSpace, unitMatrix,
155            shader.getLocalMatrix(), modelViewMatrix);
156
157    // re-query shader to get full color / offset data
158    std::unique_ptr<SkColor[]> colorStorage(new SkColor[gradInfo.fColorCount]);
159    std::unique_ptr<SkScalar[]> colorOffsets(new SkScalar[gradInfo.fColorCount]);
160    gradInfo.fColors = &colorStorage[0];
161    gradInfo.fColorOffsets = &colorOffsets[0];
162    shader.asAGradient(&gradInfo);
163
164    if (CC_UNLIKELY(!description->isSimpleGradient)) {
165        outData->gradientSampler = (*textureUnit)++;
166
167#ifndef SK_SCALAR_IS_FLOAT
168    #error Need to convert gradInfo.fColorOffsets to float!
169#endif
170        outData->gradientTexture = caches.gradientCache.get(
171                gradInfo.fColors, gradInfo.fColorOffsets, gradInfo.fColorCount);
172        outData->wrapST = gTileModes[gradInfo.fTileMode];
173    } else {
174        outData->gradientSampler = 0;
175        outData->gradientTexture = nullptr;
176
177        outData->startColor.setUnPreMultipliedSRGB(gradInfo.fColors[0]);
178        outData->endColor.setUnPreMultipliedSRGB(gradInfo.fColors[1]);
179    }
180
181    return true;
182}
183
184void applyGradient(Caches& caches, const SkiaShaderData::GradientShaderData& data,
185        const GLsizei width, const GLsizei height) {
186
187    if (CC_UNLIKELY(data.gradientTexture)) {
188        caches.textureState().activateTexture(data.gradientSampler);
189        bindTexture(&caches, data.gradientTexture, data.wrapST, data.wrapST);
190        glUniform1i(caches.program().getUniform("gradientSampler"), data.gradientSampler);
191    } else {
192        bindUniformColor(caches.program().getUniform("startColor"), data.startColor);
193        bindUniformColor(caches.program().getUniform("endColor"), data.endColor);
194    }
195
196    glUniform2f(caches.program().getUniform("screenSize"), 1.0f / width, 1.0f / height);
197    glUniformMatrix4fv(caches.program().getUniform("screenSpace"), 1,
198            GL_FALSE, &data.screenSpace.data[0]);
199}
200
201bool tryStoreBitmap(Caches& caches, const SkShader& shader, const Matrix4& modelViewMatrix,
202        GLuint* textureUnit, ProgramDescription* description,
203        SkiaShaderData::BitmapShaderData* outData) {
204    SkBitmap bitmap;
205    SkShader::TileMode xy[2];
206    if (!shader.isABitmap(&bitmap, nullptr, xy)) {
207        return false;
208    }
209
210    // TODO: create  hwui-owned BitmapShader.
211    Bitmap* hwuiBitmap = static_cast<Bitmap*>(bitmap.pixelRef());
212    outData->bitmapTexture = caches.textureCache.get(hwuiBitmap);
213    if (!outData->bitmapTexture) return false;
214
215    outData->bitmapSampler = (*textureUnit)++;
216
217    const float width = outData->bitmapTexture->width();
218    const float height = outData->bitmapTexture->height();
219
220    description->hasBitmap = true;
221    // gralloc doesn't support non-clamp modes
222    if (hwuiBitmap->isHardware() || (!caches.extensions().hasNPot()
223            && (!isPowerOfTwo(width) || !isPowerOfTwo(height))
224            && (xy[0] != SkShader::kClamp_TileMode || xy[1] != SkShader::kClamp_TileMode))) {
225        // need non-clamp mode, but it's not supported for this draw,
226        // so enable custom shader logic to mimic
227        description->useShaderBasedWrap = true;
228        description->bitmapWrapS = gTileModes[xy[0]];
229        description->bitmapWrapT = gTileModes[xy[1]];
230
231        outData->wrapS = GL_CLAMP_TO_EDGE;
232        outData->wrapT = GL_CLAMP_TO_EDGE;
233    } else {
234        outData->wrapS = gTileModes[xy[0]];
235        outData->wrapT = gTileModes[xy[1]];
236    }
237
238    computeScreenSpaceMatrix(outData->textureTransform, SkMatrix::I(), shader.getLocalMatrix(),
239            modelViewMatrix);
240    outData->textureDimension[0] = 1.0f / width;
241    outData->textureDimension[1] = 1.0f / height;
242
243    return true;
244}
245
246void applyBitmap(Caches& caches, const SkiaShaderData::BitmapShaderData& data) {
247    caches.textureState().activateTexture(data.bitmapSampler);
248    bindTexture(&caches, data.bitmapTexture, data.wrapS, data.wrapT);
249    data.bitmapTexture->setFilter(GL_LINEAR);
250
251    glUniform1i(caches.program().getUniform("bitmapSampler"), data.bitmapSampler);
252    glUniformMatrix4fv(caches.program().getUniform("textureTransform"), 1, GL_FALSE,
253            &data.textureTransform.data[0]);
254    glUniform2fv(caches.program().getUniform("textureDimension"), 1, &data.textureDimension[0]);
255}
256
257SkiaShaderType getComposeSubType(const SkShader& shader) {
258    // First check for a gradient shader.
259    switch (shader.asAGradient(nullptr)) {
260        case SkShader::kNone_GradientType:
261            // Not a gradient shader. Fall through to check for other types.
262            break;
263        case SkShader::kLinear_GradientType:
264        case SkShader::kRadial_GradientType:
265        case SkShader::kSweep_GradientType:
266            return kGradient_SkiaShaderType;
267        default:
268            // This is a Skia gradient that has no SkiaShader equivalent. Return None to skip.
269            return kNone_SkiaShaderType;
270    }
271
272    // The shader is not a gradient. Check for a bitmap shader.
273    if (shader.isABitmap()) {
274        return kBitmap_SkiaShaderType;
275    }
276    return kNone_SkiaShaderType;
277}
278
279void storeCompose(Caches& caches, const SkShader& bitmapShader, const SkShader& gradientShader,
280        const Matrix4& modelViewMatrix, GLuint* textureUnit,
281        ProgramDescription* description, SkiaShaderData* outData) {
282    LOG_ALWAYS_FATAL_IF(!tryStoreBitmap(caches, bitmapShader, modelViewMatrix,
283                textureUnit, description, &outData->bitmapData),
284            "failed storing bitmap shader data");
285    LOG_ALWAYS_FATAL_IF(!tryStoreGradient(caches, gradientShader, modelViewMatrix,
286                textureUnit, description, &outData->gradientData),
287            "failing storing gradient shader data");
288}
289
290bool tryStoreCompose(Caches& caches, const SkShader& shader, const Matrix4& modelViewMatrix,
291        GLuint* textureUnit, ProgramDescription* description,
292        SkiaShaderData* outData) {
293
294    SkShader::ComposeRec rec;
295    if (!shader.asACompose(&rec)) return false;
296
297    const SkiaShaderType shaderAType = getComposeSubType(*rec.fShaderA);
298    const SkiaShaderType shaderBType = getComposeSubType(*rec.fShaderB);
299
300    // check that type enum values are the 2 flags that compose the kCompose value
301    if ((shaderAType & shaderBType) != 0) return false;
302    if ((shaderAType | shaderBType) != kCompose_SkiaShaderType) return false;
303
304    mat4 transform;
305    computeScreenSpaceMatrix(transform, SkMatrix::I(), shader.getLocalMatrix(), modelViewMatrix);
306    if (shaderAType == kBitmap_SkiaShaderType) {
307        description->isBitmapFirst = true;
308        storeCompose(caches, *rec.fShaderA, *rec.fShaderB,
309                transform, textureUnit, description, outData);
310    } else {
311        description->isBitmapFirst = false;
312        storeCompose(caches, *rec.fShaderB, *rec.fShaderA,
313                transform, textureUnit, description, outData);
314    }
315    description->shadersMode = rec.fBlendMode;
316    return true;
317}
318
319bool tryStoreLayer(Caches& caches, const SkShader& shader, const Matrix4& modelViewMatrix,
320        GLuint* textureUnit, ProgramDescription* description,
321        SkiaShaderData::LayerShaderData* outData) {
322    Layer* layer;
323    if (!shader.asACustomShader(reinterpret_cast<void**>(&layer))) {
324        return false;
325    }
326
327    description->hasBitmap = true;
328    outData->layer = layer;
329    outData->bitmapSampler = (*textureUnit)++;
330
331    const float width = layer->getWidth();
332    const float height = layer->getHeight();
333
334    computeScreenSpaceMatrix(outData->textureTransform, SkMatrix::I(), shader.getLocalMatrix(),
335            modelViewMatrix);
336
337    outData->textureDimension[0] = 1.0f / width;
338    outData->textureDimension[1] = 1.0f / height;
339    return true;
340}
341
342void applyLayer(Caches& caches, const SkiaShaderData::LayerShaderData& data) {
343    caches.textureState().activateTexture(data.bitmapSampler);
344
345    data.layer->bindTexture();
346    data.layer->setWrap(GL_CLAMP_TO_EDGE);
347    data.layer->setFilter(GL_LINEAR);
348
349    glUniform1i(caches.program().getUniform("bitmapSampler"), data.bitmapSampler);
350    glUniformMatrix4fv(caches.program().getUniform("textureTransform"), 1,
351            GL_FALSE, &data.textureTransform.data[0]);
352    glUniform2fv(caches.program().getUniform("textureDimension"), 1, &data.textureDimension[0]);
353}
354
355void SkiaShader::store(Caches& caches, const SkShader& shader, const Matrix4& modelViewMatrix,
356        GLuint* textureUnit, ProgramDescription* description,
357        SkiaShaderData* outData) {
358    if (tryStoreGradient(caches, shader, modelViewMatrix,
359            textureUnit, description, &outData->gradientData)) {
360        outData->skiaShaderType = kGradient_SkiaShaderType;
361        return;
362    }
363
364    if (tryStoreBitmap(caches, shader, modelViewMatrix,
365            textureUnit, description, &outData->bitmapData)) {
366        outData->skiaShaderType = kBitmap_SkiaShaderType;
367        return;
368    }
369
370    if (tryStoreCompose(caches, shader, modelViewMatrix,
371            textureUnit, description, outData)) {
372        outData->skiaShaderType = kCompose_SkiaShaderType;
373        return;
374    }
375
376    if (tryStoreLayer(caches, shader, modelViewMatrix,
377            textureUnit, description, &outData->layerData)) {
378        outData->skiaShaderType = kLayer_SkiaShaderType;
379        return;
380    }
381
382    // Unknown/unsupported type, so explicitly ignore shader
383    outData->skiaShaderType = kNone_SkiaShaderType;
384}
385
386void SkiaShader::apply(Caches& caches, const SkiaShaderData& data,
387        const GLsizei width, const GLsizei height) {
388    if (!data.skiaShaderType) return;
389
390    if (data.skiaShaderType & kGradient_SkiaShaderType) {
391        applyGradient(caches, data.gradientData, width, height);
392    }
393    if (data.skiaShaderType & kBitmap_SkiaShaderType) {
394        applyBitmap(caches, data.bitmapData);
395    }
396
397    if (data.skiaShaderType == kLayer_SkiaShaderType) {
398        applyLayer(caches, data.layerData);
399    }
400}
401
402}; // namespace uirenderer
403}; // namespace android
404