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