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