OpenGLRenderer.cpp revision d6b2a00dd43257d1498b09175bff63663f6cb861
15e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette/*
25e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * Copyright (C) 2010 The Android Open Source Project
35e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette *
45e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * Licensed under the Apache License, Version 2.0 (the "License");
55e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * you may not use this file except in compliance with the License.
65e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * You may obtain a copy of the License at
75e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette *
85e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette *      http://www.apache.org/licenses/LICENSE-2.0
95e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette *
105e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * Unless required by applicable law or agreed to in writing, software
115e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * distributed under the License is distributed on an "AS IS" BASIS,
125e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
135e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * See the License for the specific language governing permissions and
145e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * limitations under the License.
155e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette */
165e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
175e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#define LOG_TAG "OpenGLRenderer"
185e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
195e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#include <stdlib.h>
205e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#include <stdint.h>
21f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette#include <sys/types.h>
22f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette
235e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#include <SkCanvas.h>
245e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#include <SkTypeface.h>
255e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
265e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#include <utils/Log.h>
277bc6a3f023ca3e1dde91fc97b6036dee3ba538a2ztenghui#include <utils/StopWatch.h>
285e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
295e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#include <private/hwui/DrawGlInfo.h>
305e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
315e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#include <ui/Rect.h>
325e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
335e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#include "OpenGLRenderer.h"
345e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#include "DisplayListRenderer.h"
355e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#include "Vector.h"
365e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
375e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverettenamespace android {
385e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverettenamespace uirenderer {
395e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
405e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette///////////////////////////////////////////////////////////////////////////////
415e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette// Defines
425e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette///////////////////////////////////////////////////////////////////////////////
435e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
445e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#define RAD_TO_DEG (180.0f / 3.14159265f)
455e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#define MIN_ANGLE 0.001f
465e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
475e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette// TODO: This should be set in properties
485e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH)
495e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
505e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette///////////////////////////////////////////////////////////////////////////////
515e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette// Globals
525e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette///////////////////////////////////////////////////////////////////////////////
535e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
545e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette/**
555e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * Structure mapping Skia xfermodes to OpenGL blending factors.
565e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette */
575e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverettestruct Blender {
585e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    SkXfermode::Mode mode;
595e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    GLenum src;
605e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    GLenum dst;
615e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette}; // struct Blender
625e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
635e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette// In this array, the index of each Blender equals the value of the first
647bc6a3f023ca3e1dde91fc97b6036dee3ba538a2ztenghui// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
657bc6a3f023ca3e1dde91fc97b6036dee3ba538a2ztenghuistatic const Blender gBlends[] = {
665e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
675e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
685e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
695e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
705e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
716e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
726e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
735e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
746e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
756e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
765e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
776e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
786e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette};
795e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
805e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette// This array contains the swapped version of each SkXfermode. For instance
815e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette// this array's SrcOver blending mode is actually DstOver. You can refer to
825e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette// createLayer() for more information on the purpose of this array.
835e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverettestatic const Blender gBlendsSwap[] = {
845e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    { SkXfermode::kClear_Mode,   GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
855e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    { SkXfermode::kSrc_Mode,     GL_ZERO,                 GL_ONE },
862356c5e69b0911e6334ebf6374217898371be5acAlan Viverette    { SkXfermode::kDst_Mode,     GL_ONE,                  GL_ZERO },
872356c5e69b0911e6334ebf6374217898371be5acAlan Viverette    { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
882356c5e69b0911e6334ebf6374217898371be5acAlan Viverette    { SkXfermode::kDstOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
89f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    { SkXfermode::kSrcIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
906e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    { SkXfermode::kDstIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
912356c5e69b0911e6334ebf6374217898371be5acAlan Viverette    { SkXfermode::kSrcOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
926e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    { SkXfermode::kDstOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
936e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
94b067405bf453289a6b6bfd34b06700f08be58c24Alan Viverette    { SkXfermode::kDstATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
95b067405bf453289a6b6bfd34b06700f08be58c24Alan Viverette    { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
962356c5e69b0911e6334ebf6374217898371be5acAlan Viverette};
972356c5e69b0911e6334ebf6374217898371be5acAlan Viverette
98f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverettestatic const GLenum gTextureUnits[] = {
992356c5e69b0911e6334ebf6374217898371be5acAlan Viverette    GL_TEXTURE0,
1002356c5e69b0911e6334ebf6374217898371be5acAlan Viverette    GL_TEXTURE1,
1012356c5e69b0911e6334ebf6374217898371be5acAlan Viverette    GL_TEXTURE2
1025e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette};
1035e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
1045e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette///////////////////////////////////////////////////////////////////////////////
1055e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette// Constructors/destructor
106f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette///////////////////////////////////////////////////////////////////////////////
1075e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
1085e92c95d847a68178cf6099c801f82dcb7e4fa47Alan ViveretteOpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
109f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    mShader = NULL;
110f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    mColorFilter = NULL;
111f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    mHasShadow = false;
1125e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
113f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
114f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette
115f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    mFirstSnapshot = new Snapshot;
1165e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette}
1175e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
1185e92c95d847a68178cf6099c801f82dcb7e4fa47Alan ViveretteOpenGLRenderer::~OpenGLRenderer() {
1195e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    // The context has already been destroyed at this point, do not call
1205e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    // GL APIs. All GL state should be kept in Caches.h
1215e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette}
1225e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
1236beeb75723cec42603b47664bce794a2b97d7bacChet Haase///////////////////////////////////////////////////////////////////////////////
1245e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette// Setup
1255e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette///////////////////////////////////////////////////////////////////////////////
1266beeb75723cec42603b47664bce794a2b97d7bacChet Haase
1276beeb75723cec42603b47664bce794a2b97d7bacChet Haasevoid OpenGLRenderer::setViewport(int width, int height) {
128f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    glViewport(0, 0, width, height);
129f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
130f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette
131f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    mWidth = width;
132f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    mHeight = height;
1335e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
1345e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    mFirstSnapshot->height = height;
1355e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    mFirstSnapshot->viewport.set(0, 0, width, height);
1365e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
1375e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    mDirtyClip = false;
1385e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette}
1395e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
1405e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverettevoid OpenGLRenderer::prepare(bool opaque) {
1415e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
142f81c6af10ef3041eeddb4a4560611a17dd3d399bAlan Viverette}
143f81c6af10ef3041eeddb4a4560611a17dd3d399bAlan Viverette
144f81c6af10ef3041eeddb4a4560611a17dd3d399bAlan Viverettevoid OpenGLRenderer::prepareDirty(float left, float top, float right, float bottom, bool opaque) {
1452d91f63ec20c4b06e87c80451a656462eceba17fAlan Viverette    mCaches.clearGarbage();
146f81c6af10ef3041eeddb4a4560611a17dd3d399bAlan Viverette
147f81c6af10ef3041eeddb4a4560611a17dd3d399bAlan Viverette    mSnapshot = new Snapshot(mFirstSnapshot,
1482d91f63ec20c4b06e87c80451a656462eceba17fAlan Viverette            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
1492d91f63ec20c4b06e87c80451a656462eceba17fAlan Viverette    mSnapshot->fbo = getTargetFbo();
1502d91f63ec20c4b06e87c80451a656462eceba17fAlan Viverette
1512d91f63ec20c4b06e87c80451a656462eceba17fAlan Viverette    mSaveCount = 1;
1522d91f63ec20c4b06e87c80451a656462eceba17fAlan Viverette
1532d91f63ec20c4b06e87c80451a656462eceba17fAlan Viverette    glViewport(0, 0, mWidth, mHeight);
1542d91f63ec20c4b06e87c80451a656462eceba17fAlan Viverette    glDisable(GL_DITHER);
1552d91f63ec20c4b06e87c80451a656462eceba17fAlan Viverette
1562d91f63ec20c4b06e87c80451a656462eceba17fAlan Viverette    glEnable(GL_SCISSOR_TEST);
1575e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    glScissor(left, mSnapshot->height - bottom, right - left, bottom - top);
1585e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    mSnapshot->setClip(left, top, right, bottom);
1595e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
160d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette    if (!opaque) {
1616e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
1626e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        glClear(GL_COLOR_BUFFER_BIT);
1636e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    }
164d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette}
1655e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
166d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverettevoid OpenGLRenderer::finish() {
1675e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#if DEBUG_OPENGL
1686e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    GLenum status = GL_NO_ERROR;
169d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette    while ((status = glGetError()) != GL_NO_ERROR) {
170d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette        LOGD("GL error from OpenGLRenderer: 0x%x", status);
1715e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        switch (status) {
1725e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            case GL_OUT_OF_MEMORY:
1735e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette                LOGE("  OpenGLRenderer is out of memory!");
174d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette                break;
175d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette        }
176d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette    }
1775e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#endif
1786e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette#if DEBUG_MEMORY_USAGE
179d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette    mCaches.dumpMemoryUsage();
180d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette#else
1815e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (mCaches.getDebugLevel() & kDebugMemory) {
1825e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        mCaches.dumpMemoryUsage();
183f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    }
184d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette#endif
1856e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette}
1866e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
187f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverettevoid OpenGLRenderer::interrupt() {
1885e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (mCaches.currentProgram) {
1895e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        if (mCaches.currentProgram->isInUse()) {
1905e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            mCaches.currentProgram->remove();
1915e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            mCaches.currentProgram = NULL;
1925e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        }
1935e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    }
1945e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    mCaches.unbindMeshBuffer();
1955e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette}
1965e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
197d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverettevoid OpenGLRenderer::resume() {
1985e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    glViewport(0, 0, mSnapshot->viewport.getWidth(), mSnapshot->viewport.getHeight());
1995e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
2005e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    glEnable(GL_SCISSOR_TEST);
2015e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    dirtyClip();
2025b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui
2035b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    glDisable(GL_DITHER);
204d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette
205d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette    glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo());
206d646fa2933ddcbfd4ed9c7686bf5e8253b4ba980Alan Viverette    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
2076e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2085e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    mCaches.blend = true;
209f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    glEnable(GL_BLEND);
2106e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
2115b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    glBlendEquation(GL_FUNC_ADD);
2125b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui}
2135b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui
2146e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverettebool OpenGLRenderer::callDrawGLFunction(Functor *functor, Rect& dirty) {
2156e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    interrupt();
2165b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    if (mDirtyClip) {
2175b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui        setScissorFromClip();
2185b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    }
219f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette
2206e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    Rect clip(*mSnapshot->clipRect);
221f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    clip.snapToPixelBoundaries();
222f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette
2235e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#if RENDER_LAYERS_AS_REGIONS
2245e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    // Since we don't know what the functor will draw, let's dirty
2255e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    // tne entire clip region
2266e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    if (hasLayer()) {
2276e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        dirtyLayerUnchecked(clip, getRegion());
2286e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    }
2296e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette#endif
2306e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
231f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    DrawGlInfo info;
232f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    info.clipLeft = clip.left;
233f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    info.clipTop = clip.top;
2346e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    info.clipRight = clip.right;
2356e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    info.clipBottom = clip.bottom;
2366e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    info.isLayer = hasLayer();
2376e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    getSnapshot()->transform->copyTo(&info.transform[0]);
2386e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2396e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    status_t result = (*functor)(0, &info);
2406e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2416e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    if (result != 0) {
2426e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
2436e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        dirty.unionWith(localDirty);
2446e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    }
2456e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2466e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    resume();
2476e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    return result != 0;
2486e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette}
2496e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2506e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette///////////////////////////////////////////////////////////////////////////////
2516e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette// State management
2526e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette///////////////////////////////////////////////////////////////////////////////
2536e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2546e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viveretteint OpenGLRenderer::getSaveCount() const {
2556e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    return mSaveCount;
2566e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette}
2576e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2586e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viveretteint OpenGLRenderer::save(int flags) {
2596e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    return saveSnapshot(flags);
2606e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette}
2616e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2626e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverettevoid OpenGLRenderer::restore() {
2635e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (mSaveCount > 1) {
2645e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        restoreSnapshot();
2656e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    }
2666e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette}
2676e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2686e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverettevoid OpenGLRenderer::restoreToCount(int saveCount) {
2695b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    if (saveCount < 1) saveCount = 1;
2705b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui
2715b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    while (mSaveCount > saveCount) {
2725b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui        restoreSnapshot();
2735b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    }
2745b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui}
2756e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2766e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viveretteint OpenGLRenderer::saveSnapshot(int flags) {
2776e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    mSnapshot = new Snapshot(mSnapshot, flags);
2786e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    return mSaveCount++;
2796e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette}
2806e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2816e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverettebool OpenGLRenderer::restoreSnapshot() {
2826e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
2835b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
2846e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
2856e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2866e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    sp<Snapshot> current = mSnapshot;
2876e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    sp<Snapshot> previous = mSnapshot->previous;
2886e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2895b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    if (restoreOrtho) {
2906e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        Rect& r = previous->viewport;
2916e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        glViewport(r.left, r.top, r.right, r.bottom);
2926e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        mOrthoMatrix.load(current->orthoMatrix);
2936e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    }
2946e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2956e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    mSaveCount--;
2966e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    mSnapshot = previous;
2976e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
2986e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    if (restoreClip) {
2996e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        dirtyClip();
3006e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    }
3016e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
3026e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    if (restoreLayer) {
3036e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        composeLayer(current, previous);
3046e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    }
3056e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
3066e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    return restoreClip;
3076e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette}
3086e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
3096e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette///////////////////////////////////////////////////////////////////////////////
3105b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui// Layers
3115b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui///////////////////////////////////////////////////////////////////////////////
3126e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
3136e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viveretteint OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
3145b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui        SkPaint* p, int flags) {
3155b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    const GLuint previousFbo = mSnapshot->fbo;
3165b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    const int count = saveSnapshot(flags);
3175b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui
3185b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    if (!mSnapshot->isIgnored()) {
3195b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui        int alpha = 255;
3205b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui        SkXfermode::Mode mode;
3216e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
3226e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        if (p) {
3235b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui            alpha = p->getAlpha();
3246e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette            if (!mCaches.extensions.hasFramebufferFetch()) {
3256e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette                const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
3266e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette                if (!isMode) {
3276e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette                    // Assume SRC_OVER
3285b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui                    mode = SkXfermode::kSrcOver_Mode;
3295b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui                }
3305b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui            } else {
3315b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui                mode = getXfermode(p->getXfermode());
3326e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette            }
3336e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        } else {
3346e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette            mode = SkXfermode::kSrcOver_Mode;
3356e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        }
3366e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
3377bc6a3f023ca3e1dde91fc97b6036dee3ba538a2ztenghui        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
3386e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    }
3396e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
3406e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    return count;
3416e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette}
3426e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
3436e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viveretteint OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
3446e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette        int alpha, int flags) {
3457bc6a3f023ca3e1dde91fc97b6036dee3ba538a2ztenghui    if (alpha >= 255 - ALPHA_THRESHOLD) {
3467bc6a3f023ca3e1dde91fc97b6036dee3ba538a2ztenghui        return saveLayer(left, top, right, bottom, NULL, flags);
3477bc6a3f023ca3e1dde91fc97b6036dee3ba538a2ztenghui    } else {
3485b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui        SkPaint paint;
3495b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui        paint.setAlpha(alpha);
3507bc6a3f023ca3e1dde91fc97b6036dee3ba538a2ztenghui        return saveLayer(left, top, right, bottom, &paint, flags);
3516e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette    }
3526e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette}
3536e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette
3546e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette/**
3556e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette * Layers are viewed by Skia are slightly different than layers in image editing
3566e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette * programs (for instance.) When a layer is created, previously created layers
3576e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette * and the frame buffer still receive every drawing command. For instance, if a
3586e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette * layer is created and a shape intersecting the bounds of the layers and the
3596e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette * framebuffer is draw, the shape will be drawn on both (unless the layer was
3605e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
3615e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette *
3625e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * A way to implement layers is to create an FBO for each layer, backed by an RGBA
3635e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * texture. Unfortunately, this is inefficient as it requires every primitive to
3646e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette * be drawn n + 1 times, where n is the number of active layers. In practice this
3656e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette * means, for every primitive:
3666e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette *   - Switch active frame buffer
3676e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette *   - Change viewport, clip and projection matrix
3686e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette *   - Issue the drawing
3696e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette *
3706e0a9fa6ed86e918bfed5310d2522b2c2a527ef0Alan Viverette * Switching rendering target n + 1 times per drawn primitive is extremely costly.
3715e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * To avoid this, layers are implemented in a different way here, at least in the
3725e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * general case. FBOs are used, as an optimization, when the "clip to layer" flag
3735e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * is set. When this flag is set we can redirect all drawing operations into a
3745e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * single FBO.
375f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette *
376f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette * This implementation relies on the frame buffer being at least RGBA 8888. When
3775e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * a layer is created, only a texture is created, not an FBO. The content of the
37839e33621a725bcdaa21a723866e53c6ea3356169Alan Viverette * frame buffer contained within the layer's bounds is copied into this texture
37939e33621a725bcdaa21a723866e53c6ea3356169Alan Viverette * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
3805e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * buffer and drawing continues as normal. This technique therefore treats the
381d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette * frame buffer as a scratch buffer for the layers.
382d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette *
383d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette * To compose the layers back onto the frame buffer, each layer texture
384d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette * (containing the original frame buffer data) is drawn as a simple quad over
3855e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * the frame buffer. The trick is that the quad is set as the composition
386d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette * destination in the blending equation, and the frame buffer becomes the source
387d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette * of the composition.
388d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette *
389d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette * Drawing layers with an alpha value requires an extra step before composition.
390d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette * An empty quad is drawn over the layer's region in the frame buffer. This quad
391d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
3925e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * quad is used to multiply the colors in the frame buffer. This is achieved by
393d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette * changing the GL blend functions for the GL_FUNC_ADD blend equation to
3947f4a63d1ebc13c6499a48331ecb78c4d27446dbcAlan Viverette * GL_ZERO, GL_SRC_ALPHA.
395d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette *
396d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette * Because glCopyTexImage2D() can be slow, an alternative implementation might
3975e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette * be use to draw a single clipped layer. The implementation described above
398d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette * is correct in every case.
399d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette *
400d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette * (1) The frame buffer is actually not cleared right away. To allow the GPU
4015e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette *     to potentially optimize series of calls to glCopyTexImage2D, the frame
4025e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette *     buffer is left untouched until the first drawing operation. Only when
403d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette *     something actually gets drawn are the layers regions cleared.
404d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette */
405d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverettebool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
406d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette        float right, float bottom, int alpha, SkXfermode::Mode mode,
407d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette        int flags, GLuint previousFbo) {
408d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
409d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
410d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette
411d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
412d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette
413d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    // Window coordinates of the layer
414d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    Rect bounds(left, top, right, bottom);
415d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    if (!fboLayer) {
416d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette        mSnapshot->transform->mapRect(bounds);
417d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette
418d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette        // Layers only make sense if they are in the framebuffer's bounds
419d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette        if (bounds.intersect(*snapshot->clipRect)) {
420d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette            // We cannot work with sub-pixels in this case
421d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette            bounds.snapToPixelBoundaries();
422d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette
423d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette            // When the layer is not an FBO, we may use glCopyTexImage so we
424d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette            // need to make sure the layer does not extend outside the bounds
425d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette            // of the framebuffer
426d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette            if (!bounds.intersect(snapshot->previous->viewport)) {
427d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette                bounds.setEmpty();
428d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette            }
429d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette        } else {
430d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette            bounds.setEmpty();
431d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette        }
432d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    }
433d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette
434d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
435d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette            bounds.getHeight() > mCaches.maxTextureSize) {
4365e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        snapshot->empty = fboLayer;
4375e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    } else {
4385e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        snapshot->invisible = snapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
4395e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    }
4405e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
4415e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    // Bail out if we won't draw in this snapshot
4425e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (snapshot->invisible || snapshot->empty) {
4435e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        return false;
4445e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    }
4455e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
4465e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    glActiveTexture(gTextureUnits[0]);
4475e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
4485e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (!layer) {
4495e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        return false;
4505e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    }
4515e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
4525e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    layer->mode = mode;
4535e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    layer->alpha = alpha;
4545e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    layer->layer.set(bounds);
4555e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
4565e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            bounds.getWidth() / float(layer->width), 0.0f);
4575e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    layer->colorFilter = mColorFilter;
4585e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
459f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    // Save the layer in the snapshot
460f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    snapshot->flags |= Snapshot::kFlagIsLayer;
4615e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    snapshot->layer = layer;
462d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette
463d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette    if (fboLayer) {
464d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette        return createFboLayer(layer, bounds, snapshot, previousFbo);
465d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette    } else {
466d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette        // Copy the framebuffer into the layer
467d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette        glBindTexture(GL_TEXTURE_2D, layer->texture);
468d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette        if (!bounds.isEmpty()) {
469d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette            if (layer->empty) {
470d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette                glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left,
471d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette                        snapshot->height - bounds.bottom, layer->width, layer->height, 0);
472d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette                layer->empty = false;
473d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette            } else {
474d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette                glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
4755e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette                        snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
476d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette            }
477d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette
478d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette            // Enqueue the buffer coordinates to clear the corresponding region later
479d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette            mLayers.push(new Rect(bounds));
4805e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        }
4815e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    }
4825e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
4835e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    return true;
4845e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette}
4855e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
486d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverettebool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
4875e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        GLuint previousFbo) {
4885e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    layer->fbo = mCaches.fboCache.get();
4896dbe51b50e82057af4d29882889444d22ac19c9cAlan Viverette
4905e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#if RENDER_LAYERS_AS_REGIONS
4915e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    snapshot->region = &snapshot->layer->region;
492f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    snapshot->flags |= Snapshot::kFlagFboTarget;
4935e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#endif
4945e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
495f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    Rect clip(bounds);
496f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette    snapshot->transform->mapRect(clip);
4975e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    clip.intersect(*snapshot->clipRect);
498d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette    clip.snapToPixelBoundaries();
499d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette    clip.intersect(snapshot->previous->viewport);
500d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette
501d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette    mat4 inverse;
502d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette    inverse.loadInverse(*mSnapshot->transform);
503d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette
504d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette    inverse.mapRect(clip);
5055e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    clip.snapToPixelBoundaries();
506d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette    clip.intersect(bounds);
507d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette    clip.translate(-bounds.left, -bounds.top);
508d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette
509d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette    snapshot->flags |= Snapshot::kFlagIsFboLayer;
510d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette    snapshot->fbo = layer->fbo;
511d6570d11e4d1e43c2cfe1d10e27a7786c4283169Alan Viverette    snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
5125e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
5135e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
5145e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    snapshot->height = bounds.getHeight();
5155e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    snapshot->flags |= Snapshot::kFlagDirtyOrtho;
5165e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    snapshot->orthoMatrix.load(mOrthoMatrix);
5175e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
5185e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    // Bind texture to FBO
5195e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
5205e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    glBindTexture(GL_TEXTURE_2D, layer->texture);
5216dbe51b50e82057af4d29882889444d22ac19c9cAlan Viverette
5225e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    // Initialize the texture if needed
5235e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (layer->empty) {
5245e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        layer->empty = false;
5255e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
5265e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette                GL_RGBA, GL_UNSIGNED_BYTE, NULL);
5275e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    }
5285e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
5295004032ebc2aee97c5884b7f91cc33d2f98ae8b5Alan Viverette    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
5308dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette            layer->texture, 0);
5315e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
5325e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#if DEBUG_LAYERS_AS_REGIONS
5335e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
5345e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (status != GL_FRAMEBUFFER_COMPLETE) {
5355e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
5365e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
5378dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
5388dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette        glDeleteTextures(1, &layer->texture);
5398dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette        mCaches.fboCache.put(layer->fbo);
5408dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette
5418dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette        delete layer;
542727cae197b123ef764a1f8fbe08a995b000d14c3Alan Viverette
543727cae197b123ef764a1f8fbe08a995b000d14c3Alan Viverette        return false;
544727cae197b123ef764a1f8fbe08a995b000d14c3Alan Viverette    }
545727cae197b123ef764a1f8fbe08a995b000d14c3Alan Viverette#endif
546727cae197b123ef764a1f8fbe08a995b000d14c3Alan Viverette
547727cae197b123ef764a1f8fbe08a995b000d14c3Alan Viverette    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
548727cae197b123ef764a1f8fbe08a995b000d14c3Alan Viverette    glScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
549727cae197b123ef764a1f8fbe08a995b000d14c3Alan Viverette            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
5505e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
5515b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    glClear(GL_COLOR_BUFFER_BIT);
5525b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui
5535b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    dirtyClip();
5545b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui
5555b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    // Change the ortho projection
5565b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
5575e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
558d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette
559d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    return true;
5608dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette}
5618dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette
5625e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette/**
563f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette * Read the documentation of createLayer() before doing anything in this method.
564f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette */
5655e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverettevoid OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
5665e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (!current->layer) {
5675e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        LOGE("Attempting to compose a layer that does not exist");
5688dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette        return;
569d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    }
5708dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette
5718dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
5725e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
5735e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (fboLayer) {
5745e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        // Unbind current FBO and restore previous one
5755e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
5765e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    }
5775e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
5788dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette    Layer* layer = current->layer;
5798dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette    const Rect& rect = layer->layer;
5808dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette
5818dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette    if (!fboLayer && layer->alpha < 255) {
5828dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
583f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
5845e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        // Required below, composeLayerRect() will divide by 255
5855e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        layer->alpha = 255;
5865b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    }
5875b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui
5885b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    mCaches.unbindMeshBuffer();
5895b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui
5905b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    glActiveTexture(gTextureUnits[0]);
5915e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
5925e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    // When the layer is stored in an FBO, we can save a bit of fillrate by
5935e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    // drawing only the dirty region
5945b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    if (fboLayer) {
5955e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
5965e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        if (layer->colorFilter) {
5975e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            setupColorFilter(layer->colorFilter);
5985e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        }
5995e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        composeLayerRegion(layer, rect);
600f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette        if (layer->colorFilter) {
6015e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            resetColorFilter();
6025e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        }
6035e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    } else {
6045e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        if (!rect.isEmpty()) {
6055e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
606f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette            composeLayerRect(layer, rect, true);
6075e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        }
6085e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    }
6095e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6105e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (fboLayer) {
6115e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        // Detach the texture from the FBO
6125e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
6135e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
6145e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
6155e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6165e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
6175e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        mCaches.fboCache.put(current->fbo);
6185e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    }
6195e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6205e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    dirtyClip();
6215e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6225e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    // Failing to add the layer to the cache should happen only if the layer is too large
6235e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (!mCaches.layerCache.put(layer)) {
6245e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        LAYER_LOGD("Deleting layer");
6255e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        glDeleteTextures(1, &layer->texture);
6265b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui        delete layer;
6275b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    }
6285b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui}
6295b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui
6305b84eace6cb79c42fe43480f08c68b7dea4e074aztenghuivoid OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
6315b84eace6cb79c42fe43480f08c68b7dea4e074aztenghui    float alpha = layer->alpha / 255.0f;
6325e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6335e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    setupDraw();
6345e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (layer->renderTarget == GL_TEXTURE_2D) {
635d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette        setupDrawWithTexture();
636d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    } else {
637d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette        setupDrawWithExternalTexture();
638d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    }
639d21fd9d1ccd2b525f9c004a6cd9ba19a645701abAlan Viverette    setupDrawTextureTransform();
6405e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    setupDrawColor(alpha, alpha, alpha, alpha);
6415e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    setupDrawColorFilter();
6425e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    setupDrawBlending(layer->blend, layer->mode);
6435e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    setupDrawProgram();
6445e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    setupDrawModelView(rect.left, rect.top, rect.right, rect.bottom);
6455e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    setupDrawPureColorUniforms();
6465e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    setupDrawColorFilterUniforms();
6475e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (layer->renderTarget == GL_TEXTURE_2D) {
6485e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawTexture(layer->texture);
6495e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    } else {
6505e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawExternalTexture(layer->texture);
6515e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    }
6525e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    setupDrawTextureTransformUniforms(layer->texTransform);
6535e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    setupDrawMesh(&mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
6545ed8f27858dbdf85203068eca46eef0a65f3344eAlan Viverette
6558dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
6565e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6575e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    finishDrawTexture();
6588dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette}
6598dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette
6608dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverettevoid OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
6615e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (!layer->isTextureLayer) {
6625e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        const Rect& texCoords = layer->texCoords;
663f456b1f078639a422f966ef2e9376cbd5ae3d274Alan Viverette        resetDrawTextureTexCoords(texCoords.left, texCoords.top,
6645e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette                texCoords.right, texCoords.bottom);
6655e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6668dcd533786df8d824f1e040230ee9e7e5b083998Alan Viverette        drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
6675e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette                layer->alpha / 255.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
6685e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette                &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, swap, swap);
6695e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6705e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
6715e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    } else {
6725e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
6735e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        drawTextureLayer(layer, rect);
6745e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
6755e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    }
6765e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette}
6775e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6785e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverettevoid OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
6795e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette#if RENDER_LAYERS_AS_REGIONS
6805e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (layer->region.isRect()) {
6815e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        layer->setRegionAsRect();
6825e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6835e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        composeLayerRect(layer, layer->regionRect);
6845e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6855e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        layer->region.clear();
6865e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        return;
6875e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    }
6885e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6895e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette    if (!layer->region.isEmpty()) {
6905e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        size_t count;
6915e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        const android::Rect* rects = layer->region.getArray(&count);
6925e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6935e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        const float alpha = layer->alpha / 255.0f;
6945e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        const float texX = 1.0f / float(layer->width);
6955e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        const float texY = 1.0f / float(layer->height);
6965e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        const float height = rect.getHeight();
6975e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
6985e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        TextureVertex* mesh = mCaches.getRegionMesh();
6995e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        GLsizei numQuads = 0;
7005e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
7015e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDraw();
7025e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawWithTexture();
7035e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawColor(alpha, alpha, alpha, alpha);
7045e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawColorFilter();
7055e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
7065e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawProgram();
7075e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawDirtyRegionsDisabled();
7085e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawPureColorUniforms();
7095e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawColorFilterUniforms();
7105e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawTexture(layer->texture);
7115e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
7125e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0]);
7135e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
7145e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette        for (size_t i = 0; i < count; i++) {
7155e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            const android::Rect* r = &rects[i];
7165e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
7175e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            const float u1 = r->left * texX;
7185e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            const float v1 = (height - r->top) * texY;
7195e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            const float u2 = r->right * texX;
7205e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            const float v2 = (height - r->bottom) * texY;
7215e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
7225e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            // TODO: Reject quads outside of the clip
7235e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
7245e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
7255e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
7265e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
7275e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
7285e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            numQuads++;
7295e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette
7305e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            if (numQuads >= REGION_MESH_QUAD_COUNT) {
7315e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
7325e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette                numQuads = 0;
7335e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette                mesh = mCaches.getRegionMesh();
7345e92c95d847a68178cf6099c801f82dcb7e4fa47Alan Viverette            }
735        }
736
737        if (numQuads > 0) {
738            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
739        }
740
741        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
742        finishDrawTexture();
743
744#if DEBUG_LAYERS_AS_REGIONS
745        drawRegionRects(layer->region);
746#endif
747
748        layer->region.clear();
749    }
750#else
751    composeLayerRect(layer, rect);
752#endif
753}
754
755void OpenGLRenderer::drawRegionRects(const Region& region) {
756#if DEBUG_LAYERS_AS_REGIONS
757    size_t count;
758    const android::Rect* rects = region.getArray(&count);
759
760    uint32_t colors[] = {
761            0x7fff0000, 0x7f00ff00,
762            0x7f0000ff, 0x7fff00ff,
763    };
764
765    int offset = 0;
766    int32_t top = rects[0].top;
767
768    for (size_t i = 0; i < count; i++) {
769        if (top != rects[i].top) {
770            offset ^= 0x2;
771            top = rects[i].top;
772        }
773
774        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
775        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
776                SkXfermode::kSrcOver_Mode);
777    }
778#endif
779}
780
781void OpenGLRenderer::dirtyLayer(const float left, const float top,
782        const float right, const float bottom, const mat4 transform) {
783#if RENDER_LAYERS_AS_REGIONS
784    if (hasLayer()) {
785        Rect bounds(left, top, right, bottom);
786        transform.mapRect(bounds);
787        dirtyLayerUnchecked(bounds, getRegion());
788    }
789#endif
790}
791
792void OpenGLRenderer::dirtyLayer(const float left, const float top,
793        const float right, const float bottom) {
794#if RENDER_LAYERS_AS_REGIONS
795    if (hasLayer()) {
796        Rect bounds(left, top, right, bottom);
797        dirtyLayerUnchecked(bounds, getRegion());
798    }
799#endif
800}
801
802void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
803#if RENDER_LAYERS_AS_REGIONS
804    if (bounds.intersect(*mSnapshot->clipRect)) {
805        bounds.snapToPixelBoundaries();
806        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
807        if (!dirty.isEmpty()) {
808            region->orSelf(dirty);
809        }
810    }
811#endif
812}
813
814void OpenGLRenderer::clearLayerRegions() {
815    const size_t count = mLayers.size();
816    if (count == 0) return;
817
818    if (!mSnapshot->isIgnored()) {
819        // Doing several glScissor/glClear here can negatively impact
820        // GPUs with a tiler architecture, instead we draw quads with
821        // the Clear blending mode
822
823        // The list contains bounds that have already been clipped
824        // against their initial clip rect, and the current clip
825        // is likely different so we need to disable clipping here
826        glDisable(GL_SCISSOR_TEST);
827
828        Vertex mesh[count * 6];
829        Vertex* vertex = mesh;
830
831        for (uint32_t i = 0; i < count; i++) {
832            Rect* bounds = mLayers.itemAt(i);
833
834            Vertex::set(vertex++, bounds->left, bounds->bottom);
835            Vertex::set(vertex++, bounds->left, bounds->top);
836            Vertex::set(vertex++, bounds->right, bounds->top);
837            Vertex::set(vertex++, bounds->left, bounds->bottom);
838            Vertex::set(vertex++, bounds->right, bounds->top);
839            Vertex::set(vertex++, bounds->right, bounds->bottom);
840
841            delete bounds;
842        }
843
844        setupDraw(false);
845        setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
846        setupDrawBlending(true, SkXfermode::kClear_Mode);
847        setupDrawProgram();
848        setupDrawPureColorUniforms();
849        setupDrawModelViewTranslate(0.0f, 0.0f, 0.0f, 0.0f, true);
850
851        mCaches.unbindMeshBuffer();
852        glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
853                gVertexStride, &mesh[0].position[0]);
854        glDrawArrays(GL_TRIANGLES, 0, count * 6);
855
856        glEnable(GL_SCISSOR_TEST);
857    } else {
858        for (uint32_t i = 0; i < count; i++) {
859            delete mLayers.itemAt(i);
860        }
861    }
862
863    mLayers.clear();
864}
865
866///////////////////////////////////////////////////////////////////////////////
867// Transforms
868///////////////////////////////////////////////////////////////////////////////
869
870void OpenGLRenderer::translate(float dx, float dy) {
871    mSnapshot->transform->translate(dx, dy, 0.0f);
872}
873
874void OpenGLRenderer::rotate(float degrees) {
875    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
876}
877
878void OpenGLRenderer::scale(float sx, float sy) {
879    mSnapshot->transform->scale(sx, sy, 1.0f);
880}
881
882void OpenGLRenderer::skew(float sx, float sy) {
883    mSnapshot->transform->skew(sx, sy);
884}
885
886void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
887    mSnapshot->transform->load(*matrix);
888}
889
890const float* OpenGLRenderer::getMatrix() const {
891    if (mSnapshot->fbo != 0) {
892        return &mSnapshot->transform->data[0];
893    }
894    return &mIdentity.data[0];
895}
896
897void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
898    mSnapshot->transform->copyTo(*matrix);
899}
900
901void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
902    SkMatrix transform;
903    mSnapshot->transform->copyTo(transform);
904    transform.preConcat(*matrix);
905    mSnapshot->transform->load(transform);
906}
907
908///////////////////////////////////////////////////////////////////////////////
909// Clipping
910///////////////////////////////////////////////////////////////////////////////
911
912void OpenGLRenderer::setScissorFromClip() {
913    Rect clip(*mSnapshot->clipRect);
914    clip.snapToPixelBoundaries();
915    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
916    mDirtyClip = false;
917}
918
919const Rect& OpenGLRenderer::getClipBounds() {
920    return mSnapshot->getLocalClip();
921}
922
923bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
924    if (mSnapshot->isIgnored()) {
925        return true;
926    }
927
928    Rect r(left, top, right, bottom);
929    mSnapshot->transform->mapRect(r);
930    r.snapToPixelBoundaries();
931
932    Rect clipRect(*mSnapshot->clipRect);
933    clipRect.snapToPixelBoundaries();
934
935    return !clipRect.intersects(r);
936}
937
938bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
939    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
940    if (clipped) {
941        dirtyClip();
942    }
943    return !mSnapshot->clipRect->isEmpty();
944}
945
946///////////////////////////////////////////////////////////////////////////////
947// Drawing commands
948///////////////////////////////////////////////////////////////////////////////
949
950void OpenGLRenderer::setupDraw(bool clear) {
951    if (clear) clearLayerRegions();
952    if (mDirtyClip) {
953        setScissorFromClip();
954    }
955    mDescription.reset();
956    mSetShaderColor = false;
957    mColorSet = false;
958    mColorA = mColorR = mColorG = mColorB = 0.0f;
959    mTextureUnit = 0;
960    mTrackDirtyRegions = true;
961    mTexCoordsSlot = -1;
962}
963
964void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
965    mDescription.hasTexture = true;
966    mDescription.hasAlpha8Texture = isAlpha8;
967}
968
969void OpenGLRenderer::setupDrawWithExternalTexture() {
970    mDescription.hasExternalTexture = true;
971}
972
973void OpenGLRenderer::setupDrawAALine() {
974    mDescription.isAA = true;
975}
976
977void OpenGLRenderer::setupDrawPoint(float pointSize) {
978    mDescription.isPoint = true;
979    mDescription.pointSize = pointSize;
980}
981
982void OpenGLRenderer::setupDrawColor(int color) {
983    setupDrawColor(color, (color >> 24) & 0xFF);
984}
985
986void OpenGLRenderer::setupDrawColor(int color, int alpha) {
987    mColorA = alpha / 255.0f;
988    // Second divide of a by 255 is an optimization, allowing us to simply multiply
989    // the rgb values by a instead of also dividing by 255
990    const float a = mColorA / 255.0f;
991    mColorR = a * ((color >> 16) & 0xFF);
992    mColorG = a * ((color >>  8) & 0xFF);
993    mColorB = a * ((color      ) & 0xFF);
994    mColorSet = true;
995    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
996}
997
998void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
999    mColorA = alpha / 255.0f;
1000    // Double-divide of a by 255 is an optimization, allowing us to simply multiply
1001    // the rgb values by a instead of also dividing by 255
1002    const float a = mColorA / 255.0f;
1003    mColorR = a * ((color >> 16) & 0xFF);
1004    mColorG = a * ((color >>  8) & 0xFF);
1005    mColorB = a * ((color      ) & 0xFF);
1006    mColorSet = true;
1007    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
1008}
1009
1010void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1011    mColorA = a;
1012    mColorR = r;
1013    mColorG = g;
1014    mColorB = b;
1015    mColorSet = true;
1016    mSetShaderColor = mDescription.setColor(r, g, b, a);
1017}
1018
1019void OpenGLRenderer::setupDrawAlpha8Color(float r, float g, float b, float a) {
1020    mColorA = a;
1021    mColorR = r;
1022    mColorG = g;
1023    mColorB = b;
1024    mColorSet = true;
1025    mSetShaderColor = mDescription.setAlpha8Color(r, g, b, a);
1026}
1027
1028void OpenGLRenderer::setupDrawShader() {
1029    if (mShader) {
1030        mShader->describe(mDescription, mCaches.extensions);
1031    }
1032}
1033
1034void OpenGLRenderer::setupDrawColorFilter() {
1035    if (mColorFilter) {
1036        mColorFilter->describe(mDescription, mCaches.extensions);
1037    }
1038}
1039
1040void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1041    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1042        mColorA = 1.0f;
1043        mColorR = mColorG = mColorB = 0.0f;
1044        mSetShaderColor = mDescription.modulate = true;
1045    }
1046}
1047
1048void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
1049    // When the blending mode is kClear_Mode, we need to use a modulate color
1050    // argb=1,0,0,0
1051    accountForClear(mode);
1052    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1053            mDescription, swapSrcDst);
1054}
1055
1056void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
1057    // When the blending mode is kClear_Mode, we need to use a modulate color
1058    // argb=1,0,0,0
1059    accountForClear(mode);
1060    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1061            mDescription, swapSrcDst);
1062}
1063
1064void OpenGLRenderer::setupDrawProgram() {
1065    useProgram(mCaches.programCache.get(mDescription));
1066}
1067
1068void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1069    mTrackDirtyRegions = false;
1070}
1071
1072void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
1073        bool ignoreTransform) {
1074    mModelView.loadTranslate(left, top, 0.0f);
1075    if (!ignoreTransform) {
1076        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1077        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1078    } else {
1079        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1080        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
1081    }
1082}
1083
1084void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) {
1085    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform, offset);
1086}
1087
1088void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
1089        bool ignoreTransform, bool ignoreModelView) {
1090    if (!ignoreModelView) {
1091        mModelView.loadTranslate(left, top, 0.0f);
1092        mModelView.scale(right - left, bottom - top, 1.0f);
1093    } else {
1094        mModelView.loadIdentity();
1095    }
1096    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1097    if (!ignoreTransform) {
1098        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1099        if (mTrackDirtyRegions && dirty) {
1100            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1101        }
1102    } else {
1103        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1104        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
1105    }
1106}
1107
1108void OpenGLRenderer::setupDrawPointUniforms() {
1109    int slot = mCaches.currentProgram->getUniform("pointSize");
1110    glUniform1f(slot, mDescription.pointSize);
1111}
1112
1113void OpenGLRenderer::setupDrawColorUniforms() {
1114    if (mColorSet || (mShader && mSetShaderColor)) {
1115        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1116    }
1117}
1118
1119void OpenGLRenderer::setupDrawPureColorUniforms() {
1120    if (mSetShaderColor) {
1121        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1122    }
1123}
1124
1125void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1126    if (mShader) {
1127        if (ignoreTransform) {
1128            mModelView.loadInverse(*mSnapshot->transform);
1129        }
1130        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
1131    }
1132}
1133
1134void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1135    if (mShader) {
1136        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
1137    }
1138}
1139
1140void OpenGLRenderer::setupDrawColorFilterUniforms() {
1141    if (mColorFilter) {
1142        mColorFilter->setupProgram(mCaches.currentProgram);
1143    }
1144}
1145
1146void OpenGLRenderer::setupDrawSimpleMesh() {
1147    mCaches.bindMeshBuffer();
1148    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1149            gMeshStride, 0);
1150}
1151
1152void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1153    bindTexture(texture);
1154    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1155
1156    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1157    glEnableVertexAttribArray(mTexCoordsSlot);
1158}
1159
1160void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1161    bindExternalTexture(texture);
1162    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1163
1164    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1165    glEnableVertexAttribArray(mTexCoordsSlot);
1166}
1167
1168void OpenGLRenderer::setupDrawTextureTransform() {
1169    mDescription.hasTextureTransform = true;
1170}
1171
1172void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1173    glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1174            GL_FALSE, &transform.data[0]);
1175}
1176
1177void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1178    if (!vertices) {
1179        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1180    } else {
1181        mCaches.unbindMeshBuffer();
1182    }
1183    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1184            gMeshStride, vertices);
1185    if (mTexCoordsSlot >= 0) {
1186        glVertexAttribPointer(mTexCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1187    }
1188}
1189
1190void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) {
1191    mCaches.unbindMeshBuffer();
1192    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1193            gVertexStride, vertices);
1194}
1195
1196/**
1197 * Sets up the shader to draw an AA line. We draw AA lines with quads, where there is an
1198 * outer boundary that fades out to 0. The variables set in the shader define the proportion of
1199 * the width and length of the primitive occupied by the AA region. The vtxWidth and vtxLength
1200 * attributes (one per vertex) are values from zero to one that tells the fragment
1201 * shader where the fragment is in relation to the line width/length overall; these values are
1202 * then used to compute the proper color, based on whether the fragment lies in the fading AA
1203 * region of the line.
1204 * Note that we only pass down the width values in this setup function. The length coordinates
1205 * are set up for each individual segment.
1206 */
1207void OpenGLRenderer::setupDrawAALine(GLvoid* vertices, GLvoid* widthCoords,
1208        GLvoid* lengthCoords, float boundaryWidthProportion) {
1209    mCaches.unbindMeshBuffer();
1210    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1211            gAAVertexStride, vertices);
1212    int widthSlot = mCaches.currentProgram->getAttrib("vtxWidth");
1213    glEnableVertexAttribArray(widthSlot);
1214    glVertexAttribPointer(widthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, widthCoords);
1215    int lengthSlot = mCaches.currentProgram->getAttrib("vtxLength");
1216    glEnableVertexAttribArray(lengthSlot);
1217    glVertexAttribPointer(lengthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, lengthCoords);
1218    int boundaryWidthSlot = mCaches.currentProgram->getUniform("boundaryWidth");
1219    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1220    // Setting the inverse value saves computations per-fragment in the shader
1221    int inverseBoundaryWidthSlot = mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1222    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion));
1223}
1224
1225void OpenGLRenderer::finishDrawTexture() {
1226    glDisableVertexAttribArray(mTexCoordsSlot);
1227}
1228
1229///////////////////////////////////////////////////////////////////////////////
1230// Drawing
1231///////////////////////////////////////////////////////////////////////////////
1232
1233bool OpenGLRenderer::drawDisplayList(DisplayList* displayList, uint32_t width, uint32_t height,
1234        Rect& dirty, uint32_t level) {
1235    if (quickReject(0.0f, 0.0f, width, height)) {
1236        return false;
1237    }
1238
1239    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1240    // will be performed by the display list itself
1241    if (displayList) {
1242        return displayList->replay(*this, dirty, level);
1243    }
1244
1245    return false;
1246}
1247
1248void OpenGLRenderer::outputDisplayList(DisplayList* displayList, uint32_t level) {
1249    if (displayList) {
1250        displayList->output(*this, level);
1251    }
1252}
1253
1254void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
1255    int alpha;
1256    SkXfermode::Mode mode;
1257    getAlphaAndMode(paint, &alpha, &mode);
1258
1259    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1260
1261    float x = left;
1262    float y = top;
1263
1264    bool ignoreTransform = false;
1265    if (mSnapshot->transform->isPureTranslate()) {
1266        x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1267        y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1268        ignoreTransform = true;
1269    }
1270
1271    setupDraw();
1272    setupDrawWithTexture(true);
1273    if (paint) {
1274        setupDrawAlpha8Color(paint->getColor(), alpha);
1275    }
1276    setupDrawColorFilter();
1277    setupDrawShader();
1278    setupDrawBlending(true, mode);
1279    setupDrawProgram();
1280    setupDrawModelView(x, y, x + texture->width, y + texture->height, ignoreTransform);
1281    setupDrawTexture(texture->id);
1282    setupDrawPureColorUniforms();
1283    setupDrawColorFilterUniforms();
1284    setupDrawShaderUniforms();
1285    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1286
1287    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1288
1289    finishDrawTexture();
1290}
1291
1292void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1293    const float right = left + bitmap->width();
1294    const float bottom = top + bitmap->height();
1295
1296    if (quickReject(left, top, right, bottom)) {
1297        return;
1298    }
1299
1300    glActiveTexture(gTextureUnits[0]);
1301    Texture* texture = mCaches.textureCache.get(bitmap);
1302    if (!texture) return;
1303    const AutoTexture autoCleanup(texture);
1304
1305    if (bitmap->getConfig() == SkBitmap::kA8_Config) {
1306        drawAlphaBitmap(texture, left, top, paint);
1307    } else {
1308        drawTextureRect(left, top, right, bottom, texture, paint);
1309    }
1310}
1311
1312void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1313    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1314    const mat4 transform(*matrix);
1315    transform.mapRect(r);
1316
1317    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1318        return;
1319    }
1320
1321    glActiveTexture(gTextureUnits[0]);
1322    Texture* texture = mCaches.textureCache.get(bitmap);
1323    if (!texture) return;
1324    const AutoTexture autoCleanup(texture);
1325
1326    // This could be done in a cheaper way, all we need is pass the matrix
1327    // to the vertex shader. The save/restore is a bit overkill.
1328    save(SkCanvas::kMatrix_SaveFlag);
1329    concatMatrix(matrix);
1330    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1331    restore();
1332}
1333
1334void OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1335        float* vertices, int* colors, SkPaint* paint) {
1336    // TODO: Do a quickReject
1337    if (!vertices || mSnapshot->isIgnored()) {
1338        return;
1339    }
1340
1341    glActiveTexture(gTextureUnits[0]);
1342    Texture* texture = mCaches.textureCache.get(bitmap);
1343    if (!texture) return;
1344    const AutoTexture autoCleanup(texture);
1345    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1346
1347    int alpha;
1348    SkXfermode::Mode mode;
1349    getAlphaAndMode(paint, &alpha, &mode);
1350
1351    const uint32_t count = meshWidth * meshHeight * 6;
1352
1353    float left = FLT_MAX;
1354    float top = FLT_MAX;
1355    float right = FLT_MIN;
1356    float bottom = FLT_MIN;
1357
1358#if RENDER_LAYERS_AS_REGIONS
1359    bool hasActiveLayer = hasLayer();
1360#else
1361    bool hasActiveLayer = false;
1362#endif
1363
1364    // TODO: Support the colors array
1365    TextureVertex mesh[count];
1366    TextureVertex* vertex = mesh;
1367    for (int32_t y = 0; y < meshHeight; y++) {
1368        for (int32_t x = 0; x < meshWidth; x++) {
1369            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1370
1371            float u1 = float(x) / meshWidth;
1372            float u2 = float(x + 1) / meshWidth;
1373            float v1 = float(y) / meshHeight;
1374            float v2 = float(y + 1) / meshHeight;
1375
1376            int ax = i + (meshWidth + 1) * 2;
1377            int ay = ax + 1;
1378            int bx = i;
1379            int by = bx + 1;
1380            int cx = i + 2;
1381            int cy = cx + 1;
1382            int dx = i + (meshWidth + 1) * 2 + 2;
1383            int dy = dx + 1;
1384
1385            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1386            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1387            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1388
1389            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1390            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1391            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1392
1393#if RENDER_LAYERS_AS_REGIONS
1394            if (hasActiveLayer) {
1395                // TODO: This could be optimized to avoid unnecessary ops
1396                left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1397                top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1398                right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1399                bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1400            }
1401#endif
1402        }
1403    }
1404
1405#if RENDER_LAYERS_AS_REGIONS
1406    if (hasActiveLayer) {
1407        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1408    }
1409#endif
1410
1411    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1412            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1413            GL_TRIANGLES, count, false, false, 0, false, false);
1414}
1415
1416void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1417         float srcLeft, float srcTop, float srcRight, float srcBottom,
1418         float dstLeft, float dstTop, float dstRight, float dstBottom,
1419         SkPaint* paint) {
1420    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1421        return;
1422    }
1423
1424    glActiveTexture(gTextureUnits[0]);
1425    Texture* texture = mCaches.textureCache.get(bitmap);
1426    if (!texture) return;
1427    const AutoTexture autoCleanup(texture);
1428    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1429
1430    const float width = texture->width;
1431    const float height = texture->height;
1432
1433    const float u1 = (srcLeft + 0.5f) / width;
1434    const float v1 = (srcTop + 0.5f)  / height;
1435    const float u2 = (srcRight - 0.5f) / width;
1436    const float v2 = (srcBottom - 0.5f) / height;
1437
1438    mCaches.unbindMeshBuffer();
1439    resetDrawTextureTexCoords(u1, v1, u2, v2);
1440
1441    int alpha;
1442    SkXfermode::Mode mode;
1443    getAlphaAndMode(paint, &alpha, &mode);
1444
1445    if (mSnapshot->transform->isPureTranslate()) {
1446        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1447        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1448
1449        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
1450                texture->id, alpha / 255.0f, mode, texture->blend,
1451                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1452                GL_TRIANGLE_STRIP, gMeshCount, false, true);
1453    } else {
1454        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
1455                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1456                GL_TRIANGLE_STRIP, gMeshCount);
1457    }
1458
1459    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1460}
1461
1462void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1463        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1464        float left, float top, float right, float bottom, SkPaint* paint) {
1465    if (quickReject(left, top, right, bottom)) {
1466        return;
1467    }
1468
1469    glActiveTexture(gTextureUnits[0]);
1470    Texture* texture = mCaches.textureCache.get(bitmap);
1471    if (!texture) return;
1472    const AutoTexture autoCleanup(texture);
1473    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1474
1475    int alpha;
1476    SkXfermode::Mode mode;
1477    getAlphaAndMode(paint, &alpha, &mode);
1478
1479    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1480            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1481
1482    if (mesh && mesh->verticesCount > 0) {
1483        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1484#if RENDER_LAYERS_AS_REGIONS
1485        // Mark the current layer dirty where we are going to draw the patch
1486        if (hasLayer() && mesh->hasEmptyQuads) {
1487            const float offsetX = left + mSnapshot->transform->getTranslateX();
1488            const float offsetY = top + mSnapshot->transform->getTranslateY();
1489            const size_t count = mesh->quads.size();
1490            for (size_t i = 0; i < count; i++) {
1491                const Rect& bounds = mesh->quads.itemAt(i);
1492                if (pureTranslate) {
1493                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
1494                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
1495                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
1496                } else {
1497                    dirtyLayer(left + bounds.left, top + bounds.top,
1498                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
1499                }
1500            }
1501        }
1502#endif
1503
1504        if (pureTranslate) {
1505            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1506            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1507
1508            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1509                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1510                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1511                    true, !mesh->hasEmptyQuads);
1512        } else {
1513            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1514                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1515                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1516                    true, !mesh->hasEmptyQuads);
1517        }
1518    }
1519}
1520
1521/**
1522 * This function uses a similar approach to that of AA lines in the drawLines() function.
1523 * We expand the rectangle by a half pixel in screen space on all sides, and use a fragment
1524 * shader to compute the translucency of the color, determined by whether a given pixel is
1525 * within that boundary region and how far into the region it is.
1526 */
1527void OpenGLRenderer::drawAARect(float left, float top, float right, float bottom,
1528        int color, SkXfermode::Mode mode) {
1529    float inverseScaleX = 1.0f;
1530    float inverseScaleY = 1.0f;
1531    // The quad that we use needs to account for scaling.
1532    if (!mSnapshot->transform->isPureTranslate()) {
1533        Matrix4 *mat = mSnapshot->transform;
1534        float m00 = mat->data[Matrix4::kScaleX];
1535        float m01 = mat->data[Matrix4::kSkewY];
1536        float m02 = mat->data[2];
1537        float m10 = mat->data[Matrix4::kSkewX];
1538        float m11 = mat->data[Matrix4::kScaleX];
1539        float m12 = mat->data[6];
1540        float scaleX = sqrt(m00 * m00 + m01 * m01);
1541        float scaleY = sqrt(m10 * m10 + m11 * m11);
1542        inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1543        inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1544    }
1545
1546    setupDraw();
1547    setupDrawAALine();
1548    setupDrawColor(color);
1549    setupDrawColorFilter();
1550    setupDrawShader();
1551    setupDrawBlending(true, mode);
1552    setupDrawProgram();
1553    setupDrawModelViewIdentity(true);
1554    setupDrawColorUniforms();
1555    setupDrawColorFilterUniforms();
1556    setupDrawShaderIdentityUniforms();
1557
1558    AAVertex rects[4];
1559    AAVertex* aaVertices = &rects[0];
1560    void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
1561    void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
1562
1563    float boundarySizeX = .5 * inverseScaleX;
1564    float boundarySizeY = .5 * inverseScaleY;
1565
1566    // Adjust the rect by the AA boundary padding
1567    left -= boundarySizeX;
1568    right += boundarySizeX;
1569    top -= boundarySizeY;
1570    bottom += boundarySizeY;
1571
1572    float width = right - left;
1573    float height = bottom - top;
1574
1575    float boundaryWidthProportion = (width != 0) ? (2 * boundarySizeX) / width : 0;
1576    float boundaryHeightProportion = (height != 0) ? (2 * boundarySizeY) / height : 0;
1577    setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion);
1578    int boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
1579    int inverseBoundaryLengthSlot = mCaches.currentProgram->getUniform("inverseBoundaryLength");
1580    glUniform1f(boundaryLengthSlot, boundaryHeightProportion);
1581    glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryHeightProportion));
1582
1583    if (!quickReject(left, top, right, bottom)) {
1584        AAVertex::set(aaVertices++, left, bottom, 1, 1);
1585        AAVertex::set(aaVertices++, left, top, 1, 0);
1586        AAVertex::set(aaVertices++, right, bottom, 0, 1);
1587        AAVertex::set(aaVertices++, right, top, 0, 0);
1588        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1589        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1590    }
1591}
1592
1593/**
1594 * We draw lines as quads (tristrips). Using GL_LINES can be difficult because the rasterization
1595 * rules for those lines produces some unexpected results, and may vary between hardware devices.
1596 * The basics of lines-as-quads is easy; we simply find the normal to the line and position the
1597 * corners of the quads on either side of each line endpoint, separated by the strokeWidth
1598 * of the line. Hairlines are more involved because we need to account for transform scaling
1599 * to end up with a one-pixel-wide line in screen space..
1600 * Anti-aliased lines add another factor to the approach. We use a specialized fragment shader
1601 * in combination with values that we calculate and pass down in this method. The basic approach
1602 * is that the quad we create contains both the core line area plus a bounding area in which
1603 * the translucent/AA pixels are drawn. The values we calculate tell the shader what
1604 * proportion of the width and the length of a given segment is represented by the boundary
1605 * region. The quad ends up being exactly .5 pixel larger in all directions than the non-AA quad.
1606 * The bounding region is actually 1 pixel wide on all sides (half pixel on the outside, half pixel
1607 * on the inside). This ends up giving the result we want, with pixels that are completely
1608 * 'inside' the line area being filled opaquely and the other pixels being filled according to
1609 * how far into the boundary region they are, which is determined by shader interpolation.
1610 */
1611void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
1612    if (mSnapshot->isIgnored()) return;
1613
1614    const bool isAA = paint->isAntiAlias();
1615    // We use half the stroke width here because we're going to position the quad
1616    // corner vertices half of the width away from the line endpoints
1617    float halfStrokeWidth = paint->getStrokeWidth() * 0.5f;
1618    // A stroke width of 0 has a special meaning in Skia:
1619    // it draws a line 1 px wide regardless of current transform
1620    bool isHairLine = paint->getStrokeWidth() == 0.0f;
1621    float inverseScaleX = 1.0f;
1622    float inverseScaleY = 1.0f;
1623    bool scaled = false;
1624    int alpha;
1625    SkXfermode::Mode mode;
1626    int generatedVerticesCount = 0;
1627    int verticesCount = count;
1628    if (count > 4) {
1629        // Polyline: account for extra vertices needed for continuous tri-strip
1630        verticesCount += (count - 4);
1631    }
1632
1633    if (isHairLine || isAA) {
1634        // The quad that we use for AA and hairlines needs to account for scaling. For hairlines
1635        // the line on the screen should always be one pixel wide regardless of scale. For
1636        // AA lines, we only want one pixel of translucent boundary around the quad.
1637        if (!mSnapshot->transform->isPureTranslate()) {
1638            Matrix4 *mat = mSnapshot->transform;
1639            float m00 = mat->data[Matrix4::kScaleX];
1640            float m01 = mat->data[Matrix4::kSkewY];
1641            float m02 = mat->data[2];
1642            float m10 = mat->data[Matrix4::kSkewX];
1643            float m11 = mat->data[Matrix4::kScaleX];
1644            float m12 = mat->data[6];
1645            float scaleX = sqrt(m00*m00 + m01*m01);
1646            float scaleY = sqrt(m10*m10 + m11*m11);
1647            inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1648            inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1649            if (inverseScaleX != 1.0f || inverseScaleY != 1.0f) {
1650                scaled = true;
1651            }
1652        }
1653    }
1654
1655    getAlphaAndMode(paint, &alpha, &mode);
1656    setupDraw();
1657    if (isAA) {
1658        setupDrawAALine();
1659    }
1660    setupDrawColor(paint->getColor(), alpha);
1661    setupDrawColorFilter();
1662    setupDrawShader();
1663    if (isAA) {
1664        setupDrawBlending(true, mode);
1665    } else {
1666        setupDrawBlending(mode);
1667    }
1668    setupDrawProgram();
1669    setupDrawModelViewIdentity(true);
1670    setupDrawColorUniforms();
1671    setupDrawColorFilterUniforms();
1672    setupDrawShaderIdentityUniforms();
1673
1674    if (isHairLine) {
1675        // Set a real stroke width to be used in quad construction
1676        halfStrokeWidth = isAA? 1 : .5;
1677    } else if (isAA && !scaled) {
1678        // Expand boundary to enable AA calculations on the quad border
1679        halfStrokeWidth += .5f;
1680    }
1681    Vertex lines[verticesCount];
1682    Vertex* vertices = &lines[0];
1683    AAVertex wLines[verticesCount];
1684    AAVertex* aaVertices = &wLines[0];
1685    if (!isAA) {
1686        setupDrawVertices(vertices);
1687    } else {
1688        void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
1689        void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
1690        // innerProportion is the ratio of the inner (non-AA) part of the line to the total
1691        // AA stroke width (the base stroke width expanded by a half pixel on either side).
1692        // This value is used in the fragment shader to determine how to fill fragments.
1693        // We will need to calculate the actual width proportion on each segment for
1694        // scaled non-hairlines, since the boundary proportion may differ per-axis when scaled.
1695        float boundaryWidthProportion = 1 / (2 * halfStrokeWidth);
1696        setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion);
1697    }
1698
1699    AAVertex* prevAAVertex = NULL;
1700    Vertex* prevVertex = NULL;
1701
1702    int boundaryLengthSlot = -1;
1703    int inverseBoundaryLengthSlot = -1;
1704    int boundaryWidthSlot = -1;
1705    int inverseBoundaryWidthSlot = -1;
1706    for (int i = 0; i < count; i += 4) {
1707        // a = start point, b = end point
1708        vec2 a(points[i], points[i + 1]);
1709        vec2 b(points[i + 2], points[i + 3]);
1710        float length = 0;
1711        float boundaryLengthProportion = 0;
1712        float boundaryWidthProportion = 0;
1713
1714        // Find the normal to the line
1715        vec2 n = (b - a).copyNormalized() * halfStrokeWidth;
1716        if (isHairLine) {
1717            if (isAA) {
1718                float wideningFactor;
1719                if (fabs(n.x) >= fabs(n.y)) {
1720                    wideningFactor = fabs(1.0f / n.x);
1721                } else {
1722                    wideningFactor = fabs(1.0f / n.y);
1723                }
1724                n *= wideningFactor;
1725            }
1726            if (scaled) {
1727                n.x *= inverseScaleX;
1728                n.y *= inverseScaleY;
1729            }
1730        } else if (scaled) {
1731            // Extend n by .5 pixel on each side, post-transform
1732            vec2 extendedN = n.copyNormalized();
1733            extendedN /= 2;
1734            extendedN.x *= inverseScaleX;
1735            extendedN.y *= inverseScaleY;
1736            float extendedNLength = extendedN.length();
1737            // We need to set this value on the shader prior to drawing
1738            boundaryWidthProportion = extendedNLength / (halfStrokeWidth + extendedNLength);
1739            n += extendedN;
1740        }
1741        float x = n.x;
1742        n.x = -n.y;
1743        n.y = x;
1744
1745        // aa lines expand the endpoint vertices to encompass the AA boundary
1746        if (isAA) {
1747            vec2 abVector = (b - a);
1748            length = abVector.length();
1749            abVector.normalize();
1750            if (scaled) {
1751                abVector.x *= inverseScaleX;
1752                abVector.y *= inverseScaleY;
1753                float abLength = abVector.length();
1754                boundaryLengthProportion = abLength / (length + abLength);
1755            } else {
1756                boundaryLengthProportion = .5 / (length + 1);
1757            }
1758            abVector /= 2;
1759            a -= abVector;
1760            b += abVector;
1761        }
1762
1763        // Four corners of the rectangle defining a thick line
1764        vec2 p1 = a - n;
1765        vec2 p2 = a + n;
1766        vec2 p3 = b + n;
1767        vec2 p4 = b - n;
1768
1769
1770        const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
1771        const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
1772        const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
1773        const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
1774
1775        if (!quickReject(left, top, right, bottom)) {
1776            if (!isAA) {
1777                if (prevVertex != NULL) {
1778                    // Issue two repeat vertices to create degenerate triangles to bridge
1779                    // between the previous line and the new one. This is necessary because
1780                    // we are creating a single triangle_strip which will contain
1781                    // potentially discontinuous line segments.
1782                    Vertex::set(vertices++, prevVertex->position[0], prevVertex->position[1]);
1783                    Vertex::set(vertices++, p1.x, p1.y);
1784                    generatedVerticesCount += 2;
1785                }
1786                Vertex::set(vertices++, p1.x, p1.y);
1787                Vertex::set(vertices++, p2.x, p2.y);
1788                Vertex::set(vertices++, p4.x, p4.y);
1789                Vertex::set(vertices++, p3.x, p3.y);
1790                prevVertex = vertices - 1;
1791                generatedVerticesCount += 4;
1792            } else {
1793                if (!isHairLine && scaled) {
1794                    // Must set width proportions per-segment for scaled non-hairlines to use the
1795                    // correct AA boundary dimensions
1796                    if (boundaryWidthSlot < 0) {
1797                        boundaryWidthSlot =
1798                                mCaches.currentProgram->getUniform("boundaryWidth");
1799                        inverseBoundaryWidthSlot =
1800                                mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1801                    }
1802                    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1803                    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion));
1804                }
1805                if (boundaryLengthSlot < 0) {
1806                    boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
1807                    inverseBoundaryLengthSlot =
1808                            mCaches.currentProgram->getUniform("inverseBoundaryLength");
1809                }
1810                glUniform1f(boundaryLengthSlot, boundaryLengthProportion);
1811                glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryLengthProportion));
1812
1813                if (prevAAVertex != NULL) {
1814                    // Issue two repeat vertices to create degenerate triangles to bridge
1815                    // between the previous line and the new one. This is necessary because
1816                    // we are creating a single triangle_strip which will contain
1817                    // potentially discontinuous line segments.
1818                    AAVertex::set(aaVertices++,prevAAVertex->position[0],
1819                            prevAAVertex->position[1], prevAAVertex->width, prevAAVertex->length);
1820                    AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
1821                    generatedVerticesCount += 2;
1822                }
1823                AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
1824                AAVertex::set(aaVertices++, p1.x, p1.y, 1, 0);
1825                AAVertex::set(aaVertices++, p3.x, p3.y, 0, 1);
1826                AAVertex::set(aaVertices++, p2.x, p2.y, 0, 0);
1827                prevAAVertex = aaVertices - 1;
1828                generatedVerticesCount += 4;
1829            }
1830            dirtyLayer(a.x == b.x ? left - 1 : left, a.y == b.y ? top - 1 : top,
1831                    a.x == b.x ? right: right, a.y == b.y ? bottom: bottom,
1832                    *mSnapshot->transform);
1833        }
1834    }
1835    if (generatedVerticesCount > 0) {
1836       glDrawArrays(GL_TRIANGLE_STRIP, 0, generatedVerticesCount);
1837    }
1838}
1839
1840void OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
1841    if (mSnapshot->isIgnored()) return;
1842
1843    // TODO: The paint's cap style defines whether the points are square or circular
1844    // TODO: Handle AA for round points
1845
1846    // A stroke width of 0 has a special meaning in Skia:
1847    // it draws an unscaled 1px point
1848    float strokeWidth = paint->getStrokeWidth();
1849    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
1850    if (isHairLine) {
1851        // Now that we know it's hairline, we can set the effective width, to be used later
1852        strokeWidth = 1.0f;
1853    }
1854    const float halfWidth = strokeWidth / 2;
1855    int alpha;
1856    SkXfermode::Mode mode;
1857    getAlphaAndMode(paint, &alpha, &mode);
1858
1859    int verticesCount = count >> 1;
1860    int generatedVerticesCount = 0;
1861
1862    TextureVertex pointsData[verticesCount];
1863    TextureVertex* vertex = &pointsData[0];
1864
1865    setupDraw();
1866    setupDrawPoint(strokeWidth);
1867    setupDrawColor(paint->getColor(), alpha);
1868    setupDrawColorFilter();
1869    setupDrawShader();
1870    setupDrawBlending(mode);
1871    setupDrawProgram();
1872    setupDrawModelViewIdentity(true);
1873    setupDrawColorUniforms();
1874    setupDrawColorFilterUniforms();
1875    setupDrawPointUniforms();
1876    setupDrawShaderIdentityUniforms();
1877    setupDrawMesh(vertex);
1878
1879    for (int i = 0; i < count; i += 2) {
1880        TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
1881        generatedVerticesCount++;
1882        float left = points[i] - halfWidth;
1883        float right = points[i] + halfWidth;
1884        float top = points[i + 1] - halfWidth;
1885        float bottom = points [i + 1] + halfWidth;
1886        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1887    }
1888
1889    glDrawArrays(GL_POINTS, 0, generatedVerticesCount);
1890}
1891
1892void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1893    // No need to check against the clip, we fill the clip region
1894    if (mSnapshot->isIgnored()) return;
1895
1896    Rect& clip(*mSnapshot->clipRect);
1897    clip.snapToPixelBoundaries();
1898
1899    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
1900}
1901
1902void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, SkPaint* paint) {
1903    if (!texture) return;
1904    const AutoTexture autoCleanup(texture);
1905
1906    const float x = left + texture->left - texture->offset;
1907    const float y = top + texture->top - texture->offset;
1908
1909    drawPathTexture(texture, x, y, paint);
1910}
1911
1912void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
1913        float rx, float ry, SkPaint* paint) {
1914    if (mSnapshot->isIgnored()) return;
1915
1916    glActiveTexture(gTextureUnits[0]);
1917    const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
1918            right - left, bottom - top, rx, ry, paint);
1919    drawShape(left, top, texture, paint);
1920}
1921
1922void OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* paint) {
1923    if (mSnapshot->isIgnored()) return;
1924
1925    glActiveTexture(gTextureUnits[0]);
1926    const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, paint);
1927    drawShape(x - radius, y - radius, texture, paint);
1928}
1929
1930void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, SkPaint* paint) {
1931    if (mSnapshot->isIgnored()) return;
1932
1933    glActiveTexture(gTextureUnits[0]);
1934    const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, paint);
1935    drawShape(left, top, texture, paint);
1936}
1937
1938void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
1939        float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) {
1940    if (mSnapshot->isIgnored()) return;
1941
1942    if (fabs(sweepAngle) >= 360.0f) {
1943        drawOval(left, top, right, bottom, paint);
1944        return;
1945    }
1946
1947    glActiveTexture(gTextureUnits[0]);
1948    const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
1949            startAngle, sweepAngle, useCenter, paint);
1950    drawShape(left, top, texture, paint);
1951}
1952
1953void OpenGLRenderer::drawRectAsShape(float left, float top, float right, float bottom,
1954        SkPaint* paint) {
1955    if (mSnapshot->isIgnored()) return;
1956
1957    glActiveTexture(gTextureUnits[0]);
1958    const PathTexture* texture = mCaches.rectShapeCache.getRect(right - left, bottom - top, paint);
1959    drawShape(left, top, texture, paint);
1960}
1961
1962void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
1963    if (p->getStyle() != SkPaint::kFill_Style) {
1964        drawRectAsShape(left, top, right, bottom, p);
1965        return;
1966    }
1967
1968    if (quickReject(left, top, right, bottom)) {
1969        return;
1970    }
1971
1972    SkXfermode::Mode mode;
1973    if (!mCaches.extensions.hasFramebufferFetch()) {
1974        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
1975        if (!isMode) {
1976            // Assume SRC_OVER
1977            mode = SkXfermode::kSrcOver_Mode;
1978        }
1979    } else {
1980        mode = getXfermode(p->getXfermode());
1981    }
1982
1983    int color = p->getColor();
1984    if (p->isAntiAlias() && !mSnapshot->transform->isSimple()) {
1985        drawAARect(left, top, right, bottom, color, mode);
1986    } else {
1987        drawColorRect(left, top, right, bottom, color, mode);
1988    }
1989}
1990
1991void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
1992        float x, float y, SkPaint* paint) {
1993    if (text == NULL || count == 0) {
1994        return;
1995    }
1996    if (mSnapshot->isIgnored()) return;
1997
1998    // TODO: We should probably make a copy of the paint instead of modifying
1999    //       it; modifying the paint will change its generationID the first
2000    //       time, which might impact caches. More investigation needed to
2001    //       see if it matters.
2002    //       If we make a copy, then drawTextDecorations() should *not* make
2003    //       its own copy as it does right now.
2004    paint->setAntiAlias(true);
2005#if RENDER_TEXT_AS_GLYPHS
2006    paint->setTextEncoding(SkPaint::kGlyphID_TextEncoding);
2007#endif
2008
2009    float length = -1.0f;
2010    switch (paint->getTextAlign()) {
2011        case SkPaint::kCenter_Align:
2012            length = paint->measureText(text, bytesCount);
2013            x -= length / 2.0f;
2014            break;
2015        case SkPaint::kRight_Align:
2016            length = paint->measureText(text, bytesCount);
2017            x -= length;
2018            break;
2019        default:
2020            break;
2021    }
2022
2023    const float oldX = x;
2024    const float oldY = y;
2025    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2026    if (pureTranslate) {
2027        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2028        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2029    }
2030
2031    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
2032    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2033            paint->getTextSize());
2034
2035    int alpha;
2036    SkXfermode::Mode mode;
2037    getAlphaAndMode(paint, &alpha, &mode);
2038
2039    if (mHasShadow) {
2040        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2041        const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2042                paint, text, bytesCount, count, mShadowRadius);
2043        const AutoTexture autoCleanup(shadow);
2044
2045        const float sx = oldX - shadow->left + mShadowDx;
2046        const float sy = oldY - shadow->top + mShadowDy;
2047
2048        const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
2049        int shadowColor = mShadowColor;
2050        if (mShader) {
2051            shadowColor = 0xffffffff;
2052        }
2053
2054        glActiveTexture(gTextureUnits[0]);
2055        setupDraw();
2056        setupDrawWithTexture(true);
2057        setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2058        setupDrawColorFilter();
2059        setupDrawShader();
2060        setupDrawBlending(true, mode);
2061        setupDrawProgram();
2062        setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2063        setupDrawTexture(shadow->id);
2064        setupDrawPureColorUniforms();
2065        setupDrawColorFilterUniforms();
2066        setupDrawShaderUniforms();
2067        setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2068
2069        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2070
2071        finishDrawTexture();
2072    }
2073
2074    if (paint->getAlpha() == 0 && paint->getXfermode() == NULL) {
2075        return;
2076    }
2077
2078    // Pick the appropriate texture filtering
2079    bool linearFilter = mSnapshot->transform->changesBounds();
2080    if (pureTranslate && !linearFilter) {
2081        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2082    }
2083
2084    glActiveTexture(gTextureUnits[0]);
2085    setupDraw();
2086    setupDrawDirtyRegionsDisabled();
2087    setupDrawWithTexture(true);
2088    setupDrawAlpha8Color(paint->getColor(), alpha);
2089    setupDrawColorFilter();
2090    setupDrawShader();
2091    setupDrawBlending(true, mode);
2092    setupDrawProgram();
2093    setupDrawModelView(x, y, x, y, pureTranslate, true);
2094    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2095    setupDrawPureColorUniforms();
2096    setupDrawColorFilterUniforms();
2097    setupDrawShaderUniforms(pureTranslate);
2098
2099    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2100    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2101
2102#if RENDER_LAYERS_AS_REGIONS
2103    bool hasActiveLayer = hasLayer();
2104#else
2105    bool hasActiveLayer = false;
2106#endif
2107    mCaches.unbindMeshBuffer();
2108
2109    // Tell font renderer the locations of position and texture coord
2110    // attributes so it can bind its data properly
2111    int positionSlot = mCaches.currentProgram->position;
2112    fontRenderer.setAttributeBindingSlots(positionSlot, mTexCoordsSlot);
2113    if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y,
2114            hasActiveLayer ? &bounds : NULL)) {
2115#if RENDER_LAYERS_AS_REGIONS
2116        if (hasActiveLayer) {
2117            if (!pureTranslate) {
2118                mSnapshot->transform->mapRect(bounds);
2119            }
2120            dirtyLayerUnchecked(bounds, getRegion());
2121        }
2122#endif
2123    }
2124
2125    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
2126    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
2127
2128    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
2129}
2130
2131void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
2132    if (mSnapshot->isIgnored()) return;
2133
2134    glActiveTexture(gTextureUnits[0]);
2135
2136    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2137    if (!texture) return;
2138    const AutoTexture autoCleanup(texture);
2139
2140    const float x = texture->left - texture->offset;
2141    const float y = texture->top - texture->offset;
2142
2143    drawPathTexture(texture, x, y, paint);
2144}
2145
2146void OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
2147    if (!layer || quickReject(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight())) {
2148        return;
2149    }
2150
2151    glActiveTexture(gTextureUnits[0]);
2152
2153    int alpha;
2154    SkXfermode::Mode mode;
2155    getAlphaAndMode(paint, &alpha, &mode);
2156
2157    layer->alpha = alpha;
2158    layer->mode = mode;
2159
2160#if RENDER_LAYERS_AS_REGIONS
2161    if (!layer->region.isEmpty()) {
2162        if (layer->region.isRect()) {
2163            composeLayerRect(layer, layer->regionRect);
2164        } else if (layer->mesh) {
2165            const float a = alpha / 255.0f;
2166            const Rect& rect = layer->layer;
2167
2168            setupDraw();
2169            setupDrawWithTexture();
2170            setupDrawColor(a, a, a, a);
2171            setupDrawColorFilter();
2172            setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
2173            setupDrawProgram();
2174            setupDrawModelViewTranslate(x, y,
2175                    x + layer->layer.getWidth(), y + layer->layer.getHeight());
2176            setupDrawPureColorUniforms();
2177            setupDrawColorFilterUniforms();
2178            setupDrawTexture(layer->texture);
2179            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
2180
2181            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
2182                    GL_UNSIGNED_SHORT, layer->meshIndices);
2183
2184            finishDrawTexture();
2185
2186#if DEBUG_LAYERS_AS_REGIONS
2187            drawRegionRects(layer->region);
2188#endif
2189        }
2190    }
2191#else
2192    const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
2193    composeLayerRect(layer, r);
2194#endif
2195}
2196
2197///////////////////////////////////////////////////////////////////////////////
2198// Shaders
2199///////////////////////////////////////////////////////////////////////////////
2200
2201void OpenGLRenderer::resetShader() {
2202    mShader = NULL;
2203}
2204
2205void OpenGLRenderer::setupShader(SkiaShader* shader) {
2206    mShader = shader;
2207    if (mShader) {
2208        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
2209    }
2210}
2211
2212///////////////////////////////////////////////////////////////////////////////
2213// Color filters
2214///////////////////////////////////////////////////////////////////////////////
2215
2216void OpenGLRenderer::resetColorFilter() {
2217    mColorFilter = NULL;
2218}
2219
2220void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
2221    mColorFilter = filter;
2222}
2223
2224///////////////////////////////////////////////////////////////////////////////
2225// Drop shadow
2226///////////////////////////////////////////////////////////////////////////////
2227
2228void OpenGLRenderer::resetShadow() {
2229    mHasShadow = false;
2230}
2231
2232void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
2233    mHasShadow = true;
2234    mShadowRadius = radius;
2235    mShadowDx = dx;
2236    mShadowDy = dy;
2237    mShadowColor = color;
2238}
2239
2240///////////////////////////////////////////////////////////////////////////////
2241// Drawing implementation
2242///////////////////////////////////////////////////////////////////////////////
2243
2244void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
2245        float x, float y, SkPaint* paint) {
2246    if (quickReject(x, y, x + texture->width, y + texture->height)) {
2247        return;
2248    }
2249
2250    int alpha;
2251    SkXfermode::Mode mode;
2252    getAlphaAndMode(paint, &alpha, &mode);
2253
2254    setupDraw();
2255    setupDrawWithTexture(true);
2256    setupDrawAlpha8Color(paint->getColor(), alpha);
2257    setupDrawColorFilter();
2258    setupDrawShader();
2259    setupDrawBlending(true, mode);
2260    setupDrawProgram();
2261    setupDrawModelView(x, y, x + texture->width, y + texture->height);
2262    setupDrawTexture(texture->id);
2263    setupDrawPureColorUniforms();
2264    setupDrawColorFilterUniforms();
2265    setupDrawShaderUniforms();
2266    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2267
2268    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2269
2270    finishDrawTexture();
2271}
2272
2273// Same values used by Skia
2274#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2275#define kStdUnderline_Offset    (1.0f / 9.0f)
2276#define kStdUnderline_Thickness (1.0f / 18.0f)
2277
2278void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
2279        float x, float y, SkPaint* paint) {
2280    // Handle underline and strike-through
2281    uint32_t flags = paint->getFlags();
2282    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
2283        SkPaint paintCopy(*paint);
2284        float underlineWidth = length;
2285        // If length is > 0.0f, we already measured the text for the text alignment
2286        if (length <= 0.0f) {
2287            underlineWidth = paintCopy.measureText(text, bytesCount);
2288        }
2289
2290        float offsetX = 0;
2291        switch (paintCopy.getTextAlign()) {
2292            case SkPaint::kCenter_Align:
2293                offsetX = underlineWidth * 0.5f;
2294                break;
2295            case SkPaint::kRight_Align:
2296                offsetX = underlineWidth;
2297                break;
2298            default:
2299                break;
2300        }
2301
2302        if (underlineWidth > 0.0f) {
2303            const float textSize = paintCopy.getTextSize();
2304            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
2305
2306            const float left = x - offsetX;
2307            float top = 0.0f;
2308
2309            int linesCount = 0;
2310            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
2311            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
2312
2313            const int pointsCount = 4 * linesCount;
2314            float points[pointsCount];
2315            int currentPoint = 0;
2316
2317            if (flags & SkPaint::kUnderlineText_Flag) {
2318                top = y + textSize * kStdUnderline_Offset;
2319                points[currentPoint++] = left;
2320                points[currentPoint++] = top;
2321                points[currentPoint++] = left + underlineWidth;
2322                points[currentPoint++] = top;
2323            }
2324
2325            if (flags & SkPaint::kStrikeThruText_Flag) {
2326                top = y + textSize * kStdStrikeThru_Offset;
2327                points[currentPoint++] = left;
2328                points[currentPoint++] = top;
2329                points[currentPoint++] = left + underlineWidth;
2330                points[currentPoint++] = top;
2331            }
2332
2333            paintCopy.setStrokeWidth(strokeWidth);
2334
2335            drawLines(&points[0], pointsCount, &paintCopy);
2336        }
2337    }
2338}
2339
2340void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
2341        int color, SkXfermode::Mode mode, bool ignoreTransform) {
2342    // If a shader is set, preserve only the alpha
2343    if (mShader) {
2344        color |= 0x00ffffff;
2345    }
2346
2347    setupDraw();
2348    setupDrawColor(color);
2349    setupDrawShader();
2350    setupDrawColorFilter();
2351    setupDrawBlending(mode);
2352    setupDrawProgram();
2353    setupDrawModelView(left, top, right, bottom, ignoreTransform);
2354    setupDrawColorUniforms();
2355    setupDrawShaderUniforms(ignoreTransform);
2356    setupDrawColorFilterUniforms();
2357    setupDrawSimpleMesh();
2358
2359    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2360}
2361
2362void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2363        Texture* texture, SkPaint* paint) {
2364    int alpha;
2365    SkXfermode::Mode mode;
2366    getAlphaAndMode(paint, &alpha, &mode);
2367
2368    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
2369
2370    if (mSnapshot->transform->isPureTranslate()) {
2371        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
2372        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
2373
2374        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
2375                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
2376                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
2377    } else {
2378        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
2379                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
2380                GL_TRIANGLE_STRIP, gMeshCount);
2381    }
2382}
2383
2384void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2385        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
2386    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
2387            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
2388}
2389
2390void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
2391        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
2392        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
2393        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
2394
2395    setupDraw();
2396    setupDrawWithTexture();
2397    setupDrawColor(alpha, alpha, alpha, alpha);
2398    setupDrawColorFilter();
2399    setupDrawBlending(blend, mode, swapSrcDst);
2400    setupDrawProgram();
2401    if (!dirty) {
2402        setupDrawDirtyRegionsDisabled();
2403    }
2404    if (!ignoreScale) {
2405        setupDrawModelView(left, top, right, bottom, ignoreTransform);
2406    } else {
2407        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
2408    }
2409    setupDrawPureColorUniforms();
2410    setupDrawColorFilterUniforms();
2411    setupDrawTexture(texture);
2412    setupDrawMesh(vertices, texCoords, vbo);
2413
2414    glDrawArrays(drawMode, 0, elementsCount);
2415
2416    finishDrawTexture();
2417}
2418
2419void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
2420        ProgramDescription& description, bool swapSrcDst) {
2421    blend = blend || mode != SkXfermode::kSrcOver_Mode;
2422    if (blend) {
2423        if (mode < SkXfermode::kPlus_Mode) {
2424            if (!mCaches.blend) {
2425                glEnable(GL_BLEND);
2426            }
2427
2428            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
2429            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
2430
2431            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
2432                glBlendFunc(sourceMode, destMode);
2433                mCaches.lastSrcMode = sourceMode;
2434                mCaches.lastDstMode = destMode;
2435            }
2436        } else {
2437            // These blend modes are not supported by OpenGL directly and have
2438            // to be implemented using shaders. Since the shader will perform
2439            // the blending, turn blending off here
2440            if (mCaches.extensions.hasFramebufferFetch()) {
2441                description.framebufferMode = mode;
2442                description.swapSrcDst = swapSrcDst;
2443            }
2444
2445            if (mCaches.blend) {
2446                glDisable(GL_BLEND);
2447            }
2448            blend = false;
2449        }
2450    } else if (mCaches.blend) {
2451        glDisable(GL_BLEND);
2452    }
2453    mCaches.blend = blend;
2454}
2455
2456bool OpenGLRenderer::useProgram(Program* program) {
2457    if (!program->isInUse()) {
2458        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
2459        program->use();
2460        mCaches.currentProgram = program;
2461        return false;
2462    }
2463    return true;
2464}
2465
2466void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
2467    TextureVertex* v = &mMeshVertices[0];
2468    TextureVertex::setUV(v++, u1, v1);
2469    TextureVertex::setUV(v++, u2, v1);
2470    TextureVertex::setUV(v++, u1, v2);
2471    TextureVertex::setUV(v++, u2, v2);
2472}
2473
2474void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
2475    if (paint) {
2476        if (!mCaches.extensions.hasFramebufferFetch()) {
2477            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
2478            if (!isMode) {
2479                // Assume SRC_OVER
2480                *mode = SkXfermode::kSrcOver_Mode;
2481            }
2482        } else {
2483            *mode = getXfermode(paint->getXfermode());
2484        }
2485
2486        // Skia draws using the color's alpha channel if < 255
2487        // Otherwise, it uses the paint's alpha
2488        int color = paint->getColor();
2489        *alpha = (color >> 24) & 0xFF;
2490        if (*alpha == 255) {
2491            *alpha = paint->getAlpha();
2492        }
2493    } else {
2494        *mode = SkXfermode::kSrcOver_Mode;
2495        *alpha = 255;
2496    }
2497}
2498
2499SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
2500    SkXfermode::Mode resultMode;
2501    if (!SkXfermode::AsMode(mode, &resultMode)) {
2502        resultMode = SkXfermode::kSrcOver_Mode;
2503    }
2504    return resultMode;
2505}
2506
2507void OpenGLRenderer::setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT) {
2508    bool bound = false;
2509    if (wrapS != texture->wrapS) {
2510        glBindTexture(GL_TEXTURE_2D, texture->id);
2511        bound = true;
2512        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
2513        texture->wrapS = wrapS;
2514    }
2515    if (wrapT != texture->wrapT) {
2516        if (!bound) {
2517            glBindTexture(GL_TEXTURE_2D, texture->id);
2518        }
2519        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
2520        texture->wrapT = wrapT;
2521    }
2522}
2523
2524}; // namespace uirenderer
2525}; // namespace android
2526