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