OpenGLRenderer.cpp revision 6f72bebe92a4db7b5dc83f4ac5b5fd02e3b4e2cd
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "OpenGLRenderer"
18
19#include <stdlib.h>
20#include <stdint.h>
21#include <sys/types.h>
22
23#include <SkCanvas.h>
24#include <SkTypeface.h>
25
26#include <utils/Log.h>
27#include <utils/StopWatch.h>
28
29#include <ui/Rect.h>
30
31#include "OpenGLRenderer.h"
32#include "DisplayListRenderer.h"
33
34namespace android {
35namespace uirenderer {
36
37///////////////////////////////////////////////////////////////////////////////
38// Defines
39///////////////////////////////////////////////////////////////////////////////
40
41#define RAD_TO_DEG (180.0f / 3.14159265f)
42#define MIN_ANGLE 0.001f
43
44// TODO: This should be set in properties
45#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH)
46
47///////////////////////////////////////////////////////////////////////////////
48// Globals
49///////////////////////////////////////////////////////////////////////////////
50
51/**
52 * Structure mapping Skia xfermodes to OpenGL blending factors.
53 */
54struct Blender {
55    SkXfermode::Mode mode;
56    GLenum src;
57    GLenum dst;
58}; // struct Blender
59
60// In this array, the index of each Blender equals the value of the first
61// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
62static const Blender gBlends[] = {
63        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
64        { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
65        { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
66        { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
67        { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
68        { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
69        { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
70        { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
71        { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
72        { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
73        { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
74        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
75};
76
77// This array contains the swapped version of each SkXfermode. For instance
78// this array's SrcOver blending mode is actually DstOver. You can refer to
79// createLayer() for more information on the purpose of this array.
80static const Blender gBlendsSwap[] = {
81        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
82        { SkXfermode::kSrc_Mode,     GL_ZERO,                 GL_ONE },
83        { SkXfermode::kDst_Mode,     GL_ONE,                  GL_ZERO },
84        { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
85        { SkXfermode::kDstOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
86        { SkXfermode::kSrcIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
87        { SkXfermode::kDstIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
88        { SkXfermode::kSrcOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
89        { SkXfermode::kDstOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
90        { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
91        { SkXfermode::kDstATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
92        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
93};
94
95static const GLenum gTextureUnits[] = {
96        GL_TEXTURE0,
97        GL_TEXTURE1,
98        GL_TEXTURE2
99};
100
101///////////////////////////////////////////////////////////////////////////////
102// Constructors/destructor
103///////////////////////////////////////////////////////////////////////////////
104
105OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
106    mShader = NULL;
107    mColorFilter = NULL;
108    mHasShadow = false;
109
110    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
111
112    mFirstSnapshot = new Snapshot;
113}
114
115OpenGLRenderer::~OpenGLRenderer() {
116    // The context has already been destroyed at this point, do not call
117    // GL APIs. All GL state should be kept in Caches.h
118}
119
120///////////////////////////////////////////////////////////////////////////////
121// Setup
122///////////////////////////////////////////////////////////////////////////////
123
124void OpenGLRenderer::setViewport(int width, int height) {
125    glViewport(0, 0, width, height);
126    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
127
128    mWidth = width;
129    mHeight = height;
130
131    mFirstSnapshot->height = height;
132    mFirstSnapshot->viewport.set(0, 0, width, height);
133
134    mDirtyClip = false;
135}
136
137void OpenGLRenderer::prepare(bool opaque) {
138    mCaches.clearGarbage();
139
140    mSnapshot = new Snapshot(mFirstSnapshot,
141            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
142    mSaveCount = 1;
143
144    glViewport(0, 0, mWidth, mHeight);
145
146    glDisable(GL_DITHER);
147
148    if (!opaque) {
149        glDisable(GL_SCISSOR_TEST);
150        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
151        glClear(GL_COLOR_BUFFER_BIT);
152    }
153
154    glEnable(GL_SCISSOR_TEST);
155    glScissor(0, 0, mWidth, mHeight);
156    mSnapshot->setClip(0.0f, 0.0f, mWidth, mHeight);
157}
158
159void OpenGLRenderer::finish() {
160#if DEBUG_OPENGL
161    GLenum status = GL_NO_ERROR;
162    while ((status = glGetError()) != GL_NO_ERROR) {
163        LOGD("GL error from OpenGLRenderer: 0x%x", status);
164    }
165#endif
166#if DEBUG_MEMORY_USAGE
167    mCaches.dumpMemoryUsage();
168#else
169    if (mCaches.getDebugLevel() & kDebugMemory) {
170        mCaches.dumpMemoryUsage();
171    }
172#endif
173}
174
175void OpenGLRenderer::acquireContext() {
176    if (mCaches.currentProgram) {
177        if (mCaches.currentProgram->isInUse()) {
178            mCaches.currentProgram->remove();
179            mCaches.currentProgram = NULL;
180        }
181    }
182    mCaches.unbindMeshBuffer();
183}
184
185void OpenGLRenderer::releaseContext() {
186    glViewport(0, 0, mSnapshot->viewport.getWidth(), mSnapshot->viewport.getHeight());
187
188    glEnable(GL_SCISSOR_TEST);
189    dirtyClip();
190
191    glDisable(GL_DITHER);
192
193    glBindFramebuffer(GL_FRAMEBUFFER, 0);
194    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
195
196    mCaches.blend = true;
197    glEnable(GL_BLEND);
198    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
199    glBlendEquation(GL_FUNC_ADD);
200}
201
202///////////////////////////////////////////////////////////////////////////////
203// State management
204///////////////////////////////////////////////////////////////////////////////
205
206int OpenGLRenderer::getSaveCount() const {
207    return mSaveCount;
208}
209
210int OpenGLRenderer::save(int flags) {
211    return saveSnapshot(flags);
212}
213
214void OpenGLRenderer::restore() {
215    if (mSaveCount > 1) {
216        restoreSnapshot();
217    }
218}
219
220void OpenGLRenderer::restoreToCount(int saveCount) {
221    if (saveCount < 1) saveCount = 1;
222
223    while (mSaveCount > saveCount) {
224        restoreSnapshot();
225    }
226}
227
228int OpenGLRenderer::saveSnapshot(int flags) {
229    mSnapshot = new Snapshot(mSnapshot, flags);
230    return mSaveCount++;
231}
232
233bool OpenGLRenderer::restoreSnapshot() {
234    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
235    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
236    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
237
238    sp<Snapshot> current = mSnapshot;
239    sp<Snapshot> previous = mSnapshot->previous;
240
241    if (restoreOrtho) {
242        Rect& r = previous->viewport;
243        glViewport(r.left, r.top, r.right, r.bottom);
244        mOrthoMatrix.load(current->orthoMatrix);
245    }
246
247    mSaveCount--;
248    mSnapshot = previous;
249
250    if (restoreClip) {
251        dirtyClip();
252    }
253
254    if (restoreLayer) {
255        composeLayer(current, previous);
256    }
257
258    return restoreClip;
259}
260
261///////////////////////////////////////////////////////////////////////////////
262// Layers
263///////////////////////////////////////////////////////////////////////////////
264
265int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
266        SkPaint* p, int flags) {
267    const GLuint previousFbo = mSnapshot->fbo;
268    const int count = saveSnapshot(flags);
269
270    if (!mSnapshot->invisible) {
271        int alpha = 255;
272        SkXfermode::Mode mode;
273
274        if (p) {
275            alpha = p->getAlpha();
276            if (!mCaches.extensions.hasFramebufferFetch()) {
277                const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
278                if (!isMode) {
279                    // Assume SRC_OVER
280                    mode = SkXfermode::kSrcOver_Mode;
281                }
282            } else {
283                mode = getXfermode(p->getXfermode());
284            }
285        } else {
286            mode = SkXfermode::kSrcOver_Mode;
287        }
288
289        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
290    }
291
292    return count;
293}
294
295int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
296        int alpha, int flags) {
297    if (alpha >= 255 - ALPHA_THRESHOLD) {
298        return saveLayer(left, top, right, bottom, NULL, flags);
299    } else {
300        SkPaint paint;
301        paint.setAlpha(alpha);
302        return saveLayer(left, top, right, bottom, &paint, flags);
303    }
304}
305
306/**
307 * Layers are viewed by Skia are slightly different than layers in image editing
308 * programs (for instance.) When a layer is created, previously created layers
309 * and the frame buffer still receive every drawing command. For instance, if a
310 * layer is created and a shape intersecting the bounds of the layers and the
311 * framebuffer is draw, the shape will be drawn on both (unless the layer was
312 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
313 *
314 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
315 * texture. Unfortunately, this is inefficient as it requires every primitive to
316 * be drawn n + 1 times, where n is the number of active layers. In practice this
317 * means, for every primitive:
318 *   - Switch active frame buffer
319 *   - Change viewport, clip and projection matrix
320 *   - Issue the drawing
321 *
322 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
323 * To avoid this, layers are implemented in a different way here, at least in the
324 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
325 * is set. When this flag is set we can redirect all drawing operations into a
326 * single FBO.
327 *
328 * This implementation relies on the frame buffer being at least RGBA 8888. When
329 * a layer is created, only a texture is created, not an FBO. The content of the
330 * frame buffer contained within the layer's bounds is copied into this texture
331 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
332 * buffer and drawing continues as normal. This technique therefore treats the
333 * frame buffer as a scratch buffer for the layers.
334 *
335 * To compose the layers back onto the frame buffer, each layer texture
336 * (containing the original frame buffer data) is drawn as a simple quad over
337 * the frame buffer. The trick is that the quad is set as the composition
338 * destination in the blending equation, and the frame buffer becomes the source
339 * of the composition.
340 *
341 * Drawing layers with an alpha value requires an extra step before composition.
342 * An empty quad is drawn over the layer's region in the frame buffer. This quad
343 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
344 * quad is used to multiply the colors in the frame buffer. This is achieved by
345 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
346 * GL_ZERO, GL_SRC_ALPHA.
347 *
348 * Because glCopyTexImage2D() can be slow, an alternative implementation might
349 * be use to draw a single clipped layer. The implementation described above
350 * is correct in every case.
351 *
352 * (1) The frame buffer is actually not cleared right away. To allow the GPU
353 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
354 *     buffer is left untouched until the first drawing operation. Only when
355 *     something actually gets drawn are the layers regions cleared.
356 */
357bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
358        float right, float bottom, int alpha, SkXfermode::Mode mode,
359        int flags, GLuint previousFbo) {
360    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
361    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
362
363    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
364
365    // Window coordinates of the layer
366    Rect bounds(left, top, right, bottom);
367    if (fboLayer) {
368        // Clear the previous layer regions before we change the viewport
369        clearLayerRegions();
370    } else {
371        mSnapshot->transform->mapRect(bounds);
372
373        // Layers only make sense if they are in the framebuffer's bounds
374        bounds.intersect(*snapshot->clipRect);
375
376        // We cannot work with sub-pixels in this case
377        bounds.snapToPixelBoundaries();
378
379        // When the layer is not an FBO, we may use glCopyTexImage so we
380        // need to make sure the layer does not extend outside the bounds
381        // of the framebuffer
382        bounds.intersect(snapshot->previous->viewport);
383    }
384
385    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
386            bounds.getHeight() > mCaches.maxTextureSize) {
387        snapshot->invisible = true;
388    } else {
389        snapshot->invisible = snapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
390    }
391
392    // Bail out if we won't draw in this snapshot
393    if (snapshot->invisible) {
394        return false;
395    }
396
397    glActiveTexture(gTextureUnits[0]);
398    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
399    if (!layer) {
400        return false;
401    }
402
403    layer->mode = mode;
404    layer->alpha = alpha;
405    layer->layer.set(bounds);
406    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
407            bounds.getWidth() / float(layer->width), 0.0f);
408
409    // Save the layer in the snapshot
410    snapshot->flags |= Snapshot::kFlagIsLayer;
411    snapshot->layer = layer;
412
413    if (fboLayer) {
414        return createFboLayer(layer, bounds, snapshot, previousFbo);
415    } else {
416        // Copy the framebuffer into the layer
417        glBindTexture(GL_TEXTURE_2D, layer->texture);
418
419        if (layer->empty) {
420            glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left,
421                    snapshot->height - bounds.bottom, layer->width, layer->height, 0);
422            layer->empty = false;
423        } else {
424            glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
425                    snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
426        }
427
428        // Enqueue the buffer coordinates to clear the corresponding region later
429        mLayers.push(new Rect(bounds));
430    }
431
432    return true;
433}
434
435bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
436        GLuint previousFbo) {
437    layer->fbo = mCaches.fboCache.get();
438
439#if RENDER_LAYERS_AS_REGIONS
440    snapshot->region = &snapshot->layer->region;
441    snapshot->flags |= Snapshot::kFlagFboTarget;
442#endif
443
444    Rect clip(bounds);
445    snapshot->transform->mapRect(clip);
446    clip.intersect(*snapshot->clipRect);
447    clip.snapToPixelBoundaries();
448    clip.intersect(snapshot->previous->viewport);
449
450    mat4 inverse;
451    inverse.loadInverse(*mSnapshot->transform);
452
453    inverse.mapRect(clip);
454    clip.snapToPixelBoundaries();
455    clip.intersect(bounds);
456    clip.translate(-bounds.left, -bounds.top);
457
458    snapshot->flags |= Snapshot::kFlagIsFboLayer;
459    snapshot->fbo = layer->fbo;
460    snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
461    //snapshot->resetClip(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
462    snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
463    snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
464    snapshot->height = bounds.getHeight();
465    snapshot->flags |= Snapshot::kFlagDirtyOrtho;
466    snapshot->orthoMatrix.load(mOrthoMatrix);
467
468    // Bind texture to FBO
469    glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
470    glBindTexture(GL_TEXTURE_2D, layer->texture);
471
472    // Initialize the texture if needed
473    if (layer->empty) {
474        layer->empty = false;
475        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
476                GL_RGBA, GL_UNSIGNED_BYTE, NULL);
477    }
478
479    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
480            layer->texture, 0);
481
482#if DEBUG_LAYERS_AS_REGIONS
483    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
484    if (status != GL_FRAMEBUFFER_COMPLETE) {
485        LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
486
487        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
488        glDeleteTextures(1, &layer->texture);
489        mCaches.fboCache.put(layer->fbo);
490
491        delete layer;
492
493        return false;
494    }
495#endif
496
497    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
498    glScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
499            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
500    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
501    glClear(GL_COLOR_BUFFER_BIT);
502
503    dirtyClip();
504
505    // Change the ortho projection
506    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
507    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
508
509    return true;
510}
511
512/**
513 * Read the documentation of createLayer() before doing anything in this method.
514 */
515void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
516    if (!current->layer) {
517        LOGE("Attempting to compose a layer that does not exist");
518        return;
519    }
520
521    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
522
523    if (fboLayer) {
524        // Unbind current FBO and restore previous one
525        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
526    }
527
528    Layer* layer = current->layer;
529    const Rect& rect = layer->layer;
530
531    if (!fboLayer && layer->alpha < 255) {
532        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
533                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
534        // Required below, composeLayerRect() will divide by 255
535        layer->alpha = 255;
536    }
537
538    mCaches.unbindMeshBuffer();
539
540    glActiveTexture(gTextureUnits[0]);
541
542    // When the layer is stored in an FBO, we can save a bit of fillrate by
543    // drawing only the dirty region
544    if (fboLayer) {
545        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
546        composeLayerRegion(layer, rect);
547    } else {
548        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
549        composeLayerRect(layer, rect, true);
550    }
551
552    if (fboLayer) {
553        // Detach the texture from the FBO
554        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
555        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
556        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
557
558        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
559        mCaches.fboCache.put(current->fbo);
560    }
561
562    dirtyClip();
563
564    // Failing to add the layer to the cache should happen only if the layer is too large
565    if (!mCaches.layerCache.put(layer)) {
566        LAYER_LOGD("Deleting layer");
567        glDeleteTextures(1, &layer->texture);
568        delete layer;
569    }
570}
571
572void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
573    const Rect& texCoords = layer->texCoords;
574    resetDrawTextureTexCoords(texCoords.left, texCoords.top, texCoords.right, texCoords.bottom);
575
576    drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
577            layer->alpha / 255.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
578            &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, swap, swap);
579
580    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
581}
582
583void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
584#if RENDER_LAYERS_AS_REGIONS
585    if (layer->region.isRect()) {
586        composeLayerRect(layer, rect);
587        layer->region.clear();
588        return;
589    }
590
591    if (!layer->region.isEmpty()) {
592        size_t count;
593        const android::Rect* rects = layer->region.getArray(&count);
594
595        setupDraw();
596
597        ProgramDescription description;
598        description.hasTexture = true;
599
600        const float alpha = layer->alpha / 255.0f;
601        const bool setColor = description.setColor(alpha, alpha, alpha, alpha);
602        chooseBlending(layer->blend || layer->alpha < 255, layer->mode, description, false);
603
604        useProgram(mCaches.programCache.get(description));
605
606        // Texture
607        bindTexture(layer->texture);
608        glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
609
610        // Always premultiplied
611        if (setColor) {
612            mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha);
613        }
614
615        // Mesh
616        int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
617        glEnableVertexAttribArray(texCoordsSlot);
618
619        mModelView.loadIdentity();
620        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
621
622        const float texX = 1.0f / float(layer->width);
623        const float texY = 1.0f / float(layer->height);
624
625        TextureVertex* mesh = mCaches.getRegionMesh();
626        GLsizei numQuads = 0;
627
628        glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
629                gMeshStride, &mesh[0].position[0]);
630        glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE,
631                gMeshStride, &mesh[0].texture[0]);
632
633        for (size_t i = 0; i < count; i++) {
634            const android::Rect* r = &rects[i];
635
636            const float u1 = r->left * texX;
637            const float v1 = (rect.getHeight() - r->top) * texY;
638            const float u2 = r->right * texX;
639            const float v2 = (rect.getHeight() - r->bottom) * texY;
640
641            // TODO: Reject quads outside of the clip
642            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
643            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
644            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
645            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
646
647            numQuads++;
648
649            if (numQuads >= REGION_MESH_QUAD_COUNT) {
650                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
651                numQuads = 0;
652                mesh = mCaches.getRegionMesh();
653            }
654        }
655
656        if (numQuads > 0) {
657            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
658        }
659
660        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
661        glDisableVertexAttribArray(texCoordsSlot);
662
663#if DEBUG_LAYERS_AS_REGIONS
664        uint32_t colors[] = {
665                0x7fff0000, 0x7f00ff00,
666                0x7f0000ff, 0x7fff00ff,
667        };
668
669        int offset = 0;
670        int32_t top = rects[0].top;
671        int i = 0;
672
673        for (size_t i = 0; i < count; i++) {
674            if (top != rects[i].top) {
675                offset ^= 0x2;
676                top = rects[i].top;
677            }
678
679            Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
680            drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
681                    SkXfermode::kSrcOver_Mode);
682        }
683#endif
684
685        layer->region.clear();
686    }
687#else
688    composeLayerRect(layer, rect);
689#endif
690}
691
692void OpenGLRenderer::dirtyLayer(const float left, const float top,
693        const float right, const float bottom, const mat4 transform) {
694#if RENDER_LAYERS_AS_REGIONS
695    if ((mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region) {
696        Rect bounds(left, top, right, bottom);
697        transform.mapRect(bounds);
698        bounds.intersect(*mSnapshot->clipRect);
699        bounds.snapToPixelBoundaries();
700
701        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
702        if (!dirty.isEmpty()) {
703            mSnapshot->region->orSelf(dirty);
704        }
705    }
706#endif
707}
708
709void OpenGLRenderer::dirtyLayer(const float left, const float top,
710        const float right, const float bottom) {
711#if RENDER_LAYERS_AS_REGIONS
712    if ((mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region) {
713        Rect bounds(left, top, right, bottom);
714        bounds.intersect(*mSnapshot->clipRect);
715        bounds.snapToPixelBoundaries();
716
717        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
718        if (!dirty.isEmpty()) {
719            mSnapshot->region->orSelf(dirty);
720        }
721    }
722#endif
723}
724
725void OpenGLRenderer::setupDraw() {
726    clearLayerRegions();
727    if (mDirtyClip) {
728        setScissorFromClip();
729    }
730}
731
732void OpenGLRenderer::clearLayerRegions() {
733    if (mLayers.size() == 0 || mSnapshot->invisible) return;
734
735    Rect clipRect(*mSnapshot->clipRect);
736    clipRect.snapToPixelBoundaries();
737
738    for (uint32_t i = 0; i < mLayers.size(); i++) {
739        Rect* bounds = mLayers.itemAt(i);
740        if (clipRect.intersects(*bounds)) {
741            // Clear the framebuffer where the layer will draw
742            glScissor(bounds->left, mSnapshot->height - bounds->bottom,
743                    bounds->getWidth(), bounds->getHeight());
744            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
745            glClear(GL_COLOR_BUFFER_BIT);
746
747            // Restore the clip
748            dirtyClip();
749        }
750
751        delete bounds;
752    }
753
754    mLayers.clear();
755}
756
757///////////////////////////////////////////////////////////////////////////////
758// Transforms
759///////////////////////////////////////////////////////////////////////////////
760
761void OpenGLRenderer::translate(float dx, float dy) {
762    mSnapshot->transform->translate(dx, dy, 0.0f);
763}
764
765void OpenGLRenderer::rotate(float degrees) {
766    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
767}
768
769void OpenGLRenderer::scale(float sx, float sy) {
770    mSnapshot->transform->scale(sx, sy, 1.0f);
771}
772
773void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
774    mSnapshot->transform->load(*matrix);
775}
776
777const float* OpenGLRenderer::getMatrix() const {
778    if (mSnapshot->fbo != 0) {
779        return &mSnapshot->transform->data[0];
780    }
781    return &mIdentity.data[0];
782}
783
784void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
785    mSnapshot->transform->copyTo(*matrix);
786}
787
788void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
789    SkMatrix transform;
790    mSnapshot->transform->copyTo(transform);
791    transform.preConcat(*matrix);
792    mSnapshot->transform->load(transform);
793}
794
795///////////////////////////////////////////////////////////////////////////////
796// Clipping
797///////////////////////////////////////////////////////////////////////////////
798
799void OpenGLRenderer::setScissorFromClip() {
800    Rect clip(*mSnapshot->clipRect);
801    clip.snapToPixelBoundaries();
802    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
803    mDirtyClip = false;
804}
805
806const Rect& OpenGLRenderer::getClipBounds() {
807    return mSnapshot->getLocalClip();
808}
809
810bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
811    if (mSnapshot->invisible) {
812        return true;
813    }
814
815    Rect r(left, top, right, bottom);
816    mSnapshot->transform->mapRect(r);
817    r.snapToPixelBoundaries();
818
819    Rect clipRect(*mSnapshot->clipRect);
820    clipRect.snapToPixelBoundaries();
821
822    return !clipRect.intersects(r);
823}
824
825bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
826    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
827    if (clipped) {
828        dirtyClip();
829    }
830    return !mSnapshot->clipRect->isEmpty();
831}
832
833///////////////////////////////////////////////////////////////////////////////
834// Drawing
835///////////////////////////////////////////////////////////////////////////////
836
837void OpenGLRenderer::drawDisplayList(DisplayList* displayList) {
838    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
839    // will be performed by the display list itself
840    if (displayList) {
841        displayList->replay(*this);
842    }
843}
844
845void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
846    const float right = left + bitmap->width();
847    const float bottom = top + bitmap->height();
848
849    if (quickReject(left, top, right, bottom)) {
850        return;
851    }
852
853    glActiveTexture(GL_TEXTURE0);
854    Texture* texture = mCaches.textureCache.get(bitmap);
855    if (!texture) return;
856    const AutoTexture autoCleanup(texture);
857
858    drawTextureRect(left, top, right, bottom, texture, paint);
859}
860
861void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
862    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
863    const mat4 transform(*matrix);
864    transform.mapRect(r);
865
866    if (quickReject(r.left, r.top, r.right, r.bottom)) {
867        return;
868    }
869
870    glActiveTexture(GL_TEXTURE0);
871    Texture* texture = mCaches.textureCache.get(bitmap);
872    if (!texture) return;
873    const AutoTexture autoCleanup(texture);
874
875    // This could be done in a cheaper way, all we need is pass the matrix
876    // to the vertex shader. The save/restore is a bit overkill.
877    save(SkCanvas::kMatrix_SaveFlag);
878    concatMatrix(matrix);
879    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
880    restore();
881}
882
883void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
884         float srcLeft, float srcTop, float srcRight, float srcBottom,
885         float dstLeft, float dstTop, float dstRight, float dstBottom,
886         SkPaint* paint) {
887    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
888        return;
889    }
890
891    glActiveTexture(gTextureUnits[0]);
892    Texture* texture = mCaches.textureCache.get(bitmap);
893    if (!texture) return;
894    const AutoTexture autoCleanup(texture);
895    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
896
897    const float width = texture->width;
898    const float height = texture->height;
899
900    const float u1 = srcLeft / width;
901    const float v1 = srcTop / height;
902    const float u2 = srcRight / width;
903    const float v2 = srcBottom / height;
904
905    mCaches.unbindMeshBuffer();
906    resetDrawTextureTexCoords(u1, v1, u2, v2);
907
908    int alpha;
909    SkXfermode::Mode mode;
910    getAlphaAndMode(paint, &alpha, &mode);
911
912    drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
913            mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
914            GL_TRIANGLE_STRIP, gMeshCount);
915
916    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
917}
918
919void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
920        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
921        float left, float top, float right, float bottom, SkPaint* paint) {
922    if (quickReject(left, top, right, bottom)) {
923        return;
924    }
925
926    glActiveTexture(gTextureUnits[0]);
927    Texture* texture = mCaches.textureCache.get(bitmap);
928    if (!texture) return;
929    const AutoTexture autoCleanup(texture);
930    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
931
932    int alpha;
933    SkXfermode::Mode mode;
934    getAlphaAndMode(paint, &alpha, &mode);
935
936    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
937            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
938
939    if (mesh) {
940        // Mark the current layer dirty where we are going to draw the patch
941        if ((mSnapshot->flags & Snapshot::kFlagFboTarget) &&
942                mSnapshot->region && mesh->hasEmptyQuads) {
943            const size_t count = mesh->quads.size();
944            for (size_t i = 0; i < count; i++) {
945                Rect bounds = mesh->quads.itemAt(i);
946                dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom,
947                        *mSnapshot->transform);
948            }
949        }
950
951        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
952                mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
953                GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
954                true, !mesh->hasEmptyQuads);
955    } else {
956        PATCH_LOGD("Invisible 9patch, ignoring (%.2f, %.2f, %.2f, %.2f)",
957                left, top, right, bottom);
958    }
959}
960
961void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
962    // TODO: Should do quickReject for each line
963    if (mSnapshot->invisible) return;
964
965    setupDraw();
966
967    int alpha;
968    SkXfermode::Mode mode;
969    getAlphaAndMode(paint, &alpha, &mode);
970
971    uint32_t color = paint->getColor();
972    const GLfloat a = alpha / 255.0f;
973    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
974    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
975    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
976
977    const bool isAA = paint->isAntiAlias();
978    if (isAA) {
979        GLuint textureUnit = 0;
980        glActiveTexture(gTextureUnits[textureUnit]);
981        setupTextureAlpha8(mCaches.line.getTexture(), 0, 0, textureUnit, 0.0f, 0.0f, r, g, b, a,
982                mode, false, true, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
983                mCaches.line.getMeshBuffer());
984    } else {
985        setupColorRect(0.0f, 0.0f, 1.0f, 1.0f, r, g, b, a, mode, false, true);
986    }
987
988    const float strokeWidth = paint->getStrokeWidth();
989    const GLsizei elementsCount = isAA ? mCaches.line.getElementsCount() : gMeshCount;
990    const GLenum drawMode = isAA ? GL_TRIANGLES : GL_TRIANGLE_STRIP;
991
992    for (int i = 0; i < count; i += 4) {
993        float tx = 0.0f;
994        float ty = 0.0f;
995
996        if (isAA) {
997            mCaches.line.update(points[i], points[i + 1], points[i + 2], points[i + 3],
998                    strokeWidth, tx, ty);
999        } else {
1000            ty = strokeWidth <= 1.0f ? 0.0f : -strokeWidth * 0.5f;
1001        }
1002
1003        const float dx = points[i + 2] - points[i];
1004        const float dy = points[i + 3] - points[i + 1];
1005        const float mag = sqrtf(dx * dx + dy * dy);
1006        const float angle = acos(dx / mag);
1007
1008        mModelView.loadTranslate(points[i], points[i + 1], 0.0f);
1009        if (angle > MIN_ANGLE || angle < -MIN_ANGLE) {
1010            mModelView.rotate(angle * RAD_TO_DEG, 0.0f, 0.0f, 1.0f);
1011        }
1012        mModelView.translate(tx, ty, 0.0f);
1013        if (!isAA) {
1014            float length = mCaches.line.getLength(points[i], points[i + 1],
1015                    points[i + 2], points[i + 3]);
1016            mModelView.scale(length, strokeWidth, 1.0f);
1017        }
1018        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1019        // TODO: Add bounds to the layer's region
1020
1021        if (mShader) {
1022            mShader->updateTransforms(mCaches.currentProgram, mModelView, *mSnapshot);
1023        }
1024
1025        glDrawArrays(drawMode, 0, elementsCount);
1026    }
1027
1028    if (isAA) {
1029        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
1030    }
1031}
1032
1033void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1034    // No need to check against the clip, we fill the clip region
1035    if (mSnapshot->invisible) return;
1036
1037    Rect& clip(*mSnapshot->clipRect);
1038    clip.snapToPixelBoundaries();
1039    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
1040}
1041
1042void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
1043    if (quickReject(left, top, right, bottom)) {
1044        return;
1045    }
1046
1047    SkXfermode::Mode mode;
1048    if (!mCaches.extensions.hasFramebufferFetch()) {
1049        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
1050        if (!isMode) {
1051            // Assume SRC_OVER
1052            mode = SkXfermode::kSrcOver_Mode;
1053        }
1054    } else {
1055        mode = getXfermode(p->getXfermode());
1056    }
1057
1058    // Skia draws using the color's alpha channel if < 255
1059    // Otherwise, it uses the paint's alpha
1060    int color = p->getColor();
1061    if (((color >> 24) & 0xff) == 255) {
1062        color |= p->getAlpha() << 24;
1063    }
1064
1065    drawColorRect(left, top, right, bottom, color, mode);
1066}
1067
1068void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
1069        float x, float y, SkPaint* paint) {
1070    if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
1071        return;
1072    }
1073    if (mSnapshot->invisible) return;
1074
1075    paint->setAntiAlias(true);
1076
1077    float length = -1.0f;
1078    switch (paint->getTextAlign()) {
1079        case SkPaint::kCenter_Align:
1080            length = paint->measureText(text, bytesCount);
1081            x -= length / 2.0f;
1082            break;
1083        case SkPaint::kRight_Align:
1084            length = paint->measureText(text, bytesCount);
1085            x -= length;
1086            break;
1087        default:
1088            break;
1089    }
1090
1091    int alpha;
1092    SkXfermode::Mode mode;
1093    getAlphaAndMode(paint, &alpha, &mode);
1094
1095    uint32_t color = paint->getColor();
1096    const GLfloat a = alpha / 255.0f;
1097    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
1098    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
1099    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
1100
1101    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
1102    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
1103            paint->getTextSize());
1104
1105    setupDraw();
1106
1107    if (mHasShadow) {
1108        glActiveTexture(gTextureUnits[0]);
1109        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
1110        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
1111                count, mShadowRadius);
1112        const AutoTexture autoCleanup(shadow);
1113
1114        setupShadow(shadow, x, y, mode, a);
1115
1116        // Draw the mesh
1117        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1118        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
1119    }
1120
1121    GLuint textureUnit = 0;
1122    glActiveTexture(gTextureUnits[textureUnit]);
1123
1124    // Assume that the modelView matrix does not force scales, rotates, etc.
1125    const bool linearFilter = mSnapshot->transform->changesBounds();
1126
1127    // Dimensions are set to (0,0), the layer (if any) won't be dirtied
1128    setupTextureAlpha8(fontRenderer.getTexture(linearFilter), 0, 0, textureUnit,
1129            x, y, r, g, b, a, mode, false, true, NULL, NULL);
1130
1131    const Rect& clip = mSnapshot->getLocalClip();
1132    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
1133
1134#if RENDER_LAYERS_AS_REGIONS
1135    bool hasLayer = (mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region;
1136#else
1137    bool hasLayer = false;
1138#endif
1139
1140    mCaches.unbindMeshBuffer();
1141    if (fontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y,
1142            hasLayer ? &bounds : NULL)) {
1143#if RENDER_LAYERS_AS_REGIONS
1144        if (hasLayer) {
1145            mSnapshot->transform->mapRect(bounds);
1146            bounds.intersect(*mSnapshot->clipRect);
1147            bounds.snapToPixelBoundaries();
1148
1149            android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1150            mSnapshot->region->orSelf(dirty);
1151        }
1152#endif
1153    }
1154
1155    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1156    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
1157
1158    drawTextDecorations(text, bytesCount, length, x, y, paint);
1159}
1160
1161void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
1162    if (mSnapshot->invisible) return;
1163
1164    GLuint textureUnit = 0;
1165    glActiveTexture(gTextureUnits[textureUnit]);
1166
1167    const PathTexture* texture = mCaches.pathCache.get(path, paint);
1168    if (!texture) return;
1169    const AutoTexture autoCleanup(texture);
1170
1171    const float x = texture->left - texture->offset;
1172    const float y = texture->top - texture->offset;
1173
1174    if (quickReject(x, y, x + texture->width, y + texture->height)) {
1175        return;
1176    }
1177
1178    int alpha;
1179    SkXfermode::Mode mode;
1180    getAlphaAndMode(paint, &alpha, &mode);
1181
1182    uint32_t color = paint->getColor();
1183    const GLfloat a = alpha / 255.0f;
1184    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
1185    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
1186    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
1187
1188    setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true);
1189
1190    setupDraw();
1191
1192    // Draw the mesh
1193    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1194    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
1195}
1196
1197///////////////////////////////////////////////////////////////////////////////
1198// Shaders
1199///////////////////////////////////////////////////////////////////////////////
1200
1201void OpenGLRenderer::resetShader() {
1202    mShader = NULL;
1203}
1204
1205void OpenGLRenderer::setupShader(SkiaShader* shader) {
1206    mShader = shader;
1207    if (mShader) {
1208        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
1209    }
1210}
1211
1212///////////////////////////////////////////////////////////////////////////////
1213// Color filters
1214///////////////////////////////////////////////////////////////////////////////
1215
1216void OpenGLRenderer::resetColorFilter() {
1217    mColorFilter = NULL;
1218}
1219
1220void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
1221    mColorFilter = filter;
1222}
1223
1224///////////////////////////////////////////////////////////////////////////////
1225// Drop shadow
1226///////////////////////////////////////////////////////////////////////////////
1227
1228void OpenGLRenderer::resetShadow() {
1229    mHasShadow = false;
1230}
1231
1232void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
1233    mHasShadow = true;
1234    mShadowRadius = radius;
1235    mShadowDx = dx;
1236    mShadowDy = dy;
1237    mShadowColor = color;
1238}
1239
1240///////////////////////////////////////////////////////////////////////////////
1241// Drawing implementation
1242///////////////////////////////////////////////////////////////////////////////
1243
1244void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y,
1245        SkXfermode::Mode mode, float alpha) {
1246    const float sx = x - texture->left + mShadowDx;
1247    const float sy = y - texture->top + mShadowDy;
1248
1249    const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
1250    const GLfloat a = shadowAlpha < 255 ? shadowAlpha / 255.0f : alpha;
1251    const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f;
1252    const GLfloat g = a * ((mShadowColor >>  8) & 0xFF) / 255.0f;
1253    const GLfloat b = a * ((mShadowColor      ) & 0xFF) / 255.0f;
1254
1255    GLuint textureUnit = 0;
1256    setupTextureAlpha8(texture, textureUnit, sx, sy, r, g, b, a, mode, true, false);
1257}
1258
1259void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit,
1260        float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode,
1261        bool transforms, bool applyFilters) {
1262    setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit,
1263            x, y, r, g, b, a, mode, transforms, applyFilters,
1264            (GLvoid*) 0, (GLvoid*) gMeshTextureOffset);
1265}
1266
1267void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
1268        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
1269        SkXfermode::Mode mode, bool transforms, bool applyFilters) {
1270    setupTextureAlpha8(texture, width, height, textureUnit, x, y, r, g, b, a, mode,
1271            transforms, applyFilters, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset);
1272}
1273
1274void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
1275        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
1276        SkXfermode::Mode mode, bool transforms, bool applyFilters,
1277        GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1278     // Describe the required shaders
1279     ProgramDescription description;
1280     description.hasTexture = true;
1281     description.hasAlpha8Texture = true;
1282     const bool setColor = description.setAlpha8Color(r, g, b, a);
1283
1284     if (applyFilters) {
1285         if (mShader) {
1286             mShader->describe(description, mCaches.extensions);
1287         }
1288         if (mColorFilter) {
1289             mColorFilter->describe(description, mCaches.extensions);
1290         }
1291     }
1292
1293     // Setup the blending mode
1294     chooseBlending(true, mode, description);
1295
1296     // Build and use the appropriate shader
1297     useProgram(mCaches.programCache.get(description));
1298
1299     bindTexture(texture);
1300     glUniform1i(mCaches.currentProgram->getUniform("sampler"), textureUnit);
1301
1302     int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1303     glEnableVertexAttribArray(texCoordsSlot);
1304
1305     if (texCoords) {
1306         // Setup attributes
1307         if (!vertices) {
1308             mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1309         } else {
1310             mCaches.unbindMeshBuffer();
1311         }
1312         glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1313                 gMeshStride, vertices);
1314         glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1315     }
1316
1317     // Setup uniforms
1318     if (transforms) {
1319         mModelView.loadTranslate(x, y, 0.0f);
1320         mModelView.scale(width, height, 1.0f);
1321     } else {
1322         mModelView.loadIdentity();
1323     }
1324
1325     mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1326     if (width > 0 && height > 0) {
1327         dirtyLayer(x, y, x + width, y + height, *mSnapshot->transform);
1328     }
1329
1330     if (setColor) {
1331         mCaches.currentProgram->setColor(r, g, b, a);
1332     }
1333
1334     textureUnit++;
1335     if (applyFilters) {
1336         // Setup attributes and uniforms required by the shaders
1337         if (mShader) {
1338             mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1339         }
1340         if (mColorFilter) {
1341             mColorFilter->setupProgram(mCaches.currentProgram);
1342         }
1343     }
1344}
1345
1346// Same values used by Skia
1347#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
1348#define kStdUnderline_Offset    (1.0f / 9.0f)
1349#define kStdUnderline_Thickness (1.0f / 18.0f)
1350
1351void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
1352        float x, float y, SkPaint* paint) {
1353    // Handle underline and strike-through
1354    uint32_t flags = paint->getFlags();
1355    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
1356        float underlineWidth = length;
1357        // If length is > 0.0f, we already measured the text for the text alignment
1358        if (length <= 0.0f) {
1359            underlineWidth = paint->measureText(text, bytesCount);
1360        }
1361
1362        float offsetX = 0;
1363        switch (paint->getTextAlign()) {
1364            case SkPaint::kCenter_Align:
1365                offsetX = underlineWidth * 0.5f;
1366                break;
1367            case SkPaint::kRight_Align:
1368                offsetX = underlineWidth;
1369                break;
1370            default:
1371                break;
1372        }
1373
1374        if (underlineWidth > 0.0f) {
1375            const float textSize = paint->getTextSize();
1376            const float strokeWidth = textSize * kStdUnderline_Thickness;
1377
1378            const float left = x - offsetX;
1379            float top = 0.0f;
1380
1381            const int pointsCount = 4 * (flags & SkPaint::kStrikeThruText_Flag ? 2 : 1);
1382            float points[pointsCount];
1383            int currentPoint = 0;
1384
1385            if (flags & SkPaint::kUnderlineText_Flag) {
1386                top = y + textSize * kStdUnderline_Offset;
1387                points[currentPoint++] = left;
1388                points[currentPoint++] = top;
1389                points[currentPoint++] = left + underlineWidth;
1390                points[currentPoint++] = top;
1391            }
1392
1393            if (flags & SkPaint::kStrikeThruText_Flag) {
1394                top = y + textSize * kStdStrikeThru_Offset;
1395                points[currentPoint++] = left;
1396                points[currentPoint++] = top;
1397                points[currentPoint++] = left + underlineWidth;
1398                points[currentPoint++] = top;
1399            }
1400
1401            SkPaint linesPaint(*paint);
1402            linesPaint.setStrokeWidth(strokeWidth);
1403
1404            drawLines(&points[0], pointsCount, &linesPaint);
1405        }
1406    }
1407}
1408
1409void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
1410        int color, SkXfermode::Mode mode, bool ignoreTransform) {
1411    setupDraw();
1412
1413    // If a shader is set, preserve only the alpha
1414    if (mShader) {
1415        color |= 0x00ffffff;
1416    }
1417
1418    // Render using pre-multiplied alpha
1419    const int alpha = (color >> 24) & 0xFF;
1420    const GLfloat a = alpha / 255.0f;
1421    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
1422    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
1423    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
1424
1425    setupColorRect(left, top, right, bottom, r, g, b, a, mode, ignoreTransform);
1426
1427    // Draw the mesh
1428    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1429}
1430
1431void OpenGLRenderer::setupColorRect(float left, float top, float right, float bottom,
1432        float r, float g, float b, float a, SkXfermode::Mode mode,
1433        bool ignoreTransform, bool ignoreMatrix) {
1434    GLuint textureUnit = 0;
1435
1436    // Describe the required shaders
1437    ProgramDescription description;
1438    const bool setColor = description.setColor(r, g, b, a);
1439
1440    if (mShader) {
1441        mShader->describe(description, mCaches.extensions);
1442    }
1443    if (mColorFilter) {
1444        mColorFilter->describe(description, mCaches.extensions);
1445    }
1446
1447    // Setup the blending mode
1448    chooseBlending(a < 1.0f || (mShader && mShader->blend()), mode, description);
1449
1450    // Build and use the appropriate shader
1451    useProgram(mCaches.programCache.get(description));
1452
1453    // Setup attributes
1454    mCaches.bindMeshBuffer();
1455    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1456            gMeshStride, 0);
1457
1458    if (!ignoreMatrix) {
1459        // Setup uniforms
1460        mModelView.loadTranslate(left, top, 0.0f);
1461        mModelView.scale(right - left, bottom - top, 1.0f);
1462        if (!ignoreTransform) {
1463            mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1464            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1465        } else {
1466            mat4 identity;
1467            mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity);
1468            dirtyLayer(left, top, right, bottom);
1469        }
1470    }
1471    if (!mShader || (mShader && setColor)) {
1472        mCaches.currentProgram->setColor(r, g, b, a);
1473    }
1474
1475    // Setup attributes and uniforms required by the shaders
1476    if (mShader) {
1477        if (ignoreMatrix) mModelView.loadIdentity();
1478        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1479    }
1480    if (mColorFilter) {
1481        mColorFilter->setupProgram(mCaches.currentProgram);
1482    }
1483}
1484
1485void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1486        Texture* texture, SkPaint* paint) {
1487    int alpha;
1488    SkXfermode::Mode mode;
1489    getAlphaAndMode(paint, &alpha, &mode);
1490
1491    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1492
1493    drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
1494            texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
1495            GL_TRIANGLE_STRIP, gMeshCount);
1496}
1497
1498void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1499        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
1500    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
1501            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
1502}
1503
1504void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
1505        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
1506        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
1507        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
1508    setupDraw();
1509
1510    ProgramDescription description;
1511    description.hasTexture = true;
1512    const bool setColor = description.setColor(alpha, alpha, alpha, alpha);
1513    if (mColorFilter) {
1514        mColorFilter->describe(description, mCaches.extensions);
1515    }
1516
1517    mModelView.loadTranslate(left, top, 0.0f);
1518    if (!ignoreScale) {
1519        mModelView.scale(right - left, bottom - top, 1.0f);
1520    }
1521
1522    chooseBlending(blend || alpha < 1.0f, mode, description, swapSrcDst);
1523
1524    useProgram(mCaches.programCache.get(description));
1525    if (!ignoreTransform) {
1526        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1527        if (dirty) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1528    } else {
1529        mat4 identity;
1530        mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity);
1531        if (dirty) dirtyLayer(left, top, right, bottom);
1532    }
1533
1534    // Texture
1535    bindTexture(texture);
1536    glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
1537
1538    // Always premultiplied
1539    if (setColor) {
1540        mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha);
1541    }
1542
1543    // Mesh
1544    int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1545    glEnableVertexAttribArray(texCoordsSlot);
1546
1547    if (!vertices) {
1548        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1549    } else {
1550        mCaches.unbindMeshBuffer();
1551    }
1552    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1553            gMeshStride, vertices);
1554    glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1555
1556    // Color filter
1557    if (mColorFilter) {
1558        mColorFilter->setupProgram(mCaches.currentProgram);
1559    }
1560
1561    glDrawArrays(drawMode, 0, elementsCount);
1562    glDisableVertexAttribArray(texCoordsSlot);
1563}
1564
1565void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
1566        ProgramDescription& description, bool swapSrcDst) {
1567    blend = blend || mode != SkXfermode::kSrcOver_Mode;
1568    if (blend) {
1569        if (mode < SkXfermode::kPlus_Mode) {
1570            if (!mCaches.blend) {
1571                glEnable(GL_BLEND);
1572            }
1573
1574            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
1575            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
1576
1577            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
1578                glBlendFunc(sourceMode, destMode);
1579                mCaches.lastSrcMode = sourceMode;
1580                mCaches.lastDstMode = destMode;
1581            }
1582        } else {
1583            // These blend modes are not supported by OpenGL directly and have
1584            // to be implemented using shaders. Since the shader will perform
1585            // the blending, turn blending off here
1586            if (mCaches.extensions.hasFramebufferFetch()) {
1587                description.framebufferMode = mode;
1588                description.swapSrcDst = swapSrcDst;
1589            }
1590
1591            if (mCaches.blend) {
1592                glDisable(GL_BLEND);
1593            }
1594            blend = false;
1595        }
1596    } else if (mCaches.blend) {
1597        glDisable(GL_BLEND);
1598    }
1599    mCaches.blend = blend;
1600}
1601
1602bool OpenGLRenderer::useProgram(Program* program) {
1603    if (!program->isInUse()) {
1604        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1605        program->use();
1606        mCaches.currentProgram = program;
1607        return false;
1608    }
1609    return true;
1610}
1611
1612void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1613    TextureVertex* v = &mMeshVertices[0];
1614    TextureVertex::setUV(v++, u1, v1);
1615    TextureVertex::setUV(v++, u2, v1);
1616    TextureVertex::setUV(v++, u1, v2);
1617    TextureVertex::setUV(v++, u2, v2);
1618}
1619
1620void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1621    if (paint) {
1622        if (!mCaches.extensions.hasFramebufferFetch()) {
1623            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1624            if (!isMode) {
1625                // Assume SRC_OVER
1626                *mode = SkXfermode::kSrcOver_Mode;
1627            }
1628        } else {
1629            *mode = getXfermode(paint->getXfermode());
1630        }
1631
1632        // Skia draws using the color's alpha channel if < 255
1633        // Otherwise, it uses the paint's alpha
1634        int color = paint->getColor();
1635        *alpha = (color >> 24) & 0xFF;
1636        if (*alpha == 255) {
1637            *alpha = paint->getAlpha();
1638        }
1639    } else {
1640        *mode = SkXfermode::kSrcOver_Mode;
1641        *alpha = 255;
1642    }
1643}
1644
1645SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1646    if (mode == NULL) {
1647        return SkXfermode::kSrcOver_Mode;
1648    }
1649    return mode->fMode;
1650}
1651
1652void OpenGLRenderer::setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT) {
1653    bool bound = false;
1654    if (wrapS != texture->wrapS) {
1655        glBindTexture(GL_TEXTURE_2D, texture->id);
1656        bound = true;
1657        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1658        texture->wrapS = wrapS;
1659    }
1660    if (wrapT != texture->wrapT) {
1661        if (!bound) {
1662            glBindTexture(GL_TEXTURE_2D, texture->id);
1663        }
1664        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1665        texture->wrapT = wrapT;
1666    }
1667}
1668
1669}; // namespace uirenderer
1670}; // namespace android
1671