OpenGLRenderer.cpp revision f86ef57f8bcd8ba43ce222ec6a8b4f67d3600640
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "OpenGLRenderer"
18
19#include <stdlib.h>
20#include <stdint.h>
21#include <sys/types.h>
22
23#include <SkCanvas.h>
24
25#include <utils/Log.h>
26
27#include "OpenGLRenderer.h"
28
29namespace android {
30namespace uirenderer {
31
32///////////////////////////////////////////////////////////////////////////////
33// Defines
34///////////////////////////////////////////////////////////////////////////////
35
36#define MAX_TEXTURE_COUNT 128
37
38#define SV(x, y) { { x, y } }
39#define FV(x, y, u, v) { { x, y }, { u, v } }
40
41///////////////////////////////////////////////////////////////////////////////
42// Globals
43///////////////////////////////////////////////////////////////////////////////
44
45static const SimpleVertex gDrawColorVertices[] = {
46        SV(0.0f, 0.0f),
47        SV(1.0f, 0.0f),
48        SV(0.0f, 1.0f),
49        SV(1.0f, 1.0f)
50};
51static const GLsizei gDrawColorVertexStride = sizeof(SimpleVertex);
52static const GLsizei gDrawColorVertexCount = 4;
53
54// This array is never used directly but used as a memcpy source in the
55// OpenGLRenderer constructor
56static const TextureVertex gDrawTextureVertices[] = {
57        FV(0.0f, 0.0f, 0.0f, 0.0f),
58        FV(1.0f, 0.0f, 1.0f, 0.0f),
59        FV(0.0f, 1.0f, 0.0f, 1.0f),
60        FV(1.0f, 1.0f, 1.0f, 1.0f)
61};
62static const GLsizei gDrawTextureVertexStride = sizeof(TextureVertex);
63static const GLsizei gDrawTextureVertexCount = 4;
64
65// In this array, the index of each Blender equals the value of the first
66// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
67static const Blender gBlends[] = {
68        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
69        { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
70        { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
71        { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
72        { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
73        { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
74        { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
75        { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
76        { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
77        { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
78        { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
79        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
80};
81
82///////////////////////////////////////////////////////////////////////////////
83// Constructors/destructor
84///////////////////////////////////////////////////////////////////////////////
85
86OpenGLRenderer::OpenGLRenderer(): mTextureCache(MAX_TEXTURE_COUNT) {
87    LOGD("Create OpenGLRenderer");
88
89    mDrawColorShader = new DrawColorProgram;
90    mDrawTextureShader = new DrawTextureProgram;
91
92    memcpy(mDrawTextureVertices, gDrawTextureVertices, sizeof(gDrawTextureVertices));
93}
94
95OpenGLRenderer::~OpenGLRenderer() {
96    LOGD("Destroy OpenGLRenderer");
97
98    mTextureCache.clear();
99}
100
101///////////////////////////////////////////////////////////////////////////////
102// Setup
103///////////////////////////////////////////////////////////////////////////////
104
105void OpenGLRenderer::setViewport(int width, int height) {
106    glViewport(0, 0, width, height);
107
108    mat4 ortho;
109    ortho.loadOrtho(0, width, height, 0, -1, 1);
110    ortho.copyTo(mOrthoMatrix);
111
112    mWidth = width;
113    mHeight = height;
114    mFirstSnapshot.height = height;
115}
116
117void OpenGLRenderer::prepare() {
118    mSnapshot = &mFirstSnapshot;
119    mSaveCount = 0;
120
121    glDisable(GL_SCISSOR_TEST);
122
123    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
124    glClear(GL_COLOR_BUFFER_BIT);
125
126    glEnable(GL_SCISSOR_TEST);
127    glScissor(0, 0, mWidth, mHeight);
128
129    mSnapshot->clipRect.set(0.0f, 0.0f, mWidth, mHeight);
130}
131
132///////////////////////////////////////////////////////////////////////////////
133// State management
134///////////////////////////////////////////////////////////////////////////////
135
136int OpenGLRenderer::getSaveCount() const {
137    return mSaveCount;
138}
139
140int OpenGLRenderer::save(int flags) {
141    return saveSnapshot();
142}
143
144void OpenGLRenderer::restore() {
145    if (mSaveCount == 0) return;
146
147    if (restoreSnapshot()) {
148        setScissorFromClip();
149    }
150}
151
152void OpenGLRenderer::restoreToCount(int saveCount) {
153    if (saveCount <= 0 || saveCount > mSaveCount) return;
154
155    bool restoreClip = false;
156
157    while (mSaveCount != saveCount - 1) {
158        restoreClip |= restoreSnapshot();
159    }
160
161    if (restoreClip) {
162        setScissorFromClip();
163    }
164}
165
166int OpenGLRenderer::saveSnapshot() {
167    mSnapshot = new Snapshot(mSnapshot);
168    return ++mSaveCount;
169}
170
171bool OpenGLRenderer::restoreSnapshot() {
172    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
173    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
174    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
175
176    sp<Snapshot> current = mSnapshot;
177    sp<Snapshot> previous = mSnapshot->previous;
178
179    if (restoreOrtho) {
180        memcpy(mOrthoMatrix, current->orthoMatrix, sizeof(mOrthoMatrix));
181    }
182
183    if (restoreLayer) {
184        composeLayer(current, previous);
185    }
186
187    mSnapshot = previous;
188    mSaveCount--;
189
190    return restoreClip;
191}
192
193void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
194    // Unbind current FBO and restore previous one
195    // Most of the time, previous->fbo will be 0 to bind the default buffer
196    glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
197
198    // Restore the clip from the previous snapshot
199    const Rect& clip = previous->getMappedClip();
200    glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight());
201
202    // Compute the correct texture coordinates for the FBO texture
203    // The texture is currently as big as the window but drawn with
204    // a quad of the appropriate size
205    const Rect& layer = current->layer;
206
207    drawTextureRect(layer.left, layer.top, layer.right, layer.bottom,
208            current->texture, current->alpha, current->mode, true, true);
209
210    // TODO Don't delete these things, but cache them
211    glDeleteFramebuffers(1, &current->fbo);
212    glDeleteTextures(1, &current->texture);
213}
214
215///////////////////////////////////////////////////////////////////////////////
216// Layers
217///////////////////////////////////////////////////////////////////////////////
218
219int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
220        const SkPaint* p, int flags) {
221    int count = saveSnapshot();
222
223    int alpha = 255;
224    SkXfermode::Mode mode;
225
226    if (p) {
227        alpha = p->getAlpha();
228        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
229        if (!isMode) {
230            // Assume SRC_OVER
231            mode = SkXfermode::kSrcOver_Mode;
232        }
233    } else {
234        mode = SkXfermode::kSrcOver_Mode;
235    }
236
237    createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags);
238
239    return count;
240}
241
242int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
243        int alpha, int flags) {
244    int count = saveSnapshot();
245    createLayer(mSnapshot, left, top, right, bottom, alpha, SkXfermode::kSrcOver_Mode, flags);
246    return count;
247}
248
249bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
250        float right, float bottom, int alpha, SkXfermode::Mode mode,int flags) {
251    // Generate the FBO and attach the texture
252    glGenFramebuffers(1, &snapshot->fbo);
253    glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo);
254
255    // Generate the texture in which the FBO will draw
256    glGenTextures(1, &snapshot->texture);
257    glBindTexture(GL_TEXTURE_2D, snapshot->texture);
258
259    // The FBO will not be scaled, so we can use lower quality filtering
260    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
261    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
262
263    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
264    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
265
266    // TODO VERY IMPORTANT: Fix TextView to not call saveLayer() all the time
267    // TODO Use an FBO cache
268
269    const GLsizei width = right - left;
270    const GLsizei height = bottom - top;
271
272    const GLint format = (flags & SkCanvas::kHasAlphaLayer_SaveFlag) ? GL_RGBA : GL_RGB;
273    glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, NULL);
274    glBindTexture(GL_TEXTURE_2D, 0);
275
276    // Bind texture to FBO
277    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
278            snapshot->texture, 0);
279
280    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
281    if (status != GL_FRAMEBUFFER_COMPLETE) {
282        LOGD("Framebuffer incomplete (GL error code 0x%x)", status);
283
284        glDeleteFramebuffers(1, &snapshot->fbo);
285        glDeleteTextures(1, &snapshot->texture);
286
287        return false;
288    }
289
290    // Clear the FBO
291    glDisable(GL_SCISSOR_TEST);
292    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
293    glClear(GL_COLOR_BUFFER_BIT);
294    glEnable(GL_SCISSOR_TEST);
295
296    snapshot->flags |= Snapshot::kFlagIsLayer;
297    snapshot->mode = mode;
298    snapshot->alpha = alpha / 255.0f;
299    snapshot->layer.set(left, top, right, bottom);
300
301    // Creates a new snapshot to draw into the FBO
302    saveSnapshot();
303    // TODO: This doesn't preserve other transformations (check Skia first)
304    mSnapshot->transform.loadTranslate(-left, -top, 0.0f);
305    mSnapshot->clipRect.set(left, top, right, bottom);
306    mSnapshot->height = bottom - top;
307    setScissorFromClip();
308
309    mSnapshot->flags = Snapshot::kFlagDirtyTransform | Snapshot::kFlagDirtyOrtho |
310            Snapshot::kFlagClipSet;
311    memcpy(mSnapshot->orthoMatrix, mOrthoMatrix, sizeof(mOrthoMatrix));
312
313    // Change the ortho projection
314    mat4 ortho;
315    ortho.loadOrtho(0.0f, right - left, bottom - top, 0.0f, 0.0f, 1.0f);
316    ortho.copyTo(mOrthoMatrix);
317
318    return true;
319}
320
321///////////////////////////////////////////////////////////////////////////////
322// Transforms
323///////////////////////////////////////////////////////////////////////////////
324
325void OpenGLRenderer::translate(float dx, float dy) {
326    mSnapshot->transform.translate(dx, dy, 0.0f);
327    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
328}
329
330void OpenGLRenderer::rotate(float degrees) {
331    mSnapshot->transform.rotate(degrees, 0.0f, 0.0f, 1.0f);
332    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
333}
334
335void OpenGLRenderer::scale(float sx, float sy) {
336    mSnapshot->transform.scale(sx, sy, 1.0f);
337    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
338}
339
340void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
341    mSnapshot->transform.load(*matrix);
342    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
343}
344
345void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
346    mSnapshot->transform.copyTo(*matrix);
347}
348
349void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
350    mat4 m(*matrix);
351    mSnapshot->transform.multiply(m);
352    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
353}
354
355///////////////////////////////////////////////////////////////////////////////
356// Clipping
357///////////////////////////////////////////////////////////////////////////////
358
359void OpenGLRenderer::setScissorFromClip() {
360    const Rect& clip = mSnapshot->getMappedClip();
361    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
362}
363
364const Rect& OpenGLRenderer::getClipBounds() {
365    return mSnapshot->clipRect;
366}
367
368bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
369    /*
370     * The documentation of quickReject() indicates that the specified rect
371     * is transformed before being compared to the clip rect. However, the
372     * clip rect is not stored transformed in the snapshot and can thus be
373     * compared directly
374     *
375     * The following code can be used instead to performed a mapped comparison:
376     *
377     *     mSnapshot->transform.mapRect(r);
378     *     const Rect& clip = mSnapshot->getMappedClip();
379     *     return !clip.intersects(r);
380     */
381    Rect r(left, top, right, bottom);
382    return !mSnapshot->clipRect.intersects(r);
383}
384
385bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom) {
386    bool clipped = mSnapshot->clipRect.intersect(left, top, right, bottom);
387    if (clipped) {
388        mSnapshot->flags |= Snapshot::kFlagClipSet;
389        setScissorFromClip();
390    }
391    return clipped;
392}
393
394///////////////////////////////////////////////////////////////////////////////
395// Drawing
396///////////////////////////////////////////////////////////////////////////////
397
398void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
399    const Texture* texture = mTextureCache.get(bitmap);
400
401    int alpha;
402    SkXfermode::Mode mode;
403    getAlphaAndMode(paint, &alpha, &mode);
404
405    drawTextureRect(left, top, left + texture->width, top + texture->height, texture->id,
406            alpha / 255.0f, mode, texture->blend, true);
407}
408
409void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) {
410    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
411    const mat4 transform(*matrix);
412    transform.mapRect(r);
413
414    const Texture* texture = mTextureCache.get(bitmap);
415
416    int alpha;
417    SkXfermode::Mode mode;
418    getAlphaAndMode(paint, &alpha, &mode);
419
420    drawTextureRect(r.left, r.top, r.right, r.bottom, texture->id,
421            alpha / 255.0f, mode, texture->blend, true);
422}
423
424void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
425         float srcLeft, float srcTop, float srcRight, float srcBottom,
426         float dstLeft, float dstTop, float dstRight, float dstBottom,
427         const SkPaint* paint) {
428    const Texture* texture = mTextureCache.get(bitmap);
429
430    int alpha;
431    SkXfermode::Mode mode;
432    getAlphaAndMode(paint, &alpha, &mode);
433
434    const float width = texture->width;
435    const float height = texture->height;
436
437    const float u1 = srcLeft / width;
438    const float v1 = srcTop / height;
439    const float u2 = srcRight / width;
440    const float v2 = srcBottom / height;
441
442    resetDrawTextureTexCoords(u1, v1, u2, v2);
443
444    drawTextureRect(dstLeft, dstTop, dstRight, dstBottom, texture->id,
445            alpha / 255.0f, mode, texture->blend, true);
446
447    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
448}
449
450void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
451    const Rect& clip = mSnapshot->clipRect;
452    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode);
453}
454
455void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) {
456    SkXfermode::Mode mode;
457
458    const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
459    if (!isMode) {
460        // Assume SRC_OVER
461        mode = SkXfermode::kSrcOver_Mode;
462    }
463
464    // Skia draws using the color's alpha channel if < 255
465    // Otherwise, it uses the paint's alpha
466    int color = p->getColor();
467    if (((color >> 24) & 0xFF) == 255) {
468        color |= p->getAlpha() << 24;
469    }
470
471    drawColorRect(left, top, right, bottom, color, mode);
472}
473
474void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
475        int color, SkXfermode::Mode mode) {
476    const int alpha = (color >> 24) & 0xFF;
477    const bool blend = alpha < 255 || mode != SkXfermode::kSrcOver_Mode;
478
479    const GLfloat a = alpha                  / 255.0f;
480    const GLfloat r = ((color >> 16) & 0xFF) / 255.0f;
481    const GLfloat g = ((color >>  8) & 0xFF) / 255.0f;
482    const GLfloat b = ((color      ) & 0xFF) / 255.0f;
483
484    if (blend) {
485        glEnable(GL_BLEND);
486        glBlendFunc(gBlends[mode].src, gBlends[mode].dst);
487    }
488
489    mModelView.loadTranslate(left, top, 0.0f);
490    mModelView.scale(right - left, bottom - top, 1.0f);
491
492    mDrawColorShader->use(&mOrthoMatrix[0], &mModelView.data[0], &mSnapshot->transform.data[0]);
493
494    const GLvoid* p = &gDrawColorVertices[0].position[0];
495
496    glEnableVertexAttribArray(mDrawColorShader->position);
497    glVertexAttribPointer(mDrawColorShader->position, 2, GL_FLOAT, GL_FALSE,
498            gDrawColorVertexStride, p);
499    glVertexAttrib4f(mDrawColorShader->color, r, g, b, a);
500
501    glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawColorVertexCount);
502
503    glDisableVertexAttribArray(mDrawColorShader->position);
504
505    if (blend) {
506        glDisable(GL_BLEND);
507    }
508}
509
510void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
511        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend, bool isPremultiplied) {
512    mModelView.loadTranslate(left, top, 0.0f);
513    mModelView.scale(right - left, bottom - top, 1.0f);
514
515    mDrawTextureShader->use(&mOrthoMatrix[0], &mModelView.data[0], &mSnapshot->transform.data[0]);
516
517    if (blend || alpha < 1.0f || mode != SkXfermode::kSrcOver_Mode) {
518        GLenum sourceMode = gBlends[mode].src;
519        if (!isPremultiplied && sourceMode == GL_ONE) {
520            sourceMode = GL_SRC_ALPHA;
521        }
522
523        glEnable(GL_BLEND);
524        glBlendFunc(sourceMode, gBlends[mode].dst);
525    }
526
527    glBindTexture(GL_TEXTURE_2D, texture);
528
529    // TODO handle tiling and filtering here
530
531    glActiveTexture(GL_TEXTURE0);
532    glUniform1i(mDrawTextureShader->sampler, 0);
533
534    const GLvoid* p = &mDrawTextureVertices[0].position[0];
535    const GLvoid* t = &mDrawTextureVertices[0].texture[0];
536
537    glEnableVertexAttribArray(mDrawTextureShader->position);
538    glVertexAttribPointer(mDrawTextureShader->position, 2, GL_FLOAT, GL_FALSE,
539            gDrawTextureVertexStride, p);
540
541    glEnableVertexAttribArray(mDrawTextureShader->texCoords);
542    glVertexAttribPointer(mDrawTextureShader->texCoords, 2, GL_FLOAT, GL_FALSE,
543            gDrawTextureVertexStride, t);
544
545    glVertexAttrib4f(mDrawTextureShader->color, 1.0f, 1.0f, 1.0f, alpha);
546
547    glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawTextureVertexCount);
548
549    glDisableVertexAttribArray(mDrawTextureShader->position);
550    glDisableVertexAttribArray(mDrawTextureShader->texCoords);
551
552    glBindTexture(GL_TEXTURE_2D, 0);
553    glDisable(GL_BLEND);
554}
555
556void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
557    mDrawTextureVertices[0].texture[0] = u1;
558    mDrawTextureVertices[0].texture[1] = v1;
559    mDrawTextureVertices[1].texture[0] = u2;
560    mDrawTextureVertices[1].texture[1] = v1;
561    mDrawTextureVertices[2].texture[0] = u1;
562    mDrawTextureVertices[2].texture[1] = v2;
563    mDrawTextureVertices[3].texture[0] = u2;
564    mDrawTextureVertices[3].texture[1] = v2;
565}
566
567void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
568    if (paint) {
569        const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
570        if (!isMode) {
571            // Assume SRC_OVER
572            *mode = SkXfermode::kSrcOver_Mode;
573        }
574
575        // Skia draws using the color's alpha channel if < 255
576        // Otherwise, it uses the paint's alpha
577        int color = paint->getColor();
578        *alpha = (color >> 24) & 0xFF;
579        if (*alpha == 255) {
580            *alpha = paint->getAlpha();
581        }
582    } else {
583        *mode = SkXfermode::kSrcOver_Mode;
584        *alpha = 255;
585    }
586}
587
588}; // namespace uirenderer
589}; // namespace android
590