OpenGLRenderer.cpp revision db8c9a6a4d9bf8c39f834b25611926caf21380f6
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 <SkPathMeasure.h>
25#include <SkTypeface.h>
26
27#include <utils/Log.h>
28#include <utils/StopWatch.h>
29
30#include <private/hwui/DrawGlInfo.h>
31
32#include <ui/Rect.h>
33
34#include "OpenGLRenderer.h"
35#include "DisplayListRenderer.h"
36#include "Vector.h"
37
38namespace android {
39namespace uirenderer {
40
41///////////////////////////////////////////////////////////////////////////////
42// Defines
43///////////////////////////////////////////////////////////////////////////////
44
45#define RAD_TO_DEG (180.0f / 3.14159265f)
46#define MIN_ANGLE 0.001f
47
48// TODO: This should be set in properties
49#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH)
50
51#define FILTER(paint) (paint && paint->isFilterBitmap() ? GL_LINEAR : GL_NEAREST)
52
53///////////////////////////////////////////////////////////////////////////////
54// Globals
55///////////////////////////////////////////////////////////////////////////////
56
57/**
58 * Structure mapping Skia xfermodes to OpenGL blending factors.
59 */
60struct Blender {
61    SkXfermode::Mode mode;
62    GLenum src;
63    GLenum dst;
64}; // struct Blender
65
66// In this array, the index of each Blender equals the value of the first
67// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
68static const Blender gBlends[] = {
69    { SkXfermode::kClear_Mode,    GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA },
70    { SkXfermode::kSrc_Mode,      GL_ONE,                 GL_ZERO },
71    { SkXfermode::kDst_Mode,      GL_ZERO,                GL_ONE },
72    { SkXfermode::kSrcOver_Mode,  GL_ONE,                 GL_ONE_MINUS_SRC_ALPHA },
73    { SkXfermode::kDstOver_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_ONE },
74    { SkXfermode::kSrcIn_Mode,    GL_DST_ALPHA,           GL_ZERO },
75    { SkXfermode::kDstIn_Mode,    GL_ZERO,                GL_SRC_ALPHA },
76    { SkXfermode::kSrcOut_Mode,   GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
77    { SkXfermode::kDstOut_Mode,   GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA },
78    { SkXfermode::kSrcATop_Mode,  GL_DST_ALPHA,           GL_ONE_MINUS_SRC_ALPHA },
79    { SkXfermode::kDstATop_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA },
80    { SkXfermode::kXor_Mode,      GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
81    { SkXfermode::kPlus_Mode,     GL_ONE,                 GL_ONE },
82    { SkXfermode::kMultiply_Mode, GL_ZERO,                GL_SRC_COLOR },
83    { SkXfermode::kScreen_Mode,   GL_ONE,                 GL_ONE_MINUS_SRC_COLOR }
84};
85
86// This array contains the swapped version of each SkXfermode. For instance
87// this array's SrcOver blending mode is actually DstOver. You can refer to
88// createLayer() for more information on the purpose of this array.
89static const Blender gBlendsSwap[] = {
90    { SkXfermode::kClear_Mode,    GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
91    { SkXfermode::kSrc_Mode,      GL_ZERO,                GL_ONE },
92    { SkXfermode::kDst_Mode,      GL_ONE,                 GL_ZERO },
93    { SkXfermode::kSrcOver_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_ONE },
94    { SkXfermode::kDstOver_Mode,  GL_ONE,                 GL_ONE_MINUS_SRC_ALPHA },
95    { SkXfermode::kSrcIn_Mode,    GL_ZERO,                GL_SRC_ALPHA },
96    { SkXfermode::kDstIn_Mode,    GL_DST_ALPHA,           GL_ZERO },
97    { SkXfermode::kSrcOut_Mode,   GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA },
98    { SkXfermode::kDstOut_Mode,   GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
99    { SkXfermode::kSrcATop_Mode,  GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA },
100    { SkXfermode::kDstATop_Mode,  GL_DST_ALPHA,           GL_ONE_MINUS_SRC_ALPHA },
101    { SkXfermode::kXor_Mode,      GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
102    { SkXfermode::kPlus_Mode,     GL_ONE,                 GL_ONE },
103    { SkXfermode::kMultiply_Mode, GL_DST_COLOR,           GL_ZERO },
104    { SkXfermode::kScreen_Mode,   GL_ONE_MINUS_DST_COLOR, GL_ONE }
105};
106
107///////////////////////////////////////////////////////////////////////////////
108// Constructors/destructor
109///////////////////////////////////////////////////////////////////////////////
110
111OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
112    mShader = NULL;
113    mColorFilter = NULL;
114    mHasShadow = false;
115    mHasDrawFilter = false;
116
117    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
118
119    mFirstSnapshot = new Snapshot;
120}
121
122OpenGLRenderer::~OpenGLRenderer() {
123    // The context has already been destroyed at this point, do not call
124    // GL APIs. All GL state should be kept in Caches.h
125}
126
127///////////////////////////////////////////////////////////////////////////////
128// Debug
129///////////////////////////////////////////////////////////////////////////////
130
131void OpenGLRenderer::startMark(const char* name) const {
132    mCaches.startMark(0, name);
133}
134
135void OpenGLRenderer::endMark() const {
136    mCaches.endMark();
137}
138
139///////////////////////////////////////////////////////////////////////////////
140// Setup
141///////////////////////////////////////////////////////////////////////////////
142
143uint32_t OpenGLRenderer::getStencilSize() {
144    return STENCIL_BUFFER_SIZE;
145}
146
147void OpenGLRenderer::setViewport(int width, int height) {
148    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
149
150    mWidth = width;
151    mHeight = height;
152
153    mFirstSnapshot->height = height;
154    mFirstSnapshot->viewport.set(0, 0, width, height);
155
156    glDisable(GL_DITHER);
157    glEnable(GL_SCISSOR_TEST);
158    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
159
160    glEnableVertexAttribArray(Program::kBindingPosition);
161}
162
163void OpenGLRenderer::prepare(bool opaque) {
164    prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
165}
166
167void OpenGLRenderer::prepareDirty(float left, float top, float right, float bottom, bool opaque) {
168    mCaches.clearGarbage();
169    mFunctors.clear();
170
171    mSnapshot = new Snapshot(mFirstSnapshot,
172            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
173    mSnapshot->fbo = getTargetFbo();
174    mSaveCount = 1;
175
176    glViewport(0, 0, mWidth, mHeight);
177    mCaches.setScissor(left, mSnapshot->height - bottom, right - left, bottom - top);
178
179    mSnapshot->setClip(left, top, right, bottom);
180    mDirtyClip = false;
181
182    if (!opaque) {
183        glClear(GL_COLOR_BUFFER_BIT);
184    }
185}
186
187void OpenGLRenderer::finish() {
188#if DEBUG_OPENGL
189    GLenum status = GL_NO_ERROR;
190    while ((status = glGetError()) != GL_NO_ERROR) {
191        ALOGD("GL error from OpenGLRenderer: 0x%x", status);
192        switch (status) {
193            case GL_OUT_OF_MEMORY:
194                ALOGE("  OpenGLRenderer is out of memory!");
195                break;
196        }
197    }
198#endif
199#if DEBUG_MEMORY_USAGE
200    mCaches.dumpMemoryUsage();
201#else
202    if (mCaches.getDebugLevel() & kDebugMemory) {
203        mCaches.dumpMemoryUsage();
204    }
205#endif
206}
207
208void OpenGLRenderer::interrupt() {
209    if (mCaches.currentProgram) {
210        if (mCaches.currentProgram->isInUse()) {
211            mCaches.currentProgram->remove();
212            mCaches.currentProgram = NULL;
213        }
214    }
215    mCaches.unbindMeshBuffer();
216    mCaches.unbindIndicesBuffer();
217    mCaches.resetVertexPointers();
218    mCaches.disbaleTexCoordsVertexArray();
219}
220
221void OpenGLRenderer::resume() {
222    sp<Snapshot> snapshot = (mSnapshot != NULL) ? mSnapshot : mFirstSnapshot;
223
224    glViewport(0, 0, snapshot->viewport.getWidth(), snapshot->viewport.getHeight());
225    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
226
227    glEnable(GL_SCISSOR_TEST);
228    mCaches.resetScissor();
229    dirtyClip();
230
231    mCaches.activeTexture(0);
232    glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo);
233
234    mCaches.blend = true;
235    glEnable(GL_BLEND);
236    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
237    glBlendEquation(GL_FUNC_ADD);
238}
239
240status_t OpenGLRenderer::invokeFunctors(Rect& dirty) {
241    status_t result = DrawGlInfo::kStatusDone;
242
243    Vector<Functor*> functors(mFunctors);
244    mFunctors.clear();
245
246    DrawGlInfo info;
247    info.clipLeft = 0;
248    info.clipTop = 0;
249    info.clipRight = 0;
250    info.clipBottom = 0;
251    info.isLayer = false;
252    memset(info.transform, 0, sizeof(float) * 16);
253
254    size_t count = functors.size();
255    for (size_t i = 0; i < count; i++) {
256        Functor* f = functors.itemAt(i);
257        result |= (*f)(DrawGlInfo::kModeProcess, &info);
258
259        if (result != DrawGlInfo::kStatusDone) {
260            Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
261            dirty.unionWith(localDirty);
262
263            if (result == DrawGlInfo::kStatusInvoke) {
264                mFunctors.push(f);
265            }
266        }
267    }
268
269    return result;
270}
271
272status_t OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) {
273    interrupt();
274    if (mDirtyClip) {
275        setScissorFromClip();
276    }
277
278    Rect clip(*mSnapshot->clipRect);
279    clip.snapToPixelBoundaries();
280
281#if RENDER_LAYERS_AS_REGIONS
282    // Since we don't know what the functor will draw, let's dirty
283    // tne entire clip region
284    if (hasLayer()) {
285        dirtyLayerUnchecked(clip, getRegion());
286    }
287#endif
288
289    DrawGlInfo info;
290    info.clipLeft = clip.left;
291    info.clipTop = clip.top;
292    info.clipRight = clip.right;
293    info.clipBottom = clip.bottom;
294    info.isLayer = hasLayer();
295    getSnapshot()->transform->copyTo(&info.transform[0]);
296
297    status_t result = (*functor)(DrawGlInfo::kModeDraw, &info);
298
299    if (result != DrawGlInfo::kStatusDone) {
300        Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
301        dirty.unionWith(localDirty);
302
303        if (result == DrawGlInfo::kStatusInvoke) {
304            mFunctors.push(functor);
305        }
306    }
307
308    resume();
309    return result;
310}
311
312///////////////////////////////////////////////////////////////////////////////
313// State management
314///////////////////////////////////////////////////////////////////////////////
315
316int OpenGLRenderer::getSaveCount() const {
317    return mSaveCount;
318}
319
320int OpenGLRenderer::save(int flags) {
321    return saveSnapshot(flags);
322}
323
324void OpenGLRenderer::restore() {
325    if (mSaveCount > 1) {
326        restoreSnapshot();
327    }
328}
329
330void OpenGLRenderer::restoreToCount(int saveCount) {
331    if (saveCount < 1) saveCount = 1;
332
333    while (mSaveCount > saveCount) {
334        restoreSnapshot();
335    }
336}
337
338int OpenGLRenderer::saveSnapshot(int flags) {
339    mSnapshot = new Snapshot(mSnapshot, flags);
340    return mSaveCount++;
341}
342
343bool OpenGLRenderer::restoreSnapshot() {
344    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
345    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
346    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
347
348    sp<Snapshot> current = mSnapshot;
349    sp<Snapshot> previous = mSnapshot->previous;
350
351    if (restoreOrtho) {
352        Rect& r = previous->viewport;
353        glViewport(r.left, r.top, r.right, r.bottom);
354        mOrthoMatrix.load(current->orthoMatrix);
355    }
356
357    mSaveCount--;
358    mSnapshot = previous;
359
360    if (restoreClip) {
361        dirtyClip();
362    }
363
364    if (restoreLayer) {
365        composeLayer(current, previous);
366    }
367
368    return restoreClip;
369}
370
371///////////////////////////////////////////////////////////////////////////////
372// Layers
373///////////////////////////////////////////////////////////////////////////////
374
375int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
376        SkPaint* p, int flags) {
377    const GLuint previousFbo = mSnapshot->fbo;
378    const int count = saveSnapshot(flags);
379
380    if (!mSnapshot->isIgnored()) {
381        int alpha = 255;
382        SkXfermode::Mode mode;
383
384        if (p) {
385            alpha = p->getAlpha();
386            if (!mCaches.extensions.hasFramebufferFetch()) {
387                const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
388                if (!isMode) {
389                    // Assume SRC_OVER
390                    mode = SkXfermode::kSrcOver_Mode;
391                }
392            } else {
393                mode = getXfermode(p->getXfermode());
394            }
395        } else {
396            mode = SkXfermode::kSrcOver_Mode;
397        }
398
399        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
400    }
401
402    return count;
403}
404
405int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
406        int alpha, int flags) {
407    if (alpha >= 255 - ALPHA_THRESHOLD) {
408        return saveLayer(left, top, right, bottom, NULL, flags);
409    } else {
410        SkPaint paint;
411        paint.setAlpha(alpha);
412        return saveLayer(left, top, right, bottom, &paint, flags);
413    }
414}
415
416/**
417 * Layers are viewed by Skia are slightly different than layers in image editing
418 * programs (for instance.) When a layer is created, previously created layers
419 * and the frame buffer still receive every drawing command. For instance, if a
420 * layer is created and a shape intersecting the bounds of the layers and the
421 * framebuffer is draw, the shape will be drawn on both (unless the layer was
422 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
423 *
424 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
425 * texture. Unfortunately, this is inefficient as it requires every primitive to
426 * be drawn n + 1 times, where n is the number of active layers. In practice this
427 * means, for every primitive:
428 *   - Switch active frame buffer
429 *   - Change viewport, clip and projection matrix
430 *   - Issue the drawing
431 *
432 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
433 * To avoid this, layers are implemented in a different way here, at least in the
434 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
435 * is set. When this flag is set we can redirect all drawing operations into a
436 * single FBO.
437 *
438 * This implementation relies on the frame buffer being at least RGBA 8888. When
439 * a layer is created, only a texture is created, not an FBO. The content of the
440 * frame buffer contained within the layer's bounds is copied into this texture
441 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
442 * buffer and drawing continues as normal. This technique therefore treats the
443 * frame buffer as a scratch buffer for the layers.
444 *
445 * To compose the layers back onto the frame buffer, each layer texture
446 * (containing the original frame buffer data) is drawn as a simple quad over
447 * the frame buffer. The trick is that the quad is set as the composition
448 * destination in the blending equation, and the frame buffer becomes the source
449 * of the composition.
450 *
451 * Drawing layers with an alpha value requires an extra step before composition.
452 * An empty quad is drawn over the layer's region in the frame buffer. This quad
453 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
454 * quad is used to multiply the colors in the frame buffer. This is achieved by
455 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
456 * GL_ZERO, GL_SRC_ALPHA.
457 *
458 * Because glCopyTexImage2D() can be slow, an alternative implementation might
459 * be use to draw a single clipped layer. The implementation described above
460 * is correct in every case.
461 *
462 * (1) The frame buffer is actually not cleared right away. To allow the GPU
463 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
464 *     buffer is left untouched until the first drawing operation. Only when
465 *     something actually gets drawn are the layers regions cleared.
466 */
467bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
468        float right, float bottom, int alpha, SkXfermode::Mode mode,
469        int flags, GLuint previousFbo) {
470    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
471    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
472
473    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
474
475    // Window coordinates of the layer
476    Rect bounds(left, top, right, bottom);
477    if (!fboLayer) {
478        mSnapshot->transform->mapRect(bounds);
479
480        // Layers only make sense if they are in the framebuffer's bounds
481        if (bounds.intersect(*snapshot->clipRect)) {
482            // We cannot work with sub-pixels in this case
483            bounds.snapToPixelBoundaries();
484
485            // When the layer is not an FBO, we may use glCopyTexImage so we
486            // need to make sure the layer does not extend outside the bounds
487            // of the framebuffer
488            if (!bounds.intersect(snapshot->previous->viewport)) {
489                bounds.setEmpty();
490            }
491        } else {
492            bounds.setEmpty();
493        }
494    }
495
496    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
497            bounds.getHeight() > mCaches.maxTextureSize) {
498        snapshot->empty = fboLayer;
499    } else {
500        snapshot->invisible = snapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
501    }
502
503    // Bail out if we won't draw in this snapshot
504    if (snapshot->invisible || snapshot->empty) {
505        return false;
506    }
507
508    mCaches.activeTexture(0);
509    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
510    if (!layer) {
511        return false;
512    }
513
514    layer->setAlpha(alpha, mode);
515    layer->layer.set(bounds);
516    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()),
517            bounds.getWidth() / float(layer->getWidth()), 0.0f);
518    layer->setColorFilter(mColorFilter);
519
520    // Save the layer in the snapshot
521    snapshot->flags |= Snapshot::kFlagIsLayer;
522    snapshot->layer = layer;
523
524    if (fboLayer) {
525        return createFboLayer(layer, bounds, snapshot, previousFbo);
526    } else {
527        // Copy the framebuffer into the layer
528        layer->bindTexture();
529        if (!bounds.isEmpty()) {
530            if (layer->isEmpty()) {
531                glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
532                        bounds.left, snapshot->height - bounds.bottom,
533                        layer->getWidth(), layer->getHeight(), 0);
534                layer->setEmpty(false);
535            } else {
536                glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
537                        snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
538            }
539
540            // Enqueue the buffer coordinates to clear the corresponding region later
541            mLayers.push(new Rect(bounds));
542        }
543    }
544
545    return true;
546}
547
548bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
549        GLuint previousFbo) {
550    layer->setFbo(mCaches.fboCache.get());
551
552#if RENDER_LAYERS_AS_REGIONS
553    snapshot->region = &snapshot->layer->region;
554    snapshot->flags |= Snapshot::kFlagFboTarget;
555#endif
556
557    Rect clip(bounds);
558    snapshot->transform->mapRect(clip);
559    clip.intersect(*snapshot->clipRect);
560    clip.snapToPixelBoundaries();
561    clip.intersect(snapshot->previous->viewport);
562
563    mat4 inverse;
564    inverse.loadInverse(*mSnapshot->transform);
565
566    inverse.mapRect(clip);
567    clip.snapToPixelBoundaries();
568    clip.intersect(bounds);
569    clip.translate(-bounds.left, -bounds.top);
570
571    snapshot->flags |= Snapshot::kFlagIsFboLayer;
572    snapshot->fbo = layer->getFbo();
573    snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
574    snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
575    snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
576    snapshot->height = bounds.getHeight();
577    snapshot->flags |= Snapshot::kFlagDirtyOrtho;
578    snapshot->orthoMatrix.load(mOrthoMatrix);
579
580    // Bind texture to FBO
581    glBindFramebuffer(GL_FRAMEBUFFER, layer->getFbo());
582    layer->bindTexture();
583
584    // Initialize the texture if needed
585    if (layer->isEmpty()) {
586        layer->allocateTexture(GL_RGBA, GL_UNSIGNED_BYTE);
587        layer->setEmpty(false);
588    }
589
590    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
591            layer->getTexture(), 0);
592
593#if DEBUG_LAYERS_AS_REGIONS
594    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
595    if (status != GL_FRAMEBUFFER_COMPLETE) {
596        ALOGE("Framebuffer incomplete (GL error code 0x%x)", status);
597
598        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
599        layer->deleteTexture();
600        mCaches.fboCache.put(layer->getFbo());
601
602        delete layer;
603
604        return false;
605    }
606#endif
607
608    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
609    mCaches.setScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
610            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
611    glClear(GL_COLOR_BUFFER_BIT);
612
613    dirtyClip();
614
615    // Change the ortho projection
616    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
617    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
618
619    return true;
620}
621
622/**
623 * Read the documentation of createLayer() before doing anything in this method.
624 */
625void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
626    if (!current->layer) {
627        ALOGE("Attempting to compose a layer that does not exist");
628        return;
629    }
630
631    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
632
633    if (fboLayer) {
634        // Unbind current FBO and restore previous one
635        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
636    }
637
638    Layer* layer = current->layer;
639    const Rect& rect = layer->layer;
640
641    if (!fboLayer && layer->getAlpha() < 255) {
642        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
643                layer->getAlpha() << 24, SkXfermode::kDstIn_Mode, true);
644        // Required below, composeLayerRect() will divide by 255
645        layer->setAlpha(255);
646    }
647
648    mCaches.unbindMeshBuffer();
649
650    mCaches.activeTexture(0);
651
652    // When the layer is stored in an FBO, we can save a bit of fillrate by
653    // drawing only the dirty region
654    if (fboLayer) {
655        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
656        if (layer->getColorFilter()) {
657            setupColorFilter(layer->getColorFilter());
658        }
659        composeLayerRegion(layer, rect);
660        if (layer->getColorFilter()) {
661            resetColorFilter();
662        }
663    } else if (!rect.isEmpty()) {
664        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
665        composeLayerRect(layer, rect, true);
666    }
667
668    if (fboLayer) {
669        // Note: No need to use glDiscardFramebufferEXT() since we never
670        //       create/compose layers that are not on screen with this
671        //       code path
672        // See LayerRenderer::destroyLayer(Layer*)
673
674        // Detach the texture from the FBO
675        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
676        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
677        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
678
679        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
680        mCaches.fboCache.put(current->fbo);
681        layer->setFbo(0);
682    }
683
684    dirtyClip();
685
686    // Failing to add the layer to the cache should happen only if the layer is too large
687    if (!mCaches.layerCache.put(layer)) {
688        LAYER_LOGD("Deleting layer");
689        layer->deleteTexture();
690        delete layer;
691    }
692}
693
694void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
695    float alpha = layer->getAlpha() / 255.0f;
696
697    mat4& transform = layer->getTransform();
698    if (!transform.isIdentity()) {
699        save(0);
700        mSnapshot->transform->multiply(transform);
701    }
702
703    setupDraw();
704    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
705        setupDrawWithTexture();
706    } else {
707        setupDrawWithExternalTexture();
708    }
709    setupDrawTextureTransform();
710    setupDrawColor(alpha, alpha, alpha, alpha);
711    setupDrawColorFilter();
712    setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode());
713    setupDrawProgram();
714    setupDrawPureColorUniforms();
715    setupDrawColorFilterUniforms();
716    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
717        setupDrawTexture(layer->getTexture());
718    } else {
719        setupDrawExternalTexture(layer->getTexture());
720    }
721    if (mSnapshot->transform->isPureTranslate() &&
722            layer->getWidth() == (uint32_t) rect.getWidth() &&
723            layer->getHeight() == (uint32_t) rect.getHeight()) {
724        const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
725        const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
726
727        layer->setFilter(GL_NEAREST);
728        setupDrawModelView(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
729    } else {
730        layer->setFilter(GL_LINEAR);
731        setupDrawModelView(rect.left, rect.top, rect.right, rect.bottom);
732    }
733    setupDrawTextureTransformUniforms(layer->getTexTransform());
734    setupDrawMesh(&mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
735
736    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
737
738    finishDrawTexture();
739
740    if (!transform.isIdentity()) {
741        restore();
742    }
743}
744
745void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
746    if (!layer->isTextureLayer()) {
747        const Rect& texCoords = layer->texCoords;
748        resetDrawTextureTexCoords(texCoords.left, texCoords.top,
749                texCoords.right, texCoords.bottom);
750
751        float x = rect.left;
752        float y = rect.top;
753        bool simpleTransform = mSnapshot->transform->isPureTranslate() &&
754                layer->getWidth() == (uint32_t) rect.getWidth() &&
755                layer->getHeight() == (uint32_t) rect.getHeight();
756
757        if (simpleTransform) {
758            // When we're swapping, the layer is already in screen coordinates
759            if (!swap) {
760                x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
761                y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
762            }
763
764            layer->setFilter(GL_NEAREST, true);
765        } else {
766            layer->setFilter(GL_LINEAR, true);
767        }
768
769        drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(),
770                layer->getTexture(), layer->getAlpha() / 255.0f,
771                layer->getMode(), layer->isBlend(),
772                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
773                GL_TRIANGLE_STRIP, gMeshCount, swap, swap || simpleTransform);
774
775        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
776    } else {
777        resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
778        drawTextureLayer(layer, rect);
779        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
780    }
781}
782
783void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
784#if RENDER_LAYERS_AS_REGIONS
785    if (layer->region.isRect()) {
786        layer->setRegionAsRect();
787
788        composeLayerRect(layer, layer->regionRect);
789
790        layer->region.clear();
791        return;
792    }
793
794    // TODO: See LayerRenderer.cpp::generateMesh() for important
795    //       information about this implementation
796    if (CC_LIKELY(!layer->region.isEmpty())) {
797        size_t count;
798        const android::Rect* rects = layer->region.getArray(&count);
799
800        const float alpha = layer->getAlpha() / 255.0f;
801        const float texX = 1.0f / float(layer->getWidth());
802        const float texY = 1.0f / float(layer->getHeight());
803        const float height = rect.getHeight();
804
805        TextureVertex* mesh = mCaches.getRegionMesh();
806        GLsizei numQuads = 0;
807
808        setupDraw();
809        setupDrawWithTexture();
810        setupDrawColor(alpha, alpha, alpha, alpha);
811        setupDrawColorFilter();
812        setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode(), false);
813        setupDrawProgram();
814        setupDrawDirtyRegionsDisabled();
815        setupDrawPureColorUniforms();
816        setupDrawColorFilterUniforms();
817        setupDrawTexture(layer->getTexture());
818        if (mSnapshot->transform->isPureTranslate()) {
819            const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
820            const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
821
822            layer->setFilter(GL_NEAREST);
823            setupDrawModelViewTranslate(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
824        } else {
825            layer->setFilter(GL_LINEAR);
826            setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
827        }
828        setupDrawMeshIndices(&mesh[0].position[0], &mesh[0].texture[0]);
829
830        for (size_t i = 0; i < count; i++) {
831            const android::Rect* r = &rects[i];
832
833            const float u1 = r->left * texX;
834            const float v1 = (height - r->top) * texY;
835            const float u2 = r->right * texX;
836            const float v2 = (height - r->bottom) * texY;
837
838            // TODO: Reject quads outside of the clip
839            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
840            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
841            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
842            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
843
844            numQuads++;
845
846            if (numQuads >= REGION_MESH_QUAD_COUNT) {
847                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
848                numQuads = 0;
849                mesh = mCaches.getRegionMesh();
850            }
851        }
852
853        if (numQuads > 0) {
854            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
855        }
856
857        finishDrawTexture();
858
859#if DEBUG_LAYERS_AS_REGIONS
860        drawRegionRects(layer->region);
861#endif
862
863        layer->region.clear();
864    }
865#else
866    composeLayerRect(layer, rect);
867#endif
868}
869
870void OpenGLRenderer::drawRegionRects(const Region& region) {
871#if DEBUG_LAYERS_AS_REGIONS
872    size_t count;
873    const android::Rect* rects = region.getArray(&count);
874
875    uint32_t colors[] = {
876            0x7fff0000, 0x7f00ff00,
877            0x7f0000ff, 0x7fff00ff,
878    };
879
880    int offset = 0;
881    int32_t top = rects[0].top;
882
883    for (size_t i = 0; i < count; i++) {
884        if (top != rects[i].top) {
885            offset ^= 0x2;
886            top = rects[i].top;
887        }
888
889        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
890        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
891                SkXfermode::kSrcOver_Mode);
892    }
893#endif
894}
895
896void OpenGLRenderer::dirtyLayer(const float left, const float top,
897        const float right, const float bottom, const mat4 transform) {
898#if RENDER_LAYERS_AS_REGIONS
899    if (hasLayer()) {
900        Rect bounds(left, top, right, bottom);
901        transform.mapRect(bounds);
902        dirtyLayerUnchecked(bounds, getRegion());
903    }
904#endif
905}
906
907void OpenGLRenderer::dirtyLayer(const float left, const float top,
908        const float right, const float bottom) {
909#if RENDER_LAYERS_AS_REGIONS
910    if (hasLayer()) {
911        Rect bounds(left, top, right, bottom);
912        dirtyLayerUnchecked(bounds, getRegion());
913    }
914#endif
915}
916
917void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
918#if RENDER_LAYERS_AS_REGIONS
919    if (bounds.intersect(*mSnapshot->clipRect)) {
920        bounds.snapToPixelBoundaries();
921        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
922        if (!dirty.isEmpty()) {
923            region->orSelf(dirty);
924        }
925    }
926#endif
927}
928
929void OpenGLRenderer::clearLayerRegions() {
930    const size_t count = mLayers.size();
931    if (count == 0) return;
932
933    if (!mSnapshot->isIgnored()) {
934        // Doing several glScissor/glClear here can negatively impact
935        // GPUs with a tiler architecture, instead we draw quads with
936        // the Clear blending mode
937
938        // The list contains bounds that have already been clipped
939        // against their initial clip rect, and the current clip
940        // is likely different so we need to disable clipping here
941        glDisable(GL_SCISSOR_TEST);
942
943        Vertex mesh[count * 6];
944        Vertex* vertex = mesh;
945
946        for (uint32_t i = 0; i < count; i++) {
947            Rect* bounds = mLayers.itemAt(i);
948
949            Vertex::set(vertex++, bounds->left, bounds->bottom);
950            Vertex::set(vertex++, bounds->left, bounds->top);
951            Vertex::set(vertex++, bounds->right, bounds->top);
952            Vertex::set(vertex++, bounds->left, bounds->bottom);
953            Vertex::set(vertex++, bounds->right, bounds->top);
954            Vertex::set(vertex++, bounds->right, bounds->bottom);
955
956            delete bounds;
957        }
958
959        setupDraw(false);
960        setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
961        setupDrawBlending(true, SkXfermode::kClear_Mode);
962        setupDrawProgram();
963        setupDrawPureColorUniforms();
964        setupDrawModelViewTranslate(0.0f, 0.0f, 0.0f, 0.0f, true);
965        setupDrawVertices(&mesh[0].position[0]);
966
967        glDrawArrays(GL_TRIANGLES, 0, count * 6);
968
969        glEnable(GL_SCISSOR_TEST);
970    } else {
971        for (uint32_t i = 0; i < count; i++) {
972            delete mLayers.itemAt(i);
973        }
974    }
975
976    mLayers.clear();
977}
978
979///////////////////////////////////////////////////////////////////////////////
980// Transforms
981///////////////////////////////////////////////////////////////////////////////
982
983void OpenGLRenderer::translate(float dx, float dy) {
984    mSnapshot->transform->translate(dx, dy, 0.0f);
985}
986
987void OpenGLRenderer::rotate(float degrees) {
988    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
989}
990
991void OpenGLRenderer::scale(float sx, float sy) {
992    mSnapshot->transform->scale(sx, sy, 1.0f);
993}
994
995void OpenGLRenderer::skew(float sx, float sy) {
996    mSnapshot->transform->skew(sx, sy);
997}
998
999void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
1000    if (matrix) {
1001        mSnapshot->transform->load(*matrix);
1002    } else {
1003        mSnapshot->transform->loadIdentity();
1004    }
1005}
1006
1007void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
1008    mSnapshot->transform->copyTo(*matrix);
1009}
1010
1011void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
1012    SkMatrix transform;
1013    mSnapshot->transform->copyTo(transform);
1014    transform.preConcat(*matrix);
1015    mSnapshot->transform->load(transform);
1016}
1017
1018///////////////////////////////////////////////////////////////////////////////
1019// Clipping
1020///////////////////////////////////////////////////////////////////////////////
1021
1022void OpenGLRenderer::setScissorFromClip() {
1023    Rect clip(*mSnapshot->clipRect);
1024    clip.snapToPixelBoundaries();
1025
1026    mCaches.setScissor(clip.left, mSnapshot->height - clip.bottom,
1027            clip.getWidth(), clip.getHeight());
1028
1029    mDirtyClip = false;
1030}
1031
1032const Rect& OpenGLRenderer::getClipBounds() {
1033    return mSnapshot->getLocalClip();
1034}
1035
1036bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
1037    if (mSnapshot->isIgnored()) {
1038        return true;
1039    }
1040
1041    Rect r(left, top, right, bottom);
1042    mSnapshot->transform->mapRect(r);
1043    r.snapToPixelBoundaries();
1044
1045    Rect clipRect(*mSnapshot->clipRect);
1046    clipRect.snapToPixelBoundaries();
1047
1048    return !clipRect.intersects(r);
1049}
1050
1051bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
1052    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
1053    if (clipped) {
1054        dirtyClip();
1055    }
1056    return !mSnapshot->clipRect->isEmpty();
1057}
1058
1059///////////////////////////////////////////////////////////////////////////////
1060// Drawing commands
1061///////////////////////////////////////////////////////////////////////////////
1062
1063void OpenGLRenderer::setupDraw(bool clear) {
1064    if (clear) clearLayerRegions();
1065    if (mDirtyClip) {
1066        setScissorFromClip();
1067    }
1068    mDescription.reset();
1069    mSetShaderColor = false;
1070    mColorSet = false;
1071    mColorA = mColorR = mColorG = mColorB = 0.0f;
1072    mTextureUnit = 0;
1073    mTrackDirtyRegions = true;
1074}
1075
1076void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1077    mDescription.hasTexture = true;
1078    mDescription.hasAlpha8Texture = isAlpha8;
1079}
1080
1081void OpenGLRenderer::setupDrawWithExternalTexture() {
1082    mDescription.hasExternalTexture = true;
1083}
1084
1085void OpenGLRenderer::setupDrawNoTexture() {
1086    mCaches.disbaleTexCoordsVertexArray();
1087}
1088
1089void OpenGLRenderer::setupDrawAALine() {
1090    mDescription.isAA = true;
1091}
1092
1093void OpenGLRenderer::setupDrawPoint(float pointSize) {
1094    mDescription.isPoint = true;
1095    mDescription.pointSize = pointSize;
1096}
1097
1098void OpenGLRenderer::setupDrawColor(int color) {
1099    setupDrawColor(color, (color >> 24) & 0xFF);
1100}
1101
1102void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1103    mColorA = alpha / 255.0f;
1104    mColorA *= mSnapshot->alpha;
1105    // Second divide of a by 255 is an optimization, allowing us to simply multiply
1106    // the rgb values by a instead of also dividing by 255
1107    const float a = mColorA / 255.0f;
1108    mColorR = a * ((color >> 16) & 0xFF);
1109    mColorG = a * ((color >>  8) & 0xFF);
1110    mColorB = a * ((color      ) & 0xFF);
1111    mColorSet = true;
1112    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
1113}
1114
1115void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1116    mColorA = alpha / 255.0f;
1117    // Double-divide of a by 255 is an optimization, allowing us to simply multiply
1118    // the rgb values by a instead of also dividing by 255
1119    const float a = mColorA / 255.0f;
1120    mColorR = a * ((color >> 16) & 0xFF);
1121    mColorG = a * ((color >>  8) & 0xFF);
1122    mColorB = a * ((color      ) & 0xFF);
1123    mColorSet = true;
1124    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
1125}
1126
1127void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1128    mColorA = a;
1129    mColorR = r;
1130    mColorG = g;
1131    mColorB = b;
1132    mColorSet = true;
1133    mSetShaderColor = mDescription.setColor(r, g, b, a);
1134}
1135
1136void OpenGLRenderer::setupDrawAlpha8Color(float r, float g, float b, float a) {
1137    mColorA = a;
1138    mColorR = r;
1139    mColorG = g;
1140    mColorB = b;
1141    mColorSet = true;
1142    mSetShaderColor = mDescription.setAlpha8Color(r, g, b, a);
1143}
1144
1145void OpenGLRenderer::setupDrawShader() {
1146    if (mShader) {
1147        mShader->describe(mDescription, mCaches.extensions);
1148    }
1149}
1150
1151void OpenGLRenderer::setupDrawColorFilter() {
1152    if (mColorFilter) {
1153        mColorFilter->describe(mDescription, mCaches.extensions);
1154    }
1155}
1156
1157void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1158    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1159        mColorA = 1.0f;
1160        mColorR = mColorG = mColorB = 0.0f;
1161        mSetShaderColor = mDescription.modulate = true;
1162    }
1163}
1164
1165void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
1166    // When the blending mode is kClear_Mode, we need to use a modulate color
1167    // argb=1,0,0,0
1168    accountForClear(mode);
1169    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1170            mDescription, swapSrcDst);
1171}
1172
1173void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
1174    // When the blending mode is kClear_Mode, we need to use a modulate color
1175    // argb=1,0,0,0
1176    accountForClear(mode);
1177    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1178            mDescription, swapSrcDst);
1179}
1180
1181void OpenGLRenderer::setupDrawProgram() {
1182    useProgram(mCaches.programCache.get(mDescription));
1183}
1184
1185void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1186    mTrackDirtyRegions = false;
1187}
1188
1189void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
1190        bool ignoreTransform) {
1191    mModelView.loadTranslate(left, top, 0.0f);
1192    if (!ignoreTransform) {
1193        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1194        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1195    } else {
1196        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1197        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
1198    }
1199}
1200
1201void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) {
1202    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform, offset);
1203}
1204
1205void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
1206        bool ignoreTransform, bool ignoreModelView) {
1207    if (!ignoreModelView) {
1208        mModelView.loadTranslate(left, top, 0.0f);
1209        mModelView.scale(right - left, bottom - top, 1.0f);
1210    } else {
1211        mModelView.loadIdentity();
1212    }
1213    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1214    if (!ignoreTransform) {
1215        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1216        if (mTrackDirtyRegions && dirty) {
1217            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1218        }
1219    } else {
1220        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1221        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
1222    }
1223}
1224
1225void OpenGLRenderer::setupDrawPointUniforms() {
1226    int slot = mCaches.currentProgram->getUniform("pointSize");
1227    glUniform1f(slot, mDescription.pointSize);
1228}
1229
1230void OpenGLRenderer::setupDrawColorUniforms() {
1231    if ((mColorSet && !mShader) || (mShader && mSetShaderColor)) {
1232        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1233    }
1234}
1235
1236void OpenGLRenderer::setupDrawPureColorUniforms() {
1237    if (mSetShaderColor) {
1238        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1239    }
1240}
1241
1242void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1243    if (mShader) {
1244        if (ignoreTransform) {
1245            mModelView.loadInverse(*mSnapshot->transform);
1246        }
1247        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
1248    }
1249}
1250
1251void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1252    if (mShader) {
1253        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
1254    }
1255}
1256
1257void OpenGLRenderer::setupDrawColorFilterUniforms() {
1258    if (mColorFilter) {
1259        mColorFilter->setupProgram(mCaches.currentProgram);
1260    }
1261}
1262
1263void OpenGLRenderer::setupDrawSimpleMesh() {
1264    bool force = mCaches.bindMeshBuffer();
1265    mCaches.bindPositionVertexPointer(force, mCaches.currentProgram->position, 0);
1266    mCaches.unbindIndicesBuffer();
1267}
1268
1269void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1270    bindTexture(texture);
1271    mTextureUnit++;
1272    mCaches.enableTexCoordsVertexArray();
1273}
1274
1275void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1276    bindExternalTexture(texture);
1277    mTextureUnit++;
1278    mCaches.enableTexCoordsVertexArray();
1279}
1280
1281void OpenGLRenderer::setupDrawTextureTransform() {
1282    mDescription.hasTextureTransform = true;
1283}
1284
1285void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1286    glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1287            GL_FALSE, &transform.data[0]);
1288}
1289
1290void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1291    bool force = false;
1292    if (!vertices) {
1293        force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1294    } else {
1295        force = mCaches.unbindMeshBuffer();
1296    }
1297
1298    mCaches.bindPositionVertexPointer(force, mCaches.currentProgram->position, vertices);
1299    if (mCaches.currentProgram->texCoords >= 0) {
1300        mCaches.bindTexCoordsVertexPointer(force, mCaches.currentProgram->texCoords, texCoords);
1301    }
1302
1303    mCaches.unbindIndicesBuffer();
1304}
1305
1306void OpenGLRenderer::setupDrawMeshIndices(GLvoid* vertices, GLvoid* texCoords) {
1307    bool force = mCaches.unbindMeshBuffer();
1308    mCaches.bindPositionVertexPointer(force, mCaches.currentProgram->position, vertices);
1309    if (mCaches.currentProgram->texCoords >= 0) {
1310        mCaches.bindTexCoordsVertexPointer(force, mCaches.currentProgram->texCoords, texCoords);
1311    }
1312}
1313
1314void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) {
1315    bool force = mCaches.unbindMeshBuffer();
1316    mCaches.bindPositionVertexPointer(force, mCaches.currentProgram->position,
1317            vertices, gVertexStride);
1318    mCaches.unbindIndicesBuffer();
1319}
1320
1321/**
1322 * Sets up the shader to draw an AA line. We draw AA lines with quads, where there is an
1323 * outer boundary that fades out to 0. The variables set in the shader define the proportion of
1324 * the width and length of the primitive occupied by the AA region. The vtxWidth and vtxLength
1325 * attributes (one per vertex) are values from zero to one that tells the fragment
1326 * shader where the fragment is in relation to the line width/length overall; these values are
1327 * then used to compute the proper color, based on whether the fragment lies in the fading AA
1328 * region of the line.
1329 * Note that we only pass down the width values in this setup function. The length coordinates
1330 * are set up for each individual segment.
1331 */
1332void OpenGLRenderer::setupDrawAALine(GLvoid* vertices, GLvoid* widthCoords,
1333        GLvoid* lengthCoords, float boundaryWidthProportion) {
1334    bool force = mCaches.unbindMeshBuffer();
1335    mCaches.bindPositionVertexPointer(force, mCaches.currentProgram->position,
1336            vertices, gAAVertexStride);
1337    mCaches.resetTexCoordsVertexPointer();
1338    mCaches.unbindIndicesBuffer();
1339
1340    int widthSlot = mCaches.currentProgram->getAttrib("vtxWidth");
1341    glEnableVertexAttribArray(widthSlot);
1342    glVertexAttribPointer(widthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, widthCoords);
1343
1344    int lengthSlot = mCaches.currentProgram->getAttrib("vtxLength");
1345    glEnableVertexAttribArray(lengthSlot);
1346    glVertexAttribPointer(lengthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, lengthCoords);
1347
1348    int boundaryWidthSlot = mCaches.currentProgram->getUniform("boundaryWidth");
1349    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1350
1351    // Setting the inverse value saves computations per-fragment in the shader
1352    int inverseBoundaryWidthSlot = mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1353    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion));
1354}
1355
1356void OpenGLRenderer::finishDrawTexture() {
1357}
1358
1359///////////////////////////////////////////////////////////////////////////////
1360// Drawing
1361///////////////////////////////////////////////////////////////////////////////
1362
1363status_t OpenGLRenderer::drawDisplayList(DisplayList* displayList, uint32_t width, uint32_t height,
1364        Rect& dirty, int32_t flags, uint32_t level) {
1365
1366    if (!USE_DISPLAY_LIST_PROPERTIES && quickReject(0, 0, width, height)) {
1367        return false;
1368    }
1369
1370    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1371    // will be performed by the display list itself
1372    if (displayList && displayList->isRenderable()) {
1373        return displayList->replay(*this, width, height, dirty, flags, level);
1374    }
1375
1376    return DrawGlInfo::kStatusDone;
1377}
1378
1379void OpenGLRenderer::outputDisplayList(DisplayList* displayList, uint32_t level) {
1380    if (displayList) {
1381        displayList->output(*this, level);
1382    }
1383}
1384
1385void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
1386    int alpha;
1387    SkXfermode::Mode mode;
1388    getAlphaAndMode(paint, &alpha, &mode);
1389
1390    float x = left;
1391    float y = top;
1392
1393    GLenum filter = GL_LINEAR;
1394    bool ignoreTransform = false;
1395    if (mSnapshot->transform->isPureTranslate()) {
1396        x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1397        y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1398        ignoreTransform = true;
1399        filter = GL_NEAREST;
1400    } else {
1401        filter = FILTER(paint);
1402    }
1403
1404    setupDraw();
1405    setupDrawWithTexture(true);
1406    if (paint) {
1407        setupDrawAlpha8Color(paint->getColor(), alpha);
1408    }
1409    setupDrawColorFilter();
1410    setupDrawShader();
1411    setupDrawBlending(true, mode);
1412    setupDrawProgram();
1413    setupDrawModelView(x, y, x + texture->width, y + texture->height, ignoreTransform);
1414
1415    setupDrawTexture(texture->id);
1416    texture->setWrap(GL_CLAMP_TO_EDGE);
1417    texture->setFilter(filter);
1418
1419    setupDrawPureColorUniforms();
1420    setupDrawColorFilterUniforms();
1421    setupDrawShaderUniforms();
1422    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1423
1424    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1425
1426    finishDrawTexture();
1427}
1428
1429void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1430    const float right = left + bitmap->width();
1431    const float bottom = top + bitmap->height();
1432
1433    if (quickReject(left, top, right, bottom)) {
1434        return;
1435    }
1436
1437    mCaches.activeTexture(0);
1438    Texture* texture = mCaches.textureCache.get(bitmap);
1439    if (!texture) return;
1440    const AutoTexture autoCleanup(texture);
1441
1442    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1443        drawAlphaBitmap(texture, left, top, paint);
1444    } else {
1445        drawTextureRect(left, top, right, bottom, texture, paint);
1446    }
1447}
1448
1449void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1450    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1451    const mat4 transform(*matrix);
1452    transform.mapRect(r);
1453
1454    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1455        return;
1456    }
1457
1458    mCaches.activeTexture(0);
1459    Texture* texture = mCaches.textureCache.get(bitmap);
1460    if (!texture) return;
1461    const AutoTexture autoCleanup(texture);
1462
1463    // This could be done in a cheaper way, all we need is pass the matrix
1464    // to the vertex shader. The save/restore is a bit overkill.
1465    save(SkCanvas::kMatrix_SaveFlag);
1466    concatMatrix(matrix);
1467    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1468    restore();
1469}
1470
1471void OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1472        float* vertices, int* colors, SkPaint* paint) {
1473    // TODO: Do a quickReject
1474    if (!vertices || mSnapshot->isIgnored()) {
1475        return;
1476    }
1477
1478    mCaches.activeTexture(0);
1479    Texture* texture = mCaches.textureCache.get(bitmap);
1480    if (!texture) return;
1481    const AutoTexture autoCleanup(texture);
1482
1483    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1484    texture->setFilter(FILTER(paint), true);
1485
1486    int alpha;
1487    SkXfermode::Mode mode;
1488    getAlphaAndMode(paint, &alpha, &mode);
1489
1490    const uint32_t count = meshWidth * meshHeight * 6;
1491
1492    float left = FLT_MAX;
1493    float top = FLT_MAX;
1494    float right = FLT_MIN;
1495    float bottom = FLT_MIN;
1496
1497#if RENDER_LAYERS_AS_REGIONS
1498    const bool hasActiveLayer = hasLayer();
1499#else
1500    const bool hasActiveLayer = false;
1501#endif
1502
1503    // TODO: Support the colors array
1504    TextureVertex mesh[count];
1505    TextureVertex* vertex = mesh;
1506    for (int32_t y = 0; y < meshHeight; y++) {
1507        for (int32_t x = 0; x < meshWidth; x++) {
1508            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1509
1510            float u1 = float(x) / meshWidth;
1511            float u2 = float(x + 1) / meshWidth;
1512            float v1 = float(y) / meshHeight;
1513            float v2 = float(y + 1) / meshHeight;
1514
1515            int ax = i + (meshWidth + 1) * 2;
1516            int ay = ax + 1;
1517            int bx = i;
1518            int by = bx + 1;
1519            int cx = i + 2;
1520            int cy = cx + 1;
1521            int dx = i + (meshWidth + 1) * 2 + 2;
1522            int dy = dx + 1;
1523
1524            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1525            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1526            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1527
1528            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1529            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1530            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1531
1532#if RENDER_LAYERS_AS_REGIONS
1533            if (hasActiveLayer) {
1534                // TODO: This could be optimized to avoid unnecessary ops
1535                left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1536                top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1537                right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1538                bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1539            }
1540#endif
1541        }
1542    }
1543
1544#if RENDER_LAYERS_AS_REGIONS
1545    if (hasActiveLayer) {
1546        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1547    }
1548#endif
1549
1550    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1551            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1552            GL_TRIANGLES, count, false, false, 0, false, false);
1553}
1554
1555void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1556         float srcLeft, float srcTop, float srcRight, float srcBottom,
1557         float dstLeft, float dstTop, float dstRight, float dstBottom,
1558         SkPaint* paint) {
1559    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1560        return;
1561    }
1562
1563    mCaches.activeTexture(0);
1564    Texture* texture = mCaches.textureCache.get(bitmap);
1565    if (!texture) return;
1566    const AutoTexture autoCleanup(texture);
1567
1568    const float width = texture->width;
1569    const float height = texture->height;
1570
1571    const float u1 = fmax(0.0f, srcLeft / width);
1572    const float v1 = fmax(0.0f, srcTop / height);
1573    const float u2 = fmin(1.0f, srcRight / width);
1574    const float v2 = fmin(1.0f, srcBottom / height);
1575
1576    mCaches.unbindMeshBuffer();
1577    resetDrawTextureTexCoords(u1, v1, u2, v2);
1578
1579    int alpha;
1580    SkXfermode::Mode mode;
1581    getAlphaAndMode(paint, &alpha, &mode);
1582
1583    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1584
1585    if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) {
1586        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1587        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1588
1589        GLenum filter = GL_NEAREST;
1590        // Enable linear filtering if the source rectangle is scaled
1591        if (srcRight - srcLeft != dstRight - dstLeft || srcBottom - srcTop != dstBottom - dstTop) {
1592            filter = FILTER(paint);
1593        }
1594
1595        texture->setFilter(filter, true);
1596        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
1597                texture->id, alpha / 255.0f, mode, texture->blend,
1598                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1599                GL_TRIANGLE_STRIP, gMeshCount, false, true);
1600    } else {
1601        texture->setFilter(FILTER(paint), true);
1602        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
1603                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1604                GL_TRIANGLE_STRIP, gMeshCount);
1605    }
1606
1607    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1608}
1609
1610void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1611        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1612        float left, float top, float right, float bottom, SkPaint* paint) {
1613    if (quickReject(left, top, right, bottom)) {
1614        return;
1615    }
1616
1617    mCaches.activeTexture(0);
1618    Texture* texture = mCaches.textureCache.get(bitmap);
1619    if (!texture) return;
1620    const AutoTexture autoCleanup(texture);
1621    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1622    texture->setFilter(GL_LINEAR, true);
1623
1624    int alpha;
1625    SkXfermode::Mode mode;
1626    getAlphaAndMode(paint, &alpha, &mode);
1627
1628    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1629            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1630
1631    if (CC_LIKELY(mesh && mesh->verticesCount > 0)) {
1632        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1633#if RENDER_LAYERS_AS_REGIONS
1634        // Mark the current layer dirty where we are going to draw the patch
1635        if (hasLayer() && mesh->hasEmptyQuads) {
1636            const float offsetX = left + mSnapshot->transform->getTranslateX();
1637            const float offsetY = top + mSnapshot->transform->getTranslateY();
1638            const size_t count = mesh->quads.size();
1639            for (size_t i = 0; i < count; i++) {
1640                const Rect& bounds = mesh->quads.itemAt(i);
1641                if (CC_LIKELY(pureTranslate)) {
1642                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
1643                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
1644                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
1645                } else {
1646                    dirtyLayer(left + bounds.left, top + bounds.top,
1647                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
1648                }
1649            }
1650        }
1651#endif
1652
1653        if (CC_LIKELY(pureTranslate)) {
1654            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1655            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1656
1657            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1658                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1659                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1660                    true, !mesh->hasEmptyQuads);
1661        } else {
1662            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1663                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1664                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1665                    true, !mesh->hasEmptyQuads);
1666        }
1667    }
1668}
1669
1670/**
1671 * This function uses a similar approach to that of AA lines in the drawLines() function.
1672 * We expand the rectangle by a half pixel in screen space on all sides, and use a fragment
1673 * shader to compute the translucency of the color, determined by whether a given pixel is
1674 * within that boundary region and how far into the region it is.
1675 */
1676void OpenGLRenderer::drawAARect(float left, float top, float right, float bottom,
1677        int color, SkXfermode::Mode mode) {
1678    float inverseScaleX = 1.0f;
1679    float inverseScaleY = 1.0f;
1680    // The quad that we use needs to account for scaling.
1681    if (CC_UNLIKELY(!mSnapshot->transform->isPureTranslate())) {
1682        Matrix4 *mat = mSnapshot->transform;
1683        float m00 = mat->data[Matrix4::kScaleX];
1684        float m01 = mat->data[Matrix4::kSkewY];
1685        float m02 = mat->data[2];
1686        float m10 = mat->data[Matrix4::kSkewX];
1687        float m11 = mat->data[Matrix4::kScaleX];
1688        float m12 = mat->data[6];
1689        float scaleX = sqrt(m00 * m00 + m01 * m01);
1690        float scaleY = sqrt(m10 * m10 + m11 * m11);
1691        inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1692        inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1693    }
1694
1695    setupDraw();
1696    setupDrawNoTexture();
1697    setupDrawAALine();
1698    setupDrawColor(color);
1699    setupDrawColorFilter();
1700    setupDrawShader();
1701    setupDrawBlending(true, mode);
1702    setupDrawProgram();
1703    setupDrawModelViewIdentity(true);
1704    setupDrawColorUniforms();
1705    setupDrawColorFilterUniforms();
1706    setupDrawShaderIdentityUniforms();
1707
1708    AAVertex rects[4];
1709    AAVertex* aaVertices = &rects[0];
1710    void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
1711    void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
1712
1713    float boundarySizeX = .5 * inverseScaleX;
1714    float boundarySizeY = .5 * inverseScaleY;
1715
1716    // Adjust the rect by the AA boundary padding
1717    left -= boundarySizeX;
1718    right += boundarySizeX;
1719    top -= boundarySizeY;
1720    bottom += boundarySizeY;
1721
1722    float width = right - left;
1723    float height = bottom - top;
1724
1725    float boundaryWidthProportion = (width != 0) ? (2 * boundarySizeX) / width : 0;
1726    float boundaryHeightProportion = (height != 0) ? (2 * boundarySizeY) / height : 0;
1727    setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion);
1728    int boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
1729    int inverseBoundaryLengthSlot = mCaches.currentProgram->getUniform("inverseBoundaryLength");
1730    glUniform1f(boundaryLengthSlot, boundaryHeightProportion);
1731    glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryHeightProportion));
1732
1733    if (!quickReject(left, top, right, bottom)) {
1734        AAVertex::set(aaVertices++, left, bottom, 1, 1);
1735        AAVertex::set(aaVertices++, left, top, 1, 0);
1736        AAVertex::set(aaVertices++, right, bottom, 0, 1);
1737        AAVertex::set(aaVertices++, right, top, 0, 0);
1738        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1739        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1740    }
1741}
1742
1743/**
1744 * We draw lines as quads (tristrips). Using GL_LINES can be difficult because the rasterization
1745 * rules for those lines produces some unexpected results, and may vary between hardware devices.
1746 * The basics of lines-as-quads is easy; we simply find the normal to the line and position the
1747 * corners of the quads on either side of each line endpoint, separated by the strokeWidth
1748 * of the line. Hairlines are more involved because we need to account for transform scaling
1749 * to end up with a one-pixel-wide line in screen space..
1750 * Anti-aliased lines add another factor to the approach. We use a specialized fragment shader
1751 * in combination with values that we calculate and pass down in this method. The basic approach
1752 * is that the quad we create contains both the core line area plus a bounding area in which
1753 * the translucent/AA pixels are drawn. The values we calculate tell the shader what
1754 * proportion of the width and the length of a given segment is represented by the boundary
1755 * region. The quad ends up being exactly .5 pixel larger in all directions than the non-AA quad.
1756 * The bounding region is actually 1 pixel wide on all sides (half pixel on the outside, half pixel
1757 * on the inside). This ends up giving the result we want, with pixels that are completely
1758 * 'inside' the line area being filled opaquely and the other pixels being filled according to
1759 * how far into the boundary region they are, which is determined by shader interpolation.
1760 */
1761void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
1762    if (mSnapshot->isIgnored()) return;
1763
1764    const bool isAA = paint->isAntiAlias();
1765    // We use half the stroke width here because we're going to position the quad
1766    // corner vertices half of the width away from the line endpoints
1767    float halfStrokeWidth = paint->getStrokeWidth() * 0.5f;
1768    // A stroke width of 0 has a special meaning in Skia:
1769    // it draws a line 1 px wide regardless of current transform
1770    bool isHairLine = paint->getStrokeWidth() == 0.0f;
1771    float inverseScaleX = 1.0f;
1772    float inverseScaleY = 1.0f;
1773    bool scaled = false;
1774    int alpha;
1775    SkXfermode::Mode mode;
1776    int generatedVerticesCount = 0;
1777    int verticesCount = count;
1778    if (count > 4) {
1779        // Polyline: account for extra vertices needed for continuous tri-strip
1780        verticesCount += (count - 4);
1781    }
1782
1783    if (isHairLine || isAA) {
1784        // The quad that we use for AA and hairlines needs to account for scaling. For hairlines
1785        // the line on the screen should always be one pixel wide regardless of scale. For
1786        // AA lines, we only want one pixel of translucent boundary around the quad.
1787        if (CC_UNLIKELY(!mSnapshot->transform->isPureTranslate())) {
1788            Matrix4 *mat = mSnapshot->transform;
1789            float m00 = mat->data[Matrix4::kScaleX];
1790            float m01 = mat->data[Matrix4::kSkewY];
1791            float m02 = mat->data[2];
1792            float m10 = mat->data[Matrix4::kSkewX];
1793            float m11 = mat->data[Matrix4::kScaleX];
1794            float m12 = mat->data[6];
1795            float scaleX = sqrtf(m00 * m00 + m01 * m01);
1796            float scaleY = sqrtf(m10 * m10 + m11 * m11);
1797            inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1798            inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1799            if (inverseScaleX != 1.0f || inverseScaleY != 1.0f) {
1800                scaled = true;
1801            }
1802        }
1803    }
1804
1805    getAlphaAndMode(paint, &alpha, &mode);
1806    setupDraw();
1807    setupDrawNoTexture();
1808    if (isAA) {
1809        setupDrawAALine();
1810    }
1811    setupDrawColor(paint->getColor(), alpha);
1812    setupDrawColorFilter();
1813    setupDrawShader();
1814    setupDrawBlending(isAA, mode);
1815    setupDrawProgram();
1816    setupDrawModelViewIdentity(true);
1817    setupDrawColorUniforms();
1818    setupDrawColorFilterUniforms();
1819    setupDrawShaderIdentityUniforms();
1820
1821    if (isHairLine) {
1822        // Set a real stroke width to be used in quad construction
1823        halfStrokeWidth = isAA? 1 : .5;
1824    } else if (isAA && !scaled) {
1825        // Expand boundary to enable AA calculations on the quad border
1826        halfStrokeWidth += .5f;
1827    }
1828    Vertex lines[verticesCount];
1829    Vertex* vertices = &lines[0];
1830    AAVertex wLines[verticesCount];
1831    AAVertex* aaVertices = &wLines[0];
1832    if (CC_UNLIKELY(!isAA)) {
1833        setupDrawVertices(vertices);
1834    } else {
1835        void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
1836        void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
1837        // innerProportion is the ratio of the inner (non-AA) part of the line to the total
1838        // AA stroke width (the base stroke width expanded by a half pixel on either side).
1839        // This value is used in the fragment shader to determine how to fill fragments.
1840        // We will need to calculate the actual width proportion on each segment for
1841        // scaled non-hairlines, since the boundary proportion may differ per-axis when scaled.
1842        float boundaryWidthProportion = 1 / (2 * halfStrokeWidth);
1843        setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion);
1844    }
1845
1846    AAVertex* prevAAVertex = NULL;
1847    Vertex* prevVertex = NULL;
1848
1849    int boundaryLengthSlot = -1;
1850    int inverseBoundaryLengthSlot = -1;
1851    int boundaryWidthSlot = -1;
1852    int inverseBoundaryWidthSlot = -1;
1853    for (int i = 0; i < count; i += 4) {
1854        // a = start point, b = end point
1855        vec2 a(points[i], points[i + 1]);
1856        vec2 b(points[i + 2], points[i + 3]);
1857        float length = 0;
1858        float boundaryLengthProportion = 0;
1859        float boundaryWidthProportion = 0;
1860
1861        // Find the normal to the line
1862        vec2 n = (b - a).copyNormalized() * halfStrokeWidth;
1863        if (isHairLine) {
1864            if (isAA) {
1865                float wideningFactor;
1866                if (fabs(n.x) >= fabs(n.y)) {
1867                    wideningFactor = fabs(1.0f / n.x);
1868                } else {
1869                    wideningFactor = fabs(1.0f / n.y);
1870                }
1871                n *= wideningFactor;
1872            }
1873            if (scaled) {
1874                n.x *= inverseScaleX;
1875                n.y *= inverseScaleY;
1876            }
1877        } else if (scaled) {
1878            // Extend n by .5 pixel on each side, post-transform
1879            vec2 extendedN = n.copyNormalized();
1880            extendedN /= 2;
1881            extendedN.x *= inverseScaleX;
1882            extendedN.y *= inverseScaleY;
1883            float extendedNLength = extendedN.length();
1884            // We need to set this value on the shader prior to drawing
1885            boundaryWidthProportion = extendedNLength / (halfStrokeWidth + extendedNLength);
1886            n += extendedN;
1887        }
1888        float x = n.x;
1889        n.x = -n.y;
1890        n.y = x;
1891
1892        // aa lines expand the endpoint vertices to encompass the AA boundary
1893        if (isAA) {
1894            vec2 abVector = (b - a);
1895            length = abVector.length();
1896            abVector.normalize();
1897            if (scaled) {
1898                abVector.x *= inverseScaleX;
1899                abVector.y *= inverseScaleY;
1900                float abLength = abVector.length();
1901                boundaryLengthProportion = abLength / (length + abLength);
1902            } else {
1903                boundaryLengthProportion = .5 / (length + 1);
1904            }
1905            abVector /= 2;
1906            a -= abVector;
1907            b += abVector;
1908        }
1909
1910        // Four corners of the rectangle defining a thick line
1911        vec2 p1 = a - n;
1912        vec2 p2 = a + n;
1913        vec2 p3 = b + n;
1914        vec2 p4 = b - n;
1915
1916
1917        const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
1918        const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
1919        const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
1920        const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
1921
1922        if (!quickReject(left, top, right, bottom)) {
1923            if (!isAA) {
1924                if (prevVertex != NULL) {
1925                    // Issue two repeat vertices to create degenerate triangles to bridge
1926                    // between the previous line and the new one. This is necessary because
1927                    // we are creating a single triangle_strip which will contain
1928                    // potentially discontinuous line segments.
1929                    Vertex::set(vertices++, prevVertex->position[0], prevVertex->position[1]);
1930                    Vertex::set(vertices++, p1.x, p1.y);
1931                    generatedVerticesCount += 2;
1932                }
1933                Vertex::set(vertices++, p1.x, p1.y);
1934                Vertex::set(vertices++, p2.x, p2.y);
1935                Vertex::set(vertices++, p4.x, p4.y);
1936                Vertex::set(vertices++, p3.x, p3.y);
1937                prevVertex = vertices - 1;
1938                generatedVerticesCount += 4;
1939            } else {
1940                if (!isHairLine && scaled) {
1941                    // Must set width proportions per-segment for scaled non-hairlines to use the
1942                    // correct AA boundary dimensions
1943                    if (boundaryWidthSlot < 0) {
1944                        boundaryWidthSlot =
1945                                mCaches.currentProgram->getUniform("boundaryWidth");
1946                        inverseBoundaryWidthSlot =
1947                                mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1948                    }
1949                    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1950                    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion));
1951                }
1952                if (boundaryLengthSlot < 0) {
1953                    boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
1954                    inverseBoundaryLengthSlot =
1955                            mCaches.currentProgram->getUniform("inverseBoundaryLength");
1956                }
1957                glUniform1f(boundaryLengthSlot, boundaryLengthProportion);
1958                glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryLengthProportion));
1959
1960                if (prevAAVertex != NULL) {
1961                    // Issue two repeat vertices to create degenerate triangles to bridge
1962                    // between the previous line and the new one. This is necessary because
1963                    // we are creating a single triangle_strip which will contain
1964                    // potentially discontinuous line segments.
1965                    AAVertex::set(aaVertices++,prevAAVertex->position[0],
1966                            prevAAVertex->position[1], prevAAVertex->width, prevAAVertex->length);
1967                    AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
1968                    generatedVerticesCount += 2;
1969                }
1970                AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
1971                AAVertex::set(aaVertices++, p1.x, p1.y, 1, 0);
1972                AAVertex::set(aaVertices++, p3.x, p3.y, 0, 1);
1973                AAVertex::set(aaVertices++, p2.x, p2.y, 0, 0);
1974                prevAAVertex = aaVertices - 1;
1975                generatedVerticesCount += 4;
1976            }
1977            dirtyLayer(a.x == b.x ? left - 1 : left, a.y == b.y ? top - 1 : top,
1978                    a.x == b.x ? right: right, a.y == b.y ? bottom: bottom,
1979                    *mSnapshot->transform);
1980        }
1981    }
1982    if (generatedVerticesCount > 0) {
1983       glDrawArrays(GL_TRIANGLE_STRIP, 0, generatedVerticesCount);
1984    }
1985}
1986
1987void OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
1988    if (mSnapshot->isIgnored()) return;
1989
1990    // TODO: The paint's cap style defines whether the points are square or circular
1991    // TODO: Handle AA for round points
1992
1993    // A stroke width of 0 has a special meaning in Skia:
1994    // it draws an unscaled 1px point
1995    float strokeWidth = paint->getStrokeWidth();
1996    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
1997    if (isHairLine) {
1998        // Now that we know it's hairline, we can set the effective width, to be used later
1999        strokeWidth = 1.0f;
2000    }
2001    const float halfWidth = strokeWidth / 2;
2002    int alpha;
2003    SkXfermode::Mode mode;
2004    getAlphaAndMode(paint, &alpha, &mode);
2005
2006    int verticesCount = count >> 1;
2007    int generatedVerticesCount = 0;
2008
2009    TextureVertex pointsData[verticesCount];
2010    TextureVertex* vertex = &pointsData[0];
2011
2012    setupDraw();
2013    setupDrawNoTexture();
2014    setupDrawPoint(strokeWidth);
2015    setupDrawColor(paint->getColor(), alpha);
2016    setupDrawColorFilter();
2017    setupDrawShader();
2018    setupDrawBlending(mode);
2019    setupDrawProgram();
2020    setupDrawModelViewIdentity(true);
2021    setupDrawColorUniforms();
2022    setupDrawColorFilterUniforms();
2023    setupDrawPointUniforms();
2024    setupDrawShaderIdentityUniforms();
2025    setupDrawMesh(vertex);
2026
2027    for (int i = 0; i < count; i += 2) {
2028        TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
2029        generatedVerticesCount++;
2030        float left = points[i] - halfWidth;
2031        float right = points[i] + halfWidth;
2032        float top = points[i + 1] - halfWidth;
2033        float bottom = points [i + 1] + halfWidth;
2034        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
2035    }
2036
2037    glDrawArrays(GL_POINTS, 0, generatedVerticesCount);
2038}
2039
2040void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
2041    // No need to check against the clip, we fill the clip region
2042    if (mSnapshot->isIgnored()) return;
2043
2044    Rect& clip(*mSnapshot->clipRect);
2045    clip.snapToPixelBoundaries();
2046
2047    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
2048}
2049
2050void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, SkPaint* paint) {
2051    if (!texture) return;
2052    const AutoTexture autoCleanup(texture);
2053
2054    const float x = left + texture->left - texture->offset;
2055    const float y = top + texture->top - texture->offset;
2056
2057    drawPathTexture(texture, x, y, paint);
2058}
2059
2060void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
2061        float rx, float ry, SkPaint* paint) {
2062    if (mSnapshot->isIgnored()) return;
2063
2064    mCaches.activeTexture(0);
2065    const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
2066            right - left, bottom - top, rx, ry, paint);
2067    drawShape(left, top, texture, paint);
2068}
2069
2070void OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* paint) {
2071    if (mSnapshot->isIgnored()) return;
2072
2073    mCaches.activeTexture(0);
2074    const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, paint);
2075    drawShape(x - radius, y - radius, texture, paint);
2076}
2077
2078void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, SkPaint* paint) {
2079    if (mSnapshot->isIgnored()) return;
2080
2081    mCaches.activeTexture(0);
2082    const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, paint);
2083    drawShape(left, top, texture, paint);
2084}
2085
2086void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2087        float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) {
2088    if (mSnapshot->isIgnored()) return;
2089
2090    if (fabs(sweepAngle) >= 360.0f) {
2091        drawOval(left, top, right, bottom, paint);
2092        return;
2093    }
2094
2095    mCaches.activeTexture(0);
2096    const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
2097            startAngle, sweepAngle, useCenter, paint);
2098    drawShape(left, top, texture, paint);
2099}
2100
2101void OpenGLRenderer::drawRectAsShape(float left, float top, float right, float bottom,
2102        SkPaint* paint) {
2103    if (mSnapshot->isIgnored()) return;
2104
2105    mCaches.activeTexture(0);
2106    const PathTexture* texture = mCaches.rectShapeCache.getRect(right - left, bottom - top, paint);
2107    drawShape(left, top, texture, paint);
2108}
2109
2110void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
2111    if (p->getStyle() != SkPaint::kFill_Style) {
2112        drawRectAsShape(left, top, right, bottom, p);
2113        return;
2114    }
2115
2116    if (quickReject(left, top, right, bottom)) {
2117        return;
2118    }
2119
2120    SkXfermode::Mode mode;
2121    if (!mCaches.extensions.hasFramebufferFetch()) {
2122        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
2123        if (!isMode) {
2124            // Assume SRC_OVER
2125            mode = SkXfermode::kSrcOver_Mode;
2126        }
2127    } else {
2128        mode = getXfermode(p->getXfermode());
2129    }
2130
2131    int color = p->getColor();
2132    if (p->isAntiAlias() && !mSnapshot->transform->isSimple()) {
2133        drawAARect(left, top, right, bottom, color, mode);
2134    } else {
2135        drawColorRect(left, top, right, bottom, color, mode);
2136    }
2137}
2138
2139void OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2140        const float* positions, SkPaint* paint) {
2141    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2142            (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
2143        return;
2144    }
2145
2146    // NOTE: Skia does not support perspective transform on drawPosText yet
2147    if (!mSnapshot->transform->isSimple()) {
2148        return;
2149    }
2150
2151    float x = 0.0f;
2152    float y = 0.0f;
2153    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2154    if (pureTranslate) {
2155        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2156        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2157    }
2158
2159    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
2160    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2161            paint->getTextSize());
2162
2163    int alpha;
2164    SkXfermode::Mode mode;
2165    getAlphaAndMode(paint, &alpha, &mode);
2166
2167    // Pick the appropriate texture filtering
2168    bool linearFilter = mSnapshot->transform->changesBounds();
2169    if (pureTranslate && !linearFilter) {
2170        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2171    }
2172
2173    mCaches.activeTexture(0);
2174    setupDraw();
2175    setupDrawDirtyRegionsDisabled();
2176    setupDrawWithTexture(true);
2177    setupDrawAlpha8Color(paint->getColor(), alpha);
2178    setupDrawColorFilter();
2179    setupDrawShader();
2180    setupDrawBlending(true, mode);
2181    setupDrawProgram();
2182    setupDrawModelView(x, y, x, y, pureTranslate, true);
2183    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2184    setupDrawPureColorUniforms();
2185    setupDrawColorFilterUniforms();
2186    setupDrawShaderUniforms(pureTranslate);
2187
2188    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2189    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2190
2191#if RENDER_LAYERS_AS_REGIONS
2192    const bool hasActiveLayer = hasLayer();
2193#else
2194    const bool hasActiveLayer = false;
2195#endif
2196
2197    if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2198            positions, hasActiveLayer ? &bounds : NULL)) {
2199#if RENDER_LAYERS_AS_REGIONS
2200        if (hasActiveLayer) {
2201            if (!pureTranslate) {
2202                mSnapshot->transform->mapRect(bounds);
2203            }
2204            dirtyLayerUnchecked(bounds, getRegion());
2205        }
2206#endif
2207    }
2208}
2209
2210void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
2211        float x, float y, SkPaint* paint, float length) {
2212    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2213            (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
2214        return;
2215    }
2216
2217    if (length < 0.0f) length = paint->measureText(text, bytesCount);
2218    switch (paint->getTextAlign()) {
2219        case SkPaint::kCenter_Align:
2220            x -= length / 2.0f;
2221            break;
2222        case SkPaint::kRight_Align:
2223            x -= length;
2224            break;
2225        default:
2226            break;
2227    }
2228
2229    SkPaint::FontMetrics metrics;
2230    paint->getFontMetrics(&metrics, 0.0f);
2231    if (quickReject(x, y + metrics.fTop, x + length, y + metrics.fBottom)) {
2232        return;
2233    }
2234
2235    const float oldX = x;
2236    const float oldY = y;
2237    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2238    if (CC_LIKELY(pureTranslate)) {
2239        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2240        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2241    }
2242
2243#if DEBUG_GLYPHS
2244    ALOGD("OpenGLRenderer drawText() with FontID=%d", SkTypeface::UniqueID(paint->getTypeface()));
2245#endif
2246
2247    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
2248    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2249            paint->getTextSize());
2250
2251    int alpha;
2252    SkXfermode::Mode mode;
2253    getAlphaAndMode(paint, &alpha, &mode);
2254
2255    if (CC_UNLIKELY(mHasShadow)) {
2256        mCaches.activeTexture(0);
2257
2258        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2259        const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2260                paint, text, bytesCount, count, mShadowRadius);
2261        const AutoTexture autoCleanup(shadow);
2262
2263        const float sx = oldX - shadow->left + mShadowDx;
2264        const float sy = oldY - shadow->top + mShadowDy;
2265
2266        const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
2267        int shadowColor = mShadowColor;
2268        if (mShader) {
2269            shadowColor = 0xffffffff;
2270        }
2271
2272        setupDraw();
2273        setupDrawWithTexture(true);
2274        setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2275        setupDrawColorFilter();
2276        setupDrawShader();
2277        setupDrawBlending(true, mode);
2278        setupDrawProgram();
2279        setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2280        setupDrawTexture(shadow->id);
2281        setupDrawPureColorUniforms();
2282        setupDrawColorFilterUniforms();
2283        setupDrawShaderUniforms();
2284        setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2285
2286        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2287    }
2288
2289    // Pick the appropriate texture filtering
2290    bool linearFilter = mSnapshot->transform->changesBounds();
2291    if (pureTranslate && !linearFilter) {
2292        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2293    }
2294
2295    mCaches.activeTexture(0);
2296    setupDraw();
2297    setupDrawDirtyRegionsDisabled();
2298    setupDrawWithTexture(true);
2299    setupDrawAlpha8Color(paint->getColor(), alpha);
2300    setupDrawColorFilter();
2301    setupDrawShader();
2302    setupDrawBlending(true, mode);
2303    setupDrawProgram();
2304    setupDrawModelView(x, y, x, y, pureTranslate, true);
2305    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2306    setupDrawPureColorUniforms();
2307    setupDrawColorFilterUniforms();
2308    setupDrawShaderUniforms(pureTranslate);
2309
2310    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2311    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2312
2313#if RENDER_LAYERS_AS_REGIONS
2314    const bool hasActiveLayer = hasLayer();
2315#else
2316    const bool hasActiveLayer = false;
2317#endif
2318
2319    if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y,
2320            hasActiveLayer ? &bounds : NULL)) {
2321#if RENDER_LAYERS_AS_REGIONS
2322        if (hasActiveLayer) {
2323            if (!pureTranslate) {
2324                mSnapshot->transform->mapRect(bounds);
2325            }
2326            dirtyLayerUnchecked(bounds, getRegion());
2327        }
2328#endif
2329    }
2330
2331    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
2332}
2333
2334void OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, SkPath* path,
2335        float hOffset, float vOffset, SkPaint* paint) {
2336    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2337            (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
2338        return;
2339    }
2340
2341    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
2342    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2343            paint->getTextSize());
2344
2345    int alpha;
2346    SkXfermode::Mode mode;
2347    getAlphaAndMode(paint, &alpha, &mode);
2348
2349    mCaches.activeTexture(0);
2350    setupDraw();
2351    setupDrawDirtyRegionsDisabled();
2352    setupDrawWithTexture(true);
2353    setupDrawAlpha8Color(paint->getColor(), alpha);
2354    setupDrawColorFilter();
2355    setupDrawShader();
2356    setupDrawBlending(true, mode);
2357    setupDrawProgram();
2358    setupDrawModelView(0.0f, 0.0f, 0.0f, 0.0f, false, true);
2359    setupDrawTexture(fontRenderer.getTexture(true));
2360    setupDrawPureColorUniforms();
2361    setupDrawColorFilterUniforms();
2362    setupDrawShaderUniforms(false);
2363
2364    const Rect* clip = &mSnapshot->getLocalClip();
2365    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2366
2367#if RENDER_LAYERS_AS_REGIONS
2368    const bool hasActiveLayer = hasLayer();
2369#else
2370    const bool hasActiveLayer = false;
2371#endif
2372
2373    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2374            hOffset, vOffset, hasActiveLayer ? &bounds : NULL)) {
2375#if RENDER_LAYERS_AS_REGIONS
2376        if (hasActiveLayer) {
2377            mSnapshot->transform->mapRect(bounds);
2378            dirtyLayerUnchecked(bounds, getRegion());
2379        }
2380#endif
2381    }
2382}
2383
2384void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
2385    if (mSnapshot->isIgnored()) return;
2386
2387    mCaches.activeTexture(0);
2388
2389    // TODO: Perform early clip test before we rasterize the path
2390    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2391    if (!texture) return;
2392    const AutoTexture autoCleanup(texture);
2393
2394    const float x = texture->left - texture->offset;
2395    const float y = texture->top - texture->offset;
2396
2397    drawPathTexture(texture, x, y, paint);
2398}
2399
2400void OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
2401    if (!layer || quickReject(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight())) {
2402        return;
2403    }
2404
2405    if (layer->deferredUpdateScheduled && layer->renderer && layer->displayList) {
2406        OpenGLRenderer* renderer = layer->renderer;
2407        Rect& dirty = layer->dirtyRect;
2408
2409        interrupt();
2410        renderer->setViewport(layer->layer.getWidth(), layer->layer.getHeight());
2411        renderer->prepareDirty(dirty.left, dirty.top, dirty.right, dirty.bottom, !layer->isBlend());
2412        renderer->drawDisplayList(layer->displayList, layer->getWidth(), layer->getHeight(),
2413                dirty, DisplayList::kReplayFlag_ClipChildren);
2414        renderer->finish();
2415        resume();
2416
2417        dirty.setEmpty();
2418        layer->deferredUpdateScheduled = false;
2419        layer->renderer = NULL;
2420        layer->displayList = NULL;
2421    }
2422
2423    mCaches.activeTexture(0);
2424
2425    int alpha;
2426    SkXfermode::Mode mode;
2427    getAlphaAndMode(paint, &alpha, &mode);
2428
2429    layer->setAlpha(alpha, mode);
2430
2431#if RENDER_LAYERS_AS_REGIONS
2432    if (CC_LIKELY(!layer->region.isEmpty())) {
2433        if (layer->region.isRect()) {
2434            composeLayerRect(layer, layer->regionRect);
2435        } else if (layer->mesh) {
2436            const float a = alpha / 255.0f;
2437            const Rect& rect = layer->layer;
2438
2439            setupDraw();
2440            setupDrawWithTexture();
2441            setupDrawColor(a, a, a, a);
2442            setupDrawColorFilter();
2443            setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false);
2444            setupDrawProgram();
2445            setupDrawPureColorUniforms();
2446            setupDrawColorFilterUniforms();
2447            setupDrawTexture(layer->getTexture());
2448            if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) {
2449                x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2450                y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2451
2452                layer->setFilter(GL_NEAREST);
2453                setupDrawModelViewTranslate(x, y,
2454                        x + layer->layer.getWidth(), y + layer->layer.getHeight(), true);
2455            } else {
2456                layer->setFilter(GL_LINEAR);
2457                setupDrawModelViewTranslate(x, y,
2458                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
2459            }
2460            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
2461
2462            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
2463                    GL_UNSIGNED_SHORT, layer->meshIndices);
2464
2465            finishDrawTexture();
2466
2467#if DEBUG_LAYERS_AS_REGIONS
2468            drawRegionRects(layer->region);
2469#endif
2470        }
2471    }
2472#else
2473    const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
2474    composeLayerRect(layer, r);
2475#endif
2476}
2477
2478///////////////////////////////////////////////////////////////////////////////
2479// Shaders
2480///////////////////////////////////////////////////////////////////////////////
2481
2482void OpenGLRenderer::resetShader() {
2483    mShader = NULL;
2484}
2485
2486void OpenGLRenderer::setupShader(SkiaShader* shader) {
2487    mShader = shader;
2488    if (mShader) {
2489        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
2490    }
2491}
2492
2493///////////////////////////////////////////////////////////////////////////////
2494// Color filters
2495///////////////////////////////////////////////////////////////////////////////
2496
2497void OpenGLRenderer::resetColorFilter() {
2498    mColorFilter = NULL;
2499}
2500
2501void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
2502    mColorFilter = filter;
2503}
2504
2505///////////////////////////////////////////////////////////////////////////////
2506// Drop shadow
2507///////////////////////////////////////////////////////////////////////////////
2508
2509void OpenGLRenderer::resetShadow() {
2510    mHasShadow = false;
2511}
2512
2513void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
2514    mHasShadow = true;
2515    mShadowRadius = radius;
2516    mShadowDx = dx;
2517    mShadowDy = dy;
2518    mShadowColor = color;
2519}
2520
2521///////////////////////////////////////////////////////////////////////////////
2522// Draw filters
2523///////////////////////////////////////////////////////////////////////////////
2524
2525void OpenGLRenderer::resetPaintFilter() {
2526    mHasDrawFilter = false;
2527}
2528
2529void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) {
2530    mHasDrawFilter = true;
2531    mPaintFilterClearBits = clearBits & SkPaint::kAllFlags;
2532    mPaintFilterSetBits = setBits & SkPaint::kAllFlags;
2533}
2534
2535SkPaint* OpenGLRenderer::filterPaint(SkPaint* paint) {
2536    if (CC_LIKELY(!mHasDrawFilter || !paint)) return paint;
2537
2538    uint32_t flags = paint->getFlags();
2539
2540    mFilteredPaint = *paint;
2541    mFilteredPaint.setFlags((flags & ~mPaintFilterClearBits) | mPaintFilterSetBits);
2542
2543    return &mFilteredPaint;
2544}
2545
2546///////////////////////////////////////////////////////////////////////////////
2547// Drawing implementation
2548///////////////////////////////////////////////////////////////////////////////
2549
2550void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
2551        float x, float y, SkPaint* paint) {
2552    if (quickReject(x, y, x + texture->width, y + texture->height)) {
2553        return;
2554    }
2555
2556    int alpha;
2557    SkXfermode::Mode mode;
2558    getAlphaAndMode(paint, &alpha, &mode);
2559
2560    setupDraw();
2561    setupDrawWithTexture(true);
2562    setupDrawAlpha8Color(paint->getColor(), alpha);
2563    setupDrawColorFilter();
2564    setupDrawShader();
2565    setupDrawBlending(true, mode);
2566    setupDrawProgram();
2567    setupDrawModelView(x, y, x + texture->width, y + texture->height);
2568    setupDrawTexture(texture->id);
2569    setupDrawPureColorUniforms();
2570    setupDrawColorFilterUniforms();
2571    setupDrawShaderUniforms();
2572    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2573
2574    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2575
2576    finishDrawTexture();
2577}
2578
2579// Same values used by Skia
2580#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2581#define kStdUnderline_Offset    (1.0f / 9.0f)
2582#define kStdUnderline_Thickness (1.0f / 18.0f)
2583
2584void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
2585        float x, float y, SkPaint* paint) {
2586    // Handle underline and strike-through
2587    uint32_t flags = paint->getFlags();
2588    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
2589        SkPaint paintCopy(*paint);
2590        float underlineWidth = length;
2591        // If length is > 0.0f, we already measured the text for the text alignment
2592        if (length <= 0.0f) {
2593            underlineWidth = paintCopy.measureText(text, bytesCount);
2594        }
2595
2596        float offsetX = 0;
2597        switch (paintCopy.getTextAlign()) {
2598            case SkPaint::kCenter_Align:
2599                offsetX = underlineWidth * 0.5f;
2600                break;
2601            case SkPaint::kRight_Align:
2602                offsetX = underlineWidth;
2603                break;
2604            default:
2605                break;
2606        }
2607
2608        if (CC_LIKELY(underlineWidth > 0.0f)) {
2609            const float textSize = paintCopy.getTextSize();
2610            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
2611
2612            const float left = x - offsetX;
2613            float top = 0.0f;
2614
2615            int linesCount = 0;
2616            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
2617            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
2618
2619            const int pointsCount = 4 * linesCount;
2620            float points[pointsCount];
2621            int currentPoint = 0;
2622
2623            if (flags & SkPaint::kUnderlineText_Flag) {
2624                top = y + textSize * kStdUnderline_Offset;
2625                points[currentPoint++] = left;
2626                points[currentPoint++] = top;
2627                points[currentPoint++] = left + underlineWidth;
2628                points[currentPoint++] = top;
2629            }
2630
2631            if (flags & SkPaint::kStrikeThruText_Flag) {
2632                top = y + textSize * kStdStrikeThru_Offset;
2633                points[currentPoint++] = left;
2634                points[currentPoint++] = top;
2635                points[currentPoint++] = left + underlineWidth;
2636                points[currentPoint++] = top;
2637            }
2638
2639            paintCopy.setStrokeWidth(strokeWidth);
2640
2641            drawLines(&points[0], pointsCount, &paintCopy);
2642        }
2643    }
2644}
2645
2646void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
2647        int color, SkXfermode::Mode mode, bool ignoreTransform) {
2648    // If a shader is set, preserve only the alpha
2649    if (mShader) {
2650        color |= 0x00ffffff;
2651    }
2652
2653    setupDraw();
2654    setupDrawNoTexture();
2655    setupDrawColor(color);
2656    setupDrawShader();
2657    setupDrawColorFilter();
2658    setupDrawBlending(mode);
2659    setupDrawProgram();
2660    setupDrawModelView(left, top, right, bottom, ignoreTransform);
2661    setupDrawColorUniforms();
2662    setupDrawShaderUniforms(ignoreTransform);
2663    setupDrawColorFilterUniforms();
2664    setupDrawSimpleMesh();
2665
2666    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2667}
2668
2669void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2670        Texture* texture, SkPaint* paint) {
2671    int alpha;
2672    SkXfermode::Mode mode;
2673    getAlphaAndMode(paint, &alpha, &mode);
2674
2675    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2676
2677    if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) {
2678        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
2679        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
2680
2681        texture->setFilter(GL_NEAREST, true);
2682        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
2683                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
2684                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
2685    } else {
2686        texture->setFilter(FILTER(paint), true);
2687        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
2688                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
2689                GL_TRIANGLE_STRIP, gMeshCount);
2690    }
2691}
2692
2693void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2694        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
2695    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
2696            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
2697}
2698
2699void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
2700        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
2701        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
2702        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
2703
2704    setupDraw();
2705    setupDrawWithTexture();
2706    setupDrawColor(alpha, alpha, alpha, alpha);
2707    setupDrawColorFilter();
2708    setupDrawBlending(blend, mode, swapSrcDst);
2709    setupDrawProgram();
2710    if (!dirty) {
2711        setupDrawDirtyRegionsDisabled();
2712    }
2713    if (!ignoreScale) {
2714        setupDrawModelView(left, top, right, bottom, ignoreTransform);
2715    } else {
2716        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
2717    }
2718    setupDrawPureColorUniforms();
2719    setupDrawColorFilterUniforms();
2720    setupDrawTexture(texture);
2721    setupDrawMesh(vertices, texCoords, vbo);
2722
2723    glDrawArrays(drawMode, 0, elementsCount);
2724
2725    finishDrawTexture();
2726}
2727
2728void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
2729        ProgramDescription& description, bool swapSrcDst) {
2730    blend = blend || mode != SkXfermode::kSrcOver_Mode;
2731    if (blend) {
2732        // These blend modes are not supported by OpenGL directly and have
2733        // to be implemented using shaders. Since the shader will perform
2734        // the blending, turn blending off here
2735        // If the blend mode cannot be implemented using shaders, fall
2736        // back to the default SrcOver blend mode instead
2737        if CC_UNLIKELY((mode > SkXfermode::kScreen_Mode)) {
2738            if (CC_UNLIKELY(mCaches.extensions.hasFramebufferFetch())) {
2739                description.framebufferMode = mode;
2740                description.swapSrcDst = swapSrcDst;
2741
2742                if (mCaches.blend) {
2743                    glDisable(GL_BLEND);
2744                    mCaches.blend = false;
2745                }
2746
2747                return;
2748            } else {
2749                mode = SkXfermode::kSrcOver_Mode;
2750            }
2751        }
2752
2753        if (!mCaches.blend) {
2754            glEnable(GL_BLEND);
2755        }
2756
2757        GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
2758        GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
2759
2760        if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
2761            glBlendFunc(sourceMode, destMode);
2762            mCaches.lastSrcMode = sourceMode;
2763            mCaches.lastDstMode = destMode;
2764        }
2765    } else if (mCaches.blend) {
2766        glDisable(GL_BLEND);
2767    }
2768    mCaches.blend = blend;
2769}
2770
2771bool OpenGLRenderer::useProgram(Program* program) {
2772    if (!program->isInUse()) {
2773        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
2774        program->use();
2775        mCaches.currentProgram = program;
2776        return false;
2777    }
2778    return true;
2779}
2780
2781void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
2782    TextureVertex* v = &mMeshVertices[0];
2783    TextureVertex::setUV(v++, u1, v1);
2784    TextureVertex::setUV(v++, u2, v1);
2785    TextureVertex::setUV(v++, u1, v2);
2786    TextureVertex::setUV(v++, u2, v2);
2787}
2788
2789void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
2790    if (paint) {
2791        *mode = getXfermode(paint->getXfermode());
2792
2793        // Skia draws using the color's alpha channel if < 255
2794        // Otherwise, it uses the paint's alpha
2795        int color = paint->getColor();
2796        *alpha = (color >> 24) & 0xFF;
2797        if (*alpha == 255) {
2798            *alpha = paint->getAlpha();
2799        }
2800    } else {
2801        *mode = SkXfermode::kSrcOver_Mode;
2802        *alpha = 255;
2803    }
2804    *alpha *= mSnapshot->alpha;
2805}
2806
2807SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
2808    SkXfermode::Mode resultMode;
2809    if (!SkXfermode::AsMode(mode, &resultMode)) {
2810        resultMode = SkXfermode::kSrcOver_Mode;
2811    }
2812    return resultMode;
2813}
2814
2815}; // namespace uirenderer
2816}; // namespace android
2817