BakedOpRenderer.cpp revision 9372ac3621848085e77b867f220c0b5ffce4010d
1/*
2 * Copyright (C) 2015 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 "BakedOpRenderer.h"
18
19#include "Caches.h"
20#include "Glop.h"
21#include "GlopBuilder.h"
22#include "renderstate/OffscreenBufferPool.h"
23#include "renderstate/RenderState.h"
24#include "utils/GLUtils.h"
25#include "VertexBuffer.h"
26
27#include <algorithm>
28
29namespace android {
30namespace uirenderer {
31
32OffscreenBuffer* BakedOpRenderer::startTemporaryLayer(uint32_t width, uint32_t height) {
33    LOG_ALWAYS_FATAL_IF(mRenderTarget.offscreenBuffer, "already has layer...");
34
35    OffscreenBuffer* buffer = mRenderState.layerPool().get(mRenderState, width, height);
36    startRepaintLayer(buffer, Rect(width, height));
37    return buffer;
38}
39
40void BakedOpRenderer::startRepaintLayer(OffscreenBuffer* offscreenBuffer, const Rect& repaintRect) {
41    LOG_ALWAYS_FATAL_IF(mRenderTarget.offscreenBuffer, "already has layer...");
42
43    mRenderTarget.offscreenBuffer = offscreenBuffer;
44
45    // create and bind framebuffer
46    mRenderTarget.frameBufferId = mRenderState.genFramebuffer();
47    mRenderState.bindFramebuffer(mRenderTarget.frameBufferId);
48
49    // attach the texture to the FBO
50    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
51            offscreenBuffer->texture.id(), 0);
52    LOG_ALWAYS_FATAL_IF(GLUtils::dumpGLErrors(), "startLayer FAILED");
53    LOG_ALWAYS_FATAL_IF(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE,
54            "framebuffer incomplete!");
55
56    // Change the viewport & ortho projection
57    setViewport(offscreenBuffer->viewportWidth, offscreenBuffer->viewportHeight);
58
59    clearColorBuffer(repaintRect);
60}
61
62void BakedOpRenderer::endLayer() {
63    if (mRenderTarget.stencil) {
64        // if stencil was used for clipping, detach it and return it to pool
65        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0);
66        LOG_ALWAYS_FATAL_IF(GLUtils::dumpGLErrors(), "glfbrb endlayer failed");
67        mCaches.renderBufferCache.put(mRenderTarget.stencil);
68        mRenderTarget.stencil = nullptr;
69    }
70    mRenderTarget.lastStencilClip = nullptr;
71
72    mRenderTarget.offscreenBuffer->updateMeshFromRegion();
73    mRenderTarget.offscreenBuffer = nullptr; // It's in drawLayerOp's hands now.
74
75    // Detach the texture from the FBO
76    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
77    LOG_ALWAYS_FATAL_IF(GLUtils::dumpGLErrors(), "endLayer FAILED, bound fbo = %u",
78            mRenderState.getFramebuffer());
79    mRenderState.deleteFramebuffer(mRenderTarget.frameBufferId);
80    mRenderTarget.frameBufferId = 0;
81}
82
83OffscreenBuffer* BakedOpRenderer::copyToLayer(const Rect& area) {
84    OffscreenBuffer* buffer = mRenderState.layerPool().get(mRenderState,
85            area.getWidth(), area.getHeight());
86    if (!area.isEmpty()) {
87        mCaches.textureState().activateTexture(0);
88        mCaches.textureState().bindTexture(buffer->texture.id());
89
90        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
91                area.left, mRenderTarget.viewportHeight - area.bottom,
92                area.getWidth(), area.getHeight());
93    }
94    return buffer;
95}
96
97void BakedOpRenderer::startFrame(uint32_t width, uint32_t height, const Rect& repaintRect) {
98    LOG_ALWAYS_FATAL_IF(mRenderTarget.frameBufferId != 0, "primary framebufferId must be 0");
99    mRenderState.bindFramebuffer(0);
100    setViewport(width, height);
101
102    if (!mOpaque) {
103        clearColorBuffer(repaintRect);
104    }
105
106    mRenderState.debugOverdraw(true, true);
107}
108
109void BakedOpRenderer::endFrame(const Rect& repaintRect) {
110    if (CC_UNLIKELY(Properties::debugOverdraw)) {
111        ClipRect overdrawClip(repaintRect);
112        Rect viewportRect(mRenderTarget.viewportWidth, mRenderTarget.viewportHeight);
113        // overdraw visualization
114        for (int i = 1; i <= 4; i++) {
115            if (i < 4) {
116                // nth level of overdraw tests for n+1 draws per pixel
117                mRenderState.stencil().enableDebugTest(i + 1, false);
118            } else {
119                // 4th level tests for 4 or higher draws per pixel
120                mRenderState.stencil().enableDebugTest(4, true);
121            }
122
123            SkPaint paint;
124            paint.setColor(mCaches.getOverdrawColor(i));
125            Glop glop;
126            GlopBuilder(mRenderState, mCaches, &glop)
127                    .setRoundRectClipState(nullptr)
128                    .setMeshUnitQuad()
129                    .setFillPaint(paint, 1.0f)
130                    .setTransform(Matrix4::identity(), TransformFlags::None)
131                    .setModelViewMapUnitToRect(viewportRect)
132                    .build();
133            renderGlop(nullptr, &overdrawClip, glop);
134        }
135        mRenderState.stencil().disable();
136    }
137
138    mCaches.clearGarbage();
139    mCaches.pathCache.trim();
140    mCaches.tessellationCache.trim();
141
142#if DEBUG_OPENGL
143    GLUtils::dumpGLErrors();
144#endif
145
146#if DEBUG_MEMORY_USAGE
147    mCaches.dumpMemoryUsage();
148#else
149    if (Properties::debugLevel & kDebugMemory) {
150        mCaches.dumpMemoryUsage();
151    }
152#endif
153}
154
155void BakedOpRenderer::setViewport(uint32_t width, uint32_t height) {
156    mRenderTarget.viewportWidth = width;
157    mRenderTarget.viewportHeight = height;
158    mRenderTarget.orthoMatrix.loadOrtho(width, height);
159
160    mRenderState.setViewport(width, height);
161    mRenderState.blend().syncEnabled();
162}
163
164void BakedOpRenderer::clearColorBuffer(const Rect& rect) {
165    if (rect.contains(Rect(mRenderTarget.viewportWidth, mRenderTarget.viewportHeight))) {
166        // Full viewport is being cleared - disable scissor
167        mRenderState.scissor().setEnabled(false);
168    } else {
169        // Requested rect is subset of viewport - scissor to it to avoid over-clearing
170        mRenderState.scissor().setEnabled(true);
171        mRenderState.scissor().set(rect.left, mRenderTarget.viewportHeight - rect.bottom,
172                rect.getWidth(), rect.getHeight());
173    }
174    glClear(GL_COLOR_BUFFER_BIT);
175    if (!mRenderTarget.frameBufferId) mHasDrawn = true;
176}
177
178Texture* BakedOpRenderer::getTexture(const SkBitmap* bitmap) {
179    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap->pixelRef());
180    if (!texture) {
181        return mCaches.textureCache.get(bitmap);
182    }
183    return texture;
184}
185
186// clears and re-fills stencil with provided rendertarget space quads,
187// and then put stencil into test mode
188void BakedOpRenderer::setupStencilQuads(std::vector<Vertex>& quadVertices,
189        int incrementThreshold) {
190    mRenderState.stencil().enableWrite(incrementThreshold);
191    mRenderState.stencil().clear();
192    Glop glop;
193    GlopBuilder(mRenderState, mCaches, &glop)
194            .setRoundRectClipState(nullptr)
195            .setMeshIndexedQuads(quadVertices.data(), quadVertices.size() / 4)
196            .setFillBlack()
197            .setTransform(Matrix4::identity(), TransformFlags::None)
198            .setModelViewIdentityEmptyBounds()
199            .build();
200    mRenderState.render(glop, mRenderTarget.orthoMatrix);
201    mRenderState.stencil().enableTest(incrementThreshold);
202}
203
204void BakedOpRenderer::setupStencilRectList(const ClipBase* clip) {
205    LOG_ALWAYS_FATAL_IF(clip->mode != ClipMode::RectangleList, "can't rectlist clip without rectlist");
206    auto&& rectList = reinterpret_cast<const ClipRectList*>(clip)->rectList;
207    int quadCount = rectList.getTransformedRectanglesCount();
208    std::vector<Vertex> rectangleVertices;
209    rectangleVertices.reserve(quadCount * 4);
210    for (int i = 0; i < quadCount; i++) {
211        const TransformedRectangle& tr(rectList.getTransformedRectangle(i));
212        const Matrix4& transform = tr.getTransform();
213        Rect bounds = tr.getBounds();
214        if (transform.rectToRect()) {
215            // If rectToRect, can simply map bounds before storing verts
216            transform.mapRect(bounds);
217            bounds.doIntersect(clip->rect);
218            if (bounds.isEmpty()) {
219                continue; // will be outside of scissor, skip
220            }
221        }
222
223        rectangleVertices.push_back(Vertex{bounds.left, bounds.top});
224        rectangleVertices.push_back(Vertex{bounds.right, bounds.top});
225        rectangleVertices.push_back(Vertex{bounds.left, bounds.bottom});
226        rectangleVertices.push_back(Vertex{bounds.right, bounds.bottom});
227
228        if (!transform.rectToRect()) {
229            // If not rectToRect, must map each point individually
230            for (auto cur = rectangleVertices.end() - 4; cur < rectangleVertices.end(); cur++) {
231                transform.mapPoint(cur->x, cur->y);
232            }
233        }
234    }
235    setupStencilQuads(rectangleVertices, rectList.getTransformedRectanglesCount());
236}
237
238void BakedOpRenderer::setupStencilRegion(const ClipBase* clip) {
239    LOG_ALWAYS_FATAL_IF(clip->mode != ClipMode::Region, "can't region clip without region");
240    auto&& region = reinterpret_cast<const ClipRegion*>(clip)->region;
241
242    std::vector<Vertex> regionVertices;
243    SkRegion::Cliperator it(region, clip->rect.toSkIRect());
244    while (!it.done()) {
245        const SkIRect& r = it.rect();
246        regionVertices.push_back(Vertex{(float)r.fLeft, (float)r.fTop});
247        regionVertices.push_back(Vertex{(float)r.fRight, (float)r.fTop});
248        regionVertices.push_back(Vertex{(float)r.fLeft, (float)r.fBottom});
249        regionVertices.push_back(Vertex{(float)r.fRight, (float)r.fBottom});
250        it.next();
251    }
252    setupStencilQuads(regionVertices, 0);
253}
254
255void BakedOpRenderer::prepareRender(const Rect* dirtyBounds, const ClipBase* clip) {
256    // Prepare scissor (done before stencil, to simplify filling stencil)
257    mRenderState.scissor().setEnabled(clip != nullptr);
258    if (clip) {
259        mRenderState.scissor().set(mRenderTarget.viewportHeight, clip->rect);
260    }
261
262    // If stencil may be used for clipping, enable it, fill it, or disable it as appropriate
263    if (CC_LIKELY(!Properties::debugOverdraw)) {
264        // only modify stencil mode and content when it's not used for overdraw visualization
265        if (CC_UNLIKELY(clip && clip->mode != ClipMode::Rectangle)) {
266            // NOTE: this pointer check is only safe for non-rect clips,
267            // since rect clips may be created on the stack
268            if (mRenderTarget.lastStencilClip != clip) {
269                // Stencil needed, but current stencil isn't up to date
270                mRenderTarget.lastStencilClip = clip;
271
272                if (mRenderTarget.frameBufferId != 0 && !mRenderTarget.stencil) {
273                    OffscreenBuffer* layer = mRenderTarget.offscreenBuffer;
274                    mRenderTarget.stencil = mCaches.renderBufferCache.get(
275                            Stencil::getLayerStencilFormat(),
276                            layer->texture.width(), layer->texture.height());
277                    // stencil is bound + allocated - associate it with current FBO
278                    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
279                            GL_RENDERBUFFER, mRenderTarget.stencil->getName());
280                }
281
282                if (clip->mode == ClipMode::RectangleList) {
283                    setupStencilRectList(clip);
284                } else {
285                    setupStencilRegion(clip);
286                }
287            } else {
288                // stencil is up to date - just need to ensure it's enabled (since an unclipped
289                // or scissor-only clipped op may have been drawn, disabling the stencil)
290                int incrementThreshold = 0;
291                if (CC_LIKELY(clip->mode == ClipMode::RectangleList)) {
292                    auto&& rectList = reinterpret_cast<const ClipRectList*>(clip)->rectList;
293                    incrementThreshold = rectList.getTransformedRectanglesCount();
294                }
295                mRenderState.stencil().enableTest(incrementThreshold);
296            }
297        } else {
298            // either scissor or no clip, so disable stencil test
299            mRenderState.stencil().disable();
300        }
301    }
302
303    // dirty offscreenbuffer
304    if (dirtyBounds && mRenderTarget.offscreenBuffer) {
305        // register layer damage to draw-back region
306        android::Rect dirty(dirtyBounds->left, dirtyBounds->top,
307                dirtyBounds->right, dirtyBounds->bottom);
308        mRenderTarget.offscreenBuffer->region.orSelf(dirty);
309    }
310}
311
312void BakedOpRenderer::renderGlop(const Rect* dirtyBounds, const ClipBase* clip,
313        const Glop& glop) {
314    prepareRender(dirtyBounds, clip);
315    mRenderState.render(glop, mRenderTarget.orthoMatrix);
316    if (!mRenderTarget.frameBufferId) mHasDrawn = true;
317}
318
319void BakedOpRenderer::renderFunctor(const FunctorOp& op, const BakedOpState& state) {
320    prepareRender(&state.computedState.clippedBounds, state.computedState.getClipIfNeeded());
321
322    DrawGlInfo info;
323    auto&& clip = state.computedState.clipRect();
324    info.clipLeft = clip.left;
325    info.clipTop = clip.top;
326    info.clipRight = clip.right;
327    info.clipBottom = clip.bottom;
328    info.isLayer = offscreenRenderTarget();
329    info.width = mRenderTarget.viewportWidth;
330    info.height = mRenderTarget.viewportHeight;
331    state.computedState.transform.copyTo(&info.transform[0]);
332
333    mRenderState.invokeFunctor(op.functor, DrawGlInfo::kModeDraw, &info);
334}
335
336void BakedOpRenderer::dirtyRenderTarget(const Rect& uiDirty) {
337    if (mRenderTarget.offscreenBuffer) {
338        android::Rect dirty(uiDirty.left, uiDirty.top, uiDirty.right, uiDirty.bottom);
339        mRenderTarget.offscreenBuffer->region.orSelf(dirty);
340    }
341}
342
343} // namespace uirenderer
344} // namespace android
345