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