LayerRenderer.cpp revision 96885eb480c5e0526fe2f77d30f6e551f3f3ceab
1/*
2 * Copyright (C) 2011 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 <ui/Rect.h>
20
21#include <private/hwui/DrawGlInfo.h>
22
23#include "LayerCache.h"
24#include "LayerRenderer.h"
25#include "Matrix.h"
26#include "Properties.h"
27#include "Rect.h"
28
29namespace android {
30namespace uirenderer {
31
32///////////////////////////////////////////////////////////////////////////////
33// Rendering
34///////////////////////////////////////////////////////////////////////////////
35
36LayerRenderer::LayerRenderer(Layer* layer): mLayer(layer) {
37}
38
39LayerRenderer::~LayerRenderer() {
40}
41
42void LayerRenderer::setViewport(int width, int height) {
43    initViewport(width, height);
44}
45
46status_t LayerRenderer::prepareDirty(float left, float top, float right, float bottom,
47        bool opaque) {
48    LAYER_RENDERER_LOGD("Rendering into layer, fbo = %d", mLayer->getFbo());
49
50    glBindFramebuffer(GL_FRAMEBUFFER, mLayer->getFbo());
51
52    const float width = mLayer->layer.getWidth();
53    const float height = mLayer->layer.getHeight();
54
55    Rect dirty(left, top, right, bottom);
56    if (dirty.isEmpty() || (dirty.left <= 0 && dirty.top <= 0 &&
57            dirty.right >= width && dirty.bottom >= height)) {
58        mLayer->region.clear();
59        dirty.set(0.0f, 0.0f, width, height);
60    } else {
61        dirty.intersect(0.0f, 0.0f, width, height);
62        android::Rect r(dirty.left, dirty.top, dirty.right, dirty.bottom);
63        mLayer->region.subtractSelf(r);
64    }
65    mLayer->clipRect.set(dirty);
66
67    return OpenGLRenderer::prepareDirty(dirty.left, dirty.top, dirty.right, dirty.bottom, opaque);
68}
69
70status_t LayerRenderer::clear(float left, float top, float right, float bottom, bool opaque) {
71    if (mLayer->isDirty()) {
72        getCaches().disableScissor();
73        glClear(GL_COLOR_BUFFER_BIT);
74
75        getCaches().resetScissor();
76        mLayer->setDirty(false);
77
78        return DrawGlInfo::kStatusDone;
79    }
80
81    return OpenGLRenderer::clear(left, top, right, bottom, opaque);
82}
83
84void LayerRenderer::finish() {
85    OpenGLRenderer::finish();
86
87    generateMesh();
88
89    LAYER_RENDERER_LOGD("Finished rendering into layer, fbo = %d", mLayer->getFbo());
90
91    // No need to unbind our FBO, this will be taken care of by the caller
92    // who will invoke OpenGLRenderer::resume()
93}
94
95GLint LayerRenderer::getTargetFbo() const {
96    return mLayer->getFbo();
97}
98
99bool LayerRenderer::suppressErrorChecks() const {
100    return true;
101}
102
103///////////////////////////////////////////////////////////////////////////////
104// Layer support
105///////////////////////////////////////////////////////////////////////////////
106
107bool LayerRenderer::hasLayer() const {
108    return true;
109}
110
111void LayerRenderer::ensureStencilBuffer() {
112    attachStencilBufferToLayer(mLayer);
113}
114
115///////////////////////////////////////////////////////////////////////////////
116// Dirty region tracking
117///////////////////////////////////////////////////////////////////////////////
118
119Region* LayerRenderer::getRegion() const {
120    if (getSnapshot()->flags & Snapshot::kFlagFboTarget) {
121        return OpenGLRenderer::getRegion();
122    }
123    return &mLayer->region;
124}
125
126// TODO: This implementation uses a very simple approach to fixing T-junctions which keeps the
127//       results as rectangles, and is thus not necessarily efficient in the geometry
128//       produced. Eventually, it may be better to develop triangle-based mechanism.
129void LayerRenderer::generateMesh() {
130    if (mLayer->region.isRect() || mLayer->region.isEmpty()) {
131        if (mLayer->mesh) {
132            delete[] mLayer->mesh;
133            delete[] mLayer->meshIndices;
134
135            mLayer->mesh = NULL;
136            mLayer->meshIndices = NULL;
137            mLayer->meshElementCount = 0;
138        }
139
140        mLayer->setRegionAsRect();
141        return;
142    }
143
144    // avoid T-junctions as they cause artifacts in between the resultant
145    // geometry when complex transforms occur.
146    // TODO: generate the safeRegion only if necessary based on drawing transform (see
147    // OpenGLRenderer::composeLayerRegion())
148    Region safeRegion = Region::createTJunctionFreeRegion(mLayer->region);
149
150    size_t count;
151    const android::Rect* rects = safeRegion.getArray(&count);
152
153    GLsizei elementCount = count * 6;
154
155    if (mLayer->mesh && mLayer->meshElementCount < elementCount) {
156        delete[] mLayer->mesh;
157        delete[] mLayer->meshIndices;
158
159        mLayer->mesh = NULL;
160        mLayer->meshIndices = NULL;
161    }
162
163    bool rebuildIndices = false;
164    if (!mLayer->mesh) {
165        mLayer->mesh = new TextureVertex[count * 4];
166        mLayer->meshIndices = new uint16_t[elementCount];
167        rebuildIndices = true;
168    }
169    mLayer->meshElementCount = elementCount;
170
171    const float texX = 1.0f / float(mLayer->getWidth());
172    const float texY = 1.0f / float(mLayer->getHeight());
173    const float height = mLayer->layer.getHeight();
174
175    TextureVertex* mesh = mLayer->mesh;
176    uint16_t* indices = mLayer->meshIndices;
177
178    for (size_t i = 0; i < count; i++) {
179        const android::Rect* r = &rects[i];
180
181        const float u1 = r->left * texX;
182        const float v1 = (height - r->top) * texY;
183        const float u2 = r->right * texX;
184        const float v2 = (height - r->bottom) * texY;
185
186        TextureVertex::set(mesh++, r->left, r->top, u1, v1);
187        TextureVertex::set(mesh++, r->right, r->top, u2, v1);
188        TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
189        TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
190
191        if (rebuildIndices) {
192            uint16_t quad = i * 4;
193            int index = i * 6;
194            indices[index    ] = quad;       // top-left
195            indices[index + 1] = quad + 1;   // top-right
196            indices[index + 2] = quad + 2;   // bottom-left
197            indices[index + 3] = quad + 2;   // bottom-left
198            indices[index + 4] = quad + 1;   // top-right
199            indices[index + 5] = quad + 3;   // bottom-right
200        }
201    }
202}
203
204///////////////////////////////////////////////////////////////////////////////
205// Layers management
206///////////////////////////////////////////////////////////////////////////////
207
208Layer* LayerRenderer::createLayer(uint32_t width, uint32_t height, bool isOpaque) {
209    LAYER_RENDERER_LOGD("Requesting new render layer %dx%d", width, height);
210
211    Caches& caches = Caches::getInstance();
212    GLuint fbo = caches.fboCache.get();
213    if (!fbo) {
214        ALOGW("Could not obtain an FBO");
215        return NULL;
216    }
217
218    caches.activeTexture(0);
219    Layer* layer = caches.layerCache.get(width, height);
220    if (!layer) {
221        ALOGW("Could not obtain a layer");
222        return NULL;
223    }
224
225    layer->setFbo(fbo);
226    layer->layer.set(0.0f, 0.0f, width, height);
227    layer->texCoords.set(0.0f, height / float(layer->getHeight()),
228            width / float(layer->getWidth()), 0.0f);
229    layer->setAlpha(255, SkXfermode::kSrcOver_Mode);
230    layer->setBlend(!isOpaque);
231    layer->setColorFilter(NULL);
232    layer->setDirty(true);
233    layer->region.clear();
234
235    GLuint previousFbo;
236    glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*) &previousFbo);
237
238    glBindFramebuffer(GL_FRAMEBUFFER, layer->getFbo());
239    layer->bindTexture();
240
241    // Initialize the texture if needed
242    if (layer->isEmpty()) {
243        layer->setEmpty(false);
244        layer->allocateTexture(GL_RGBA, GL_UNSIGNED_BYTE);
245
246        if (glGetError() != GL_NO_ERROR) {
247            ALOGD("Could not allocate texture for layer (fbo=%d %dx%d)",
248                    fbo, width, height);
249
250            glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
251
252            Caches::getInstance().resourceCache.decrementRefcount(layer);
253
254            return NULL;
255        }
256    }
257
258    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
259            layer->getTexture(), 0);
260
261    glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
262
263    return layer;
264}
265
266bool LayerRenderer::resizeLayer(Layer* layer, uint32_t width, uint32_t height) {
267    if (layer) {
268        LAYER_RENDERER_LOGD("Resizing layer fbo = %d to %dx%d", layer->getFbo(), width, height);
269
270        if (layer->resize(width, height)) {
271            layer->layer.set(0.0f, 0.0f, width, height);
272            layer->texCoords.set(0.0f, height / float(layer->getHeight()),
273                    width / float(layer->getWidth()), 0.0f);
274        } else {
275            Caches::getInstance().resourceCache.decrementRefcount(layer);
276            return false;
277        }
278    }
279
280    return true;
281}
282
283Layer* LayerRenderer::createTextureLayer(bool isOpaque) {
284    LAYER_RENDERER_LOGD("Creating new texture layer");
285
286    Layer* layer = new Layer(0, 0);
287    layer->setCacheable(false);
288    layer->setTextureLayer(true);
289    layer->setBlend(!isOpaque);
290    layer->setEmpty(true);
291    layer->setFbo(0);
292    layer->setAlpha(255, SkXfermode::kSrcOver_Mode);
293    layer->layer.set(0.0f, 0.0f, 0.0f, 0.0f);
294    layer->texCoords.set(0.0f, 1.0f, 1.0f, 0.0f);
295    layer->region.clear();
296    layer->setRenderTarget(GL_NONE); // see ::updateTextureLayer()
297
298    Caches::getInstance().activeTexture(0);
299    layer->generateTexture();
300
301    return layer;
302}
303
304void LayerRenderer::updateTextureLayer(Layer* layer, uint32_t width, uint32_t height,
305        bool isOpaque, GLenum renderTarget, float* transform) {
306    if (layer) {
307        layer->setBlend(!isOpaque);
308        layer->setSize(width, height);
309        layer->layer.set(0.0f, 0.0f, width, height);
310        layer->region.set(width, height);
311        layer->regionRect.set(0.0f, 0.0f, width, height);
312        layer->getTexTransform().load(transform);
313
314        if (renderTarget != layer->getRenderTarget()) {
315            layer->setRenderTarget(renderTarget);
316            layer->bindTexture();
317            layer->setFilter(GL_NEAREST, false, true);
318            layer->setWrap(GL_CLAMP_TO_EDGE, false, true);
319        }
320    }
321}
322
323void LayerRenderer::destroyLayer(Layer* layer) {
324    if (layer) {
325        LAYER_RENDERER_LOGD("Recycling layer, %dx%d fbo = %d",
326                layer->getWidth(), layer->getHeight(), layer->getFbo());
327
328        if (!Caches::getInstance().layerCache.put(layer)) {
329            LAYER_RENDERER_LOGD("  Destroyed!");
330            Caches::getInstance().resourceCache.decrementRefcount(layer);
331        } else {
332            LAYER_RENDERER_LOGD("  Cached!");
333#if DEBUG_LAYER_RENDERER
334            Caches::getInstance().layerCache.dump();
335#endif
336            layer->removeFbo();
337            layer->region.clear();
338        }
339    }
340}
341
342void LayerRenderer::destroyLayerDeferred(Layer* layer) {
343    if (layer) {
344        LAYER_RENDERER_LOGD("Deferring layer destruction, fbo = %d", layer->getFbo());
345
346        Caches::getInstance().deleteLayerDeferred(layer);
347    }
348}
349
350void LayerRenderer::flushLayer(Layer* layer) {
351#ifdef GL_EXT_discard_framebuffer
352    GLuint fbo = layer->getFbo();
353    if (layer && fbo) {
354        // If possible, discard any enqueud operations on deferred
355        // rendering architectures
356        if (Extensions::getInstance().hasDiscardFramebuffer()) {
357            GLuint previousFbo;
358            glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*) &previousFbo);
359            if (fbo != previousFbo) glBindFramebuffer(GL_FRAMEBUFFER, fbo);
360
361            const GLenum attachments[] = { GL_COLOR_ATTACHMENT0 };
362            glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
363
364            if (fbo != previousFbo) glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
365        }
366    }
367#endif
368}
369
370bool LayerRenderer::copyLayer(Layer* layer, SkBitmap* bitmap) {
371    Caches& caches = Caches::getInstance();
372    if (layer && bitmap->width() <= caches.maxTextureSize &&
373            bitmap->height() <= caches.maxTextureSize) {
374
375        GLuint fbo = caches.fboCache.get();
376        if (!fbo) {
377            ALOGW("Could not obtain an FBO");
378            return false;
379        }
380
381        SkAutoLockPixels alp(*bitmap);
382
383        GLuint texture;
384        GLuint previousFbo;
385        GLuint previousViewport[4];
386
387        GLenum format;
388        GLenum type;
389
390        GLenum error = GL_NO_ERROR;
391        bool status = false;
392
393        switch (bitmap->config()) {
394            case SkBitmap::kA8_Config:
395                format = GL_ALPHA;
396                type = GL_UNSIGNED_BYTE;
397                break;
398            case SkBitmap::kRGB_565_Config:
399                format = GL_RGB;
400                type = GL_UNSIGNED_SHORT_5_6_5;
401                break;
402            case SkBitmap::kARGB_4444_Config:
403                format = GL_RGBA;
404                type = GL_UNSIGNED_SHORT_4_4_4_4;
405                break;
406            case SkBitmap::kARGB_8888_Config:
407            default:
408                format = GL_RGBA;
409                type = GL_UNSIGNED_BYTE;
410                break;
411        }
412
413        float alpha = layer->getAlpha();
414        SkXfermode::Mode mode = layer->getMode();
415        GLuint previousLayerFbo = layer->getFbo();
416
417        layer->setAlpha(255, SkXfermode::kSrc_Mode);
418        layer->setFbo(fbo);
419
420        glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*) &previousFbo);
421        glGetIntegerv(GL_VIEWPORT, (GLint*) &previousViewport);
422        glBindFramebuffer(GL_FRAMEBUFFER, fbo);
423
424        glGenTextures(1, &texture);
425        if ((error = glGetError()) != GL_NO_ERROR) goto error;
426
427        caches.activeTexture(0);
428        glBindTexture(GL_TEXTURE_2D, texture);
429
430        glPixelStorei(GL_PACK_ALIGNMENT, bitmap->bytesPerPixel());
431
432        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
433        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
434
435        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
436        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
437
438        glTexImage2D(GL_TEXTURE_2D, 0, format, bitmap->width(), bitmap->height(),
439                0, format, type, NULL);
440        if ((error = glGetError()) != GL_NO_ERROR) goto error;
441
442        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
443                GL_TEXTURE_2D, texture, 0);
444        if ((error = glGetError()) != GL_NO_ERROR) goto error;
445
446        {
447            LayerRenderer renderer(layer);
448            renderer.setViewport(bitmap->width(), bitmap->height());
449            renderer.OpenGLRenderer::prepareDirty(0.0f, 0.0f,
450                    bitmap->width(), bitmap->height(), !layer->isBlend());
451
452            caches.disableScissor();
453            renderer.translate(0.0f, bitmap->height());
454            renderer.scale(1.0f, -1.0f);
455
456            mat4 texTransform(layer->getTexTransform());
457
458            mat4 invert;
459            invert.translate(0.0f, 1.0f, 0.0f);
460            invert.scale(1.0f, -1.0f, 1.0f);
461            layer->getTexTransform().multiply(invert);
462
463            if ((error = glGetError()) != GL_NO_ERROR) goto error;
464
465            {
466                Rect bounds;
467                bounds.set(0.0f, 0.0f, bitmap->width(), bitmap->height());
468                renderer.drawTextureLayer(layer, bounds);
469
470                glReadPixels(0, 0, bitmap->width(), bitmap->height(), format,
471                        type, bitmap->getPixels());
472
473                if ((error = glGetError()) != GL_NO_ERROR) goto error;
474            }
475
476            layer->getTexTransform().load(texTransform);
477            status = true;
478        }
479
480error:
481#if DEBUG_OPENGL
482        if (error != GL_NO_ERROR) {
483            ALOGD("GL error while copying layer into bitmap = 0x%x", error);
484        }
485#endif
486
487        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
488        layer->setAlpha(alpha, mode);
489        layer->setFbo(previousLayerFbo);
490        glDeleteTextures(1, &texture);
491        caches.fboCache.put(fbo);
492        glViewport(previousViewport[0], previousViewport[1],
493                previousViewport[2], previousViewport[3]);
494
495        return status;
496    }
497    return false;
498}
499
500}; // namespace uirenderer
501}; // namespace android
502