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