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