OpenGLRenderer.cpp revision 8164c2d338781c3a3c4a443941070dca5d88f2a7
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        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        // Clear the previous layer regions before we change the viewport
358        clearLayerRegions();
359    } else {
360        mSnapshot->transform->mapRect(bounds);
361
362        // Layers only make sense if they are in the framebuffer's bounds
363        bounds.intersect(*snapshot->clipRect);
364
365        // We cannot work with sub-pixels in this case
366        bounds.snapToPixelBoundaries();
367
368        // When the layer is not an FBO, we may use glCopyTexImage so we
369        // need to make sure the layer does not extend outside the bounds
370        // of the framebuffer
371        bounds.intersect(snapshot->previous->viewport);
372    }
373
374    if (bounds.isEmpty() || bounds.getWidth() > mMaxTextureSize ||
375            bounds.getHeight() > mMaxTextureSize) {
376        snapshot->invisible = true;
377    } else {
378        // TODO: Should take the mode into account
379        snapshot->invisible = snapshot->previous->invisible ||
380                (alpha <= ALPHA_THRESHOLD && fboLayer);
381    }
382
383    // Bail out if we won't draw in this snapshot
384    if (snapshot->invisible) {
385        return false;
386    }
387
388    glActiveTexture(GL_TEXTURE0);
389
390    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
391    if (!layer) {
392        return false;
393    }
394
395    layer->mode = mode;
396    layer->alpha = alpha;
397    layer->layer.set(bounds);
398    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
399            bounds.getWidth() / float(layer->width), 0.0f);
400
401    // Save the layer in the snapshot
402    snapshot->flags |= Snapshot::kFlagIsLayer;
403    snapshot->layer = layer;
404
405    if (fboLayer) {
406        layer->fbo = mCaches.fboCache.get();
407
408        snapshot->flags |= Snapshot::kFlagIsFboLayer;
409        snapshot->fbo = layer->fbo;
410        snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
411        snapshot->resetClip(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
412        snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
413        snapshot->height = bounds.getHeight();
414        snapshot->flags |= Snapshot::kFlagDirtyOrtho;
415        snapshot->orthoMatrix.load(mOrthoMatrix);
416
417        // Bind texture to FBO
418        glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
419        glBindTexture(GL_TEXTURE_2D, layer->texture);
420
421        // Initialize the texture if needed
422        if (layer->empty) {
423            layer->empty = false;
424            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
425                    GL_RGBA, GL_UNSIGNED_BYTE, NULL);
426        }
427
428        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
429                layer->texture, 0);
430
431#if DEBUG_LAYERS
432        GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
433        if (status != GL_FRAMEBUFFER_COMPLETE) {
434            LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
435
436            glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
437            glDeleteTextures(1, &layer->texture);
438            mCaches.fboCache.put(layer->fbo);
439
440            delete layer;
441
442            return false;
443        }
444#endif
445
446        // Clear the FBO
447        glScissor(0.0f, 0.0f, bounds.getWidth() + 1.0f, bounds.getHeight() + 1.0f);
448        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
449        glClear(GL_COLOR_BUFFER_BIT);
450
451        setScissorFromClip();
452
453        // Change the ortho projection
454        glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
455        mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
456    } else {
457        // Copy the framebuffer into the layer
458        glBindTexture(GL_TEXTURE_2D, layer->texture);
459
460        if (layer->empty) {
461            glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left,
462                    snapshot->height - bounds.bottom, layer->width, layer->height, 0);
463            layer->empty = false;
464        } else {
465            glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
466                    snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
467        }
468
469        // Enqueue the buffer coordinates to clear the corresponding region later
470        mLayers.push(new Rect(bounds));
471    }
472
473    return true;
474}
475
476/**
477 * Read the documentation of createLayer() before doing anything in this method.
478 */
479void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
480    if (!current->layer) {
481        LOGE("Attempting to compose a layer that does not exist");
482        return;
483    }
484
485    const bool fboLayer = current->flags & SkCanvas::kClipToLayer_SaveFlag;
486
487    if (fboLayer) {
488        // Unbind current FBO and restore previous one
489        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
490    }
491
492    // Restore the clip from the previous snapshot
493    Rect& clip(*previous->clipRect);
494    clip.snapToPixelBoundaries();
495    glScissor(clip.left, previous->height - clip.bottom, clip.getWidth(), clip.getHeight());
496
497    Layer* layer = current->layer;
498    const Rect& rect = layer->layer;
499
500    if (!fboLayer && layer->alpha < 255) {
501        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
502                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
503    }
504
505    const Rect& texCoords = layer->texCoords;
506    mCaches.unbindMeshBuffer();
507    resetDrawTextureTexCoords(texCoords.left, texCoords.top, texCoords.right, texCoords.bottom);
508
509    if (fboLayer) {
510        drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
511                layer->alpha / 255.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
512                &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount);
513    } else {
514        drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
515                1.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
516                &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, true, true);
517    }
518
519    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
520
521    if (fboLayer) {
522        // Detach the texture from the FBO
523        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
524        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
525        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
526
527        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
528        mCaches.fboCache.put(current->fbo);
529    }
530
531    // Failing to add the layer to the cache should happen only if the layer is too large
532    if (!mCaches.layerCache.put(layer)) {
533        LAYER_LOGD("Deleting layer");
534        glDeleteTextures(1, &layer->texture);
535        delete layer;
536    }
537}
538
539void OpenGLRenderer::clearLayerRegions() {
540    if (mLayers.size() == 0 || mSnapshot->invisible) return;
541
542    for (uint32_t i = 0; i < mLayers.size(); i++) {
543        Rect* bounds = mLayers.itemAt(i);
544
545        // Clear the framebuffer where the layer will draw
546        glScissor(bounds->left, mSnapshot->height - bounds->bottom,
547                bounds->getWidth(), bounds->getHeight());
548        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
549        glClear(GL_COLOR_BUFFER_BIT);
550
551        delete bounds;
552    }
553    mLayers.clear();
554
555    // Restore the clip
556    setScissorFromClip();
557}
558
559///////////////////////////////////////////////////////////////////////////////
560// Transforms
561///////////////////////////////////////////////////////////////////////////////
562
563void OpenGLRenderer::translate(float dx, float dy) {
564    mSnapshot->transform->translate(dx, dy, 0.0f);
565}
566
567void OpenGLRenderer::rotate(float degrees) {
568    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
569}
570
571void OpenGLRenderer::scale(float sx, float sy) {
572    mSnapshot->transform->scale(sx, sy, 1.0f);
573}
574
575void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
576    mSnapshot->transform->load(*matrix);
577}
578
579const float* OpenGLRenderer::getMatrix() const {
580    if (mSnapshot->fbo != 0) {
581        return &mSnapshot->transform->data[0];
582    }
583    return &mIdentity.data[0];
584}
585
586void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
587    mSnapshot->transform->copyTo(*matrix);
588}
589
590void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
591    SkMatrix transform;
592    mSnapshot->transform->copyTo(transform);
593    transform.preConcat(*matrix);
594    mSnapshot->transform->load(transform);
595}
596
597///////////////////////////////////////////////////////////////////////////////
598// Clipping
599///////////////////////////////////////////////////////////////////////////////
600
601void OpenGLRenderer::setScissorFromClip() {
602    Rect clip(*mSnapshot->clipRect);
603    clip.snapToPixelBoundaries();
604    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
605}
606
607const Rect& OpenGLRenderer::getClipBounds() {
608    return mSnapshot->getLocalClip();
609}
610
611bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
612    if (mSnapshot->invisible) {
613        return true;
614    }
615
616    Rect r(left, top, right, bottom);
617    mSnapshot->transform->mapRect(r);
618    r.snapToPixelBoundaries();
619
620    Rect clipRect(*mSnapshot->clipRect);
621    clipRect.snapToPixelBoundaries();
622
623    return !clipRect.intersects(r);
624}
625
626bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
627    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
628    if (clipped) {
629        setScissorFromClip();
630    }
631    return !mSnapshot->clipRect->isEmpty();
632}
633
634///////////////////////////////////////////////////////////////////////////////
635// Drawing
636///////////////////////////////////////////////////////////////////////////////
637
638void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
639    const float right = left + bitmap->width();
640    const float bottom = top + bitmap->height();
641
642    if (quickReject(left, top, right, bottom)) {
643        return;
644    }
645
646    glActiveTexture(GL_TEXTURE0);
647    Texture* texture = mCaches.textureCache.get(bitmap);
648    if (!texture) return;
649    const AutoTexture autoCleanup(texture);
650
651    drawTextureRect(left, top, right, bottom, texture, paint);
652}
653
654void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
655    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
656    const mat4 transform(*matrix);
657    transform.mapRect(r);
658
659    if (quickReject(r.left, r.top, r.right, r.bottom)) {
660        return;
661    }
662
663    glActiveTexture(GL_TEXTURE0);
664    Texture* texture = mCaches.textureCache.get(bitmap);
665    if (!texture) return;
666    const AutoTexture autoCleanup(texture);
667
668    drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint);
669}
670
671void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
672         float srcLeft, float srcTop, float srcRight, float srcBottom,
673         float dstLeft, float dstTop, float dstRight, float dstBottom,
674         SkPaint* paint) {
675    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
676        return;
677    }
678
679    glActiveTexture(GL_TEXTURE0);
680    Texture* texture = mCaches.textureCache.get(bitmap);
681    if (!texture) return;
682    const AutoTexture autoCleanup(texture);
683    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
684
685    const float width = texture->width;
686    const float height = texture->height;
687
688    const float u1 = srcLeft / width;
689    const float v1 = srcTop / height;
690    const float u2 = srcRight / width;
691    const float v2 = srcBottom / height;
692
693    mCaches.unbindMeshBuffer();
694    resetDrawTextureTexCoords(u1, v1, u2, v2);
695
696    int alpha;
697    SkXfermode::Mode mode;
698    getAlphaAndMode(paint, &alpha, &mode);
699
700    drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
701            mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
702            GL_TRIANGLE_STRIP, gMeshCount);
703
704    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
705}
706
707void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
708        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
709        float left, float top, float right, float bottom, SkPaint* paint) {
710    if (quickReject(left, top, right, bottom)) {
711        return;
712    }
713
714    glActiveTexture(GL_TEXTURE0);
715    Texture* texture = mCaches.textureCache.get(bitmap);
716    if (!texture) return;
717    const AutoTexture autoCleanup(texture);
718    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
719
720    int alpha;
721    SkXfermode::Mode mode;
722    getAlphaAndMode(paint, &alpha, &mode);
723
724    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
725            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
726
727    if (mesh) {
728        // Specify right and bottom as +1.0f from left/top to prevent scaling since the
729        // patch mesh already defines the final size
730        drawTextureMesh(left, top, left + 1.0f, top + 1.0f, texture->id, alpha / 255.0f,
731                mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
732                GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer);
733    }
734}
735
736void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
737    if (mSnapshot->invisible) return;
738
739    int alpha;
740    SkXfermode::Mode mode;
741    getAlphaAndMode(paint, &alpha, &mode);
742
743    uint32_t color = paint->getColor();
744    const GLfloat a = alpha / 255.0f;
745    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
746    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
747    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
748
749    const bool isAA = paint->isAntiAlias();
750    if (isAA) {
751        GLuint textureUnit = 0;
752        setupTextureAlpha8(mCaches.line.getTexture(), 0, 0, textureUnit, 0.0f, 0.0f, r, g, b, a,
753                mode, false, true, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
754                mCaches.line.getMeshBuffer());
755    } else {
756        setupColorRect(0.0f, 0.0f, 1.0f, 1.0f, r, g, b, a, mode, false);
757    }
758
759    const float strokeWidth = paint->getStrokeWidth();
760    const GLsizei elementsCount = isAA ? mCaches.line.getElementsCount() : gMeshCount;
761    const GLenum drawMode = isAA ? GL_TRIANGLES : GL_TRIANGLE_STRIP;
762
763    for (int i = 0; i < count; i += 4) {
764        float tx = 0.0f;
765        float ty = 0.0f;
766
767        if (isAA) {
768            mCaches.line.update(points[i], points[i + 1], points[i + 2], points[i + 3],
769                    strokeWidth, tx, ty);
770        } else {
771            ty = strokeWidth <= 1.0f ? 0.0f : -strokeWidth * 0.5f;
772        }
773
774        const float dx = points[i + 2] - points[i];
775        const float dy = points[i + 3] - points[i + 1];
776        const float mag = sqrtf(dx * dx + dy * dy);
777        const float angle = acos(dx / mag);
778
779        mModelView.loadTranslate(points[i], points[i + 1], 0.0f);
780        if (angle > MIN_ANGLE || angle < -MIN_ANGLE) {
781            mModelView.rotate(angle * RAD_TO_DEG, 0.0f, 0.0f, 1.0f);
782        }
783        mModelView.translate(tx, ty, 0.0f);
784        if (!isAA) {
785            float length = mCaches.line.getLength(points[i], points[i + 1],
786                    points[i + 2], points[i + 3]);
787            mModelView.scale(length, strokeWidth, 1.0f);
788        }
789        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
790
791        if (mShader) {
792            mShader->updateTransforms(mCaches.currentProgram, mModelView, *mSnapshot);
793        }
794
795        glDrawArrays(drawMode, 0, elementsCount);
796    }
797
798    if (isAA) {
799        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
800    }
801}
802
803void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
804    Rect& clip(*mSnapshot->clipRect);
805    clip.snapToPixelBoundaries();
806    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
807}
808
809void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
810    if (quickReject(left, top, right, bottom)) {
811        return;
812    }
813
814    SkXfermode::Mode mode;
815    if (!mExtensions.hasFramebufferFetch()) {
816        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
817        if (!isMode) {
818            // Assume SRC_OVER
819            mode = SkXfermode::kSrcOver_Mode;
820        }
821    } else {
822        mode = getXfermode(p->getXfermode());
823    }
824
825    // Skia draws using the color's alpha channel if < 255
826    // Otherwise, it uses the paint's alpha
827    int color = p->getColor();
828    if (((color >> 24) & 0xff) == 255) {
829        color |= p->getAlpha() << 24;
830    }
831
832    drawColorRect(left, top, right, bottom, color, mode);
833}
834
835void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
836        float x, float y, SkPaint* paint) {
837    if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
838        return;
839    }
840    if (mSnapshot->invisible) return;
841
842    paint->setAntiAlias(true);
843
844    float length = -1.0f;
845    switch (paint->getTextAlign()) {
846        case SkPaint::kCenter_Align:
847            length = paint->measureText(text, bytesCount);
848            x -= length / 2.0f;
849            break;
850        case SkPaint::kRight_Align:
851            length = paint->measureText(text, bytesCount);
852            x -= length;
853            break;
854        default:
855            break;
856    }
857
858    int alpha;
859    SkXfermode::Mode mode;
860    getAlphaAndMode(paint, &alpha, &mode);
861
862    uint32_t color = paint->getColor();
863    const GLfloat a = alpha / 255.0f;
864    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
865    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
866    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
867
868    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
869    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
870            paint->getTextSize());
871
872    Rect clipRect(*mSnapshot->clipRect);
873    clipRect.snapToPixelBoundaries();
874    glScissor(clipRect.left, mSnapshot->height - clipRect.bottom,
875            clipRect.getWidth(), clipRect.getHeight());
876
877    if (mHasShadow) {
878        glActiveTexture(gTextureUnits[0]);
879        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
880        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
881                count, mShadowRadius);
882        const AutoTexture autoCleanup(shadow);
883
884        setupShadow(shadow, x, y, mode, a);
885
886        // Draw the mesh
887        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
888        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
889    }
890
891    GLuint textureUnit = 0;
892    glActiveTexture(gTextureUnits[textureUnit]);
893
894    // Assume that the modelView matrix does not force scales, rotates, etc.
895    const bool linearFilter = mSnapshot->transform->changesBounds();
896    setupTextureAlpha8(fontRenderer.getTexture(linearFilter), 0, 0, textureUnit,
897            x, y, r, g, b, a, mode, false, true, NULL, NULL);
898
899    const Rect& clip = mSnapshot->getLocalClip();
900    clearLayerRegions();
901
902    mCaches.unbindMeshBuffer();
903    fontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y);
904
905    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
906    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
907
908    drawTextDecorations(text, bytesCount, length, x, y, paint);
909
910    setScissorFromClip();
911}
912
913void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
914    if (mSnapshot->invisible) return;
915
916    GLuint textureUnit = 0;
917    glActiveTexture(gTextureUnits[textureUnit]);
918
919    const PathTexture* texture = mCaches.pathCache.get(path, paint);
920    if (!texture) return;
921    const AutoTexture autoCleanup(texture);
922
923    const float x = texture->left - texture->offset;
924    const float y = texture->top - texture->offset;
925
926    if (quickReject(x, y, x + texture->width, y + texture->height)) {
927        return;
928    }
929
930    int alpha;
931    SkXfermode::Mode mode;
932    getAlphaAndMode(paint, &alpha, &mode);
933
934    uint32_t color = paint->getColor();
935    const GLfloat a = alpha / 255.0f;
936    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
937    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
938    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
939
940    setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true);
941
942    clearLayerRegions();
943
944    // Draw the mesh
945    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
946    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
947}
948
949///////////////////////////////////////////////////////////////////////////////
950// Shaders
951///////////////////////////////////////////////////////////////////////////////
952
953void OpenGLRenderer::resetShader() {
954    mShader = NULL;
955}
956
957void OpenGLRenderer::setupShader(SkiaShader* shader) {
958    mShader = shader;
959    if (mShader) {
960        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
961    }
962}
963
964///////////////////////////////////////////////////////////////////////////////
965// Color filters
966///////////////////////////////////////////////////////////////////////////////
967
968void OpenGLRenderer::resetColorFilter() {
969    mColorFilter = NULL;
970}
971
972void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
973    mColorFilter = filter;
974}
975
976///////////////////////////////////////////////////////////////////////////////
977// Drop shadow
978///////////////////////////////////////////////////////////////////////////////
979
980void OpenGLRenderer::resetShadow() {
981    mHasShadow = false;
982}
983
984void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
985    mHasShadow = true;
986    mShadowRadius = radius;
987    mShadowDx = dx;
988    mShadowDy = dy;
989    mShadowColor = color;
990}
991
992///////////////////////////////////////////////////////////////////////////////
993// Drawing implementation
994///////////////////////////////////////////////////////////////////////////////
995
996void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y,
997        SkXfermode::Mode mode, float alpha) {
998    const float sx = x - texture->left + mShadowDx;
999    const float sy = y - texture->top + mShadowDy;
1000
1001    const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
1002    const GLfloat a = shadowAlpha < 255 ? shadowAlpha / 255.0f : alpha;
1003    const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f;
1004    const GLfloat g = a * ((mShadowColor >>  8) & 0xFF) / 255.0f;
1005    const GLfloat b = a * ((mShadowColor      ) & 0xFF) / 255.0f;
1006
1007    GLuint textureUnit = 0;
1008    setupTextureAlpha8(texture, textureUnit, sx, sy, r, g, b, a, mode, true, false);
1009}
1010
1011void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit,
1012        float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode,
1013        bool transforms, bool applyFilters) {
1014    setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit,
1015            x, y, r, g, b, a, mode, transforms, applyFilters,
1016            (GLvoid*) 0, (GLvoid*) gMeshTextureOffset);
1017}
1018
1019void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
1020        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
1021        SkXfermode::Mode mode, bool transforms, bool applyFilters) {
1022    setupTextureAlpha8(texture, width, height, textureUnit, x, y, r, g, b, a, mode,
1023            transforms, applyFilters, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset);
1024}
1025
1026void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
1027        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
1028        SkXfermode::Mode mode, bool transforms, bool applyFilters,
1029        GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1030     // Describe the required shaders
1031     ProgramDescription description;
1032     description.hasTexture = true;
1033     description.hasAlpha8Texture = true;
1034     const bool setColor = description.setAlpha8Color(r, g, b, a);
1035
1036     if (applyFilters) {
1037         if (mShader) {
1038             mShader->describe(description, mExtensions);
1039         }
1040         if (mColorFilter) {
1041             mColorFilter->describe(description, mExtensions);
1042         }
1043     }
1044
1045     // Setup the blending mode
1046     chooseBlending(true, mode, description);
1047
1048     // Build and use the appropriate shader
1049     useProgram(mCaches.programCache.get(description));
1050
1051     bindTexture(texture, textureUnit);
1052     glUniform1i(mCaches.currentProgram->getUniform("sampler"), textureUnit);
1053
1054     int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1055     glEnableVertexAttribArray(texCoordsSlot);
1056
1057     if (texCoords) {
1058         // Setup attributes
1059         if (!vertices) {
1060             mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1061         } else {
1062             mCaches.unbindMeshBuffer();
1063         }
1064         glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1065                 gMeshStride, vertices);
1066         glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1067     }
1068
1069     // Setup uniforms
1070     if (transforms) {
1071         mModelView.loadTranslate(x, y, 0.0f);
1072         mModelView.scale(width, height, 1.0f);
1073     } else {
1074         mModelView.loadIdentity();
1075     }
1076     mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1077     if (setColor) {
1078         mCaches.currentProgram->setColor(r, g, b, a);
1079     }
1080
1081     textureUnit++;
1082     if (applyFilters) {
1083         // Setup attributes and uniforms required by the shaders
1084         if (mShader) {
1085             mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1086         }
1087         if (mColorFilter) {
1088             mColorFilter->setupProgram(mCaches.currentProgram);
1089         }
1090     }
1091}
1092
1093// Same values used by Skia
1094#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
1095#define kStdUnderline_Offset    (1.0f / 9.0f)
1096#define kStdUnderline_Thickness (1.0f / 18.0f)
1097
1098void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
1099        float x, float y, SkPaint* paint) {
1100    // Handle underline and strike-through
1101    uint32_t flags = paint->getFlags();
1102    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
1103        float underlineWidth = length;
1104        // If length is > 0.0f, we already measured the text for the text alignment
1105        if (length <= 0.0f) {
1106            underlineWidth = paint->measureText(text, bytesCount);
1107        }
1108
1109        float offsetX = 0;
1110        switch (paint->getTextAlign()) {
1111            case SkPaint::kCenter_Align:
1112                offsetX = underlineWidth * 0.5f;
1113                break;
1114            case SkPaint::kRight_Align:
1115                offsetX = underlineWidth;
1116                break;
1117            default:
1118                break;
1119        }
1120
1121        if (underlineWidth > 0.0f) {
1122            const float textSize = paint->getTextSize();
1123            const float strokeWidth = textSize * kStdUnderline_Thickness;
1124
1125            const float left = x - offsetX;
1126            float top = 0.0f;
1127
1128            const int pointsCount = 4 * (flags & SkPaint::kStrikeThruText_Flag ? 2 : 1);
1129            float points[pointsCount];
1130            int currentPoint = 0;
1131
1132            if (flags & SkPaint::kUnderlineText_Flag) {
1133                top = y + textSize * kStdUnderline_Offset;
1134                points[currentPoint++] = left;
1135                points[currentPoint++] = top;
1136                points[currentPoint++] = left + underlineWidth;
1137                points[currentPoint++] = top;
1138            }
1139
1140            if (flags & SkPaint::kStrikeThruText_Flag) {
1141                top = y + textSize * kStdStrikeThru_Offset;
1142                points[currentPoint++] = left;
1143                points[currentPoint++] = top;
1144                points[currentPoint++] = left + underlineWidth;
1145                points[currentPoint++] = top;
1146            }
1147
1148            SkPaint linesPaint(*paint);
1149            linesPaint.setStrokeWidth(strokeWidth);
1150
1151            drawLines(&points[0], pointsCount, &linesPaint);
1152        }
1153    }
1154}
1155
1156void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
1157        int color, SkXfermode::Mode mode, bool ignoreTransform) {
1158    clearLayerRegions();
1159
1160    // If a shader is set, preserve only the alpha
1161    if (mShader) {
1162        color |= 0x00ffffff;
1163    }
1164
1165    // Render using pre-multiplied alpha
1166    const int alpha = (color >> 24) & 0xFF;
1167    const GLfloat a = alpha / 255.0f;
1168    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
1169    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
1170    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
1171
1172    setupColorRect(left, top, right, bottom, r, g, b, a, mode, ignoreTransform);
1173
1174    // Draw the mesh
1175    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1176}
1177
1178void OpenGLRenderer::setupColorRect(float left, float top, float right, float bottom,
1179        float r, float g, float b, float a, SkXfermode::Mode mode, bool ignoreTransform) {
1180    GLuint textureUnit = 0;
1181
1182    // Describe the required shaders
1183    ProgramDescription description;
1184    const bool setColor = description.setColor(r, g, b, a);
1185
1186    if (mShader) {
1187        mShader->describe(description, mExtensions);
1188    }
1189    if (mColorFilter) {
1190        mColorFilter->describe(description, mExtensions);
1191    }
1192
1193    // Setup the blending mode
1194    chooseBlending(a < 1.0f || (mShader && mShader->blend()), mode, description);
1195
1196    // Build and use the appropriate shader
1197    useProgram(mCaches.programCache.get(description));
1198
1199    // Setup attributes
1200    mCaches.bindMeshBuffer();
1201    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1202            gMeshStride, 0);
1203
1204    // Setup uniforms
1205    mModelView.loadTranslate(left, top, 0.0f);
1206    mModelView.scale(right - left, bottom - top, 1.0f);
1207    if (!ignoreTransform) {
1208        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1209    } else {
1210        mat4 identity;
1211        mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity);
1212    }
1213    mCaches.currentProgram->setColor(r, g, b, a);
1214
1215    // Setup attributes and uniforms required by the shaders
1216    if (mShader) {
1217        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1218    }
1219    if (mColorFilter) {
1220        mColorFilter->setupProgram(mCaches.currentProgram);
1221    }
1222}
1223
1224void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1225        Texture* texture, SkPaint* paint) {
1226    int alpha;
1227    SkXfermode::Mode mode;
1228    getAlphaAndMode(paint, &alpha, &mode);
1229
1230    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1231
1232    drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
1233            texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
1234            GL_TRIANGLE_STRIP, gMeshCount);
1235}
1236
1237void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1238        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
1239    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
1240            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
1241}
1242
1243void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
1244        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
1245        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
1246        bool swapSrcDst, bool ignoreTransform, GLuint vbo) {
1247    clearLayerRegions();
1248
1249    ProgramDescription description;
1250    description.hasTexture = true;
1251    const bool setColor = description.setColor(alpha, alpha, alpha, alpha);
1252    if (mColorFilter) {
1253        mColorFilter->describe(description, mExtensions);
1254    }
1255
1256    mModelView.loadTranslate(left, top, 0.0f);
1257    mModelView.scale(right - left, bottom - top, 1.0f);
1258
1259    chooseBlending(blend || alpha < 1.0f, mode, description, swapSrcDst);
1260
1261    useProgram(mCaches.programCache.get(description));
1262    if (!ignoreTransform) {
1263        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1264    } else {
1265        mat4 m;
1266        mCaches.currentProgram->set(mOrthoMatrix, mModelView, m);
1267    }
1268
1269    // Texture
1270    bindTexture(texture);
1271    glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
1272
1273    // Always premultiplied
1274    if (setColor) {
1275        mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha);
1276    }
1277
1278    // Mesh
1279    int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1280    glEnableVertexAttribArray(texCoordsSlot);
1281
1282    if (!vertices) {
1283        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1284    } else {
1285        mCaches.unbindMeshBuffer();
1286    }
1287    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1288            gMeshStride, vertices);
1289    glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1290
1291    // Color filter
1292    if (mColorFilter) {
1293        mColorFilter->setupProgram(mCaches.currentProgram);
1294    }
1295
1296    glDrawArrays(drawMode, 0, elementsCount);
1297    glDisableVertexAttribArray(texCoordsSlot);
1298}
1299
1300void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
1301        ProgramDescription& description, bool swapSrcDst) {
1302    blend = blend || mode != SkXfermode::kSrcOver_Mode;
1303    if (blend) {
1304        if (mode < SkXfermode::kPlus_Mode) {
1305            if (!mCaches.blend) {
1306                glEnable(GL_BLEND);
1307            }
1308
1309            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
1310            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
1311
1312            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
1313                glBlendFunc(sourceMode, destMode);
1314                mCaches.lastSrcMode = sourceMode;
1315                mCaches.lastDstMode = destMode;
1316            }
1317        } else {
1318            // These blend modes are not supported by OpenGL directly and have
1319            // to be implemented using shaders. Since the shader will perform
1320            // the blending, turn blending off here
1321            if (mExtensions.hasFramebufferFetch()) {
1322                description.framebufferMode = mode;
1323                description.swapSrcDst = swapSrcDst;
1324            }
1325
1326            if (mCaches.blend) {
1327                glDisable(GL_BLEND);
1328            }
1329            blend = false;
1330        }
1331    } else if (mCaches.blend) {
1332        glDisable(GL_BLEND);
1333    }
1334    mCaches.blend = blend;
1335}
1336
1337bool OpenGLRenderer::useProgram(Program* program) {
1338    if (!program->isInUse()) {
1339        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1340        program->use();
1341        mCaches.currentProgram = program;
1342        return false;
1343    }
1344    return true;
1345}
1346
1347void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1348    TextureVertex* v = &mMeshVertices[0];
1349    TextureVertex::setUV(v++, u1, v1);
1350    TextureVertex::setUV(v++, u2, v1);
1351    TextureVertex::setUV(v++, u1, v2);
1352    TextureVertex::setUV(v++, u2, v2);
1353}
1354
1355void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1356    if (paint) {
1357        if (!mExtensions.hasFramebufferFetch()) {
1358            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1359            if (!isMode) {
1360                // Assume SRC_OVER
1361                *mode = SkXfermode::kSrcOver_Mode;
1362            }
1363        } else {
1364            *mode = getXfermode(paint->getXfermode());
1365        }
1366
1367        // Skia draws using the color's alpha channel if < 255
1368        // Otherwise, it uses the paint's alpha
1369        int color = paint->getColor();
1370        *alpha = (color >> 24) & 0xFF;
1371        if (*alpha == 255) {
1372            *alpha = paint->getAlpha();
1373        }
1374    } else {
1375        *mode = SkXfermode::kSrcOver_Mode;
1376        *alpha = 255;
1377    }
1378}
1379
1380SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1381    if (mode == NULL) {
1382        return SkXfermode::kSrcOver_Mode;
1383    }
1384    return mode->fMode;
1385}
1386
1387void OpenGLRenderer::bindTexture(GLuint texture, GLuint textureUnit) {
1388    glActiveTexture(gTextureUnits[textureUnit]);
1389    glBindTexture(GL_TEXTURE_2D, texture);
1390}
1391
1392void OpenGLRenderer::setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT,
1393        GLuint textureUnit) {
1394    glActiveTexture(gTextureUnits[textureUnit]);
1395    bool bound = false;
1396    if (wrapS != texture->wrapS) {
1397        glBindTexture(GL_TEXTURE_2D, texture->id);
1398        bound = true;
1399        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1400        texture->wrapS = wrapS;
1401    }
1402    if (wrapT != texture->wrapT) {
1403        if (!bound) glBindTexture(GL_TEXTURE_2D, texture->id);
1404        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1405        texture->wrapT = wrapT;
1406    }
1407}
1408
1409}; // namespace uirenderer
1410}; // namespace android
1411