OpenGLRenderer.cpp revision fca52b7583d1e5f5ff8ed06554875d2a30ef56fa
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#include "OpenGLRenderer.h"
18
19#include "DeferredDisplayList.h"
20#include "GammaFontRenderer.h"
21#include "Glop.h"
22#include "GlopBuilder.h"
23#include "Patch.h"
24#include "PathTessellator.h"
25#include "Properties.h"
26#include "RenderNode.h"
27#include "renderstate/MeshState.h"
28#include "renderstate/RenderState.h"
29#include "ShadowTessellator.h"
30#include "SkiaShader.h"
31#include "Vector.h"
32#include "VertexBuffer.h"
33#include "utils/GLUtils.h"
34#include "utils/PaintUtils.h"
35#include "utils/TraceUtils.h"
36
37#include <stdlib.h>
38#include <stdint.h>
39#include <sys/types.h>
40
41#include <SkCanvas.h>
42#include <SkColor.h>
43#include <SkPathOps.h>
44#include <SkShader.h>
45#include <SkTypeface.h>
46
47#include <utils/Log.h>
48#include <utils/StopWatch.h>
49
50#include <private/hwui/DrawGlInfo.h>
51
52#include <ui/Rect.h>
53
54#if DEBUG_DETAILED_EVENTS
55    #define EVENT_LOGD(...) eventMarkDEBUG(__VA_ARGS__)
56#else
57    #define EVENT_LOGD(...)
58#endif
59
60namespace android {
61namespace uirenderer {
62
63///////////////////////////////////////////////////////////////////////////////
64// Constructors/destructor
65///////////////////////////////////////////////////////////////////////////////
66
67OpenGLRenderer::OpenGLRenderer(RenderState& renderState)
68        : mState(*this)
69        , mCaches(Caches::getInstance())
70        , mRenderState(renderState)
71        , mFrameStarted(false)
72        , mScissorOptimizationDisabled(false)
73        , mSuppressTiling(false)
74        , mFirstFrameAfterResize(true)
75        , mDirty(false)
76        , mLightCenter((Vector3){FLT_MIN, FLT_MIN, FLT_MIN})
77        , mLightRadius(FLT_MIN)
78        , mAmbientShadowAlpha(0)
79        , mSpotShadowAlpha(0) {
80}
81
82OpenGLRenderer::~OpenGLRenderer() {
83    // The context has already been destroyed at this point, do not call
84    // GL APIs. All GL state should be kept in Caches.h
85}
86
87void OpenGLRenderer::initProperties() {
88    char property[PROPERTY_VALUE_MAX];
89    if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) {
90        mScissorOptimizationDisabled = !strcasecmp(property, "true");
91        INIT_LOGD("  Scissor optimization %s",
92                mScissorOptimizationDisabled ? "disabled" : "enabled");
93    } else {
94        INIT_LOGD("  Scissor optimization enabled");
95    }
96}
97
98void OpenGLRenderer::initLight(float lightRadius, uint8_t ambientShadowAlpha,
99        uint8_t spotShadowAlpha) {
100    mLightRadius = lightRadius;
101    mAmbientShadowAlpha = ambientShadowAlpha;
102    mSpotShadowAlpha = spotShadowAlpha;
103}
104
105void OpenGLRenderer::setLightCenter(const Vector3& lightCenter) {
106    mLightCenter = lightCenter;
107}
108
109///////////////////////////////////////////////////////////////////////////////
110// Setup
111///////////////////////////////////////////////////////////////////////////////
112
113void OpenGLRenderer::onViewportInitialized() {
114    glDisable(GL_DITHER);
115    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
116    mFirstFrameAfterResize = true;
117}
118
119void OpenGLRenderer::setupFrameState(float left, float top,
120        float right, float bottom, bool opaque) {
121    mCaches.clearGarbage();
122    mState.initializeSaveStack(left, top, right, bottom, mLightCenter);
123    mOpaque = opaque;
124    mTilingClip.set(left, top, right, bottom);
125}
126
127void OpenGLRenderer::startFrame() {
128    if (mFrameStarted) return;
129    mFrameStarted = true;
130
131    mState.setDirtyClip(true);
132
133    discardFramebuffer(mTilingClip.left, mTilingClip.top, mTilingClip.right, mTilingClip.bottom);
134
135    mRenderState.setViewport(mState.getWidth(), mState.getHeight());
136
137    // Functors break the tiling extension in pretty spectacular ways
138    // This ensures we don't use tiling when a functor is going to be
139    // invoked during the frame
140    mSuppressTiling = mCaches.hasRegisteredFunctors()
141            || mFirstFrameAfterResize;
142    mFirstFrameAfterResize = false;
143
144    startTilingCurrentClip(true);
145
146    debugOverdraw(true, true);
147
148    clear(mTilingClip.left, mTilingClip.top,
149            mTilingClip.right, mTilingClip.bottom, mOpaque);
150}
151
152void OpenGLRenderer::prepareDirty(float left, float top,
153        float right, float bottom, bool opaque) {
154
155    setupFrameState(left, top, right, bottom, opaque);
156
157    // Layer renderers will start the frame immediately
158    // The framebuffer renderer will first defer the display list
159    // for each layer and wait until the first drawing command
160    // to start the frame
161    if (currentSnapshot()->fbo == 0) {
162        mRenderState.blend().syncEnabled();
163        updateLayers();
164    } else {
165        startFrame();
166    }
167}
168
169void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) {
170    // If we know that we are going to redraw the entire framebuffer,
171    // perform a discard to let the driver know we don't need to preserve
172    // the back buffer for this frame.
173    if (mCaches.extensions().hasDiscardFramebuffer() &&
174            left <= 0.0f && top <= 0.0f && right >= mState.getWidth() && bottom >= mState.getHeight()) {
175        const bool isFbo = getTargetFbo() == 0;
176        const GLenum attachments[] = {
177                isFbo ? (const GLenum) GL_COLOR_EXT : (const GLenum) GL_COLOR_ATTACHMENT0,
178                isFbo ? (const GLenum) GL_STENCIL_EXT : (const GLenum) GL_STENCIL_ATTACHMENT };
179        glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
180    }
181}
182
183void OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) {
184    if (!opaque) {
185        mRenderState.scissor().setEnabled(true);
186        mRenderState.scissor().set(left, getViewportHeight() - bottom, right - left, bottom - top);
187        glClear(GL_COLOR_BUFFER_BIT);
188        mDirty = true;
189        return;
190    }
191
192    mRenderState.scissor().reset();
193}
194
195void OpenGLRenderer::startTilingCurrentClip(bool opaque, bool expand) {
196    if (!mSuppressTiling) {
197        const Snapshot* snapshot = currentSnapshot();
198
199        const Rect* clip = &mTilingClip;
200        if (snapshot->flags & Snapshot::kFlagFboTarget) {
201            clip = &(snapshot->layer->clipRect);
202        }
203
204        startTiling(*clip, getViewportHeight(), opaque, expand);
205    }
206}
207
208void OpenGLRenderer::startTiling(const Rect& clip, int windowHeight, bool opaque, bool expand) {
209    if (!mSuppressTiling) {
210        if(expand) {
211            // Expand the startTiling region by 1
212            int leftNotZero = (clip.left > 0) ? 1 : 0;
213            int topNotZero = (windowHeight - clip.bottom > 0) ? 1 : 0;
214
215            mCaches.startTiling(
216                clip.left - leftNotZero,
217                windowHeight - clip.bottom - topNotZero,
218                clip.right - clip.left + leftNotZero + 1,
219                clip.bottom - clip.top + topNotZero + 1,
220                opaque);
221        } else {
222            mCaches.startTiling(clip.left, windowHeight - clip.bottom,
223                clip.right - clip.left, clip.bottom - clip.top, opaque);
224        }
225    }
226}
227
228void OpenGLRenderer::endTiling() {
229    if (!mSuppressTiling) mCaches.endTiling();
230}
231
232bool OpenGLRenderer::finish() {
233    renderOverdraw();
234    endTiling();
235    mTempPaths.clear();
236
237    // When finish() is invoked on FBO 0 we've reached the end
238    // of the current frame
239    if (getTargetFbo() == 0) {
240        mCaches.pathCache.trim();
241        mCaches.tessellationCache.trim();
242    }
243
244    if (!suppressErrorChecks()) {
245#if DEBUG_OPENGL
246        GLUtils::dumpGLErrors();
247#endif
248
249#if DEBUG_MEMORY_USAGE
250        mCaches.dumpMemoryUsage();
251#else
252        if (Properties::debugLevel & kDebugMemory) {
253            mCaches.dumpMemoryUsage();
254        }
255#endif
256    }
257
258    mFrameStarted = false;
259
260    return reportAndClearDirty();
261}
262
263void OpenGLRenderer::resumeAfterLayer() {
264    mRenderState.setViewport(getViewportWidth(), getViewportHeight());
265    mRenderState.bindFramebuffer(currentSnapshot()->fbo);
266    debugOverdraw(true, false);
267
268    mRenderState.scissor().reset();
269    dirtyClip();
270}
271
272void OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) {
273    if (mState.currentlyIgnored()) return;
274
275    Rect clip(mState.currentClipRect());
276    clip.snapToPixelBoundaries();
277
278    // Since we don't know what the functor will draw, let's dirty
279    // the entire clip region
280    if (hasLayer()) {
281        dirtyLayerUnchecked(clip, getRegion());
282    }
283
284    DrawGlInfo info;
285    info.clipLeft = clip.left;
286    info.clipTop = clip.top;
287    info.clipRight = clip.right;
288    info.clipBottom = clip.bottom;
289    info.isLayer = hasLayer();
290    info.width = getViewportWidth();
291    info.height = getViewportHeight();
292    currentTransform()->copyTo(&info.transform[0]);
293
294    bool prevDirtyClip = mState.getDirtyClip();
295    // setup GL state for functor
296    if (mState.getDirtyClip()) {
297        setStencilFromClip(); // can issue draws, so must precede enableScissor()/interrupt()
298    }
299    if (mRenderState.scissor().setEnabled(true) || prevDirtyClip) {
300        setScissorFromClip();
301    }
302
303    mRenderState.invokeFunctor(functor, DrawGlInfo::kModeDraw, &info);
304    // Scissor may have been modified, reset dirty clip
305    dirtyClip();
306
307    mDirty = true;
308}
309
310///////////////////////////////////////////////////////////////////////////////
311// Debug
312///////////////////////////////////////////////////////////////////////////////
313
314void OpenGLRenderer::eventMarkDEBUG(const char* fmt, ...) const {
315#if DEBUG_DETAILED_EVENTS
316    const int BUFFER_SIZE = 256;
317    va_list ap;
318    char buf[BUFFER_SIZE];
319
320    va_start(ap, fmt);
321    vsnprintf(buf, BUFFER_SIZE, fmt, ap);
322    va_end(ap);
323
324    eventMark(buf);
325#endif
326}
327
328
329void OpenGLRenderer::eventMark(const char* name) const {
330    mCaches.eventMark(0, name);
331}
332
333void OpenGLRenderer::startMark(const char* name) const {
334    mCaches.startMark(0, name);
335}
336
337void OpenGLRenderer::endMark() const {
338    mCaches.endMark();
339}
340
341void OpenGLRenderer::debugOverdraw(bool enable, bool clear) {
342    mRenderState.debugOverdraw(enable, clear);
343}
344
345void OpenGLRenderer::renderOverdraw() {
346    if (Properties::debugOverdraw && getTargetFbo() == 0) {
347        const Rect* clip = &mTilingClip;
348
349        mRenderState.scissor().setEnabled(true);
350        mRenderState.scissor().set(clip->left,
351                mState.firstSnapshot()->getViewportHeight() - clip->bottom,
352                clip->right - clip->left,
353                clip->bottom - clip->top);
354
355        // 1x overdraw
356        mRenderState.stencil().enableDebugTest(2);
357        drawColor(mCaches.getOverdrawColor(1), SkXfermode::kSrcOver_Mode);
358
359        // 2x overdraw
360        mRenderState.stencil().enableDebugTest(3);
361        drawColor(mCaches.getOverdrawColor(2), SkXfermode::kSrcOver_Mode);
362
363        // 3x overdraw
364        mRenderState.stencil().enableDebugTest(4);
365        drawColor(mCaches.getOverdrawColor(3), SkXfermode::kSrcOver_Mode);
366
367        // 4x overdraw and higher
368        mRenderState.stencil().enableDebugTest(4, true);
369        drawColor(mCaches.getOverdrawColor(4), SkXfermode::kSrcOver_Mode);
370
371        mRenderState.stencil().disable();
372    }
373}
374
375///////////////////////////////////////////////////////////////////////////////
376// Layers
377///////////////////////////////////////////////////////////////////////////////
378
379bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) {
380    if (layer->deferredUpdateScheduled && layer->renderer
381            && layer->renderNode.get() && layer->renderNode->isRenderable()) {
382
383        if (inFrame) {
384            endTiling();
385            debugOverdraw(false, false);
386        }
387
388        if (CC_UNLIKELY(inFrame || Properties::drawDeferDisabled)) {
389            layer->render(*this);
390        } else {
391            layer->defer(*this);
392        }
393
394        if (inFrame) {
395            resumeAfterLayer();
396            startTilingCurrentClip();
397        }
398
399        layer->debugDrawUpdate = Properties::debugLayersUpdates;
400        layer->hasDrawnSinceUpdate = false;
401
402        return true;
403    }
404
405    return false;
406}
407
408void OpenGLRenderer::updateLayers() {
409    // If draw deferring is enabled this method will simply defer
410    // the display list of each individual layer. The layers remain
411    // in the layer updates list which will be cleared by flushLayers().
412    int count = mLayerUpdates.size();
413    if (count > 0) {
414        if (CC_UNLIKELY(Properties::drawDeferDisabled)) {
415            startMark("Layer Updates");
416        } else {
417            startMark("Defer Layer Updates");
418        }
419
420        // Note: it is very important to update the layers in order
421        for (int i = 0; i < count; i++) {
422            Layer* layer = mLayerUpdates.itemAt(i).get();
423            updateLayer(layer, false);
424        }
425
426        if (CC_UNLIKELY(Properties::drawDeferDisabled)) {
427            mLayerUpdates.clear();
428            mRenderState.bindFramebuffer(getTargetFbo());
429        }
430        endMark();
431    }
432}
433
434void OpenGLRenderer::flushLayers() {
435    int count = mLayerUpdates.size();
436    if (count > 0) {
437        startMark("Apply Layer Updates");
438
439        // Note: it is very important to update the layers in order
440        for (int i = 0; i < count; i++) {
441            mLayerUpdates.itemAt(i)->flush();
442        }
443
444        mLayerUpdates.clear();
445        mRenderState.bindFramebuffer(getTargetFbo());
446
447        endMark();
448    }
449}
450
451void OpenGLRenderer::pushLayerUpdate(Layer* layer) {
452    if (layer) {
453        // Make sure we don't introduce duplicates.
454        // SortedVector would do this automatically but we need to respect
455        // the insertion order. The linear search is not an issue since
456        // this list is usually very short (typically one item, at most a few)
457        for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
458            if (mLayerUpdates.itemAt(i) == layer) {
459                return;
460            }
461        }
462        mLayerUpdates.push_back(layer);
463    }
464}
465
466void OpenGLRenderer::cancelLayerUpdate(Layer* layer) {
467    if (layer) {
468        for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
469            if (mLayerUpdates.itemAt(i) == layer) {
470                mLayerUpdates.removeAt(i);
471                break;
472            }
473        }
474    }
475}
476
477void OpenGLRenderer::flushLayerUpdates() {
478    ATRACE_NAME("Update HW Layers");
479    mRenderState.blend().syncEnabled();
480    updateLayers();
481    flushLayers();
482    // Wait for all the layer updates to be executed
483    glFinish();
484}
485
486void OpenGLRenderer::markLayersAsBuildLayers() {
487    for (size_t i = 0; i < mLayerUpdates.size(); i++) {
488        mLayerUpdates[i]->wasBuildLayered = true;
489    }
490}
491
492///////////////////////////////////////////////////////////////////////////////
493// State management
494///////////////////////////////////////////////////////////////////////////////
495
496void OpenGLRenderer::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) {
497    bool restoreViewport = removed.flags & Snapshot::kFlagIsFboLayer;
498    bool restoreClip = removed.flags & Snapshot::kFlagClipSet;
499    bool restoreLayer = removed.flags & Snapshot::kFlagIsLayer;
500
501    if (restoreViewport) {
502        mRenderState.setViewport(getViewportWidth(), getViewportHeight());
503    }
504
505    if (restoreClip) {
506        dirtyClip();
507    }
508
509    if (restoreLayer) {
510        endMark(); // Savelayer
511        ATRACE_END(); // SaveLayer
512        startMark("ComposeLayer");
513        composeLayer(removed, restored);
514        endMark();
515    }
516}
517
518///////////////////////////////////////////////////////////////////////////////
519// Layers
520///////////////////////////////////////////////////////////////////////////////
521
522int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
523        const SkPaint* paint, int flags, const SkPath* convexMask) {
524    // force matrix/clip isolation for layer
525    flags |= SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag;
526
527    const int count = mState.saveSnapshot(flags);
528
529    if (!mState.currentlyIgnored()) {
530        createLayer(left, top, right, bottom, paint, flags, convexMask);
531    }
532
533    return count;
534}
535
536void OpenGLRenderer::calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer) {
537    const Rect untransformedBounds(bounds);
538
539    currentTransform()->mapRect(bounds);
540
541    // Layers only make sense if they are in the framebuffer's bounds
542    if (bounds.intersect(mState.currentClipRect())) {
543        // We cannot work with sub-pixels in this case
544        bounds.snapToPixelBoundaries();
545
546        // When the layer is not an FBO, we may use glCopyTexImage so we
547        // need to make sure the layer does not extend outside the bounds
548        // of the framebuffer
549        const Snapshot& previous = *(currentSnapshot()->previous);
550        Rect previousViewport(0, 0, previous.getViewportWidth(), previous.getViewportHeight());
551        if (!bounds.intersect(previousViewport)) {
552            bounds.setEmpty();
553        } else if (fboLayer) {
554            clip.set(bounds);
555            mat4 inverse;
556            inverse.loadInverse(*currentTransform());
557            inverse.mapRect(clip);
558            clip.snapToPixelBoundaries();
559            if (clip.intersect(untransformedBounds)) {
560                clip.translate(-untransformedBounds.left, -untransformedBounds.top);
561                bounds.set(untransformedBounds);
562            } else {
563                clip.setEmpty();
564            }
565        }
566    } else {
567        bounds.setEmpty();
568    }
569}
570
571void OpenGLRenderer::updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
572        bool fboLayer, int alpha) {
573    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
574            bounds.getHeight() > mCaches.maxTextureSize ||
575            (fboLayer && clip.isEmpty())) {
576        writableSnapshot()->empty = fboLayer;
577    } else {
578        writableSnapshot()->invisible = writableSnapshot()->invisible || (alpha <= 0 && fboLayer);
579    }
580}
581
582int OpenGLRenderer::saveLayerDeferred(float left, float top, float right, float bottom,
583        const SkPaint* paint, int flags) {
584    const int count = mState.saveSnapshot(flags);
585
586    if (!mState.currentlyIgnored() && (flags & SkCanvas::kClipToLayer_SaveFlag)) {
587        // initialize the snapshot as though it almost represents an FBO layer so deferred draw
588        // operations will be able to store and restore the current clip and transform info, and
589        // quick rejection will be correct (for display lists)
590
591        Rect bounds(left, top, right, bottom);
592        Rect clip;
593        calculateLayerBoundsAndClip(bounds, clip, true);
594        updateSnapshotIgnoreForLayer(bounds, clip, true, getAlphaDirect(paint));
595
596        if (!mState.currentlyIgnored()) {
597            writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f);
598            writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom);
599            writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight());
600            writableSnapshot()->roundRectClipState = nullptr;
601        }
602    }
603
604    return count;
605}
606
607/**
608 * Layers are viewed by Skia are slightly different than layers in image editing
609 * programs (for instance.) When a layer is created, previously created layers
610 * and the frame buffer still receive every drawing command. For instance, if a
611 * layer is created and a shape intersecting the bounds of the layers and the
612 * framebuffer is draw, the shape will be drawn on both (unless the layer was
613 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
614 *
615 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
616 * texture. Unfortunately, this is inefficient as it requires every primitive to
617 * be drawn n + 1 times, where n is the number of active layers. In practice this
618 * means, for every primitive:
619 *   - Switch active frame buffer
620 *   - Change viewport, clip and projection matrix
621 *   - Issue the drawing
622 *
623 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
624 * To avoid this, layers are implemented in a different way here, at least in the
625 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
626 * is set. When this flag is set we can redirect all drawing operations into a
627 * single FBO.
628 *
629 * This implementation relies on the frame buffer being at least RGBA 8888. When
630 * a layer is created, only a texture is created, not an FBO. The content of the
631 * frame buffer contained within the layer's bounds is copied into this texture
632 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
633 * buffer and drawing continues as normal. This technique therefore treats the
634 * frame buffer as a scratch buffer for the layers.
635 *
636 * To compose the layers back onto the frame buffer, each layer texture
637 * (containing the original frame buffer data) is drawn as a simple quad over
638 * the frame buffer. The trick is that the quad is set as the composition
639 * destination in the blending equation, and the frame buffer becomes the source
640 * of the composition.
641 *
642 * Drawing layers with an alpha value requires an extra step before composition.
643 * An empty quad is drawn over the layer's region in the frame buffer. This quad
644 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
645 * quad is used to multiply the colors in the frame buffer. This is achieved by
646 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
647 * GL_ZERO, GL_SRC_ALPHA.
648 *
649 * Because glCopyTexImage2D() can be slow, an alternative implementation might
650 * be use to draw a single clipped layer. The implementation described above
651 * is correct in every case.
652 *
653 * (1) The frame buffer is actually not cleared right away. To allow the GPU
654 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
655 *     buffer is left untouched until the first drawing operation. Only when
656 *     something actually gets drawn are the layers regions cleared.
657 */
658bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom,
659        const SkPaint* paint, int flags, const SkPath* convexMask) {
660    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
661    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
662
663    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
664
665    // Window coordinates of the layer
666    Rect clip;
667    Rect bounds(left, top, right, bottom);
668    calculateLayerBoundsAndClip(bounds, clip, fboLayer);
669    updateSnapshotIgnoreForLayer(bounds, clip, fboLayer, getAlphaDirect(paint));
670
671    // Bail out if we won't draw in this snapshot
672    if (mState.currentlyIgnored()) {
673        return false;
674    }
675
676    mCaches.textureState().activateTexture(0);
677    Layer* layer = mCaches.layerCache.get(mRenderState, bounds.getWidth(), bounds.getHeight());
678    if (!layer) {
679        return false;
680    }
681
682    layer->setPaint(paint);
683    layer->layer.set(bounds);
684    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()),
685            bounds.getWidth() / float(layer->getWidth()), 0.0f);
686
687    layer->setBlend(true);
688    layer->setDirty(false);
689    layer->setConvexMask(convexMask); // note: the mask must be cleared before returning to the cache
690
691    // Save the layer in the snapshot
692    writableSnapshot()->flags |= Snapshot::kFlagIsLayer;
693    writableSnapshot()->layer = layer;
694
695    ATRACE_FORMAT_BEGIN("%ssaveLayer %ux%u",
696            fboLayer ? "" : "unclipped ",
697            layer->getWidth(), layer->getHeight());
698    startMark("SaveLayer");
699    if (fboLayer) {
700        return createFboLayer(layer, bounds, clip);
701    } else {
702        // Copy the framebuffer into the layer
703        layer->bindTexture();
704        if (!bounds.isEmpty()) {
705            if (layer->isEmpty()) {
706                // Workaround for some GL drivers. When reading pixels lying outside
707                // of the window we should get undefined values for those pixels.
708                // Unfortunately some drivers will turn the entire target texture black
709                // when reading outside of the window.
710                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->getWidth(), layer->getHeight(),
711                        0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
712                layer->setEmpty(false);
713            }
714
715            glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
716                    bounds.left, getViewportHeight() - bounds.bottom,
717                    bounds.getWidth(), bounds.getHeight());
718
719            // Enqueue the buffer coordinates to clear the corresponding region later
720            mLayers.push_back(Rect(bounds));
721        }
722    }
723
724    return true;
725}
726
727bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip) {
728    layer->clipRect.set(clip);
729    layer->setFbo(mCaches.fboCache.get());
730
731    writableSnapshot()->region = &writableSnapshot()->layer->region;
732    writableSnapshot()->flags |= Snapshot::kFlagFboTarget | Snapshot::kFlagIsFboLayer;
733    writableSnapshot()->fbo = layer->getFbo();
734    writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f);
735    writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom);
736    writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight());
737    writableSnapshot()->roundRectClipState = nullptr;
738
739    endTiling();
740    debugOverdraw(false, false);
741    // Bind texture to FBO
742    mRenderState.bindFramebuffer(layer->getFbo());
743    layer->bindTexture();
744
745    // Initialize the texture if needed
746    if (layer->isEmpty()) {
747        layer->allocateTexture();
748        layer->setEmpty(false);
749    }
750
751    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
752            layer->getTextureId(), 0);
753
754    // Expand the startTiling region by 1
755    startTilingCurrentClip(true, true);
756
757    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
758    mRenderState.scissor().setEnabled(true);
759    mRenderState.scissor().set(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
760            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
761    glClear(GL_COLOR_BUFFER_BIT);
762
763    dirtyClip();
764
765    // Change the ortho projection
766    mRenderState.setViewport(bounds.getWidth(), bounds.getHeight());
767    return true;
768}
769
770/**
771 * Read the documentation of createLayer() before doing anything in this method.
772 */
773void OpenGLRenderer::composeLayer(const Snapshot& removed, const Snapshot& restored) {
774    if (!removed.layer) {
775        ALOGE("Attempting to compose a layer that does not exist");
776        return;
777    }
778
779    Layer* layer = removed.layer;
780    const Rect& rect = layer->layer;
781    const bool fboLayer = removed.flags & Snapshot::kFlagIsFboLayer;
782
783    bool clipRequired = false;
784    mState.calculateQuickRejectForScissor(rect.left, rect.top, rect.right, rect.bottom,
785            &clipRequired, nullptr, false); // safely ignore return, should never be rejected
786    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
787
788    if (fboLayer) {
789        endTiling();
790
791        // Detach the texture from the FBO
792        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
793
794        layer->removeFbo(false);
795
796        // Unbind current FBO and restore previous one
797        mRenderState.bindFramebuffer(restored.fbo);
798        debugOverdraw(true, false);
799
800        startTilingCurrentClip();
801    }
802
803    if (!fboLayer && layer->getAlpha() < 255) {
804        SkPaint layerPaint;
805        layerPaint.setAlpha(layer->getAlpha());
806        layerPaint.setXfermodeMode(SkXfermode::kDstIn_Mode);
807        layerPaint.setColorFilter(layer->getColorFilter());
808
809        drawColorRect(rect.left, rect.top, rect.right, rect.bottom, &layerPaint, true);
810        // Required below, composeLayerRect() will divide by 255
811        layer->setAlpha(255);
812    }
813
814    mRenderState.meshState().unbindMeshBuffer();
815
816    mCaches.textureState().activateTexture(0);
817
818    // When the layer is stored in an FBO, we can save a bit of fillrate by
819    // drawing only the dirty region
820    if (fboLayer) {
821        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *restored.transform);
822        composeLayerRegion(layer, rect);
823    } else if (!rect.isEmpty()) {
824        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
825
826        save(0);
827        // the layer contains screen buffer content that shouldn't be alpha modulated
828        // (and any necessary alpha modulation was handled drawing into the layer)
829        writableSnapshot()->alpha = 1.0f;
830        composeLayerRect(layer, rect, true);
831        restore();
832    }
833
834    dirtyClip();
835
836    // Failing to add the layer to the cache should happen only if the layer is too large
837    layer->setConvexMask(nullptr);
838    if (!mCaches.layerCache.put(layer)) {
839        LAYER_LOGD("Deleting layer");
840        layer->decStrong(nullptr);
841    }
842}
843
844void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
845    bool snap = !layer->getForceFilter()
846            && layer->getWidth() == (uint32_t) rect.getWidth()
847            && layer->getHeight() == (uint32_t) rect.getHeight();
848    Glop glop;
849    GlopBuilder(mRenderState, mCaches, &glop)
850            .setMeshTexturedUvQuad(nullptr, Rect(0, 1, 1, 0)) // TODO: simplify with VBO
851            .setFillTextureLayer(*layer, getLayerAlpha(layer))
852            .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
853            .setModelViewMapUnitToRectOptionalSnap(snap, rect)
854            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
855            .build();
856    renderGlop(glop);
857}
858
859void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
860    if (layer->isTextureLayer()) {
861        EVENT_LOGD("composeTextureLayerRect");
862        drawTextureLayer(layer, rect);
863    } else {
864        EVENT_LOGD("composeHardwareLayerRect");
865
866        Blend::ModeOrderSwap modeUsage = swap ?
867                Blend::ModeOrderSwap::Swap : Blend::ModeOrderSwap::NoSwap;
868        const Matrix4& transform = swap ? Matrix4::identity() : *currentTransform();
869        bool snap = !swap
870                && layer->getWidth() == static_cast<uint32_t>(rect.getWidth())
871                && layer->getHeight() == static_cast<uint32_t>(rect.getHeight());
872        Glop glop;
873        GlopBuilder(mRenderState, mCaches, &glop)
874                .setMeshTexturedUvQuad(nullptr, layer->texCoords)
875                .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), modeUsage)
876                .setTransform(currentSnapshot()->getOrthoMatrix(), transform, false)
877                .setModelViewMapUnitToRectOptionalSnap(snap, rect)
878                .setRoundRectClipState(currentSnapshot()->roundRectClipState)
879                .build();
880        renderGlop(glop);
881    }
882}
883
884/**
885 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated
886 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw
887 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used
888 * by saveLayer's restore
889 */
890#define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) { \
891        DRAW_COMMAND; \
892        if (CC_UNLIKELY(Properties::debugOverdraw && getTargetFbo() == 0 && COND)) { \
893            glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); \
894            DRAW_COMMAND; \
895            glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); \
896        } \
897    }
898
899#define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND)
900
901// This class is purely for inspection. It inherits from SkShader, but Skia does not know how to
902// use it. The OpenGLRenderer will look at it to find its Layer and whether it is opaque.
903class LayerShader : public SkShader {
904public:
905    LayerShader(Layer* layer, const SkMatrix* localMatrix)
906    : INHERITED(localMatrix)
907    , mLayer(layer) {
908    }
909
910    virtual bool asACustomShader(void** data) const override {
911        if (data) {
912            *data = static_cast<void*>(mLayer);
913        }
914        return true;
915    }
916
917    virtual bool isOpaque() const override {
918        return !mLayer->isBlend();
919    }
920
921protected:
922    virtual void shadeSpan(int x, int y, SkPMColor[], int count) {
923        LOG_ALWAYS_FATAL("LayerShader should never be drawn with raster backend.");
924    }
925
926    virtual void flatten(SkWriteBuffer&) const override {
927        LOG_ALWAYS_FATAL("LayerShader should never be flattened.");
928    }
929
930    virtual Factory getFactory() const override {
931        LOG_ALWAYS_FATAL("LayerShader should never be created from a stream.");
932        return nullptr;
933    }
934private:
935    // Unowned.
936    Layer* mLayer;
937    typedef SkShader INHERITED;
938};
939
940void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
941    if (CC_UNLIKELY(layer->region.isEmpty())) return; // nothing to draw
942
943    if (layer->getConvexMask()) {
944        save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag);
945
946        // clip to the area of the layer the mask can be larger
947        clipRect(rect.left, rect.top, rect.right, rect.bottom, SkRegion::kIntersect_Op);
948
949        SkPaint paint;
950        paint.setAntiAlias(true);
951        paint.setColor(SkColorSetARGB(int(getLayerAlpha(layer) * 255), 0, 0, 0));
952
953        // create LayerShader to map SaveLayer content into subsequent draw
954        SkMatrix shaderMatrix;
955        shaderMatrix.setTranslate(rect.left, rect.bottom);
956        shaderMatrix.preScale(1, -1);
957        LayerShader layerShader(layer, &shaderMatrix);
958        paint.setShader(&layerShader);
959
960        // Since the drawing primitive is defined in local drawing space,
961        // we don't need to modify the draw matrix
962        const SkPath* maskPath = layer->getConvexMask();
963        DRAW_DOUBLE_STENCIL(drawConvexPath(*maskPath, &paint));
964
965        paint.setShader(nullptr);
966        restore();
967
968        return;
969    }
970
971    if (layer->region.isRect()) {
972        layer->setRegionAsRect();
973
974        DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect));
975
976        layer->region.clear();
977        return;
978    }
979
980    EVENT_LOGD("composeLayerRegion");
981    // standard Region based draw
982    size_t count;
983    const android::Rect* rects;
984    Region safeRegion;
985    if (CC_LIKELY(hasRectToRectTransform())) {
986        rects = layer->region.getArray(&count);
987    } else {
988        safeRegion = Region::createTJunctionFreeRegion(layer->region);
989        rects = safeRegion.getArray(&count);
990    }
991
992    const float texX = 1.0f / float(layer->getWidth());
993    const float texY = 1.0f / float(layer->getHeight());
994    const float height = rect.getHeight();
995
996    TextureVertex quadVertices[count * 4];
997    TextureVertex* mesh = &quadVertices[0];
998    for (size_t i = 0; i < count; i++) {
999        const android::Rect* r = &rects[i];
1000
1001        const float u1 = r->left * texX;
1002        const float v1 = (height - r->top) * texY;
1003        const float u2 = r->right * texX;
1004        const float v2 = (height - r->bottom) * texY;
1005
1006        // TODO: Reject quads outside of the clip
1007        TextureVertex::set(mesh++, r->left, r->top, u1, v1);
1008        TextureVertex::set(mesh++, r->right, r->top, u2, v1);
1009        TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
1010        TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
1011    }
1012    Rect modelRect = Rect(rect.getWidth(), rect.getHeight());
1013    Glop glop;
1014    GlopBuilder(mRenderState, mCaches, &glop)
1015            .setMeshTexturedIndexedQuads(&quadVertices[0], count * 6)
1016            .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap)
1017            .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
1018            .setModelViewOffsetRectSnap(rect.left, rect.top, modelRect)
1019            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1020            .build();
1021    DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, renderGlop(glop));
1022
1023#if DEBUG_LAYERS_AS_REGIONS
1024    drawRegionRectsDebug(layer->region);
1025#endif
1026
1027    layer->region.clear();
1028}
1029
1030#if DEBUG_LAYERS_AS_REGIONS
1031void OpenGLRenderer::drawRegionRectsDebug(const Region& region) {
1032    size_t count;
1033    const android::Rect* rects = region.getArray(&count);
1034
1035    uint32_t colors[] = {
1036            0x7fff0000, 0x7f00ff00,
1037            0x7f0000ff, 0x7fff00ff,
1038    };
1039
1040    int offset = 0;
1041    int32_t top = rects[0].top;
1042
1043    for (size_t i = 0; i < count; i++) {
1044        if (top != rects[i].top) {
1045            offset ^= 0x2;
1046            top = rects[i].top;
1047        }
1048
1049        SkPaint paint;
1050        paint.setColor(colors[offset + (i & 0x1)]);
1051        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
1052        drawColorRect(r.left, r.top, r.right, r.bottom, paint);
1053    }
1054}
1055#endif
1056
1057void OpenGLRenderer::drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty) {
1058    Vector<float> rects;
1059
1060    SkRegion::Iterator it(region);
1061    while (!it.done()) {
1062        const SkIRect& r = it.rect();
1063        rects.push(r.fLeft);
1064        rects.push(r.fTop);
1065        rects.push(r.fRight);
1066        rects.push(r.fBottom);
1067        it.next();
1068    }
1069
1070    drawColorRects(rects.array(), rects.size(), &paint, true, dirty, false);
1071}
1072
1073void OpenGLRenderer::dirtyLayer(const float left, const float top,
1074        const float right, const float bottom, const Matrix4& transform) {
1075    if (hasLayer()) {
1076        Rect bounds(left, top, right, bottom);
1077        transform.mapRect(bounds);
1078        dirtyLayerUnchecked(bounds, getRegion());
1079    }
1080}
1081
1082void OpenGLRenderer::dirtyLayer(const float left, const float top,
1083        const float right, const float bottom) {
1084    if (hasLayer()) {
1085        Rect bounds(left, top, right, bottom);
1086        dirtyLayerUnchecked(bounds, getRegion());
1087    }
1088}
1089
1090void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
1091    if (bounds.intersect(mState.currentClipRect())) {
1092        bounds.snapToPixelBoundaries();
1093        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1094        if (!dirty.isEmpty()) {
1095            region->orSelf(dirty);
1096        }
1097    }
1098}
1099
1100void OpenGLRenderer::clearLayerRegions() {
1101    const size_t quadCount = mLayers.size();
1102    if (quadCount == 0) return;
1103
1104    if (!mState.currentlyIgnored()) {
1105        EVENT_LOGD("clearLayerRegions");
1106        // Doing several glScissor/glClear here can negatively impact
1107        // GPUs with a tiler architecture, instead we draw quads with
1108        // the Clear blending mode
1109
1110        // The list contains bounds that have already been clipped
1111        // against their initial clip rect, and the current clip
1112        // is likely different so we need to disable clipping here
1113        bool scissorChanged = mRenderState.scissor().setEnabled(false);
1114
1115        Vertex mesh[quadCount * 4];
1116        Vertex* vertex = mesh;
1117
1118        for (uint32_t i = 0; i < quadCount; i++) {
1119            const Rect& bounds = mLayers[i];
1120
1121            Vertex::set(vertex++, bounds.left, bounds.top);
1122            Vertex::set(vertex++, bounds.right, bounds.top);
1123            Vertex::set(vertex++, bounds.left, bounds.bottom);
1124            Vertex::set(vertex++, bounds.right, bounds.bottom);
1125        }
1126        // We must clear the list of dirty rects before we
1127        // call clearLayerRegions() in renderGlop to prevent
1128        // stencil setup from doing the same thing again
1129        mLayers.clear();
1130
1131        Glop glop;
1132        GlopBuilder(mRenderState, mCaches, &glop)
1133                .setMeshIndexedQuads(&mesh[0], quadCount)
1134                .setFillClear()
1135                .setTransform(currentSnapshot()->getOrthoMatrix(), Matrix4::identity(), false)
1136                .setModelViewOffsetRect(0, 0, Rect(currentSnapshot()->getClipRect()))
1137                .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1138                .build();
1139        renderGlop(glop, false);
1140
1141        if (scissorChanged) mRenderState.scissor().setEnabled(true);
1142    } else {
1143        mLayers.clear();
1144    }
1145}
1146
1147///////////////////////////////////////////////////////////////////////////////
1148// State Deferral
1149///////////////////////////////////////////////////////////////////////////////
1150
1151bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) {
1152    const Rect& currentClip = mState.currentClipRect();
1153    const mat4* currentMatrix = currentTransform();
1154
1155    if (stateDeferFlags & kStateDeferFlag_Draw) {
1156        // state has bounds initialized in local coordinates
1157        if (!state.mBounds.isEmpty()) {
1158            currentMatrix->mapRect(state.mBounds);
1159            Rect clippedBounds(state.mBounds);
1160            // NOTE: if we ever want to use this clipping info to drive whether the scissor
1161            // is used, it should more closely duplicate the quickReject logic (in how it uses
1162            // snapToPixelBoundaries)
1163
1164            if (!clippedBounds.intersect(currentClip)) {
1165                // quick rejected
1166                return true;
1167            }
1168
1169            state.mClipSideFlags = kClipSide_None;
1170            if (!currentClip.contains(state.mBounds)) {
1171                int& flags = state.mClipSideFlags;
1172                // op partially clipped, so record which sides are clipped for clip-aware merging
1173                if (currentClip.left > state.mBounds.left) flags |= kClipSide_Left;
1174                if (currentClip.top > state.mBounds.top) flags |= kClipSide_Top;
1175                if (currentClip.right < state.mBounds.right) flags |= kClipSide_Right;
1176                if (currentClip.bottom < state.mBounds.bottom) flags |= kClipSide_Bottom;
1177            }
1178            state.mBounds.set(clippedBounds);
1179        } else {
1180            // Empty bounds implies size unknown. Label op as conservatively clipped to disable
1181            // overdraw avoidance (since we don't know what it overlaps)
1182            state.mClipSideFlags = kClipSide_ConservativeFull;
1183            state.mBounds.set(currentClip);
1184        }
1185    }
1186
1187    state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip);
1188    if (state.mClipValid) {
1189        state.mClip.set(currentClip);
1190    }
1191
1192    // Transform and alpha always deferred, since they are used by state operations
1193    // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything)
1194    state.mMatrix.load(*currentMatrix);
1195    state.mAlpha = currentSnapshot()->alpha;
1196
1197    // always store/restore, since these are just pointers
1198    state.mRoundRectClipState = currentSnapshot()->roundRectClipState;
1199    state.mProjectionPathMask = currentSnapshot()->projectionPathMask;
1200    return false;
1201}
1202
1203void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) {
1204    setMatrix(state.mMatrix);
1205    writableSnapshot()->alpha = state.mAlpha;
1206    writableSnapshot()->roundRectClipState = state.mRoundRectClipState;
1207    writableSnapshot()->projectionPathMask = state.mProjectionPathMask;
1208
1209    if (state.mClipValid && !skipClipRestore) {
1210        writableSnapshot()->setClip(state.mClip.left, state.mClip.top,
1211                state.mClip.right, state.mClip.bottom);
1212        dirtyClip();
1213    }
1214}
1215
1216/**
1217 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done
1218 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at
1219 * least one op is clipped), or disabled entirely (because no merged op is clipped)
1220 *
1221 * This method should be called when restoreDisplayState() won't be restoring the clip
1222 */
1223void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) {
1224    if (clipRect != nullptr) {
1225        writableSnapshot()->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom);
1226    } else {
1227        writableSnapshot()->setClip(0, 0, mState.getWidth(), mState.getHeight());
1228    }
1229    dirtyClip();
1230    bool enableScissor = (clipRect != nullptr) || mScissorOptimizationDisabled;
1231    mRenderState.scissor().setEnabled(enableScissor);
1232}
1233
1234///////////////////////////////////////////////////////////////////////////////
1235// Clipping
1236///////////////////////////////////////////////////////////////////////////////
1237
1238void OpenGLRenderer::setScissorFromClip() {
1239    Rect clip(mState.currentClipRect());
1240    clip.snapToPixelBoundaries();
1241
1242    if (mRenderState.scissor().set(clip.left, getViewportHeight() - clip.bottom,
1243            clip.getWidth(), clip.getHeight())) {
1244        mState.setDirtyClip(false);
1245    }
1246}
1247
1248void OpenGLRenderer::ensureStencilBuffer() {
1249    // Thanks to the mismatch between EGL and OpenGL ES FBO we
1250    // cannot attach a stencil buffer to fbo0 dynamically. Let's
1251    // just hope we have one when hasLayer() returns false.
1252    if (hasLayer()) {
1253        attachStencilBufferToLayer(currentSnapshot()->layer);
1254    }
1255}
1256
1257void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) {
1258    // The layer's FBO is already bound when we reach this stage
1259    if (!layer->getStencilRenderBuffer()) {
1260        // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer
1261        // is attached after we initiated tiling. We must turn it off,
1262        // attach the new render buffer then turn tiling back on
1263        endTiling();
1264
1265        RenderBuffer* buffer = mCaches.renderBufferCache.get(
1266                Stencil::getLayerStencilFormat(),
1267                layer->getWidth(), layer->getHeight());
1268        layer->setStencilRenderBuffer(buffer);
1269
1270        startTiling(layer->clipRect, layer->layer.getHeight());
1271    }
1272}
1273
1274static void handlePoint(std::vector<Vertex>& rectangleVertices, const Matrix4& transform,
1275        float x, float y) {
1276    Vertex v;
1277    v.x = x;
1278    v.y = y;
1279    transform.mapPoint(v.x, v.y);
1280    rectangleVertices.push_back(v);
1281}
1282
1283static void handlePointNoTransform(std::vector<Vertex>& rectangleVertices, float x, float y) {
1284    Vertex v;
1285    v.x = x;
1286    v.y = y;
1287    rectangleVertices.push_back(v);
1288}
1289
1290void OpenGLRenderer::drawRectangleList(const RectangleList& rectangleList) {
1291    int quadCount = rectangleList.getTransformedRectanglesCount();
1292    std::vector<Vertex> rectangleVertices(quadCount * 4);
1293    Rect scissorBox = rectangleList.calculateBounds();
1294    scissorBox.snapToPixelBoundaries();
1295    for (int i = 0; i < quadCount; ++i) {
1296        const TransformedRectangle& tr(rectangleList.getTransformedRectangle(i));
1297        const Matrix4& transform = tr.getTransform();
1298        Rect bounds = tr.getBounds();
1299        if (transform.rectToRect()) {
1300            transform.mapRect(bounds);
1301            if (!bounds.intersect(scissorBox)) {
1302                bounds.setEmpty();
1303            } else {
1304                handlePointNoTransform(rectangleVertices, bounds.left, bounds.top);
1305                handlePointNoTransform(rectangleVertices, bounds.right, bounds.top);
1306                handlePointNoTransform(rectangleVertices, bounds.left, bounds.bottom);
1307                handlePointNoTransform(rectangleVertices, bounds.right, bounds.bottom);
1308            }
1309        } else {
1310            handlePoint(rectangleVertices, transform, bounds.left, bounds.top);
1311            handlePoint(rectangleVertices, transform, bounds.right, bounds.top);
1312            handlePoint(rectangleVertices, transform, bounds.left, bounds.bottom);
1313            handlePoint(rectangleVertices, transform, bounds.right, bounds.bottom);
1314        }
1315    }
1316
1317    mRenderState.scissor().set(scissorBox.left, getViewportHeight() - scissorBox.bottom,
1318            scissorBox.getWidth(), scissorBox.getHeight());
1319
1320    Glop glop;
1321    Vertex* vertices = &rectangleVertices[0];
1322    GlopBuilder(mRenderState, mCaches, &glop)
1323            .setMeshIndexedQuads(vertices, rectangleVertices.size() / 4)
1324            .setFillBlack()
1325            .setTransform(currentSnapshot()->getOrthoMatrix(), Matrix4::identity(), false)
1326            .setModelViewOffsetRect(0, 0, scissorBox)
1327            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1328            .build();
1329    renderGlop(glop);
1330}
1331
1332void OpenGLRenderer::setStencilFromClip() {
1333    if (!Properties::debugOverdraw) {
1334        if (!currentSnapshot()->clipIsSimple()) {
1335            int incrementThreshold;
1336            EVENT_LOGD("setStencilFromClip - enabling");
1337
1338            // NOTE: The order here is important, we must set dirtyClip to false
1339            //       before any draw call to avoid calling back into this method
1340            mState.setDirtyClip(false);
1341
1342            ensureStencilBuffer();
1343
1344            const ClipArea& clipArea = currentSnapshot()->getClipArea();
1345
1346            bool isRectangleList = clipArea.isRectangleList();
1347            if (isRectangleList) {
1348                incrementThreshold = clipArea.getRectangleList().getTransformedRectanglesCount();
1349            } else {
1350                incrementThreshold = 0;
1351            }
1352
1353            mRenderState.stencil().enableWrite(incrementThreshold);
1354
1355            // Clean and update the stencil, but first make sure we restrict drawing
1356            // to the region's bounds
1357            bool resetScissor = mRenderState.scissor().setEnabled(true);
1358            if (resetScissor) {
1359                // The scissor was not set so we now need to update it
1360                setScissorFromClip();
1361            }
1362
1363            mRenderState.stencil().clear();
1364
1365            // stash and disable the outline clip state, since stencil doesn't account for outline
1366            bool storedSkipOutlineClip = mSkipOutlineClip;
1367            mSkipOutlineClip = true;
1368
1369            SkPaint paint;
1370            paint.setColor(SK_ColorBLACK);
1371            paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1372
1373            if (isRectangleList) {
1374                drawRectangleList(clipArea.getRectangleList());
1375            } else {
1376                // NOTE: We could use the region contour path to generate a smaller mesh
1377                //       Since we are using the stencil we could use the red book path
1378                //       drawing technique. It might increase bandwidth usage though.
1379
1380                // The last parameter is important: we are not drawing in the color buffer
1381                // so we don't want to dirty the current layer, if any
1382                drawRegionRects(clipArea.getClipRegion(), paint, false);
1383            }
1384            if (resetScissor) mRenderState.scissor().setEnabled(false);
1385            mSkipOutlineClip = storedSkipOutlineClip;
1386
1387            mRenderState.stencil().enableTest(incrementThreshold);
1388
1389            // Draw the region used to generate the stencil if the appropriate debug
1390            // mode is enabled
1391            // TODO: Implement for rectangle list clip areas
1392            if (Properties::debugStencilClip == StencilClipDebug::ShowRegion
1393                    && !clipArea.isRectangleList()) {
1394                paint.setColor(0x7f0000ff);
1395                paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
1396                drawRegionRects(currentSnapshot()->getClipRegion(), paint);
1397            }
1398        } else {
1399            EVENT_LOGD("setStencilFromClip - disabling");
1400            mRenderState.stencil().disable();
1401        }
1402    }
1403}
1404
1405/**
1406 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out.
1407 *
1408 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint
1409 *         style, and tessellated AA ramp
1410 */
1411bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom,
1412        const SkPaint* paint) {
1413    bool snapOut = paint && paint->isAntiAlias();
1414
1415    if (paint && paint->getStyle() != SkPaint::kFill_Style) {
1416        float outset = paint->getStrokeWidth() * 0.5f;
1417        left -= outset;
1418        top -= outset;
1419        right += outset;
1420        bottom += outset;
1421    }
1422
1423    bool clipRequired = false;
1424    bool roundRectClipRequired = false;
1425    if (mState.calculateQuickRejectForScissor(left, top, right, bottom,
1426            &clipRequired, &roundRectClipRequired, snapOut)) {
1427        return true;
1428    }
1429
1430    // not quick rejected, so enable the scissor if clipRequired
1431    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
1432    mSkipOutlineClip = !roundRectClipRequired;
1433    return false;
1434}
1435
1436void OpenGLRenderer::debugClip() {
1437#if DEBUG_CLIP_REGIONS
1438    if (!currentSnapshot()->clipRegion->isEmpty()) {
1439        SkPaint paint;
1440        paint.setColor(0x7f00ff00);
1441        drawRegionRects(*(currentSnapshot()->clipRegion, paint);
1442
1443    }
1444#endif
1445}
1446
1447void OpenGLRenderer::renderGlop(const Glop& glop, bool clearLayer) {
1448    // TODO: It would be best if we could do this before quickRejectSetupScissor()
1449    //       changes the scissor test state
1450    if (clearLayer) clearLayerRegions();
1451
1452    if (mState.getDirtyClip()) {
1453        if (mRenderState.scissor().isEnabled()) {
1454            setScissorFromClip();
1455        }
1456
1457        setStencilFromClip();
1458    }
1459    mRenderState.render(glop);
1460    if (!mRenderState.stencil().isWriteEnabled()) {
1461        // TODO: specify more clearly when a draw should dirty the layer.
1462        // is writing to the stencil the only time we should ignore this?
1463        dirtyLayer(glop.bounds.left, glop.bounds.top, glop.bounds.right, glop.bounds.bottom);
1464        mDirty = true;
1465    }
1466}
1467
1468///////////////////////////////////////////////////////////////////////////////
1469// Drawing
1470///////////////////////////////////////////////////////////////////////////////
1471
1472void OpenGLRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty, int32_t replayFlags) {
1473    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1474    // will be performed by the display list itself
1475    if (renderNode && renderNode->isRenderable()) {
1476        // compute 3d ordering
1477        renderNode->computeOrdering();
1478        if (CC_UNLIKELY(Properties::drawDeferDisabled)) {
1479            startFrame();
1480            ReplayStateStruct replayStruct(*this, dirty, replayFlags);
1481            renderNode->replay(replayStruct, 0);
1482            return;
1483        }
1484
1485        // Don't avoid overdraw when visualizing, since that makes it harder to
1486        // debug where it's coming from, and when the problem occurs.
1487        bool avoidOverdraw = !Properties::debugOverdraw;
1488        DeferredDisplayList deferredList(mState.currentClipRect(), avoidOverdraw);
1489        DeferStateStruct deferStruct(deferredList, *this, replayFlags);
1490        renderNode->defer(deferStruct, 0);
1491
1492        flushLayers();
1493        startFrame();
1494
1495        deferredList.flush(*this, dirty);
1496    } else {
1497        // Even if there is no drawing command(Ex: invisible),
1498        // it still needs startFrame to clear buffer and start tiling.
1499        startFrame();
1500    }
1501}
1502
1503/**
1504 * Important note: this method is intended to draw batches of bitmaps and
1505 * will not set the scissor enable or dirty the current layer, if any.
1506 * The caller is responsible for properly dirtying the current layer.
1507 */
1508void OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
1509        int bitmapCount, TextureVertex* vertices, bool pureTranslate,
1510        const Rect& bounds, const SkPaint* paint) {
1511    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
1512    if (!texture) return;
1513
1514    const AutoTexture autoCleanup(texture);
1515
1516    // TODO: remove layer dirty in multi-draw callers
1517    // TODO: snap doesn't need to touch transform, only texture filter.
1518    bool snap = pureTranslate;
1519    const float x = floorf(bounds.left + 0.5f);
1520    const float y = floorf(bounds.top + 0.5f);
1521    int textureFillFlags = static_cast<int>((bitmap->colorType() == kAlpha_8_SkColorType)
1522            ? TextureFillFlags::kIsAlphaMaskTexture : TextureFillFlags::kNone);
1523    Glop glop;
1524    GlopBuilder(mRenderState, mCaches, &glop)
1525            .setMeshTexturedMesh(vertices, bitmapCount * 6)
1526            .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1527            .setTransform(currentSnapshot()->getOrthoMatrix(), Matrix4::identity(), false)
1528            .setModelViewOffsetRectOptionalSnap(snap, x, y, Rect(0, 0, bounds.getWidth(), bounds.getHeight()))
1529            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1530            .build();
1531    renderGlop(glop);
1532}
1533
1534void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) {
1535    if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) {
1536        return;
1537    }
1538
1539    mCaches.textureState().activateTexture(0);
1540    Texture* texture = getTexture(bitmap);
1541    if (!texture) return;
1542    const AutoTexture autoCleanup(texture);
1543
1544    int textureFillFlags = static_cast<int>((bitmap->colorType() == kAlpha_8_SkColorType)
1545            ? TextureFillFlags::kIsAlphaMaskTexture : TextureFillFlags::kNone);
1546    Glop glop;
1547    GlopBuilder(mRenderState, mCaches, &glop)
1548            .setMeshTexturedUnitQuad(texture->uvMapper)
1549            .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1550            .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
1551            .setModelViewMapUnitToRectSnap(Rect(0, 0, texture->width, texture->height))
1552            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1553            .build();
1554    renderGlop(glop);
1555}
1556
1557void OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
1558        const float* vertices, const int* colors, const SkPaint* paint) {
1559    if (!vertices || mState.currentlyIgnored()) {
1560        return;
1561    }
1562
1563    float left = FLT_MAX;
1564    float top = FLT_MAX;
1565    float right = FLT_MIN;
1566    float bottom = FLT_MIN;
1567
1568    const uint32_t elementCount = meshWidth * meshHeight * 6;
1569
1570    std::unique_ptr<ColorTextureVertex[]> mesh(new ColorTextureVertex[elementCount]);
1571    ColorTextureVertex* vertex = &mesh[0];
1572
1573    std::unique_ptr<int[]> tempColors;
1574    if (!colors) {
1575        uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1);
1576        tempColors.reset(new int[colorsCount]);
1577        memset(tempColors.get(), 0xff, colorsCount * sizeof(int));
1578        colors = tempColors.get();
1579    }
1580
1581    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
1582    const UvMapper& mapper(getMapper(texture));
1583
1584    for (int32_t y = 0; y < meshHeight; y++) {
1585        for (int32_t x = 0; x < meshWidth; x++) {
1586            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1587
1588            float u1 = float(x) / meshWidth;
1589            float u2 = float(x + 1) / meshWidth;
1590            float v1 = float(y) / meshHeight;
1591            float v2 = float(y + 1) / meshHeight;
1592
1593            mapper.map(u1, v1, u2, v2);
1594
1595            int ax = i + (meshWidth + 1) * 2;
1596            int ay = ax + 1;
1597            int bx = i;
1598            int by = bx + 1;
1599            int cx = i + 2;
1600            int cy = cx + 1;
1601            int dx = i + (meshWidth + 1) * 2 + 2;
1602            int dy = dx + 1;
1603
1604            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
1605            ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
1606            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
1607
1608            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
1609            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
1610            ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
1611
1612            left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1613            top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1614            right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1615            bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1616        }
1617    }
1618
1619    if (quickRejectSetupScissor(left, top, right, bottom)) {
1620        return;
1621    }
1622
1623    if (!texture) {
1624        texture = mCaches.textureCache.get(bitmap);
1625        if (!texture) {
1626            return;
1627        }
1628    }
1629    const AutoTexture autoCleanup(texture);
1630
1631    /*
1632     * TODO: handle alpha_8 textures correctly by applying paint color, but *not*
1633     * shader in that case to mimic the behavior in SkiaCanvas::drawBitmapMesh.
1634     */
1635    Glop glop;
1636    GlopBuilder(mRenderState, mCaches, &glop)
1637            .setMeshColoredTexturedMesh(mesh.get(), elementCount)
1638            .setFillTexturePaint(*texture, static_cast<int>(TextureFillFlags::kNone), paint, currentSnapshot()->alpha)
1639            .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
1640            .setModelViewOffsetRect(0, 0, Rect(left, top, right, bottom))
1641            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1642            .build();
1643    renderGlop(glop);
1644}
1645
1646void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, Rect src, Rect dst, const SkPaint* paint) {
1647    if (quickRejectSetupScissor(dst)) {
1648        return;
1649    }
1650
1651    Texture* texture = getTexture(bitmap);
1652    if (!texture) return;
1653    const AutoTexture autoCleanup(texture);
1654
1655    Rect uv(fmax(0.0f, src.left / texture->width),
1656            fmax(0.0f, src.top / texture->height),
1657            fmin(1.0f, src.right / texture->width),
1658            fmin(1.0f, src.bottom / texture->height));
1659
1660    int textureFillFlags = static_cast<int>((bitmap->colorType() == kAlpha_8_SkColorType)
1661            ? TextureFillFlags::kIsAlphaMaskTexture : TextureFillFlags::kNone);
1662    Glop glop;
1663    GlopBuilder(mRenderState, mCaches, &glop)
1664            .setMeshTexturedUvQuad(texture->uvMapper, uv)
1665            .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1666            .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
1667            .setModelViewMapUnitToRectSnap(dst)
1668            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1669            .build();
1670    renderGlop(glop);
1671}
1672
1673void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh,
1674        AssetAtlas::Entry* entry, float left, float top, float right, float bottom,
1675        const SkPaint* paint) {
1676    if (!mesh || !mesh->verticesCount || quickRejectSetupScissor(left, top, right, bottom)) {
1677        return;
1678    }
1679
1680    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
1681    if (!texture) return;
1682
1683    // 9 patches are built for stretching - always filter
1684    int textureFillFlags = static_cast<int>(TextureFillFlags::kForceFilter);
1685    if (bitmap->colorType() == kAlpha_8_SkColorType) {
1686        textureFillFlags |= TextureFillFlags::kIsAlphaMaskTexture;
1687    }
1688    Glop glop;
1689    GlopBuilder(mRenderState, mCaches, &glop)
1690            .setMeshPatchQuads(*mesh)
1691            .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1692            .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
1693            .setModelViewOffsetRectSnap(left, top, Rect(0, 0, right - left, bottom - top)) // TODO: get minimal bounds from patch
1694            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1695            .build();
1696    renderGlop(glop);
1697}
1698
1699/**
1700 * Important note: this method is intended to draw batches of 9-patch objects and
1701 * will not set the scissor enable or dirty the current layer, if any.
1702 * The caller is responsible for properly dirtying the current layer.
1703 */
1704void OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
1705        TextureVertex* vertices, uint32_t elementCount, const SkPaint* paint) {
1706    mCaches.textureState().activateTexture(0);
1707    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
1708    if (!texture) return;
1709    const AutoTexture autoCleanup(texture);
1710
1711    // TODO: get correct bounds from caller
1712    // 9 patches are built for stretching - always filter
1713    int textureFillFlags = static_cast<int>(TextureFillFlags::kForceFilter);
1714    if (bitmap->colorType() == kAlpha_8_SkColorType) {
1715        textureFillFlags |= TextureFillFlags::kIsAlphaMaskTexture;
1716    }
1717    Glop glop;
1718    GlopBuilder(mRenderState, mCaches, &glop)
1719            .setMeshTexturedIndexedQuads(vertices, elementCount)
1720            .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1721            .setTransform(currentSnapshot()->getOrthoMatrix(), Matrix4::identity(), false)
1722            .setModelViewOffsetRect(0, 0, Rect(0, 0, 0, 0))
1723            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1724            .build();
1725    renderGlop(glop);
1726}
1727
1728void OpenGLRenderer::drawVertexBuffer(float translateX, float translateY,
1729        const VertexBuffer& vertexBuffer, const SkPaint* paint, int displayFlags) {
1730    // not missing call to quickReject/dirtyLayer, always done at a higher level
1731    if (!vertexBuffer.getVertexCount()) {
1732        // no vertices to draw
1733        return;
1734    }
1735
1736    bool fudgeOffset = displayFlags & kVertexBuffer_Offset;
1737    bool shadowInterp = displayFlags & kVertexBuffer_ShadowInterp;
1738    Glop glop;
1739    GlopBuilder(mRenderState, mCaches, &glop)
1740            .setMeshVertexBuffer(vertexBuffer, shadowInterp)
1741            .setFillPaint(*paint, currentSnapshot()->alpha)
1742            .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), fudgeOffset)
1743            .setModelViewOffsetRect(translateX, translateY, vertexBuffer.getBounds())
1744            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1745            .build();
1746    renderGlop(glop);
1747}
1748
1749/**
1750 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
1751 * that of AA lines in the drawLines() function.  We expand the convex path by a half pixel in
1752 * screen space in all directions. However, instead of using a fragment shader to compute the
1753 * translucency of the color from its position, we simply use a varying parameter to define how far
1754 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
1755 *
1756 * Doesn't yet support joins, caps, or path effects.
1757 */
1758void OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) {
1759    VertexBuffer vertexBuffer;
1760    // TODO: try clipping large paths to viewport
1761
1762    PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer);
1763    drawVertexBuffer(vertexBuffer, paint);
1764}
1765
1766/**
1767 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha
1768 * and additional geometry for defining an alpha slope perimeter.
1769 *
1770 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some
1771 * unexpected results, and may vary between hardware devices. Previously we used a varying-base
1772 * in-shader alpha region, but found it to be taxing on some GPUs.
1773 *
1774 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce
1775 * memory transfer by removing need for degenerate vertices.
1776 */
1777void OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) {
1778    if (mState.currentlyIgnored() || count < 4) return;
1779
1780    count &= ~0x3; // round down to nearest four
1781
1782    VertexBuffer buffer;
1783    PathTessellator::tessellateLines(points, count, paint, *currentTransform(), buffer);
1784    const Rect& bounds = buffer.getBounds();
1785
1786    if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
1787        return;
1788    }
1789
1790    int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
1791    drawVertexBuffer(buffer, paint, displayFlags);
1792}
1793
1794void OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) {
1795    if (mState.currentlyIgnored() || count < 2) return;
1796
1797    count &= ~0x1; // round down to nearest two
1798
1799    VertexBuffer buffer;
1800    PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), buffer);
1801
1802    const Rect& bounds = buffer.getBounds();
1803    if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
1804        return;
1805    }
1806
1807    int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
1808    drawVertexBuffer(buffer, paint, displayFlags);
1809
1810    mDirty = true;
1811}
1812
1813void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1814    // No need to check against the clip, we fill the clip region
1815    if (mState.currentlyIgnored()) return;
1816
1817    Rect clip(mState.currentClipRect());
1818    clip.snapToPixelBoundaries();
1819
1820    SkPaint paint;
1821    paint.setColor(color);
1822    paint.setXfermodeMode(mode);
1823
1824    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true);
1825
1826    mDirty = true;
1827}
1828
1829void OpenGLRenderer::drawShape(float left, float top, PathTexture* texture,
1830        const SkPaint* paint) {
1831    if (!texture) return;
1832    const AutoTexture autoCleanup(texture);
1833
1834    const float x = left + texture->left - texture->offset;
1835    const float y = top + texture->top - texture->offset;
1836
1837    drawPathTexture(texture, x, y, paint);
1838
1839    mDirty = true;
1840}
1841
1842void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
1843        float rx, float ry, const SkPaint* p) {
1844    if (mState.currentlyIgnored()
1845            || quickRejectSetupScissor(left, top, right, bottom, p)
1846            || PaintUtils::paintWillNotDraw(*p)) {
1847        return;
1848    }
1849
1850    if (p->getPathEffect() != nullptr) {
1851        mCaches.textureState().activateTexture(0);
1852        PathTexture* texture = mCaches.pathCache.getRoundRect(
1853                right - left, bottom - top, rx, ry, p);
1854        drawShape(left, top, texture, p);
1855    } else {
1856        const VertexBuffer* vertexBuffer = mCaches.tessellationCache.getRoundRect(
1857                *currentTransform(), *p, right - left, bottom - top, rx, ry);
1858        drawVertexBuffer(left, top, *vertexBuffer, p);
1859    }
1860}
1861
1862void OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) {
1863    if (mState.currentlyIgnored()
1864            || quickRejectSetupScissor(x - radius, y - radius, x + radius, y + radius, p)
1865            || PaintUtils::paintWillNotDraw(*p)) {
1866        return;
1867    }
1868
1869    if (p->getPathEffect() != nullptr) {
1870        mCaches.textureState().activateTexture(0);
1871        PathTexture* texture = mCaches.pathCache.getCircle(radius, p);
1872        drawShape(x - radius, y - radius, texture, p);
1873        return;
1874    }
1875
1876    SkPath path;
1877    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
1878        path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
1879    } else {
1880        path.addCircle(x, y, radius);
1881    }
1882
1883    if (CC_UNLIKELY(currentSnapshot()->projectionPathMask != nullptr)) {
1884        // mask ripples with projection mask
1885        SkPath maskPath = *(currentSnapshot()->projectionPathMask->projectionMask);
1886
1887        Matrix4 screenSpaceTransform;
1888        currentSnapshot()->buildScreenSpaceTransform(&screenSpaceTransform);
1889
1890        Matrix4 totalTransform;
1891        totalTransform.loadInverse(screenSpaceTransform);
1892        totalTransform.multiply(currentSnapshot()->projectionPathMask->projectionMaskTransform);
1893
1894        SkMatrix skTotalTransform;
1895        totalTransform.copyTo(skTotalTransform);
1896        maskPath.transform(skTotalTransform);
1897
1898        // Mask the ripple path by the projection mask, now that it's
1899        // in local space. Note that this can create CCW paths.
1900        Op(path, maskPath, kIntersect_PathOp, &path);
1901    }
1902    drawConvexPath(path, p);
1903}
1904
1905void OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
1906        const SkPaint* p) {
1907    if (mState.currentlyIgnored()
1908            || quickRejectSetupScissor(left, top, right, bottom, p)
1909            || PaintUtils::paintWillNotDraw(*p)) {
1910        return;
1911    }
1912
1913    if (p->getPathEffect() != nullptr) {
1914        mCaches.textureState().activateTexture(0);
1915        PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p);
1916        drawShape(left, top, texture, p);
1917    } else {
1918        SkPath path;
1919        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
1920        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
1921            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
1922        }
1923        path.addOval(rect);
1924        drawConvexPath(path, p);
1925    }
1926}
1927
1928void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
1929        float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) {
1930    if (mState.currentlyIgnored()
1931            || quickRejectSetupScissor(left, top, right, bottom, p)
1932            || PaintUtils::paintWillNotDraw(*p)) {
1933        return;
1934    }
1935
1936    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
1937    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != nullptr || useCenter) {
1938        mCaches.textureState().activateTexture(0);
1939        PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top,
1940                startAngle, sweepAngle, useCenter, p);
1941        drawShape(left, top, texture, p);
1942        return;
1943    }
1944    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
1945    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
1946        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
1947    }
1948
1949    SkPath path;
1950    if (useCenter) {
1951        path.moveTo(rect.centerX(), rect.centerY());
1952    }
1953    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
1954    if (useCenter) {
1955        path.close();
1956    }
1957    drawConvexPath(path, p);
1958}
1959
1960// See SkPaintDefaults.h
1961#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
1962
1963void OpenGLRenderer::drawRect(float left, float top, float right, float bottom,
1964        const SkPaint* p) {
1965    if (mState.currentlyIgnored()
1966            || quickRejectSetupScissor(left, top, right, bottom, p)
1967            || PaintUtils::paintWillNotDraw(*p)) {
1968        return;
1969    }
1970
1971    if (p->getStyle() != SkPaint::kFill_Style) {
1972        // only fill style is supported by drawConvexPath, since others have to handle joins
1973        if (p->getPathEffect() != nullptr || p->getStrokeJoin() != SkPaint::kMiter_Join ||
1974                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
1975            mCaches.textureState().activateTexture(0);
1976            PathTexture* texture =
1977                    mCaches.pathCache.getRect(right - left, bottom - top, p);
1978            drawShape(left, top, texture, p);
1979        } else {
1980            SkPath path;
1981            SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
1982            if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
1983                rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
1984            }
1985            path.addRect(rect);
1986            drawConvexPath(path, p);
1987        }
1988    } else {
1989        if (p->isAntiAlias() && !currentTransform()->isSimple()) {
1990            SkPath path;
1991            path.addRect(left, top, right, bottom);
1992            drawConvexPath(path, p);
1993        } else {
1994            drawColorRect(left, top, right, bottom, p);
1995
1996            mDirty = true;
1997        }
1998    }
1999}
2000
2001void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text,
2002        int bytesCount, int count, const float* positions,
2003        FontRenderer& fontRenderer, int alpha, float x, float y) {
2004    mCaches.textureState().activateTexture(0);
2005
2006    TextShadow textShadow;
2007    if (!getTextShadow(paint, &textShadow)) {
2008        LOG_ALWAYS_FATAL("failed to query shadow attributes");
2009    }
2010
2011    // NOTE: The drop shadow will not perform gamma correction
2012    //       if shader-based correction is enabled
2013    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2014    ShadowTexture* texture = mCaches.dropShadowCache.get(
2015            paint, text, bytesCount, count, textShadow.radius, positions);
2016    // If the drop shadow exceeds the max texture size or couldn't be
2017    // allocated, skip drawing
2018    if (!texture) return;
2019    const AutoTexture autoCleanup(texture);
2020
2021    const float sx = x - texture->left + textShadow.dx;
2022    const float sy = y - texture->top + textShadow.dy;
2023
2024    Glop glop;
2025    GlopBuilder(mRenderState, mCaches, &glop)
2026            .setMeshTexturedUnitQuad(nullptr)
2027            .setFillShadowTexturePaint(*texture, textShadow.color, *paint, currentSnapshot()->alpha)
2028            .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
2029            .setModelViewMapUnitToRect(Rect(sx, sy, sx + texture->width, sy + texture->height))
2030            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2031            .build();
2032    renderGlop(glop);
2033}
2034
2035bool OpenGLRenderer::canSkipText(const SkPaint* paint) const {
2036    float alpha = (hasTextShadow(paint) ? 1.0f : paint->getAlpha()) * currentSnapshot()->alpha;
2037    return MathUtils::isZero(alpha)
2038            && PaintUtils::getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode;
2039}
2040
2041void OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2042        const float* positions, const SkPaint* paint) {
2043    if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2044        return;
2045    }
2046
2047    // NOTE: Skia does not support perspective transform on drawPosText yet
2048    if (!currentTransform()->isSimple()) {
2049        return;
2050    }
2051
2052    mRenderState.scissor().setEnabled(true);
2053
2054    float x = 0.0f;
2055    float y = 0.0f;
2056    const bool pureTranslate = currentTransform()->isPureTranslate();
2057    if (pureTranslate) {
2058        x = floorf(x + currentTransform()->getTranslateX() + 0.5f);
2059        y = floorf(y + currentTransform()->getTranslateY() + 0.5f);
2060    }
2061
2062    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2063    fontRenderer.setFont(paint, SkMatrix::I());
2064
2065    int alpha;
2066    SkXfermode::Mode mode;
2067    getAlphaAndMode(paint, &alpha, &mode);
2068
2069    if (CC_UNLIKELY(hasTextShadow(paint))) {
2070        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2071                alpha, 0.0f, 0.0f);
2072    }
2073
2074    // Pick the appropriate texture filtering
2075    bool linearFilter = currentTransform()->changesBounds();
2076    if (pureTranslate && !linearFilter) {
2077        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2078    }
2079    fontRenderer.setTextureFiltering(linearFilter);
2080
2081    const Rect& clip(pureTranslate ? writableSnapshot()->getClipRect() : writableSnapshot()->getLocalClip());
2082    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2083
2084    TextDrawFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2085    if (fontRenderer.renderPosText(paint, &clip, text, 0, bytesCount, count, x, y,
2086            positions, hasLayer() ? &bounds : nullptr, &functor)) {
2087        dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform());
2088        mDirty = true;
2089    }
2090
2091}
2092
2093bool OpenGLRenderer::findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const {
2094    if (CC_LIKELY(transform.isPureTranslate())) {
2095        outMatrix->setIdentity();
2096        return false;
2097    } else if (CC_UNLIKELY(transform.isPerspective())) {
2098        outMatrix->setIdentity();
2099        return true;
2100    }
2101
2102    /**
2103     * Input is a non-perspective, scaling transform. Generate a scale-only transform,
2104     * with values rounded to the nearest int.
2105     */
2106    float sx, sy;
2107    transform.decomposeScale(sx, sy);
2108    outMatrix->setScale(
2109            roundf(fmaxf(1.0f, sx)),
2110            roundf(fmaxf(1.0f, sy)));
2111    return true;
2112}
2113
2114int OpenGLRenderer::getSaveCount() const {
2115    return mState.getSaveCount();
2116}
2117
2118int OpenGLRenderer::save(int flags) {
2119    return mState.save(flags);
2120}
2121
2122void OpenGLRenderer::restore() {
2123    mState.restore();
2124}
2125
2126void OpenGLRenderer::restoreToCount(int saveCount) {
2127    mState.restoreToCount(saveCount);
2128}
2129
2130void OpenGLRenderer::translate(float dx, float dy, float dz) {
2131    mState.translate(dx, dy, dz);
2132}
2133
2134void OpenGLRenderer::rotate(float degrees) {
2135    mState.rotate(degrees);
2136}
2137
2138void OpenGLRenderer::scale(float sx, float sy) {
2139    mState.scale(sx, sy);
2140}
2141
2142void OpenGLRenderer::skew(float sx, float sy) {
2143    mState.skew(sx, sy);
2144}
2145
2146void OpenGLRenderer::setMatrix(const Matrix4& matrix) {
2147    mState.setMatrix(matrix);
2148}
2149
2150void OpenGLRenderer::concatMatrix(const Matrix4& matrix) {
2151    mState.concatMatrix(matrix);
2152}
2153
2154bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
2155    return mState.clipRect(left, top, right, bottom, op);
2156}
2157
2158bool OpenGLRenderer::clipPath(const SkPath* path, SkRegion::Op op) {
2159    return mState.clipPath(path, op);
2160}
2161
2162bool OpenGLRenderer::clipRegion(const SkRegion* region, SkRegion::Op op) {
2163    return mState.clipRegion(region, op);
2164}
2165
2166void OpenGLRenderer::setClippingOutline(LinearAllocator& allocator, const Outline* outline) {
2167    mState.setClippingOutline(allocator, outline);
2168}
2169
2170void OpenGLRenderer::setClippingRoundRect(LinearAllocator& allocator,
2171        const Rect& rect, float radius, bool highPriority) {
2172    mState.setClippingRoundRect(allocator, rect, radius, highPriority);
2173}
2174
2175void OpenGLRenderer::setProjectionPathMask(LinearAllocator& allocator, const SkPath* path) {
2176    mState.setProjectionPathMask(allocator, path);
2177}
2178
2179void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y,
2180        const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
2181        DrawOpMode drawOpMode) {
2182
2183    if (drawOpMode == DrawOpMode::kImmediate) {
2184        // The checks for corner-case ignorable text and quick rejection is only done for immediate
2185        // drawing as ops from DeferredDisplayList are already filtered for these
2186        if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint) ||
2187                quickRejectSetupScissor(bounds)) {
2188            return;
2189        }
2190    }
2191
2192    const float oldX = x;
2193    const float oldY = y;
2194
2195    const mat4& transform = *currentTransform();
2196    const bool pureTranslate = transform.isPureTranslate();
2197
2198    if (CC_LIKELY(pureTranslate)) {
2199        x = floorf(x + transform.getTranslateX() + 0.5f);
2200        y = floorf(y + transform.getTranslateY() + 0.5f);
2201    }
2202
2203    int alpha;
2204    SkXfermode::Mode mode;
2205    getAlphaAndMode(paint, &alpha, &mode);
2206
2207    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2208
2209    if (CC_UNLIKELY(hasTextShadow(paint))) {
2210        fontRenderer.setFont(paint, SkMatrix::I());
2211        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2212                alpha, oldX, oldY);
2213    }
2214
2215    const bool hasActiveLayer = hasLayer();
2216
2217    // We only pass a partial transform to the font renderer. That partial
2218    // matrix defines how glyphs are rasterized. Typically we want glyphs
2219    // to be rasterized at their final size on screen, which means the partial
2220    // matrix needs to take the scale factor into account.
2221    // When a partial matrix is used to transform glyphs during rasterization,
2222    // the mesh is generated with the inverse transform (in the case of scale,
2223    // the mesh is generated at 1.0 / scale for instance.) This allows us to
2224    // apply the full transform matrix at draw time in the vertex shader.
2225    // Applying the full matrix in the shader is the easiest way to handle
2226    // rotation and perspective and allows us to always generated quads in the
2227    // font renderer which greatly simplifies the code, clipping in particular.
2228    SkMatrix fontTransform;
2229    bool linearFilter = findBestFontTransform(transform, &fontTransform)
2230            || fabs(y - (int) y) > 0.0f
2231            || fabs(x - (int) x) > 0.0f;
2232    fontRenderer.setFont(paint, fontTransform);
2233    fontRenderer.setTextureFiltering(linearFilter);
2234
2235    // TODO: Implement better clipping for scaled/rotated text
2236    const Rect* clip = !pureTranslate ? nullptr : &mState.currentClipRect();
2237    Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2238
2239    bool status;
2240    TextDrawFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2241
2242    // don't call issuedrawcommand, do it at end of batch
2243    bool forceFinish = (drawOpMode != DrawOpMode::kDefer);
2244    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2245        SkPaint paintCopy(*paint);
2246        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2247        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2248                positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2249    } else {
2250        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2251                positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2252    }
2253
2254    if ((status || drawOpMode != DrawOpMode::kImmediate) && hasActiveLayer) {
2255        if (!pureTranslate) {
2256            transform.mapRect(layerBounds);
2257        }
2258        dirtyLayerUnchecked(layerBounds, getRegion());
2259    }
2260
2261    drawTextDecorations(totalAdvance, oldX, oldY, paint);
2262
2263    mDirty = true;
2264}
2265
2266void OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count,
2267        const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) {
2268    if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2269        return;
2270    }
2271
2272    // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics
2273    mRenderState.scissor().setEnabled(true);
2274
2275    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2276    fontRenderer.setFont(paint, SkMatrix::I());
2277    fontRenderer.setTextureFiltering(true);
2278
2279    int alpha;
2280    SkXfermode::Mode mode;
2281    getAlphaAndMode(paint, &alpha, &mode);
2282    TextDrawFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint);
2283
2284    const Rect* clip = &writableSnapshot()->getLocalClip();
2285    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2286
2287    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2288            hOffset, vOffset, hasLayer() ? &bounds : nullptr, &functor)) {
2289        dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform());
2290        mDirty = true;
2291    }
2292}
2293
2294void OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) {
2295    if (mState.currentlyIgnored()) return;
2296
2297    mCaches.textureState().activateTexture(0);
2298
2299    PathTexture* texture = mCaches.pathCache.get(path, paint);
2300    if (!texture) return;
2301    const AutoTexture autoCleanup(texture);
2302
2303    const float x = texture->left - texture->offset;
2304    const float y = texture->top - texture->offset;
2305
2306    drawPathTexture(texture, x, y, paint);
2307    mDirty = true;
2308}
2309
2310void OpenGLRenderer::drawLayer(Layer* layer, float x, float y) {
2311    if (!layer) {
2312        return;
2313    }
2314
2315    mat4* transform = nullptr;
2316    if (layer->isTextureLayer()) {
2317        transform = &layer->getTransform();
2318        if (!transform->isIdentity()) {
2319            save(SkCanvas::kMatrix_SaveFlag);
2320            concatMatrix(*transform);
2321        }
2322    }
2323
2324    bool clipRequired = false;
2325    const bool rejected = mState.calculateQuickRejectForScissor(
2326            x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
2327            &clipRequired, nullptr, false);
2328
2329    if (rejected) {
2330        if (transform && !transform->isIdentity()) {
2331            restore();
2332        }
2333        return;
2334    }
2335
2336    EVENT_LOGD("drawLayer," RECT_STRING ", clipRequired %d", x, y,
2337            x + layer->layer.getWidth(), y + layer->layer.getHeight(), clipRequired);
2338
2339    updateLayer(layer, true);
2340
2341    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
2342    mCaches.textureState().activateTexture(0);
2343
2344    if (CC_LIKELY(!layer->region.isEmpty())) {
2345        if (layer->region.isRect()) {
2346            DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
2347                    composeLayerRect(layer, layer->regionRect));
2348        } else if (layer->mesh) {
2349            Glop glop;
2350            GlopBuilder(mRenderState, mCaches, &glop)
2351                    .setMeshTexturedIndexedQuads(layer->mesh, layer->meshElementCount)
2352                    .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap)
2353                    .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
2354                    .setModelViewOffsetRectSnap(x, y, Rect(0, 0, layer->layer.getWidth(), layer->layer.getHeight()))
2355                    .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2356                    .build();
2357            DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, renderGlop(glop));
2358#if DEBUG_LAYERS_AS_REGIONS
2359            drawRegionRectsDebug(layer->region);
2360#endif
2361        }
2362
2363        if (layer->debugDrawUpdate) {
2364            layer->debugDrawUpdate = false;
2365
2366            SkPaint paint;
2367            paint.setColor(0x7f00ff00);
2368            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint);
2369        }
2370    }
2371    layer->hasDrawnSinceUpdate = true;
2372
2373    if (transform && !transform->isIdentity()) {
2374        restore();
2375    }
2376
2377    mDirty = true;
2378}
2379
2380///////////////////////////////////////////////////////////////////////////////
2381// Draw filters
2382///////////////////////////////////////////////////////////////////////////////
2383void OpenGLRenderer::setDrawFilter(SkDrawFilter* filter) {
2384    // We should never get here since we apply the draw filter when stashing
2385    // the paints in the DisplayList.
2386    LOG_ALWAYS_FATAL("OpenGLRenderer does not directly support DrawFilters");
2387}
2388
2389///////////////////////////////////////////////////////////////////////////////
2390// Drawing implementation
2391///////////////////////////////////////////////////////////////////////////////
2392
2393Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) {
2394    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
2395    if (!texture) {
2396        return mCaches.textureCache.get(bitmap);
2397    }
2398    return texture;
2399}
2400
2401void OpenGLRenderer::drawPathTexture(PathTexture* texture, float x, float y,
2402        const SkPaint* paint) {
2403    if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) {
2404        return;
2405    }
2406
2407    Glop glop;
2408    GlopBuilder(mRenderState, mCaches, &glop)
2409            .setMeshTexturedUnitQuad(nullptr)
2410            .setFillPathTexturePaint(*texture, *paint, currentSnapshot()->alpha)
2411            .setTransform(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false)
2412            .setModelViewMapUnitToRect(Rect(x, y, x + texture->width, y + texture->height))
2413            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2414            .build();
2415    renderGlop(glop);
2416}
2417
2418// Same values used by Skia
2419#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2420#define kStdUnderline_Offset    (1.0f / 9.0f)
2421#define kStdUnderline_Thickness (1.0f / 18.0f)
2422
2423void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y,
2424        const SkPaint* paint) {
2425    // Handle underline and strike-through
2426    uint32_t flags = paint->getFlags();
2427    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
2428        SkPaint paintCopy(*paint);
2429
2430        if (CC_LIKELY(underlineWidth > 0.0f)) {
2431            const float textSize = paintCopy.getTextSize();
2432            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
2433
2434            const float left = x;
2435            float top = 0.0f;
2436
2437            int linesCount = 0;
2438            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
2439            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
2440
2441            const int pointsCount = 4 * linesCount;
2442            float points[pointsCount];
2443            int currentPoint = 0;
2444
2445            if (flags & SkPaint::kUnderlineText_Flag) {
2446                top = y + textSize * kStdUnderline_Offset;
2447                points[currentPoint++] = left;
2448                points[currentPoint++] = top;
2449                points[currentPoint++] = left + underlineWidth;
2450                points[currentPoint++] = top;
2451            }
2452
2453            if (flags & SkPaint::kStrikeThruText_Flag) {
2454                top = y + textSize * kStdStrikeThru_Offset;
2455                points[currentPoint++] = left;
2456                points[currentPoint++] = top;
2457                points[currentPoint++] = left + underlineWidth;
2458                points[currentPoint++] = top;
2459            }
2460
2461            paintCopy.setStrokeWidth(strokeWidth);
2462
2463            drawLines(&points[0], pointsCount, &paintCopy);
2464        }
2465    }
2466}
2467
2468void OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) {
2469    if (mState.currentlyIgnored()) {
2470        return;
2471    }
2472
2473    drawColorRects(rects, count, paint, false, true, true);
2474}
2475
2476void OpenGLRenderer::drawShadow(float casterAlpha,
2477        const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer) {
2478    if (mState.currentlyIgnored()) return;
2479
2480    // TODO: use quickRejectWithScissor. For now, always force enable scissor.
2481    mRenderState.scissor().setEnabled(true);
2482
2483    SkPaint paint;
2484    paint.setAntiAlias(true); // want to use AlphaVertex
2485
2486    // The caller has made sure casterAlpha > 0.
2487    float ambientShadowAlpha = mAmbientShadowAlpha;
2488    if (CC_UNLIKELY(Properties::overrideAmbientShadowStrength >= 0)) {
2489        ambientShadowAlpha = Properties::overrideAmbientShadowStrength;
2490    }
2491    if (ambientShadowVertexBuffer && ambientShadowAlpha > 0) {
2492        paint.setARGB(casterAlpha * ambientShadowAlpha, 0, 0, 0);
2493        drawVertexBuffer(*ambientShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
2494    }
2495
2496    float spotShadowAlpha = mSpotShadowAlpha;
2497    if (CC_UNLIKELY(Properties::overrideSpotShadowStrength >= 0)) {
2498        spotShadowAlpha = Properties::overrideSpotShadowStrength;
2499    }
2500    if (spotShadowVertexBuffer && spotShadowAlpha > 0) {
2501        paint.setARGB(casterAlpha * spotShadowAlpha, 0, 0, 0);
2502        drawVertexBuffer(*spotShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
2503    }
2504
2505    mDirty=true;
2506}
2507
2508void OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint,
2509        bool ignoreTransform, bool dirty, bool clip) {
2510    if (count == 0) {
2511        return;
2512    }
2513
2514    float left = FLT_MAX;
2515    float top = FLT_MAX;
2516    float right = FLT_MIN;
2517    float bottom = FLT_MIN;
2518
2519    Vertex mesh[count];
2520    Vertex* vertex = mesh;
2521
2522    for (int index = 0; index < count; index += 4) {
2523        float l = rects[index + 0];
2524        float t = rects[index + 1];
2525        float r = rects[index + 2];
2526        float b = rects[index + 3];
2527
2528        Vertex::set(vertex++, l, t);
2529        Vertex::set(vertex++, r, t);
2530        Vertex::set(vertex++, l, b);
2531        Vertex::set(vertex++, r, b);
2532
2533        left = fminf(left, l);
2534        top = fminf(top, t);
2535        right = fmaxf(right, r);
2536        bottom = fmaxf(bottom, b);
2537    }
2538
2539    if (clip && quickRejectSetupScissor(left, top, right, bottom)) {
2540        return;
2541    }
2542
2543    const Matrix4& transform = ignoreTransform ? Matrix4::identity() : *currentTransform();
2544    Glop glop;
2545    GlopBuilder(mRenderState, mCaches, &glop)
2546            .setMeshIndexedQuads(&mesh[0], count / 4)
2547            .setFillPaint(*paint, currentSnapshot()->alpha)
2548            .setTransform(currentSnapshot()->getOrthoMatrix(), transform, false)
2549            .setModelViewOffsetRect(0, 0, Rect(left, top, right, bottom))
2550            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2551            .build();
2552    renderGlop(glop);
2553}
2554
2555void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
2556        const SkPaint* paint, bool ignoreTransform) {
2557    const Matrix4& transform = ignoreTransform ? Matrix4::identity() : *currentTransform();
2558    Glop glop;
2559    GlopBuilder(mRenderState, mCaches, &glop)
2560            .setMeshUnitQuad()
2561            .setFillPaint(*paint, currentSnapshot()->alpha)
2562            .setTransform(currentSnapshot()->getOrthoMatrix(), transform, false)
2563            .setModelViewMapUnitToRect(Rect(left, top, right, bottom))
2564            .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2565            .build();
2566    renderGlop(glop);
2567}
2568
2569void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha,
2570        SkXfermode::Mode* mode) const {
2571    getAlphaAndModeDirect(paint, alpha,  mode);
2572    *alpha *= currentSnapshot()->alpha;
2573}
2574
2575float OpenGLRenderer::getLayerAlpha(const Layer* layer) const {
2576    return (layer->getAlpha() / 255.0f) * currentSnapshot()->alpha;
2577}
2578
2579}; // namespace uirenderer
2580}; // namespace android
2581