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