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