OpenGLRenderer.cpp revision 50c0f093d942a59d4e01b2c76d26c0e9d6ed796c
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 "OpenGLRenderer.h"
30
31namespace android {
32namespace uirenderer {
33
34///////////////////////////////////////////////////////////////////////////////
35// Defines
36///////////////////////////////////////////////////////////////////////////////
37
38#define RAD_TO_DEG (180.0f / 3.14159265f)
39#define MIN_ANGLE 0.001f
40
41// TODO: This should be set in properties
42#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH)
43
44///////////////////////////////////////////////////////////////////////////////
45// Globals
46///////////////////////////////////////////////////////////////////////////////
47
48/**
49 * Structure mapping Skia xfermodes to OpenGL blending factors.
50 */
51struct Blender {
52    SkXfermode::Mode mode;
53    GLenum src;
54    GLenum dst;
55}; // struct Blender
56
57// In this array, the index of each Blender equals the value of the first
58// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
59static const Blender gBlends[] = {
60        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
61        { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
62        { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
63        { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
64        { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
65        { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
66        { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
67        { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
68        { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
69        { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
70        { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
71        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
72};
73
74// This array contains the swapped version of each SkXfermode. For instance
75// this array's SrcOver blending mode is actually DstOver. You can refer to
76// createLayer() for more information on the purpose of this array.
77static const Blender gBlendsSwap[] = {
78        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
79        { SkXfermode::kSrc_Mode,     GL_ZERO,                 GL_ONE },
80        { SkXfermode::kDst_Mode,     GL_ONE,                  GL_ZERO },
81        { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
82        { SkXfermode::kDstOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
83        { SkXfermode::kSrcIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
84        { SkXfermode::kDstIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
85        { SkXfermode::kSrcOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
86        { SkXfermode::kDstOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
87        { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
88        { SkXfermode::kDstATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
89        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
90};
91
92static const GLenum gTextureUnits[] = {
93        GL_TEXTURE0,
94        GL_TEXTURE1,
95        GL_TEXTURE2
96};
97
98///////////////////////////////////////////////////////////////////////////////
99// Constructors/destructor
100///////////////////////////////////////////////////////////////////////////////
101
102OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
103    mShader = NULL;
104    mColorFilter = NULL;
105    mHasShadow = false;
106
107    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
108
109    mFirstSnapshot = new Snapshot;
110
111    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
112}
113
114OpenGLRenderer::~OpenGLRenderer() {
115    // The context has already been destroyed at this point, do not call
116    // GL APIs. All GL state should be kept in Caches.h
117}
118
119///////////////////////////////////////////////////////////////////////////////
120// Setup
121///////////////////////////////////////////////////////////////////////////////
122
123void OpenGLRenderer::setViewport(int width, int height) {
124    glViewport(0, 0, width, height);
125    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
126
127    mWidth = width;
128    mHeight = height;
129
130    mFirstSnapshot->height = height;
131    mFirstSnapshot->viewport.set(0, 0, width, height);
132}
133
134void OpenGLRenderer::prepare(bool opaque) {
135    mSnapshot = new Snapshot(mFirstSnapshot,
136            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
137    mSaveCount = 1;
138
139    glViewport(0, 0, mWidth, mHeight);
140
141    glDisable(GL_DITHER);
142    glDisable(GL_SCISSOR_TEST);
143
144    if (!opaque) {
145        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
146        glClear(GL_COLOR_BUFFER_BIT);
147    }
148
149    glEnable(GL_SCISSOR_TEST);
150    glScissor(0, 0, mWidth, mHeight);
151
152    mSnapshot->setClip(0.0f, 0.0f, mWidth, mHeight);
153}
154
155void OpenGLRenderer::finish() {
156#if DEBUG_OPENGL
157    GLenum status = GL_NO_ERROR;
158    while ((status = glGetError()) != GL_NO_ERROR) {
159        LOGD("GL error from OpenGLRenderer: 0x%x", status);
160    }
161#endif
162}
163
164void OpenGLRenderer::acquireContext() {
165    if (mCaches.currentProgram) {
166        if (mCaches.currentProgram->isInUse()) {
167            mCaches.currentProgram->remove();
168            mCaches.currentProgram = NULL;
169        }
170    }
171    mCaches.unbindMeshBuffer();
172}
173
174void OpenGLRenderer::releaseContext() {
175    glViewport(0, 0, mSnapshot->viewport.getWidth(), mSnapshot->viewport.getHeight());
176
177    glEnable(GL_SCISSOR_TEST);
178    setScissorFromClip();
179
180    glDisable(GL_DITHER);
181
182    glBindFramebuffer(GL_FRAMEBUFFER, 0);
183    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
184
185    mCaches.blend = true;
186    glEnable(GL_BLEND);
187    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
188    glBlendEquation(GL_FUNC_ADD);
189}
190
191///////////////////////////////////////////////////////////////////////////////
192// State management
193///////////////////////////////////////////////////////////////////////////////
194
195int OpenGLRenderer::getSaveCount() const {
196    return mSaveCount;
197}
198
199int OpenGLRenderer::save(int flags) {
200    return saveSnapshot(flags);
201}
202
203void OpenGLRenderer::restore() {
204    if (mSaveCount > 1) {
205        restoreSnapshot();
206    }
207}
208
209void OpenGLRenderer::restoreToCount(int saveCount) {
210    if (saveCount < 1) saveCount = 1;
211
212    while (mSaveCount > saveCount) {
213        restoreSnapshot();
214    }
215}
216
217int OpenGLRenderer::saveSnapshot(int flags) {
218    mSnapshot = new Snapshot(mSnapshot, flags);
219    return mSaveCount++;
220}
221
222bool OpenGLRenderer::restoreSnapshot() {
223    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
224    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
225    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
226
227    sp<Snapshot> current = mSnapshot;
228    sp<Snapshot> previous = mSnapshot->previous;
229
230    if (restoreOrtho) {
231        Rect& r = previous->viewport;
232        glViewport(r.left, r.top, r.right, r.bottom);
233        mOrthoMatrix.load(current->orthoMatrix);
234    }
235
236    mSaveCount--;
237    mSnapshot = previous;
238
239    if (restoreLayer) {
240        composeLayer(current, previous);
241    }
242
243    if (restoreClip) {
244        setScissorFromClip();
245    }
246
247    return restoreClip;
248}
249
250///////////////////////////////////////////////////////////////////////////////
251// Layers
252///////////////////////////////////////////////////////////////////////////////
253
254int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
255        const SkPaint* p, int flags) {
256    const GLuint previousFbo = mSnapshot->fbo;
257    const int count = saveSnapshot(flags);
258
259    int alpha = 255;
260    SkXfermode::Mode mode;
261
262    if (p) {
263        alpha = p->getAlpha();
264        if (!mExtensions.hasFramebufferFetch()) {
265            const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
266            if (!isMode) {
267                // Assume SRC_OVER
268                mode = SkXfermode::kSrcOver_Mode;
269            }
270        } else {
271            mode = getXfermode(p->getXfermode());
272        }
273    } else {
274        mode = SkXfermode::kSrcOver_Mode;
275    }
276
277    if (!mSnapshot->previous->invisible) {
278        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
279    }
280
281    return count;
282}
283
284int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
285        int alpha, int flags) {
286    if (alpha == 0xff) {
287        return saveLayer(left, top, right, bottom, NULL, flags);
288    } else {
289        SkPaint paint;
290        paint.setAlpha(alpha);
291        return saveLayer(left, top, right, bottom, &paint, flags);
292    }
293}
294
295/**
296 * Layers are viewed by Skia are slightly different than layers in image editing
297 * programs (for instance.) When a layer is created, previously created layers
298 * and the frame buffer still receive every drawing command. For instance, if a
299 * layer is created and a shape intersecting the bounds of the layers and the
300 * framebuffer is draw, the shape will be drawn on both (unless the layer was
301 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
302 *
303 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
304 * texture. Unfortunately, this is inefficient as it requires every primitive to
305 * be drawn n + 1 times, where n is the number of active layers. In practice this
306 * means, for every primitive:
307 *   - Switch active frame buffer
308 *   - Change viewport, clip and projection matrix
309 *   - Issue the drawing
310 *
311 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
312 * To avoid this, layers are implemented in a different way here, at least in the
313 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
314 * is set. When this flag is set we can redirect all drawing operations into a
315 * single FBO.
316 *
317 * This implementation relies on the frame buffer being at least RGBA 8888. When
318 * a layer is created, only a texture is created, not an FBO. The content of the
319 * frame buffer contained within the layer's bounds is copied into this texture
320 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
321 * buffer and drawing continues as normal. This technique therefore treats the
322 * frame buffer as a scratch buffer for the layers.
323 *
324 * To compose the layers back onto the frame buffer, each layer texture
325 * (containing the original frame buffer data) is drawn as a simple quad over
326 * the frame buffer. The trick is that the quad is set as the composition
327 * destination in the blending equation, and the frame buffer becomes the source
328 * of the composition.
329 *
330 * Drawing layers with an alpha value requires an extra step before composition.
331 * An empty quad is drawn over the layer's region in the frame buffer. This quad
332 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
333 * quad is used to multiply the colors in the frame buffer. This is achieved by
334 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
335 * GL_ZERO, GL_SRC_ALPHA.
336 *
337 * Because glCopyTexImage2D() can be slow, an alternative implementation might
338 * be use to draw a single clipped layer. The implementation described above
339 * is correct in every case.
340 *
341 * (1) The frame buffer is actually not cleared right away. To allow the GPU
342 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
343 *     buffer is left untouched until the first drawing operation. Only when
344 *     something actually gets drawn are the layers regions cleared.
345 */
346bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
347        float right, float bottom, int alpha, SkXfermode::Mode mode,
348        int flags, GLuint previousFbo) {
349    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
350    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
351
352    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
353
354    // Window coordinates of the layer
355    Rect bounds(left, top, right, bottom);
356    if (!fboLayer) {
357        mSnapshot->transform->mapRect(bounds);
358        // Layers only make sense if they are in the framebuffer's bounds
359        bounds.intersect(*mSnapshot->clipRect);
360        bounds.snapToPixelBoundaries();
361    }
362
363    if (bounds.isEmpty() || bounds.getWidth() > mMaxTextureSize ||
364            bounds.getHeight() > mMaxTextureSize) {
365        snapshot->invisible = true;
366    } else {
367        // TODO: Should take the mode into account
368        snapshot->invisible = snapshot->previous->invisible ||
369                (alpha <= ALPHA_THRESHOLD && fboLayer);
370    }
371
372    // Bail out if we won't draw in this snapshot
373    if (snapshot->invisible) {
374        return false;
375    }
376
377    glActiveTexture(GL_TEXTURE0);
378
379    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
380    if (!layer) {
381        return false;
382    }
383
384    layer->mode = mode;
385    layer->alpha = alpha;
386    layer->layer.set(bounds);
387    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
388            bounds.getWidth() / float(layer->width), 0.0f);
389
390    // Save the layer in the snapshot
391    snapshot->flags |= Snapshot::kFlagIsLayer;
392    snapshot->layer = layer;
393
394    if (fboLayer) {
395        layer->fbo = mCaches.fboCache.get();
396
397        snapshot->flags |= Snapshot::kFlagIsFboLayer;
398        snapshot->fbo = layer->fbo;
399        snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
400        snapshot->resetClip(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
401        snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
402        snapshot->height = bounds.getHeight();
403        snapshot->flags |= Snapshot::kFlagDirtyOrtho;
404        snapshot->orthoMatrix.load(mOrthoMatrix);
405
406        // Bind texture to FBO
407        glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
408        glBindTexture(GL_TEXTURE_2D, layer->texture);
409
410        // Initialize the texture if needed
411        if (layer->empty) {
412            layer->empty = false;
413            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
414                    GL_RGBA, GL_UNSIGNED_BYTE, NULL);
415        }
416
417        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
418                layer->texture, 0);
419
420#if DEBUG_LAYERS
421        GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
422        if (status != GL_FRAMEBUFFER_COMPLETE) {
423            LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
424
425            glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
426            glDeleteTextures(1, &layer->texture);
427            mCaches.fboCache.put(layer->fbo);
428
429            delete layer;
430
431            return false;
432        }
433#endif
434
435        // Clear the FBO
436        glScissor(0.0f, 0.0f, bounds.getWidth() + 1.0f, bounds.getHeight() + 1.0f);
437        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
438        glClear(GL_COLOR_BUFFER_BIT);
439
440        setScissorFromClip();
441
442        // Change the ortho projection
443        glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
444        mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
445    } else {
446        // Copy the framebuffer into the layer
447        glBindTexture(GL_TEXTURE_2D, layer->texture);
448
449         if (layer->empty) {
450             glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left, mHeight - bounds.bottom,
451                     layer->width, layer->height, 0);
452             layer->empty = false;
453         } else {
454             glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left, mHeight - bounds.bottom,
455                     bounds.getWidth(), bounds.getHeight());
456          }
457
458        // Enqueue the buffer coordinates to clear the corresponding region later
459        mLayers.push(new Rect(bounds));
460    }
461
462    return true;
463}
464
465/**
466 * Read the documentation of createLayer() before doing anything in this method.
467 */
468void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
469    if (!current->layer) {
470        LOGE("Attempting to compose a layer that does not exist");
471        return;
472    }
473
474    const bool fboLayer = current->flags & SkCanvas::kClipToLayer_SaveFlag;
475
476    if (fboLayer) {
477        // Unbind current FBO and restore previous one
478        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
479    }
480
481    // Restore the clip from the previous snapshot
482    const Rect& clip = *previous->clipRect;
483    glScissor(clip.left, previous->height - clip.bottom, clip.getWidth(), clip.getHeight());
484
485    Layer* layer = current->layer;
486    const Rect& rect = layer->layer;
487
488    if (!fboLayer && layer->alpha < 255) {
489        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
490                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
491    }
492
493    const Rect& texCoords = layer->texCoords;
494    mCaches.unbindMeshBuffer();
495    resetDrawTextureTexCoords(texCoords.left, texCoords.top, texCoords.right, texCoords.bottom);
496
497    if (fboLayer) {
498        drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
499                layer->alpha / 255.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
500                &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount);
501    } else {
502        drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
503                1.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
504                &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, true, true);
505    }
506
507    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
508
509    if (fboLayer) {
510        // Detach the texture from the FBO
511        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
512        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
513        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
514
515        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
516        mCaches.fboCache.put(current->fbo);
517    }
518
519    // Failing to add the layer to the cache should happen only if the layer is too large
520    if (!mCaches.layerCache.put(layer)) {
521        LAYER_LOGD("Deleting layer");
522        glDeleteTextures(1, &layer->texture);
523        delete layer;
524    }
525}
526
527void OpenGLRenderer::clearLayerRegions() {
528    if (mLayers.size() == 0 || mSnapshot->invisible) return;
529
530    for (uint32_t i = 0; i < mLayers.size(); i++) {
531        Rect* bounds = mLayers.itemAt(i);
532
533        // Clear the framebuffer where the layer will draw
534        glScissor(bounds->left, mSnapshot->height - bounds->bottom,
535                bounds->getWidth(), bounds->getHeight());
536        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
537        glClear(GL_COLOR_BUFFER_BIT);
538
539        delete bounds;
540    }
541    mLayers.clear();
542
543    // Restore the clip
544    setScissorFromClip();
545}
546
547///////////////////////////////////////////////////////////////////////////////
548// Transforms
549///////////////////////////////////////////////////////////////////////////////
550
551void OpenGLRenderer::translate(float dx, float dy) {
552    mSnapshot->transform->translate(dx, dy, 0.0f);
553}
554
555void OpenGLRenderer::rotate(float degrees) {
556    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
557}
558
559void OpenGLRenderer::scale(float sx, float sy) {
560    mSnapshot->transform->scale(sx, sy, 1.0f);
561}
562
563void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
564    mSnapshot->transform->load(*matrix);
565}
566
567const float* OpenGLRenderer::getMatrix() const {
568    if (mSnapshot->fbo != 0) {
569        return &mSnapshot->transform->data[0];
570    }
571    return &mIdentity.data[0];
572}
573
574void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
575    mSnapshot->transform->copyTo(*matrix);
576}
577
578void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
579    SkMatrix transform;
580    mSnapshot->transform->copyTo(transform);
581    transform.preConcat(*matrix);
582    mSnapshot->transform->load(transform);
583}
584
585///////////////////////////////////////////////////////////////////////////////
586// Clipping
587///////////////////////////////////////////////////////////////////////////////
588
589void OpenGLRenderer::setScissorFromClip() {
590    Rect clip(*mSnapshot->clipRect);
591    clip.snapToPixelBoundaries();
592    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
593}
594
595const Rect& OpenGLRenderer::getClipBounds() {
596    return mSnapshot->getLocalClip();
597}
598
599bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
600    if (mSnapshot->invisible) {
601        return true;
602    }
603
604    Rect r(left, top, right, bottom);
605    mSnapshot->transform->mapRect(r);
606    r.snapToPixelBoundaries();
607
608    Rect clipRect(*mSnapshot->clipRect);
609    clipRect.snapToPixelBoundaries();
610
611    return !clipRect.intersects(r);
612}
613
614bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
615    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
616    if (clipped) {
617        setScissorFromClip();
618    }
619    return !mSnapshot->clipRect->isEmpty();
620}
621
622///////////////////////////////////////////////////////////////////////////////
623// Drawing
624///////////////////////////////////////////////////////////////////////////////
625
626void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
627    const float right = left + bitmap->width();
628    const float bottom = top + bitmap->height();
629
630    if (quickReject(left, top, right, bottom)) {
631        return;
632    }
633
634    glActiveTexture(GL_TEXTURE0);
635    const Texture* texture = mCaches.textureCache.get(bitmap);
636    if (!texture) return;
637    const AutoTexture autoCleanup(texture);
638
639    drawTextureRect(left, top, right, bottom, texture, paint);
640}
641
642void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) {
643    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
644    const mat4 transform(*matrix);
645    transform.mapRect(r);
646
647    if (quickReject(r.left, r.top, r.right, r.bottom)) {
648        return;
649    }
650
651    glActiveTexture(GL_TEXTURE0);
652    const Texture* texture = mCaches.textureCache.get(bitmap);
653    if (!texture) return;
654    const AutoTexture autoCleanup(texture);
655
656    drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint);
657}
658
659void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
660         float srcLeft, float srcTop, float srcRight, float srcBottom,
661         float dstLeft, float dstTop, float dstRight, float dstBottom,
662         const SkPaint* paint) {
663    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
664        return;
665    }
666
667    glActiveTexture(GL_TEXTURE0);
668    const Texture* texture = mCaches.textureCache.get(bitmap);
669    if (!texture) return;
670    const AutoTexture autoCleanup(texture);
671
672    const float width = texture->width;
673    const float height = texture->height;
674
675    const float u1 = srcLeft / width;
676    const float v1 = srcTop / height;
677    const float u2 = srcRight / width;
678    const float v2 = srcBottom / height;
679
680    mCaches.unbindMeshBuffer();
681    resetDrawTextureTexCoords(u1, v1, u2, v2);
682
683    int alpha;
684    SkXfermode::Mode mode;
685    getAlphaAndMode(paint, &alpha, &mode);
686
687    drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
688            mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
689            GL_TRIANGLE_STRIP, gMeshCount);
690
691    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
692}
693
694void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
695        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
696        float left, float top, float right, float bottom, const SkPaint* paint) {
697    if (quickReject(left, top, right, bottom)) {
698        return;
699    }
700
701    glActiveTexture(GL_TEXTURE0);
702    const Texture* texture = mCaches.textureCache.get(bitmap);
703    if (!texture) return;
704    const AutoTexture autoCleanup(texture);
705
706    int alpha;
707    SkXfermode::Mode mode;
708    getAlphaAndMode(paint, &alpha, &mode);
709
710    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
711            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
712
713    if (mesh) {
714        // Specify right and bottom as +1.0f from left/top to prevent scaling since the
715        // patch mesh already defines the final size
716        drawTextureMesh(left, top, left + 1.0f, top + 1.0f, texture->id, alpha / 255.0f,
717                mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
718                GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer);
719    }
720}
721
722void OpenGLRenderer::drawLines(float* points, int count, const SkPaint* paint) {
723    if (mSnapshot->invisible) return;
724
725    int alpha;
726    SkXfermode::Mode mode;
727    getAlphaAndMode(paint, &alpha, &mode);
728
729    uint32_t color = paint->getColor();
730    const GLfloat a = alpha / 255.0f;
731    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
732    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
733    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
734
735    const bool isAA = paint->isAntiAlias();
736    if (isAA) {
737        GLuint textureUnit = 0;
738        setupTextureAlpha8(mCaches.line.getTexture(), 0, 0, textureUnit, 0.0f, 0.0f, r, g, b, a,
739                mode, false, true, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
740                mCaches.line.getMeshBuffer());
741    } else {
742        setupColorRect(0.0f, 0.0f, 1.0f, 1.0f, r, g, b, a, mode, false);
743    }
744
745    const float strokeWidth = paint->getStrokeWidth();
746    const GLsizei elementsCount = isAA ? mCaches.line.getElementsCount() : gMeshCount;
747    const GLenum drawMode = isAA ? GL_TRIANGLES : GL_TRIANGLE_STRIP;
748
749    for (int i = 0; i < count; i += 4) {
750        float tx = 0.0f;
751        float ty = 0.0f;
752
753        if (isAA) {
754            mCaches.line.update(points[i], points[i + 1], points[i + 2], points[i + 3],
755                    strokeWidth, tx, ty);
756        } else {
757            ty = strokeWidth <= 1.0f ? 0.0f : -strokeWidth * 0.5f;
758        }
759
760        const float dx = points[i + 2] - points[i];
761        const float dy = points[i + 3] - points[i + 1];
762        const float mag = sqrtf(dx * dx + dy * dy);
763        const float angle = acos(dx / mag);
764
765        mModelView.loadTranslate(points[i], points[i + 1], 0.0f);
766        if (angle > MIN_ANGLE || angle < -MIN_ANGLE) {
767            mModelView.rotate(angle * RAD_TO_DEG, 0.0f, 0.0f, 1.0f);
768        }
769        mModelView.translate(tx, ty, 0.0f);
770        if (!isAA) {
771            float length = mCaches.line.getLength(points[i], points[i + 1],
772                    points[i + 2], points[i + 3]);
773            mModelView.scale(length, strokeWidth, 1.0f);
774        }
775        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
776
777        if (mShader) {
778            mShader->updateTransforms(mCaches.currentProgram, mModelView, *mSnapshot);
779        }
780
781        glDrawArrays(drawMode, 0, elementsCount);
782    }
783
784    if (isAA) {
785        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
786    }
787}
788
789void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
790    const Rect& clip = *mSnapshot->clipRect;
791    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
792}
793
794void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) {
795    if (quickReject(left, top, right, bottom)) {
796        return;
797    }
798
799    SkXfermode::Mode mode;
800    if (!mExtensions.hasFramebufferFetch()) {
801        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
802        if (!isMode) {
803            // Assume SRC_OVER
804            mode = SkXfermode::kSrcOver_Mode;
805        }
806    } else {
807        mode = getXfermode(p->getXfermode());
808    }
809
810    // Skia draws using the color's alpha channel if < 255
811    // Otherwise, it uses the paint's alpha
812    int color = p->getColor();
813    if (((color >> 24) & 0xff) == 255) {
814        color |= p->getAlpha() << 24;
815    }
816
817    drawColorRect(left, top, right, bottom, color, mode);
818}
819
820void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
821        float x, float y, SkPaint* paint) {
822    if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
823        return;
824    }
825    if (mSnapshot->invisible) return;
826
827    paint->setAntiAlias(true);
828
829    float length = -1.0f;
830    switch (paint->getTextAlign()) {
831        case SkPaint::kCenter_Align:
832            length = paint->measureText(text, bytesCount);
833            x -= length / 2.0f;
834            break;
835        case SkPaint::kRight_Align:
836            length = paint->measureText(text, bytesCount);
837            x -= length;
838            break;
839        default:
840            break;
841    }
842
843    int alpha;
844    SkXfermode::Mode mode;
845    getAlphaAndMode(paint, &alpha, &mode);
846
847    uint32_t color = paint->getColor();
848    const GLfloat a = alpha / 255.0f;
849    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
850    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
851    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
852
853    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
854    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
855            paint->getTextSize());
856
857    Rect clipRect(*mSnapshot->clipRect);
858    glScissor(clipRect.left, mSnapshot->height - clipRect.bottom,
859            clipRect.getWidth(), clipRect.getHeight());
860
861    if (mHasShadow) {
862        glActiveTexture(gTextureUnits[0]);
863        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
864        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
865                count, mShadowRadius);
866        const AutoTexture autoCleanup(shadow);
867
868        setupShadow(shadow, x, y, mode, a);
869
870        // Draw the mesh
871        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
872        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
873    }
874
875    GLuint textureUnit = 0;
876    glActiveTexture(gTextureUnits[textureUnit]);
877
878    // Assume that the modelView matrix does not force scales, rotates, etc.
879    const bool linearFilter = mSnapshot->transform->changesBounds();
880    setupTextureAlpha8(fontRenderer.getTexture(linearFilter), 0, 0, textureUnit,
881            x, y, r, g, b, a, mode, false, true, NULL, NULL);
882
883    const Rect& clip = mSnapshot->getLocalClip();
884    clearLayerRegions();
885
886    mCaches.unbindMeshBuffer();
887    fontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y);
888
889    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
890    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
891
892    drawTextDecorations(text, bytesCount, length, x, y, paint);
893
894    setScissorFromClip();
895}
896
897void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
898    if (mSnapshot->invisible) return;
899
900    GLuint textureUnit = 0;
901    glActiveTexture(gTextureUnits[textureUnit]);
902
903    const PathTexture* texture = mCaches.pathCache.get(path, paint);
904    if (!texture) return;
905    const AutoTexture autoCleanup(texture);
906
907    const float x = texture->left - texture->offset;
908    const float y = texture->top - texture->offset;
909
910    if (quickReject(x, y, x + texture->width, y + texture->height)) {
911        return;
912    }
913
914    int alpha;
915    SkXfermode::Mode mode;
916    getAlphaAndMode(paint, &alpha, &mode);
917
918    uint32_t color = paint->getColor();
919    const GLfloat a = alpha / 255.0f;
920    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
921    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
922    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
923
924    setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true);
925
926    clearLayerRegions();
927
928    // Draw the mesh
929    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
930    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
931}
932
933///////////////////////////////////////////////////////////////////////////////
934// Shaders
935///////////////////////////////////////////////////////////////////////////////
936
937void OpenGLRenderer::resetShader() {
938    mShader = NULL;
939}
940
941void OpenGLRenderer::setupShader(SkiaShader* shader) {
942    mShader = shader;
943    if (mShader) {
944        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
945    }
946}
947
948///////////////////////////////////////////////////////////////////////////////
949// Color filters
950///////////////////////////////////////////////////////////////////////////////
951
952void OpenGLRenderer::resetColorFilter() {
953    mColorFilter = NULL;
954}
955
956void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
957    mColorFilter = filter;
958}
959
960///////////////////////////////////////////////////////////////////////////////
961// Drop shadow
962///////////////////////////////////////////////////////////////////////////////
963
964void OpenGLRenderer::resetShadow() {
965    mHasShadow = false;
966}
967
968void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
969    mHasShadow = true;
970    mShadowRadius = radius;
971    mShadowDx = dx;
972    mShadowDy = dy;
973    mShadowColor = color;
974}
975
976///////////////////////////////////////////////////////////////////////////////
977// Drawing implementation
978///////////////////////////////////////////////////////////////////////////////
979
980void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y,
981        SkXfermode::Mode mode, float alpha) {
982    const float sx = x - texture->left + mShadowDx;
983    const float sy = y - texture->top + mShadowDy;
984
985    const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
986    const GLfloat a = shadowAlpha < 255 ? shadowAlpha / 255.0f : alpha;
987    const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f;
988    const GLfloat g = a * ((mShadowColor >>  8) & 0xFF) / 255.0f;
989    const GLfloat b = a * ((mShadowColor      ) & 0xFF) / 255.0f;
990
991    GLuint textureUnit = 0;
992    setupTextureAlpha8(texture, textureUnit, sx, sy, r, g, b, a, mode, true, false);
993}
994
995void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit,
996        float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode,
997        bool transforms, bool applyFilters) {
998    setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit,
999            x, y, r, g, b, a, mode, transforms, applyFilters,
1000            (GLvoid*) 0, (GLvoid*) gMeshTextureOffset);
1001}
1002
1003void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
1004        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
1005        SkXfermode::Mode mode, bool transforms, bool applyFilters) {
1006    setupTextureAlpha8(texture, width, height, textureUnit, x, y, r, g, b, a, mode,
1007            transforms, applyFilters, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset);
1008}
1009
1010void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
1011        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
1012        SkXfermode::Mode mode, bool transforms, bool applyFilters,
1013        GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1014     // Describe the required shaders
1015     ProgramDescription description;
1016     description.hasTexture = true;
1017     description.hasAlpha8Texture = true;
1018     const bool setColor = description.setAlpha8Color(r, g, b, a);
1019
1020     if (applyFilters) {
1021         if (mShader) {
1022             mShader->describe(description, mExtensions);
1023         }
1024         if (mColorFilter) {
1025             mColorFilter->describe(description, mExtensions);
1026         }
1027     }
1028
1029     // Setup the blending mode
1030     chooseBlending(true, mode, description);
1031
1032     // Build and use the appropriate shader
1033     useProgram(mCaches.programCache.get(description));
1034
1035     bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, textureUnit);
1036     glUniform1i(mCaches.currentProgram->getUniform("sampler"), textureUnit);
1037
1038     int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1039     glEnableVertexAttribArray(texCoordsSlot);
1040
1041     if (texCoords) {
1042         // Setup attributes
1043         if (!vertices) {
1044             mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1045         } else {
1046             mCaches.unbindMeshBuffer();
1047         }
1048         glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1049                 gMeshStride, vertices);
1050         glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1051     }
1052
1053     // Setup uniforms
1054     if (transforms) {
1055         mModelView.loadTranslate(x, y, 0.0f);
1056         mModelView.scale(width, height, 1.0f);
1057     } else {
1058         mModelView.loadIdentity();
1059     }
1060     mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1061     if (setColor) {
1062         mCaches.currentProgram->setColor(r, g, b, a);
1063     }
1064
1065     textureUnit++;
1066     if (applyFilters) {
1067         // Setup attributes and uniforms required by the shaders
1068         if (mShader) {
1069             mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1070         }
1071         if (mColorFilter) {
1072             mColorFilter->setupProgram(mCaches.currentProgram);
1073         }
1074     }
1075}
1076
1077// Same values used by Skia
1078#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
1079#define kStdUnderline_Offset    (1.0f / 9.0f)
1080#define kStdUnderline_Thickness (1.0f / 18.0f)
1081
1082void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
1083        float x, float y, SkPaint* paint) {
1084    // Handle underline and strike-through
1085    uint32_t flags = paint->getFlags();
1086    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
1087        float underlineWidth = length;
1088        // If length is > 0.0f, we already measured the text for the text alignment
1089        if (length <= 0.0f) {
1090            underlineWidth = paint->measureText(text, bytesCount);
1091        }
1092
1093        float offsetX = 0;
1094        switch (paint->getTextAlign()) {
1095            case SkPaint::kCenter_Align:
1096                offsetX = underlineWidth * 0.5f;
1097                break;
1098            case SkPaint::kRight_Align:
1099                offsetX = underlineWidth;
1100                break;
1101            default:
1102                break;
1103        }
1104
1105        if (underlineWidth > 0.0f) {
1106            const float textSize = paint->getTextSize();
1107            const float strokeWidth = textSize * kStdUnderline_Thickness;
1108
1109            const float left = x - offsetX;
1110            float top = 0.0f;
1111
1112            const int pointsCount = 4 * (flags & SkPaint::kStrikeThruText_Flag ? 2 : 1);
1113            float points[pointsCount];
1114            int currentPoint = 0;
1115
1116            if (flags & SkPaint::kUnderlineText_Flag) {
1117                top = y + textSize * kStdUnderline_Offset;
1118                points[currentPoint++] = left;
1119                points[currentPoint++] = top;
1120                points[currentPoint++] = left + underlineWidth;
1121                points[currentPoint++] = top;
1122            }
1123
1124            if (flags & SkPaint::kStrikeThruText_Flag) {
1125                top = y + textSize * kStdStrikeThru_Offset;
1126                points[currentPoint++] = left;
1127                points[currentPoint++] = top;
1128                points[currentPoint++] = left + underlineWidth;
1129                points[currentPoint++] = top;
1130            }
1131
1132            SkPaint linesPaint(*paint);
1133            linesPaint.setStrokeWidth(strokeWidth);
1134
1135            drawLines(&points[0], pointsCount, &linesPaint);
1136        }
1137    }
1138}
1139
1140void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
1141        int color, SkXfermode::Mode mode, bool ignoreTransform) {
1142    clearLayerRegions();
1143
1144    // If a shader is set, preserve only the alpha
1145    if (mShader) {
1146        color |= 0x00ffffff;
1147    }
1148
1149    // Render using pre-multiplied alpha
1150    const int alpha = (color >> 24) & 0xFF;
1151    const GLfloat a = alpha / 255.0f;
1152    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
1153    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
1154    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
1155
1156    setupColorRect(left, top, right, bottom, r, g, b, a, mode, ignoreTransform);
1157
1158    // Draw the mesh
1159    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1160}
1161
1162void OpenGLRenderer::setupColorRect(float left, float top, float right, float bottom,
1163        float r, float g, float b, float a, SkXfermode::Mode mode, bool ignoreTransform) {
1164    GLuint textureUnit = 0;
1165
1166    // Describe the required shaders
1167    ProgramDescription description;
1168    const bool setColor = description.setColor(r, g, b, a);
1169
1170    if (mShader) {
1171        mShader->describe(description, mExtensions);
1172    }
1173    if (mColorFilter) {
1174        mColorFilter->describe(description, mExtensions);
1175    }
1176
1177    // Setup the blending mode
1178    chooseBlending(a < 1.0f || (mShader && mShader->blend()), mode, description);
1179
1180    // Build and use the appropriate shader
1181    useProgram(mCaches.programCache.get(description));
1182
1183    // Setup attributes
1184    mCaches.bindMeshBuffer();
1185    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1186            gMeshStride, 0);
1187
1188    // Setup uniforms
1189    mModelView.loadTranslate(left, top, 0.0f);
1190    mModelView.scale(right - left, bottom - top, 1.0f);
1191    if (!ignoreTransform) {
1192        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1193    } else {
1194        mat4 identity;
1195        mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity);
1196    }
1197    mCaches.currentProgram->setColor(r, g, b, a);
1198
1199    // Setup attributes and uniforms required by the shaders
1200    if (mShader) {
1201        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1202    }
1203    if (mColorFilter) {
1204        mColorFilter->setupProgram(mCaches.currentProgram);
1205    }
1206}
1207
1208void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1209        const Texture* texture, const SkPaint* paint) {
1210    int alpha;
1211    SkXfermode::Mode mode;
1212    getAlphaAndMode(paint, &alpha, &mode);
1213
1214    drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
1215            texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
1216            GL_TRIANGLE_STRIP, gMeshCount);
1217}
1218
1219void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1220        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
1221    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
1222            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
1223}
1224
1225void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
1226        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
1227        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
1228        bool swapSrcDst, bool ignoreTransform, GLuint vbo) {
1229    clearLayerRegions();
1230
1231    ProgramDescription description;
1232    description.hasTexture = true;
1233    const bool setColor = description.setColor(alpha, alpha, alpha, alpha);
1234    if (mColorFilter) {
1235        mColorFilter->describe(description, mExtensions);
1236    }
1237
1238    mModelView.loadTranslate(left, top, 0.0f);
1239    mModelView.scale(right - left, bottom - top, 1.0f);
1240
1241    chooseBlending(blend || alpha < 1.0f, mode, description, swapSrcDst);
1242
1243    useProgram(mCaches.programCache.get(description));
1244    if (!ignoreTransform) {
1245        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1246    } else {
1247        mat4 m;
1248        mCaches.currentProgram->set(mOrthoMatrix, mModelView, m);
1249    }
1250
1251    // Texture
1252    bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, 0);
1253    glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
1254
1255    // Always premultiplied
1256    if (setColor) {
1257        mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha);
1258    }
1259
1260    // Mesh
1261    int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1262    glEnableVertexAttribArray(texCoordsSlot);
1263
1264    if (!vertices) {
1265        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1266    } else {
1267        mCaches.unbindMeshBuffer();
1268    }
1269    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1270            gMeshStride, vertices);
1271    glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1272
1273    // Color filter
1274    if (mColorFilter) {
1275        mColorFilter->setupProgram(mCaches.currentProgram);
1276    }
1277
1278    glDrawArrays(drawMode, 0, elementsCount);
1279    glDisableVertexAttribArray(texCoordsSlot);
1280}
1281
1282void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
1283        ProgramDescription& description, bool swapSrcDst) {
1284    blend = blend || mode != SkXfermode::kSrcOver_Mode;
1285    if (blend) {
1286        if (mode < SkXfermode::kPlus_Mode) {
1287            if (!mCaches.blend) {
1288                glEnable(GL_BLEND);
1289            }
1290
1291            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
1292            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
1293
1294            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
1295                glBlendFunc(sourceMode, destMode);
1296                mCaches.lastSrcMode = sourceMode;
1297                mCaches.lastDstMode = destMode;
1298            }
1299        } else {
1300            // These blend modes are not supported by OpenGL directly and have
1301            // to be implemented using shaders. Since the shader will perform
1302            // the blending, turn blending off here
1303            if (mExtensions.hasFramebufferFetch()) {
1304                description.framebufferMode = mode;
1305                description.swapSrcDst = swapSrcDst;
1306            }
1307
1308            if (mCaches.blend) {
1309                glDisable(GL_BLEND);
1310            }
1311            blend = false;
1312        }
1313    } else if (mCaches.blend) {
1314        glDisable(GL_BLEND);
1315    }
1316    mCaches.blend = blend;
1317}
1318
1319bool OpenGLRenderer::useProgram(Program* program) {
1320    if (!program->isInUse()) {
1321        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1322        program->use();
1323        mCaches.currentProgram = program;
1324        return false;
1325    }
1326    return true;
1327}
1328
1329void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1330    TextureVertex* v = &mMeshVertices[0];
1331    TextureVertex::setUV(v++, u1, v1);
1332    TextureVertex::setUV(v++, u2, v1);
1333    TextureVertex::setUV(v++, u1, v2);
1334    TextureVertex::setUV(v++, u2, v2);
1335}
1336
1337void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1338    if (paint) {
1339        if (!mExtensions.hasFramebufferFetch()) {
1340            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1341            if (!isMode) {
1342                // Assume SRC_OVER
1343                *mode = SkXfermode::kSrcOver_Mode;
1344            }
1345        } else {
1346            *mode = getXfermode(paint->getXfermode());
1347        }
1348
1349        // Skia draws using the color's alpha channel if < 255
1350        // Otherwise, it uses the paint's alpha
1351        int color = paint->getColor();
1352        *alpha = (color >> 24) & 0xFF;
1353        if (*alpha == 255) {
1354            *alpha = paint->getAlpha();
1355        }
1356    } else {
1357        *mode = SkXfermode::kSrcOver_Mode;
1358        *alpha = 255;
1359    }
1360}
1361
1362SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1363    if (mode == NULL) {
1364        return SkXfermode::kSrcOver_Mode;
1365    }
1366    return mode->fMode;
1367}
1368
1369void OpenGLRenderer::bindTexture(GLuint texture, GLenum wrapS, GLenum wrapT, GLuint textureUnit) {
1370    glActiveTexture(gTextureUnits[textureUnit]);
1371    glBindTexture(GL_TEXTURE_2D, texture);
1372    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1373    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1374}
1375
1376}; // namespace uirenderer
1377}; // namespace android
1378