OpenGLRenderer.cpp revision cf28957c89127ccfc82d535903c776124665446a
156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi/*
256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi * Copyright (C) 2010 The Android Open Source Project
356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi *
456ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi * Licensed under the Apache License, Version 2.0 (the "License");
556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi * you may not use this file except in compliance with the License.
656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi * You may obtain a copy of the License at
756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi *
856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi *      http://www.apache.org/licenses/LICENSE-2.0
956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi *
1056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi * Unless required by applicable law or agreed to in writing, software
1156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi * distributed under the License is distributed on an "AS IS" BASIS,
1256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi * See the License for the specific language governing permissions and
1456ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi * limitations under the License.
1556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi */
1656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
1756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi#define LOG_TAG "OpenGLRenderer"
1856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
1956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi#include <stdlib.h>
20c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent#include <stdint.h>
21ad3183e2d4cecd02f6261270a7ea1c68be0efa0fFrançois Gaffie#include <sys/types.h>
22ad3183e2d4cecd02f6261270a7ea1c68be0efa0fFrançois Gaffie
2398cc191247388132b6fd8a4ecd07abd6e4c5a0edFrançois Gaffie#include <SkCanvas.h>
24ffbc80f5908eaf67a033c6e93a343c39dd6894ebEric Laurent#include <SkTypeface.h>
25ad3183e2d4cecd02f6261270a7ea1c68be0efa0fFrançois Gaffie
26ad3183e2d4cecd02f6261270a7ea1c68be0efa0fFrançois Gaffie#include <utils/Log.h>
2756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi#include <utils/StopWatch.h>
2853615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
2953615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie#include <ui/Rect.h>
3053615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
3153615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie#include "OpenGLRenderer.h"
3256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi#include "DisplayListRenderer.h"
3356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi#include "Vector.h"
34c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
35c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurentnamespace android {
36c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurentnamespace uirenderer {
37a13cde98a880341f0a56d91da6364b093fb5d24eGlenn Kasten
3856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi///////////////////////////////////////////////////////////////////////////////
3956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi// Defines
4056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi///////////////////////////////////////////////////////////////////////////////
4156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
4256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi#define RAD_TO_DEG (180.0f / 3.14159265f)
4356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi#define MIN_ANGLE 0.001f
4456ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
4556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi// TODO: This should be set in properties
4656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH)
4756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
4856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi///////////////////////////////////////////////////////////////////////////////
49c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent// Globals
50112b0af826aeca45855690b9c105b2cdf9938bbeFrançois Gaffie///////////////////////////////////////////////////////////////////////////////
51c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
52c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent/**
5356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi * Structure mapping Skia xfermodes to OpenGL blending factors.
5456ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi */
5556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivistruct Blender {
5656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    SkXfermode::Mode mode;
5753615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    GLenum src;
5853615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    GLenum dst;
59c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent}; // struct Blender
6053615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
6153615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie// In this array, the index of each Blender equals the value of the first
62322b4d25387a04c9afebe998326d005bbdf17edeEric Laurent// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
63322b4d25387a04c9afebe998326d005bbdf17edeEric Laurentstatic const Blender gBlends[] = {
64322b4d25387a04c9afebe998326d005bbdf17edeEric Laurent    { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
65322b4d25387a04c9afebe998326d005bbdf17edeEric Laurent    { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
66322b4d25387a04c9afebe998326d005bbdf17edeEric Laurent    { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
6756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
6856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
69c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
7056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
7156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
72c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
7356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
74c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
7556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
7656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi};
7756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
7856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi// This array contains the swapped version of each SkXfermode. For instance
7956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi// this array's SrcOver blending mode is actually DstOver. You can refer to
80c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent// createLayer() for more information on the purpose of this array.
81c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurentstatic const Blender gBlendsSwap[] = {
82c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
8356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kSrc_Mode,     GL_ZERO,                 GL_ONE },
84232f26f8b673973ffa463f80b08b731ffacc8785Eric Laurent    { SkXfermode::kDst_Mode,     GL_ONE,                  GL_ZERO },
8556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
8656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kDstOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
8756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kSrcIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
8856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kDstIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
8956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kSrcOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
9056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kDstOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
9156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
9256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kDstATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
9356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
9456ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi};
9556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
9656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivistatic const GLenum gTextureUnits[] = {
9756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    GL_TEXTURE0,
9856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    GL_TEXTURE1,
9956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    GL_TEXTURE2
10056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi};
10156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
10256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi///////////////////////////////////////////////////////////////////////////////
103ad3183e2d4cecd02f6261270a7ea1c68be0efa0fFrançois Gaffie// Constructors/destructor
104ad3183e2d4cecd02f6261270a7ea1c68be0efa0fFrançois Gaffie///////////////////////////////////////////////////////////////////////////////
10556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
10656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel TriviOpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
10756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mShader = NULL;
10856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mColorFilter = NULL;
10956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mHasShadow = false;
11056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
111ad3183e2d4cecd02f6261270a7ea1c68be0efa0fFrançois Gaffie    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
11256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
11356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mFirstSnapshot = new Snapshot;
11456ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi}
11556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
11656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel TriviOpenGLRenderer::~OpenGLRenderer() {
11756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    // The context has already been destroyed at this point, do not call
11856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    // GL APIs. All GL state should be kept in Caches.h
11953615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie}
12053615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
12156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi///////////////////////////////////////////////////////////////////////////////
12256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi// Setup
12356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi///////////////////////////////////////////////////////////////////////////////
12456ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
12556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivivoid OpenGLRenderer::setViewport(int width, int height) {
12656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    glViewport(0, 0, width, height);
12756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
12856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
12956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mWidth = width;
13056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mHeight = height;
13156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
13256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mFirstSnapshot->height = height;
13356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mFirstSnapshot->viewport.set(0, 0, width, height);
13456ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
13556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mDirtyClip = false;
13656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi}
137c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
138c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurentvoid OpenGLRenderer::prepare(bool opaque) {
139c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
140c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent}
141c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
142c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurentvoid OpenGLRenderer::prepareDirty(float left, float top, float right, float bottom, bool opaque) {
143c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    mCaches.clearGarbage();
144c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
145c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    mSnapshot = new Snapshot(mFirstSnapshot,
146c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
147c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    mSaveCount = 1;
148c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
149c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    glViewport(0, 0, mWidth, mHeight);
150c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
151c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    glDisable(GL_DITHER);
152c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
153c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    glEnable(GL_SCISSOR_TEST);
154c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    glScissor(left, mSnapshot->height - bottom, right - left, bottom - top);
155c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    mSnapshot->setClip(left, top, right, bottom);
156c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
157c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    if (!opaque) {
158c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
159c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        glClear(GL_COLOR_BUFFER_BIT);
16056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    }
16156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi}
16256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
16356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivivoid OpenGLRenderer::finish() {
16456ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi#if DEBUG_OPENGL
16556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    GLenum status = GL_NO_ERROR;
16656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    while ((status = glGetError()) != GL_NO_ERROR) {
16756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi        LOGD("GL error from OpenGLRenderer: 0x%x", status);
16856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi        switch (status) {
16956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi            case GL_OUT_OF_MEMORY:
17056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi                LOGE("  OpenGLRenderer is out of memory!");
17156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi                break;
17256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi        }
17356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    }
174322b4d25387a04c9afebe998326d005bbdf17edeEric Laurent#endif
17556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi#if DEBUG_MEMORY_USAGE
17656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mCaches.dumpMemoryUsage();
17756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi#else
17856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    if (mCaches.getDebugLevel() & kDebugMemory) {
17956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi        mCaches.dumpMemoryUsage();
18056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    }
181c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent#endif
18256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi}
183322b4d25387a04c9afebe998326d005bbdf17edeEric Laurent
18456ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivivoid OpenGLRenderer::interrupt() {
18556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    if (mCaches.currentProgram) {
18656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi        if (mCaches.currentProgram->isInUse()) {
18756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi            mCaches.currentProgram->remove();
18856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi            mCaches.currentProgram = NULL;
18956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi        }
19056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    }
19156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mCaches.unbindMeshBuffer();
192c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent}
19356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
19456ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivivoid OpenGLRenderer::resume() {
19556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    glViewport(0, 0, mSnapshot->viewport.getWidth(), mSnapshot->viewport.getHeight());
19656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
19756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    glEnable(GL_SCISSOR_TEST);
19856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    dirtyClip();
19956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
20056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    glDisable(GL_DITHER);
20156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
20256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo());
20356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
20456ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
20556ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    mCaches.blend = true;
20656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    glEnable(GL_BLEND);
20756ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
20856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    glBlendEquation(GL_FUNC_ADD);
20956ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi}
21056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi
21156ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivibool OpenGLRenderer::callDrawGLFunction(Functor *functor) {
21256ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    interrupt();
21356ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    if (mDirtyClip) {
214aa9811945f575614b3482d09e4d969792701cebbPaul McLean        setScissorFromClip();
215aa9811945f575614b3482d09e4d969792701cebbPaul McLean    }
216c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    status_t result = (*functor)();
217c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    resume();
218c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    return (result == 0) ? false : true;
219c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent}
220c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
221d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent///////////////////////////////////////////////////////////////////////////////
222d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent// State management
223c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent///////////////////////////////////////////////////////////////////////////////
224c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
225c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurentint OpenGLRenderer::getSaveCount() const {
226de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi    return mSaveCount;
227c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent}
228c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
229a8ecc2c72ca26389bd6b0162181d60aaeaca8149François Gaffieint OpenGLRenderer::save(int flags) {
230c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    return saveSnapshot(flags);
231c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent}
232c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
233c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurentvoid OpenGLRenderer::restore() {
234c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    if (mSaveCount > 1) {
235c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        restoreSnapshot();
236c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    }
237c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent}
238c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
239c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurentvoid OpenGLRenderer::restoreToCount(int saveCount) {
240c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    if (saveCount < 1) saveCount = 1;
241c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
242c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    while (mSaveCount > saveCount) {
243c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        restoreSnapshot();
244c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    }
245c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent}
246c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
247c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurentint OpenGLRenderer::saveSnapshot(int flags) {
248c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    mSnapshot = new Snapshot(mSnapshot, flags);
249c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    return mSaveCount++;
250c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent}
251c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
252c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurentbool OpenGLRenderer::restoreSnapshot() {
253c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
254c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
255c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
256c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
257c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    sp<Snapshot> current = mSnapshot;
258c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    sp<Snapshot> previous = mSnapshot->previous;
259c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
260c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    if (restoreOrtho) {
261c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        Rect& r = previous->viewport;
262c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        glViewport(r.left, r.top, r.right, r.bottom);
263c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        mOrthoMatrix.load(current->orthoMatrix);
264aa9811945f575614b3482d09e4d969792701cebbPaul McLean    }
265aa9811945f575614b3482d09e4d969792701cebbPaul McLean
266c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    mSaveCount--;
267c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    mSnapshot = previous;
268c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
269c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    if (restoreClip) {
270c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        dirtyClip();
271c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    }
272c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
273c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    if (restoreLayer) {
274c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        composeLayer(current, previous);
275c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    }
276c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
277c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    return restoreClip;
278c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent}
279c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
280c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent///////////////////////////////////////////////////////////////////////////////
281c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent// Layers
282c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent///////////////////////////////////////////////////////////////////////////////
283c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
284a8ecc2c72ca26389bd6b0162181d60aaeaca8149François Gaffieint OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
285c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        SkPaint* p, int flags) {
286c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    const GLuint previousFbo = mSnapshot->fbo;
287c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    const int count = saveSnapshot(flags);
288c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
289c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    if (!mSnapshot->isIgnored()) {
290c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        int alpha = 255;
291c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        SkXfermode::Mode mode;
292c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
293c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        if (p) {
294c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent            alpha = p->getAlpha();
295c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent            if (!mCaches.extensions.hasFramebufferFetch()) {
296c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent                const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
297c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent                if (!isMode) {
298c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent                    // Assume SRC_OVER
299c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent                    mode = SkXfermode::kSrcOver_Mode;
300c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent                }
301c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent            } else {
302c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent                mode = getXfermode(p->getXfermode());
303c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent            }
304c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        } else {
305c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent            mode = SkXfermode::kSrcOver_Mode;
306de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi        }
307de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi
308de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
309de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi    }
310de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi
311de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi    return count;
312de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi}
313de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi
314de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Triviint OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
315de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi        int alpha, int flags) {
316f613d42b12389335b2ecf06df18d0d095d6bfd44Jean-Michel Trivi    if (alpha >= 255 - ALPHA_THRESHOLD) {
317f613d42b12389335b2ecf06df18d0d095d6bfd44Jean-Michel Trivi        return saveLayer(left, top, right, bottom, NULL, flags);
3187638ca29e8400a19524adb982e9d22c02786de82Jean-Michel Trivi    } else {
319de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi        SkPaint paint;
320de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi        paint.setAlpha(alpha);
321de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi        return saveLayer(left, top, right, bottom, &paint, flags);
322de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi    }
323f613d42b12389335b2ecf06df18d0d095d6bfd44Jean-Michel Trivi}
324f613d42b12389335b2ecf06df18d0d095d6bfd44Jean-Michel Trivi
3257638ca29e8400a19524adb982e9d22c02786de82Jean-Michel Trivi/**
326de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi * Layers are viewed by Skia are slightly different than layers in image editing
327de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi * programs (for instance.) When a layer is created, previously created layers
328de80105c3f2db0eabd47640c49387ea3b44d4782Jean-Michel Trivi * and the frame buffer still receive every drawing command. For instance, if a
329c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * layer is created and a shape intersecting the bounds of the layers and the
330c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * framebuffer is draw, the shape will be drawn on both (unless the layer was
331c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
332c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *
333c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * A way to implement layers is to create an FBO for each layer, backed by an RGBA
334c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * texture. Unfortunately, this is inefficient as it requires every primitive to
335c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * be drawn n + 1 times, where n is the number of active layers. In practice this
336c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * means, for every primitive:
337c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *   - Switch active frame buffer
338c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *   - Change viewport, clip and projection matrix
339c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *   - Issue the drawing
340c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *
341c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * Switching rendering target n + 1 times per drawn primitive is extremely costly.
342c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * To avoid this, layers are implemented in a different way here, at least in the
343c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * general case. FBOs are used, as an optimization, when the "clip to layer" flag
344c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * is set. When this flag is set we can redirect all drawing operations into a
345c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * single FBO.
346c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *
347c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * This implementation relies on the frame buffer being at least RGBA 8888. When
348c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * a layer is created, only a texture is created, not an FBO. The content of the
349c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * frame buffer contained within the layer's bounds is copied into this texture
350c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
351c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * buffer and drawing continues as normal. This technique therefore treats the
352c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * frame buffer as a scratch buffer for the layers.
353c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *
354c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * To compose the layers back onto the frame buffer, each layer texture
355c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * (containing the original frame buffer data) is drawn as a simple quad over
356c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * the frame buffer. The trick is that the quad is set as the composition
357c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * destination in the blending equation, and the frame buffer becomes the source
358c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * of the composition.
359c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *
360c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * Drawing layers with an alpha value requires an extra step before composition.
361c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * An empty quad is drawn over the layer's region in the frame buffer. This quad
362c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
363c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * quad is used to multiply the colors in the frame buffer. This is achieved by
364c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * changing the GL blend functions for the GL_FUNC_ADD blend equation to
365c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * GL_ZERO, GL_SRC_ALPHA.
366c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *
367c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * Because glCopyTexImage2D() can be slow, an alternative implementation might
368c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * be use to draw a single clipped layer. The implementation described above
369c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * is correct in every case.
370c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *
371c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent * (1) The frame buffer is actually not cleared right away. To allow the GPU
372c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *     to potentially optimize series of calls to glCopyTexImage2D, the frame
373c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *     buffer is left untouched until the first drawing operation. Only when
374c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent *     something actually gets drawn are the layers regions cleared.
375c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent */
376c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurentbool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
377c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        float right, float bottom, int alpha, SkXfermode::Mode mode,
378c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        int flags, GLuint previousFbo) {
379ffbc80f5908eaf67a033c6e93a343c39dd6894ebEric Laurent    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
380c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
381c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
382ffbc80f5908eaf67a033c6e93a343c39dd6894ebEric Laurent    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
383c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
384ffbc80f5908eaf67a033c6e93a343c39dd6894ebEric Laurent    // Window coordinates of the layer
385c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    Rect bounds(left, top, right, bottom);
386c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    if (fboLayer) {
387c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        // Clear the previous layer regions before we change the viewport
388c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent        clearLayerRegions();
389d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    } else {
390d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        mSnapshot->transform->mapRect(bounds);
391d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
392d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        // Layers only make sense if they are in the framebuffer's bounds
393d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        bounds.intersect(*snapshot->clipRect);
394d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
395d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        // We cannot work with sub-pixels in this case
396d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        bounds.snapToPixelBoundaries();
397d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
398d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        // When the layer is not an FBO, we may use glCopyTexImage so we
399d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        // need to make sure the layer does not extend outside the bounds
400d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        // of the framebuffer
401d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        bounds.intersect(snapshot->previous->viewport);
402d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    }
403d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
404d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
405d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent            bounds.getHeight() > mCaches.maxTextureSize) {
406d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        snapshot->empty = fboLayer;
407d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    } else {
408d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        snapshot->invisible = snapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
409d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    }
410d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
411d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    // Bail out if we won't draw in this snapshot
412d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    if (snapshot->invisible || snapshot->empty) {
413d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        return false;
414d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    }
415d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
416d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    glActiveTexture(gTextureUnits[0]);
417d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
418d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    if (!layer) {
419d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        return false;
420d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    }
421d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
422d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    layer->mode = mode;
423d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    layer->alpha = alpha;
424d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    layer->layer.set(bounds);
425d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
426d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent            bounds.getWidth() / float(layer->width), 0.0f);
427d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    layer->colorFilter = mColorFilter;
428d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
429d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    // Save the layer in the snapshot
430d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    snapshot->flags |= Snapshot::kFlagIsLayer;
431d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    snapshot->layer = layer;
432d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
433d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    if (fboLayer) {
434d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        return createFboLayer(layer, bounds, snapshot, previousFbo);
435d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    } else {
436d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        // Copy the framebuffer into the layer
437d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        glBindTexture(GL_TEXTURE_2D, layer->texture);
438d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        if (!bounds.isEmpty()) {
439d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent            if (layer->empty) {
440d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent                glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left,
441d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent                        snapshot->height - bounds.bottom, layer->width, layer->height, 0);
442d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent                layer->empty = false;
443d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent            } else {
444d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent                glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
445c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent                        snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
446d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent            }
447c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent            // Enqueue the buffer coordinates to clear the corresponding region later
44853615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie            mLayers.push(new Rect(bounds));
44953615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        }
45053615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    }
451c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
45253615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    return true;
45353615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie}
45453615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
45553615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffiebool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
45653615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        GLuint previousFbo) {
45753615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    layer->fbo = mCaches.fboCache.get();
45853615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
459c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent#if RENDER_LAYERS_AS_REGIONS
46053615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    snapshot->region = &snapshot->layer->region;
46153615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    snapshot->flags |= Snapshot::kFlagFboTarget;
46253615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie#endif
46353615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
464c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    Rect clip(bounds);
46553615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    snapshot->transform->mapRect(clip);
46653615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    clip.intersect(*snapshot->clipRect);
46753615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    clip.snapToPixelBoundaries();
46853615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    clip.intersect(snapshot->previous->viewport);
46953615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
47053615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    mat4 inverse;
47153615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    inverse.loadInverse(*mSnapshot->transform);
47253615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
47353615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    inverse.mapRect(clip);
47453615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    clip.snapToPixelBoundaries();
47553615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    clip.intersect(bounds);
47653615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    clip.translate(-bounds.left, -bounds.top);
477c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
47853615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    snapshot->flags |= Snapshot::kFlagIsFboLayer;
47953615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    snapshot->fbo = layer->fbo;
480c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
48153615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
48253615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
48353615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    snapshot->height = bounds.getHeight();
48453615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    snapshot->flags |= Snapshot::kFlagDirtyOrtho;
48553615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    snapshot->orthoMatrix.load(mOrthoMatrix);
48653615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
48753615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    // Bind texture to FBO
488c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
48953615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    glBindTexture(GL_TEXTURE_2D, layer->texture);
49053615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
491c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    // Initialize the texture if needed
49253615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    if (layer->empty) {
49353615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        layer->empty = false;
49453615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
49553615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie                GL_RGBA, GL_UNSIGNED_BYTE, NULL);
49653615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    }
49753615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
49856ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
499c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent            layer->texture, 0);
50053615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
501c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent#if DEBUG_LAYERS_AS_REGIONS
50253615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
50353615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    if (status != GL_FRAMEBUFFER_COMPLETE) {
504322b4d25387a04c9afebe998326d005bbdf17edeEric Laurent        LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
50553615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
50653615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
50753615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        glDeleteTextures(1, &layer->texture);
50853615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        mCaches.fboCache.put(layer->fbo);
50953615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
51053615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        delete layer;
511c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
51253615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        return false;
51353615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    }
51453615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie#endif
51553615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
51653615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
51753615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    glScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
518c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
51953615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
52053615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    glClear(GL_COLOR_BUFFER_BIT);
52153615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
52253615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    dirtyClip();
52353615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
52453615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    // Change the ortho projection
52553615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
52653615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
527c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent
52853615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    return true;
529c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent}
530a8ecc2c72ca26389bd6b0162181d60aaeaca8149François Gaffie
53153615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie/**
53253615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie * Read the documentation of createLayer() before doing anything in this method.
53353615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie */
53453615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffievoid OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
535c75307b73d324d590d0dbc05b44bce9aa89b7145Eric Laurent    if (!current->layer) {
53653615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        LOGE("Attempting to compose a layer that does not exist");
53753615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        return;
53853615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    }
53953615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
54053615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
54153615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
54253615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    if (fboLayer) {
54353615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        // Unbind current FBO and restore previous one
54453615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
54553615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    }
54653615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
54753615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    Layer* layer = current->layer;
54853615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie    const Rect& rect = layer->layer;
54953615e29c99c5e9d2ca77aaefd7bf5c770513120François Gaffie
55056ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    if (!fboLayer && layer->alpha < 255) {
551d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
552d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
553d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        // Required below, composeLayerRect() will divide by 255
554d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        layer->alpha = 255;
555d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    }
556d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
557d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    mCaches.unbindMeshBuffer();
558d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
559d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    glActiveTexture(gTextureUnits[0]);
560d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
561d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    // When the layer is stored in an FBO, we can save a bit of fillrate by
562d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    // drawing only the dirty region
563d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    if (fboLayer) {
564d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
565d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        if (layer->colorFilter) {
566d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent            setupColorFilter(layer->colorFilter);
567d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        }
568d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        composeLayerRegion(layer, rect);
569d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        if (layer->colorFilter) {
570d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent            resetColorFilter();
571d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        }
572d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    } else {
573d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        if (!rect.isEmpty()) {
574d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent            dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
575d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent            composeLayerRect(layer, rect, true);
576d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        }
577d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    }
578d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
579d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    if (fboLayer) {
580d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        // Detach the texture from the FBO
581d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
582d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
583d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
584d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
585d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
586d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        mCaches.fboCache.put(current->fbo);
587d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    }
588d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
589d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    dirtyClip();
590d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent
591d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    // Failing to add the layer to the cache should happen only if the layer is too large
592d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent    if (!mCaches.layerCache.put(layer)) {
593d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        LAYER_LOGD("Deleting layer");
594d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        glDeleteTextures(1, &layer->texture);
595d60560af7cb559762593161c8202459cc01fb0f5Eric Laurent        delete layer;
59656ec4ffcbae8aeac6c5245fc7b825d02e2e6cefdJean-Michel Trivi    }
597}
598
599void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
600    const Rect& texCoords = layer->texCoords;
601    resetDrawTextureTexCoords(texCoords.left, texCoords.top, texCoords.right, texCoords.bottom);
602
603    drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
604            layer->alpha / 255.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
605            &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, swap, swap);
606
607    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
608}
609
610void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
611#if RENDER_LAYERS_AS_REGIONS
612    if (layer->region.isRect()) {
613        composeLayerRect(layer, rect);
614        layer->region.clear();
615        return;
616    }
617
618    if (!layer->region.isEmpty()) {
619        size_t count;
620        const android::Rect* rects = layer->region.getArray(&count);
621
622        const float alpha = layer->alpha / 255.0f;
623        const float texX = 1.0f / float(layer->width);
624        const float texY = 1.0f / float(layer->height);
625        const float height = rect.getHeight();
626
627        TextureVertex* mesh = mCaches.getRegionMesh();
628        GLsizei numQuads = 0;
629
630        setupDraw();
631        setupDrawWithTexture();
632        setupDrawColor(alpha, alpha, alpha, alpha);
633        setupDrawColorFilter();
634        setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
635        setupDrawProgram();
636        setupDrawDirtyRegionsDisabled();
637        setupDrawPureColorUniforms();
638        setupDrawColorFilterUniforms();
639        setupDrawTexture(layer->texture);
640        setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
641        setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0]);
642
643        for (size_t i = 0; i < count; i++) {
644            const android::Rect* r = &rects[i];
645
646            const float u1 = r->left * texX;
647            const float v1 = (height - r->top) * texY;
648            const float u2 = r->right * texX;
649            const float v2 = (height - r->bottom) * texY;
650
651            // TODO: Reject quads outside of the clip
652            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
653            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
654            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
655            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
656
657            numQuads++;
658
659            if (numQuads >= REGION_MESH_QUAD_COUNT) {
660                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
661                numQuads = 0;
662                mesh = mCaches.getRegionMesh();
663            }
664        }
665
666        if (numQuads > 0) {
667            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
668        }
669
670        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
671        finishDrawTexture();
672
673#if DEBUG_LAYERS_AS_REGIONS
674        drawRegionRects(layer->region);
675#endif
676
677        layer->region.clear();
678    }
679#else
680    composeLayerRect(layer, rect);
681#endif
682}
683
684void OpenGLRenderer::drawRegionRects(const Region& region) {
685#if DEBUG_LAYERS_AS_REGIONS
686    size_t count;
687    const android::Rect* rects = region.getArray(&count);
688
689    uint32_t colors[] = {
690            0x7fff0000, 0x7f00ff00,
691            0x7f0000ff, 0x7fff00ff,
692    };
693
694    int offset = 0;
695    int32_t top = rects[0].top;
696
697    for (size_t i = 0; i < count; i++) {
698        if (top != rects[i].top) {
699            offset ^= 0x2;
700            top = rects[i].top;
701        }
702
703        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
704        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
705                SkXfermode::kSrcOver_Mode);
706    }
707#endif
708}
709
710void OpenGLRenderer::dirtyLayer(const float left, const float top,
711        const float right, const float bottom, const mat4 transform) {
712#if RENDER_LAYERS_AS_REGIONS
713    if (hasLayer()) {
714        Rect bounds(left, top, right, bottom);
715        transform.mapRect(bounds);
716        dirtyLayerUnchecked(bounds, getRegion());
717    }
718#endif
719}
720
721void OpenGLRenderer::dirtyLayer(const float left, const float top,
722        const float right, const float bottom) {
723#if RENDER_LAYERS_AS_REGIONS
724    if (hasLayer()) {
725        Rect bounds(left, top, right, bottom);
726        dirtyLayerUnchecked(bounds, getRegion());
727    }
728#endif
729}
730
731void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
732#if RENDER_LAYERS_AS_REGIONS
733    if (bounds.intersect(*mSnapshot->clipRect)) {
734        bounds.snapToPixelBoundaries();
735        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
736        if (!dirty.isEmpty()) {
737            region->orSelf(dirty);
738        }
739    }
740#endif
741}
742
743void OpenGLRenderer::clearLayerRegions() {
744    if (mLayers.size() == 0 || mSnapshot->isIgnored()) return;
745
746    Rect clipRect(*mSnapshot->clipRect);
747    clipRect.snapToPixelBoundaries();
748
749    for (uint32_t i = 0; i < mLayers.size(); i++) {
750        Rect* bounds = mLayers.itemAt(i);
751        if (clipRect.intersects(*bounds)) {
752            // Clear the framebuffer where the layer will draw
753            glScissor(bounds->left, mSnapshot->height - bounds->bottom,
754                    bounds->getWidth(), bounds->getHeight());
755            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
756            glClear(GL_COLOR_BUFFER_BIT);
757
758            // Restore the clip
759            dirtyClip();
760        }
761
762        delete bounds;
763    }
764
765    mLayers.clear();
766}
767
768///////////////////////////////////////////////////////////////////////////////
769// Transforms
770///////////////////////////////////////////////////////////////////////////////
771
772void OpenGLRenderer::translate(float dx, float dy) {
773    mSnapshot->transform->translate(dx, dy, 0.0f);
774}
775
776void OpenGLRenderer::rotate(float degrees) {
777    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
778}
779
780void OpenGLRenderer::scale(float sx, float sy) {
781    mSnapshot->transform->scale(sx, sy, 1.0f);
782}
783
784void OpenGLRenderer::skew(float sx, float sy) {
785    mSnapshot->transform->skew(sx, sy);
786}
787
788void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
789    mSnapshot->transform->load(*matrix);
790}
791
792const float* OpenGLRenderer::getMatrix() const {
793    if (mSnapshot->fbo != 0) {
794        return &mSnapshot->transform->data[0];
795    }
796    return &mIdentity.data[0];
797}
798
799void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
800    mSnapshot->transform->copyTo(*matrix);
801}
802
803void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
804    SkMatrix transform;
805    mSnapshot->transform->copyTo(transform);
806    transform.preConcat(*matrix);
807    mSnapshot->transform->load(transform);
808}
809
810///////////////////////////////////////////////////////////////////////////////
811// Clipping
812///////////////////////////////////////////////////////////////////////////////
813
814void OpenGLRenderer::setScissorFromClip() {
815    Rect clip(*mSnapshot->clipRect);
816    clip.snapToPixelBoundaries();
817    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
818    mDirtyClip = false;
819}
820
821const Rect& OpenGLRenderer::getClipBounds() {
822    return mSnapshot->getLocalClip();
823}
824
825bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
826    if (mSnapshot->isIgnored()) {
827        return true;
828    }
829
830    Rect r(left, top, right, bottom);
831    mSnapshot->transform->mapRect(r);
832    r.snapToPixelBoundaries();
833
834    Rect clipRect(*mSnapshot->clipRect);
835    clipRect.snapToPixelBoundaries();
836
837    return !clipRect.intersects(r);
838}
839
840bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
841    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
842    if (clipped) {
843        dirtyClip();
844    }
845    return !mSnapshot->clipRect->isEmpty();
846}
847
848///////////////////////////////////////////////////////////////////////////////
849// Drawing commands
850///////////////////////////////////////////////////////////////////////////////
851
852void OpenGLRenderer::setupDraw() {
853    clearLayerRegions();
854    if (mDirtyClip) {
855        setScissorFromClip();
856    }
857    mDescription.reset();
858    mSetShaderColor = false;
859    mColorSet = false;
860    mColorA = mColorR = mColorG = mColorB = 0.0f;
861    mTextureUnit = 0;
862    mTrackDirtyRegions = true;
863    mTexCoordsSlot = -1;
864}
865
866void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
867    mDescription.hasTexture = true;
868    mDescription.hasAlpha8Texture = isAlpha8;
869}
870
871void OpenGLRenderer::setupDrawColor(int color) {
872    setupDrawColor(color, (color >> 24) & 0xFF);
873}
874
875void OpenGLRenderer::setupDrawColor(int color, int alpha) {
876    mColorA = alpha / 255.0f;
877    const float a = mColorA / 255.0f;
878    mColorR = a * ((color >> 16) & 0xFF);
879    mColorG = a * ((color >>  8) & 0xFF);
880    mColorB = a * ((color      ) & 0xFF);
881    mColorSet = true;
882    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
883}
884
885void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
886    mColorA = alpha / 255.0f;
887    const float a = mColorA / 255.0f;
888    mColorR = a * ((color >> 16) & 0xFF);
889    mColorG = a * ((color >>  8) & 0xFF);
890    mColorB = a * ((color      ) & 0xFF);
891    mColorSet = true;
892    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
893}
894
895void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
896    mColorA = a;
897    mColorR = r;
898    mColorG = g;
899    mColorB = b;
900    mColorSet = true;
901    mSetShaderColor = mDescription.setColor(r, g, b, a);
902}
903
904void OpenGLRenderer::setupDrawAlpha8Color(float r, float g, float b, float a) {
905    mColorA = a;
906    mColorR = r;
907    mColorG = g;
908    mColorB = b;
909    mColorSet = true;
910    mSetShaderColor = mDescription.setAlpha8Color(r, g, b, a);
911}
912
913void OpenGLRenderer::setupDrawShader() {
914    if (mShader) {
915        mShader->describe(mDescription, mCaches.extensions);
916    }
917}
918
919void OpenGLRenderer::setupDrawColorFilter() {
920    if (mColorFilter) {
921        mColorFilter->describe(mDescription, mCaches.extensions);
922    }
923}
924
925void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
926    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
927            mDescription, swapSrcDst);
928}
929
930void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
931    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
932            mDescription, swapSrcDst);
933}
934
935void OpenGLRenderer::setupDrawProgram() {
936    useProgram(mCaches.programCache.get(mDescription));
937}
938
939void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
940    mTrackDirtyRegions = false;
941}
942
943void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
944        bool ignoreTransform) {
945    mModelView.loadTranslate(left, top, 0.0f);
946    if (!ignoreTransform) {
947        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
948        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
949    } else {
950        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
951        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
952    }
953}
954
955void OpenGLRenderer::setupDrawModelViewIdentity() {
956    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform);
957}
958
959void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
960        bool ignoreTransform, bool ignoreModelView) {
961    if (!ignoreModelView) {
962        mModelView.loadTranslate(left, top, 0.0f);
963        mModelView.scale(right - left, bottom - top, 1.0f);
964    } else {
965        mModelView.loadIdentity();
966    }
967    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
968    if (!ignoreTransform) {
969        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
970        if (mTrackDirtyRegions && dirty) {
971            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
972        }
973    } else {
974        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
975        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
976    }
977}
978
979void OpenGLRenderer::setupDrawColorUniforms() {
980    if (mColorSet || (mShader && mSetShaderColor)) {
981        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
982    }
983}
984
985void OpenGLRenderer::setupDrawPureColorUniforms() {
986    if (mSetShaderColor) {
987        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
988    }
989}
990
991void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
992    if (mShader) {
993        if (ignoreTransform) {
994            mModelView.loadInverse(*mSnapshot->transform);
995        }
996        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
997    }
998}
999
1000void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1001    if (mShader) {
1002        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
1003    }
1004}
1005
1006void OpenGLRenderer::setupDrawColorFilterUniforms() {
1007    if (mColorFilter) {
1008        mColorFilter->setupProgram(mCaches.currentProgram);
1009    }
1010}
1011
1012void OpenGLRenderer::setupDrawSimpleMesh() {
1013    mCaches.bindMeshBuffer();
1014    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1015            gMeshStride, 0);
1016}
1017
1018void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1019    bindTexture(texture);
1020    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1021
1022    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1023    glEnableVertexAttribArray(mTexCoordsSlot);
1024}
1025
1026void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1027    if (!vertices) {
1028        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1029    } else {
1030        mCaches.unbindMeshBuffer();
1031    }
1032    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1033            gMeshStride, vertices);
1034    if (mTexCoordsSlot >= 0) {
1035        glVertexAttribPointer(mTexCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1036    }
1037}
1038
1039void OpenGLRenderer::finishDrawTexture() {
1040    glDisableVertexAttribArray(mTexCoordsSlot);
1041}
1042
1043///////////////////////////////////////////////////////////////////////////////
1044// Drawing
1045///////////////////////////////////////////////////////////////////////////////
1046
1047bool OpenGLRenderer::drawDisplayList(DisplayList* displayList, uint32_t level) {
1048    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1049    // will be performed by the display list itself
1050    if (displayList) {
1051        return displayList->replay(*this, level);
1052    }
1053    return false;
1054}
1055
1056void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1057    const float right = left + bitmap->width();
1058    const float bottom = top + bitmap->height();
1059
1060    if (quickReject(left, top, right, bottom)) {
1061        return;
1062    }
1063
1064    glActiveTexture(gTextureUnits[0]);
1065    Texture* texture = mCaches.textureCache.get(bitmap);
1066    if (!texture) return;
1067    const AutoTexture autoCleanup(texture);
1068
1069    drawTextureRect(left, top, right, bottom, texture, paint);
1070}
1071
1072void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1073    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1074    const mat4 transform(*matrix);
1075    transform.mapRect(r);
1076
1077    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1078        return;
1079    }
1080
1081    glActiveTexture(gTextureUnits[0]);
1082    Texture* texture = mCaches.textureCache.get(bitmap);
1083    if (!texture) return;
1084    const AutoTexture autoCleanup(texture);
1085
1086    // This could be done in a cheaper way, all we need is pass the matrix
1087    // to the vertex shader. The save/restore is a bit overkill.
1088    save(SkCanvas::kMatrix_SaveFlag);
1089    concatMatrix(matrix);
1090    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1091    restore();
1092}
1093
1094void OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1095        float* vertices, int* colors, SkPaint* paint) {
1096    // TODO: Do a quickReject
1097    if (!vertices || mSnapshot->isIgnored()) {
1098        return;
1099    }
1100
1101    glActiveTexture(gTextureUnits[0]);
1102    Texture* texture = mCaches.textureCache.get(bitmap);
1103    if (!texture) return;
1104    const AutoTexture autoCleanup(texture);
1105    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1106
1107    int alpha;
1108    SkXfermode::Mode mode;
1109    getAlphaAndMode(paint, &alpha, &mode);
1110
1111    const uint32_t count = meshWidth * meshHeight * 6;
1112
1113    float left = FLT_MAX;
1114    float top = FLT_MAX;
1115    float right = FLT_MIN;
1116    float bottom = FLT_MIN;
1117
1118#if RENDER_LAYERS_AS_REGIONS
1119    bool hasActiveLayer = hasLayer();
1120#else
1121    bool hasActiveLayer = false;
1122#endif
1123
1124    // TODO: Support the colors array
1125    TextureVertex mesh[count];
1126    TextureVertex* vertex = mesh;
1127    for (int32_t y = 0; y < meshHeight; y++) {
1128        for (int32_t x = 0; x < meshWidth; x++) {
1129            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1130
1131            float u1 = float(x) / meshWidth;
1132            float u2 = float(x + 1) / meshWidth;
1133            float v1 = float(y) / meshHeight;
1134            float v2 = float(y + 1) / meshHeight;
1135
1136            int ax = i + (meshWidth + 1) * 2;
1137            int ay = ax + 1;
1138            int bx = i;
1139            int by = bx + 1;
1140            int cx = i + 2;
1141            int cy = cx + 1;
1142            int dx = i + (meshWidth + 1) * 2 + 2;
1143            int dy = dx + 1;
1144
1145            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1146            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1147            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1148
1149            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1150            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1151            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1152
1153#if RENDER_LAYERS_AS_REGIONS
1154            if (hasActiveLayer) {
1155                // TODO: This could be optimized to avoid unnecessary ops
1156                left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1157                top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1158                right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1159                bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1160            }
1161#endif
1162        }
1163    }
1164
1165#if RENDER_LAYERS_AS_REGIONS
1166    if (hasActiveLayer) {
1167        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1168    }
1169#endif
1170
1171    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1172            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1173            GL_TRIANGLES, count, false, false, 0, false, false);
1174}
1175
1176void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1177         float srcLeft, float srcTop, float srcRight, float srcBottom,
1178         float dstLeft, float dstTop, float dstRight, float dstBottom,
1179         SkPaint* paint) {
1180    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1181        return;
1182    }
1183
1184    glActiveTexture(gTextureUnits[0]);
1185    Texture* texture = mCaches.textureCache.get(bitmap);
1186    if (!texture) return;
1187    const AutoTexture autoCleanup(texture);
1188    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1189
1190    const float width = texture->width;
1191    const float height = texture->height;
1192
1193    const float u1 = srcLeft / width;
1194    const float v1 = srcTop / height;
1195    const float u2 = srcRight / width;
1196    const float v2 = srcBottom / height;
1197
1198    mCaches.unbindMeshBuffer();
1199    resetDrawTextureTexCoords(u1, v1, u2, v2);
1200
1201    int alpha;
1202    SkXfermode::Mode mode;
1203    getAlphaAndMode(paint, &alpha, &mode);
1204
1205    if (mSnapshot->transform->isPureTranslate()) {
1206        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1207        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1208
1209        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
1210                texture->id, alpha / 255.0f, mode, texture->blend,
1211                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1212                GL_TRIANGLE_STRIP, gMeshCount, false, true);
1213    } else {
1214        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
1215                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1216                GL_TRIANGLE_STRIP, gMeshCount);
1217    }
1218
1219    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1220}
1221
1222void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1223        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1224        float left, float top, float right, float bottom, SkPaint* paint) {
1225    if (quickReject(left, top, right, bottom)) {
1226        return;
1227    }
1228
1229    glActiveTexture(gTextureUnits[0]);
1230    Texture* texture = mCaches.textureCache.get(bitmap);
1231    if (!texture) return;
1232    const AutoTexture autoCleanup(texture);
1233    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1234
1235    int alpha;
1236    SkXfermode::Mode mode;
1237    getAlphaAndMode(paint, &alpha, &mode);
1238
1239    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1240            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1241
1242    if (mesh && mesh->verticesCount > 0) {
1243        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1244#if RENDER_LAYERS_AS_REGIONS
1245        // Mark the current layer dirty where we are going to draw the patch
1246        if (hasLayer() && mesh->hasEmptyQuads) {
1247            const float offsetX = left + mSnapshot->transform->getTranslateX();
1248            const float offsetY = top + mSnapshot->transform->getTranslateY();
1249            const size_t count = mesh->quads.size();
1250            for (size_t i = 0; i < count; i++) {
1251                const Rect& bounds = mesh->quads.itemAt(i);
1252                if (pureTranslate) {
1253                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
1254                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
1255                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
1256                } else {
1257                    dirtyLayer(left + bounds.left, top + bounds.top,
1258                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
1259                }
1260            }
1261        }
1262#endif
1263
1264        if (pureTranslate) {
1265            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1266            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1267
1268            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1269                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1270                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1271                    true, !mesh->hasEmptyQuads);
1272        } else {
1273            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1274                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1275                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1276                    true, !mesh->hasEmptyQuads);
1277        }
1278    }
1279}
1280
1281void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
1282    if (mSnapshot->isIgnored()) return;
1283
1284    const bool isAA = paint->isAntiAlias();
1285    const float strokeWidth = paint->getStrokeWidth() * 0.5f;
1286    // A stroke width of 0 has a special meaningin Skia:
1287    // it draws an unscaled 1px wide line
1288    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
1289
1290    int alpha;
1291    SkXfermode::Mode mode;
1292    getAlphaAndMode(paint, &alpha, &mode);
1293
1294    int verticesCount = count >> 2;
1295    int generatedVerticesCount = 0;
1296    if (!isHairLine) {
1297        // TODO: AA needs more vertices
1298        verticesCount *= 6;
1299    } else {
1300        // TODO: AA will be different
1301        verticesCount *= 2;
1302    }
1303
1304    TextureVertex lines[verticesCount];
1305    TextureVertex* vertex = &lines[0];
1306
1307    setupDraw();
1308    setupDrawColor(paint->getColor(), alpha);
1309    setupDrawColorFilter();
1310    setupDrawShader();
1311    setupDrawBlending(mode);
1312    setupDrawProgram();
1313    setupDrawModelViewIdentity();
1314    setupDrawColorUniforms();
1315    setupDrawColorFilterUniforms();
1316    setupDrawShaderIdentityUniforms();
1317    setupDrawMesh(vertex);
1318
1319    if (!isHairLine) {
1320        // TODO: Handle the AA case
1321        for (int i = 0; i < count; i += 4) {
1322            // a = start point, b = end point
1323            vec2 a(points[i], points[i + 1]);
1324            vec2 b(points[i + 2], points[i + 3]);
1325
1326            // Bias to snap to the same pixels as Skia
1327            a += 0.375;
1328            b += 0.375;
1329
1330            // Find the normal to the line
1331            vec2 n = (b - a).copyNormalized() * strokeWidth;
1332            float x = n.x;
1333            n.x = -n.y;
1334            n.y = x;
1335
1336            // Four corners of the rectangle defining a thick line
1337            vec2 p1 = a - n;
1338            vec2 p2 = a + n;
1339            vec2 p3 = b + n;
1340            vec2 p4 = b - n;
1341
1342            const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
1343            const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
1344            const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
1345            const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
1346
1347            if (!quickReject(left, top, right, bottom)) {
1348                // Draw the line as 2 triangles, could be optimized
1349                // by using only 4 vertices and the correct indices
1350                // Also we should probably used non textured vertices
1351                // when line AA is disabled to save on bandwidth
1352                TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
1353                TextureVertex::set(vertex++, p2.x, p2.y, 0.0f, 0.0f);
1354                TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
1355                TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
1356                TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
1357                TextureVertex::set(vertex++, p4.x, p4.y, 0.0f, 0.0f);
1358
1359                generatedVerticesCount += 6;
1360
1361                dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1362            }
1363        }
1364
1365        if (generatedVerticesCount > 0) {
1366            // GL_LINE does not give the result we want to match Skia
1367            glDrawArrays(GL_TRIANGLES, 0, generatedVerticesCount);
1368        }
1369    } else {
1370        // TODO: Handle the AA case
1371        for (int i = 0; i < count; i += 4) {
1372            const float left = fmin(points[i], points[i + 1]);
1373            const float right = fmax(points[i], points[i + 1]);
1374            const float top = fmin(points[i + 2], points[i + 3]);
1375            const float bottom = fmax(points[i + 2], points[i + 3]);
1376
1377            if (!quickReject(left, top, right, bottom)) {
1378                TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
1379                TextureVertex::set(vertex++, points[i + 2], points[i + 3], 0.0f, 0.0f);
1380
1381                generatedVerticesCount += 2;
1382
1383                dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1384            }
1385        }
1386
1387        if (generatedVerticesCount > 0) {
1388            glLineWidth(1.0f);
1389            glDrawArrays(GL_LINES, 0, generatedVerticesCount);
1390        }
1391    }
1392}
1393
1394void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1395    // No need to check against the clip, we fill the clip region
1396    if (mSnapshot->isIgnored()) return;
1397
1398    Rect& clip(*mSnapshot->clipRect);
1399    clip.snapToPixelBoundaries();
1400
1401    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
1402}
1403
1404void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, SkPaint* paint) {
1405    if (!texture) return;
1406    const AutoTexture autoCleanup(texture);
1407
1408    const float x = left + texture->left - texture->offset;
1409    const float y = top + texture->top - texture->offset;
1410
1411    drawPathTexture(texture, x, y, paint);
1412}
1413
1414void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
1415        float rx, float ry, SkPaint* paint) {
1416    if (mSnapshot->isIgnored()) return;
1417
1418    glActiveTexture(gTextureUnits[0]);
1419    const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
1420            right - left, bottom - top, rx, ry, paint);
1421    drawShape(left, top, texture, paint);
1422}
1423
1424void OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* paint) {
1425    if (mSnapshot->isIgnored()) return;
1426
1427    glActiveTexture(gTextureUnits[0]);
1428    const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, paint);
1429    drawShape(x - radius, y - radius, texture, paint);
1430}
1431
1432void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, SkPaint* paint) {
1433    if (mSnapshot->isIgnored()) return;
1434
1435    glActiveTexture(gTextureUnits[0]);
1436    const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, paint);
1437    drawShape(left, top, texture, paint);
1438}
1439
1440void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
1441        float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) {
1442    if (mSnapshot->isIgnored()) return;
1443
1444    if (fabs(sweepAngle) >= 360.0f) {
1445        drawOval(left, top, right, bottom, paint);
1446        return;
1447    }
1448
1449    glActiveTexture(gTextureUnits[0]);
1450    const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
1451            startAngle, sweepAngle, useCenter, paint);
1452    drawShape(left, top, texture, paint);
1453}
1454
1455void OpenGLRenderer::drawRectAsShape(float left, float top, float right, float bottom,
1456        SkPaint* paint) {
1457    if (mSnapshot->isIgnored()) return;
1458
1459    glActiveTexture(gTextureUnits[0]);
1460    const PathTexture* texture = mCaches.rectShapeCache.getRect(right - left, bottom - top, paint);
1461    drawShape(left, top, texture, paint);
1462}
1463
1464void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
1465    if (p->getStyle() != SkPaint::kFill_Style) {
1466        drawRectAsShape(left, top, right, bottom, p);
1467        return;
1468    }
1469
1470    if (quickReject(left, top, right, bottom)) {
1471        return;
1472    }
1473
1474    SkXfermode::Mode mode;
1475    if (!mCaches.extensions.hasFramebufferFetch()) {
1476        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
1477        if (!isMode) {
1478            // Assume SRC_OVER
1479            mode = SkXfermode::kSrcOver_Mode;
1480        }
1481    } else {
1482        mode = getXfermode(p->getXfermode());
1483    }
1484
1485    int color = p->getColor();
1486    drawColorRect(left, top, right, bottom, color, mode);
1487}
1488
1489void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
1490        float x, float y, SkPaint* paint) {
1491    if (text == NULL || count == 0) {
1492        return;
1493    }
1494    if (mSnapshot->isIgnored()) return;
1495
1496    paint->setAntiAlias(true);
1497
1498    float length = -1.0f;
1499    switch (paint->getTextAlign()) {
1500        case SkPaint::kCenter_Align:
1501            length = paint->measureText(text, bytesCount);
1502            x -= length / 2.0f;
1503            break;
1504        case SkPaint::kRight_Align:
1505            length = paint->measureText(text, bytesCount);
1506            x -= length;
1507            break;
1508        default:
1509            break;
1510    }
1511
1512    // TODO: Handle paint->getTextScaleX()
1513    const float oldX = x;
1514    const float oldY = y;
1515    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1516    if (pureTranslate) {
1517        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
1518        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
1519    }
1520
1521    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
1522    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
1523            paint->getTextSize());
1524
1525    int alpha;
1526    SkXfermode::Mode mode;
1527    getAlphaAndMode(paint, &alpha, &mode);
1528
1529    if (mHasShadow) {
1530        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
1531        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
1532                count, mShadowRadius);
1533        const AutoTexture autoCleanup(shadow);
1534
1535        const float sx = x - shadow->left + mShadowDx;
1536        const float sy = y - shadow->top + mShadowDy;
1537
1538        const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
1539
1540        glActiveTexture(gTextureUnits[0]);
1541        setupDraw();
1542        setupDrawWithTexture(true);
1543        setupDrawAlpha8Color(mShadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
1544        setupDrawBlending(true, mode);
1545        setupDrawProgram();
1546        setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height, pureTranslate);
1547        setupDrawTexture(shadow->id);
1548        setupDrawPureColorUniforms();
1549        setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1550
1551        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1552        finishDrawTexture();
1553    }
1554
1555    if (paint->getAlpha() == 0 && paint->getXfermode() == NULL) {
1556        return;
1557    }
1558
1559    // Pick the appropriate texture filtering
1560    bool linearFilter = mSnapshot->transform->changesBounds();
1561    if (pureTranslate && !linearFilter) {
1562        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
1563    }
1564
1565    glActiveTexture(gTextureUnits[0]);
1566    setupDraw();
1567    setupDrawDirtyRegionsDisabled();
1568    setupDrawWithTexture(true);
1569    setupDrawAlpha8Color(paint->getColor(), alpha);
1570    setupDrawColorFilter();
1571    setupDrawShader();
1572    setupDrawBlending(true, mode);
1573    setupDrawProgram();
1574    setupDrawModelView(x, y, x, y, pureTranslate, true);
1575    setupDrawTexture(fontRenderer.getTexture(linearFilter));
1576    setupDrawPureColorUniforms();
1577    setupDrawColorFilterUniforms();
1578    setupDrawShaderUniforms(pureTranslate);
1579
1580    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
1581    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
1582
1583#if RENDER_LAYERS_AS_REGIONS
1584    bool hasActiveLayer = hasLayer();
1585#else
1586    bool hasActiveLayer = false;
1587#endif
1588    mCaches.unbindMeshBuffer();
1589
1590    // Tell font renderer the locations of position and texture coord
1591    // attributes so it can bind its data properly
1592    int positionSlot = mCaches.currentProgram->position;
1593    fontRenderer.setAttributeBindingSlots(positionSlot, mTexCoordsSlot);
1594    if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y,
1595            hasActiveLayer ? &bounds : NULL)) {
1596#if RENDER_LAYERS_AS_REGIONS
1597        if (hasActiveLayer) {
1598            if (!pureTranslate) {
1599                mSnapshot->transform->mapRect(bounds);
1600            }
1601            dirtyLayerUnchecked(bounds, getRegion());
1602        }
1603#endif
1604    }
1605
1606    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1607    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
1608
1609    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
1610}
1611
1612void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
1613    if (mSnapshot->isIgnored()) return;
1614
1615    glActiveTexture(gTextureUnits[0]);
1616
1617    const PathTexture* texture = mCaches.pathCache.get(path, paint);
1618    if (!texture) return;
1619    const AutoTexture autoCleanup(texture);
1620
1621    const float x = texture->left - texture->offset;
1622    const float y = texture->top - texture->offset;
1623
1624    drawPathTexture(texture, x, y, paint);
1625}
1626
1627void OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
1628    if (!layer || quickReject(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight())) {
1629        return;
1630    }
1631
1632    glActiveTexture(gTextureUnits[0]);
1633
1634    int alpha;
1635    SkXfermode::Mode mode;
1636    getAlphaAndMode(paint, &alpha, &mode);
1637
1638    layer->alpha = alpha;
1639    layer->mode = mode;
1640
1641#if RENDER_LAYERS_AS_REGIONS
1642    if (!layer->region.isEmpty()) {
1643        if (layer->region.isRect()) {
1644            const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
1645            composeLayerRect(layer, r);
1646        } else if (layer->mesh) {
1647            const float a = alpha / 255.0f;
1648            const Rect& rect = layer->layer;
1649
1650            setupDraw();
1651            setupDrawWithTexture();
1652            setupDrawColor(a, a, a, a);
1653            setupDrawColorFilter();
1654            setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
1655            setupDrawProgram();
1656            setupDrawPureColorUniforms();
1657            setupDrawColorFilterUniforms();
1658            setupDrawTexture(layer->texture);
1659            // TODO: The current layer, if any, will be dirtied with the bounding box
1660            //       of the layer we are drawing. Since the layer we are drawing has
1661            //       a mesh, we know the dirty region, we should use it instead
1662            setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
1663            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
1664
1665            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
1666                    GL_UNSIGNED_SHORT, layer->meshIndices);
1667
1668            finishDrawTexture();
1669
1670#if DEBUG_LAYERS_AS_REGIONS
1671            drawRegionRects(layer->region);
1672#endif
1673        }
1674    }
1675#else
1676    const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
1677    composeLayerRect(layer, r);
1678#endif
1679}
1680
1681///////////////////////////////////////////////////////////////////////////////
1682// Shaders
1683///////////////////////////////////////////////////////////////////////////////
1684
1685void OpenGLRenderer::resetShader() {
1686    mShader = NULL;
1687}
1688
1689void OpenGLRenderer::setupShader(SkiaShader* shader) {
1690    mShader = shader;
1691    if (mShader) {
1692        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
1693    }
1694}
1695
1696///////////////////////////////////////////////////////////////////////////////
1697// Color filters
1698///////////////////////////////////////////////////////////////////////////////
1699
1700void OpenGLRenderer::resetColorFilter() {
1701    mColorFilter = NULL;
1702}
1703
1704void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
1705    mColorFilter = filter;
1706}
1707
1708///////////////////////////////////////////////////////////////////////////////
1709// Drop shadow
1710///////////////////////////////////////////////////////////////////////////////
1711
1712void OpenGLRenderer::resetShadow() {
1713    mHasShadow = false;
1714}
1715
1716void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
1717    mHasShadow = true;
1718    mShadowRadius = radius;
1719    mShadowDx = dx;
1720    mShadowDy = dy;
1721    mShadowColor = color;
1722}
1723
1724///////////////////////////////////////////////////////////////////////////////
1725// Drawing implementation
1726///////////////////////////////////////////////////////////////////////////////
1727
1728void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
1729        float x, float y, SkPaint* paint) {
1730    if (quickReject(x, y, x + texture->width, y + texture->height)) {
1731        return;
1732    }
1733
1734    int alpha;
1735    SkXfermode::Mode mode;
1736    getAlphaAndMode(paint, &alpha, &mode);
1737
1738    setupDraw();
1739    setupDrawWithTexture(true);
1740    setupDrawAlpha8Color(paint->getColor(), alpha);
1741    setupDrawColorFilter();
1742    setupDrawShader();
1743    setupDrawBlending(true, mode);
1744    setupDrawProgram();
1745    setupDrawModelView(x, y, x + texture->width, y + texture->height);
1746    setupDrawTexture(texture->id);
1747    setupDrawPureColorUniforms();
1748    setupDrawColorFilterUniforms();
1749    setupDrawShaderUniforms();
1750    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1751
1752    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1753
1754    finishDrawTexture();
1755}
1756
1757// Same values used by Skia
1758#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
1759#define kStdUnderline_Offset    (1.0f / 9.0f)
1760#define kStdUnderline_Thickness (1.0f / 18.0f)
1761
1762void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
1763        float x, float y, SkPaint* paint) {
1764    // Handle underline and strike-through
1765    uint32_t flags = paint->getFlags();
1766    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
1767        float underlineWidth = length;
1768        // If length is > 0.0f, we already measured the text for the text alignment
1769        if (length <= 0.0f) {
1770            underlineWidth = paint->measureText(text, bytesCount);
1771        }
1772
1773        float offsetX = 0;
1774        switch (paint->getTextAlign()) {
1775            case SkPaint::kCenter_Align:
1776                offsetX = underlineWidth * 0.5f;
1777                break;
1778            case SkPaint::kRight_Align:
1779                offsetX = underlineWidth;
1780                break;
1781            default:
1782                break;
1783        }
1784
1785        if (underlineWidth > 0.0f) {
1786            const float textSize = paint->getTextSize();
1787            // TODO: Support stroke width < 1.0f when we have AA lines
1788            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
1789
1790            const float left = x - offsetX;
1791            float top = 0.0f;
1792
1793            int linesCount = 0;
1794            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
1795            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
1796
1797            const int pointsCount = 4 * linesCount;
1798            float points[pointsCount];
1799            int currentPoint = 0;
1800
1801            if (flags & SkPaint::kUnderlineText_Flag) {
1802                top = y + textSize * kStdUnderline_Offset;
1803                points[currentPoint++] = left;
1804                points[currentPoint++] = top;
1805                points[currentPoint++] = left + underlineWidth;
1806                points[currentPoint++] = top;
1807            }
1808
1809            if (flags & SkPaint::kStrikeThruText_Flag) {
1810                top = y + textSize * kStdStrikeThru_Offset;
1811                points[currentPoint++] = left;
1812                points[currentPoint++] = top;
1813                points[currentPoint++] = left + underlineWidth;
1814                points[currentPoint++] = top;
1815            }
1816
1817            SkPaint linesPaint(*paint);
1818            linesPaint.setStrokeWidth(strokeWidth);
1819
1820            drawLines(&points[0], pointsCount, &linesPaint);
1821        }
1822    }
1823}
1824
1825void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
1826        int color, SkXfermode::Mode mode, bool ignoreTransform) {
1827    // If a shader is set, preserve only the alpha
1828    if (mShader) {
1829        color |= 0x00ffffff;
1830    }
1831
1832    setupDraw();
1833    setupDrawColor(color);
1834    setupDrawShader();
1835    setupDrawColorFilter();
1836    setupDrawBlending(mode);
1837    setupDrawProgram();
1838    setupDrawModelView(left, top, right, bottom, ignoreTransform);
1839    setupDrawColorUniforms();
1840    setupDrawShaderUniforms(ignoreTransform);
1841    setupDrawColorFilterUniforms();
1842    setupDrawSimpleMesh();
1843
1844    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1845}
1846
1847void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1848        Texture* texture, SkPaint* paint) {
1849    int alpha;
1850    SkXfermode::Mode mode;
1851    getAlphaAndMode(paint, &alpha, &mode);
1852
1853    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1854
1855    if (mSnapshot->transform->isPureTranslate()) {
1856        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1857        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1858
1859        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
1860                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
1861                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
1862    } else {
1863        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
1864                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
1865                GL_TRIANGLE_STRIP, gMeshCount);
1866    }
1867}
1868
1869void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1870        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
1871    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
1872            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
1873}
1874
1875void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
1876        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
1877        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
1878        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
1879
1880    setupDraw();
1881    setupDrawWithTexture();
1882    setupDrawColor(alpha, alpha, alpha, alpha);
1883    setupDrawColorFilter();
1884    setupDrawBlending(blend, mode, swapSrcDst);
1885    setupDrawProgram();
1886    if (!dirty) {
1887        setupDrawDirtyRegionsDisabled();
1888    }
1889    if (!ignoreScale) {
1890        setupDrawModelView(left, top, right, bottom, ignoreTransform);
1891    } else {
1892        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
1893    }
1894    setupDrawPureColorUniforms();
1895    setupDrawColorFilterUniforms();
1896    setupDrawTexture(texture);
1897    setupDrawMesh(vertices, texCoords, vbo);
1898
1899    glDrawArrays(drawMode, 0, elementsCount);
1900
1901    finishDrawTexture();
1902}
1903
1904void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
1905        ProgramDescription& description, bool swapSrcDst) {
1906    blend = blend || mode != SkXfermode::kSrcOver_Mode;
1907    if (blend) {
1908        if (mode < SkXfermode::kPlus_Mode) {
1909            if (!mCaches.blend) {
1910                glEnable(GL_BLEND);
1911            }
1912
1913            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
1914            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
1915
1916            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
1917                glBlendFunc(sourceMode, destMode);
1918                mCaches.lastSrcMode = sourceMode;
1919                mCaches.lastDstMode = destMode;
1920            }
1921        } else {
1922            // These blend modes are not supported by OpenGL directly and have
1923            // to be implemented using shaders. Since the shader will perform
1924            // the blending, turn blending off here
1925            if (mCaches.extensions.hasFramebufferFetch()) {
1926                description.framebufferMode = mode;
1927                description.swapSrcDst = swapSrcDst;
1928            }
1929
1930            if (mCaches.blend) {
1931                glDisable(GL_BLEND);
1932            }
1933            blend = false;
1934        }
1935    } else if (mCaches.blend) {
1936        glDisable(GL_BLEND);
1937    }
1938    mCaches.blend = blend;
1939}
1940
1941bool OpenGLRenderer::useProgram(Program* program) {
1942    if (!program->isInUse()) {
1943        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1944        program->use();
1945        mCaches.currentProgram = program;
1946        return false;
1947    }
1948    return true;
1949}
1950
1951void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1952    TextureVertex* v = &mMeshVertices[0];
1953    TextureVertex::setUV(v++, u1, v1);
1954    TextureVertex::setUV(v++, u2, v1);
1955    TextureVertex::setUV(v++, u1, v2);
1956    TextureVertex::setUV(v++, u2, v2);
1957}
1958
1959void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1960    if (paint) {
1961        if (!mCaches.extensions.hasFramebufferFetch()) {
1962            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1963            if (!isMode) {
1964                // Assume SRC_OVER
1965                *mode = SkXfermode::kSrcOver_Mode;
1966            }
1967        } else {
1968            *mode = getXfermode(paint->getXfermode());
1969        }
1970
1971        // Skia draws using the color's alpha channel if < 255
1972        // Otherwise, it uses the paint's alpha
1973        int color = paint->getColor();
1974        *alpha = (color >> 24) & 0xFF;
1975        if (*alpha == 255) {
1976            *alpha = paint->getAlpha();
1977        }
1978    } else {
1979        *mode = SkXfermode::kSrcOver_Mode;
1980        *alpha = 255;
1981    }
1982}
1983
1984SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1985    if (mode == NULL) {
1986        return SkXfermode::kSrcOver_Mode;
1987    }
1988    return mode->fMode;
1989}
1990
1991void OpenGLRenderer::setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT) {
1992    bool bound = false;
1993    if (wrapS != texture->wrapS) {
1994        glBindTexture(GL_TEXTURE_2D, texture->id);
1995        bound = true;
1996        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1997        texture->wrapS = wrapS;
1998    }
1999    if (wrapT != texture->wrapT) {
2000        if (!bound) {
2001            glBindTexture(GL_TEXTURE_2D, texture->id);
2002        }
2003        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
2004        texture->wrapT = wrapT;
2005    }
2006}
2007
2008}; // namespace uirenderer
2009}; // namespace android
2010