OpenGLPipeline.cpp revision 3e9999bd866fac71c72e6b484a9836c87c328a08
1/*
2 * Copyright (C) 2016 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 "OpenGLPipeline.h"
18
19#include "DeferredLayerUpdater.h"
20#include "EglManager.h"
21#include "Frame.h"
22#include "GlLayer.h"
23#include "ProfileRenderer.h"
24#include "renderstate/RenderState.h"
25#include "OpenGLReadback.h"
26
27#include <android/native_window.h>
28#include <cutils/properties.h>
29#include <strings.h>
30
31namespace android {
32namespace uirenderer {
33namespace renderthread {
34
35OpenGLPipeline::OpenGLPipeline(RenderThread& thread)
36        :  mEglManager(thread.eglManager())
37        , mRenderThread(thread) {
38}
39
40MakeCurrentResult OpenGLPipeline::makeCurrent() {
41    // TODO: Figure out why this workaround is needed, see b/13913604
42    // In the meantime this matches the behavior of GLRenderer, so it is not a regression
43    EGLint error = 0;
44    bool haveNewSurface = mEglManager.makeCurrent(mEglSurface, &error);
45
46    Caches::getInstance().textureCache.resetMarkInUse(this);
47    if (!haveNewSurface) {
48        return MakeCurrentResult::AlreadyCurrent;
49    }
50    return error ? MakeCurrentResult::Failed : MakeCurrentResult::Succeeded;
51}
52
53Frame OpenGLPipeline::getFrame() {
54    LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE,
55                "drawRenderNode called on a context with no surface!");
56    return mEglManager.beginFrame(mEglSurface);
57}
58
59bool OpenGLPipeline::draw(const Frame& frame, const SkRect& screenDirty, const SkRect& dirty,
60        const FrameBuilder::LightGeometry& lightGeometry,
61        LayerUpdateQueue* layerUpdateQueue,
62        const Rect& contentDrawBounds, bool opaque,
63        const BakedOpRenderer::LightInfo& lightInfo,
64        const std::vector< sp<RenderNode> >& renderNodes,
65        FrameInfoVisualizer* profiler) {
66
67    mEglManager.damageFrame(frame, dirty);
68
69    bool drew = false;
70
71
72    auto& caches = Caches::getInstance();
73    FrameBuilder frameBuilder(dirty, frame.width(), frame.height(), lightGeometry, caches);
74
75    frameBuilder.deferLayers(*layerUpdateQueue);
76    layerUpdateQueue->clear();
77
78    frameBuilder.deferRenderNodeScene(renderNodes, contentDrawBounds);
79
80    BakedOpRenderer renderer(caches, mRenderThread.renderState(),
81            opaque, lightInfo);
82    frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer);
83    ProfileRenderer profileRenderer(renderer);
84    profiler->draw(profileRenderer);
85    drew = renderer.didDraw();
86
87    // post frame cleanup
88    caches.clearGarbage();
89    caches.pathCache.trim();
90    caches.tessellationCache.trim();
91
92#if DEBUG_MEMORY_USAGE
93    caches.dumpMemoryUsage();
94#else
95    if (CC_UNLIKELY(Properties::debugLevel & kDebugMemory)) {
96        caches.dumpMemoryUsage();
97    }
98#endif
99
100    return drew;
101}
102
103bool OpenGLPipeline::swapBuffers(const Frame& frame, bool drew, const SkRect& screenDirty,
104        FrameInfo* currentFrameInfo, bool* requireSwap) {
105
106    GL_CHECKPOINT(LOW);
107
108    // Even if we decided to cancel the frame, from the perspective of jank
109    // metrics the frame was swapped at this point
110    currentFrameInfo->markSwapBuffers();
111
112    *requireSwap = drew || mEglManager.damageRequiresSwap();
113
114    if (*requireSwap && (CC_UNLIKELY(!mEglManager.swapBuffers(frame, screenDirty)))) {
115        return false;
116    }
117
118    return *requireSwap;
119}
120
121bool OpenGLPipeline::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) {
122    ATRACE_CALL();
123    layer->apply();
124    return OpenGLReadbackImpl::copyLayerInto(mRenderThread,
125            static_cast<GlLayer&>(*layer->backingLayer()), bitmap);
126}
127
128static Layer* createLayer(RenderState& renderState, uint32_t layerWidth, uint32_t layerHeight,
129        SkColorFilter* colorFilter, int alpha, SkBlendMode mode, bool blend) {
130    GlLayer* layer = new GlLayer(renderState, layerWidth, layerHeight, colorFilter, alpha,
131            mode, blend);
132    Caches::getInstance().textureState().activateTexture(0);
133    layer->generateTexture();
134    return layer;
135}
136
137DeferredLayerUpdater* OpenGLPipeline::createTextureLayer() {
138    mEglManager.initialize();
139    return new DeferredLayerUpdater(mRenderThread.renderState(), createLayer, Layer::Api::OpenGL);
140}
141
142void OpenGLPipeline::onStop() {
143    if (mEglManager.isCurrent(mEglSurface)) {
144        mEglManager.makeCurrent(EGL_NO_SURFACE);
145    }
146}
147
148bool OpenGLPipeline::setSurface(Surface* surface, SwapBehavior swapBehavior) {
149
150    if (mEglSurface != EGL_NO_SURFACE) {
151        mEglManager.destroySurface(mEglSurface);
152        mEglSurface = EGL_NO_SURFACE;
153    }
154
155    if (surface) {
156        mEglSurface = mEglManager.createSurface(surface);
157    }
158
159    if (mEglSurface != EGL_NO_SURFACE) {
160        const bool preserveBuffer = (swapBehavior != SwapBehavior::kSwap_discardBuffer);
161        mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer);
162        return true;
163    }
164
165    return false;
166}
167
168bool OpenGLPipeline::isSurfaceReady() {
169    return CC_UNLIKELY(mEglSurface != EGL_NO_SURFACE);
170}
171
172bool OpenGLPipeline::isContextReady() {
173    return CC_LIKELY(mEglManager.hasEglContext());
174}
175
176void OpenGLPipeline::onDestroyHardwareResources() {
177    Caches& caches = Caches::getInstance();
178    // Make sure to release all the textures we were owning as there won't
179    // be another draw
180    caches.textureCache.resetMarkInUse(this);
181    mRenderThread.renderState().flush(Caches::FlushMode::Layers);
182}
183
184void OpenGLPipeline::renderLayers(const FrameBuilder::LightGeometry& lightGeometry,
185        LayerUpdateQueue* layerUpdateQueue, bool opaque,
186        const BakedOpRenderer::LightInfo& lightInfo) {
187    static const std::vector< sp<RenderNode> > emptyNodeList;
188    auto& caches = Caches::getInstance();
189    FrameBuilder frameBuilder(*layerUpdateQueue, lightGeometry, caches);
190    layerUpdateQueue->clear();
191    BakedOpRenderer renderer(caches, mRenderThread.renderState(),
192            opaque, lightInfo);
193    LOG_ALWAYS_FATAL_IF(renderer.didDraw(), "shouldn't draw in buildlayer case");
194    frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer);
195}
196
197TaskManager* OpenGLPipeline::getTaskManager() {
198    return &Caches::getInstance().tasks;
199}
200
201static bool layerMatchesWH(OffscreenBuffer* layer, int width, int height) {
202    return layer->viewportWidth == (uint32_t)width && layer->viewportHeight == (uint32_t)height;
203}
204
205bool OpenGLPipeline::createOrUpdateLayer(RenderNode* node,
206        const DamageAccumulator& damageAccumulator) {
207    RenderState& renderState = mRenderThread.renderState();
208    OffscreenBufferPool& layerPool = renderState.layerPool();
209    bool transformUpdateNeeded = false;
210    if (node->getLayer() == nullptr) {
211        node->setLayer(layerPool.get(renderState, node->getWidth(), node->getHeight()));
212        transformUpdateNeeded = true;
213    } else if (!layerMatchesWH(node->getLayer(), node->getWidth(), node->getHeight())) {
214        // TODO: remove now irrelevant, currently enqueued damage (respecting damage ordering)
215        // Or, ideally, maintain damage between frames on node/layer so ordering is always correct
216        if (node->properties().fitsOnLayer()) {
217            node->setLayer(layerPool.resize(node->getLayer(), node->getWidth(), node->getHeight()));
218        } else {
219            destroyLayer(node);
220        }
221        transformUpdateNeeded = true;
222    }
223
224    if (transformUpdateNeeded && node->getLayer()) {
225        // update the transform in window of the layer to reset its origin wrt light source position
226        Matrix4 windowTransform;
227        damageAccumulator.computeCurrentTransform(&windowTransform);
228        node->getLayer()->setWindowTransform(windowTransform);
229    }
230
231    return transformUpdateNeeded;
232}
233
234bool OpenGLPipeline::pinImages(LsaVector<sk_sp<Bitmap>>& images) {
235    TextureCache& cache = Caches::getInstance().textureCache;
236    bool prefetchSucceeded = true;
237    for (auto& bitmapResource : images) {
238        prefetchSucceeded &= cache.prefetchAndMarkInUse(this, bitmapResource.get());
239    }
240    return prefetchSucceeded;
241}
242
243void OpenGLPipeline::unpinImages() {
244    Caches::getInstance().textureCache.resetMarkInUse(this);
245}
246
247void OpenGLPipeline::destroyLayer(RenderNode* node) {
248    if (OffscreenBuffer* layer = node->getLayer()) {
249        layer->renderState.layerPool().putOrDelete(layer);
250        node->setLayer(nullptr);
251    }
252}
253
254void OpenGLPipeline::prepareToDraw(const RenderThread& thread, Bitmap* bitmap) {
255    if (Caches::hasInstance() && thread.eglManager().hasEglContext()) {
256        ATRACE_NAME("Bitmap#prepareToDraw task");
257        Caches::getInstance().textureCache.prefetch(bitmap);
258    }
259}
260
261void OpenGLPipeline::invokeFunctor(const RenderThread& thread, Functor* functor) {
262    DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
263    if (thread.eglManager().hasEglContext()) {
264        mode = DrawGlInfo::kModeProcess;
265    }
266    thread.renderState().invokeFunctor(functor, mode, nullptr);
267}
268
269} /* namespace renderthread */
270} /* namespace uirenderer */
271} /* namespace android */
272