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