OpenGLRenderer.cpp revision a1db574036c9bc2d397b69f8200594027e1fff16
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#define LOG_TAG "OpenGLRenderer"
18
19#include <stdlib.h>
20#include <stdint.h>
21#include <sys/types.h>
22
23#include <SkCanvas.h>
24
25#include <cutils/properties.h>
26#include <utils/Log.h>
27
28#include "OpenGLRenderer.h"
29
30namespace android {
31namespace uirenderer {
32
33///////////////////////////////////////////////////////////////////////////////
34// Defines
35///////////////////////////////////////////////////////////////////////////////
36
37// These properties are defined in mega-bytes
38#define PROPERTY_TEXTURE_CACHE_SIZE "ro.hwui.texture_cache_size"
39#define PROPERTY_LAYER_CACHE_SIZE "ro.hwui.layer_cache_size"
40#define PROPERTY_GRADIENT_CACHE_SIZE "ro.hwui.gradient_cache_size"
41
42#define DEFAULT_TEXTURE_CACHE_SIZE 20.0f
43#define DEFAULT_LAYER_CACHE_SIZE 10.0f
44#define DEFAULT_PATCH_CACHE_SIZE 100
45#define DEFAULT_GRADIENT_CACHE_SIZE 0.5f
46
47// Converts a number of mega-bytes into bytes
48#define MB(s) s * 1024 * 1024
49
50// Generates simple and textured vertices
51#define SV(x, y) { { x, y } }
52#define FV(x, y, u, v) { { x, y }, { u, v } }
53
54///////////////////////////////////////////////////////////////////////////////
55// Globals
56///////////////////////////////////////////////////////////////////////////////
57
58static const SimpleVertex gDrawColorVertices[] = {
59        SV(0.0f, 0.0f),
60        SV(1.0f, 0.0f),
61        SV(0.0f, 1.0f),
62        SV(1.0f, 1.0f)
63};
64static const GLsizei gDrawColorVertexStride = sizeof(SimpleVertex);
65static const GLsizei gDrawColorVertexCount = 4;
66
67// This array is never used directly but used as a memcpy source in the
68// OpenGLRenderer constructor
69static const TextureVertex gDrawTextureVertices[] = {
70        FV(0.0f, 0.0f, 0.0f, 0.0f),
71        FV(1.0f, 0.0f, 1.0f, 0.0f),
72        FV(0.0f, 1.0f, 0.0f, 1.0f),
73        FV(1.0f, 1.0f, 1.0f, 1.0f)
74};
75static const GLsizei gDrawTextureVertexStride = sizeof(TextureVertex);
76static const GLsizei gDrawTextureVertexCount = 4;
77
78// In this array, the index of each Blender equals the value of the first
79// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
80static const Blender gBlends[] = {
81        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
82        { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
83        { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
84        { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
85        { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
86        { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
87        { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
88        { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
89        { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
90        { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
91        { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
92        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
93};
94
95static const GLint gTileModes[] = {
96        GL_CLAMP_TO_EDGE,   // == SkShader::kClamp_TileMode
97        GL_REPEAT,          // == SkShader::kRepeat_Mode
98        GL_MIRRORED_REPEAT  // == SkShader::kMirror_TileMode
99};
100
101///////////////////////////////////////////////////////////////////////////////
102// Constructors/destructor
103///////////////////////////////////////////////////////////////////////////////
104
105OpenGLRenderer::OpenGLRenderer():
106        mBlend(false), mLastSrcMode(GL_ZERO), mLastDstMode(GL_ZERO),
107        mTextureCache(MB(DEFAULT_TEXTURE_CACHE_SIZE)),
108        mLayerCache(MB(DEFAULT_LAYER_CACHE_SIZE)),
109        mGradientCache(MB(DEFAULT_GRADIENT_CACHE_SIZE)),
110        mPatchCache(DEFAULT_PATCH_CACHE_SIZE) {
111    LOGD("Create OpenGLRenderer");
112
113    char property[PROPERTY_VALUE_MAX];
114    if (property_get(PROPERTY_TEXTURE_CACHE_SIZE, property, NULL) > 0) {
115        LOGD("  Setting texture cache size to %sMB", property);
116        mTextureCache.setMaxSize(MB(atof(property)));
117    } else {
118        LOGD("  Using default texture cache size of %.2fMB", DEFAULT_TEXTURE_CACHE_SIZE);
119    }
120
121    if (property_get(PROPERTY_LAYER_CACHE_SIZE, property, NULL) > 0) {
122        LOGD("  Setting layer cache size to %sMB", property);
123        mLayerCache.setMaxSize(MB(atof(property)));
124    } else {
125        LOGD("  Using default layer cache size of %.2fMB", DEFAULT_LAYER_CACHE_SIZE);
126    }
127
128    if (property_get(PROPERTY_GRADIENT_CACHE_SIZE, property, NULL) > 0) {
129        LOGD("  Setting gradient cache size to %sMB", property);
130        mLayerCache.setMaxSize(MB(atof(property)));
131    } else {
132        LOGD("  Using default gradient cache size of %.2fMB", DEFAULT_GRADIENT_CACHE_SIZE);
133    }
134
135    mDrawColorProgram = new DrawColorProgram;
136    mDrawTextureProgram = new DrawTextureProgram;
137    mDrawLinearGradientProgram = new DrawLinearGradientProgram;
138    mCurrentProgram = mDrawTextureProgram;
139
140    mShader = kShaderNone;
141    mShaderTileX = GL_CLAMP_TO_EDGE;
142    mShaderTileY = GL_CLAMP_TO_EDGE;
143    mShaderMatrix = NULL;
144    mShaderBitmap = NULL;
145
146    mLastTexture = 0;
147
148    memcpy(mDrawTextureVertices, gDrawTextureVertices, sizeof(gDrawTextureVertices));
149}
150
151OpenGLRenderer::~OpenGLRenderer() {
152    LOGD("Destroy OpenGLRenderer");
153
154    mTextureCache.clear();
155    mLayerCache.clear();
156    mGradientCache.clear();
157    mPatchCache.clear();
158}
159
160///////////////////////////////////////////////////////////////////////////////
161// Setup
162///////////////////////////////////////////////////////////////////////////////
163
164void OpenGLRenderer::setViewport(int width, int height) {
165    glViewport(0, 0, width, height);
166
167    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
168
169    mWidth = width;
170    mHeight = height;
171    mFirstSnapshot.height = height;
172}
173
174void OpenGLRenderer::prepare() {
175    mSnapshot = &mFirstSnapshot;
176    mSaveCount = 0;
177
178    glDisable(GL_SCISSOR_TEST);
179
180    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
181    glClear(GL_COLOR_BUFFER_BIT);
182
183    glEnable(GL_SCISSOR_TEST);
184    glScissor(0, 0, mWidth, mHeight);
185
186    mSnapshot->clipRect.set(0.0f, 0.0f, mWidth, mHeight);
187}
188
189///////////////////////////////////////////////////////////////////////////////
190// State management
191///////////////////////////////////////////////////////////////////////////////
192
193int OpenGLRenderer::getSaveCount() const {
194    return mSaveCount;
195}
196
197int OpenGLRenderer::save(int flags) {
198    return saveSnapshot();
199}
200
201void OpenGLRenderer::restore() {
202    if (mSaveCount == 0) return;
203
204    if (restoreSnapshot()) {
205        setScissorFromClip();
206    }
207}
208
209void OpenGLRenderer::restoreToCount(int saveCount) {
210    if (saveCount <= 0 || saveCount > mSaveCount) return;
211
212    bool restoreClip = false;
213
214    while (mSaveCount != saveCount - 1) {
215        restoreClip |= restoreSnapshot();
216    }
217
218    if (restoreClip) {
219        setScissorFromClip();
220    }
221}
222
223int OpenGLRenderer::saveSnapshot() {
224    mSnapshot = new Snapshot(mSnapshot);
225    return ++mSaveCount;
226}
227
228bool OpenGLRenderer::restoreSnapshot() {
229    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
230    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
231    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
232
233    sp<Snapshot> current = mSnapshot;
234    sp<Snapshot> previous = mSnapshot->previous;
235
236    if (restoreOrtho) {
237        mOrthoMatrix.load(current->orthoMatrix);
238    }
239
240    if (restoreLayer) {
241        composeLayer(current, previous);
242    }
243
244    mSnapshot = previous;
245    mSaveCount--;
246
247    return restoreClip;
248}
249
250void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
251    if (!current->layer) {
252        LOGE("Attempting to compose a layer that does not exist");
253        return;
254    }
255
256    // Unbind current FBO and restore previous one
257    // Most of the time, previous->fbo will be 0 to bind the default buffer
258    glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
259
260    // Restore the clip from the previous snapshot
261    const Rect& clip = previous->clipRect;
262    glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight());
263
264    Layer* layer = current->layer;
265
266    // Compute the correct texture coordinates for the FBO texture
267    // The texture is currently as big as the window but drawn with
268    // a quad of the appropriate size
269    const Rect& rect = layer->layer;
270
271    drawTextureRect(rect.left, rect.top, rect.right, rect.bottom,
272            layer->texture, layer->alpha, layer->mode, layer->blend);
273
274    LayerSize size(rect.getWidth(), rect.getHeight());
275    // Failing to add the layer to the cache should happen only if the
276    // layer is too large
277    if (!mLayerCache.put(size, layer)) {
278        LAYER_LOGD("Deleting layer");
279
280        glDeleteFramebuffers(1, &layer->fbo);
281        glDeleteTextures(1, &layer->texture);
282
283        delete layer;
284    }
285}
286
287///////////////////////////////////////////////////////////////////////////////
288// Layers
289///////////////////////////////////////////////////////////////////////////////
290
291int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
292        const SkPaint* p, int flags) {
293    int count = saveSnapshot();
294
295    int alpha = 255;
296    SkXfermode::Mode mode;
297
298    if (p) {
299        alpha = p->getAlpha();
300        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
301        if (!isMode) {
302            // Assume SRC_OVER
303            mode = SkXfermode::kSrcOver_Mode;
304        }
305    } else {
306        mode = SkXfermode::kSrcOver_Mode;
307    }
308
309    createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags);
310
311    return count;
312}
313
314int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
315        int alpha, int flags) {
316    int count = saveSnapshot();
317    createLayer(mSnapshot, left, top, right, bottom, alpha, SkXfermode::kSrcOver_Mode, flags);
318    return count;
319}
320
321bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
322        float right, float bottom, int alpha, SkXfermode::Mode mode,int flags) {
323
324    LAYER_LOGD("Requesting layer %fx%f", right - left, bottom - top);
325    LAYER_LOGD("Layer cache size = %d", mLayerCache.getSize());
326
327    GLuint previousFbo = snapshot->previous.get() ? snapshot->previous->fbo : 0;
328    LayerSize size(right - left, bottom - top);
329
330    Layer* layer = mLayerCache.get(size, previousFbo);
331    if (!layer) {
332        return false;
333    }
334
335    glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
336
337    // Clear the FBO
338    glDisable(GL_SCISSOR_TEST);
339    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
340    glClear(GL_COLOR_BUFFER_BIT);
341    glEnable(GL_SCISSOR_TEST);
342
343    // Save the layer in the snapshot
344    snapshot->flags |= Snapshot::kFlagIsLayer;
345    layer->mode = mode;
346    layer->alpha = alpha / 255.0f;
347    layer->layer.set(left, top, right, bottom);
348
349    snapshot->layer = layer;
350    snapshot->fbo = layer->fbo;
351
352    // Creates a new snapshot to draw into the FBO
353    saveSnapshot();
354    // TODO: This doesn't preserve other transformations (check Skia first)
355    mSnapshot->transform.loadTranslate(-left, -top, 0.0f);
356    mSnapshot->setClip(0.0f, 0.0f, right - left, bottom - top);
357    mSnapshot->height = bottom - top;
358    setScissorFromClip();
359
360    mSnapshot->flags = Snapshot::kFlagDirtyOrtho | Snapshot::kFlagClipSet;
361    mSnapshot->orthoMatrix.load(mOrthoMatrix);
362
363    // Change the ortho projection
364    mOrthoMatrix.loadOrtho(0.0f, right - left, bottom - top, 0.0f, 0.0f, 1.0f);
365
366    return true;
367}
368
369///////////////////////////////////////////////////////////////////////////////
370// Transforms
371///////////////////////////////////////////////////////////////////////////////
372
373void OpenGLRenderer::translate(float dx, float dy) {
374    mSnapshot->transform.translate(dx, dy, 0.0f);
375}
376
377void OpenGLRenderer::rotate(float degrees) {
378    mSnapshot->transform.rotate(degrees, 0.0f, 0.0f, 1.0f);
379}
380
381void OpenGLRenderer::scale(float sx, float sy) {
382    mSnapshot->transform.scale(sx, sy, 1.0f);
383}
384
385void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
386    mSnapshot->transform.load(*matrix);
387}
388
389void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
390    mSnapshot->transform.copyTo(*matrix);
391}
392
393void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
394    mat4 m(*matrix);
395    mSnapshot->transform.multiply(m);
396}
397
398///////////////////////////////////////////////////////////////////////////////
399// Clipping
400///////////////////////////////////////////////////////////////////////////////
401
402void OpenGLRenderer::setScissorFromClip() {
403    const Rect& clip = mSnapshot->clipRect;
404    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
405}
406
407const Rect& OpenGLRenderer::getClipBounds() {
408    return mSnapshot->getLocalClip();
409}
410
411bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
412    Rect r(left, top, right, bottom);
413    mSnapshot->transform.mapRect(r);
414    return !mSnapshot->clipRect.intersects(r);
415}
416
417bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
418    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
419    if (clipped) {
420        setScissorFromClip();
421    }
422    return !mSnapshot->clipRect.isEmpty();
423}
424
425///////////////////////////////////////////////////////////////////////////////
426// Drawing
427///////////////////////////////////////////////////////////////////////////////
428
429void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
430    const float right = left + bitmap->width();
431    const float bottom = top + bitmap->height();
432
433    if (quickReject(left, top, right, bottom)) {
434        return;
435    }
436
437    const Texture* texture = mTextureCache.get(bitmap);
438    drawTextureRect(left, top, right, bottom, texture, paint);
439}
440
441void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) {
442    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
443    const mat4 transform(*matrix);
444    transform.mapRect(r);
445
446    if (quickReject(r.left, r.top, r.right, r.bottom)) {
447        return;
448    }
449
450    const Texture* texture = mTextureCache.get(bitmap);
451    drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint);
452}
453
454void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
455         float srcLeft, float srcTop, float srcRight, float srcBottom,
456         float dstLeft, float dstTop, float dstRight, float dstBottom,
457         const SkPaint* paint) {
458    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
459        return;
460    }
461
462    const Texture* texture = mTextureCache.get(bitmap);
463
464    const float width = texture->width;
465    const float height = texture->height;
466
467    const float u1 = srcLeft / width;
468    const float v1 = srcTop / height;
469    const float u2 = srcRight / width;
470    const float v2 = srcBottom / height;
471
472    resetDrawTextureTexCoords(u1, v1, u2, v2);
473
474    drawTextureRect(dstLeft, dstTop, dstRight, dstBottom, texture, paint);
475
476    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
477}
478
479void OpenGLRenderer::drawPatch(SkBitmap* bitmap, Res_png_9patch* patch,
480        float left, float top, float right, float bottom, const SkPaint* paint) {
481    if (quickReject(left, top, right, bottom)) {
482        return;
483    }
484
485    const Texture* texture = mTextureCache.get(bitmap);
486
487    int alpha;
488    SkXfermode::Mode mode;
489    getAlphaAndMode(paint, &alpha, &mode);
490
491    Patch* mesh = mPatchCache.get(patch);
492    mesh->updateVertices(bitmap, left, top, right, bottom,
493            &patch->xDivs[0], &patch->yDivs[0], patch->numXDivs, patch->numYDivs);
494
495    // Specify right and bottom as +1.0f from left/top to prevent scaling since the
496    // patch mesh already defines the final size
497    drawTextureMesh(left, top, left + 1.0f, top + 1.0f, texture->id, alpha / 255.0f,
498            mode, texture->blend, &mesh->vertices[0].position[0],
499            &mesh->vertices[0].texture[0], mesh->indices, mesh->indicesCount);
500}
501
502void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
503    const Rect& clip = mSnapshot->clipRect;
504    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
505}
506
507void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) {
508    if (quickReject(left, top, right, bottom)) {
509        return;
510    }
511
512    SkXfermode::Mode mode;
513
514    const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
515    if (!isMode) {
516        // Assume SRC_OVER
517        mode = SkXfermode::kSrcOver_Mode;
518    }
519
520    // Skia draws using the color's alpha channel if < 255
521    // Otherwise, it uses the paint's alpha
522    int color = p->getColor();
523    if (((color >> 24) & 0xff) == 255) {
524        color |= p->getAlpha() << 24;
525    }
526
527    drawColorRect(left, top, right, bottom, color, mode);
528}
529
530///////////////////////////////////////////////////////////////////////////////
531// Shaders
532///////////////////////////////////////////////////////////////////////////////
533
534void OpenGLRenderer::resetShader() {
535    mShader = OpenGLRenderer::kShaderNone;
536    mShaderKey = NULL;
537    mShaderBlend = false;
538    mShaderTileX = GL_CLAMP_TO_EDGE;
539    mShaderTileY = GL_CLAMP_TO_EDGE;
540}
541
542void OpenGLRenderer::setupBitmapShader(SkBitmap* bitmap, SkShader::TileMode tileX,
543        SkShader::TileMode tileY, SkMatrix* matrix, bool hasAlpha) {
544    mShader = OpenGLRenderer::kShaderBitmap;
545    mShaderBlend = hasAlpha;
546    mShaderBitmap = bitmap;
547    mShaderTileX = gTileModes[tileX];
548    mShaderTileY = gTileModes[tileY];
549    mShaderMatrix = matrix;
550}
551
552void OpenGLRenderer::setupLinearGradientShader(SkShader* shader, float* bounds, uint32_t* colors,
553        float* positions, int count, SkShader::TileMode tileMode, SkMatrix* matrix,
554        bool hasAlpha) {
555    // TODO: We should use a struct to describe each shader
556    mShader = OpenGLRenderer::kShaderLinearGradient;
557    mShaderKey = shader;
558    mShaderBlend = hasAlpha;
559    mShaderTileX = gTileModes[tileMode];
560    mShaderTileY = gTileModes[tileMode];
561    mShaderMatrix = matrix;
562    mShaderBounds = bounds;
563    mShaderColors = colors;
564    mShaderPositions = positions;
565    mShaderCount = count;
566}
567
568///////////////////////////////////////////////////////////////////////////////
569// Drawing implementation
570///////////////////////////////////////////////////////////////////////////////
571
572void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
573        int color, SkXfermode::Mode mode, bool ignoreTransform) {
574    // If a shader is set, preserve only the alpha
575    if (mShader != kShaderNone) {
576        color |= 0x00ffffff;
577    }
578
579    // Render using pre-multiplied alpha
580    const int alpha = (color >> 24) & 0xFF;
581    const GLfloat a = alpha / 255.0f;
582
583    switch (mShader) {
584        case OpenGLRenderer::kShaderBitmap:
585            drawBitmapShader(left, top, right, bottom, a, mode);
586            return;
587        case OpenGLRenderer::kShaderLinearGradient:
588            drawLinearGradientShader(left, top, right, bottom, a, mode);
589            return;
590        default:
591            break;
592    }
593
594    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
595    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
596    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
597
598    // Pre-multiplication happens when setting the shader color
599    chooseBlending(alpha < 255 || mShaderBlend, mode);
600
601    mModelView.loadTranslate(left, top, 0.0f);
602    mModelView.scale(right - left, bottom - top, 1.0f);
603
604    if (!useProgram(mDrawColorProgram)) {
605        const GLvoid* p = &gDrawColorVertices[0].position[0];
606        glVertexAttribPointer(mDrawColorProgram->position, 2, GL_FLOAT, GL_FALSE,
607                gDrawColorVertexStride, p);
608    }
609
610    if (!ignoreTransform) {
611        mDrawColorProgram->set(mOrthoMatrix, mModelView, mSnapshot->transform);
612    } else {
613        mat4 identity;
614        mDrawColorProgram->set(mOrthoMatrix, mModelView, identity);
615    }
616
617    glUniform4f(mDrawColorProgram->color, r, g, b, a);
618
619    glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawColorVertexCount);
620}
621
622void OpenGLRenderer::drawLinearGradientShader(float left, float top, float right, float bottom,
623        float alpha, SkXfermode::Mode mode) {
624    Texture* texture = mGradientCache.get(mShaderKey);
625    if (!texture) {
626        SkShader::TileMode tileMode = SkShader::kClamp_TileMode;
627        switch (mShaderTileX) {
628            case GL_REPEAT:
629                tileMode = SkShader::kRepeat_TileMode;
630                break;
631            case GL_MIRRORED_REPEAT:
632                tileMode = SkShader::kMirror_TileMode;
633                break;
634        }
635
636        texture = mGradientCache.addLinearGradient(mShaderKey, mShaderBounds, mShaderColors,
637                mShaderPositions, mShaderCount, tileMode);
638    }
639
640    mModelView.loadTranslate(left, top, 0.0f);
641    mModelView.scale(right - left, bottom - top, 1.0f);
642
643    useProgram(mDrawLinearGradientProgram);
644    mDrawLinearGradientProgram->set(mOrthoMatrix, mModelView, mSnapshot->transform);
645
646    chooseBlending(mShaderBlend || alpha < 1.0f, mode);
647    bindTexture(texture->id, mShaderTileX, mShaderTileY);
648
649    Rect start(mShaderBounds[0], mShaderBounds[1], mShaderBounds[2], mShaderBounds[3]);
650    if (mShaderMatrix) {
651        mat4 shaderMatrix(*mShaderMatrix);
652        shaderMatrix.mapRect(start);
653    }
654    mSnapshot->transform.mapRect(start);
655
656    const float gradientX = start.right - start.left;
657    const float gradientY = start.bottom - start.top;
658
659    mat4 screenSpace(mSnapshot->transform);
660    screenSpace.multiply(mModelView);
661
662    // Always premultiplied
663    glUniform4f(mDrawLinearGradientProgram->color, alpha, alpha, alpha, alpha);
664    glUniform2f(mDrawLinearGradientProgram->start, start.left, start.top);
665    glUniform2f(mDrawLinearGradientProgram->gradient, gradientX, gradientY);
666    glUniform1f(mDrawLinearGradientProgram->gradientLength,
667            1.0f / (gradientX * gradientX + gradientY * gradientY));
668    glUniformMatrix4fv(mDrawLinearGradientProgram->screenSpace, 1, GL_FALSE,
669            &screenSpace.data[0]);
670
671    glVertexAttribPointer(mDrawLinearGradientProgram->position, 2, GL_FLOAT, GL_FALSE,
672            gDrawTextureVertexStride, &mDrawTextureVertices[0].position[0]);
673
674    glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawTextureVertexCount);
675}
676
677void OpenGLRenderer::drawBitmapShader(float left, float top, float right, float bottom,
678        float alpha, SkXfermode::Mode mode) {
679    const Texture* texture = mTextureCache.get(mShaderBitmap);
680
681    const float width = texture->width;
682    const float height = texture->height;
683
684    // This could be done in the vertex shader but we have only 4 vertices
685    float u1 = 0.0f;
686    float v1 = 0.0f;
687    float u2 = right - left;
688    float v2 = bottom - top;
689
690    if (mShaderMatrix) {
691        SkMatrix inverse;
692        mShaderMatrix->invert(&inverse);
693        mat4 m(inverse);
694        Rect r(u1, v1, u2, v2);
695        m.mapRect(r);
696
697        u1 = r.left;
698        u2 = r.right;
699        v1 = r.top;
700        v2 = r.bottom;
701    }
702
703    u1 /= width;
704    u2 /= width;
705    v1 /= height;
706    v2 /= height;
707
708    resetDrawTextureTexCoords(u1, v1, u2, v2);
709
710    drawTextureMesh(left, top, right, bottom, texture->id, alpha, mode, texture->blend,
711            &mDrawTextureVertices[0].position[0], &mDrawTextureVertices[0].texture[0], NULL);
712
713    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
714}
715
716void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
717        const Texture* texture, const SkPaint* paint) {
718    int alpha;
719    SkXfermode::Mode mode;
720    getAlphaAndMode(paint, &alpha, &mode);
721
722    drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, texture->blend,
723            &mDrawTextureVertices[0].position[0], &mDrawTextureVertices[0].texture[0], NULL);
724}
725
726void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
727        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
728    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
729            &mDrawTextureVertices[0].position[0], &mDrawTextureVertices[0].texture[0], NULL);
730}
731
732void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
733        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
734        GLvoid* vertices, GLvoid* texCoords, GLvoid* indices, GLsizei elementsCount) {
735    mModelView.loadTranslate(left, top, 0.0f);
736    mModelView.scale(right - left, bottom - top, 1.0f);
737
738    useProgram(mDrawTextureProgram);
739    mDrawTextureProgram->set(mOrthoMatrix, mModelView, mSnapshot->transform);
740
741    chooseBlending(blend || alpha < 1.0f, mode);
742    bindTexture(texture, mShaderTileX, mShaderTileY);
743
744    // Always premultiplied
745    //glUniform4f(mDrawTextureProgram->color, alpha, alpha, alpha, alpha);
746    glUniform4f(mDrawTextureProgram->color, alpha, alpha, alpha, alpha);
747
748    glVertexAttribPointer(mDrawTextureProgram->position, 2, GL_FLOAT, GL_FALSE,
749            gDrawTextureVertexStride, vertices);
750    glVertexAttribPointer(mDrawTextureProgram->texCoords, 2, GL_FLOAT, GL_FALSE,
751            gDrawTextureVertexStride, texCoords);
752
753    if (!indices) {
754        glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawTextureVertexCount);
755    } else {
756        glDrawElements(GL_TRIANGLES, elementsCount, GL_UNSIGNED_SHORT, indices);
757    }
758}
759
760void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, bool isPremultiplied) {
761    // In theory we should not blend if the mode is Src, but it's rare enough
762    // that it's not worth it
763    blend = blend || mode != SkXfermode::kSrcOver_Mode;
764    if (blend) {
765        if (!mBlend) {
766            glEnable(GL_BLEND);
767        }
768
769        GLenum sourceMode = gBlends[mode].src;
770        GLenum destMode = gBlends[mode].dst;
771        if (!isPremultiplied && sourceMode == GL_ONE) {
772            sourceMode = GL_SRC_ALPHA;
773        }
774
775        if (sourceMode != mLastSrcMode || destMode != mLastDstMode) {
776            glBlendFunc(sourceMode, destMode);
777            mLastSrcMode = sourceMode;
778            mLastDstMode = destMode;
779        }
780    } else if (mBlend) {
781        glDisable(GL_BLEND);
782    }
783    mBlend = blend;
784}
785
786bool OpenGLRenderer::useProgram(const sp<Program>& program) {
787    if (!program->isInUse()) {
788        mCurrentProgram->remove();
789        program->use();
790        mCurrentProgram = program;
791        return false;
792    }
793    return true;
794}
795
796void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
797    TextureVertex* v = &mDrawTextureVertices[0];
798    TextureVertex::setUV(v++, u1, v1);
799    TextureVertex::setUV(v++, u2, v1);
800    TextureVertex::setUV(v++, u1, v2);
801    TextureVertex::setUV(v++, u2, v2);
802}
803
804void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
805    if (paint) {
806        const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
807        if (!isMode) {
808            // Assume SRC_OVER
809            *mode = SkXfermode::kSrcOver_Mode;
810        }
811
812        // Skia draws using the color's alpha channel if < 255
813        // Otherwise, it uses the paint's alpha
814        int color = paint->getColor();
815        *alpha = (color >> 24) & 0xFF;
816        if (*alpha == 255) {
817            *alpha = paint->getAlpha();
818        }
819    } else {
820        *mode = SkXfermode::kSrcOver_Mode;
821        *alpha = 255;
822    }
823}
824
825void OpenGLRenderer::bindTexture(GLuint texture, GLenum wrapS, GLenum wrapT) {
826    if (texture != mLastTexture) {
827        glBindTexture(GL_TEXTURE_2D, texture);
828        mLastTexture = texture;
829    }
830    // TODO: Don't set the texture parameters every time
831    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
832    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
833}
834
835}; // namespace uirenderer
836}; // namespace android
837