OpenGLRenderer.cpp revision c0ac193b9415680f0a69e20a3f5f22d16f8053be
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
25#include <cutils/properties.h>
26#include <utils/Log.h>
27
28#include "OpenGLRenderer.h"
29
30namespace android {
31namespace uirenderer {
32
33///////////////////////////////////////////////////////////////////////////////
34// Defines
35///////////////////////////////////////////////////////////////////////////////
36
37// These properties are defined in mega-bytes
38#define PROPERTY_TEXTURE_CACHE_SIZE "ro.hwui.texture_cache_size"
39#define PROPERTY_LAYER_CACHE_SIZE "ro.hwui.layer_cache_size"
40#define PROPERTY_GRADIENT_CACHE_SIZE "ro.hwui.gradient_cache_size"
41
42#define DEFAULT_TEXTURE_CACHE_SIZE 20.0f
43#define DEFAULT_LAYER_CACHE_SIZE 10.0f
44#define DEFAULT_PATCH_CACHE_SIZE 100
45#define DEFAULT_GRADIENT_CACHE_SIZE 0.5f
46
47// Converts a number of mega-bytes into bytes
48#define MB(s) s * 1024 * 1024
49
50// Generates simple and textured vertices
51#define SV(x, y) { { x, y } }
52#define FV(x, y, u, v) { { x, y }, { u, v } }
53
54///////////////////////////////////////////////////////////////////////////////
55// Globals
56///////////////////////////////////////////////////////////////////////////////
57
58static const SimpleVertex gDrawColorVertices[] = {
59        SV(0.0f, 0.0f),
60        SV(1.0f, 0.0f),
61        SV(0.0f, 1.0f),
62        SV(1.0f, 1.0f)
63};
64static const GLsizei gDrawColorVertexStride = sizeof(SimpleVertex);
65static const GLsizei gDrawColorVertexCount = 4;
66
67// This array is never used directly but used as a memcpy source in the
68// OpenGLRenderer constructor
69static const TextureVertex gDrawTextureVertices[] = {
70        FV(0.0f, 0.0f, 0.0f, 0.0f),
71        FV(1.0f, 0.0f, 1.0f, 0.0f),
72        FV(0.0f, 1.0f, 0.0f, 1.0f),
73        FV(1.0f, 1.0f, 1.0f, 1.0f)
74};
75static const GLsizei gDrawTextureVertexStride = sizeof(TextureVertex);
76static const GLsizei gDrawTextureVertexCount = 4;
77
78// In this array, the index of each Blender equals the value of the first
79// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
80static const Blender gBlends[] = {
81        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
82        { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
83        { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
84        { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
85        { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
86        { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
87        { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
88        { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
89        { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
90        { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
91        { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
92        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
93};
94
95static const GLint gTileModes[] = {
96        GL_CLAMP_TO_EDGE,   // == SkShader::kClamp_TileMode
97        GL_REPEAT,          // == SkShader::kRepeat_Mode
98        GL_MIRRORED_REPEAT  // == SkShader::kMirror_TileMode
99};
100
101///////////////////////////////////////////////////////////////////////////////
102// Constructors/destructor
103///////////////////////////////////////////////////////////////////////////////
104
105OpenGLRenderer::OpenGLRenderer():
106        mBlend(false), mLastSrcMode(GL_ZERO), mLastDstMode(GL_ZERO),
107        mTextureCache(MB(DEFAULT_TEXTURE_CACHE_SIZE)),
108        mLayerCache(MB(DEFAULT_LAYER_CACHE_SIZE)),
109        mGradientCache(MB(DEFAULT_GRADIENT_CACHE_SIZE)),
110        mPatchCache(DEFAULT_PATCH_CACHE_SIZE) {
111    LOGD("Create OpenGLRenderer");
112
113    char property[PROPERTY_VALUE_MAX];
114    if (property_get(PROPERTY_TEXTURE_CACHE_SIZE, property, NULL) > 0) {
115        LOGD("  Setting texture cache size to %sMB", property);
116        mTextureCache.setMaxSize(MB(atof(property)));
117    } else {
118        LOGD("  Using default texture cache size of %.2fMB", DEFAULT_TEXTURE_CACHE_SIZE);
119    }
120
121    if (property_get(PROPERTY_LAYER_CACHE_SIZE, property, NULL) > 0) {
122        LOGD("  Setting layer cache size to %sMB", property);
123        mLayerCache.setMaxSize(MB(atof(property)));
124    } else {
125        LOGD("  Using default layer cache size of %.2fMB", DEFAULT_LAYER_CACHE_SIZE);
126    }
127
128    if (property_get(PROPERTY_GRADIENT_CACHE_SIZE, property, NULL) > 0) {
129        LOGD("  Setting gradient cache size to %sMB", property);
130        mLayerCache.setMaxSize(MB(atof(property)));
131    } else {
132        LOGD("  Using default gradient cache size of %.2fMB", DEFAULT_GRADIENT_CACHE_SIZE);
133    }
134
135    mDrawColorProgram = new DrawColorProgram;
136    mDrawTextureProgram = new DrawTextureProgram;
137    mDrawLinearGradientProgram = new DrawLinearGradientProgram;
138    mCurrentProgram = mDrawTextureProgram;
139
140    mShader = kShaderNone;
141    mShaderTileX = SkShader::kClamp_TileMode;
142    mShaderTileY = SkShader::kClamp_TileMode;
143    mShaderMatrix = NULL;
144    mShaderBitmap = NULL;
145
146    mLastTexture = 0;
147
148    memcpy(mDrawTextureVertices, gDrawTextureVertices, sizeof(gDrawTextureVertices));
149}
150
151OpenGLRenderer::~OpenGLRenderer() {
152    LOGD("Destroy OpenGLRenderer");
153
154    mTextureCache.clear();
155    mLayerCache.clear();
156    mGradientCache.clear();
157    mPatchCache.clear();
158}
159
160///////////////////////////////////////////////////////////////////////////////
161// Setup
162///////////////////////////////////////////////////////////////////////////////
163
164void OpenGLRenderer::setViewport(int width, int height) {
165    glViewport(0, 0, width, height);
166
167    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
168
169    mWidth = width;
170    mHeight = height;
171    mFirstSnapshot.height = height;
172}
173
174void OpenGLRenderer::prepare() {
175    mSnapshot = &mFirstSnapshot;
176    mSaveCount = 0;
177
178    glDisable(GL_SCISSOR_TEST);
179
180    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
181    glClear(GL_COLOR_BUFFER_BIT);
182
183    glEnable(GL_SCISSOR_TEST);
184    glScissor(0, 0, mWidth, mHeight);
185
186    mSnapshot->clipRect.set(0.0f, 0.0f, mWidth, mHeight);
187}
188
189///////////////////////////////////////////////////////////////////////////////
190// State management
191///////////////////////////////////////////////////////////////////////////////
192
193int OpenGLRenderer::getSaveCount() const {
194    return mSaveCount;
195}
196
197int OpenGLRenderer::save(int flags) {
198    return saveSnapshot();
199}
200
201void OpenGLRenderer::restore() {
202    if (mSaveCount == 0) return;
203
204    if (restoreSnapshot()) {
205        setScissorFromClip();
206    }
207}
208
209void OpenGLRenderer::restoreToCount(int saveCount) {
210    if (saveCount <= 0 || saveCount > mSaveCount) return;
211
212    bool restoreClip = false;
213
214    while (mSaveCount != saveCount - 1) {
215        restoreClip |= restoreSnapshot();
216    }
217
218    if (restoreClip) {
219        setScissorFromClip();
220    }
221}
222
223int OpenGLRenderer::saveSnapshot() {
224    mSnapshot = new Snapshot(mSnapshot);
225    return ++mSaveCount;
226}
227
228bool OpenGLRenderer::restoreSnapshot() {
229    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
230    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
231    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
232
233    sp<Snapshot> current = mSnapshot;
234    sp<Snapshot> previous = mSnapshot->previous;
235
236    if (restoreOrtho) {
237        mOrthoMatrix.load(current->orthoMatrix);
238    }
239
240    if (restoreLayer) {
241        composeLayer(current, previous);
242    }
243
244    mSnapshot = previous;
245    mSaveCount--;
246
247    return restoreClip;
248}
249
250void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
251    if (!current->layer) {
252        LOGE("Attempting to compose a layer that does not exist");
253        return;
254    }
255
256    // Unbind current FBO and restore previous one
257    // Most of the time, previous->fbo will be 0 to bind the default buffer
258    glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
259
260    // Restore the clip from the previous snapshot
261    const Rect& clip = previous->clipRect;
262    glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight());
263
264    Layer* layer = current->layer;
265
266    // Compute the correct texture coordinates for the FBO texture
267    // The texture is currently as big as the window but drawn with
268    // a quad of the appropriate size
269    const Rect& rect = layer->layer;
270
271    drawTextureRect(rect.left, rect.top, rect.right, rect.bottom,
272            layer->texture, layer->alpha, layer->mode, layer->blend);
273
274    LayerSize size(rect.getWidth(), rect.getHeight());
275    // Failing to add the layer to the cache should happen only if the
276    // layer is too large
277    if (!mLayerCache.put(size, layer)) {
278        LAYER_LOGD("Deleting layer");
279
280        glDeleteFramebuffers(1, &layer->fbo);
281        glDeleteTextures(1, &layer->texture);
282
283        delete layer;
284    }
285}
286
287///////////////////////////////////////////////////////////////////////////////
288// Layers
289///////////////////////////////////////////////////////////////////////////////
290
291int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
292        const SkPaint* p, int flags) {
293    int count = saveSnapshot();
294
295    int alpha = 255;
296    SkXfermode::Mode mode;
297
298    if (p) {
299        alpha = p->getAlpha();
300        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
301        if (!isMode) {
302            // Assume SRC_OVER
303            mode = SkXfermode::kSrcOver_Mode;
304        }
305    } else {
306        mode = SkXfermode::kSrcOver_Mode;
307    }
308
309    createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags);
310
311    return count;
312}
313
314int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
315        int alpha, int flags) {
316    int count = saveSnapshot();
317    createLayer(mSnapshot, left, top, right, bottom, alpha, SkXfermode::kSrcOver_Mode, flags);
318    return count;
319}
320
321bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
322        float right, float bottom, int alpha, SkXfermode::Mode mode,int flags) {
323
324    LAYER_LOGD("Requesting layer %fx%f", right - left, bottom - top);
325    LAYER_LOGD("Layer cache size = %d", mLayerCache.getSize());
326
327    GLuint previousFbo = snapshot->previous.get() ? snapshot->previous->fbo : 0;
328    LayerSize size(right - left, bottom - top);
329
330    Layer* layer = mLayerCache.get(size, previousFbo);
331    if (!layer) {
332        return false;
333    }
334
335    glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
336
337    // Clear the FBO
338    glDisable(GL_SCISSOR_TEST);
339    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
340    glClear(GL_COLOR_BUFFER_BIT);
341    glEnable(GL_SCISSOR_TEST);
342
343    // Save the layer in the snapshot
344    snapshot->flags |= Snapshot::kFlagIsLayer;
345    layer->mode = mode;
346    layer->alpha = alpha / 255.0f;
347    layer->layer.set(left, top, right, bottom);
348
349    snapshot->layer = layer;
350    snapshot->fbo = layer->fbo;
351
352    // Creates a new snapshot to draw into the FBO
353    saveSnapshot();
354    // TODO: This doesn't preserve other transformations (check Skia first)
355    mSnapshot->transform.loadTranslate(-left, -top, 0.0f);
356    mSnapshot->setClip(0.0f, 0.0f, right - left, bottom - top);
357    mSnapshot->height = bottom - top;
358    setScissorFromClip();
359
360    mSnapshot->flags = Snapshot::kFlagDirtyOrtho | Snapshot::kFlagClipSet;
361    mSnapshot->orthoMatrix.load(mOrthoMatrix);
362
363    // Change the ortho projection
364    mOrthoMatrix.loadOrtho(0.0f, right - left, bottom - top, 0.0f, 0.0f, 1.0f);
365
366    return true;
367}
368
369///////////////////////////////////////////////////////////////////////////////
370// Transforms
371///////////////////////////////////////////////////////////////////////////////
372
373void OpenGLRenderer::translate(float dx, float dy) {
374    mSnapshot->transform.translate(dx, dy, 0.0f);
375}
376
377void OpenGLRenderer::rotate(float degrees) {
378    mSnapshot->transform.rotate(degrees, 0.0f, 0.0f, 1.0f);
379}
380
381void OpenGLRenderer::scale(float sx, float sy) {
382    mSnapshot->transform.scale(sx, sy, 1.0f);
383}
384
385void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
386    mSnapshot->transform.load(*matrix);
387}
388
389void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
390    mSnapshot->transform.copyTo(*matrix);
391}
392
393void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
394    mat4 m(*matrix);
395    mSnapshot->transform.multiply(m);
396}
397
398///////////////////////////////////////////////////////////////////////////////
399// Clipping
400///////////////////////////////////////////////////////////////////////////////
401
402void OpenGLRenderer::setScissorFromClip() {
403    const Rect& clip = mSnapshot->clipRect;
404    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
405}
406
407const Rect& OpenGLRenderer::getClipBounds() {
408    return mSnapshot->getLocalClip();
409}
410
411bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
412    Rect r(left, top, right, bottom);
413    mSnapshot->transform.mapRect(r);
414    return !mSnapshot->clipRect.intersects(r);
415}
416
417bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
418    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
419    if (clipped) {
420        setScissorFromClip();
421    }
422    return !mSnapshot->clipRect.isEmpty();
423}
424
425///////////////////////////////////////////////////////////////////////////////
426// Drawing
427///////////////////////////////////////////////////////////////////////////////
428
429void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
430    const float right = left + bitmap->width();
431    const float bottom = top + bitmap->height();
432
433    if (quickReject(left, top, right, bottom)) {
434        return;
435    }
436
437    const Texture* texture = mTextureCache.get(bitmap);
438    drawTextureRect(left, top, right, bottom, texture, paint);
439}
440
441void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) {
442    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
443    const mat4 transform(*matrix);
444    transform.mapRect(r);
445
446    if (quickReject(r.left, r.top, r.right, r.bottom)) {
447        return;
448    }
449
450    const Texture* texture = mTextureCache.get(bitmap);
451    drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint);
452}
453
454void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
455         float srcLeft, float srcTop, float srcRight, float srcBottom,
456         float dstLeft, float dstTop, float dstRight, float dstBottom,
457         const SkPaint* paint) {
458    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
459        return;
460    }
461
462    const Texture* texture = mTextureCache.get(bitmap);
463
464    const float width = texture->width;
465    const float height = texture->height;
466
467    const float u1 = srcLeft / width;
468    const float v1 = srcTop / height;
469    const float u2 = srcRight / width;
470    const float v2 = srcBottom / height;
471
472    resetDrawTextureTexCoords(u1, v1, u2, v2);
473
474    drawTextureRect(dstLeft, dstTop, dstRight, dstBottom, texture, paint);
475
476    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
477}
478
479void OpenGLRenderer::drawPatch(SkBitmap* bitmap, Res_png_9patch* patch,
480        float left, float top, float right, float bottom, const SkPaint* paint) {
481    if (quickReject(left, top, right, bottom)) {
482        return;
483    }
484
485    const Texture* texture = mTextureCache.get(bitmap);
486
487    int alpha;
488    SkXfermode::Mode mode;
489    getAlphaAndMode(paint, &alpha, &mode);
490
491    Patch* mesh = mPatchCache.get(patch);
492    mesh->updateVertices(bitmap, left, top, right, bottom,
493            &patch->xDivs[0], &patch->yDivs[0], patch->numXDivs, patch->numYDivs);
494
495    // Specify right and bottom as +1.0f from left/top to prevent scaling since the
496    // patch mesh already defines the final size
497    drawTextureMesh(left, top, left + 1.0f, top + 1.0f, texture->id, alpha / 255.0f,
498            mode, texture->blend, &mesh->vertices[0].position[0],
499            &mesh->vertices[0].texture[0], mesh->indices, mesh->indicesCount);
500}
501
502void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
503    const Rect& clip = mSnapshot->clipRect;
504    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
505}
506
507void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) {
508    if (quickReject(left, top, right, bottom)) {
509        return;
510    }
511
512    SkXfermode::Mode mode;
513
514    const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
515    if (!isMode) {
516        // Assume SRC_OVER
517        mode = SkXfermode::kSrcOver_Mode;
518    }
519
520    // Skia draws using the color's alpha channel if < 255
521    // Otherwise, it uses the paint's alpha
522    int color = p->getColor();
523    if (((color >> 24) & 0xff) == 255) {
524        color |= p->getAlpha() << 24;
525    }
526
527    drawColorRect(left, top, right, bottom, color, mode);
528}
529
530///////////////////////////////////////////////////////////////////////////////
531// Shaders
532///////////////////////////////////////////////////////////////////////////////
533
534void OpenGLRenderer::resetShader() {
535    mShader = OpenGLRenderer::kShaderNone;
536    mShaderKey = NULL;
537    mShaderBlend = false;
538    mShaderTileX = SkShader::kClamp_TileMode;
539    mShaderTileY = SkShader::kClamp_TileMode;
540}
541
542void OpenGLRenderer::setupBitmapShader(SkBitmap* bitmap, SkShader::TileMode tileX,
543        SkShader::TileMode tileY, SkMatrix* matrix, bool hasAlpha) {
544    mShader = OpenGLRenderer::kShaderBitmap;
545    mShaderBlend = hasAlpha;
546    mShaderBitmap = bitmap;
547    mShaderTileX = tileX;
548    mShaderTileY = tileY;
549    mShaderMatrix = matrix;
550}
551
552void OpenGLRenderer::setupLinearGradientShader(SkShader* shader, float* bounds, uint32_t* colors,
553        float* positions, int count, SkShader::TileMode tileMode, SkMatrix* matrix,
554        bool hasAlpha) {
555    // TODO: We should use a struct to describe each shader
556    mShader = OpenGLRenderer::kShaderLinearGradient;
557    mShaderKey = shader;
558    mShaderBlend = hasAlpha;
559    mShaderTileX = tileMode;
560    mShaderTileY = tileMode;
561    mShaderMatrix = matrix;
562    mShaderBounds = bounds;
563    mShaderColors = colors;
564    mShaderPositions = positions;
565    mShaderCount = count;
566}
567
568///////////////////////////////////////////////////////////////////////////////
569// Drawing implementation
570///////////////////////////////////////////////////////////////////////////////
571
572void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
573        int color, SkXfermode::Mode mode, bool ignoreTransform) {
574    // If a shader is set, preserve only the alpha
575    if (mShader != kShaderNone) {
576        color |= 0x00ffffff;
577    }
578
579    // Render using pre-multiplied alpha
580    const int alpha = (color >> 24) & 0xFF;
581    const GLfloat a = alpha / 255.0f;
582
583    switch (mShader) {
584        case OpenGLRenderer::kShaderBitmap:
585            drawBitmapShader(left, top, right, bottom, a, mode);
586            return;
587        case OpenGLRenderer::kShaderLinearGradient:
588            drawLinearGradientShader(left, top, right, bottom, a, mode);
589            return;
590        default:
591            break;
592    }
593
594    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
595    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
596    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
597
598    // Pre-multiplication happens when setting the shader color
599    chooseBlending(alpha < 255 || mShaderBlend, mode);
600
601    mModelView.loadTranslate(left, top, 0.0f);
602    mModelView.scale(right - left, bottom - top, 1.0f);
603
604    if (!useProgram(mDrawColorProgram)) {
605        const GLvoid* p = &gDrawColorVertices[0].position[0];
606        glVertexAttribPointer(mDrawColorProgram->position, 2, GL_FLOAT, GL_FALSE,
607                gDrawColorVertexStride, p);
608    }
609
610    if (!ignoreTransform) {
611        mDrawColorProgram->set(mOrthoMatrix, mModelView, mSnapshot->transform);
612    } else {
613        mat4 identity;
614        mDrawColorProgram->set(mOrthoMatrix, mModelView, identity);
615    }
616
617    glUniform4f(mDrawColorProgram->color, r, g, b, a);
618
619    glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawColorVertexCount);
620}
621
622void OpenGLRenderer::drawLinearGradientShader(float left, float top, float right, float bottom,
623        float alpha, SkXfermode::Mode mode) {
624    Texture* texture = mGradientCache.get(mShaderKey);
625    if (!texture) {
626        texture = mGradientCache.addLinearGradient(mShaderKey, mShaderBounds, mShaderColors,
627                mShaderPositions, mShaderCount, mShaderTileX);
628    }
629
630    mModelView.loadTranslate(left, top, 0.0f);
631    mModelView.scale(right - left, bottom - top, 1.0f);
632
633    useProgram(mDrawLinearGradientProgram);
634    mDrawLinearGradientProgram->set(mOrthoMatrix, mModelView, mSnapshot->transform);
635
636    chooseBlending(mShaderBlend || alpha < 1.0f, mode);
637
638    if (texture->id != mLastTexture) {
639        glBindTexture(GL_TEXTURE_2D, texture->id);
640        mLastTexture = texture->id;
641    }
642    // TODO: Don't set the texture parameters every time
643    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, gTileModes[mShaderTileX]);
644    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, gTileModes[mShaderTileX]);
645
646    Rect start(mShaderBounds[0], mShaderBounds[1], mShaderBounds[2], mShaderBounds[3]);
647    if (mShaderMatrix) {
648        mat4 shaderMatrix(*mShaderMatrix);
649        shaderMatrix.mapRect(start);
650    }
651    mSnapshot->transform.mapRect(start);
652
653    const float gradientX = start.right - start.left;
654    const float gradientY = start.bottom - start.top;
655
656    mat4 screenSpace(mSnapshot->transform);
657    screenSpace.multiply(mModelView);
658
659    // Always premultiplied
660    glUniform4f(mDrawLinearGradientProgram->color, alpha, alpha, alpha, alpha);
661    glUniform2f(mDrawLinearGradientProgram->start, start.left, start.top);
662    glUniform2f(mDrawLinearGradientProgram->gradient, gradientX, gradientY);
663    glUniform1f(mDrawLinearGradientProgram->gradientLength,
664            1.0f / (gradientX * gradientX + gradientY * gradientY));
665    glUniformMatrix4fv(mDrawLinearGradientProgram->screenSpace, 1, GL_FALSE,
666            &screenSpace.data[0]);
667
668    glVertexAttribPointer(mDrawLinearGradientProgram->position, 2, GL_FLOAT, GL_FALSE,
669            gDrawTextureVertexStride, &mDrawTextureVertices[0].position[0]);
670
671    glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawTextureVertexCount);
672}
673
674void OpenGLRenderer::drawBitmapShader(float left, float top, float right, float bottom,
675        float alpha, SkXfermode::Mode mode) {
676    const Texture* texture = mTextureCache.get(mShaderBitmap);
677
678    const float width = texture->width;
679    const float height = texture->height;
680
681    // This could be done in the vertex shader but we have only 4 vertices
682    float u1 = 0.0f;
683    float v1 = 0.0f;
684    float u2 = right - left;
685    float v2 = bottom - top;
686
687    if (mShaderMatrix) {
688        SkMatrix inverse;
689        mShaderMatrix->invert(&inverse);
690        mat4 m(inverse);
691        Rect r(u1, v1, u2, v2);
692        m.mapRect(r);
693
694        u1 = r.left;
695        u2 = r.right;
696        v1 = r.top;
697        v2 = r.bottom;
698    }
699
700    u1 /= width;
701    u2 /= width;
702    v1 /= height;
703    v2 /= height;
704
705    resetDrawTextureTexCoords(u1, v1, u2, v2);
706
707    drawTextureMesh(left, top, right, bottom, texture->id, alpha, mode, texture->blend,
708            &mDrawTextureVertices[0].position[0], &mDrawTextureVertices[0].texture[0], NULL);
709
710    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
711}
712
713void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
714        const Texture* texture, const SkPaint* paint) {
715    int alpha;
716    SkXfermode::Mode mode;
717    getAlphaAndMode(paint, &alpha, &mode);
718
719    drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, texture->blend,
720            &mDrawTextureVertices[0].position[0], &mDrawTextureVertices[0].texture[0], NULL);
721}
722
723void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
724        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
725    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
726            &mDrawTextureVertices[0].position[0], &mDrawTextureVertices[0].texture[0], NULL);
727}
728
729void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
730        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
731        GLvoid* vertices, GLvoid* texCoords, GLvoid* indices, GLsizei elementsCount) {
732    mModelView.loadTranslate(left, top, 0.0f);
733    mModelView.scale(right - left, bottom - top, 1.0f);
734
735    useProgram(mDrawTextureProgram);
736    mDrawTextureProgram->set(mOrthoMatrix, mModelView, mSnapshot->transform);
737
738    chooseBlending(blend || alpha < 1.0f, mode);
739
740    if (texture != mLastTexture) {
741        glBindTexture(GL_TEXTURE_2D, texture);
742        mLastTexture = texture;
743    }
744    // TODO: Don't set the texture parameters every time
745    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, gTileModes[mShaderTileX]);
746    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, gTileModes[mShaderTileY]);
747
748    // Always premultiplied
749    //glUniform4f(mDrawTextureProgram->color, alpha, alpha, alpha, alpha);
750    glUniform4f(mDrawTextureProgram->color, alpha, alpha, alpha, alpha);
751
752    glVertexAttribPointer(mDrawTextureProgram->position, 2, GL_FLOAT, GL_FALSE,
753            gDrawTextureVertexStride, vertices);
754    glVertexAttribPointer(mDrawTextureProgram->texCoords, 2, GL_FLOAT, GL_FALSE,
755            gDrawTextureVertexStride, texCoords);
756
757    if (!indices) {
758        glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawTextureVertexCount);
759    } else {
760        glDrawElements(GL_TRIANGLES, elementsCount, GL_UNSIGNED_SHORT, indices);
761    }
762}
763
764void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, bool isPremultiplied) {
765    // In theory we should not blend if the mode is Src, but it's rare enough
766    // that it's not worth it
767    blend = blend || mode != SkXfermode::kSrcOver_Mode;
768    if (blend) {
769        if (!mBlend) {
770            glEnable(GL_BLEND);
771        }
772
773        GLenum sourceMode = gBlends[mode].src;
774        GLenum destMode = gBlends[mode].dst;
775        if (!isPremultiplied && sourceMode == GL_ONE) {
776            sourceMode = GL_SRC_ALPHA;
777        }
778
779        if (sourceMode != mLastSrcMode || destMode != mLastDstMode) {
780            glBlendFunc(sourceMode, destMode);
781            mLastSrcMode = sourceMode;
782            mLastDstMode = destMode;
783        }
784    } else if (mBlend) {
785        glDisable(GL_BLEND);
786    }
787    mBlend = blend;
788}
789
790bool OpenGLRenderer::useProgram(const sp<Program>& program) {
791    if (!program->isInUse()) {
792        mCurrentProgram->remove();
793        program->use();
794        mCurrentProgram = program;
795        return false;
796    }
797    return true;
798}
799
800void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
801    TextureVertex* v = &mDrawTextureVertices[0];
802    TextureVertex::setUV(v++, u1, v1);
803    TextureVertex::setUV(v++, u2, v1);
804    TextureVertex::setUV(v++, u1, v2);
805    TextureVertex::setUV(v++, u2, v2);
806}
807
808void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
809    if (paint) {
810        const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
811        if (!isMode) {
812            // Assume SRC_OVER
813            *mode = SkXfermode::kSrcOver_Mode;
814        }
815
816        // Skia draws using the color's alpha channel if < 255
817        // Otherwise, it uses the paint's alpha
818        int color = paint->getColor();
819        *alpha = (color >> 24) & 0xFF;
820        if (*alpha == 255) {
821            *alpha = paint->getAlpha();
822        }
823    } else {
824        *mode = SkXfermode::kSrcOver_Mode;
825        *alpha = 255;
826    }
827}
828
829}; // namespace uirenderer
830}; // namespace android
831