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