OpenGLRenderer.cpp revision 8fb954263dd2f918ad339045cc6d82e346515599
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 6.0f
41#define DEFAULT_PATH_CACHE_SIZE 6.0f
42#define DEFAULT_PATCH_CACHE_SIZE 100
43#define DEFAULT_GRADIENT_CACHE_SIZE 0.5f
44#define DEFAULT_DROP_SHADOW_CACHE_SIZE 1.0f
45
46#define REQUIRED_TEXTURE_UNITS_COUNT 3
47
48// Converts a number of mega-bytes into bytes
49#define MB(s) s * 1024 * 1024
50
51// Generates simple and textured vertices
52#define FV(x, y, u, v) { { x, y }, { u, v } }
53
54///////////////////////////////////////////////////////////////////////////////
55// Globals
56///////////////////////////////////////////////////////////////////////////////
57
58// This array is never used directly but used as a memcpy source in the
59// OpenGLRenderer constructor
60static const TextureVertex gMeshVertices[] = {
61        FV(0.0f, 0.0f, 0.0f, 0.0f),
62        FV(1.0f, 0.0f, 1.0f, 0.0f),
63        FV(0.0f, 1.0f, 0.0f, 1.0f),
64        FV(1.0f, 1.0f, 1.0f, 1.0f)
65};
66static const GLsizei gMeshStride = sizeof(TextureVertex);
67static const GLsizei gMeshCount = 4;
68
69/**
70 * Structure mapping Skia xfermodes to OpenGL blending factors.
71 */
72struct Blender {
73    SkXfermode::Mode mode;
74    GLenum src;
75    GLenum dst;
76}; // struct Blender
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 GLenum gTextureUnits[] = {
96        GL_TEXTURE0,
97        GL_TEXTURE1,
98        GL_TEXTURE2
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        mPathCache(MB(DEFAULT_PATH_CACHE_SIZE)),
111        mPatchCache(DEFAULT_PATCH_CACHE_SIZE),
112        mDropShadowCache(MB(DEFAULT_DROP_SHADOW_CACHE_SIZE)) {
113    LOGD("Create OpenGLRenderer");
114
115    char property[PROPERTY_VALUE_MAX];
116    if (property_get(PROPERTY_TEXTURE_CACHE_SIZE, property, NULL) > 0) {
117        LOGD("  Setting texture cache size to %sMB", property);
118        mTextureCache.setMaxSize(MB(atof(property)));
119    } else {
120        LOGD("  Using default texture cache size of %.2fMB", DEFAULT_TEXTURE_CACHE_SIZE);
121    }
122
123    if (property_get(PROPERTY_LAYER_CACHE_SIZE, property, NULL) > 0) {
124        LOGD("  Setting layer cache size to %sMB", property);
125        mLayerCache.setMaxSize(MB(atof(property)));
126    } else {
127        LOGD("  Using default layer cache size of %.2fMB", DEFAULT_LAYER_CACHE_SIZE);
128    }
129
130    if (property_get(PROPERTY_GRADIENT_CACHE_SIZE, property, NULL) > 0) {
131        LOGD("  Setting gradient cache size to %sMB", property);
132        mGradientCache.setMaxSize(MB(atof(property)));
133    } else {
134        LOGD("  Using default gradient cache size of %.2fMB", DEFAULT_GRADIENT_CACHE_SIZE);
135    }
136
137    if (property_get(PROPERTY_PATH_CACHE_SIZE, property, NULL) > 0) {
138        LOGD("  Setting path cache size to %sMB", property);
139        mPathCache.setMaxSize(MB(atof(property)));
140    } else {
141        LOGD("  Using default path cache size of %.2fMB", DEFAULT_PATH_CACHE_SIZE);
142    }
143
144    if (property_get(PROPERTY_DROP_SHADOW_CACHE_SIZE, property, NULL) > 0) {
145        LOGD("  Setting drop shadow cache size to %sMB", property);
146        mDropShadowCache.setMaxSize(MB(atof(property)));
147    } else {
148        LOGD("  Using default drop shadow cache size of %.2fMB", DEFAULT_DROP_SHADOW_CACHE_SIZE);
149    }
150    mDropShadowCache.setFontRenderer(mFontRenderer);
151
152    mCurrentProgram = NULL;
153    mShader = NULL;
154    mColorFilter = NULL;
155    mHasShadow = false;
156
157    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
158
159    mFirstSnapshot = new Snapshot;
160
161    GLint maxTextureUnits;
162    glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
163    if (maxTextureUnits < REQUIRED_TEXTURE_UNITS_COUNT) {
164        LOGW("At least %d texture units are required!", REQUIRED_TEXTURE_UNITS_COUNT);
165    }
166}
167
168OpenGLRenderer::~OpenGLRenderer() {
169    LOGD("Destroy OpenGLRenderer");
170
171    mTextureCache.clear();
172    mLayerCache.clear();
173    mGradientCache.clear();
174    mPathCache.clear();
175    mPatchCache.clear();
176    mProgramCache.clear();
177    mDropShadowCache.clear();
178}
179
180///////////////////////////////////////////////////////////////////////////////
181// Setup
182///////////////////////////////////////////////////////////////////////////////
183
184void OpenGLRenderer::setViewport(int width, int height) {
185    glViewport(0, 0, width, height);
186    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
187
188    mWidth = width;
189    mHeight = height;
190    mFirstSnapshot->height = height;
191    mFirstSnapshot->viewport.set(0, 0, width, height);
192}
193
194void OpenGLRenderer::prepare() {
195    mSnapshot = new Snapshot(mFirstSnapshot);
196    mSaveCount = 1;
197
198    glDisable(GL_SCISSOR_TEST);
199
200    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
201    glClear(GL_COLOR_BUFFER_BIT);
202
203    glEnable(GL_SCISSOR_TEST);
204    glScissor(0, 0, mWidth, mHeight);
205
206    mSnapshot->setClip(0.0f, 0.0f, mWidth, mHeight);
207}
208
209///////////////////////////////////////////////////////////////////////////////
210// State management
211///////////////////////////////////////////////////////////////////////////////
212
213int OpenGLRenderer::getSaveCount() const {
214    return mSaveCount;
215}
216
217int OpenGLRenderer::save(int flags) {
218    return saveSnapshot();
219}
220
221void OpenGLRenderer::restore() {
222    if (mSaveCount > 1 && restoreSnapshot()) {
223        setScissorFromClip();
224    }
225}
226
227void OpenGLRenderer::restoreToCount(int saveCount) {
228    if (saveCount < 1) saveCount = 1;
229
230    bool restoreClip = false;
231
232    while (mSaveCount > saveCount) {
233        restoreClip |= restoreSnapshot();
234    }
235
236    if (restoreClip) {
237        setScissorFromClip();
238    }
239}
240
241int OpenGLRenderer::saveSnapshot() {
242    mSnapshot = new Snapshot(mSnapshot);
243    return mSaveCount++;
244}
245
246bool OpenGLRenderer::restoreSnapshot() {
247    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
248    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
249    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
250
251    sp<Snapshot> current = mSnapshot;
252    sp<Snapshot> previous = mSnapshot->previous;
253
254    if (restoreOrtho) {
255        Rect& r = previous->viewport;
256        glViewport(r.left, r.top, r.right, r.bottom);
257        mOrthoMatrix.load(current->orthoMatrix);
258    }
259
260    if (restoreLayer) {
261        composeLayer(current, previous);
262    }
263
264    bool skip = mSnapshot->skip;
265    if (!skip) {
266        mSaveCount--;
267    }
268    mSnapshot = previous;
269
270    if (!skip) {
271        return restoreClip;
272    } else {
273        bool restorePreviousClip = restoreSnapshot();
274        return restoreClip || restorePreviousClip;
275    }
276}
277
278///////////////////////////////////////////////////////////////////////////////
279// Layers
280///////////////////////////////////////////////////////////////////////////////
281
282int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
283        const SkPaint* p, int flags) {
284    int count = saveSnapshot();
285
286    int alpha = 255;
287    SkXfermode::Mode mode;
288
289    if (p) {
290        alpha = p->getAlpha();
291        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
292        if (!isMode) {
293            // Assume SRC_OVER
294            mode = SkXfermode::kSrcOver_Mode;
295        }
296    } else {
297        mode = SkXfermode::kSrcOver_Mode;
298    }
299
300    createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags);
301
302    return count;
303}
304
305int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
306        int alpha, int flags) {
307    int count = saveSnapshot();
308    createLayer(mSnapshot, left, top, right, bottom, alpha, SkXfermode::kSrcOver_Mode, flags);
309    return count;
310}
311
312bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
313        float right, float bottom, int alpha, SkXfermode::Mode mode,int flags) {
314    LAYER_LOGD("Requesting layer %fx%f", right - left, bottom - top);
315    LAYER_LOGD("Layer cache size = %d", mLayerCache.getSize());
316
317    GLuint previousFbo = snapshot->previous.get() ? snapshot->previous->fbo : 0;
318    LayerSize size(right - left, bottom - top);
319
320    Layer* layer = mLayerCache.get(size, previousFbo);
321    if (!layer) {
322        return false;
323    }
324
325    glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
326
327    // Clear the FBO
328    glDisable(GL_SCISSOR_TEST);
329    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
330    glClear(GL_COLOR_BUFFER_BIT);
331    glEnable(GL_SCISSOR_TEST);
332
333    layer->mode = mode;
334    layer->alpha = alpha / 255.0f;
335    layer->layer.set(left, top, right, bottom);
336
337    // Save the layer in the snapshot
338    snapshot->flags |= Snapshot::kFlagIsLayer;
339    snapshot->layer = layer;
340    snapshot->fbo = layer->fbo;
341
342    // Creates a new snapshot to draw into the FBO
343    saveSnapshot();
344    mSaveCount--;
345
346    mSnapshot->skip = true;
347    mSnapshot->transform.loadTranslate(-left, -top, 0.0f);
348    mSnapshot->setClip(0.0f, 0.0f, right - left, bottom - top);
349    mSnapshot->viewport.set(0.0f, 0.0f, right - left, bottom - top);
350    mSnapshot->height = bottom - top;
351
352    setScissorFromClip();
353
354    mSnapshot->flags = Snapshot::kFlagDirtyOrtho | Snapshot::kFlagClipSet;
355    mSnapshot->orthoMatrix.load(mOrthoMatrix);
356
357    // Change the ortho projection
358    glViewport(0, 0, right - left, bottom - top);
359    // Don't flip the FBO, it will get flipped when drawing back to the framebuffer
360    mOrthoMatrix.loadOrtho(0.0f, right - left, 0.0f, bottom - top, -1.0f, 1.0f);
361
362    return true;
363}
364
365void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
366    if (!current->layer) {
367        LOGE("Attempting to compose a layer that does not exist");
368        return;
369    }
370
371    // Unbind current FBO and restore previous one
372    // Most of the time, previous->fbo will be 0 to bind the default buffer
373    glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
374
375    // Restore the clip from the previous snapshot
376    const Rect& clip = previous->clipRect;
377    glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight());
378
379    Layer* layer = current->layer;
380    const Rect& rect = layer->layer;
381
382    drawTextureRect(rect.left, rect.top, rect.right, rect.bottom,
383            layer->texture, layer->alpha, layer->mode, layer->blend);
384
385    LayerSize size(rect.getWidth(), rect.getHeight());
386    // Failing to add the layer to the cache should happen only if the
387    // layer is too large
388    if (!mLayerCache.put(size, layer)) {
389        LAYER_LOGD("Deleting layer");
390
391        glDeleteFramebuffers(1, &layer->fbo);
392        glDeleteTextures(1, &layer->texture);
393
394        delete layer;
395    }
396}
397
398///////////////////////////////////////////////////////////////////////////////
399// Transforms
400///////////////////////////////////////////////////////////////////////////////
401
402void OpenGLRenderer::translate(float dx, float dy) {
403    mSnapshot->transform.translate(dx, dy, 0.0f);
404}
405
406void OpenGLRenderer::rotate(float degrees) {
407    mSnapshot->transform.rotate(degrees, 0.0f, 0.0f, 1.0f);
408}
409
410void OpenGLRenderer::scale(float sx, float sy) {
411    mSnapshot->transform.scale(sx, sy, 1.0f);
412}
413
414void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
415    mSnapshot->transform.load(*matrix);
416}
417
418void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
419    mSnapshot->transform.copyTo(*matrix);
420}
421
422void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
423    mat4 m(*matrix);
424    mSnapshot->transform.multiply(m);
425}
426
427///////////////////////////////////////////////////////////////////////////////
428// Clipping
429///////////////////////////////////////////////////////////////////////////////
430
431void OpenGLRenderer::setScissorFromClip() {
432    const Rect& clip = mSnapshot->clipRect;
433    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
434}
435
436const Rect& OpenGLRenderer::getClipBounds() {
437    return mSnapshot->getLocalClip();
438}
439
440bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
441    Rect r(left, top, right, bottom);
442    mSnapshot->transform.mapRect(r);
443    return !mSnapshot->clipRect.intersects(r);
444}
445
446bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
447    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
448    if (clipped) {
449        setScissorFromClip();
450    }
451    return !mSnapshot->clipRect.isEmpty();
452}
453
454///////////////////////////////////////////////////////////////////////////////
455// Drawing
456///////////////////////////////////////////////////////////////////////////////
457
458void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
459    const float right = left + bitmap->width();
460    const float bottom = top + bitmap->height();
461
462    if (quickReject(left, top, right, bottom)) {
463        return;
464    }
465
466    glActiveTexture(GL_TEXTURE0);
467    const Texture* texture = mTextureCache.get(bitmap);
468    if (!texture) return;
469    const AutoTexture autoCleanup(texture);
470
471    drawTextureRect(left, top, right, bottom, texture, paint);
472}
473
474void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) {
475    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
476    const mat4 transform(*matrix);
477    transform.mapRect(r);
478
479    if (quickReject(r.left, r.top, r.right, r.bottom)) {
480        return;
481    }
482
483    glActiveTexture(GL_TEXTURE0);
484    const Texture* texture = mTextureCache.get(bitmap);
485    if (!texture) return;
486    const AutoTexture autoCleanup(texture);
487
488    drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint);
489}
490
491void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
492         float srcLeft, float srcTop, float srcRight, float srcBottom,
493         float dstLeft, float dstTop, float dstRight, float dstBottom,
494         const SkPaint* paint) {
495    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
496        return;
497    }
498
499    glActiveTexture(GL_TEXTURE0);
500    const Texture* texture = mTextureCache.get(bitmap);
501    if (!texture) return;
502    const AutoTexture autoCleanup(texture);
503
504    const float width = texture->width;
505    const float height = texture->height;
506
507    const float u1 = srcLeft / width;
508    const float v1 = srcTop / height;
509    const float u2 = srcRight / width;
510    const float v2 = srcBottom / height;
511
512    resetDrawTextureTexCoords(u1, v1, u2, v2);
513
514    drawTextureRect(dstLeft, dstTop, dstRight, dstBottom, texture, paint);
515
516    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
517}
518
519void OpenGLRenderer::drawPatch(SkBitmap* bitmap, Res_png_9patch* patch,
520        float left, float top, float right, float bottom, const SkPaint* paint) {
521    if (quickReject(left, top, right, bottom)) {
522        return;
523    }
524
525    glActiveTexture(GL_TEXTURE0);
526    const Texture* texture = mTextureCache.get(bitmap);
527    if (!texture) return;
528    const AutoTexture autoCleanup(texture);
529
530    int alpha;
531    SkXfermode::Mode mode;
532    getAlphaAndMode(paint, &alpha, &mode);
533
534    Patch* mesh = mPatchCache.get(patch);
535    mesh->updateVertices(bitmap, left, top, right, bottom,
536            &patch->xDivs[0], &patch->yDivs[0], patch->numXDivs, patch->numYDivs);
537
538    // Specify right and bottom as +1.0f from left/top to prevent scaling since the
539    // patch mesh already defines the final size
540    drawTextureMesh(left, top, left + 1.0f, top + 1.0f, texture->id, alpha / 255.0f,
541            mode, texture->blend, &mesh->vertices[0].position[0],
542            &mesh->vertices[0].texture[0], mesh->indices, mesh->indicesCount);
543}
544
545void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
546    const Rect& clip = mSnapshot->clipRect;
547    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
548}
549
550void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) {
551    if (quickReject(left, top, right, bottom)) {
552        return;
553    }
554
555    SkXfermode::Mode mode;
556
557    const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
558    if (!isMode) {
559        // Assume SRC_OVER
560        mode = SkXfermode::kSrcOver_Mode;
561    }
562
563    // Skia draws using the color's alpha channel if < 255
564    // Otherwise, it uses the paint's alpha
565    int color = p->getColor();
566    if (((color >> 24) & 0xff) == 255) {
567        color |= p->getAlpha() << 24;
568    }
569
570    drawColorRect(left, top, right, bottom, color, mode);
571}
572
573void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
574        float x, float y, SkPaint* paint) {
575    if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
576        return;
577    }
578
579    float length = -1.0f;
580    switch (paint->getTextAlign()) {
581        case SkPaint::kCenter_Align:
582            length = paint->measureText(text, bytesCount);
583            x -= length / 2.0f;
584            break;
585        case SkPaint::kRight_Align:
586            length = paint->measureText(text, bytesCount);
587            x -= length;
588            break;
589        default:
590            break;
591    }
592
593    int alpha;
594    SkXfermode::Mode mode;
595    getAlphaAndMode(paint, &alpha, &mode);
596
597    mFontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()), paint->getTextSize());
598    if (mHasShadow) {
599        glActiveTexture(gTextureUnits[0]);
600        const ShadowTexture* shadow = mDropShadowCache.get(paint, text, bytesCount,
601                count, mShadowRadius);
602        const AutoTexture autoCleanup(shadow);
603
604        setupShadow(shadow, x, y, mode);
605
606        // Draw the mesh
607        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
608        glDisableVertexAttribArray(mCurrentProgram->getAttrib("texCoords"));
609    }
610
611    uint32_t color = paint->getColor();
612    const GLfloat a = alpha / 255.0f;
613    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
614    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
615    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
616
617    GLuint textureUnit = 0;
618    glActiveTexture(gTextureUnits[textureUnit]);
619
620    setupTextureAlpha8(mFontRenderer.getTexture(), 0, 0, textureUnit, x, y, r, g, b, a,
621            mode, false, true);
622
623    const Rect& clip = mSnapshot->getLocalClip();
624    mFontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y);
625
626    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
627    glDisableVertexAttribArray(mCurrentProgram->getAttrib("texCoords"));
628
629    drawTextDecorations(text, bytesCount, length, x, y, paint);
630}
631
632void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
633    GLuint textureUnit = 0;
634    glActiveTexture(gTextureUnits[textureUnit]);
635
636    const PathTexture* texture = mPathCache.get(path, paint);
637    if (!texture) return;
638    const AutoTexture autoCleanup(texture);
639
640    int alpha;
641    SkXfermode::Mode mode;
642    getAlphaAndMode(paint, &alpha, &mode);
643
644    uint32_t color = paint->getColor();
645    const GLfloat a = alpha / 255.0f;
646    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
647    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
648    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
649
650    const float x = texture->left - texture->offset;
651    const float y = texture->top - texture->offset;
652
653    setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true);
654
655    // Draw the mesh
656    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
657    glDisableVertexAttribArray(mCurrentProgram->getAttrib("texCoords"));
658}
659
660///////////////////////////////////////////////////////////////////////////////
661// Shaders
662///////////////////////////////////////////////////////////////////////////////
663
664void OpenGLRenderer::resetShader() {
665    mShader = NULL;
666}
667
668void OpenGLRenderer::setupShader(SkiaShader* shader) {
669    mShader = shader;
670    if (mShader) {
671        mShader->set(&mTextureCache, &mGradientCache);
672    }
673}
674
675///////////////////////////////////////////////////////////////////////////////
676// Color filters
677///////////////////////////////////////////////////////////////////////////////
678
679void OpenGLRenderer::resetColorFilter() {
680    mColorFilter = NULL;
681}
682
683void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
684    mColorFilter = filter;
685}
686
687///////////////////////////////////////////////////////////////////////////////
688// Drop shadow
689///////////////////////////////////////////////////////////////////////////////
690
691void OpenGLRenderer::resetShadow() {
692    mHasShadow = false;
693}
694
695void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
696    mHasShadow = true;
697    mShadowRadius = radius;
698    mShadowDx = dx;
699    mShadowDy = dy;
700    mShadowColor = color;
701}
702
703///////////////////////////////////////////////////////////////////////////////
704// Drawing implementation
705///////////////////////////////////////////////////////////////////////////////
706
707void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y,
708        SkXfermode::Mode mode) {
709    const float sx = x - texture->left + mShadowDx;
710    const float sy = y - texture->top + mShadowDy;
711
712    const GLfloat a = ((mShadowColor >> 24) & 0xFF) / 255.0f;
713    const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f;
714    const GLfloat g = a * ((mShadowColor >>  8) & 0xFF) / 255.0f;
715    const GLfloat b = a * ((mShadowColor      ) & 0xFF) / 255.0f;
716
717    GLuint textureUnit = 0;
718    setupTextureAlpha8(texture, textureUnit, sx, sy, r, g, b, a, mode, true, false);
719}
720
721void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit,
722        float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode,
723        bool transforms, bool applyFilters) {
724    setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit,
725            x, y, r, g, b, a, mode, transforms, applyFilters);
726}
727
728void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
729        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
730        SkXfermode::Mode mode, bool transforms, bool applyFilters) {
731     // Describe the required shaders
732     ProgramDescription description;
733     description.hasTexture = true;
734     description.hasAlpha8Texture = true;
735
736     if (applyFilters) {
737         if (mShader) {
738             mShader->describe(description, mExtensions);
739         }
740         if (mColorFilter) {
741             mColorFilter->describe(description, mExtensions);
742         }
743     }
744
745     // Build and use the appropriate shader
746     useProgram(mProgramCache.get(description));
747
748     // Setup the blending mode
749     chooseBlending(true, mode);
750     bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, textureUnit);
751     glUniform1i(mCurrentProgram->getUniform("sampler"), textureUnit);
752
753     int texCoordsSlot = mCurrentProgram->getAttrib("texCoords");
754     glEnableVertexAttribArray(texCoordsSlot);
755
756     // Setup attributes
757     glVertexAttribPointer(mCurrentProgram->position, 2, GL_FLOAT, GL_FALSE,
758             gMeshStride, &mMeshVertices[0].position[0]);
759     glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE,
760             gMeshStride, &mMeshVertices[0].texture[0]);
761
762     // Setup uniforms
763     if (transforms) {
764         mModelView.loadTranslate(x, y, 0.0f);
765         mModelView.scale(width, height, 1.0f);
766     } else {
767         mModelView.loadIdentity();
768     }
769     mCurrentProgram->set(mOrthoMatrix, mModelView, mSnapshot->transform);
770     glUniform4f(mCurrentProgram->color, r, g, b, a);
771
772     textureUnit++;
773     if (applyFilters) {
774         // Setup attributes and uniforms required by the shaders
775         if (mShader) {
776             mShader->setupProgram(mCurrentProgram, mModelView, *mSnapshot, &textureUnit);
777         }
778         if (mColorFilter) {
779             mColorFilter->setupProgram(mCurrentProgram);
780         }
781     }
782}
783
784#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
785#define kStdUnderline_Offset    (1.0f / 9.0f)
786#define kStdUnderline_Thickness (1.0f / 18.0f)
787
788void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
789        float x, float y, SkPaint* paint) {
790    // Handle underline and strike-through
791    uint32_t flags = paint->getFlags();
792    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
793        float underlineWidth = length;
794        // If length is > 0.0f, we already measured the text for the text alignment
795        if (length <= 0.0f) {
796            underlineWidth = paint->measureText(text, bytesCount);
797        }
798
799        float offsetX = 0;
800        switch (paint->getTextAlign()) {
801            case SkPaint::kCenter_Align:
802                offsetX = underlineWidth * 0.5f;
803                break;
804            case SkPaint::kRight_Align:
805                offsetX = underlineWidth;
806                break;
807            default:
808                break;
809        }
810
811        if (underlineWidth > 0.0f) {
812            float textSize = paint->getTextSize();
813            float height = textSize * kStdUnderline_Thickness;
814
815            float left = x - offsetX;
816            float top = 0.0f;
817            float right = left + underlineWidth;
818            float bottom = 0.0f;
819
820            if (flags & SkPaint::kUnderlineText_Flag) {
821                top = y + textSize * kStdUnderline_Offset;
822                bottom = top + height;
823                drawRect(left, top, right, bottom, paint);
824            }
825
826            if (flags & SkPaint::kStrikeThruText_Flag) {
827                top = y + textSize * kStdStrikeThru_Offset;
828                bottom = top + height;
829                drawRect(left, top, right, bottom, paint);
830            }
831        }
832    }
833}
834
835void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
836        int color, SkXfermode::Mode mode, bool ignoreTransform) {
837    // If a shader is set, preserve only the alpha
838    if (mShader) {
839        color |= 0x00ffffff;
840    }
841
842    // Render using pre-multiplied alpha
843    const int alpha = (color >> 24) & 0xFF;
844    const GLfloat a = alpha / 255.0f;
845    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
846    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
847    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
848
849    GLuint textureUnit = 0;
850
851    // Setup the blending mode
852    chooseBlending(alpha < 255 || (mShader && mShader->blend()), mode);
853
854    // Describe the required shaders
855    ProgramDescription description;
856    if (mShader) {
857        mShader->describe(description, mExtensions);
858    }
859    if (mColorFilter) {
860        mColorFilter->describe(description, mExtensions);
861    }
862
863    // Build and use the appropriate shader
864    useProgram(mProgramCache.get(description));
865
866    // Setup attributes
867    glVertexAttribPointer(mCurrentProgram->position, 2, GL_FLOAT, GL_FALSE,
868            gMeshStride, &mMeshVertices[0].position[0]);
869
870    // Setup uniforms
871    mModelView.loadTranslate(left, top, 0.0f);
872    mModelView.scale(right - left, bottom - top, 1.0f);
873    if (!ignoreTransform) {
874        mCurrentProgram->set(mOrthoMatrix, mModelView, mSnapshot->transform);
875    } else {
876        mat4 identity;
877        mCurrentProgram->set(mOrthoMatrix, mModelView, identity);
878    }
879    glUniform4f(mCurrentProgram->color, r, g, b, a);
880
881    // Setup attributes and uniforms required by the shaders
882    if (mShader) {
883        mShader->setupProgram(mCurrentProgram, mModelView, *mSnapshot, &textureUnit);
884    }
885    if (mColorFilter) {
886        mColorFilter->setupProgram(mCurrentProgram);
887    }
888
889    // Draw the mesh
890    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
891}
892
893void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
894        const Texture* texture, const SkPaint* paint) {
895    int alpha;
896    SkXfermode::Mode mode;
897    getAlphaAndMode(paint, &alpha, &mode);
898
899    drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, texture->blend,
900            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], NULL);
901}
902
903void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
904        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
905    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
906            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], NULL);
907}
908
909void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
910        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
911        GLvoid* vertices, GLvoid* texCoords, GLvoid* indices, GLsizei elementsCount) {
912    ProgramDescription description;
913    description.hasTexture = true;
914    if (mColorFilter) {
915        mColorFilter->describe(description, mExtensions);
916    }
917
918    mModelView.loadTranslate(left, top, 0.0f);
919    mModelView.scale(right - left, bottom - top, 1.0f);
920
921    useProgram(mProgramCache.get(description));
922    mCurrentProgram->set(mOrthoMatrix, mModelView, mSnapshot->transform);
923
924    chooseBlending(blend || alpha < 1.0f, mode);
925
926    // Texture
927    bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, 0);
928    glUniform1i(mCurrentProgram->getUniform("sampler"), 0);
929
930    // Always premultiplied
931    glUniform4f(mCurrentProgram->color, alpha, alpha, alpha, alpha);
932
933    // Mesh
934    int texCoordsSlot = mCurrentProgram->getAttrib("texCoords");
935    glEnableVertexAttribArray(texCoordsSlot);
936    glVertexAttribPointer(mCurrentProgram->position, 2, GL_FLOAT, GL_FALSE,
937            gMeshStride, vertices);
938    glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
939
940    // Color filter
941    if (mColorFilter) {
942        mColorFilter->setupProgram(mCurrentProgram);
943    }
944
945    if (!indices) {
946        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
947    } else {
948        glDrawElements(GL_TRIANGLES, elementsCount, GL_UNSIGNED_SHORT, indices);
949    }
950    glDisableVertexAttribArray(texCoordsSlot);
951}
952
953void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, bool isPremultiplied) {
954    blend = blend || mode != SkXfermode::kSrcOver_Mode;
955    if (blend) {
956        if (!mBlend) {
957            glEnable(GL_BLEND);
958        }
959
960        GLenum sourceMode = gBlends[mode].src;
961        GLenum destMode = gBlends[mode].dst;
962        if (!isPremultiplied && sourceMode == GL_ONE) {
963            sourceMode = GL_SRC_ALPHA;
964        }
965
966        if (sourceMode != mLastSrcMode || destMode != mLastDstMode) {
967            glBlendFunc(sourceMode, destMode);
968            mLastSrcMode = sourceMode;
969            mLastDstMode = destMode;
970        }
971    } else if (mBlend) {
972        glDisable(GL_BLEND);
973    }
974    mBlend = blend;
975}
976
977bool OpenGLRenderer::useProgram(Program* program) {
978    if (!program->isInUse()) {
979        if (mCurrentProgram != NULL) mCurrentProgram->remove();
980        program->use();
981        mCurrentProgram = program;
982        return false;
983    }
984    return true;
985}
986
987void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
988    TextureVertex* v = &mMeshVertices[0];
989    TextureVertex::setUV(v++, u1, v1);
990    TextureVertex::setUV(v++, u2, v1);
991    TextureVertex::setUV(v++, u1, v2);
992    TextureVertex::setUV(v++, u2, v2);
993}
994
995void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
996    if (paint) {
997        const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
998        if (!isMode) {
999            // Assume SRC_OVER
1000            *mode = SkXfermode::kSrcOver_Mode;
1001        }
1002
1003        // Skia draws using the color's alpha channel if < 255
1004        // Otherwise, it uses the paint's alpha
1005        int color = paint->getColor();
1006        *alpha = (color >> 24) & 0xFF;
1007        if (*alpha == 255) {
1008            *alpha = paint->getAlpha();
1009        }
1010    } else {
1011        *mode = SkXfermode::kSrcOver_Mode;
1012        *alpha = 255;
1013    }
1014}
1015
1016void OpenGLRenderer::bindTexture(GLuint texture, GLenum wrapS, GLenum wrapT, GLuint textureUnit) {
1017    glActiveTexture(gTextureUnits[textureUnit]);
1018    glBindTexture(GL_TEXTURE_2D, texture);
1019    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1020    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1021}
1022
1023}; // namespace uirenderer
1024}; // namespace android
1025