2 * Copyright (C) 2014 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "CanvasContext.h"
20 #include <private/hwui/DrawGlInfo.h>
23 #include "EglManager.h"
24 #include "RenderThread.h"
25 #include "../AnimationContext.h"
26 #include "../Caches.h"
27 #include "../DeferredLayerUpdater.h"
28 #include "../RenderState.h"
29 #include "../LayerRenderer.h"
30 #include "../OpenGLRenderer.h"
31 #include "../Stencil.h"
33 #define TRIM_MEMORY_COMPLETE 80
34 #define TRIM_MEMORY_UI_HIDDEN 20
37 namespace uirenderer {
38 namespace renderthread {
40 CanvasContext::CanvasContext(RenderThread& thread, bool translucent,
41 RenderNode* rootRenderNode, IContextFactory* contextFactory)
42 : mRenderThread(thread)
43 , mEglManager(thread.eglManager())
44 , mEglSurface(EGL_NO_SURFACE)
45 , mBufferPreserved(false)
46 , mSwapBehavior(kSwap_default)
47 , mOpaque(!translucent)
49 , mHaveNewSurface(false)
50 , mRootRenderNode(rootRenderNode) {
51 mAnimationContext = contextFactory->createAnimationContext(mRenderThread.timeLord());
52 mRenderThread.renderState().registerCanvasContext(this);
55 CanvasContext::~CanvasContext() {
57 delete mAnimationContext;
58 mRenderThread.renderState().unregisterCanvasContext(this);
61 void CanvasContext::destroy() {
64 freePrefetechedLayers();
65 destroyHardwareResources();
66 mAnimationContext->destroy();
73 void CanvasContext::setSurface(ANativeWindow* window) {
76 mNativeWindow = window;
78 if (mEglSurface != EGL_NO_SURFACE) {
79 mEglManager.destroySurface(mEglSurface);
80 mEglSurface = EGL_NO_SURFACE;
84 mEglSurface = mEglManager.createSurface(window);
87 if (mEglSurface != EGL_NO_SURFACE) {
88 const bool preserveBuffer = (mSwapBehavior != kSwap_discardBuffer);
89 mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer);
90 mHaveNewSurface = true;
93 mRenderThread.removeFrameCallback(this);
97 void CanvasContext::swapBuffers() {
98 if (CC_UNLIKELY(!mEglManager.swapBuffers(mEglSurface))) {
101 mHaveNewSurface = false;
104 void CanvasContext::requireSurface() {
105 LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE,
106 "requireSurface() called but no surface set!");
110 void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) {
111 mSwapBehavior = swapBehavior;
114 bool CanvasContext::initialize(ANativeWindow* window) {
116 if (mCanvas) return false;
117 mCanvas = new OpenGLRenderer(mRenderThread.renderState());
118 mCanvas->initProperties();
122 void CanvasContext::updateSurface(ANativeWindow* window) {
126 bool CanvasContext::pauseSurface(ANativeWindow* window) {
127 return mRenderThread.removeFrameCallback(this);
130 // TODO: don't pass viewport size, it's automatic via EGL
131 void CanvasContext::setup(int width, int height, const Vector3& lightCenter, float lightRadius,
132 uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
133 if (!mCanvas) return;
134 mCanvas->initLight(lightCenter, lightRadius, ambientShadowAlpha, spotShadowAlpha);
137 void CanvasContext::setOpaque(bool opaque) {
141 void CanvasContext::makeCurrent() {
142 // TODO: Figure out why this workaround is needed, see b/13913604
143 // In the meantime this matches the behavior of GLRenderer, so it is not a regression
144 mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface);
147 void CanvasContext::processLayerUpdate(DeferredLayerUpdater* layerUpdater) {
148 bool success = layerUpdater->apply();
149 LOG_ALWAYS_FATAL_IF(!success, "Failed to update layer!");
150 if (layerUpdater->backingLayer()->deferredUpdateScheduled) {
151 mCanvas->pushLayerUpdate(layerUpdater->backingLayer());
155 void CanvasContext::prepareTree(TreeInfo& info) {
156 mRenderThread.removeFrameCallback(this);
158 info.damageAccumulator = &mDamageAccumulator;
159 info.renderer = mCanvas;
160 if (mPrefetechedLayers.size() && info.mode == TreeInfo::MODE_FULL) {
161 info.canvasContext = this;
163 mAnimationContext->startFrame(info.mode);
164 mRootRenderNode->prepareTree(info);
165 mAnimationContext->runRemainingAnimations(info);
167 if (info.canvasContext) {
168 freePrefetechedLayers();
171 if (CC_UNLIKELY(!mNativeWindow.get())) {
172 info.out.canDrawThisFrame = false;
176 int runningBehind = 0;
177 // TODO: This query is moderately expensive, investigate adding some sort
178 // of fast-path based off when we last called eglSwapBuffers() as well as
179 // last vsync time. Or something.
180 mNativeWindow->query(mNativeWindow.get(),
181 NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &runningBehind);
182 info.out.canDrawThisFrame = !runningBehind;
184 if (info.out.hasAnimations || !info.out.canDrawThisFrame) {
185 if (!info.out.requiresUiRedraw) {
186 // If animationsNeedsRedraw is set don't bother posting for an RT anim
187 // as we will just end up fighting the UI thread.
188 mRenderThread.postFrameCallback(this);
193 void CanvasContext::stopDrawing() {
194 mRenderThread.removeFrameCallback(this);
197 void CanvasContext::notifyFramePending() {
199 mRenderThread.pushBackFrameCallback(this);
202 void CanvasContext::draw() {
203 LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE,
204 "drawRenderNode called on a context with no canvas or surface!");
206 profiler().markPlaybackStart();
209 mDamageAccumulator.finish(&dirty);
211 EGLint width, height;
212 mEglManager.beginFrame(mEglSurface, &width, &height);
213 if (width != mCanvas->getViewportWidth() || height != mCanvas->getViewportHeight()) {
214 mCanvas->setViewport(width, height);
216 } else if (!mBufferPreserved || mHaveNewSurface) {
219 if (!dirty.isEmpty() && !dirty.intersect(0, 0, width, height)) {
220 ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?",
221 SK_RECT_ARGS(dirty), width, height);
224 profiler().unionDirty(&dirty);
228 if (!dirty.isEmpty()) {
229 status = mCanvas->prepareDirty(dirty.fLeft, dirty.fTop,
230 dirty.fRight, dirty.fBottom, mOpaque);
232 status = mCanvas->prepare(mOpaque);
236 status |= mCanvas->drawRenderNode(mRootRenderNode.get(), outBounds);
238 profiler().draw(mCanvas);
242 profiler().markPlaybackEnd();
244 if (status & DrawGlInfo::kStatusDrew) {
247 mEglManager.cancelFrame();
250 profiler().finishFrame();
253 // Called by choreographer to do an RT-driven animation
254 void CanvasContext::doFrame() {
255 if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) {
261 profiler().startFrame();
263 TreeInfo info(TreeInfo::MODE_RT_ONLY, mRenderThread.renderState());
265 if (info.out.canDrawThisFrame) {
270 void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) {
272 DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
273 if (thread.eglManager().hasEglContext()) {
274 thread.eglManager().requireGlContext();
275 mode = DrawGlInfo::kModeProcess;
278 thread.renderState().invokeFunctor(functor, mode, NULL);
281 void CanvasContext::markLayerInUse(RenderNode* node) {
282 if (mPrefetechedLayers.erase(node)) {
287 static void destroyPrefetechedNode(RenderNode* node) {
288 ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...", node->getName());
289 node->destroyHardwareResources();
293 void CanvasContext::freePrefetechedLayers() {
294 if (mPrefetechedLayers.size()) {
296 std::for_each(mPrefetechedLayers.begin(), mPrefetechedLayers.end(), destroyPrefetechedNode);
297 mPrefetechedLayers.clear();
301 void CanvasContext::buildLayer(RenderNode* node) {
303 if (!mEglManager.hasEglContext() || !mCanvas) {
307 // buildLayer() will leave the tree in an unknown state, so we must stop drawing
310 TreeInfo info(TreeInfo::MODE_FULL, mRenderThread.renderState());
311 info.damageAccumulator = &mDamageAccumulator;
312 info.renderer = mCanvas;
313 info.runAnimations = false;
314 node->prepareTree(info);
316 mDamageAccumulator.finish(&ignore);
317 // Tickle the GENERIC property on node to mark it as dirty for damaging
318 // purposes when the frame is actually drawn
319 node->setPropertyFieldsDirty(RenderNode::GENERIC);
321 mCanvas->markLayersAsBuildLayers();
322 mCanvas->flushLayerUpdates();
325 mPrefetechedLayers.insert(node);
328 bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) {
331 return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap);
334 void CanvasContext::destroyHardwareResources() {
336 if (mEglManager.hasEglContext()) {
338 freePrefetechedLayers();
339 mRootRenderNode->destroyHardwareResources();
340 Caches::getInstance().flush(Caches::kFlushMode_Layers);
344 void CanvasContext::trimMemory(RenderThread& thread, int level) {
345 // No context means nothing to free
346 if (!thread.eglManager().hasEglContext()) return;
349 thread.eglManager().requireGlContext();
350 if (level >= TRIM_MEMORY_COMPLETE) {
351 Caches::getInstance().flush(Caches::kFlushMode_Full);
352 thread.eglManager().destroy();
353 } else if (level >= TRIM_MEMORY_UI_HIDDEN) {
354 Caches::getInstance().flush(Caches::kFlushMode_Moderate);
358 void CanvasContext::runWithGlContext(RenderTask* task) {
363 Layer* CanvasContext::createTextureLayer() {
365 return LayerRenderer::createTextureLayer(mRenderThread.renderState());
368 void CanvasContext::requireGlContext() {
369 mEglManager.requireGlContext();
372 void CanvasContext::setTextureAtlas(RenderThread& thread,
373 const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) {
374 thread.eglManager().setTextureAtlas(buffer, map, mapSize);
377 } /* namespace renderthread */
378 } /* namespace uirenderer */
379 } /* namespace android */