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