OpenGLRenderer.cpp revision af636ebf5feb2837683fbfe965040cb706b32ec1
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 <ui/Rect.h>
30
31#include "OpenGLRenderer.h"
32#include "DisplayListRenderer.h"
33#include "Vector.h"
34
35namespace android {
36namespace uirenderer {
37
38///////////////////////////////////////////////////////////////////////////////
39// Defines
40///////////////////////////////////////////////////////////////////////////////
41
42#define RAD_TO_DEG (180.0f / 3.14159265f)
43#define MIN_ANGLE 0.001f
44
45// TODO: This should be set in properties
46#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH)
47
48///////////////////////////////////////////////////////////////////////////////
49// Globals
50///////////////////////////////////////////////////////////////////////////////
51
52/**
53 * Structure mapping Skia xfermodes to OpenGL blending factors.
54 */
55struct Blender {
56    SkXfermode::Mode mode;
57    GLenum src;
58    GLenum dst;
59}; // struct Blender
60
61// In this array, the index of each Blender equals the value of the first
62// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
63static const Blender gBlends[] = {
64        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
65        { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
66        { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
67        { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
68        { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
69        { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
70        { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
71        { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
72        { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
73        { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
74        { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
75        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
76};
77
78// This array contains the swapped version of each SkXfermode. For instance
79// this array's SrcOver blending mode is actually DstOver. You can refer to
80// createLayer() for more information on the purpose of this array.
81static const Blender gBlendsSwap[] = {
82        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
83        { SkXfermode::kSrc_Mode,     GL_ZERO,                 GL_ONE },
84        { SkXfermode::kDst_Mode,     GL_ONE,                  GL_ZERO },
85        { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
86        { SkXfermode::kDstOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
87        { SkXfermode::kSrcIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
88        { SkXfermode::kDstIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
89        { SkXfermode::kSrcOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
90        { SkXfermode::kDstOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
91        { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
92        { SkXfermode::kDstATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
93        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
94};
95
96static const GLenum gTextureUnits[] = {
97        GL_TEXTURE0,
98        GL_TEXTURE1,
99        GL_TEXTURE2
100};
101
102///////////////////////////////////////////////////////////////////////////////
103// Constructors/destructor
104///////////////////////////////////////////////////////////////////////////////
105
106OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
107    mShader = NULL;
108    mColorFilter = NULL;
109    mHasShadow = false;
110
111    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
112
113    mFirstSnapshot = new Snapshot;
114}
115
116OpenGLRenderer::~OpenGLRenderer() {
117    // The context has already been destroyed at this point, do not call
118    // GL APIs. All GL state should be kept in Caches.h
119}
120
121///////////////////////////////////////////////////////////////////////////////
122// Setup
123///////////////////////////////////////////////////////////////////////////////
124
125void OpenGLRenderer::setViewport(int width, int height) {
126    glViewport(0, 0, width, height);
127    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
128
129    mWidth = width;
130    mHeight = height;
131
132    mFirstSnapshot->height = height;
133    mFirstSnapshot->viewport.set(0, 0, width, height);
134
135    mDirtyClip = false;
136}
137
138void OpenGLRenderer::prepare(bool opaque) {
139    mCaches.clearGarbage();
140
141    mSnapshot = new Snapshot(mFirstSnapshot,
142            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
143    mSaveCount = 1;
144
145    glViewport(0, 0, mWidth, mHeight);
146
147    glDisable(GL_DITHER);
148
149    if (!opaque) {
150        glDisable(GL_SCISSOR_TEST);
151        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
152        glClear(GL_COLOR_BUFFER_BIT);
153    }
154
155    glEnable(GL_SCISSOR_TEST);
156    glScissor(0, 0, mWidth, mHeight);
157    mSnapshot->setClip(0.0f, 0.0f, mWidth, mHeight);
158}
159
160void OpenGLRenderer::finish() {
161#if DEBUG_OPENGL
162    GLenum status = GL_NO_ERROR;
163    while ((status = glGetError()) != GL_NO_ERROR) {
164        LOGD("GL error from OpenGLRenderer: 0x%x", status);
165    }
166#endif
167#if DEBUG_MEMORY_USAGE
168    mCaches.dumpMemoryUsage();
169#else
170    if (mCaches.getDebugLevel() & kDebugMemory) {
171        mCaches.dumpMemoryUsage();
172    }
173#endif
174}
175
176void OpenGLRenderer::acquireContext() {
177    if (mCaches.currentProgram) {
178        if (mCaches.currentProgram->isInUse()) {
179            mCaches.currentProgram->remove();
180            mCaches.currentProgram = NULL;
181        }
182    }
183    mCaches.unbindMeshBuffer();
184}
185
186void OpenGLRenderer::releaseContext() {
187    glViewport(0, 0, mSnapshot->viewport.getWidth(), mSnapshot->viewport.getHeight());
188
189    glEnable(GL_SCISSOR_TEST);
190    dirtyClip();
191
192    glDisable(GL_DITHER);
193
194    glBindFramebuffer(GL_FRAMEBUFFER, 0);
195    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
196
197    mCaches.blend = true;
198    glEnable(GL_BLEND);
199    glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
200    glBlendEquation(GL_FUNC_ADD);
201}
202
203///////////////////////////////////////////////////////////////////////////////
204// State management
205///////////////////////////////////////////////////////////////////////////////
206
207int OpenGLRenderer::getSaveCount() const {
208    return mSaveCount;
209}
210
211int OpenGLRenderer::save(int flags) {
212    return saveSnapshot(flags);
213}
214
215void OpenGLRenderer::restore() {
216    if (mSaveCount > 1) {
217        restoreSnapshot();
218    }
219}
220
221void OpenGLRenderer::restoreToCount(int saveCount) {
222    if (saveCount < 1) saveCount = 1;
223
224    while (mSaveCount > saveCount) {
225        restoreSnapshot();
226    }
227}
228
229int OpenGLRenderer::saveSnapshot(int flags) {
230    mSnapshot = new Snapshot(mSnapshot, flags);
231    return mSaveCount++;
232}
233
234bool OpenGLRenderer::restoreSnapshot() {
235    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
236    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
237    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
238
239    sp<Snapshot> current = mSnapshot;
240    sp<Snapshot> previous = mSnapshot->previous;
241
242    if (restoreOrtho) {
243        Rect& r = previous->viewport;
244        glViewport(r.left, r.top, r.right, r.bottom);
245        mOrthoMatrix.load(current->orthoMatrix);
246    }
247
248    mSaveCount--;
249    mSnapshot = previous;
250
251    if (restoreClip) {
252        dirtyClip();
253    }
254
255    if (restoreLayer) {
256        composeLayer(current, previous);
257    }
258
259    return restoreClip;
260}
261
262///////////////////////////////////////////////////////////////////////////////
263// Layers
264///////////////////////////////////////////////////////////////////////////////
265
266int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
267        SkPaint* p, int flags) {
268    const GLuint previousFbo = mSnapshot->fbo;
269    const int count = saveSnapshot(flags);
270
271    if (!mSnapshot->isIgnored()) {
272        int alpha = 255;
273        SkXfermode::Mode mode;
274
275        if (p) {
276            alpha = p->getAlpha();
277            if (!mCaches.extensions.hasFramebufferFetch()) {
278                const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
279                if (!isMode) {
280                    // Assume SRC_OVER
281                    mode = SkXfermode::kSrcOver_Mode;
282                }
283            } else {
284                mode = getXfermode(p->getXfermode());
285            }
286        } else {
287            mode = SkXfermode::kSrcOver_Mode;
288        }
289
290        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
291    }
292
293    return count;
294}
295
296int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
297        int alpha, int flags) {
298    if (alpha >= 255 - ALPHA_THRESHOLD) {
299        return saveLayer(left, top, right, bottom, NULL, flags);
300    } else {
301        SkPaint paint;
302        paint.setAlpha(alpha);
303        return saveLayer(left, top, right, bottom, &paint, flags);
304    }
305}
306
307/**
308 * Layers are viewed by Skia are slightly different than layers in image editing
309 * programs (for instance.) When a layer is created, previously created layers
310 * and the frame buffer still receive every drawing command. For instance, if a
311 * layer is created and a shape intersecting the bounds of the layers and the
312 * framebuffer is draw, the shape will be drawn on both (unless the layer was
313 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
314 *
315 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
316 * texture. Unfortunately, this is inefficient as it requires every primitive to
317 * be drawn n + 1 times, where n is the number of active layers. In practice this
318 * means, for every primitive:
319 *   - Switch active frame buffer
320 *   - Change viewport, clip and projection matrix
321 *   - Issue the drawing
322 *
323 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
324 * To avoid this, layers are implemented in a different way here, at least in the
325 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
326 * is set. When this flag is set we can redirect all drawing operations into a
327 * single FBO.
328 *
329 * This implementation relies on the frame buffer being at least RGBA 8888. When
330 * a layer is created, only a texture is created, not an FBO. The content of the
331 * frame buffer contained within the layer's bounds is copied into this texture
332 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
333 * buffer and drawing continues as normal. This technique therefore treats the
334 * frame buffer as a scratch buffer for the layers.
335 *
336 * To compose the layers back onto the frame buffer, each layer texture
337 * (containing the original frame buffer data) is drawn as a simple quad over
338 * the frame buffer. The trick is that the quad is set as the composition
339 * destination in the blending equation, and the frame buffer becomes the source
340 * of the composition.
341 *
342 * Drawing layers with an alpha value requires an extra step before composition.
343 * An empty quad is drawn over the layer's region in the frame buffer. This quad
344 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
345 * quad is used to multiply the colors in the frame buffer. This is achieved by
346 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
347 * GL_ZERO, GL_SRC_ALPHA.
348 *
349 * Because glCopyTexImage2D() can be slow, an alternative implementation might
350 * be use to draw a single clipped layer. The implementation described above
351 * is correct in every case.
352 *
353 * (1) The frame buffer is actually not cleared right away. To allow the GPU
354 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
355 *     buffer is left untouched until the first drawing operation. Only when
356 *     something actually gets drawn are the layers regions cleared.
357 */
358bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
359        float right, float bottom, int alpha, SkXfermode::Mode mode,
360        int flags, GLuint previousFbo) {
361    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
362    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
363
364    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
365
366    // Window coordinates of the layer
367    Rect bounds(left, top, right, bottom);
368    if (fboLayer) {
369        // Clear the previous layer regions before we change the viewport
370        clearLayerRegions();
371    } else {
372        mSnapshot->transform->mapRect(bounds);
373
374        // Layers only make sense if they are in the framebuffer's bounds
375        bounds.intersect(*snapshot->clipRect);
376
377        // We cannot work with sub-pixels in this case
378        bounds.snapToPixelBoundaries();
379
380        // When the layer is not an FBO, we may use glCopyTexImage so we
381        // need to make sure the layer does not extend outside the bounds
382        // of the framebuffer
383        bounds.intersect(snapshot->previous->viewport);
384    }
385
386    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
387            bounds.getHeight() > mCaches.maxTextureSize) {
388        if (fboLayer) {
389            snapshot->invisible = true;
390        } else {
391            snapshot->empty = true;
392        }
393    } else {
394        snapshot->invisible = snapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
395    }
396
397    // Bail out if we won't draw in this snapshot
398    if (snapshot->invisible || snapshot->empty) {
399        return false;
400    }
401
402    glActiveTexture(gTextureUnits[0]);
403    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
404    if (!layer) {
405        return false;
406    }
407
408    layer->mode = mode;
409    layer->alpha = alpha;
410    layer->layer.set(bounds);
411    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
412            bounds.getWidth() / float(layer->width), 0.0f);
413
414    // Save the layer in the snapshot
415    snapshot->flags |= Snapshot::kFlagIsLayer;
416    snapshot->layer = layer;
417
418    if (fboLayer) {
419        return createFboLayer(layer, bounds, snapshot, previousFbo);
420    } else {
421        // Copy the framebuffer into the layer
422        glBindTexture(GL_TEXTURE_2D, layer->texture);
423
424        if (layer->empty) {
425            glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left,
426                    snapshot->height - bounds.bottom, layer->width, layer->height, 0);
427            layer->empty = false;
428        } else {
429            glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
430                    snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
431        }
432
433        // Enqueue the buffer coordinates to clear the corresponding region later
434        mLayers.push(new Rect(bounds));
435    }
436
437    return true;
438}
439
440bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
441        GLuint previousFbo) {
442    layer->fbo = mCaches.fboCache.get();
443
444#if RENDER_LAYERS_AS_REGIONS
445    snapshot->region = &snapshot->layer->region;
446    snapshot->flags |= Snapshot::kFlagFboTarget;
447#endif
448
449    Rect clip(bounds);
450    snapshot->transform->mapRect(clip);
451    clip.intersect(*snapshot->clipRect);
452    clip.snapToPixelBoundaries();
453    clip.intersect(snapshot->previous->viewport);
454
455    mat4 inverse;
456    inverse.loadInverse(*mSnapshot->transform);
457
458    inverse.mapRect(clip);
459    clip.snapToPixelBoundaries();
460    clip.intersect(bounds);
461    clip.translate(-bounds.left, -bounds.top);
462
463    snapshot->flags |= Snapshot::kFlagIsFboLayer;
464    snapshot->fbo = layer->fbo;
465    snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
466    //snapshot->resetClip(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
467    snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
468    snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
469    snapshot->height = bounds.getHeight();
470    snapshot->flags |= Snapshot::kFlagDirtyOrtho;
471    snapshot->orthoMatrix.load(mOrthoMatrix);
472
473    // Bind texture to FBO
474    glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
475    glBindTexture(GL_TEXTURE_2D, layer->texture);
476
477    // Initialize the texture if needed
478    if (layer->empty) {
479        layer->empty = false;
480        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
481                GL_RGBA, GL_UNSIGNED_BYTE, NULL);
482    }
483
484    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
485            layer->texture, 0);
486
487#if DEBUG_LAYERS_AS_REGIONS
488    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
489    if (status != GL_FRAMEBUFFER_COMPLETE) {
490        LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
491
492        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
493        glDeleteTextures(1, &layer->texture);
494        mCaches.fboCache.put(layer->fbo);
495
496        delete layer;
497
498        return false;
499    }
500#endif
501
502    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
503    glScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
504            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
505    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
506    glClear(GL_COLOR_BUFFER_BIT);
507
508    dirtyClip();
509
510    // Change the ortho projection
511    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
512    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
513
514    return true;
515}
516
517/**
518 * Read the documentation of createLayer() before doing anything in this method.
519 */
520void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
521    if (!current->layer) {
522        LOGE("Attempting to compose a layer that does not exist");
523        return;
524    }
525
526    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
527
528    if (fboLayer) {
529        // Unbind current FBO and restore previous one
530        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
531    }
532
533    Layer* layer = current->layer;
534    const Rect& rect = layer->layer;
535
536    if (!fboLayer && layer->alpha < 255) {
537        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
538                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
539        // Required below, composeLayerRect() will divide by 255
540        layer->alpha = 255;
541    }
542
543    mCaches.unbindMeshBuffer();
544
545    glActiveTexture(gTextureUnits[0]);
546
547    // When the layer is stored in an FBO, we can save a bit of fillrate by
548    // drawing only the dirty region
549    if (fboLayer) {
550        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
551        composeLayerRegion(layer, rect);
552    } else {
553        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
554        composeLayerRect(layer, rect, true);
555    }
556
557    if (fboLayer) {
558        // Detach the texture from the FBO
559        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
560        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
561        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
562
563        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
564        mCaches.fboCache.put(current->fbo);
565    }
566
567    dirtyClip();
568
569    // Failing to add the layer to the cache should happen only if the layer is too large
570    if (!mCaches.layerCache.put(layer)) {
571        LAYER_LOGD("Deleting layer");
572        glDeleteTextures(1, &layer->texture);
573        delete layer;
574    }
575}
576
577void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
578    const Rect& texCoords = layer->texCoords;
579    resetDrawTextureTexCoords(texCoords.left, texCoords.top, texCoords.right, texCoords.bottom);
580
581    drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
582            layer->alpha / 255.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
583            &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, swap, swap);
584
585    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
586}
587
588void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
589#if RENDER_LAYERS_AS_REGIONS
590    if (layer->region.isRect()) {
591        composeLayerRect(layer, rect);
592        layer->region.clear();
593        return;
594    }
595
596    if (!layer->region.isEmpty()) {
597        size_t count;
598        const android::Rect* rects = layer->region.getArray(&count);
599
600        setupDraw();
601
602        ProgramDescription description;
603        description.hasTexture = true;
604
605        const float alpha = layer->alpha / 255.0f;
606        const bool setColor = description.setColor(alpha, alpha, alpha, alpha);
607        chooseBlending(layer->blend || layer->alpha < 255, layer->mode, description, false);
608
609        useProgram(mCaches.programCache.get(description));
610
611        // Texture
612        bindTexture(layer->texture);
613        glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
614
615        // Always premultiplied
616        if (setColor) {
617            mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha);
618        }
619
620        // Mesh
621        int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
622        glEnableVertexAttribArray(texCoordsSlot);
623
624        mModelView.loadIdentity();
625        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
626
627        const float texX = 1.0f / float(layer->width);
628        const float texY = 1.0f / float(layer->height);
629
630        TextureVertex* mesh = mCaches.getRegionMesh();
631        GLsizei numQuads = 0;
632
633        glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
634                gMeshStride, &mesh[0].position[0]);
635        glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE,
636                gMeshStride, &mesh[0].texture[0]);
637
638        for (size_t i = 0; i < count; i++) {
639            const android::Rect* r = &rects[i];
640
641            const float u1 = r->left * texX;
642            const float v1 = (rect.getHeight() - r->top) * texY;
643            const float u2 = r->right * texX;
644            const float v2 = (rect.getHeight() - r->bottom) * texY;
645
646            // TODO: Reject quads outside of the clip
647            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
648            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
649            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
650            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
651
652            numQuads++;
653
654            if (numQuads >= REGION_MESH_QUAD_COUNT) {
655                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
656                numQuads = 0;
657                mesh = mCaches.getRegionMesh();
658            }
659        }
660
661        if (numQuads > 0) {
662            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
663        }
664
665        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
666        glDisableVertexAttribArray(texCoordsSlot);
667
668#if DEBUG_LAYERS_AS_REGIONS
669        uint32_t colors[] = {
670                0x7fff0000, 0x7f00ff00,
671                0x7f0000ff, 0x7fff00ff,
672        };
673
674        int offset = 0;
675        int32_t top = rects[0].top;
676        int i = 0;
677
678        for (size_t i = 0; i < count; i++) {
679            if (top != rects[i].top) {
680                offset ^= 0x2;
681                top = rects[i].top;
682            }
683
684            Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
685            drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
686                    SkXfermode::kSrcOver_Mode);
687        }
688#endif
689
690        layer->region.clear();
691    }
692#else
693    composeLayerRect(layer, rect);
694#endif
695}
696
697void OpenGLRenderer::dirtyLayer(const float left, const float top,
698        const float right, const float bottom, const mat4 transform) {
699#if RENDER_LAYERS_AS_REGIONS
700    if ((mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region) {
701        Rect bounds(left, top, right, bottom);
702        transform.mapRect(bounds);
703        bounds.intersect(*mSnapshot->clipRect);
704        bounds.snapToPixelBoundaries();
705
706        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
707        if (!dirty.isEmpty()) {
708            mSnapshot->region->orSelf(dirty);
709        }
710    }
711#endif
712}
713
714void OpenGLRenderer::dirtyLayer(const float left, const float top,
715        const float right, const float bottom) {
716#if RENDER_LAYERS_AS_REGIONS
717    if ((mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region) {
718        Rect bounds(left, top, right, bottom);
719        bounds.intersect(*mSnapshot->clipRect);
720        bounds.snapToPixelBoundaries();
721
722        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
723        if (!dirty.isEmpty()) {
724            mSnapshot->region->orSelf(dirty);
725        }
726    }
727#endif
728}
729
730void OpenGLRenderer::setupDraw() {
731    clearLayerRegions();
732    if (mDirtyClip) {
733        setScissorFromClip();
734    }
735}
736
737void OpenGLRenderer::clearLayerRegions() {
738    if (mLayers.size() == 0 || mSnapshot->isIgnored()) return;
739
740    Rect clipRect(*mSnapshot->clipRect);
741    clipRect.snapToPixelBoundaries();
742
743    for (uint32_t i = 0; i < mLayers.size(); i++) {
744        Rect* bounds = mLayers.itemAt(i);
745        if (clipRect.intersects(*bounds)) {
746            // Clear the framebuffer where the layer will draw
747            glScissor(bounds->left, mSnapshot->height - bounds->bottom,
748                    bounds->getWidth(), bounds->getHeight());
749            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
750            glClear(GL_COLOR_BUFFER_BIT);
751
752            // Restore the clip
753            dirtyClip();
754        }
755
756        delete bounds;
757    }
758
759    mLayers.clear();
760}
761
762///////////////////////////////////////////////////////////////////////////////
763// Transforms
764///////////////////////////////////////////////////////////////////////////////
765
766void OpenGLRenderer::translate(float dx, float dy) {
767    mSnapshot->transform->translate(dx, dy, 0.0f);
768}
769
770void OpenGLRenderer::rotate(float degrees) {
771    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
772}
773
774void OpenGLRenderer::scale(float sx, float sy) {
775    mSnapshot->transform->scale(sx, sy, 1.0f);
776}
777
778void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
779    mSnapshot->transform->load(*matrix);
780}
781
782const float* OpenGLRenderer::getMatrix() const {
783    if (mSnapshot->fbo != 0) {
784        return &mSnapshot->transform->data[0];
785    }
786    return &mIdentity.data[0];
787}
788
789void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
790    mSnapshot->transform->copyTo(*matrix);
791}
792
793void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
794    SkMatrix transform;
795    mSnapshot->transform->copyTo(transform);
796    transform.preConcat(*matrix);
797    mSnapshot->transform->load(transform);
798}
799
800///////////////////////////////////////////////////////////////////////////////
801// Clipping
802///////////////////////////////////////////////////////////////////////////////
803
804void OpenGLRenderer::setScissorFromClip() {
805    Rect clip(*mSnapshot->clipRect);
806    clip.snapToPixelBoundaries();
807    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
808    mDirtyClip = false;
809}
810
811const Rect& OpenGLRenderer::getClipBounds() {
812    return mSnapshot->getLocalClip();
813}
814
815bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
816    if (mSnapshot->isIgnored()) {
817        return true;
818    }
819
820    Rect r(left, top, right, bottom);
821    mSnapshot->transform->mapRect(r);
822    r.snapToPixelBoundaries();
823
824    Rect clipRect(*mSnapshot->clipRect);
825    clipRect.snapToPixelBoundaries();
826
827    return !clipRect.intersects(r);
828}
829
830bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
831    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
832    if (clipped) {
833        dirtyClip();
834    }
835    return !mSnapshot->clipRect->isEmpty();
836}
837
838///////////////////////////////////////////////////////////////////////////////
839// Drawing
840///////////////////////////////////////////////////////////////////////////////
841
842void OpenGLRenderer::drawDisplayList(DisplayList* displayList) {
843    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
844    // will be performed by the display list itself
845    if (displayList) {
846        displayList->replay(*this);
847    }
848}
849
850void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
851    const float right = left + bitmap->width();
852    const float bottom = top + bitmap->height();
853
854    if (quickReject(left, top, right, bottom)) {
855        return;
856    }
857
858    glActiveTexture(GL_TEXTURE0);
859    Texture* texture = mCaches.textureCache.get(bitmap);
860    if (!texture) return;
861    const AutoTexture autoCleanup(texture);
862
863    drawTextureRect(left, top, right, bottom, texture, paint);
864}
865
866void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
867    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
868    const mat4 transform(*matrix);
869    transform.mapRect(r);
870
871    if (quickReject(r.left, r.top, r.right, r.bottom)) {
872        return;
873    }
874
875    glActiveTexture(GL_TEXTURE0);
876    Texture* texture = mCaches.textureCache.get(bitmap);
877    if (!texture) return;
878    const AutoTexture autoCleanup(texture);
879
880    // This could be done in a cheaper way, all we need is pass the matrix
881    // to the vertex shader. The save/restore is a bit overkill.
882    save(SkCanvas::kMatrix_SaveFlag);
883    concatMatrix(matrix);
884    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
885    restore();
886}
887
888void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
889         float srcLeft, float srcTop, float srcRight, float srcBottom,
890         float dstLeft, float dstTop, float dstRight, float dstBottom,
891         SkPaint* paint) {
892    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
893        return;
894    }
895
896    glActiveTexture(gTextureUnits[0]);
897    Texture* texture = mCaches.textureCache.get(bitmap);
898    if (!texture) return;
899    const AutoTexture autoCleanup(texture);
900    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
901
902    const float width = texture->width;
903    const float height = texture->height;
904
905    const float u1 = srcLeft / width;
906    const float v1 = srcTop / height;
907    const float u2 = srcRight / width;
908    const float v2 = srcBottom / height;
909
910    mCaches.unbindMeshBuffer();
911    resetDrawTextureTexCoords(u1, v1, u2, v2);
912
913    int alpha;
914    SkXfermode::Mode mode;
915    getAlphaAndMode(paint, &alpha, &mode);
916
917    if (mSnapshot->transform->isPureTranslate()) {
918        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
919        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
920
921        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
922                texture->id, alpha / 255.0f, mode, texture->blend,
923                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
924                GL_TRIANGLE_STRIP, gMeshCount, false, true);
925    } else {
926        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
927                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
928                GL_TRIANGLE_STRIP, gMeshCount);
929    }
930
931    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
932}
933
934void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
935        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
936        float left, float top, float right, float bottom, SkPaint* paint) {
937    if (quickReject(left, top, right, bottom)) {
938        return;
939    }
940
941    glActiveTexture(gTextureUnits[0]);
942    Texture* texture = mCaches.textureCache.get(bitmap);
943    if (!texture) return;
944    const AutoTexture autoCleanup(texture);
945    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
946
947    int alpha;
948    SkXfermode::Mode mode;
949    getAlphaAndMode(paint, &alpha, &mode);
950
951    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
952            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
953
954    if (mesh && mesh->verticesCount > 0) {
955        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
956#if RENDER_LAYERS_AS_REGIONS
957        // Mark the current layer dirty where we are going to draw the patch
958        if ((mSnapshot->flags & Snapshot::kFlagFboTarget) &&
959                mSnapshot->region && mesh->hasEmptyQuads) {
960            const size_t count = mesh->quads.size();
961            for (size_t i = 0; i < count; i++) {
962                const Rect& bounds = mesh->quads.itemAt(i);
963                if (pureTranslate) {
964                    const float x = (int) floorf(bounds.left + 0.5f);
965                    const float y = (int) floorf(bounds.top + 0.5f);
966                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
967                            *mSnapshot->transform);
968                } else {
969                    dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom,
970                            *mSnapshot->transform);
971                }
972            }
973        }
974#endif
975
976        if (pureTranslate) {
977            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
978            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
979
980            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
981                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
982                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
983                    true, !mesh->hasEmptyQuads);
984        } else {
985            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
986                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
987                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
988                    true, !mesh->hasEmptyQuads);
989        }
990    }
991}
992
993void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
994    // TODO: Should do quickReject for each line
995    if (mSnapshot->isIgnored()) return;
996
997    const bool isAA = paint->isAntiAlias();
998    const float strokeWidth = paint->getStrokeWidth() * 0.5f;
999    // A stroke width of 0 has a special meaningin Skia:
1000    // it draws an unscaled 1px wide line
1001    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
1002
1003    setupDraw();
1004
1005    int alpha;
1006    SkXfermode::Mode mode;
1007    getAlphaAndMode(paint, &alpha, &mode);
1008
1009    uint32_t color = paint->getColor();
1010    const GLfloat a = alpha / 255.0f;
1011    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
1012    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
1013    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
1014
1015    // Used only with AA lines
1016    GLuint textureUnit = 0;
1017
1018    // Describe the required shaders
1019    ProgramDescription description;
1020    const bool setColor = description.setColor(r, g, b, a);
1021
1022    if (mShader) {
1023        mShader->describe(description, mCaches.extensions);
1024    }
1025    if (mColorFilter) {
1026        mColorFilter->describe(description, mCaches.extensions);
1027    }
1028
1029    // Setup the blending mode
1030    chooseBlending(a < 1.0f || (mShader && mShader->blend()), mode, description);
1031
1032    // We're not drawing with VBOs here
1033    mCaches.unbindMeshBuffer();
1034
1035    int verticesCount = count >> 2;
1036    if (!isHairLine) {
1037        // TODO: AA needs more vertices
1038        verticesCount *= 6;
1039    } else {
1040        // TODO: AA will be different
1041        verticesCount *= 2;
1042    }
1043
1044    TextureVertex lines[verticesCount];
1045    TextureVertex* vertex = &lines[0];
1046
1047    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1048            gMeshStride, vertex);
1049
1050    mModelView.loadIdentity();
1051
1052    // Build and use the appropriate shader
1053    useProgram(mCaches.programCache.get(description));
1054    mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1055
1056    if (!mShader || (mShader && setColor)) {
1057        mCaches.currentProgram->setColor(r, g, b, a);
1058    }
1059
1060    if (mShader) {
1061        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1062    }
1063    if (mColorFilter) {
1064        mColorFilter->setupProgram(mCaches.currentProgram);
1065    }
1066
1067    if (!isHairLine) {
1068        // TODO: Handle the AA case
1069        for (int i = 0; i < count; i += 4) {
1070            // a = start point, b = end point
1071            vec2 a(points[i], points[i + 1]);
1072            vec2 b(points[i + 2], points[i + 3]);
1073
1074            // Bias to snap to the same pixels as Skia
1075            a += 0.375;
1076            b += 0.375;
1077
1078            // Find the normal to the line
1079            vec2 n = (b - a).copyNormalized() * strokeWidth;
1080            float x = n.x;
1081            n.x = -n.y;
1082            n.y = x;
1083
1084            // Four corners of the rectangle defining a thick line
1085            vec2 p1 = a - n;
1086            vec2 p2 = a + n;
1087            vec2 p3 = b + n;
1088            vec2 p4 = b - n;
1089
1090            // Draw the line as 2 triangles, could be optimized
1091            // by using only 4 vertices and the correct indices
1092            // Also we should probably used non textured vertices
1093            // when line AA is disabled to save on bandwidth
1094            TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
1095            TextureVertex::set(vertex++, p2.x, p2.y, 0.0f, 0.0f);
1096            TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
1097            TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
1098            TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
1099            TextureVertex::set(vertex++, p4.x, p4.y, 0.0f, 0.0f);
1100
1101            // TODO: Mark the dirty regions when RENDER_LAYERS_AS_REGIONS is set
1102        }
1103
1104        // GL_LINE does not give the result we want to match Skia
1105        glDrawArrays(GL_TRIANGLES, 0, verticesCount);
1106    } else {
1107        // TODO: Handle the AA case
1108        for (int i = 0; i < count; i += 4) {
1109            TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
1110            TextureVertex::set(vertex++, points[i + 2], points[i + 3], 0.0f, 0.0f);
1111        }
1112        glLineWidth(1.0f);
1113        glDrawArrays(GL_LINES, 0, verticesCount);
1114    }
1115}
1116
1117void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1118    // No need to check against the clip, we fill the clip region
1119    if (mSnapshot->isIgnored()) return;
1120
1121    Rect& clip(*mSnapshot->clipRect);
1122    clip.snapToPixelBoundaries();
1123    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
1124}
1125
1126void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
1127    if (quickReject(left, top, right, bottom)) {
1128        return;
1129    }
1130
1131    SkXfermode::Mode mode;
1132    if (!mCaches.extensions.hasFramebufferFetch()) {
1133        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
1134        if (!isMode) {
1135            // Assume SRC_OVER
1136            mode = SkXfermode::kSrcOver_Mode;
1137        }
1138    } else {
1139        mode = getXfermode(p->getXfermode());
1140    }
1141
1142    // Skia draws using the color's alpha channel if < 255
1143    // Otherwise, it uses the paint's alpha
1144    int color = p->getColor();
1145    if (((color >> 24) & 0xff) == 255) {
1146        color |= p->getAlpha() << 24;
1147    }
1148
1149    drawColorRect(left, top, right, bottom, color, mode);
1150}
1151
1152void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
1153        float x, float y, SkPaint* paint) {
1154    if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
1155        return;
1156    }
1157    if (mSnapshot->isIgnored()) return;
1158
1159    paint->setAntiAlias(true);
1160
1161    float length = -1.0f;
1162    switch (paint->getTextAlign()) {
1163        case SkPaint::kCenter_Align:
1164            length = paint->measureText(text, bytesCount);
1165            x -= length / 2.0f;
1166            break;
1167        case SkPaint::kRight_Align:
1168            length = paint->measureText(text, bytesCount);
1169            x -= length;
1170            break;
1171        default:
1172            break;
1173    }
1174
1175    // TODO: Handle paint->getTextScaleX()
1176    const float oldX = x;
1177    const float oldY = y;
1178    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1179    if (pureTranslate) {
1180        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
1181        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
1182    }
1183
1184    int alpha;
1185    SkXfermode::Mode mode;
1186    getAlphaAndMode(paint, &alpha, &mode);
1187
1188    uint32_t color = paint->getColor();
1189    const GLfloat a = alpha / 255.0f;
1190    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
1191    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
1192    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
1193
1194    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
1195    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
1196            paint->getTextSize());
1197
1198    setupDraw();
1199
1200    if (mHasShadow) {
1201        glActiveTexture(gTextureUnits[0]);
1202        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
1203        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
1204                count, mShadowRadius);
1205        const AutoTexture autoCleanup(shadow);
1206
1207        setupShadow(shadow, x, y, mode, a, pureTranslate);
1208
1209        // Draw the mesh
1210        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1211        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
1212    }
1213
1214    GLuint textureUnit = 0;
1215    glActiveTexture(gTextureUnits[textureUnit]);
1216
1217    // Pick the appropriate texture filtering
1218    bool linearFilter = mSnapshot->transform->changesBounds();
1219    if (pureTranslate && !linearFilter) {
1220        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
1221    }
1222
1223    // Dimensions are set to (0,0), the layer (if any) won't be dirtied
1224    setupTextureAlpha8(fontRenderer.getTexture(linearFilter), 0, 0, textureUnit,
1225            x, y, r, g, b, a, mode, false, true, NULL, NULL, 0, pureTranslate);
1226
1227    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
1228    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
1229
1230#if RENDER_LAYERS_AS_REGIONS
1231    bool hasLayer = (mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region;
1232#else
1233    bool hasLayer = false;
1234#endif
1235
1236    mCaches.unbindMeshBuffer();
1237    if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y,
1238            hasLayer ? &bounds : NULL)) {
1239#if RENDER_LAYERS_AS_REGIONS
1240        if (hasLayer) {
1241            if (!pureTranslate) {
1242                mSnapshot->transform->mapRect(bounds);
1243            }
1244            bounds.intersect(*mSnapshot->clipRect);
1245            bounds.snapToPixelBoundaries();
1246
1247            android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1248            mSnapshot->region->orSelf(dirty);
1249        }
1250#endif
1251    }
1252
1253    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1254    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
1255
1256    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
1257}
1258
1259void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
1260    if (mSnapshot->isIgnored()) return;
1261
1262    GLuint textureUnit = 0;
1263    glActiveTexture(gTextureUnits[textureUnit]);
1264
1265    const PathTexture* texture = mCaches.pathCache.get(path, paint);
1266    if (!texture) return;
1267    const AutoTexture autoCleanup(texture);
1268
1269    const float x = texture->left - texture->offset;
1270    const float y = texture->top - texture->offset;
1271
1272    if (quickReject(x, y, x + texture->width, y + texture->height)) {
1273        return;
1274    }
1275
1276    int alpha;
1277    SkXfermode::Mode mode;
1278    getAlphaAndMode(paint, &alpha, &mode);
1279
1280    uint32_t color = paint->getColor();
1281    const GLfloat a = alpha / 255.0f;
1282    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
1283    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
1284    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
1285
1286    setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true);
1287
1288    setupDraw();
1289
1290    // Draw the mesh
1291    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1292    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
1293}
1294
1295///////////////////////////////////////////////////////////////////////////////
1296// Shaders
1297///////////////////////////////////////////////////////////////////////////////
1298
1299void OpenGLRenderer::resetShader() {
1300    mShader = NULL;
1301}
1302
1303void OpenGLRenderer::setupShader(SkiaShader* shader) {
1304    mShader = shader;
1305    if (mShader) {
1306        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
1307    }
1308}
1309
1310///////////////////////////////////////////////////////////////////////////////
1311// Color filters
1312///////////////////////////////////////////////////////////////////////////////
1313
1314void OpenGLRenderer::resetColorFilter() {
1315    mColorFilter = NULL;
1316}
1317
1318void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
1319    mColorFilter = filter;
1320}
1321
1322///////////////////////////////////////////////////////////////////////////////
1323// Drop shadow
1324///////////////////////////////////////////////////////////////////////////////
1325
1326void OpenGLRenderer::resetShadow() {
1327    mHasShadow = false;
1328}
1329
1330void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
1331    mHasShadow = true;
1332    mShadowRadius = radius;
1333    mShadowDx = dx;
1334    mShadowDy = dy;
1335    mShadowColor = color;
1336}
1337
1338///////////////////////////////////////////////////////////////////////////////
1339// Drawing implementation
1340///////////////////////////////////////////////////////////////////////////////
1341
1342void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y,
1343        SkXfermode::Mode mode, float alpha, bool ignoreTransforms) {
1344    const float sx = x - texture->left + mShadowDx;
1345    const float sy = y - texture->top + mShadowDy;
1346
1347    const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
1348    const GLfloat a = shadowAlpha < 255 ? shadowAlpha / 255.0f : alpha;
1349    const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f;
1350    const GLfloat g = a * ((mShadowColor >>  8) & 0xFF) / 255.0f;
1351    const GLfloat b = a * ((mShadowColor      ) & 0xFF) / 255.0f;
1352
1353    GLuint textureUnit = 0;
1354    setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit,
1355            sx, sy, r, g, b, a, mode, true, false,
1356            (GLvoid*) 0, (GLvoid*) gMeshTextureOffset, 0, ignoreTransforms);
1357}
1358
1359void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit,
1360        float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode,
1361        bool transforms, bool applyFilters) {
1362    setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit,
1363            x, y, r, g, b, a, mode, transforms, applyFilters,
1364            (GLvoid*) 0, (GLvoid*) gMeshTextureOffset);
1365}
1366
1367void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
1368        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
1369        SkXfermode::Mode mode, bool transforms, bool applyFilters) {
1370    setupTextureAlpha8(texture, width, height, textureUnit, x, y, r, g, b, a, mode,
1371            transforms, applyFilters, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset);
1372}
1373
1374void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
1375        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
1376        SkXfermode::Mode mode, bool transforms, bool applyFilters,
1377        GLvoid* vertices, GLvoid* texCoords, GLuint vbo, bool ignoreTransform) {
1378     // Describe the required shaders
1379     ProgramDescription description;
1380     description.hasTexture = true;
1381     description.hasAlpha8Texture = true;
1382     const bool setColor = description.setAlpha8Color(r, g, b, a);
1383
1384     if (applyFilters) {
1385         if (mShader) {
1386             mShader->describe(description, mCaches.extensions);
1387         }
1388         if (mColorFilter) {
1389             mColorFilter->describe(description, mCaches.extensions);
1390         }
1391     }
1392
1393     // Setup the blending mode
1394     chooseBlending(true, mode, description);
1395
1396     // Build and use the appropriate shader
1397     useProgram(mCaches.programCache.get(description));
1398
1399     bindTexture(texture);
1400     glUniform1i(mCaches.currentProgram->getUniform("sampler"), textureUnit);
1401
1402     int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1403     glEnableVertexAttribArray(texCoordsSlot);
1404
1405     if (texCoords) {
1406         // Setup attributes
1407         if (!vertices) {
1408             mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1409         } else {
1410             mCaches.unbindMeshBuffer();
1411         }
1412         glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1413                 gMeshStride, vertices);
1414         glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1415     }
1416
1417     // Setup uniforms
1418     if (transforms) {
1419         mModelView.loadTranslate(x, y, 0.0f);
1420         mModelView.scale(width, height, 1.0f);
1421     } else {
1422         mModelView.loadIdentity();
1423     }
1424
1425     mat4 t;
1426     if (!ignoreTransform) {
1427         t.load(*mSnapshot->transform);
1428     }
1429
1430     mCaches.currentProgram->set(mOrthoMatrix, mModelView, t);
1431     if (width > 0 && height > 0) {
1432         dirtyLayer(x, y, x + width, y + height, t);
1433     }
1434
1435     if (setColor) {
1436         mCaches.currentProgram->setColor(r, g, b, a);
1437     }
1438
1439     textureUnit++;
1440     if (applyFilters) {
1441         // Setup attributes and uniforms required by the shaders
1442         if (mShader) {
1443             if (ignoreTransform) {
1444                 mModelView.loadInverse(*mSnapshot->transform);
1445             }
1446             mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1447         }
1448         if (mColorFilter) {
1449             mColorFilter->setupProgram(mCaches.currentProgram);
1450         }
1451     }
1452}
1453
1454// Same values used by Skia
1455#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
1456#define kStdUnderline_Offset    (1.0f / 9.0f)
1457#define kStdUnderline_Thickness (1.0f / 18.0f)
1458
1459void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
1460        float x, float y, SkPaint* paint) {
1461    // Handle underline and strike-through
1462    uint32_t flags = paint->getFlags();
1463    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
1464        float underlineWidth = length;
1465        // If length is > 0.0f, we already measured the text for the text alignment
1466        if (length <= 0.0f) {
1467            underlineWidth = paint->measureText(text, bytesCount);
1468        }
1469
1470        float offsetX = 0;
1471        switch (paint->getTextAlign()) {
1472            case SkPaint::kCenter_Align:
1473                offsetX = underlineWidth * 0.5f;
1474                break;
1475            case SkPaint::kRight_Align:
1476                offsetX = underlineWidth;
1477                break;
1478            default:
1479                break;
1480        }
1481
1482        if (underlineWidth > 0.0f) {
1483            const float textSize = paint->getTextSize();
1484            const float strokeWidth = textSize * kStdUnderline_Thickness;
1485
1486            const float left = x - offsetX;
1487            float top = 0.0f;
1488
1489            const int pointsCount = 4 * (flags & SkPaint::kStrikeThruText_Flag ? 2 : 1);
1490            float points[pointsCount];
1491            int currentPoint = 0;
1492
1493            if (flags & SkPaint::kUnderlineText_Flag) {
1494                top = y + textSize * kStdUnderline_Offset;
1495                points[currentPoint++] = left;
1496                points[currentPoint++] = top;
1497                points[currentPoint++] = left + underlineWidth;
1498                points[currentPoint++] = top;
1499            }
1500
1501            if (flags & SkPaint::kStrikeThruText_Flag) {
1502                top = y + textSize * kStdStrikeThru_Offset;
1503                points[currentPoint++] = left;
1504                points[currentPoint++] = top;
1505                points[currentPoint++] = left + underlineWidth;
1506                points[currentPoint++] = top;
1507            }
1508
1509            SkPaint linesPaint(*paint);
1510            linesPaint.setStrokeWidth(strokeWidth);
1511
1512            drawLines(&points[0], pointsCount, &linesPaint);
1513        }
1514    }
1515}
1516
1517void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
1518        int color, SkXfermode::Mode mode, bool ignoreTransform) {
1519    setupDraw();
1520
1521    // If a shader is set, preserve only the alpha
1522    if (mShader) {
1523        color |= 0x00ffffff;
1524    }
1525
1526    // Render using pre-multiplied alpha
1527    const int alpha = (color >> 24) & 0xFF;
1528    const GLfloat a = alpha / 255.0f;
1529    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
1530    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
1531    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
1532
1533    setupColorRect(left, top, right, bottom, r, g, b, a, mode, ignoreTransform);
1534
1535    // Draw the mesh
1536    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1537}
1538
1539void OpenGLRenderer::setupColorRect(float left, float top, float right, float bottom,
1540        float r, float g, float b, float a, SkXfermode::Mode mode,
1541        bool ignoreTransform, bool ignoreMatrix) {
1542    GLuint textureUnit = 0;
1543
1544    // Describe the required shaders
1545    ProgramDescription description;
1546    const bool setColor = description.setColor(r, g, b, a);
1547
1548    if (mShader) {
1549        mShader->describe(description, mCaches.extensions);
1550    }
1551    if (mColorFilter) {
1552        mColorFilter->describe(description, mCaches.extensions);
1553    }
1554
1555    // Setup the blending mode
1556    chooseBlending(a < 1.0f || (mShader && mShader->blend()), mode, description);
1557
1558    // Build and use the appropriate shader
1559    useProgram(mCaches.programCache.get(description));
1560
1561    // Setup attributes
1562    mCaches.bindMeshBuffer();
1563    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1564            gMeshStride, 0);
1565
1566    if (!ignoreMatrix) {
1567        // Setup uniforms
1568        mModelView.loadTranslate(left, top, 0.0f);
1569        mModelView.scale(right - left, bottom - top, 1.0f);
1570        if (!ignoreTransform) {
1571            mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1572            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1573        } else {
1574            mat4 identity;
1575            mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity);
1576            dirtyLayer(left, top, right, bottom);
1577        }
1578    }
1579    if (!mShader || (mShader && setColor)) {
1580        mCaches.currentProgram->setColor(r, g, b, a);
1581    }
1582
1583    // Setup attributes and uniforms required by the shaders
1584    if (mShader) {
1585        if (ignoreMatrix) {
1586            mModelView.loadIdentity();
1587        } else if (ignoreTransform) {
1588            mModelView.loadInverse(*mSnapshot->transform);
1589        }
1590        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1591    }
1592    if (mColorFilter) {
1593        mColorFilter->setupProgram(mCaches.currentProgram);
1594    }
1595}
1596
1597void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1598        Texture* texture, SkPaint* paint) {
1599    int alpha;
1600    SkXfermode::Mode mode;
1601    getAlphaAndMode(paint, &alpha, &mode);
1602
1603    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1604
1605    if (mSnapshot->transform->isPureTranslate()) {
1606        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1607        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1608
1609        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
1610                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
1611                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
1612    } else {
1613        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
1614                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
1615                GL_TRIANGLE_STRIP, gMeshCount);
1616    }
1617}
1618
1619void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1620        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
1621    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
1622            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
1623}
1624
1625void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
1626        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
1627        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
1628        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
1629    setupDraw();
1630
1631    ProgramDescription description;
1632    description.hasTexture = true;
1633    const bool setColor = description.setColor(alpha, alpha, alpha, alpha);
1634    if (mColorFilter) {
1635        mColorFilter->describe(description, mCaches.extensions);
1636    }
1637
1638    mModelView.loadTranslate(left, top, 0.0f);
1639    if (!ignoreScale) {
1640        mModelView.scale(right - left, bottom - top, 1.0f);
1641    }
1642
1643    chooseBlending(blend || alpha < 1.0f, mode, description, swapSrcDst);
1644
1645    useProgram(mCaches.programCache.get(description));
1646    if (!ignoreTransform) {
1647        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1648        if (dirty) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1649    } else {
1650        mat4 identity;
1651        mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity);
1652        if (dirty) dirtyLayer(left, top, right, bottom);
1653    }
1654
1655    // Texture
1656    bindTexture(texture);
1657    glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
1658
1659    // Always premultiplied
1660    if (setColor) {
1661        mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha);
1662    }
1663
1664    // Mesh
1665    int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1666    glEnableVertexAttribArray(texCoordsSlot);
1667
1668    if (!vertices) {
1669        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1670    } else {
1671        mCaches.unbindMeshBuffer();
1672    }
1673    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1674            gMeshStride, vertices);
1675    glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1676
1677    // Color filter
1678    if (mColorFilter) {
1679        mColorFilter->setupProgram(mCaches.currentProgram);
1680    }
1681
1682    glDrawArrays(drawMode, 0, elementsCount);
1683    glDisableVertexAttribArray(texCoordsSlot);
1684}
1685
1686void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
1687        ProgramDescription& description, bool swapSrcDst) {
1688    blend = blend || mode != SkXfermode::kSrcOver_Mode;
1689    if (blend) {
1690        if (mode < SkXfermode::kPlus_Mode) {
1691            if (!mCaches.blend) {
1692                glEnable(GL_BLEND);
1693            }
1694
1695            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
1696            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
1697
1698            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
1699                glBlendFunc(sourceMode, destMode);
1700                mCaches.lastSrcMode = sourceMode;
1701                mCaches.lastDstMode = destMode;
1702            }
1703        } else {
1704            // These blend modes are not supported by OpenGL directly and have
1705            // to be implemented using shaders. Since the shader will perform
1706            // the blending, turn blending off here
1707            if (mCaches.extensions.hasFramebufferFetch()) {
1708                description.framebufferMode = mode;
1709                description.swapSrcDst = swapSrcDst;
1710            }
1711
1712            if (mCaches.blend) {
1713                glDisable(GL_BLEND);
1714            }
1715            blend = false;
1716        }
1717    } else if (mCaches.blend) {
1718        glDisable(GL_BLEND);
1719    }
1720    mCaches.blend = blend;
1721}
1722
1723bool OpenGLRenderer::useProgram(Program* program) {
1724    if (!program->isInUse()) {
1725        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1726        program->use();
1727        mCaches.currentProgram = program;
1728        return false;
1729    }
1730    return true;
1731}
1732
1733void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1734    TextureVertex* v = &mMeshVertices[0];
1735    TextureVertex::setUV(v++, u1, v1);
1736    TextureVertex::setUV(v++, u2, v1);
1737    TextureVertex::setUV(v++, u1, v2);
1738    TextureVertex::setUV(v++, u2, v2);
1739}
1740
1741void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1742    if (paint) {
1743        if (!mCaches.extensions.hasFramebufferFetch()) {
1744            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1745            if (!isMode) {
1746                // Assume SRC_OVER
1747                *mode = SkXfermode::kSrcOver_Mode;
1748            }
1749        } else {
1750            *mode = getXfermode(paint->getXfermode());
1751        }
1752
1753        // Skia draws using the color's alpha channel if < 255
1754        // Otherwise, it uses the paint's alpha
1755        int color = paint->getColor();
1756        *alpha = (color >> 24) & 0xFF;
1757        if (*alpha == 255) {
1758            *alpha = paint->getAlpha();
1759        }
1760    } else {
1761        *mode = SkXfermode::kSrcOver_Mode;
1762        *alpha = 255;
1763    }
1764}
1765
1766SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1767    if (mode == NULL) {
1768        return SkXfermode::kSrcOver_Mode;
1769    }
1770    return mode->fMode;
1771}
1772
1773void OpenGLRenderer::setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT) {
1774    bool bound = false;
1775    if (wrapS != texture->wrapS) {
1776        glBindTexture(GL_TEXTURE_2D, texture->id);
1777        bound = true;
1778        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1779        texture->wrapS = wrapS;
1780    }
1781    if (wrapT != texture->wrapT) {
1782        if (!bound) {
1783            glBindTexture(GL_TEXTURE_2D, texture->id);
1784        }
1785        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1786        texture->wrapT = wrapT;
1787    }
1788}
1789
1790}; // namespace uirenderer
1791}; // namespace android
1792