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