OpenGLRenderer.cpp revision 9acd1b4fa897f3a007dd23dc1f0471b151fa03ad
1326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams/*
2bc0ca6ba4e31239bf77060578d0bdf1a10e04168Jason Sams * Copyright (C) 2010 The Android Open Source Project
3326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams *
4326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams * Licensed under the Apache License, Version 2.0 (the "License");
5326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams * you may not use this file except in compliance with the License.
6326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams * You may obtain a copy of the License at
7326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams *
8326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams *      http://www.apache.org/licenses/LICENSE-2.0
9326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams *
10326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams * Unless required by applicable law or agreed to in writing, software
11326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams * distributed under the License is distributed on an "AS IS" BASIS,
12326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams * See the License for the specific language governing permissions and
14326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams * limitations under the License.
15326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams */
16326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams
17326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams#define LOG_TAG "OpenGLRenderer"
18326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams
19326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams#include <stdlib.h>
20326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams#include <stdint.h>
21326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams#include <sys/types.h>
22326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams
23326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams#include <SkCanvas.h>
243522f40418fdf877f5a136475dbf75e57a3b7c77Jason Sams#include <SkPathMeasure.h>
25326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams#include <SkTypeface.h>
26326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams
275c3e3bc8af6de6be5e6bd68e1d5168496f99e6cfJason Sams#include <utils/Log.h>
28326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams#include <utils/StopWatch.h>
291e5149f5cd3e75a010b58b985b1151d955d227d1Stephen Hines
301e5149f5cd3e75a010b58b985b1151d955d227d1Stephen Hines#include <private/hwui/DrawGlInfo.h>
311e5149f5cd3e75a010b58b985b1151d955d227d1Stephen Hines
321e5149f5cd3e75a010b58b985b1151d955d227d1Stephen Hines#include <ui/Rect.h>
331e5149f5cd3e75a010b58b985b1151d955d227d1Stephen Hines
341e5149f5cd3e75a010b58b985b1151d955d227d1Stephen Hines#include "OpenGLRenderer.h"
351e5149f5cd3e75a010b58b985b1151d955d227d1Stephen Hines#include "DisplayListRenderer.h"
361e5149f5cd3e75a010b58b985b1151d955d227d1Stephen Hines#include "PathRenderer.h"
37afb743aca56c18beb7ab924e75cb6e070ef3e55aAlex Sakhartchouk#include "Properties.h"
381e5149f5cd3e75a010b58b985b1151d955d227d1Stephen Hines#include "Vector.h"
39326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams
40326e0ddf89e8df2837752fbfd7a014814b32082cJason Samsnamespace android {
41807fdc4b6f3fb893015ee136565d6151bb2332d3Jason Samsnamespace uirenderer {
42807fdc4b6f3fb893015ee136565d6151bb2332d3Jason Sams
43bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams///////////////////////////////////////////////////////////////////////////////
44bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams// Defines
45bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams///////////////////////////////////////////////////////////////////////////////
46bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams
47064aa7ed76db9564b041afcd4b75da5b3d12fabaAlex Sakhartchouk#define RAD_TO_DEG (180.0f / 3.14159265f)
48bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams#define MIN_ANGLE 0.001f
49bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams
50bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams#define ALPHA_THRESHOLD 0
51bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams
52bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams#define FILTER(paint) (!paint || paint->isFilterBitmap() ? GL_LINEAR : GL_NEAREST)
53bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams
54a572aca4eb4ddb32c10baa1f529431cfefd756b8Jason Sams///////////////////////////////////////////////////////////////////////////////
55bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams// Globals
56bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams///////////////////////////////////////////////////////////////////////////////
57bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams
58bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams/**
592e1a94df812f0caa42ff24eaefeba8f90fbdf1acTim Murray * Structure mapping Skia xfermodes to OpenGL blending factors.
60cf27eb46f97cff087ebfc5b81fe998eabe0569cfJason Sams */
613a25fdd3786c1a08b783d8a83ef94b756347ff5cTim Murraystruct Blender {
623a25fdd3786c1a08b783d8a83ef94b756347ff5cTim Murray    SkXfermode::Mode mode;
63bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams    GLenum src;
64bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams    GLenum dst;
65eb4fe18dd88634330f9566cbb9e785d8c7ec5813Jason Sams}; // struct Blender
66eb4fe18dd88634330f9566cbb9e785d8c7ec5813Jason Sams
67709a0978ae141198018ca9769f8d96292a8928e6Jason Sams// In this array, the index of each Blender equals the value of the first
68709a0978ae141198018ca9769f8d96292a8928e6Jason Sams// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
69709a0978ae141198018ca9769f8d96292a8928e6Jason Samsstatic const Blender gBlends[] = {
70709a0978ae141198018ca9769f8d96292a8928e6Jason Sams    { SkXfermode::kClear_Mode,    GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA },
71709a0978ae141198018ca9769f8d96292a8928e6Jason Sams    { SkXfermode::kSrc_Mode,      GL_ONE,                 GL_ZERO },
72709a0978ae141198018ca9769f8d96292a8928e6Jason Sams    { SkXfermode::kDst_Mode,      GL_ZERO,                GL_ONE },
73709a0978ae141198018ca9769f8d96292a8928e6Jason Sams    { SkXfermode::kSrcOver_Mode,  GL_ONE,                 GL_ONE_MINUS_SRC_ALPHA },
74709a0978ae141198018ca9769f8d96292a8928e6Jason Sams    { SkXfermode::kDstOver_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_ONE },
75709a0978ae141198018ca9769f8d96292a8928e6Jason Sams    { SkXfermode::kSrcIn_Mode,    GL_DST_ALPHA,           GL_ZERO },
76709a0978ae141198018ca9769f8d96292a8928e6Jason Sams    { SkXfermode::kDstIn_Mode,    GL_ZERO,                GL_SRC_ALPHA },
77709a0978ae141198018ca9769f8d96292a8928e6Jason Sams    { SkXfermode::kSrcOut_Mode,   GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
78709a0978ae141198018ca9769f8d96292a8928e6Jason Sams    { SkXfermode::kDstOut_Mode,   GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA },
79eb4fe18dd88634330f9566cbb9e785d8c7ec5813Jason Sams    { SkXfermode::kSrcATop_Mode,  GL_DST_ALPHA,           GL_ONE_MINUS_SRC_ALPHA },
80bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams    { SkXfermode::kDstATop_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA },
81bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams    { SkXfermode::kXor_Mode,      GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
82bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams    { SkXfermode::kPlus_Mode,     GL_ONE,                 GL_ONE },
8334689388556747b52c3c2f1c894929fb44580898Tim Murray    { SkXfermode::kMultiply_Mode, GL_ZERO,                GL_SRC_COLOR },
8434689388556747b52c3c2f1c894929fb44580898Tim Murray    { SkXfermode::kScreen_Mode,   GL_ONE,                 GL_ONE_MINUS_SRC_COLOR }
85eb4fe18dd88634330f9566cbb9e785d8c7ec5813Jason Sams};
86179e9a457095fea4c9e6d366c269754b882d05ddJason Sams
87179e9a457095fea4c9e6d366c269754b882d05ddJason Sams// This array contains the swapped version of each SkXfermode. For instance
88326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams// this array's SrcOver blending mode is actually DstOver. You can refer to
89bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams// createLayer() for more information on the purpose of this array.
90326e0ddf89e8df2837752fbfd7a014814b32082cJason Samsstatic const Blender gBlendsSwap[] = {
91064aa7ed76db9564b041afcd4b75da5b3d12fabaAlex Sakhartchouk    { SkXfermode::kClear_Mode,    GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
92326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams    { SkXfermode::kSrc_Mode,      GL_ZERO,                GL_ONE },
93366c9c85196675437a8dd74c1cf6b63ddbde3d6aJason Sams    { SkXfermode::kDst_Mode,      GL_ONE,                 GL_ZERO },
94366c9c85196675437a8dd74c1cf6b63ddbde3d6aJason Sams    { SkXfermode::kSrcOver_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_ONE },
9596abf819e50b59ba8cf886c13f894633eb0a24baJason Sams    { SkXfermode::kDstOver_Mode,  GL_ONE,                 GL_ONE_MINUS_SRC_ALPHA },
9696abf819e50b59ba8cf886c13f894633eb0a24baJason Sams    { SkXfermode::kSrcIn_Mode,    GL_ZERO,                GL_SRC_ALPHA },
9796abf819e50b59ba8cf886c13f894633eb0a24baJason Sams    { SkXfermode::kDstIn_Mode,    GL_DST_ALPHA,           GL_ZERO },
9896abf819e50b59ba8cf886c13f894633eb0a24baJason Sams    { SkXfermode::kSrcOut_Mode,   GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA },
99326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams    { SkXfermode::kDstOut_Mode,   GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
1006ae039baf797915d46f3b3901d1b7f5cc83feaceStephen Hines    { SkXfermode::kSrcATop_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA },
1014b45b8998e0d7038efaea80c70d23c086640b4e3Jason Sams    { SkXfermode::kDstATop_Mode,  GL_DST_ALPHA,           GL_ONE_MINUS_SRC_ALPHA },
102358747a3118301c5faeee73c98dd5f839bbfb54aTim Murray    { SkXfermode::kXor_Mode,      GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
1033bbc0fd40264ddae1592706d9023865b7b3e3195Jason Sams    { SkXfermode::kPlus_Mode,     GL_ONE,                 GL_ONE },
1043bbc0fd40264ddae1592706d9023865b7b3e3195Jason Sams    { SkXfermode::kMultiply_Mode, GL_DST_COLOR,           GL_ZERO },
105326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams    { SkXfermode::kScreen_Mode,   GL_ONE_MINUS_DST_COLOR, GL_ONE }
106807fdc4b6f3fb893015ee136565d6151bb2332d3Jason Sams};
107358747a3118301c5faeee73c98dd5f839bbfb54aTim Murray
108358747a3118301c5faeee73c98dd5f839bbfb54aTim Murray///////////////////////////////////////////////////////////////////////////////
1093bbc0fd40264ddae1592706d9023865b7b3e3195Jason Sams// Constructors/destructor
1103bbc0fd40264ddae1592706d9023865b7b3e3195Jason Sams///////////////////////////////////////////////////////////////////////////////
111807fdc4b6f3fb893015ee136565d6151bb2332d3Jason Sams
1124b45b8998e0d7038efaea80c70d23c086640b4e3Jason SamsOpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
1136ae039baf797915d46f3b3901d1b7f5cc83feaceStephen Hines    mShader = NULL;
1144b45b8998e0d7038efaea80c70d23c086640b4e3Jason Sams    mColorFilter = NULL;
1156ae039baf797915d46f3b3901d1b7f5cc83feaceStephen Hines    mHasShadow = false;
1165f0c84cf464dda719cef65fdc9b4d0980e86b98fJason Sams    mHasDrawFilter = false;
1175c3e3bc8af6de6be5e6bd68e1d5168496f99e6cfJason Sams
1185c3e3bc8af6de6be5e6bd68e1d5168496f99e6cfJason Sams    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
119e5ffb879ae535a899a486285a23bea05e912480fJason Sams
1203dd429cc32388ca0c3d7a9368ed2e348b8fdaab1Jason Sams    mFirstSnapshot = new Snapshot;
121e3150cfb3edb028407669e4a65e087eae77e718cJason Sams
122b825f67adb5d1e1751fe108e6dbf9c6f2555c283Alex Sakhartchouk    mScissorOptimizationDisabled = false;
123fb6b614bcea88a587a7ea4530be45ff0ffa0210eAlex Sakhartchouk}
124e5ffb879ae535a899a486285a23bea05e912480fJason Sams
125b89b0b7dd8199967502c92fe5c8f57c3bc255e1cJason SamsOpenGLRenderer::~OpenGLRenderer() {
126bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams    // The context has already been destroyed at this point, do not call
127b89b0b7dd8199967502c92fe5c8f57c3bc255e1cJason Sams    // GL APIs. All GL state should be kept in Caches.h
128ebc5019400a129b1f1e57bd1fe8200a21f8da00bJason Sams}
129bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams
130ebc5019400a129b1f1e57bd1fe8200a21f8da00bJason Samsvoid OpenGLRenderer::initProperties() {
1317d9c5ffccb7a5e682860f752403e5a03aed587beAlex Sakhartchouk    char property[PROPERTY_VALUE_MAX];
1327d9c5ffccb7a5e682860f752403e5a03aed587beAlex Sakhartchouk    if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) {
1337d9c5ffccb7a5e682860f752403e5a03aed587beAlex Sakhartchouk        mScissorOptimizationDisabled = !strcasecmp(property, "true");
134ebc5019400a129b1f1e57bd1fe8200a21f8da00bJason Sams        INIT_LOGD("  Scissor optimization %s",
135bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams                mScissorOptimizationDisabled ? "disabled" : "enabled");
136ebc5019400a129b1f1e57bd1fe8200a21f8da00bJason Sams    } else {
137760f1f7335ad0c5aee59ca829a40bbf6e3328a1bJason Sams        INIT_LOGD("  Scissor optimization enabled");
13896abf819e50b59ba8cf886c13f894633eb0a24baJason Sams    }
13996abf819e50b59ba8cf886c13f894633eb0a24baJason Sams}
140c7cec1e3577cc77a5a73d5bd5a82733b1b9936a1Jason Sams
141e3929c9bc6f3897e132304faf1b40c3cf1f47474Jason Sams///////////////////////////////////////////////////////////////////////////////
142eb4fe18dd88634330f9566cbb9e785d8c7ec5813Jason Sams// Setup
143b89b0b7dd8199967502c92fe5c8f57c3bc255e1cJason Sams///////////////////////////////////////////////////////////////////////////////
144bad807405b2b9764372af1ad24bcfd4fb1f33d8eJason Sams
145b89b0b7dd8199967502c92fe5c8f57c3bc255e1cJason Samsbool OpenGLRenderer::isDeferred() {
146b89b0b7dd8199967502c92fe5c8f57c3bc255e1cJason Sams    return false;
147733396b67724162844ea2785c7495115dc5ee8d8Jason Sams}
1487ac2a4dda4d20ca1f1b714e129a3a08f63178c18Jason Sams
1497ac2a4dda4d20ca1f1b714e129a3a08f63178c18Jason Samsvoid OpenGLRenderer::setViewport(int width, int height) {
1507ac2a4dda4d20ca1f1b714e129a3a08f63178c18Jason Sams    initViewport(width, height);
1515c3e3bc8af6de6be5e6bd68e1d5168496f99e6cfJason Sams
1521e5168d113ccdcf9fe1b817dcbf2f7f476d36c74Alex Sakhartchouk    glDisable(GL_DITHER);
1535c3e3bc8af6de6be5e6bd68e1d5168496f99e6cfJason Sams    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
154064aa7ed76db9564b041afcd4b75da5b3d12fabaAlex Sakhartchouk
155064aa7ed76db9564b041afcd4b75da5b3d12fabaAlex Sakhartchouk    glEnableVertexAttribArray(Program::kBindingPosition);
156064aa7ed76db9564b041afcd4b75da5b3d12fabaAlex Sakhartchouk}
157064aa7ed76db9564b041afcd4b75da5b3d12fabaAlex Sakhartchouk
158064aa7ed76db9564b041afcd4b75da5b3d12fabaAlex Sakhartchoukvoid OpenGLRenderer::initViewport(int width, int height) {
1595c3e3bc8af6de6be5e6bd68e1d5168496f99e6cfJason Sams    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
160fa84da2cbc271f855b3b1ec75bb688abdf1d1d01Jason Sams
161c7cec1e3577cc77a5a73d5bd5a82733b1b9936a1Jason Sams    mWidth = width;
162179e9a457095fea4c9e6d366c269754b882d05ddJason Sams    mHeight = height;
1632d1220c27ae91f0b307f283fe66cb767b63dfe38Alex Sakhartchouk
1642d1220c27ae91f0b307f283fe66cb767b63dfe38Alex Sakhartchouk    mFirstSnapshot->height = height;
165807fdc4b6f3fb893015ee136565d6151bb2332d3Jason Sams    mFirstSnapshot->viewport.set(0, 0, width, height);
166807fdc4b6f3fb893015ee136565d6151bb2332d3Jason Sams}
167e3150cfb3edb028407669e4a65e087eae77e718cJason Sams
168e3150cfb3edb028407669e4a65e087eae77e718cJason Samsstatus_t OpenGLRenderer::prepare(bool opaque) {
169326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams    return prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
170326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams}
171326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams
172326e0ddf89e8df2837752fbfd7a014814b32082cJason Samsstatus_t OpenGLRenderer::prepareDirty(float left, float top, float right, float bottom,
173326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams        bool opaque) {
174326e0ddf89e8df2837752fbfd7a014814b32082cJason Sams    mCaches.clearGarbage();
175
176    mSnapshot = new Snapshot(mFirstSnapshot,
177            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
178    mSnapshot->fbo = getTargetFbo();
179    mSaveCount = 1;
180
181    mSnapshot->setClip(left, top, right, bottom);
182    mDirtyClip = true;
183
184    updateLayers();
185
186    discardFramebuffer(left, top, right, bottom);
187
188    syncState();
189
190    // Functors break the tiling extension in pretty spectacular ways
191    // This ensures we don't use tiling when a functor is going to be
192    // invoked during the frame
193    mSuppressTiling = mCaches.hasRegisteredFunctors();
194
195    mTilingSnapshot = mSnapshot;
196    startTiling(mTilingSnapshot, true);
197
198    debugOverdraw(true, true);
199
200    return clear(left, top, right, bottom, opaque);
201}
202
203void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) {
204    // If we know that we are going to redraw the entire framebuffer,
205    // perform a discard to let the driver know we don't need to preserve
206    // the back buffer for this frame.
207    if (mCaches.extensions.hasDiscardFramebuffer() &&
208            left <= 0.0f && top <= 0.0f && right >= mWidth && bottom >= mHeight) {
209        const GLenum attachments[] = { getTargetFbo() == 0 ? (const GLenum) GL_COLOR_EXT :
210                (const GLenum) GL_COLOR_ATTACHMENT0 };
211        glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
212    }
213}
214
215status_t OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) {
216    if (!opaque) {
217        mCaches.enableScissor();
218        mCaches.setScissor(left, mSnapshot->height - bottom, right - left, bottom - top);
219        glClear(GL_COLOR_BUFFER_BIT);
220        return DrawGlInfo::kStatusDrew;
221    }
222
223    mCaches.resetScissor();
224    return DrawGlInfo::kStatusDone;
225}
226
227void OpenGLRenderer::syncState() {
228    glViewport(0, 0, mWidth, mHeight);
229
230    if (mCaches.blend) {
231        glEnable(GL_BLEND);
232    } else {
233        glDisable(GL_BLEND);
234    }
235}
236
237void OpenGLRenderer::startTiling(const sp<Snapshot>& s, bool opaque) {
238    if (!mSuppressTiling) {
239        Rect* clip = mTilingSnapshot->clipRect;
240        if (s->flags & Snapshot::kFlagIsFboLayer) {
241            clip = s->clipRect;
242        }
243
244        mCaches.startTiling(clip->left, s->height - clip->bottom,
245                clip->right - clip->left, clip->bottom - clip->top, opaque);
246    }
247}
248
249void OpenGLRenderer::endTiling() {
250    if (!mSuppressTiling) mCaches.endTiling();
251}
252
253void OpenGLRenderer::finish() {
254    renderOverdraw();
255    endTiling();
256
257    if (!suppressErrorChecks()) {
258#if DEBUG_OPENGL
259        GLenum status = GL_NO_ERROR;
260        while ((status = glGetError()) != GL_NO_ERROR) {
261            ALOGD("GL error from OpenGLRenderer: 0x%x", status);
262            switch (status) {
263                case GL_INVALID_ENUM:
264                    ALOGE("  GL_INVALID_ENUM");
265                    break;
266                case GL_INVALID_VALUE:
267                    ALOGE("  GL_INVALID_VALUE");
268                    break;
269                case GL_INVALID_OPERATION:
270                    ALOGE("  GL_INVALID_OPERATION");
271                    break;
272                case GL_OUT_OF_MEMORY:
273                    ALOGE("  Out of memory!");
274                    break;
275            }
276        }
277#endif
278
279#if DEBUG_MEMORY_USAGE
280        mCaches.dumpMemoryUsage();
281#else
282        if (mCaches.getDebugLevel() & kDebugMemory) {
283            mCaches.dumpMemoryUsage();
284        }
285#endif
286    }
287}
288
289void OpenGLRenderer::interrupt() {
290    if (mCaches.currentProgram) {
291        if (mCaches.currentProgram->isInUse()) {
292            mCaches.currentProgram->remove();
293            mCaches.currentProgram = NULL;
294        }
295    }
296    mCaches.unbindMeshBuffer();
297    mCaches.unbindIndicesBuffer();
298    mCaches.resetVertexPointers();
299    mCaches.disbaleTexCoordsVertexArray();
300    debugOverdraw(false, false);
301}
302
303void OpenGLRenderer::resume() {
304    sp<Snapshot> snapshot = (mSnapshot != NULL) ? mSnapshot : mFirstSnapshot;
305    glViewport(0, 0, snapshot->viewport.getWidth(), snapshot->viewport.getHeight());
306    glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo);
307    debugOverdraw(true, false);
308
309    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
310
311    mCaches.scissorEnabled = glIsEnabled(GL_SCISSOR_TEST);
312    mCaches.enableScissor();
313    mCaches.resetScissor();
314    dirtyClip();
315
316    mCaches.activeTexture(0);
317
318    mCaches.blend = true;
319    glEnable(GL_BLEND);
320    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
321    glBlendEquation(GL_FUNC_ADD);
322}
323
324void OpenGLRenderer::resumeAfterLayer() {
325    sp<Snapshot> snapshot = (mSnapshot != NULL) ? mSnapshot : mFirstSnapshot;
326    glViewport(0, 0, snapshot->viewport.getWidth(), snapshot->viewport.getHeight());
327    glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo);
328    debugOverdraw(true, false);
329
330    mCaches.resetScissor();
331    dirtyClip();
332}
333
334void OpenGLRenderer::detachFunctor(Functor* functor) {
335    mFunctors.remove(functor);
336}
337
338void OpenGLRenderer::attachFunctor(Functor* functor) {
339    mFunctors.add(functor);
340}
341
342status_t OpenGLRenderer::invokeFunctors(Rect& dirty) {
343    status_t result = DrawGlInfo::kStatusDone;
344    size_t count = mFunctors.size();
345
346    if (count > 0) {
347        interrupt();
348        SortedVector<Functor*> functors(mFunctors);
349        mFunctors.clear();
350
351        DrawGlInfo info;
352        info.clipLeft = 0;
353        info.clipTop = 0;
354        info.clipRight = 0;
355        info.clipBottom = 0;
356        info.isLayer = false;
357        info.width = 0;
358        info.height = 0;
359        memset(info.transform, 0, sizeof(float) * 16);
360
361        for (size_t i = 0; i < count; i++) {
362            Functor* f = functors.itemAt(i);
363            result |= (*f)(DrawGlInfo::kModeProcess, &info);
364
365            if (result & DrawGlInfo::kStatusDraw) {
366                Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
367                dirty.unionWith(localDirty);
368            }
369
370            if (result & DrawGlInfo::kStatusInvoke) {
371                mFunctors.add(f);
372            }
373        }
374        resume();
375    }
376
377    return result;
378}
379
380status_t OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) {
381    interrupt();
382    detachFunctor(functor);
383
384    mCaches.enableScissor();
385    if (mDirtyClip) {
386        setScissorFromClip();
387    }
388
389    Rect clip(*mSnapshot->clipRect);
390    clip.snapToPixelBoundaries();
391
392    // Since we don't know what the functor will draw, let's dirty
393    // tne entire clip region
394    if (hasLayer()) {
395        dirtyLayerUnchecked(clip, getRegion());
396    }
397
398    DrawGlInfo info;
399    info.clipLeft = clip.left;
400    info.clipTop = clip.top;
401    info.clipRight = clip.right;
402    info.clipBottom = clip.bottom;
403    info.isLayer = hasLayer();
404    info.width = getSnapshot()->viewport.getWidth();
405    info.height = getSnapshot()->height;
406    getSnapshot()->transform->copyTo(&info.transform[0]);
407
408    status_t result = (*functor)(DrawGlInfo::kModeDraw, &info) | DrawGlInfo::kStatusDrew;
409
410    if (result != DrawGlInfo::kStatusDone) {
411        Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
412        dirty.unionWith(localDirty);
413
414        if (result & DrawGlInfo::kStatusInvoke) {
415            mFunctors.add(functor);
416        }
417    }
418
419    resume();
420    return result;
421}
422
423///////////////////////////////////////////////////////////////////////////////
424// Debug
425///////////////////////////////////////////////////////////////////////////////
426
427void OpenGLRenderer::startMark(const char* name) const {
428    mCaches.startMark(0, name);
429}
430
431void OpenGLRenderer::endMark() const {
432    mCaches.endMark();
433}
434
435void OpenGLRenderer::debugOverdraw(bool enable, bool clear) {
436    if (mCaches.debugOverdraw && getTargetFbo() == 0) {
437        if (clear) {
438            mCaches.disableScissor();
439            mCaches.stencil.clear();
440        }
441        if (enable) {
442            mCaches.stencil.enableDebugWrite();
443        } else {
444            mCaches.stencil.disable();
445        }
446    }
447}
448
449void OpenGLRenderer::renderOverdraw() {
450    if (mCaches.debugOverdraw && getTargetFbo() == 0) {
451        const Rect* clip = mTilingSnapshot->clipRect;
452
453        mCaches.enableScissor();
454        mCaches.setScissor(clip->left, mTilingSnapshot->height - clip->bottom,
455                clip->right - clip->left, clip->bottom - clip->top);
456
457        mCaches.stencil.enableDebugTest(2);
458        drawColor(0x2f0000ff, SkXfermode::kSrcOver_Mode);
459        mCaches.stencil.enableDebugTest(3);
460        drawColor(0x2f00ff00, SkXfermode::kSrcOver_Mode);
461        mCaches.stencil.enableDebugTest(4);
462        drawColor(0x3fff0000, SkXfermode::kSrcOver_Mode);
463        mCaches.stencil.enableDebugTest(4, true);
464        drawColor(0x7fff0000, SkXfermode::kSrcOver_Mode);
465        mCaches.stencil.disable();
466    }
467}
468
469///////////////////////////////////////////////////////////////////////////////
470// Layers
471///////////////////////////////////////////////////////////////////////////////
472
473bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) {
474    if (layer->deferredUpdateScheduled && layer->renderer && layer->displayList) {
475        OpenGLRenderer* renderer = layer->renderer;
476        Rect& dirty = layer->dirtyRect;
477
478        if (inFrame) {
479            endTiling();
480            debugOverdraw(false, false);
481        }
482
483        renderer->setViewport(layer->layer.getWidth(), layer->layer.getHeight());
484        renderer->prepareDirty(dirty.left, dirty.top, dirty.right, dirty.bottom, !layer->isBlend());
485        renderer->drawDisplayList(layer->displayList, dirty, DisplayList::kReplayFlag_ClipChildren);
486        renderer->finish();
487
488        if (inFrame) {
489            resumeAfterLayer();
490            startTiling(mSnapshot);
491        }
492
493        dirty.setEmpty();
494        layer->deferredUpdateScheduled = false;
495        layer->renderer = NULL;
496        layer->displayList = NULL;
497        layer->debugDrawUpdate = mCaches.debugLayersUpdates;
498
499        return true;
500    }
501
502    return false;
503}
504
505void OpenGLRenderer::updateLayers() {
506    int count = mLayerUpdates.size();
507    if (count > 0) {
508        startMark("Layer Updates");
509
510        // Note: it is very important to update the layers in reverse order
511        for (int i = count - 1; i >= 0; i--) {
512            Layer* layer = mLayerUpdates.itemAt(i);
513            updateLayer(layer, false);
514            mCaches.resourceCache.decrementRefcount(layer);
515        }
516        mLayerUpdates.clear();
517
518        glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo());
519        endMark();
520    }
521}
522
523void OpenGLRenderer::pushLayerUpdate(Layer* layer) {
524    if (layer) {
525        mLayerUpdates.push_back(layer);
526        mCaches.resourceCache.incrementRefcount(layer);
527    }
528}
529
530void OpenGLRenderer::clearLayerUpdates() {
531    size_t count = mLayerUpdates.size();
532    if (count > 0) {
533        mCaches.resourceCache.lock();
534        for (size_t i = 0; i < count; i++) {
535            mCaches.resourceCache.decrementRefcountLocked(mLayerUpdates.itemAt(i));
536        }
537        mCaches.resourceCache.unlock();
538        mLayerUpdates.clear();
539    }
540}
541
542///////////////////////////////////////////////////////////////////////////////
543// State management
544///////////////////////////////////////////////////////////////////////////////
545
546int OpenGLRenderer::getSaveCount() const {
547    return mSaveCount;
548}
549
550int OpenGLRenderer::save(int flags) {
551    return saveSnapshot(flags);
552}
553
554void OpenGLRenderer::restore() {
555    if (mSaveCount > 1) {
556        restoreSnapshot();
557    }
558}
559
560void OpenGLRenderer::restoreToCount(int saveCount) {
561    if (saveCount < 1) saveCount = 1;
562
563    while (mSaveCount > saveCount) {
564        restoreSnapshot();
565    }
566}
567
568int OpenGLRenderer::saveSnapshot(int flags) {
569    mSnapshot = new Snapshot(mSnapshot, flags);
570    return mSaveCount++;
571}
572
573bool OpenGLRenderer::restoreSnapshot() {
574    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
575    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
576    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
577
578    sp<Snapshot> current = mSnapshot;
579    sp<Snapshot> previous = mSnapshot->previous;
580
581    if (restoreOrtho) {
582        Rect& r = previous->viewport;
583        glViewport(r.left, r.top, r.right, r.bottom);
584        mOrthoMatrix.load(current->orthoMatrix);
585    }
586
587    mSaveCount--;
588    mSnapshot = previous;
589
590    if (restoreClip) {
591        dirtyClip();
592    }
593
594    if (restoreLayer) {
595        composeLayer(current, previous);
596    }
597
598    return restoreClip;
599}
600
601///////////////////////////////////////////////////////////////////////////////
602// Layers
603///////////////////////////////////////////////////////////////////////////////
604
605int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
606        SkPaint* p, int flags) {
607    const GLuint previousFbo = mSnapshot->fbo;
608    const int count = saveSnapshot(flags);
609
610    if (!mSnapshot->isIgnored()) {
611        int alpha = 255;
612        SkXfermode::Mode mode;
613
614        if (p) {
615            alpha = p->getAlpha();
616            mode = getXfermode(p->getXfermode());
617        } else {
618            mode = SkXfermode::kSrcOver_Mode;
619        }
620
621        createLayer(left, top, right, bottom, alpha, mode, flags, previousFbo);
622    }
623
624    return count;
625}
626
627int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
628        int alpha, int flags) {
629    if (alpha >= 255) {
630        return saveLayer(left, top, right, bottom, NULL, flags);
631    } else {
632        SkPaint paint;
633        paint.setAlpha(alpha);
634        return saveLayer(left, top, right, bottom, &paint, flags);
635    }
636}
637
638/**
639 * Layers are viewed by Skia are slightly different than layers in image editing
640 * programs (for instance.) When a layer is created, previously created layers
641 * and the frame buffer still receive every drawing command. For instance, if a
642 * layer is created and a shape intersecting the bounds of the layers and the
643 * framebuffer is draw, the shape will be drawn on both (unless the layer was
644 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
645 *
646 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
647 * texture. Unfortunately, this is inefficient as it requires every primitive to
648 * be drawn n + 1 times, where n is the number of active layers. In practice this
649 * means, for every primitive:
650 *   - Switch active frame buffer
651 *   - Change viewport, clip and projection matrix
652 *   - Issue the drawing
653 *
654 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
655 * To avoid this, layers are implemented in a different way here, at least in the
656 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
657 * is set. When this flag is set we can redirect all drawing operations into a
658 * single FBO.
659 *
660 * This implementation relies on the frame buffer being at least RGBA 8888. When
661 * a layer is created, only a texture is created, not an FBO. The content of the
662 * frame buffer contained within the layer's bounds is copied into this texture
663 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
664 * buffer and drawing continues as normal. This technique therefore treats the
665 * frame buffer as a scratch buffer for the layers.
666 *
667 * To compose the layers back onto the frame buffer, each layer texture
668 * (containing the original frame buffer data) is drawn as a simple quad over
669 * the frame buffer. The trick is that the quad is set as the composition
670 * destination in the blending equation, and the frame buffer becomes the source
671 * of the composition.
672 *
673 * Drawing layers with an alpha value requires an extra step before composition.
674 * An empty quad is drawn over the layer's region in the frame buffer. This quad
675 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
676 * quad is used to multiply the colors in the frame buffer. This is achieved by
677 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
678 * GL_ZERO, GL_SRC_ALPHA.
679 *
680 * Because glCopyTexImage2D() can be slow, an alternative implementation might
681 * be use to draw a single clipped layer. The implementation described above
682 * is correct in every case.
683 *
684 * (1) The frame buffer is actually not cleared right away. To allow the GPU
685 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
686 *     buffer is left untouched until the first drawing operation. Only when
687 *     something actually gets drawn are the layers regions cleared.
688 */
689bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom,
690        int alpha, SkXfermode::Mode mode, int flags, GLuint previousFbo) {
691    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
692    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
693
694    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
695
696    // Window coordinates of the layer
697    Rect clip;
698    Rect bounds(left, top, right, bottom);
699    Rect untransformedBounds(bounds);
700    mSnapshot->transform->mapRect(bounds);
701
702    // Layers only make sense if they are in the framebuffer's bounds
703    if (bounds.intersect(*mSnapshot->clipRect)) {
704        // We cannot work with sub-pixels in this case
705        bounds.snapToPixelBoundaries();
706
707        // When the layer is not an FBO, we may use glCopyTexImage so we
708        // need to make sure the layer does not extend outside the bounds
709        // of the framebuffer
710        if (!bounds.intersect(mSnapshot->previous->viewport)) {
711            bounds.setEmpty();
712        } else if (fboLayer) {
713            clip.set(bounds);
714            mat4 inverse;
715            inverse.loadInverse(*mSnapshot->transform);
716            inverse.mapRect(clip);
717            clip.snapToPixelBoundaries();
718            if (clip.intersect(untransformedBounds)) {
719                clip.translate(-left, -top);
720                bounds.set(untransformedBounds);
721            } else {
722                clip.setEmpty();
723            }
724        }
725    } else {
726        bounds.setEmpty();
727    }
728
729    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
730            bounds.getHeight() > mCaches.maxTextureSize ||
731            (fboLayer && clip.isEmpty())) {
732        mSnapshot->empty = fboLayer;
733    } else {
734        mSnapshot->invisible = mSnapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
735    }
736
737    // Bail out if we won't draw in this snapshot
738    if (mSnapshot->invisible || mSnapshot->empty) {
739        return false;
740    }
741
742    mCaches.activeTexture(0);
743    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
744    if (!layer) {
745        return false;
746    }
747
748    layer->setAlpha(alpha, mode);
749    layer->layer.set(bounds);
750    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()),
751            bounds.getWidth() / float(layer->getWidth()), 0.0f);
752    layer->setColorFilter(mColorFilter);
753    layer->setBlend(true);
754    layer->setDirty(false);
755
756    // Save the layer in the snapshot
757    mSnapshot->flags |= Snapshot::kFlagIsLayer;
758    mSnapshot->layer = layer;
759
760    if (fboLayer) {
761        return createFboLayer(layer, bounds, clip, previousFbo);
762    } else {
763        // Copy the framebuffer into the layer
764        layer->bindTexture();
765        if (!bounds.isEmpty()) {
766            if (layer->isEmpty()) {
767                glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
768                        bounds.left, mSnapshot->height - bounds.bottom,
769                        layer->getWidth(), layer->getHeight(), 0);
770                layer->setEmpty(false);
771            } else {
772                glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
773                        mSnapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
774            }
775
776            // Enqueue the buffer coordinates to clear the corresponding region later
777            mLayers.push(new Rect(bounds));
778        }
779    }
780
781    return true;
782}
783
784bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip, GLuint previousFbo) {
785    layer->setFbo(mCaches.fboCache.get());
786
787    mSnapshot->region = &mSnapshot->layer->region;
788    mSnapshot->flags |= Snapshot::kFlagFboTarget;
789
790    mSnapshot->flags |= Snapshot::kFlagIsFboLayer;
791    mSnapshot->fbo = layer->getFbo();
792    mSnapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
793    mSnapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
794    mSnapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
795    mSnapshot->height = bounds.getHeight();
796    mSnapshot->flags |= Snapshot::kFlagDirtyOrtho;
797    mSnapshot->orthoMatrix.load(mOrthoMatrix);
798
799    endTiling();
800    debugOverdraw(false, false);
801    // Bind texture to FBO
802    glBindFramebuffer(GL_FRAMEBUFFER, layer->getFbo());
803    layer->bindTexture();
804
805    // Initialize the texture if needed
806    if (layer->isEmpty()) {
807        layer->allocateTexture(GL_RGBA, GL_UNSIGNED_BYTE);
808        layer->setEmpty(false);
809    }
810
811    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
812            layer->getTexture(), 0);
813
814    startTiling(mSnapshot);
815
816    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
817    mCaches.enableScissor();
818    mCaches.setScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
819            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
820    glClear(GL_COLOR_BUFFER_BIT);
821
822    dirtyClip();
823
824    // Change the ortho projection
825    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
826    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
827
828    return true;
829}
830
831/**
832 * Read the documentation of createLayer() before doing anything in this method.
833 */
834void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
835    if (!current->layer) {
836        ALOGE("Attempting to compose a layer that does not exist");
837        return;
838    }
839
840    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
841
842    if (fboLayer) {
843        endTiling();
844
845        // Detach the texture from the FBO
846        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
847        // Unbind current FBO and restore previous one
848        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
849        debugOverdraw(true, false);
850
851        startTiling(previous);
852    }
853
854    Layer* layer = current->layer;
855    const Rect& rect = layer->layer;
856
857    if (!fboLayer && layer->getAlpha() < 255) {
858        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
859                layer->getAlpha() << 24, SkXfermode::kDstIn_Mode, true);
860        // Required below, composeLayerRect() will divide by 255
861        layer->setAlpha(255);
862    }
863
864    mCaches.unbindMeshBuffer();
865
866    mCaches.activeTexture(0);
867
868    // When the layer is stored in an FBO, we can save a bit of fillrate by
869    // drawing only the dirty region
870    if (fboLayer) {
871        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
872        if (layer->getColorFilter()) {
873            setupColorFilter(layer->getColorFilter());
874        }
875        composeLayerRegion(layer, rect);
876        if (layer->getColorFilter()) {
877            resetColorFilter();
878        }
879    } else if (!rect.isEmpty()) {
880        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
881        composeLayerRect(layer, rect, true);
882    }
883
884    if (fboLayer) {
885        // Note: No need to use glDiscardFramebufferEXT() since we never
886        //       create/compose layers that are not on screen with this
887        //       code path
888        // See LayerRenderer::destroyLayer(Layer*)
889
890        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
891        mCaches.fboCache.put(current->fbo);
892        layer->setFbo(0);
893    }
894
895    dirtyClip();
896
897    // Failing to add the layer to the cache should happen only if the layer is too large
898    if (!mCaches.layerCache.put(layer)) {
899        LAYER_LOGD("Deleting layer");
900        Caches::getInstance().resourceCache.decrementRefcount(layer);
901    }
902}
903
904void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
905    float alpha = layer->getAlpha() / 255.0f;
906
907    setupDraw();
908    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
909        setupDrawWithTexture();
910    } else {
911        setupDrawWithExternalTexture();
912    }
913    setupDrawTextureTransform();
914    setupDrawColor(alpha, alpha, alpha, alpha);
915    setupDrawColorFilter();
916    setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode());
917    setupDrawProgram();
918    setupDrawPureColorUniforms();
919    setupDrawColorFilterUniforms();
920    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
921        setupDrawTexture(layer->getTexture());
922    } else {
923        setupDrawExternalTexture(layer->getTexture());
924    }
925    if (mSnapshot->transform->isPureTranslate() &&
926            layer->getWidth() == (uint32_t) rect.getWidth() &&
927            layer->getHeight() == (uint32_t) rect.getHeight()) {
928        const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
929        const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
930
931        layer->setFilter(GL_NEAREST);
932        setupDrawModelView(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
933    } else {
934        layer->setFilter(GL_LINEAR);
935        setupDrawModelView(rect.left, rect.top, rect.right, rect.bottom);
936    }
937    setupDrawTextureTransformUniforms(layer->getTexTransform());
938    setupDrawMesh(&mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
939
940    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
941
942    finishDrawTexture();
943}
944
945void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
946    if (!layer->isTextureLayer()) {
947        const Rect& texCoords = layer->texCoords;
948        resetDrawTextureTexCoords(texCoords.left, texCoords.top,
949                texCoords.right, texCoords.bottom);
950
951        float x = rect.left;
952        float y = rect.top;
953        bool simpleTransform = mSnapshot->transform->isPureTranslate() &&
954                layer->getWidth() == (uint32_t) rect.getWidth() &&
955                layer->getHeight() == (uint32_t) rect.getHeight();
956
957        if (simpleTransform) {
958            // When we're swapping, the layer is already in screen coordinates
959            if (!swap) {
960                x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
961                y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
962            }
963
964            layer->setFilter(GL_NEAREST, true);
965        } else {
966            layer->setFilter(GL_LINEAR, true);
967        }
968
969        drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(),
970                layer->getTexture(), layer->getAlpha() / 255.0f,
971                layer->getMode(), layer->isBlend(),
972                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
973                GL_TRIANGLE_STRIP, gMeshCount, swap, swap || simpleTransform);
974
975        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
976    } else {
977        resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
978        drawTextureLayer(layer, rect);
979        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
980    }
981}
982
983void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
984    if (layer->region.isRect()) {
985        layer->setRegionAsRect();
986
987        composeLayerRect(layer, layer->regionRect);
988
989        layer->region.clear();
990        return;
991    }
992
993    // TODO: See LayerRenderer.cpp::generateMesh() for important
994    //       information about this implementation
995    if (CC_LIKELY(!layer->region.isEmpty())) {
996        size_t count;
997        const android::Rect* rects = layer->region.getArray(&count);
998
999        const float alpha = layer->getAlpha() / 255.0f;
1000        const float texX = 1.0f / float(layer->getWidth());
1001        const float texY = 1.0f / float(layer->getHeight());
1002        const float height = rect.getHeight();
1003
1004        TextureVertex* mesh = mCaches.getRegionMesh();
1005        GLsizei numQuads = 0;
1006
1007        setupDraw();
1008        setupDrawWithTexture();
1009        setupDrawColor(alpha, alpha, alpha, alpha);
1010        setupDrawColorFilter();
1011        setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode(), false);
1012        setupDrawProgram();
1013        setupDrawDirtyRegionsDisabled();
1014        setupDrawPureColorUniforms();
1015        setupDrawColorFilterUniforms();
1016        setupDrawTexture(layer->getTexture());
1017        if (mSnapshot->transform->isPureTranslate()) {
1018            const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
1019            const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
1020
1021            layer->setFilter(GL_NEAREST);
1022            setupDrawModelViewTranslate(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
1023        } else {
1024            layer->setFilter(GL_LINEAR);
1025            setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
1026        }
1027        setupDrawMeshIndices(&mesh[0].position[0], &mesh[0].texture[0]);
1028
1029        for (size_t i = 0; i < count; i++) {
1030            const android::Rect* r = &rects[i];
1031
1032            const float u1 = r->left * texX;
1033            const float v1 = (height - r->top) * texY;
1034            const float u2 = r->right * texX;
1035            const float v2 = (height - r->bottom) * texY;
1036
1037            // TODO: Reject quads outside of the clip
1038            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
1039            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
1040            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
1041            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
1042
1043            numQuads++;
1044
1045            if (numQuads >= REGION_MESH_QUAD_COUNT) {
1046                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
1047                numQuads = 0;
1048                mesh = mCaches.getRegionMesh();
1049            }
1050        }
1051
1052        if (numQuads > 0) {
1053            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
1054        }
1055
1056        finishDrawTexture();
1057
1058#if DEBUG_LAYERS_AS_REGIONS
1059        drawRegionRects(layer->region);
1060#endif
1061
1062        layer->region.clear();
1063    }
1064}
1065
1066void OpenGLRenderer::drawRegionRects(const Region& region) {
1067#if DEBUG_LAYERS_AS_REGIONS
1068    size_t count;
1069    const android::Rect* rects = region.getArray(&count);
1070
1071    uint32_t colors[] = {
1072            0x7fff0000, 0x7f00ff00,
1073            0x7f0000ff, 0x7fff00ff,
1074    };
1075
1076    int offset = 0;
1077    int32_t top = rects[0].top;
1078
1079    for (size_t i = 0; i < count; i++) {
1080        if (top != rects[i].top) {
1081            offset ^= 0x2;
1082            top = rects[i].top;
1083        }
1084
1085        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
1086        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
1087                SkXfermode::kSrcOver_Mode);
1088    }
1089#endif
1090}
1091
1092void OpenGLRenderer::dirtyLayer(const float left, const float top,
1093        const float right, const float bottom, const mat4 transform) {
1094    if (hasLayer()) {
1095        Rect bounds(left, top, right, bottom);
1096        transform.mapRect(bounds);
1097        dirtyLayerUnchecked(bounds, getRegion());
1098    }
1099}
1100
1101void OpenGLRenderer::dirtyLayer(const float left, const float top,
1102        const float right, const float bottom) {
1103    if (hasLayer()) {
1104        Rect bounds(left, top, right, bottom);
1105        dirtyLayerUnchecked(bounds, getRegion());
1106    }
1107}
1108
1109void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
1110    if (bounds.intersect(*mSnapshot->clipRect)) {
1111        bounds.snapToPixelBoundaries();
1112        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1113        if (!dirty.isEmpty()) {
1114            region->orSelf(dirty);
1115        }
1116    }
1117}
1118
1119void OpenGLRenderer::clearLayerRegions() {
1120    const size_t count = mLayers.size();
1121    if (count == 0) return;
1122
1123    if (!mSnapshot->isIgnored()) {
1124        // Doing several glScissor/glClear here can negatively impact
1125        // GPUs with a tiler architecture, instead we draw quads with
1126        // the Clear blending mode
1127
1128        // The list contains bounds that have already been clipped
1129        // against their initial clip rect, and the current clip
1130        // is likely different so we need to disable clipping here
1131        bool scissorChanged = mCaches.disableScissor();
1132
1133        Vertex mesh[count * 6];
1134        Vertex* vertex = mesh;
1135
1136        for (uint32_t i = 0; i < count; i++) {
1137            Rect* bounds = mLayers.itemAt(i);
1138
1139            Vertex::set(vertex++, bounds->left, bounds->bottom);
1140            Vertex::set(vertex++, bounds->left, bounds->top);
1141            Vertex::set(vertex++, bounds->right, bounds->top);
1142            Vertex::set(vertex++, bounds->left, bounds->bottom);
1143            Vertex::set(vertex++, bounds->right, bounds->top);
1144            Vertex::set(vertex++, bounds->right, bounds->bottom);
1145
1146            delete bounds;
1147        }
1148
1149        setupDraw(false);
1150        setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
1151        setupDrawBlending(true, SkXfermode::kClear_Mode);
1152        setupDrawProgram();
1153        setupDrawPureColorUniforms();
1154        setupDrawModelViewTranslate(0.0f, 0.0f, 0.0f, 0.0f, true);
1155        setupDrawVertices(&mesh[0].position[0]);
1156
1157        glDrawArrays(GL_TRIANGLES, 0, count * 6);
1158
1159        if (scissorChanged) mCaches.enableScissor();
1160    } else {
1161        for (uint32_t i = 0; i < count; i++) {
1162            delete mLayers.itemAt(i);
1163        }
1164    }
1165
1166    mLayers.clear();
1167}
1168
1169///////////////////////////////////////////////////////////////////////////////
1170// Transforms
1171///////////////////////////////////////////////////////////////////////////////
1172
1173void OpenGLRenderer::translate(float dx, float dy) {
1174    mSnapshot->transform->translate(dx, dy, 0.0f);
1175}
1176
1177void OpenGLRenderer::rotate(float degrees) {
1178    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
1179}
1180
1181void OpenGLRenderer::scale(float sx, float sy) {
1182    mSnapshot->transform->scale(sx, sy, 1.0f);
1183}
1184
1185void OpenGLRenderer::skew(float sx, float sy) {
1186    mSnapshot->transform->skew(sx, sy);
1187}
1188
1189void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
1190    if (matrix) {
1191        mSnapshot->transform->load(*matrix);
1192    } else {
1193        mSnapshot->transform->loadIdentity();
1194    }
1195}
1196
1197void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
1198    mSnapshot->transform->copyTo(*matrix);
1199}
1200
1201void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
1202    SkMatrix transform;
1203    mSnapshot->transform->copyTo(transform);
1204    transform.preConcat(*matrix);
1205    mSnapshot->transform->load(transform);
1206}
1207
1208///////////////////////////////////////////////////////////////////////////////
1209// Clipping
1210///////////////////////////////////////////////////////////////////////////////
1211
1212void OpenGLRenderer::setScissorFromClip() {
1213    Rect clip(*mSnapshot->clipRect);
1214    clip.snapToPixelBoundaries();
1215
1216    if (mCaches.setScissor(clip.left, mSnapshot->height - clip.bottom,
1217            clip.getWidth(), clip.getHeight())) {
1218        mDirtyClip = false;
1219    }
1220}
1221
1222const Rect& OpenGLRenderer::getClipBounds() {
1223    return mSnapshot->getLocalClip();
1224}
1225
1226bool OpenGLRenderer::quickRejectNoScissor(float left, float top, float right, float bottom) {
1227    if (mSnapshot->isIgnored()) {
1228        return true;
1229    }
1230
1231    Rect r(left, top, right, bottom);
1232    mSnapshot->transform->mapRect(r);
1233    r.snapToPixelBoundaries();
1234
1235    Rect clipRect(*mSnapshot->clipRect);
1236    clipRect.snapToPixelBoundaries();
1237
1238    return !clipRect.intersects(r);
1239}
1240
1241bool OpenGLRenderer::quickRejectNoScissor(float left, float top, float right, float bottom,
1242        Rect& transformed, Rect& clip) {
1243    if (mSnapshot->isIgnored()) {
1244        return true;
1245    }
1246
1247    transformed.set(left, top, right, bottom);
1248    mSnapshot->transform->mapRect(transformed);
1249    transformed.snapToPixelBoundaries();
1250
1251    clip.set(*mSnapshot->clipRect);
1252    clip.snapToPixelBoundaries();
1253
1254    return !clip.intersects(transformed);
1255}
1256
1257bool OpenGLRenderer::quickRejectPreStroke(float left, float top, float right, float bottom,
1258        SkPaint* paint) {
1259    if (paint->getStyle() != SkPaint::kFill_Style) {
1260        float outset = paint->getStrokeWidth() * 0.5f;
1261        return quickReject(left - outset, top - outset, right + outset, bottom + outset);
1262    } else {
1263        return quickReject(left, top, right, bottom);
1264    }
1265}
1266
1267bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
1268    if (mSnapshot->isIgnored() || bottom <= top || right <= left) {
1269        return true;
1270    }
1271
1272    Rect r(left, top, right, bottom);
1273    mSnapshot->transform->mapRect(r);
1274    r.snapToPixelBoundaries();
1275
1276    Rect clipRect(*mSnapshot->clipRect);
1277    clipRect.snapToPixelBoundaries();
1278
1279    bool rejected = !clipRect.intersects(r);
1280    if (!isDeferred() && !rejected) {
1281        mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clipRect.contains(r));
1282    }
1283
1284    return rejected;
1285}
1286
1287bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
1288    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
1289    if (clipped) {
1290        dirtyClip();
1291    }
1292    return !mSnapshot->clipRect->isEmpty();
1293}
1294
1295Rect* OpenGLRenderer::getClipRect() {
1296    return mSnapshot->clipRect;
1297}
1298
1299///////////////////////////////////////////////////////////////////////////////
1300// Drawing commands
1301///////////////////////////////////////////////////////////////////////////////
1302
1303void OpenGLRenderer::setupDraw(bool clear) {
1304    // TODO: It would be best if we could do this before quickReject()
1305    //       changes the scissor test state
1306    if (clear) clearLayerRegions();
1307    if (mDirtyClip) {
1308        setScissorFromClip();
1309    }
1310    mDescription.reset();
1311    mSetShaderColor = false;
1312    mColorSet = false;
1313    mColorA = mColorR = mColorG = mColorB = 0.0f;
1314    mTextureUnit = 0;
1315    mTrackDirtyRegions = true;
1316}
1317
1318void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1319    mDescription.hasTexture = true;
1320    mDescription.hasAlpha8Texture = isAlpha8;
1321}
1322
1323void OpenGLRenderer::setupDrawWithExternalTexture() {
1324    mDescription.hasExternalTexture = true;
1325}
1326
1327void OpenGLRenderer::setupDrawNoTexture() {
1328    mCaches.disbaleTexCoordsVertexArray();
1329}
1330
1331void OpenGLRenderer::setupDrawAA() {
1332    mDescription.isAA = true;
1333}
1334
1335void OpenGLRenderer::setupDrawVertexShape() {
1336    mDescription.isVertexShape = true;
1337}
1338
1339void OpenGLRenderer::setupDrawPoint(float pointSize) {
1340    mDescription.isPoint = true;
1341    mDescription.pointSize = pointSize;
1342}
1343
1344void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1345    mColorA = alpha / 255.0f;
1346    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1347    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1348    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1349    mColorSet = true;
1350    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
1351}
1352
1353void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1354    mColorA = alpha / 255.0f;
1355    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1356    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1357    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1358    mColorSet = true;
1359    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
1360}
1361
1362void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) {
1363    mCaches.fontRenderer->describe(mDescription, paint);
1364}
1365
1366void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1367    mColorA = a;
1368    mColorR = r;
1369    mColorG = g;
1370    mColorB = b;
1371    mColorSet = true;
1372    mSetShaderColor = mDescription.setColor(r, g, b, a);
1373}
1374
1375void OpenGLRenderer::setupDrawShader() {
1376    if (mShader) {
1377        mShader->describe(mDescription, mCaches.extensions);
1378    }
1379}
1380
1381void OpenGLRenderer::setupDrawColorFilter() {
1382    if (mColorFilter) {
1383        mColorFilter->describe(mDescription, mCaches.extensions);
1384    }
1385}
1386
1387void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1388    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1389        mColorA = 1.0f;
1390        mColorR = mColorG = mColorB = 0.0f;
1391        mSetShaderColor = mDescription.modulate = true;
1392    }
1393}
1394
1395void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
1396    // When the blending mode is kClear_Mode, we need to use a modulate color
1397    // argb=1,0,0,0
1398    accountForClear(mode);
1399    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1400            mDescription, swapSrcDst);
1401}
1402
1403void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
1404    // When the blending mode is kClear_Mode, we need to use a modulate color
1405    // argb=1,0,0,0
1406    accountForClear(mode);
1407    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()) ||
1408            (mColorFilter && mColorFilter->blend()), mode, mDescription, swapSrcDst);
1409}
1410
1411void OpenGLRenderer::setupDrawProgram() {
1412    useProgram(mCaches.programCache.get(mDescription));
1413}
1414
1415void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1416    mTrackDirtyRegions = false;
1417}
1418
1419void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
1420        bool ignoreTransform) {
1421    mModelView.loadTranslate(left, top, 0.0f);
1422    if (!ignoreTransform) {
1423        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1424        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1425    } else {
1426        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1427        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
1428    }
1429}
1430
1431void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) {
1432    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform, offset);
1433}
1434
1435void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
1436        bool ignoreTransform, bool ignoreModelView) {
1437    if (!ignoreModelView) {
1438        mModelView.loadTranslate(left, top, 0.0f);
1439        mModelView.scale(right - left, bottom - top, 1.0f);
1440    } else {
1441        mModelView.loadIdentity();
1442    }
1443    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1444    if (!ignoreTransform) {
1445        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1446        if (mTrackDirtyRegions && dirty) {
1447            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1448        }
1449    } else {
1450        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1451        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
1452    }
1453}
1454
1455void OpenGLRenderer::setupDrawPointUniforms() {
1456    int slot = mCaches.currentProgram->getUniform("pointSize");
1457    glUniform1f(slot, mDescription.pointSize);
1458}
1459
1460void OpenGLRenderer::setupDrawColorUniforms() {
1461    if ((mColorSet && !mShader) || (mShader && mSetShaderColor)) {
1462        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1463    }
1464}
1465
1466void OpenGLRenderer::setupDrawPureColorUniforms() {
1467    if (mSetShaderColor) {
1468        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1469    }
1470}
1471
1472void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1473    if (mShader) {
1474        if (ignoreTransform) {
1475            mModelView.loadInverse(*mSnapshot->transform);
1476        }
1477        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
1478    }
1479}
1480
1481void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1482    if (mShader) {
1483        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
1484    }
1485}
1486
1487void OpenGLRenderer::setupDrawColorFilterUniforms() {
1488    if (mColorFilter) {
1489        mColorFilter->setupProgram(mCaches.currentProgram);
1490    }
1491}
1492
1493void OpenGLRenderer::setupDrawTextGammaUniforms() {
1494    mCaches.fontRenderer->setupProgram(mDescription, mCaches.currentProgram);
1495}
1496
1497void OpenGLRenderer::setupDrawSimpleMesh() {
1498    bool force = mCaches.bindMeshBuffer();
1499    mCaches.bindPositionVertexPointer(force, 0);
1500    mCaches.unbindIndicesBuffer();
1501}
1502
1503void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1504    bindTexture(texture);
1505    mTextureUnit++;
1506    mCaches.enableTexCoordsVertexArray();
1507}
1508
1509void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1510    bindExternalTexture(texture);
1511    mTextureUnit++;
1512    mCaches.enableTexCoordsVertexArray();
1513}
1514
1515void OpenGLRenderer::setupDrawTextureTransform() {
1516    mDescription.hasTextureTransform = true;
1517}
1518
1519void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1520    glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1521            GL_FALSE, &transform.data[0]);
1522}
1523
1524void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1525    bool force = false;
1526    if (!vertices) {
1527        force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1528    } else {
1529        force = mCaches.unbindMeshBuffer();
1530    }
1531
1532    mCaches.bindPositionVertexPointer(force, vertices);
1533    if (mCaches.currentProgram->texCoords >= 0) {
1534        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1535    }
1536
1537    mCaches.unbindIndicesBuffer();
1538}
1539
1540void OpenGLRenderer::setupDrawMeshIndices(GLvoid* vertices, GLvoid* texCoords) {
1541    bool force = mCaches.unbindMeshBuffer();
1542    mCaches.bindPositionVertexPointer(force, vertices);
1543    if (mCaches.currentProgram->texCoords >= 0) {
1544        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1545    }
1546}
1547
1548void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) {
1549    bool force = mCaches.unbindMeshBuffer();
1550    mCaches.bindPositionVertexPointer(force, vertices, gVertexStride);
1551    mCaches.unbindIndicesBuffer();
1552}
1553
1554/**
1555 * Sets up the shader to draw an AA line. We draw AA lines with quads, where there is an
1556 * outer boundary that fades out to 0. The variables set in the shader define the proportion of
1557 * the width and length of the primitive occupied by the AA region. The vtxWidth and vtxLength
1558 * attributes (one per vertex) are values from zero to one that tells the fragment
1559 * shader where the fragment is in relation to the line width/length overall; these values are
1560 * then used to compute the proper color, based on whether the fragment lies in the fading AA
1561 * region of the line.
1562 * Note that we only pass down the width values in this setup function. The length coordinates
1563 * are set up for each individual segment.
1564 */
1565void OpenGLRenderer::setupDrawAALine(GLvoid* vertices, GLvoid* widthCoords,
1566        GLvoid* lengthCoords, float boundaryWidthProportion, int& widthSlot, int& lengthSlot) {
1567    bool force = mCaches.unbindMeshBuffer();
1568    mCaches.bindPositionVertexPointer(force, vertices, gAAVertexStride);
1569    mCaches.resetTexCoordsVertexPointer();
1570    mCaches.unbindIndicesBuffer();
1571
1572    widthSlot = mCaches.currentProgram->getAttrib("vtxWidth");
1573    glEnableVertexAttribArray(widthSlot);
1574    glVertexAttribPointer(widthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, widthCoords);
1575
1576    lengthSlot = mCaches.currentProgram->getAttrib("vtxLength");
1577    glEnableVertexAttribArray(lengthSlot);
1578    glVertexAttribPointer(lengthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, lengthCoords);
1579
1580    int boundaryWidthSlot = mCaches.currentProgram->getUniform("boundaryWidth");
1581    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1582}
1583
1584void OpenGLRenderer::finishDrawAALine(const int widthSlot, const int lengthSlot) {
1585    glDisableVertexAttribArray(widthSlot);
1586    glDisableVertexAttribArray(lengthSlot);
1587}
1588
1589void OpenGLRenderer::finishDrawTexture() {
1590}
1591
1592///////////////////////////////////////////////////////////////////////////////
1593// Drawing
1594///////////////////////////////////////////////////////////////////////////////
1595
1596status_t OpenGLRenderer::drawDisplayList(DisplayList* displayList,
1597        Rect& dirty, int32_t flags, uint32_t level) {
1598
1599    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1600    // will be performed by the display list itself
1601    if (displayList && displayList->isRenderable()) {
1602        return displayList->replay(*this, dirty, flags, level);
1603    }
1604
1605    return DrawGlInfo::kStatusDone;
1606}
1607
1608void OpenGLRenderer::outputDisplayList(DisplayList* displayList, uint32_t level) {
1609    if (displayList) {
1610        displayList->output(*this, level);
1611    }
1612}
1613
1614void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
1615    int alpha;
1616    SkXfermode::Mode mode;
1617    getAlphaAndMode(paint, &alpha, &mode);
1618
1619    int color = paint != NULL ? paint->getColor() : 0;
1620
1621    float x = left;
1622    float y = top;
1623
1624    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1625
1626    bool ignoreTransform = false;
1627    if (mSnapshot->transform->isPureTranslate()) {
1628        x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1629        y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1630        ignoreTransform = true;
1631
1632        texture->setFilter(GL_NEAREST, true);
1633    } else {
1634        texture->setFilter(FILTER(paint), true);
1635    }
1636
1637    drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
1638            paint != NULL, color, alpha, mode, (GLvoid*) NULL,
1639            (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
1640}
1641
1642status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1643    const float right = left + bitmap->width();
1644    const float bottom = top + bitmap->height();
1645
1646    if (quickReject(left, top, right, bottom)) {
1647        return DrawGlInfo::kStatusDone;
1648    }
1649
1650    mCaches.activeTexture(0);
1651    Texture* texture = mCaches.textureCache.get(bitmap);
1652    if (!texture) return DrawGlInfo::kStatusDone;
1653    const AutoTexture autoCleanup(texture);
1654
1655    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1656        drawAlphaBitmap(texture, left, top, paint);
1657    } else {
1658        drawTextureRect(left, top, right, bottom, texture, paint);
1659    }
1660
1661    return DrawGlInfo::kStatusDrew;
1662}
1663
1664status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1665    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1666    const mat4 transform(*matrix);
1667    transform.mapRect(r);
1668
1669    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1670        return DrawGlInfo::kStatusDone;
1671    }
1672
1673    mCaches.activeTexture(0);
1674    Texture* texture = mCaches.textureCache.get(bitmap);
1675    if (!texture) return DrawGlInfo::kStatusDone;
1676    const AutoTexture autoCleanup(texture);
1677
1678    // This could be done in a cheaper way, all we need is pass the matrix
1679    // to the vertex shader. The save/restore is a bit overkill.
1680    save(SkCanvas::kMatrix_SaveFlag);
1681    concatMatrix(matrix);
1682    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1683        drawAlphaBitmap(texture, 0.0f, 0.0f, paint);
1684    } else {
1685        drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1686    }
1687    restore();
1688
1689    return DrawGlInfo::kStatusDrew;
1690}
1691
1692status_t OpenGLRenderer::drawBitmapData(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1693    const float right = left + bitmap->width();
1694    const float bottom = top + bitmap->height();
1695
1696    if (quickReject(left, top, right, bottom)) {
1697        return DrawGlInfo::kStatusDone;
1698    }
1699
1700    mCaches.activeTexture(0);
1701    Texture* texture = mCaches.textureCache.getTransient(bitmap);
1702    const AutoTexture autoCleanup(texture);
1703
1704    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1705        drawAlphaBitmap(texture, left, top, paint);
1706    } else {
1707        drawTextureRect(left, top, right, bottom, texture, paint);
1708    }
1709
1710    return DrawGlInfo::kStatusDrew;
1711}
1712
1713status_t OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1714        float* vertices, int* colors, SkPaint* paint) {
1715    if (!vertices || mSnapshot->isIgnored()) {
1716        return DrawGlInfo::kStatusDone;
1717    }
1718
1719    // TODO: We should compute the bounding box when recording the display list
1720    float left = FLT_MAX;
1721    float top = FLT_MAX;
1722    float right = FLT_MIN;
1723    float bottom = FLT_MIN;
1724
1725    const uint32_t count = meshWidth * meshHeight * 6;
1726
1727    // TODO: Support the colors array
1728    TextureVertex mesh[count];
1729    TextureVertex* vertex = mesh;
1730
1731    for (int32_t y = 0; y < meshHeight; y++) {
1732        for (int32_t x = 0; x < meshWidth; x++) {
1733            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1734
1735            float u1 = float(x) / meshWidth;
1736            float u2 = float(x + 1) / meshWidth;
1737            float v1 = float(y) / meshHeight;
1738            float v2 = float(y + 1) / meshHeight;
1739
1740            int ax = i + (meshWidth + 1) * 2;
1741            int ay = ax + 1;
1742            int bx = i;
1743            int by = bx + 1;
1744            int cx = i + 2;
1745            int cy = cx + 1;
1746            int dx = i + (meshWidth + 1) * 2 + 2;
1747            int dy = dx + 1;
1748
1749            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1750            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1751            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1752
1753            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1754            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1755            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1756
1757            // TODO: This could be optimized to avoid unnecessary ops
1758            left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1759            top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1760            right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1761            bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1762        }
1763    }
1764
1765    if (quickReject(left, top, right, bottom)) {
1766        return DrawGlInfo::kStatusDone;
1767    }
1768
1769    mCaches.activeTexture(0);
1770    Texture* texture = mCaches.textureCache.get(bitmap);
1771    if (!texture) return DrawGlInfo::kStatusDone;
1772    const AutoTexture autoCleanup(texture);
1773
1774    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1775    texture->setFilter(FILTER(paint), true);
1776
1777    int alpha;
1778    SkXfermode::Mode mode;
1779    getAlphaAndMode(paint, &alpha, &mode);
1780
1781    if (hasLayer()) {
1782        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1783    }
1784
1785    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1786            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1787            GL_TRIANGLES, count, false, false, 0, false, false);
1788
1789    return DrawGlInfo::kStatusDrew;
1790}
1791
1792status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1793         float srcLeft, float srcTop, float srcRight, float srcBottom,
1794         float dstLeft, float dstTop, float dstRight, float dstBottom,
1795         SkPaint* paint) {
1796    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1797        return DrawGlInfo::kStatusDone;
1798    }
1799
1800    mCaches.activeTexture(0);
1801    Texture* texture = mCaches.textureCache.get(bitmap);
1802    if (!texture) return DrawGlInfo::kStatusDone;
1803    const AutoTexture autoCleanup(texture);
1804
1805    const float width = texture->width;
1806    const float height = texture->height;
1807
1808    const float u1 = fmax(0.0f, srcLeft / width);
1809    const float v1 = fmax(0.0f, srcTop / height);
1810    const float u2 = fmin(1.0f, srcRight / width);
1811    const float v2 = fmin(1.0f, srcBottom / height);
1812
1813    mCaches.unbindMeshBuffer();
1814    resetDrawTextureTexCoords(u1, v1, u2, v2);
1815
1816    int alpha;
1817    SkXfermode::Mode mode;
1818    getAlphaAndMode(paint, &alpha, &mode);
1819
1820    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1821
1822    float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft);
1823    float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop);
1824
1825    bool scaled = scaleX != 1.0f || scaleY != 1.0f;
1826    // Apply a scale transform on the canvas only when a shader is in use
1827    // Skia handles the ratio between the dst and src rects as a scale factor
1828    // when a shader is set
1829    bool useScaleTransform = mShader && scaled;
1830    bool ignoreTransform = false;
1831
1832    if (CC_LIKELY(mSnapshot->transform->isPureTranslate() && !useScaleTransform)) {
1833        float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1834        float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1835
1836        dstRight = x + (dstRight - dstLeft);
1837        dstBottom = y + (dstBottom - dstTop);
1838
1839        dstLeft = x;
1840        dstTop = y;
1841
1842        texture->setFilter(scaled ? FILTER(paint) : GL_NEAREST, true);
1843        ignoreTransform = true;
1844    } else {
1845        texture->setFilter(FILTER(paint), true);
1846    }
1847
1848    if (CC_UNLIKELY(useScaleTransform)) {
1849        save(SkCanvas::kMatrix_SaveFlag);
1850        translate(dstLeft, dstTop);
1851        scale(scaleX, scaleY);
1852
1853        dstLeft = 0.0f;
1854        dstTop = 0.0f;
1855
1856        dstRight = srcRight - srcLeft;
1857        dstBottom = srcBottom - srcTop;
1858    }
1859
1860    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1861        int color = paint ? paint->getColor() : 0;
1862        drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom,
1863                texture->id, paint != NULL, color, alpha, mode,
1864                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1865                GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
1866    } else {
1867        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom,
1868                texture->id, alpha / 255.0f, mode, texture->blend,
1869                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1870                GL_TRIANGLE_STRIP, gMeshCount, false, ignoreTransform);
1871    }
1872
1873    if (CC_UNLIKELY(useScaleTransform)) {
1874        restore();
1875    }
1876
1877    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1878
1879    return DrawGlInfo::kStatusDrew;
1880}
1881
1882status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1883        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1884        float left, float top, float right, float bottom, SkPaint* paint) {
1885    int alpha;
1886    SkXfermode::Mode mode;
1887    getAlphaAndModeDirect(paint, &alpha, &mode);
1888
1889    return drawPatch(bitmap, xDivs, yDivs, colors, width, height, numColors,
1890            left, top, right, bottom, alpha, mode);
1891}
1892
1893status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1894        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1895        float left, float top, float right, float bottom, int alpha, SkXfermode::Mode mode) {
1896    if (quickReject(left, top, right, bottom)) {
1897        return DrawGlInfo::kStatusDone;
1898    }
1899
1900    alpha *= mSnapshot->alpha;
1901
1902    mCaches.activeTexture(0);
1903    Texture* texture = mCaches.textureCache.get(bitmap);
1904    if (!texture) return DrawGlInfo::kStatusDone;
1905    const AutoTexture autoCleanup(texture);
1906    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1907    texture->setFilter(GL_LINEAR, true);
1908
1909    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1910            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1911
1912    if (CC_LIKELY(mesh && mesh->verticesCount > 0)) {
1913        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1914        // Mark the current layer dirty where we are going to draw the patch
1915        if (hasLayer() && mesh->hasEmptyQuads) {
1916            const float offsetX = left + mSnapshot->transform->getTranslateX();
1917            const float offsetY = top + mSnapshot->transform->getTranslateY();
1918            const size_t count = mesh->quads.size();
1919            for (size_t i = 0; i < count; i++) {
1920                const Rect& bounds = mesh->quads.itemAt(i);
1921                if (CC_LIKELY(pureTranslate)) {
1922                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
1923                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
1924                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
1925                } else {
1926                    dirtyLayer(left + bounds.left, top + bounds.top,
1927                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
1928                }
1929            }
1930        }
1931
1932        if (CC_LIKELY(pureTranslate)) {
1933            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1934            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1935
1936            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1937                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1938                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1939                    true, !mesh->hasEmptyQuads);
1940        } else {
1941            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1942                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1943                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1944                    true, !mesh->hasEmptyQuads);
1945        }
1946    }
1947
1948    return DrawGlInfo::kStatusDrew;
1949}
1950
1951/**
1952 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
1953 * that of AA lines in the drawLines() function.  We expand the convex path by a half pixel in
1954 * screen space in all directions. However, instead of using a fragment shader to compute the
1955 * translucency of the color from its position, we simply use a varying parameter to define how far
1956 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
1957 *
1958 * Doesn't yet support joins, caps, or path effects.
1959 */
1960void OpenGLRenderer::drawConvexPath(const SkPath& path, SkPaint* paint) {
1961    int color = paint->getColor();
1962    SkPaint::Style style = paint->getStyle();
1963    SkXfermode::Mode mode = getXfermode(paint->getXfermode());
1964    bool isAA = paint->isAntiAlias();
1965
1966    VertexBuffer vertexBuffer;
1967    // TODO: try clipping large paths to viewport
1968    PathRenderer::convexPathVertices(path, paint, mSnapshot->transform, vertexBuffer);
1969
1970    if (!vertexBuffer.getSize()) {
1971        // no vertices to draw
1972        return;
1973    }
1974
1975    setupDraw();
1976    setupDrawNoTexture();
1977    if (isAA) setupDrawAA();
1978    setupDrawVertexShape();
1979    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
1980    setupDrawColorFilter();
1981    setupDrawShader();
1982    setupDrawBlending(isAA, mode);
1983    setupDrawProgram();
1984    setupDrawModelViewIdentity();
1985    setupDrawColorUniforms();
1986    setupDrawColorFilterUniforms();
1987    setupDrawShaderIdentityUniforms();
1988
1989    void* vertices = vertexBuffer.getBuffer();
1990    bool force = mCaches.unbindMeshBuffer();
1991    mCaches.bindPositionVertexPointer(true, vertices, isAA ? gAlphaVertexStride : gVertexStride);
1992    mCaches.resetTexCoordsVertexPointer();
1993    mCaches.unbindIndicesBuffer();
1994
1995    int alphaSlot = -1;
1996    if (isAA) {
1997        void* alphaCoords = ((GLbyte*) vertices) + gVertexAlphaOffset;
1998        alphaSlot = mCaches.currentProgram->getAttrib("vtxAlpha");
1999
2000        // TODO: avoid enable/disable in back to back uses of the alpha attribute
2001        glEnableVertexAttribArray(alphaSlot);
2002        glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, alphaCoords);
2003    }
2004
2005    SkRect bounds = PathRenderer::computePathBounds(path, paint);
2006    dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *mSnapshot->transform);
2007
2008    glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getSize());
2009
2010    if (isAA) {
2011        glDisableVertexAttribArray(alphaSlot);
2012    }
2013}
2014
2015/**
2016 * We draw lines as quads (tristrips). Using GL_LINES can be difficult because the rasterization
2017 * rules for those lines produces some unexpected results, and may vary between hardware devices.
2018 * The basics of lines-as-quads is easy; we simply find the normal to the line and position the
2019 * corners of the quads on either side of each line endpoint, separated by the strokeWidth
2020 * of the line. Hairlines are more involved because we need to account for transform scaling
2021 * to end up with a one-pixel-wide line in screen space..
2022 * Anti-aliased lines add another factor to the approach. We use a specialized fragment shader
2023 * in combination with values that we calculate and pass down in this method. The basic approach
2024 * is that the quad we create contains both the core line area plus a bounding area in which
2025 * the translucent/AA pixels are drawn. The values we calculate tell the shader what
2026 * proportion of the width and the length of a given segment is represented by the boundary
2027 * region. The quad ends up being exactly .5 pixel larger in all directions than the non-AA quad.
2028 * The bounding region is actually 1 pixel wide on all sides (half pixel on the outside, half pixel
2029 * on the inside). This ends up giving the result we want, with pixels that are completely
2030 * 'inside' the line area being filled opaquely and the other pixels being filled according to
2031 * how far into the boundary region they are, which is determined by shader interpolation.
2032 */
2033status_t OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
2034    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2035
2036    const bool isAA = paint->isAntiAlias();
2037    // We use half the stroke width here because we're going to position the quad
2038    // corner vertices half of the width away from the line endpoints
2039    float halfStrokeWidth = paint->getStrokeWidth() * 0.5f;
2040    // A stroke width of 0 has a special meaning in Skia:
2041    // it draws a line 1 px wide regardless of current transform
2042    bool isHairLine = paint->getStrokeWidth() == 0.0f;
2043
2044    float inverseScaleX = 1.0f;
2045    float inverseScaleY = 1.0f;
2046    bool scaled = false;
2047
2048    int alpha;
2049    SkXfermode::Mode mode;
2050
2051    int generatedVerticesCount = 0;
2052    int verticesCount = count;
2053    if (count > 4) {
2054        // Polyline: account for extra vertices needed for continuous tri-strip
2055        verticesCount += (count - 4);
2056    }
2057
2058    if (isHairLine || isAA) {
2059        // The quad that we use for AA and hairlines needs to account for scaling. For hairlines
2060        // the line on the screen should always be one pixel wide regardless of scale. For
2061        // AA lines, we only want one pixel of translucent boundary around the quad.
2062        if (CC_UNLIKELY(!mSnapshot->transform->isPureTranslate())) {
2063            Matrix4 *mat = mSnapshot->transform;
2064            float m00 = mat->data[Matrix4::kScaleX];
2065            float m01 = mat->data[Matrix4::kSkewY];
2066            float m10 = mat->data[Matrix4::kSkewX];
2067            float m11 = mat->data[Matrix4::kScaleY];
2068
2069            float scaleX = sqrtf(m00 * m00 + m01 * m01);
2070            float scaleY = sqrtf(m10 * m10 + m11 * m11);
2071
2072            inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
2073            inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
2074
2075            if (inverseScaleX != 1.0f || inverseScaleY != 1.0f) {
2076                scaled = true;
2077            }
2078        }
2079    }
2080
2081    getAlphaAndMode(paint, &alpha, &mode);
2082
2083    mCaches.enableScissor();
2084
2085    setupDraw();
2086    setupDrawNoTexture();
2087    if (isAA) {
2088        setupDrawAA();
2089    }
2090    setupDrawColor(paint->getColor(), alpha);
2091    setupDrawColorFilter();
2092    setupDrawShader();
2093    setupDrawBlending(isAA, mode);
2094    setupDrawProgram();
2095    setupDrawModelViewIdentity(true);
2096    setupDrawColorUniforms();
2097    setupDrawColorFilterUniforms();
2098    setupDrawShaderIdentityUniforms();
2099
2100    if (isHairLine) {
2101        // Set a real stroke width to be used in quad construction
2102        halfStrokeWidth = isAA? 1 : .5;
2103    } else if (isAA && !scaled) {
2104        // Expand boundary to enable AA calculations on the quad border
2105        halfStrokeWidth += .5f;
2106    }
2107
2108    int widthSlot;
2109    int lengthSlot;
2110
2111    Vertex lines[verticesCount];
2112    Vertex* vertices = &lines[0];
2113
2114    AAVertex wLines[verticesCount];
2115    AAVertex* aaVertices = &wLines[0];
2116
2117    if (CC_UNLIKELY(!isAA)) {
2118        setupDrawVertices(vertices);
2119    } else {
2120        void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
2121        void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
2122        // innerProportion is the ratio of the inner (non-AA) part of the line to the total
2123        // AA stroke width (the base stroke width expanded by a half pixel on either side).
2124        // This value is used in the fragment shader to determine how to fill fragments.
2125        // We will need to calculate the actual width proportion on each segment for
2126        // scaled non-hairlines, since the boundary proportion may differ per-axis when scaled.
2127        float boundaryWidthProportion = .5 - 1 / (2 * halfStrokeWidth);
2128        setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords,
2129                boundaryWidthProportion, widthSlot, lengthSlot);
2130    }
2131
2132    AAVertex* prevAAVertex = NULL;
2133    Vertex* prevVertex = NULL;
2134
2135    int boundaryLengthSlot = -1;
2136    int boundaryWidthSlot = -1;
2137
2138    for (int i = 0; i < count; i += 4) {
2139        // a = start point, b = end point
2140        vec2 a(points[i], points[i + 1]);
2141        vec2 b(points[i + 2], points[i + 3]);
2142
2143        float length = 0;
2144        float boundaryLengthProportion = 0;
2145        float boundaryWidthProportion = 0;
2146
2147        // Find the normal to the line
2148        vec2 n = (b - a).copyNormalized() * halfStrokeWidth;
2149        float x = n.x;
2150        n.x = -n.y;
2151        n.y = x;
2152
2153        if (isHairLine) {
2154            if (isAA) {
2155                float wideningFactor;
2156                if (fabs(n.x) >= fabs(n.y)) {
2157                    wideningFactor = fabs(1.0f / n.x);
2158                } else {
2159                    wideningFactor = fabs(1.0f / n.y);
2160                }
2161                n *= wideningFactor;
2162            }
2163
2164            if (scaled) {
2165                n.x *= inverseScaleX;
2166                n.y *= inverseScaleY;
2167            }
2168        } else if (scaled) {
2169            // Extend n by .5 pixel on each side, post-transform
2170            vec2 extendedN = n.copyNormalized();
2171            extendedN /= 2;
2172            extendedN.x *= inverseScaleX;
2173            extendedN.y *= inverseScaleY;
2174
2175            float extendedNLength = extendedN.length();
2176            // We need to set this value on the shader prior to drawing
2177            boundaryWidthProportion = .5 - extendedNLength / (halfStrokeWidth + extendedNLength);
2178            n += extendedN;
2179        }
2180
2181        // aa lines expand the endpoint vertices to encompass the AA boundary
2182        if (isAA) {
2183            vec2 abVector = (b - a);
2184            length = abVector.length();
2185            abVector.normalize();
2186
2187            if (scaled) {
2188                abVector.x *= inverseScaleX;
2189                abVector.y *= inverseScaleY;
2190                float abLength = abVector.length();
2191                boundaryLengthProportion = .5 - abLength / (length + abLength);
2192            } else {
2193                boundaryLengthProportion = .5 - .5 / (length + 1);
2194            }
2195
2196            abVector /= 2;
2197            a -= abVector;
2198            b += abVector;
2199        }
2200
2201        // Four corners of the rectangle defining a thick line
2202        vec2 p1 = a - n;
2203        vec2 p2 = a + n;
2204        vec2 p3 = b + n;
2205        vec2 p4 = b - n;
2206
2207
2208        const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
2209        const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
2210        const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
2211        const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
2212
2213        if (!quickRejectNoScissor(left, top, right, bottom)) {
2214            if (!isAA) {
2215                if (prevVertex != NULL) {
2216                    // Issue two repeat vertices to create degenerate triangles to bridge
2217                    // between the previous line and the new one. This is necessary because
2218                    // we are creating a single triangle_strip which will contain
2219                    // potentially discontinuous line segments.
2220                    Vertex::set(vertices++, prevVertex->position[0], prevVertex->position[1]);
2221                    Vertex::set(vertices++, p1.x, p1.y);
2222                    generatedVerticesCount += 2;
2223                }
2224
2225                Vertex::set(vertices++, p1.x, p1.y);
2226                Vertex::set(vertices++, p2.x, p2.y);
2227                Vertex::set(vertices++, p4.x, p4.y);
2228                Vertex::set(vertices++, p3.x, p3.y);
2229
2230                prevVertex = vertices - 1;
2231                generatedVerticesCount += 4;
2232            } else {
2233                if (!isHairLine && scaled) {
2234                    // Must set width proportions per-segment for scaled non-hairlines to use the
2235                    // correct AA boundary dimensions
2236                    if (boundaryWidthSlot < 0) {
2237                        boundaryWidthSlot =
2238                                mCaches.currentProgram->getUniform("boundaryWidth");
2239                    }
2240
2241                    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
2242                }
2243
2244                if (boundaryLengthSlot < 0) {
2245                    boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
2246                }
2247
2248                glUniform1f(boundaryLengthSlot, boundaryLengthProportion);
2249
2250                if (prevAAVertex != NULL) {
2251                    // Issue two repeat vertices to create degenerate triangles to bridge
2252                    // between the previous line and the new one. This is necessary because
2253                    // we are creating a single triangle_strip which will contain
2254                    // potentially discontinuous line segments.
2255                    AAVertex::set(aaVertices++,prevAAVertex->position[0],
2256                            prevAAVertex->position[1], prevAAVertex->width, prevAAVertex->length);
2257                    AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
2258                    generatedVerticesCount += 2;
2259                }
2260
2261                AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
2262                AAVertex::set(aaVertices++, p1.x, p1.y, 1, 0);
2263                AAVertex::set(aaVertices++, p3.x, p3.y, 0, 1);
2264                AAVertex::set(aaVertices++, p2.x, p2.y, 0, 0);
2265
2266                prevAAVertex = aaVertices - 1;
2267                generatedVerticesCount += 4;
2268            }
2269
2270            dirtyLayer(a.x == b.x ? left - 1 : left, a.y == b.y ? top - 1 : top,
2271                    a.x == b.x ? right: right, a.y == b.y ? bottom: bottom,
2272                    *mSnapshot->transform);
2273        }
2274    }
2275
2276    if (generatedVerticesCount > 0) {
2277       glDrawArrays(GL_TRIANGLE_STRIP, 0, generatedVerticesCount);
2278    }
2279
2280    if (isAA) {
2281        finishDrawAALine(widthSlot, lengthSlot);
2282    }
2283
2284    return DrawGlInfo::kStatusDrew;
2285}
2286
2287status_t OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
2288    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2289
2290    // TODO: The paint's cap style defines whether the points are square or circular
2291    // TODO: Handle AA for round points
2292
2293    // A stroke width of 0 has a special meaning in Skia:
2294    // it draws an unscaled 1px point
2295    float strokeWidth = paint->getStrokeWidth();
2296    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
2297    if (isHairLine) {
2298        // Now that we know it's hairline, we can set the effective width, to be used later
2299        strokeWidth = 1.0f;
2300    }
2301    const float halfWidth = strokeWidth / 2;
2302    int alpha;
2303    SkXfermode::Mode mode;
2304    getAlphaAndMode(paint, &alpha, &mode);
2305
2306    int verticesCount = count >> 1;
2307    int generatedVerticesCount = 0;
2308
2309    TextureVertex pointsData[verticesCount];
2310    TextureVertex* vertex = &pointsData[0];
2311
2312    // TODO: We should optimize this method to not generate vertices for points
2313    // that lie outside of the clip.
2314    mCaches.enableScissor();
2315
2316    setupDraw();
2317    setupDrawNoTexture();
2318    setupDrawPoint(strokeWidth);
2319    setupDrawColor(paint->getColor(), alpha);
2320    setupDrawColorFilter();
2321    setupDrawShader();
2322    setupDrawBlending(mode);
2323    setupDrawProgram();
2324    setupDrawModelViewIdentity(true);
2325    setupDrawColorUniforms();
2326    setupDrawColorFilterUniforms();
2327    setupDrawPointUniforms();
2328    setupDrawShaderIdentityUniforms();
2329    setupDrawMesh(vertex);
2330
2331    for (int i = 0; i < count; i += 2) {
2332        TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
2333        generatedVerticesCount++;
2334
2335        float left = points[i] - halfWidth;
2336        float right = points[i] + halfWidth;
2337        float top = points[i + 1] - halfWidth;
2338        float bottom = points [i + 1] + halfWidth;
2339
2340        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
2341    }
2342
2343    glDrawArrays(GL_POINTS, 0, generatedVerticesCount);
2344
2345    return DrawGlInfo::kStatusDrew;
2346}
2347
2348status_t OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
2349    // No need to check against the clip, we fill the clip region
2350    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2351
2352    Rect& clip(*mSnapshot->clipRect);
2353    clip.snapToPixelBoundaries();
2354
2355    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
2356
2357    return DrawGlInfo::kStatusDrew;
2358}
2359
2360status_t OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture,
2361        SkPaint* paint) {
2362    if (!texture) return DrawGlInfo::kStatusDone;
2363    const AutoTexture autoCleanup(texture);
2364
2365    const float x = left + texture->left - texture->offset;
2366    const float y = top + texture->top - texture->offset;
2367
2368    drawPathTexture(texture, x, y, paint);
2369
2370    return DrawGlInfo::kStatusDrew;
2371}
2372
2373status_t OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
2374        float rx, float ry, SkPaint* p) {
2375    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2376        return DrawGlInfo::kStatusDone;
2377    }
2378
2379    if (p->getPathEffect() != 0) {
2380        mCaches.activeTexture(0);
2381        const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
2382                right - left, bottom - top, rx, ry, p);
2383        return drawShape(left, top, texture, p);
2384    }
2385
2386    SkPath path;
2387    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2388    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2389        float outset = p->getStrokeWidth() / 2;
2390        rect.outset(outset, outset);
2391        rx += outset;
2392        ry += outset;
2393    }
2394    path.addRoundRect(rect, rx, ry);
2395    drawConvexPath(path, p);
2396
2397    return DrawGlInfo::kStatusDrew;
2398}
2399
2400status_t OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* p) {
2401    if (mSnapshot->isIgnored() || quickRejectPreStroke(x - radius, y - radius,
2402            x + radius, y + radius, p)) {
2403        return DrawGlInfo::kStatusDone;
2404    }
2405    if (p->getPathEffect() != 0) {
2406        mCaches.activeTexture(0);
2407        const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, p);
2408        return drawShape(x - radius, y - radius, texture, p);
2409    }
2410
2411    SkPath path;
2412    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2413        path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
2414    } else {
2415        path.addCircle(x, y, radius);
2416    }
2417    drawConvexPath(path, p);
2418
2419    return DrawGlInfo::kStatusDrew;
2420}
2421
2422status_t OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
2423        SkPaint* p) {
2424    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2425        return DrawGlInfo::kStatusDone;
2426    }
2427
2428    if (p->getPathEffect() != 0) {
2429        mCaches.activeTexture(0);
2430        const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, p);
2431        return drawShape(left, top, texture, p);
2432    }
2433
2434    SkPath path;
2435    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2436    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2437        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2438    }
2439    path.addOval(rect);
2440    drawConvexPath(path, p);
2441
2442    return DrawGlInfo::kStatusDrew;
2443}
2444
2445status_t OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2446        float startAngle, float sweepAngle, bool useCenter, SkPaint* p) {
2447    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2448        return DrawGlInfo::kStatusDone;
2449    }
2450
2451    if (fabs(sweepAngle) >= 360.0f) {
2452        return drawOval(left, top, right, bottom, p);
2453    }
2454
2455    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
2456    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != 0 || p->getStrokeCap() != SkPaint::kButt_Cap || useCenter) {
2457        mCaches.activeTexture(0);
2458        const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
2459                startAngle, sweepAngle, useCenter, p);
2460        return drawShape(left, top, texture, p);
2461    }
2462
2463    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2464    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2465        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2466    }
2467
2468    SkPath path;
2469    if (useCenter) {
2470        path.moveTo(rect.centerX(), rect.centerY());
2471    }
2472    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
2473    if (useCenter) {
2474        path.close();
2475    }
2476    drawConvexPath(path, p);
2477
2478    return DrawGlInfo::kStatusDrew;
2479}
2480
2481// See SkPaintDefaults.h
2482#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
2483
2484status_t OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
2485    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2486        return DrawGlInfo::kStatusDone;
2487    }
2488
2489    if (p->getStyle() != SkPaint::kFill_Style) {
2490        // only fill style is supported by drawConvexPath, since others have to handle joins
2491        if (p->getPathEffect() != 0 || p->getStrokeJoin() != SkPaint::kMiter_Join ||
2492                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
2493            mCaches.activeTexture(0);
2494            const PathTexture* texture =
2495                    mCaches.rectShapeCache.getRect(right - left, bottom - top, p);
2496            return drawShape(left, top, texture, p);
2497        }
2498
2499        SkPath path;
2500        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2501        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2502            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2503        }
2504        path.addRect(rect);
2505        drawConvexPath(path, p);
2506
2507        return DrawGlInfo::kStatusDrew;
2508    }
2509
2510    if (p->isAntiAlias() && !mSnapshot->transform->isSimple()) {
2511        SkPath path;
2512        path.addRect(left, top, right, bottom);
2513        drawConvexPath(path, p);
2514    } else {
2515        drawColorRect(left, top, right, bottom, p->getColor(), getXfermode(p->getXfermode()));
2516    }
2517
2518    return DrawGlInfo::kStatusDrew;
2519}
2520
2521void OpenGLRenderer::drawTextShadow(SkPaint* paint, const char* text, int bytesCount, int count,
2522        const float* positions, FontRenderer& fontRenderer, int alpha, SkXfermode::Mode mode,
2523        float x, float y) {
2524    mCaches.activeTexture(0);
2525
2526    // NOTE: The drop shadow will not perform gamma correction
2527    //       if shader-based correction is enabled
2528    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2529    const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2530            paint, text, bytesCount, count, mShadowRadius, positions);
2531    const AutoTexture autoCleanup(shadow);
2532
2533    const float sx = x - shadow->left + mShadowDx;
2534    const float sy = y - shadow->top + mShadowDy;
2535
2536    const int shadowAlpha = ((mShadowColor >> 24) & 0xFF) * mSnapshot->alpha;
2537    int shadowColor = mShadowColor;
2538    if (mShader) {
2539        shadowColor = 0xffffffff;
2540    }
2541
2542    setupDraw();
2543    setupDrawWithTexture(true);
2544    setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2545    setupDrawColorFilter();
2546    setupDrawShader();
2547    setupDrawBlending(true, mode);
2548    setupDrawProgram();
2549    setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2550    setupDrawTexture(shadow->id);
2551    setupDrawPureColorUniforms();
2552    setupDrawColorFilterUniforms();
2553    setupDrawShaderUniforms();
2554    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2555
2556    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2557}
2558
2559status_t OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2560        const float* positions, SkPaint* paint) {
2561    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2562            (paint->getAlpha() * mSnapshot->alpha == 0 && paint->getXfermode() == NULL)) {
2563        return DrawGlInfo::kStatusDone;
2564    }
2565
2566    // NOTE: Skia does not support perspective transform on drawPosText yet
2567    if (!mSnapshot->transform->isSimple()) {
2568        return DrawGlInfo::kStatusDone;
2569    }
2570
2571    float x = 0.0f;
2572    float y = 0.0f;
2573    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2574    if (pureTranslate) {
2575        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2576        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2577    }
2578
2579    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2580    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2581            paint->getTextSize());
2582
2583    int alpha;
2584    SkXfermode::Mode mode;
2585    getAlphaAndMode(paint, &alpha, &mode);
2586
2587    if (CC_UNLIKELY(mHasShadow)) {
2588        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, alpha, mode,
2589                0.0f, 0.0f);
2590    }
2591
2592    // Pick the appropriate texture filtering
2593    bool linearFilter = mSnapshot->transform->changesBounds();
2594    if (pureTranslate && !linearFilter) {
2595        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2596    }
2597
2598    mCaches.activeTexture(0);
2599    setupDraw();
2600    setupDrawTextGamma(paint);
2601    setupDrawDirtyRegionsDisabled();
2602    setupDrawWithTexture(true);
2603    setupDrawAlpha8Color(paint->getColor(), alpha);
2604    setupDrawColorFilter();
2605    setupDrawShader();
2606    setupDrawBlending(true, mode);
2607    setupDrawProgram();
2608    setupDrawModelView(x, y, x, y, pureTranslate, true);
2609    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2610    setupDrawPureColorUniforms();
2611    setupDrawColorFilterUniforms();
2612    setupDrawShaderUniforms(pureTranslate);
2613    setupDrawTextGammaUniforms();
2614
2615    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2616    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2617
2618    const bool hasActiveLayer = hasLayer();
2619
2620    if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2621            positions, hasActiveLayer ? &bounds : NULL)) {
2622        if (hasActiveLayer) {
2623            if (!pureTranslate) {
2624                mSnapshot->transform->mapRect(bounds);
2625            }
2626            dirtyLayerUnchecked(bounds, getRegion());
2627        }
2628    }
2629
2630    return DrawGlInfo::kStatusDrew;
2631}
2632
2633status_t OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
2634        float x, float y, const float* positions, SkPaint* paint, float length) {
2635    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2636            (paint->getAlpha() * mSnapshot->alpha == 0 && paint->getXfermode() == NULL)) {
2637        return DrawGlInfo::kStatusDone;
2638    }
2639
2640    if (length < 0.0f) length = paint->measureText(text, bytesCount);
2641    switch (paint->getTextAlign()) {
2642        case SkPaint::kCenter_Align:
2643            x -= length / 2.0f;
2644            break;
2645        case SkPaint::kRight_Align:
2646            x -= length;
2647            break;
2648        default:
2649            break;
2650    }
2651
2652    SkPaint::FontMetrics metrics;
2653    paint->getFontMetrics(&metrics, 0.0f);
2654    if (quickReject(x, y + metrics.fTop, x + length, y + metrics.fBottom)) {
2655        return DrawGlInfo::kStatusDone;
2656    }
2657
2658    const float oldX = x;
2659    const float oldY = y;
2660    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2661    if (CC_LIKELY(pureTranslate)) {
2662        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2663        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2664    }
2665
2666#if DEBUG_GLYPHS
2667    ALOGD("OpenGLRenderer drawText() with FontID=%d",
2668            SkTypeface::UniqueID(paint->getTypeface()));
2669#endif
2670
2671    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2672    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2673            paint->getTextSize());
2674
2675    int alpha;
2676    SkXfermode::Mode mode;
2677    getAlphaAndMode(paint, &alpha, &mode);
2678
2679    if (CC_UNLIKELY(mHasShadow)) {
2680        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, alpha, mode,
2681                oldX, oldY);
2682    }
2683
2684    // Pick the appropriate texture filtering
2685    bool linearFilter = mSnapshot->transform->changesBounds();
2686    if (pureTranslate && !linearFilter) {
2687        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2688    }
2689
2690    // The font renderer will always use texture unit 0
2691    mCaches.activeTexture(0);
2692    setupDraw();
2693    setupDrawTextGamma(paint);
2694    setupDrawDirtyRegionsDisabled();
2695    setupDrawWithTexture(true);
2696    setupDrawAlpha8Color(paint->getColor(), alpha);
2697    setupDrawColorFilter();
2698    setupDrawShader();
2699    setupDrawBlending(true, mode);
2700    setupDrawProgram();
2701    setupDrawModelView(x, y, x, y, pureTranslate, true);
2702    // See comment above; the font renderer must use texture unit 0
2703    // assert(mTextureUnit == 0)
2704    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2705    setupDrawPureColorUniforms();
2706    setupDrawColorFilterUniforms();
2707    setupDrawShaderUniforms(pureTranslate);
2708    setupDrawTextGammaUniforms();
2709
2710    const Rect* clip = pureTranslate ? mSnapshot->clipRect :
2711            (mSnapshot->hasPerspectiveTransform() ? NULL : &mSnapshot->getLocalClip());
2712    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2713
2714    const bool hasActiveLayer = hasLayer();
2715
2716    bool status;
2717    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2718        SkPaint paintCopy(*paint);
2719        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2720        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2721                positions, hasActiveLayer ? &bounds : NULL);
2722    } else {
2723        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2724                positions, hasActiveLayer ? &bounds : NULL);
2725    }
2726
2727    if (status && hasActiveLayer) {
2728        if (!pureTranslate) {
2729            mSnapshot->transform->mapRect(bounds);
2730        }
2731        dirtyLayerUnchecked(bounds, getRegion());
2732    }
2733
2734    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
2735
2736    return DrawGlInfo::kStatusDrew;
2737}
2738
2739status_t OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, SkPath* path,
2740        float hOffset, float vOffset, SkPaint* paint) {
2741    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2742            (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
2743        return DrawGlInfo::kStatusDone;
2744    }
2745
2746    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2747    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2748            paint->getTextSize());
2749
2750    int alpha;
2751    SkXfermode::Mode mode;
2752    getAlphaAndMode(paint, &alpha, &mode);
2753
2754    mCaches.activeTexture(0);
2755    setupDraw();
2756    setupDrawTextGamma(paint);
2757    setupDrawDirtyRegionsDisabled();
2758    setupDrawWithTexture(true);
2759    setupDrawAlpha8Color(paint->getColor(), alpha);
2760    setupDrawColorFilter();
2761    setupDrawShader();
2762    setupDrawBlending(true, mode);
2763    setupDrawProgram();
2764    setupDrawModelView(0.0f, 0.0f, 0.0f, 0.0f, false, true);
2765    setupDrawTexture(fontRenderer.getTexture(true));
2766    setupDrawPureColorUniforms();
2767    setupDrawColorFilterUniforms();
2768    setupDrawShaderUniforms(false);
2769    setupDrawTextGammaUniforms();
2770
2771    const Rect* clip = &mSnapshot->getLocalClip();
2772    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2773
2774    const bool hasActiveLayer = hasLayer();
2775
2776    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2777            hOffset, vOffset, hasActiveLayer ? &bounds : NULL)) {
2778        if (hasActiveLayer) {
2779            mSnapshot->transform->mapRect(bounds);
2780            dirtyLayerUnchecked(bounds, getRegion());
2781        }
2782    }
2783
2784    return DrawGlInfo::kStatusDrew;
2785}
2786
2787status_t OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
2788    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2789
2790    mCaches.activeTexture(0);
2791
2792    // TODO: Perform early clip test before we rasterize the path
2793    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2794    if (!texture) return DrawGlInfo::kStatusDone;
2795    const AutoTexture autoCleanup(texture);
2796
2797    const float x = texture->left - texture->offset;
2798    const float y = texture->top - texture->offset;
2799
2800    drawPathTexture(texture, x, y, paint);
2801
2802    return DrawGlInfo::kStatusDrew;
2803}
2804
2805status_t OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
2806    if (!layer) {
2807        return DrawGlInfo::kStatusDone;
2808    }
2809
2810    mat4* transform = NULL;
2811    if (layer->isTextureLayer()) {
2812        transform = &layer->getTransform();
2813        if (!transform->isIdentity()) {
2814            save(0);
2815            mSnapshot->transform->multiply(*transform);
2816        }
2817    }
2818
2819    Rect transformed;
2820    Rect clip;
2821    const bool rejected = quickRejectNoScissor(x, y,
2822            x + layer->layer.getWidth(), y + layer->layer.getHeight(), transformed, clip);
2823
2824    if (rejected) {
2825        if (transform && !transform->isIdentity()) {
2826            restore();
2827        }
2828        return DrawGlInfo::kStatusDone;
2829    }
2830
2831    updateLayer(layer, true);
2832
2833    mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clip.contains(transformed));
2834    mCaches.activeTexture(0);
2835
2836    if (CC_LIKELY(!layer->region.isEmpty())) {
2837        SkiaColorFilter* oldFilter = mColorFilter;
2838        mColorFilter = layer->getColorFilter();
2839
2840        if (layer->region.isRect()) {
2841            composeLayerRect(layer, layer->regionRect);
2842        } else if (layer->mesh) {
2843            const float a = layer->getAlpha() / 255.0f;
2844            setupDraw();
2845            setupDrawWithTexture();
2846            setupDrawColor(a, a, a, a);
2847            setupDrawColorFilter();
2848            setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false);
2849            setupDrawProgram();
2850            setupDrawPureColorUniforms();
2851            setupDrawColorFilterUniforms();
2852            setupDrawTexture(layer->getTexture());
2853            if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) {
2854                int tx = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2855                int ty = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2856
2857                layer->setFilter(GL_NEAREST);
2858                setupDrawModelViewTranslate(tx, ty,
2859                        tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true);
2860            } else {
2861                layer->setFilter(GL_LINEAR);
2862                setupDrawModelViewTranslate(x, y,
2863                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
2864            }
2865            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
2866
2867            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
2868                    GL_UNSIGNED_SHORT, layer->meshIndices);
2869
2870            finishDrawTexture();
2871
2872#if DEBUG_LAYERS_AS_REGIONS
2873            drawRegionRects(layer->region);
2874#endif
2875        }
2876
2877        mColorFilter = oldFilter;
2878
2879        if (layer->debugDrawUpdate) {
2880            layer->debugDrawUpdate = false;
2881            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
2882                    0x7f00ff00, SkXfermode::kSrcOver_Mode);
2883        }
2884    }
2885
2886    if (transform && !transform->isIdentity()) {
2887        restore();
2888    }
2889
2890    return DrawGlInfo::kStatusDrew;
2891}
2892
2893///////////////////////////////////////////////////////////////////////////////
2894// Shaders
2895///////////////////////////////////////////////////////////////////////////////
2896
2897void OpenGLRenderer::resetShader() {
2898    mShader = NULL;
2899}
2900
2901void OpenGLRenderer::setupShader(SkiaShader* shader) {
2902    mShader = shader;
2903    if (mShader) {
2904        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
2905    }
2906}
2907
2908///////////////////////////////////////////////////////////////////////////////
2909// Color filters
2910///////////////////////////////////////////////////////////////////////////////
2911
2912void OpenGLRenderer::resetColorFilter() {
2913    mColorFilter = NULL;
2914}
2915
2916void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
2917    mColorFilter = filter;
2918}
2919
2920///////////////////////////////////////////////////////////////////////////////
2921// Drop shadow
2922///////////////////////////////////////////////////////////////////////////////
2923
2924void OpenGLRenderer::resetShadow() {
2925    mHasShadow = false;
2926}
2927
2928void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
2929    mHasShadow = true;
2930    mShadowRadius = radius;
2931    mShadowDx = dx;
2932    mShadowDy = dy;
2933    mShadowColor = color;
2934}
2935
2936///////////////////////////////////////////////////////////////////////////////
2937// Draw filters
2938///////////////////////////////////////////////////////////////////////////////
2939
2940void OpenGLRenderer::resetPaintFilter() {
2941    mHasDrawFilter = false;
2942}
2943
2944void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) {
2945    mHasDrawFilter = true;
2946    mPaintFilterClearBits = clearBits & SkPaint::kAllFlags;
2947    mPaintFilterSetBits = setBits & SkPaint::kAllFlags;
2948}
2949
2950SkPaint* OpenGLRenderer::filterPaint(SkPaint* paint) {
2951    if (CC_LIKELY(!mHasDrawFilter || !paint)) return paint;
2952
2953    uint32_t flags = paint->getFlags();
2954
2955    mFilteredPaint = *paint;
2956    mFilteredPaint.setFlags((flags & ~mPaintFilterClearBits) | mPaintFilterSetBits);
2957
2958    return &mFilteredPaint;
2959}
2960
2961///////////////////////////////////////////////////////////////////////////////
2962// Drawing implementation
2963///////////////////////////////////////////////////////////////////////////////
2964
2965void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
2966        float x, float y, SkPaint* paint) {
2967    if (quickReject(x, y, x + texture->width, y + texture->height)) {
2968        return;
2969    }
2970
2971    int alpha;
2972    SkXfermode::Mode mode;
2973    getAlphaAndMode(paint, &alpha, &mode);
2974
2975    setupDraw();
2976    setupDrawWithTexture(true);
2977    setupDrawAlpha8Color(paint->getColor(), alpha);
2978    setupDrawColorFilter();
2979    setupDrawShader();
2980    setupDrawBlending(true, mode);
2981    setupDrawProgram();
2982    setupDrawModelView(x, y, x + texture->width, y + texture->height);
2983    setupDrawTexture(texture->id);
2984    setupDrawPureColorUniforms();
2985    setupDrawColorFilterUniforms();
2986    setupDrawShaderUniforms();
2987    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2988
2989    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2990
2991    finishDrawTexture();
2992}
2993
2994// Same values used by Skia
2995#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2996#define kStdUnderline_Offset    (1.0f / 9.0f)
2997#define kStdUnderline_Thickness (1.0f / 18.0f)
2998
2999void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
3000        float x, float y, SkPaint* paint) {
3001    // Handle underline and strike-through
3002    uint32_t flags = paint->getFlags();
3003    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
3004        SkPaint paintCopy(*paint);
3005        float underlineWidth = length;
3006        // If length is > 0.0f, we already measured the text for the text alignment
3007        if (length <= 0.0f) {
3008            underlineWidth = paintCopy.measureText(text, bytesCount);
3009        }
3010
3011        if (CC_LIKELY(underlineWidth > 0.0f)) {
3012            const float textSize = paintCopy.getTextSize();
3013            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
3014
3015            const float left = x;
3016            float top = 0.0f;
3017
3018            int linesCount = 0;
3019            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
3020            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
3021
3022            const int pointsCount = 4 * linesCount;
3023            float points[pointsCount];
3024            int currentPoint = 0;
3025
3026            if (flags & SkPaint::kUnderlineText_Flag) {
3027                top = y + textSize * kStdUnderline_Offset;
3028                points[currentPoint++] = left;
3029                points[currentPoint++] = top;
3030                points[currentPoint++] = left + underlineWidth;
3031                points[currentPoint++] = top;
3032            }
3033
3034            if (flags & SkPaint::kStrikeThruText_Flag) {
3035                top = y + textSize * kStdStrikeThru_Offset;
3036                points[currentPoint++] = left;
3037                points[currentPoint++] = top;
3038                points[currentPoint++] = left + underlineWidth;
3039                points[currentPoint++] = top;
3040            }
3041
3042            paintCopy.setStrokeWidth(strokeWidth);
3043
3044            drawLines(&points[0], pointsCount, &paintCopy);
3045        }
3046    }
3047}
3048
3049status_t OpenGLRenderer::drawRects(const float* rects, int count, SkPaint* paint) {
3050    if (mSnapshot->isIgnored()) {
3051        return DrawGlInfo::kStatusDone;
3052    }
3053
3054    float left = FLT_MAX;
3055    float top = FLT_MAX;
3056    float right = FLT_MIN;
3057    float bottom = FLT_MIN;
3058
3059    int vertexCount = 0;
3060    Vertex mesh[count * 6];
3061    Vertex* vertex = mesh;
3062
3063    for (int i = 0; i < count; i++) {
3064        int index = i * 4;
3065        float l = rects[index + 0];
3066        float t = rects[index + 1];
3067        float r = rects[index + 2];
3068        float b = rects[index + 3];
3069
3070        if (!quickRejectNoScissor(left, top, right, bottom)) {
3071            Vertex::set(vertex++, l, b);
3072            Vertex::set(vertex++, l, t);
3073            Vertex::set(vertex++, r, t);
3074            Vertex::set(vertex++, l, b);
3075            Vertex::set(vertex++, r, t);
3076            Vertex::set(vertex++, r, b);
3077
3078            vertexCount += 6;
3079
3080            left = fminf(left, l);
3081            top = fminf(top, t);
3082            right = fmaxf(right, r);
3083            bottom = fmaxf(bottom, b);
3084        }
3085    }
3086
3087    if (count == 0) return DrawGlInfo::kStatusDone;
3088
3089    int color = paint->getColor();
3090    // If a shader is set, preserve only the alpha
3091    if (mShader) {
3092        color |= 0x00ffffff;
3093    }
3094    SkXfermode::Mode mode = getXfermode(paint->getXfermode());
3095
3096    setupDraw();
3097    setupDrawNoTexture();
3098    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
3099    setupDrawShader();
3100    setupDrawColorFilter();
3101    setupDrawBlending(mode);
3102    setupDrawProgram();
3103    setupDrawDirtyRegionsDisabled();
3104    setupDrawModelView(0.0f, 0.0f, 1.0f, 1.0f);
3105    setupDrawColorUniforms();
3106    setupDrawShaderUniforms();
3107    setupDrawColorFilterUniforms();
3108    setupDrawVertices((GLvoid*) &mesh[0].position[0]);
3109
3110    if (hasLayer()) {
3111        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
3112    }
3113
3114    glDrawArrays(GL_TRIANGLES, 0, vertexCount);
3115
3116    return DrawGlInfo::kStatusDrew;
3117}
3118
3119void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
3120        int color, SkXfermode::Mode mode, bool ignoreTransform) {
3121    // If a shader is set, preserve only the alpha
3122    if (mShader) {
3123        color |= 0x00ffffff;
3124    }
3125
3126    setupDraw();
3127    setupDrawNoTexture();
3128    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
3129    setupDrawShader();
3130    setupDrawColorFilter();
3131    setupDrawBlending(mode);
3132    setupDrawProgram();
3133    setupDrawModelView(left, top, right, bottom, ignoreTransform);
3134    setupDrawColorUniforms();
3135    setupDrawShaderUniforms(ignoreTransform);
3136    setupDrawColorFilterUniforms();
3137    setupDrawSimpleMesh();
3138
3139    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3140}
3141
3142void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3143        Texture* texture, SkPaint* paint) {
3144    int alpha;
3145    SkXfermode::Mode mode;
3146    getAlphaAndMode(paint, &alpha, &mode);
3147
3148    texture->setWrap(GL_CLAMP_TO_EDGE, true);
3149
3150    if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) {
3151        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
3152        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
3153
3154        texture->setFilter(GL_NEAREST, true);
3155        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
3156                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
3157                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
3158    } else {
3159        texture->setFilter(FILTER(paint), true);
3160        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
3161                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
3162                GL_TRIANGLE_STRIP, gMeshCount);
3163    }
3164}
3165
3166void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3167        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
3168    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
3169            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
3170}
3171
3172void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
3173        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
3174        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3175        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
3176
3177    setupDraw();
3178    setupDrawWithTexture();
3179    setupDrawColor(alpha, alpha, alpha, alpha);
3180    setupDrawColorFilter();
3181    setupDrawBlending(blend, mode, swapSrcDst);
3182    setupDrawProgram();
3183    if (!dirty) setupDrawDirtyRegionsDisabled();
3184    if (!ignoreScale) {
3185        setupDrawModelView(left, top, right, bottom, ignoreTransform);
3186    } else {
3187        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
3188    }
3189    setupDrawTexture(texture);
3190    setupDrawPureColorUniforms();
3191    setupDrawColorFilterUniforms();
3192    setupDrawMesh(vertices, texCoords, vbo);
3193
3194    glDrawArrays(drawMode, 0, elementsCount);
3195
3196    finishDrawTexture();
3197}
3198
3199void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom,
3200        GLuint texture, bool hasColor, int color, int alpha, SkXfermode::Mode mode,
3201        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3202        bool ignoreTransform, bool dirty) {
3203
3204    setupDraw();
3205    setupDrawWithTexture(true);
3206    if (hasColor) {
3207        setupDrawAlpha8Color(color, alpha);
3208    }
3209    setupDrawColorFilter();
3210    setupDrawShader();
3211    setupDrawBlending(true, mode);
3212    setupDrawProgram();
3213    if (!dirty) setupDrawDirtyRegionsDisabled();
3214    setupDrawModelView(left, top, right, bottom, ignoreTransform);
3215    setupDrawTexture(texture);
3216    setupDrawPureColorUniforms();
3217    setupDrawColorFilterUniforms();
3218    setupDrawShaderUniforms();
3219    setupDrawMesh(vertices, texCoords);
3220
3221    glDrawArrays(drawMode, 0, elementsCount);
3222
3223    finishDrawTexture();
3224}
3225
3226void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
3227        ProgramDescription& description, bool swapSrcDst) {
3228    blend = blend || mode != SkXfermode::kSrcOver_Mode;
3229
3230    if (blend) {
3231        // These blend modes are not supported by OpenGL directly and have
3232        // to be implemented using shaders. Since the shader will perform
3233        // the blending, turn blending off here
3234        // If the blend mode cannot be implemented using shaders, fall
3235        // back to the default SrcOver blend mode instead
3236        if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) {
3237            if (CC_UNLIKELY(mCaches.extensions.hasFramebufferFetch())) {
3238                description.framebufferMode = mode;
3239                description.swapSrcDst = swapSrcDst;
3240
3241                if (mCaches.blend) {
3242                    glDisable(GL_BLEND);
3243                    mCaches.blend = false;
3244                }
3245
3246                return;
3247            } else {
3248                mode = SkXfermode::kSrcOver_Mode;
3249            }
3250        }
3251
3252        if (!mCaches.blend) {
3253            glEnable(GL_BLEND);
3254        }
3255
3256        GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
3257        GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
3258
3259        if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
3260            glBlendFunc(sourceMode, destMode);
3261            mCaches.lastSrcMode = sourceMode;
3262            mCaches.lastDstMode = destMode;
3263        }
3264    } else if (mCaches.blend) {
3265        glDisable(GL_BLEND);
3266    }
3267    mCaches.blend = blend;
3268}
3269
3270bool OpenGLRenderer::useProgram(Program* program) {
3271    if (!program->isInUse()) {
3272        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
3273        program->use();
3274        mCaches.currentProgram = program;
3275        return false;
3276    }
3277    return true;
3278}
3279
3280void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
3281    TextureVertex* v = &mMeshVertices[0];
3282    TextureVertex::setUV(v++, u1, v1);
3283    TextureVertex::setUV(v++, u2, v1);
3284    TextureVertex::setUV(v++, u1, v2);
3285    TextureVertex::setUV(v++, u2, v2);
3286}
3287
3288void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
3289    getAlphaAndModeDirect(paint, alpha,  mode);
3290    *alpha *= mSnapshot->alpha;
3291}
3292
3293}; // namespace uirenderer
3294}; // namespace android
3295