summaryrefslogtreecommitdiffstats
path: root/libs/hwui
diff options
context:
space:
mode:
Diffstat (limited to 'libs/hwui')
-rw-r--r--libs/hwui/Caches.cpp42
-rw-r--r--libs/hwui/DeferredDisplayList.cpp11
-rw-r--r--libs/hwui/DeferredDisplayList.h5
-rw-r--r--libs/hwui/DeferredLayerUpdater.cpp21
-rw-r--r--libs/hwui/DisplayList.cpp5
-rw-r--r--libs/hwui/DisplayList.h7
-rw-r--r--libs/hwui/DisplayListOp.h5
-rw-r--r--libs/hwui/DisplayListRenderer.cpp24
-rw-r--r--libs/hwui/DisplayListRenderer.h6
-rw-r--r--libs/hwui/DrawProfiler.cpp50
-rw-r--r--libs/hwui/DrawProfiler.h4
-rw-r--r--libs/hwui/Layer.cpp19
-rw-r--r--libs/hwui/Layer.h8
-rw-r--r--libs/hwui/LayerCache.cpp2
-rw-r--r--libs/hwui/LayerRenderer.cpp14
-rw-r--r--libs/hwui/LayerRenderer.h1
-rwxr-xr-xlibs/hwui/OpenGLRenderer.cpp96
-rwxr-xr-xlibs/hwui/OpenGLRenderer.h16
-rw-r--r--libs/hwui/Program.h6
-rw-r--r--libs/hwui/ProgramCache.cpp13
-rw-r--r--libs/hwui/Properties.h9
-rw-r--r--libs/hwui/RenderNode.cpp21
-rw-r--r--libs/hwui/RenderNode.h2
-rw-r--r--libs/hwui/RenderState.cpp37
-rw-r--r--libs/hwui/RenderState.h19
-rw-r--r--libs/hwui/Renderer.h11
-rw-r--r--libs/hwui/ResourceCache.cpp23
-rw-r--r--libs/hwui/ResourceCache.h7
-rw-r--r--libs/hwui/SpotShadow.cpp223
-rw-r--r--libs/hwui/SpotShadow.h7
-rw-r--r--libs/hwui/renderthread/CanvasContext.cpp15
-rw-r--r--libs/hwui/renderthread/CanvasContext.h11
-rw-r--r--libs/hwui/renderthread/EglManager.cpp59
-rw-r--r--libs/hwui/renderthread/EglManager.h14
-rw-r--r--libs/hwui/renderthread/RenderProxy.cpp54
-rw-r--r--libs/hwui/renderthread/RenderProxy.h8
-rw-r--r--libs/hwui/renderthread/RenderThread.cpp2
-rw-r--r--libs/hwui/tests/Android.mk55
-rw-r--r--libs/hwui/tests/TestContext.cpp45
-rw-r--r--libs/hwui/tests/TestContext.h33
-rw-r--r--libs/hwui/tests/main.cpp131
41 files changed, 608 insertions, 533 deletions
diff --git a/libs/hwui/Caches.cpp b/libs/hwui/Caches.cpp
index f0bf7b2..ad50894 100644
--- a/libs/hwui/Caches.cpp
+++ b/libs/hwui/Caches.cpp
@@ -265,14 +265,27 @@ void Caches::dumpMemoryUsage() {
}
void Caches::dumpMemoryUsage(String8 &log) {
+ uint32_t total = 0;
log.appendFormat("Current memory usage / total memory usage (bytes):\n");
log.appendFormat(" TextureCache %8d / %8d\n",
textureCache.getSize(), textureCache.getMaxSize());
log.appendFormat(" LayerCache %8d / %8d (numLayers = %zu)\n",
layerCache.getSize(), layerCache.getMaxSize(), layerCache.getCount());
- log.appendFormat(" Garbage layers %8zu\n", mLayerGarbage.size());
- log.appendFormat(" Active layers %8zu\n",
- mRenderState ? mRenderState->mActiveLayers.size() : 0);
+ if (mRenderState) {
+ int memused = 0;
+ for (std::set<const Layer*>::iterator it = mRenderState->mActiveLayers.begin();
+ it != mRenderState->mActiveLayers.end(); it++) {
+ const Layer* layer = *it;
+ log.appendFormat(" Layer size %dx%d; isTextureLayer()=%d; texid=%u fbo=%u; refs=%d\n",
+ layer->getWidth(), layer->getHeight(),
+ layer->isTextureLayer(), layer->getTexture(),
+ layer->getFbo(), layer->getStrongCount());
+ memused = layer->getWidth() * layer->getHeight() * 4;
+ }
+ log.appendFormat(" Layers total %8d (numLayers = %zu)\n",
+ memused, mRenderState->mActiveLayers.size());
+ total += memused;
+ }
log.appendFormat(" RenderBufferCache %8d / %8d\n",
renderBufferCache.getSize(), renderBufferCache.getMaxSize());
log.appendFormat(" GradientCache %8d / %8d\n",
@@ -297,9 +310,7 @@ void Caches::dumpMemoryUsage(String8 &log) {
log.appendFormat(" FboCache %8d / %8d\n",
fboCache.getSize(), fboCache.getMaxSize());
- uint32_t total = 0;
total += textureCache.getSize();
- total += layerCache.getSize();
total += renderBufferCache.getSize();
total += gradientCache.getSize();
total += pathCache.getSize();
@@ -323,27 +334,6 @@ void Caches::clearGarbage() {
textureCache.clearGarbage();
pathCache.clearGarbage();
patchCache.clearGarbage();
-
- Vector<Layer*> layers;
-
- { // scope for the lock
- Mutex::Autolock _l(mGarbageLock);
- layers = mLayerGarbage;
- mLayerGarbage.clear();
- }
-
- size_t count = layers.size();
- for (size_t i = 0; i < count; i++) {
- Layer* layer = layers.itemAt(i);
- delete layer;
- }
- layers.clear();
-}
-
-void Caches::deleteLayerDeferred(Layer* layer) {
- Mutex::Autolock _l(mGarbageLock);
- layer->state = Layer::kState_InGarbageList;
- mLayerGarbage.push(layer);
}
void Caches::flush(FlushMode mode) {
diff --git a/libs/hwui/DeferredDisplayList.cpp b/libs/hwui/DeferredDisplayList.cpp
index a998594..fab4a1a 100644
--- a/libs/hwui/DeferredDisplayList.cpp
+++ b/libs/hwui/DeferredDisplayList.cpp
@@ -525,7 +525,7 @@ void DeferredDisplayList::addDrawOp(OpenGLRenderer& renderer, DrawOp* op) {
deferInfo.mergeable &= !recordingComplexClip();
deferInfo.opaqueOverBounds &= !recordingComplexClip() && mSaveStack.isEmpty();
- if (CC_LIKELY(mAvoidOverdraw) && mBatches.size() &&
+ if (mBatches.size() &&
state->mClipSideFlags != kClipSide_ConservativeFull &&
deferInfo.opaqueOverBounds && state->mBounds.contains(mBounds)) {
// avoid overdraw by resetting drawing state + discarding drawing ops
@@ -677,13 +677,12 @@ status_t DeferredDisplayList::flush(OpenGLRenderer& renderer, Rect& dirty) {
DrawModifiers restoreDrawModifiers = renderer.getDrawModifiers();
renderer.save(SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
- if (CC_LIKELY(mAvoidOverdraw)) {
- for (unsigned int i = 1; i < mBatches.size(); i++) {
- if (mBatches[i] && mBatches[i]->coversBounds(mBounds)) {
- discardDrawingBatches(i - 1);
- }
+ for (unsigned int i = 1; i < mBatches.size(); i++) {
+ if (mBatches[i] && mBatches[i]->coversBounds(mBounds)) {
+ discardDrawingBatches(i - 1);
}
}
+
// NOTE: depth of the save stack at this point, before playback, should be reflected in
// FLUSH_SAVE_STACK_DEPTH, so that save/restores match up correctly
status |= replayBatchList(mBatches, renderer, dirty);
diff --git a/libs/hwui/DeferredDisplayList.h b/libs/hwui/DeferredDisplayList.h
index 8a015b2..885b411 100644
--- a/libs/hwui/DeferredDisplayList.h
+++ b/libs/hwui/DeferredDisplayList.h
@@ -81,8 +81,8 @@ public:
class DeferredDisplayList {
friend class DeferStateStruct; // used to give access to allocator
public:
- DeferredDisplayList(const Rect& bounds, bool avoidOverdraw = true) :
- mBounds(bounds), mAvoidOverdraw(avoidOverdraw) {
+ DeferredDisplayList(const Rect& bounds) :
+ mBounds(bounds) {
clear();
}
~DeferredDisplayList() { clear(); }
@@ -150,7 +150,6 @@ private:
// layer space bounds of rendering
Rect mBounds;
- const bool mAvoidOverdraw;
/**
* At defer time, stores the *defer time* savecount of save/saveLayer ops that were deferred, so
diff --git a/libs/hwui/DeferredLayerUpdater.cpp b/libs/hwui/DeferredLayerUpdater.cpp
index a6d7e78..d02455c 100644
--- a/libs/hwui/DeferredLayerUpdater.cpp
+++ b/libs/hwui/DeferredLayerUpdater.cpp
@@ -24,25 +24,6 @@
namespace android {
namespace uirenderer {
-class DeleteLayerTask : public renderthread::RenderTask {
-public:
- DeleteLayerTask(renderthread::EglManager& eglManager, Layer* layer)
- : mEglManager(eglManager)
- , mLayer(layer)
- {}
-
- virtual void run() {
- mEglManager.requireGlContext();
- LayerRenderer::destroyLayer(mLayer);
- mLayer = 0;
- delete this;
- }
-
-private:
- renderthread::EglManager& mEglManager;
- Layer* mLayer;
-};
-
DeferredLayerUpdater::DeferredLayerUpdater(renderthread::RenderThread& thread, Layer* layer)
: mSurfaceTexture(0)
, mTransform(0)
@@ -62,7 +43,7 @@ DeferredLayerUpdater::DeferredLayerUpdater(renderthread::RenderThread& thread, L
DeferredLayerUpdater::~DeferredLayerUpdater() {
SkSafeUnref(mColorFilter);
setTransform(0);
- mRenderThread.queue(new DeleteLayerTask(mRenderThread.eglManager(), mLayer));
+ mLayer->postDecStrong();
mLayer = 0;
}
diff --git a/libs/hwui/DisplayList.cpp b/libs/hwui/DisplayList.cpp
index d8932ce..4a927cf 100644
--- a/libs/hwui/DisplayList.cpp
+++ b/libs/hwui/DisplayList.cpp
@@ -61,10 +61,6 @@ void DisplayListData::cleanupResources() {
caches.resourceCache.decrementRefcountLocked(sourcePaths.itemAt(i));
}
- for (size_t i = 0; i < layers.size(); i++) {
- caches.resourceCache.decrementRefcountLocked(layers.itemAt(i));
- }
-
caches.resourceCache.unlock();
for (size_t i = 0; i < paints.size(); i++) {
@@ -86,7 +82,6 @@ void DisplayListData::cleanupResources() {
paints.clear();
regions.clear();
paths.clear();
- layers.clear();
}
size_t DisplayListData::addChild(DrawRenderNodeOp* op) {
diff --git a/libs/hwui/DisplayList.h b/libs/hwui/DisplayList.h
index dea109c..cb8a8d1 100644
--- a/libs/hwui/DisplayList.h
+++ b/libs/hwui/DisplayList.h
@@ -147,7 +147,6 @@ public:
Vector<const SkPath*> paths;
SortedVector<const SkPath*> sourcePaths;
Vector<const SkRegion*> regions;
- Vector<Layer*> layers;
Vector<Functor*> functors;
const Vector<Chunk>& getChunks() const {
@@ -157,11 +156,7 @@ public:
size_t addChild(DrawRenderNodeOp* childOp);
const Vector<DrawRenderNodeOp*>& children() { return mChildren; }
- void refProperty(CanvasPropertyPrimitive* prop) {
- mReferenceHolders.push(prop);
- }
-
- void refProperty(CanvasPropertyPaint* prop) {
+ void ref(VirtualLightRefBase* prop) {
mReferenceHolders.push(prop);
}
diff --git a/libs/hwui/DisplayListOp.h b/libs/hwui/DisplayListOp.h
index cb3ef9b..d78c1cb 100644
--- a/libs/hwui/DisplayListOp.h
+++ b/libs/hwui/DisplayListOp.h
@@ -212,10 +212,13 @@ protected:
// check state/paint for transparency
if (mPaint) {
+ if (mPaint->getAlpha() != 0xFF) {
+ return false;
+ }
if (mPaint->getShader() && !mPaint->getShader()->isOpaque()) {
return false;
}
- if (mPaint->getAlpha() != 0xFF) {
+ if (Renderer::isBlendedColorFilter(mPaint->getColorFilter())) {
return false;
}
}
diff --git a/libs/hwui/DisplayListRenderer.cpp b/libs/hwui/DisplayListRenderer.cpp
index 1f70921..c17dd09 100644
--- a/libs/hwui/DisplayListRenderer.cpp
+++ b/libs/hwui/DisplayListRenderer.cpp
@@ -189,7 +189,7 @@ status_t DisplayListRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty
}
status_t DisplayListRenderer::drawLayer(Layer* layer, float x, float y) {
- layer = refLayer(layer);
+ mDisplayListData->ref(layer);
addDrawOp(new (alloc()) DrawLayerOp(layer, x, y));
return DrawGlInfo::kStatusDone;
}
@@ -280,13 +280,13 @@ status_t DisplayListRenderer::drawRoundRect(
CanvasPropertyPrimitive* right, CanvasPropertyPrimitive* bottom,
CanvasPropertyPrimitive* rx, CanvasPropertyPrimitive* ry,
CanvasPropertyPaint* paint) {
- mDisplayListData->refProperty(left);
- mDisplayListData->refProperty(top);
- mDisplayListData->refProperty(right);
- mDisplayListData->refProperty(bottom);
- mDisplayListData->refProperty(rx);
- mDisplayListData->refProperty(ry);
- mDisplayListData->refProperty(paint);
+ mDisplayListData->ref(left);
+ mDisplayListData->ref(top);
+ mDisplayListData->ref(right);
+ mDisplayListData->ref(bottom);
+ mDisplayListData->ref(rx);
+ mDisplayListData->ref(ry);
+ mDisplayListData->ref(paint);
addDrawOp(new (alloc()) DrawRoundRectPropsOp(&left->value, &top->value,
&right->value, &bottom->value, &rx->value, &ry->value, &paint->value));
return DrawGlInfo::kStatusDone;
@@ -300,10 +300,10 @@ status_t DisplayListRenderer::drawCircle(float x, float y, float radius, const S
status_t DisplayListRenderer::drawCircle(CanvasPropertyPrimitive* x, CanvasPropertyPrimitive* y,
CanvasPropertyPrimitive* radius, CanvasPropertyPaint* paint) {
- mDisplayListData->refProperty(x);
- mDisplayListData->refProperty(y);
- mDisplayListData->refProperty(radius);
- mDisplayListData->refProperty(paint);
+ mDisplayListData->ref(x);
+ mDisplayListData->ref(y);
+ mDisplayListData->ref(radius);
+ mDisplayListData->ref(paint);
addDrawOp(new (alloc()) DrawCirclePropsOp(&x->value, &y->value,
&radius->value, &paint->value));
return DrawGlInfo::kStatusDone;
diff --git a/libs/hwui/DisplayListRenderer.h b/libs/hwui/DisplayListRenderer.h
index 3a3fc3a..901e8f0 100644
--- a/libs/hwui/DisplayListRenderer.h
+++ b/libs/hwui/DisplayListRenderer.h
@@ -267,12 +267,6 @@ private:
return regionCopy;
}
- inline Layer* refLayer(Layer* layer) {
- mDisplayListData->layers.add(layer);
- mCaches.resourceCache.incrementRefcount(layer);
- return layer;
- }
-
inline const SkBitmap* refBitmap(const SkBitmap* bitmap) {
// Note that this assumes the bitmap is immutable. There are cases this won't handle
// correctly, such as creating the bitmap from scratch, drawing with it, changing its
diff --git a/libs/hwui/DrawProfiler.cpp b/libs/hwui/DrawProfiler.cpp
index 2409554..e590642 100644
--- a/libs/hwui/DrawProfiler.cpp
+++ b/libs/hwui/DrawProfiler.cpp
@@ -22,7 +22,8 @@
#define DEFAULT_MAX_FRAMES 128
-#define RETURN_IF_DISABLED() if (CC_LIKELY(mType == kNone)) return
+#define RETURN_IF_PROFILING_DISABLED() if (CC_LIKELY(mType == kNone)) return
+#define RETURN_IF_DISABLED() if (CC_LIKELY(mType == kNone && !mShowDirtyRegions)) return
#define NANOS_TO_MILLIS_FLOAT(nanos) ((nanos) * 0.000001f)
@@ -64,7 +65,9 @@ DrawProfiler::DrawProfiler()
, mPreviousTime(0)
, mVerticalUnit(0)
, mHorizontalUnit(0)
- , mThresholdStroke(0) {
+ , mThresholdStroke(0)
+ , mShowDirtyRegions(false)
+ , mFlashToggle(false) {
setDensity(1);
}
@@ -82,27 +85,27 @@ void DrawProfiler::setDensity(float density) {
}
void DrawProfiler::startFrame(nsecs_t recordDurationNanos) {
- RETURN_IF_DISABLED();
+ RETURN_IF_PROFILING_DISABLED();
mData[mCurrentFrame].record = NANOS_TO_MILLIS_FLOAT(recordDurationNanos);
mPreviousTime = systemTime(CLOCK_MONOTONIC);
}
void DrawProfiler::markPlaybackStart() {
- RETURN_IF_DISABLED();
+ RETURN_IF_PROFILING_DISABLED();
nsecs_t now = systemTime(CLOCK_MONOTONIC);
mData[mCurrentFrame].prepare = NANOS_TO_MILLIS_FLOAT(now - mPreviousTime);
mPreviousTime = now;
}
void DrawProfiler::markPlaybackEnd() {
- RETURN_IF_DISABLED();
+ RETURN_IF_PROFILING_DISABLED();
nsecs_t now = systemTime(CLOCK_MONOTONIC);
mData[mCurrentFrame].playback = NANOS_TO_MILLIS_FLOAT(now - mPreviousTime);
mPreviousTime = now;
}
void DrawProfiler::finishFrame() {
- RETURN_IF_DISABLED();
+ RETURN_IF_PROFILING_DISABLED();
nsecs_t now = systemTime(CLOCK_MONOTONIC);
mData[mCurrentFrame].swapBuffers = NANOS_TO_MILLIS_FLOAT(now - mPreviousTime);
mPreviousTime = now;
@@ -114,19 +117,30 @@ void DrawProfiler::unionDirty(SkRect* dirty) {
// Not worth worrying about minimizing the dirty region for debugging, so just
// dirty the entire viewport.
if (dirty) {
+ mDirtyRegion = *dirty;
dirty->setEmpty();
}
}
void DrawProfiler::draw(OpenGLRenderer* canvas) {
- if (CC_LIKELY(mType != kBars)) {
- return;
+ RETURN_IF_DISABLED();
+
+ if (mShowDirtyRegions) {
+ mFlashToggle = !mFlashToggle;
+ if (mFlashToggle) {
+ SkPaint paint;
+ paint.setColor(0x7fff0000);
+ canvas->drawRect(mDirtyRegion.fLeft, mDirtyRegion.fTop,
+ mDirtyRegion.fRight, mDirtyRegion.fBottom, &paint);
+ }
}
- prepareShapes(canvas->getViewportHeight());
- drawGraph(canvas);
- drawCurrentFrame(canvas);
- drawThreshold(canvas);
+ if (mType == kBars) {
+ prepareShapes(canvas->getViewportHeight());
+ drawGraph(canvas);
+ drawCurrentFrame(canvas);
+ drawThreshold(canvas);
+ }
}
void DrawProfiler::createData() {
@@ -217,6 +231,7 @@ DrawProfiler::ProfileType DrawProfiler::loadRequestedProfileType() {
}
bool DrawProfiler::loadSystemProperties() {
+ bool changed = false;
ProfileType newType = loadRequestedProfileType();
if (newType != mType) {
mType = newType;
@@ -225,13 +240,18 @@ bool DrawProfiler::loadSystemProperties() {
} else {
createData();
}
- return true;
+ changed = true;
}
- return false;
+ bool showDirty = property_get_bool(PROPERTY_DEBUG_SHOW_DIRTY_REGIONS, false);
+ if (showDirty != mShowDirtyRegions) {
+ mShowDirtyRegions = showDirty;
+ changed = true;
+ }
+ return changed;
}
void DrawProfiler::dumpData(int fd) {
- RETURN_IF_DISABLED();
+ RETURN_IF_PROFILING_DISABLED();
// This method logs the last N frames (where N is <= mDataSize) since the
// last call to dumpData(). In other words if there's a dumpData(), draw frame,
diff --git a/libs/hwui/DrawProfiler.h b/libs/hwui/DrawProfiler.h
index 7c06e5d..de64088 100644
--- a/libs/hwui/DrawProfiler.h
+++ b/libs/hwui/DrawProfiler.h
@@ -88,6 +88,10 @@ private:
* information.
*/
float** mRects;
+
+ bool mShowDirtyRegions;
+ SkRect mDirtyRegion;
+ bool mFlashToggle;
};
} /* namespace uirenderer */
diff --git a/libs/hwui/Layer.cpp b/libs/hwui/Layer.cpp
index b5089aa..b95636b 100644
--- a/libs/hwui/Layer.cpp
+++ b/libs/hwui/Layer.cpp
@@ -35,6 +35,9 @@ Layer::Layer(Type layerType, RenderState& renderState, const uint32_t layerWidth
, renderState(renderState)
, texture(caches)
, type(layerType) {
+ // TODO: This is a violation of Android's typical ref counting, but it
+ // preserves the old inc/dec ref locations. This should be changed...
+ incStrong(0);
mesh = NULL;
meshElementCount = 0;
cacheable = true;
@@ -53,20 +56,14 @@ Layer::Layer(Type layerType, RenderState& renderState, const uint32_t layerWidth
forceFilter = false;
deferredList = NULL;
convexMask = NULL;
- caches.resourceCache.incrementRefcount(this);
rendererLightPosDirty = true;
wasBuildLayered = false;
- if (!isTextureLayer()) {
- // track only non-texture layer lifecycles in renderstate,
- // because texture layers are destroyed via finalizer
- renderState.registerLayer(this);
- }
+ renderState.registerLayer(this);
}
Layer::~Layer() {
- if (!isTextureLayer()) {
- renderState.unregisterLayer(this);
- }
+ renderState.requireGLContext();
+ renderState.unregisterLayer(this);
SkSafeUnref(colorFilter);
removeFbo();
deleteTexture();
@@ -292,5 +289,9 @@ void Layer::render(const OpenGLRenderer& rootRenderer) {
renderNode = NULL;
}
+void Layer::postDecStrong() {
+ renderState.postDecStrong(this);
+}
+
}; // namespace uirenderer
}; // namespace android
diff --git a/libs/hwui/Layer.h b/libs/hwui/Layer.h
index a8e1c26..64d1d12 100644
--- a/libs/hwui/Layer.h
+++ b/libs/hwui/Layer.h
@@ -52,7 +52,7 @@ class DeferStateStruct;
/**
* A layer has dimensions and is backed by an OpenGL texture or FBO.
*/
-class Layer {
+class Layer : public VirtualLightRefBase {
public:
enum Type {
kType_Texture,
@@ -280,6 +280,12 @@ public:
void render(const OpenGLRenderer& rootRenderer);
/**
+ * Posts a decStrong call to the appropriate thread.
+ * Thread-safe.
+ */
+ void postDecStrong();
+
+ /**
* Bounds of the layer.
*/
Rect layer;
diff --git a/libs/hwui/LayerCache.cpp b/libs/hwui/LayerCache.cpp
index 833f64b..3033dc6 100644
--- a/libs/hwui/LayerCache.cpp
+++ b/libs/hwui/LayerCache.cpp
@@ -84,7 +84,7 @@ void LayerCache::deleteLayer(Layer* layer) {
layer->getFbo());
mSize -= layer->getWidth() * layer->getHeight() * 4;
layer->state = Layer::kState_DeletedFromCache;
- Caches::getInstance().resourceCache.decrementRefcount(layer);
+ layer->decStrong(0);
}
}
diff --git a/libs/hwui/LayerRenderer.cpp b/libs/hwui/LayerRenderer.cpp
index 103c843..394c647 100644
--- a/libs/hwui/LayerRenderer.cpp
+++ b/libs/hwui/LayerRenderer.cpp
@@ -212,7 +212,7 @@ Layer* LayerRenderer::createRenderLayer(RenderState& renderState, uint32_t width
// Creating a new layer always increment its refcount by 1, this allows
// us to destroy the layer object if one was created for us
- Caches::getInstance().resourceCache.decrementRefcount(layer);
+ layer->decStrong(0);
return NULL;
}
@@ -240,7 +240,7 @@ Layer* LayerRenderer::createRenderLayer(RenderState& renderState, uint32_t width
if (glGetError() != GL_NO_ERROR) {
ALOGE("Could not allocate texture for layer (fbo=%d %dx%d)", fbo, width, height);
renderState.bindFramebuffer(previousFbo);
- caches.resourceCache.decrementRefcount(layer);
+ layer->decStrong(0);
return NULL;
}
}
@@ -316,7 +316,7 @@ void LayerRenderer::destroyLayer(Layer* layer) {
if (!Caches::getInstance().layerCache.put(layer)) {
LAYER_RENDERER_LOGD(" Destroyed!");
- Caches::getInstance().resourceCache.decrementRefcount(layer);
+ layer->decStrong(0);
} else {
LAYER_RENDERER_LOGD(" Cached!");
#if DEBUG_LAYER_RENDERER
@@ -328,14 +328,6 @@ void LayerRenderer::destroyLayer(Layer* layer) {
}
}
-void LayerRenderer::destroyLayerDeferred(Layer* layer) {
- if (layer) {
- LAYER_RENDERER_LOGD("Deferring layer destruction, fbo = %d", layer->getFbo());
-
- Caches::getInstance().deleteLayerDeferred(layer);
- }
-}
-
void LayerRenderer::flushLayer(RenderState& renderState, Layer* layer) {
#ifdef GL_EXT_discard_framebuffer
if (!layer) return;
diff --git a/libs/hwui/LayerRenderer.h b/libs/hwui/LayerRenderer.h
index bf7828c..4d8620b 100644
--- a/libs/hwui/LayerRenderer.h
+++ b/libs/hwui/LayerRenderer.h
@@ -60,7 +60,6 @@ public:
static void updateTextureLayer(Layer* layer, uint32_t width, uint32_t height,
bool isOpaque, bool forceFilter, GLenum renderTarget, float* textureTransform);
static void destroyLayer(Layer* layer);
- ANDROID_API static void destroyLayerDeferred(Layer* layer);
static bool copyLayer(RenderState& renderState, Layer* layer, SkBitmap* bitmap);
static void flushLayer(RenderState& renderState, Layer* layer);
diff --git a/libs/hwui/OpenGLRenderer.cpp b/libs/hwui/OpenGLRenderer.cpp
index ce1d09f..d570b0d 100755
--- a/libs/hwui/OpenGLRenderer.cpp
+++ b/libs/hwui/OpenGLRenderer.cpp
@@ -51,6 +51,21 @@
#define EVENT_LOGD(...)
#endif
+static void atraceFormatBegin(const char* fmt, ...) {
+ const int BUFFER_SIZE = 256;
+ va_list ap;
+ char buf[BUFFER_SIZE];
+
+ va_start(ap, fmt);
+ vsnprintf(buf, BUFFER_SIZE, fmt, ap);
+ va_end(ap);
+
+ ATRACE_BEGIN(buf);
+}
+
+#define ATRACE_FORMAT_BEGIN(fmt, ...) \
+ if (CC_UNLIKELY(ATRACE_ENABLED())) atraceFormatBegin(fmt, ##__VA_ARGS__)
+
namespace android {
namespace uirenderer {
@@ -136,7 +151,6 @@ OpenGLRenderer::OpenGLRenderer(RenderState& renderState)
, mScissorOptimizationDisabled(false)
, mSuppressTiling(false)
, mFirstFrameAfterResize(true)
- , mCountOverdraw(false)
, mLightCenter((Vector3){FLT_MIN, FLT_MIN, FLT_MIN})
, mLightRadius(FLT_MIN)
, mAmbientShadowAlpha(0)
@@ -251,7 +265,7 @@ void OpenGLRenderer::discardFramebuffer(float left, float top, float right, floa
}
status_t OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) {
- if (!opaque || mCountOverdraw) {
+ if (!opaque) {
mCaches.enableScissor();
mCaches.setScissor(left, getViewportHeight() - bottom, right - left, bottom - top);
glClear(GL_COLOR_BUFFER_BIT);
@@ -332,10 +346,6 @@ void OpenGLRenderer::finish() {
#endif
}
- if (mCountOverdraw) {
- countOverdraw();
- }
-
mFrameStarted = false;
}
@@ -449,21 +459,6 @@ void OpenGLRenderer::renderOverdraw() {
}
}
-void OpenGLRenderer::countOverdraw() {
- size_t count = getWidth() * getHeight();
- uint32_t* buffer = new uint32_t[count];
- glReadPixels(0, 0, getWidth(), getHeight(), GL_RGBA, GL_UNSIGNED_BYTE, &buffer[0]);
-
- size_t total = 0;
- for (size_t i = 0; i < count; i++) {
- total += buffer[i] & 0xff;
- }
-
- mOverdraw = total / float(count);
-
- delete[] buffer;
-}
-
///////////////////////////////////////////////////////////////////////////////
// Layers
///////////////////////////////////////////////////////////////////////////////
@@ -514,11 +509,8 @@ void OpenGLRenderer::updateLayers() {
// Note: it is very important to update the layers in order
for (int i = 0; i < count; i++) {
- Layer* layer = mLayerUpdates.itemAt(i);
+ Layer* layer = mLayerUpdates.itemAt(i).get();
updateLayer(layer, false);
- if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
- mCaches.resourceCache.decrementRefcount(layer);
- }
}
if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
@@ -537,16 +529,15 @@ void OpenGLRenderer::flushLayers() {
// Note: it is very important to update the layers in order
for (int i = 0; i < count; i++) {
+ Layer* layer = mLayerUpdates.itemAt(i).get();
+
sprintf(layerName, "Layer #%d", i);
startMark(layerName);
+ ATRACE_FORMAT_BEGIN("flushLayer %ux%u", layer->getWidth(), layer->getHeight());
- ATRACE_BEGIN("flushLayer");
- Layer* layer = mLayerUpdates.itemAt(i);
layer->flush();
- ATRACE_END();
-
- mCaches.resourceCache.decrementRefcount(layer);
+ ATRACE_END();
endMark();
}
@@ -569,7 +560,6 @@ void OpenGLRenderer::pushLayerUpdate(Layer* layer) {
}
}
mLayerUpdates.push_back(layer);
- mCaches.resourceCache.incrementRefcount(layer);
}
}
@@ -578,25 +568,12 @@ void OpenGLRenderer::cancelLayerUpdate(Layer* layer) {
for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
if (mLayerUpdates.itemAt(i) == layer) {
mLayerUpdates.removeAt(i);
- mCaches.resourceCache.decrementRefcount(layer);
break;
}
}
}
}
-void OpenGLRenderer::clearLayerUpdates() {
- size_t count = mLayerUpdates.size();
- if (count > 0) {
- mCaches.resourceCache.lock();
- for (size_t i = 0; i < count; i++) {
- mCaches.resourceCache.decrementRefcountLocked(mLayerUpdates.itemAt(i));
- }
- mCaches.resourceCache.unlock();
- mLayerUpdates.clear();
- }
-}
-
void OpenGLRenderer::flushLayerUpdates() {
ATRACE_CALL();
syncState();
@@ -631,6 +608,7 @@ void OpenGLRenderer::onSnapshotRestored(const Snapshot& removed, const Snapshot&
if (restoreLayer) {
endMark(); // Savelayer
+ ATRACE_END(); // SaveLayer
startMark("ComposeLayer");
composeLayer(removed, restored);
endMark();
@@ -814,6 +792,9 @@ bool OpenGLRenderer::createLayer(float left, float top, float right, float botto
mSnapshot->flags |= Snapshot::kFlagIsLayer;
mSnapshot->layer = layer;
+ ATRACE_FORMAT_BEGIN("%ssaveLayer %ux%u",
+ fboLayer ? "" : "unclipped ",
+ layer->getWidth(), layer->getHeight());
startMark("SaveLayer");
if (fboLayer) {
return createFboLayer(layer, bounds, clip);
@@ -956,7 +937,7 @@ void OpenGLRenderer::composeLayer(const Snapshot& removed, const Snapshot& resto
layer->setConvexMask(NULL);
if (!mCaches.layerCache.put(layer)) {
LAYER_LOGD("Deleting layer");
- Caches::getInstance().resourceCache.decrementRefcount(layer);
+ layer->decStrong(0);
}
}
@@ -1627,8 +1608,6 @@ void OpenGLRenderer::setupDraw(bool clearLayer) {
mDescription.hasDebugHighlight = !mCaches.debugOverdraw &&
mCaches.debugStencilClip == Caches::kStencilShowHighlight &&
mCaches.stencil.isTestEnabled();
-
- mDescription.emulateStencil = mCountOverdraw;
}
void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
@@ -1714,13 +1693,6 @@ void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
}
}
-static bool isBlendedColorFilter(const SkColorFilter* filter) {
- if (filter == NULL) {
- return false;
- }
- return (filter->getFlags() & SkColorFilter::kAlphaUnchanged_Flag) == 0;
-}
-
void OpenGLRenderer::setupDrawBlending(const Layer* layer, bool swapSrcDst) {
SkXfermode::Mode mode = layer->getMode();
// When the blending mode is kClear_Mode, we need to use a modulate color
@@ -1967,8 +1939,7 @@ status_t OpenGLRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty, int
return status | replayStruct.mDrawGlStatus;
}
- bool avoidOverdraw = !mCaches.debugOverdraw && !mCountOverdraw; // shh, don't tell devs!
- DeferredDisplayList deferredList(*currentClipRect(), avoidOverdraw);
+ DeferredDisplayList deferredList(*currentClipRect());
DeferStateStruct deferStruct(deferredList, *this, replayFlags);
renderNode->defer(deferStruct, 0);
@@ -3440,19 +3411,6 @@ void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
}
mSkipOutlineClip = true;
- if (mCountOverdraw) {
- if (!mCaches.blend) glEnable(GL_BLEND);
- if (mCaches.lastSrcMode != GL_ONE || mCaches.lastDstMode != GL_ONE) {
- glBlendFunc(GL_ONE, GL_ONE);
- }
-
- mCaches.blend = true;
- mCaches.lastSrcMode = GL_ONE;
- mCaches.lastDstMode = GL_ONE;
-
- return;
- }
-
blend = blend || mode != SkXfermode::kSrcOver_Mode;
if (blend) {
diff --git a/libs/hwui/OpenGLRenderer.h b/libs/hwui/OpenGLRenderer.h
index 47ef1a9..e1c3d10 100755
--- a/libs/hwui/OpenGLRenderer.h
+++ b/libs/hwui/OpenGLRenderer.h
@@ -136,19 +136,10 @@ public:
virtual status_t prepareDirty(float left, float top, float right, float bottom, bool opaque);
virtual void finish();
- void setCountOverdrawEnabled(bool enabled) {
- mCountOverdraw = enabled;
- }
-
- float getOverdraw() {
- return mCountOverdraw ? mOverdraw : 0.0f;
- }
-
virtual status_t callDrawGLFunction(Functor* functor, Rect& dirty);
void pushLayerUpdate(Layer* layer);
void cancelLayerUpdate(Layer* layer);
- void clearLayerUpdates();
void flushLayerUpdates();
void markLayersAsBuildLayers();
@@ -990,7 +981,7 @@ private:
// List of rectangles to clear after saveLayer() is invoked
Vector<Rect*> mLayers;
// List of layers to update at the beginning of a frame
- Vector<Layer*> mLayerUpdates;
+ Vector< sp<Layer> > mLayerUpdates;
// The following fields are used to setup drawing
// Used to describe the shaders to generate
@@ -1015,11 +1006,6 @@ private:
bool mSuppressTiling;
bool mFirstFrameAfterResize;
- // If true, this renderer will setup drawing to emulate
- // an increment stencil buffer in the color buffer
- bool mCountOverdraw;
- float mOverdraw;
-
bool mSkipOutlineClip;
// Lighting + shadows
diff --git a/libs/hwui/Program.h b/libs/hwui/Program.h
index 56773f4..d05b331 100644
--- a/libs/hwui/Program.h
+++ b/libs/hwui/Program.h
@@ -84,8 +84,7 @@ namespace uirenderer {
#define PROGRAM_HAS_COLORS 42
#define PROGRAM_HAS_DEBUG_HIGHLIGHT 43
-#define PROGRAM_EMULATE_STENCIL 44
-#define PROGRAM_HAS_ROUND_RECT_CLIP 45
+#define PROGRAM_HAS_ROUND_RECT_CLIP 44
///////////////////////////////////////////////////////////////////////////////
// Types
@@ -161,7 +160,6 @@ struct ProgramDescription {
float gamma;
bool hasDebugHighlight;
- bool emulateStencil;
bool hasRoundRectClip;
/**
@@ -204,7 +202,6 @@ struct ProgramDescription {
gamma = 2.2f;
hasDebugHighlight = false;
- emulateStencil = false;
hasRoundRectClip = false;
}
@@ -272,7 +269,6 @@ struct ProgramDescription {
if (isSimpleGradient) key |= programid(0x1) << PROGRAM_IS_SIMPLE_GRADIENT;
if (hasColors) key |= programid(0x1) << PROGRAM_HAS_COLORS;
if (hasDebugHighlight) key |= programid(0x1) << PROGRAM_HAS_DEBUG_HIGHLIGHT;
- if (emulateStencil) key |= programid(0x1) << PROGRAM_EMULATE_STENCIL;
if (hasRoundRectClip) key |= programid(0x1) << PROGRAM_HAS_ROUND_RECT_CLIP;
return key;
}
diff --git a/libs/hwui/ProgramCache.cpp b/libs/hwui/ProgramCache.cpp
index 06353c0..62835e0 100644
--- a/libs/hwui/ProgramCache.cpp
+++ b/libs/hwui/ProgramCache.cpp
@@ -347,12 +347,6 @@ const char* gFS_Main_FragColor_HasRoundRectClip =
const char* gFS_Main_DebugHighlight =
" gl_FragColor.rgb = vec3(0.0, gl_FragColor.a, 0.0);\n";
-const char* gFS_Main_EmulateStencil =
- " gl_FragColor.rgba = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 1.0);\n"
- " return;\n"
- " /*\n";
-const char* gFS_Footer_EmulateStencil =
- " */\n";
const char* gFS_Footer =
"}\n\n";
@@ -617,7 +611,6 @@ String8 ProgramCache::generateFragmentShader(const ProgramDescription& descripti
&& !description.hasColors
&& description.colorOp == ProgramDescription::kColorNone
&& !description.hasDebugHighlight
- && !description.emulateStencil
&& !description.hasRoundRectClip) {
bool fast = false;
@@ -698,9 +691,6 @@ String8 ProgramCache::generateFragmentShader(const ProgramDescription& descripti
// Begin the shader
shader.append(gFS_Main); {
- if (description.emulateStencil) {
- shader.append(gFS_Main_EmulateStencil);
- }
// Stores the result in fragColor directly
if (description.hasTexture || description.hasExternalTexture) {
if (description.hasAlpha8Texture) {
@@ -779,9 +769,6 @@ String8 ProgramCache::generateFragmentShader(const ProgramDescription& descripti
shader.append(gFS_Main_DebugHighlight);
}
}
- if (description.emulateStencil) {
- shader.append(gFS_Footer_EmulateStencil);
- }
// End the shader
shader.append(gFS_Footer);
diff --git a/libs/hwui/Properties.h b/libs/hwui/Properties.h
index 7eb9a32..befed16 100644
--- a/libs/hwui/Properties.h
+++ b/libs/hwui/Properties.h
@@ -133,6 +133,15 @@ enum DebugLevel {
#define PROPERTY_DEBUG_STENCIL_CLIP "debug.hwui.show_non_rect_clip"
/**
+ * Turn on to draw dirty regions every other frame.
+ *
+ * Possible values:
+ * "true", to enable dirty regions debugging
+ * "false", to disable dirty regions debugging
+ */
+#define PROPERTY_DEBUG_SHOW_DIRTY_REGIONS "debug.hwui.show_dirty_regions"
+
+/**
* Disables draw operation deferral if set to "true", forcing draw
* commands to be issued to OpenGL in order, and processed in sequence
* with state-manipulation canvas commands.
diff --git a/libs/hwui/RenderNode.cpp b/libs/hwui/RenderNode.cpp
index 254492f..c9ed9a7 100644
--- a/libs/hwui/RenderNode.cpp
+++ b/libs/hwui/RenderNode.cpp
@@ -50,10 +50,13 @@ void RenderNode::outputLogBuffer(int fd) {
fprintf(file, "\nRecent DisplayList operations\n");
logBuffer.outputCommands(file);
- String8 cachesLog;
- Caches::getInstance().dumpMemoryUsage(cachesLog);
- fprintf(file, "\nCaches:\n%s", cachesLog.string());
- fprintf(file, "\n");
+ if (Caches::hasInstance()) {
+ String8 cachesLog;
+ Caches::getInstance().dumpMemoryUsage(cachesLog);
+ fprintf(file, "\nCaches:\n%s\n", cachesLog.string());
+ } else {
+ fprintf(file, "\nNo caches instance.\n");
+ }
fflush(file);
}
@@ -84,7 +87,11 @@ RenderNode::RenderNode()
RenderNode::~RenderNode() {
deleteDisplayListData();
delete mStagingDisplayListData;
- LayerRenderer::destroyLayerDeferred(mLayer);
+ if (mLayer) {
+ ALOGW("Memory Warning: Layer %p missed its detachment, held on to for far too long!", mLayer);
+ mLayer->postDecStrong();
+ mLayer = 0;
+ }
}
void RenderNode::setStagingDisplayList(DisplayListData* data) {
@@ -198,6 +205,7 @@ void RenderNode::pushLayerUpdate(TreeInfo& info) {
info.damageAccumulator->peekAtDirty(&dirty);
if (!mLayer) {
+ Caches::getInstance().dumpMemoryUsage();
if (info.errorHandler) {
std::string msg = "Unable to create layer for ";
msg += getName();
@@ -293,6 +301,9 @@ void RenderNode::pushStagingDisplayListChanges(TreeInfo& info) {
mStagingDisplayListData->children()[i]->mRenderNode->incParentRefCount();
}
}
+ // Damage with the old display list first then the new one to catch any
+ // changes in isRenderable or, in the future, bounds
+ damageSelf(info);
deleteDisplayListData();
mDisplayListData = mStagingDisplayListData;
mStagingDisplayListData = NULL;
diff --git a/libs/hwui/RenderNode.h b/libs/hwui/RenderNode.h
index f329283..2ce7cb7 100644
--- a/libs/hwui/RenderNode.h
+++ b/libs/hwui/RenderNode.h
@@ -101,7 +101,7 @@ public:
kReplayFlag_ClipChildren = 0x1
};
- ANDROID_API static void outputLogBuffer(int fd);
+ static void outputLogBuffer(int fd);
void debugDumpLayers(const char* prefix);
ANDROID_API void setStagingDisplayList(DisplayListData* newData);
diff --git a/libs/hwui/RenderState.cpp b/libs/hwui/RenderState.cpp
index 86bd7dd..a8cf26f 100644
--- a/libs/hwui/RenderState.cpp
+++ b/libs/hwui/RenderState.cpp
@@ -16,15 +16,18 @@
#include "RenderState.h"
#include "renderthread/CanvasContext.h"
+#include "renderthread/EglManager.h"
namespace android {
namespace uirenderer {
-RenderState::RenderState()
- : mCaches(NULL)
+RenderState::RenderState(renderthread::RenderThread& thread)
+ : mRenderThread(thread)
+ , mCaches(NULL)
, mViewportWidth(0)
, mViewportHeight(0)
, mFramebuffer(0) {
+ mThreadId = pthread_self();
}
RenderState::~RenderState() {
@@ -39,7 +42,6 @@ void RenderState::onGLContextCreated() {
void RenderState::onGLContextDestroyed() {
/*
- AutoMutex _lock(mLayerLock);
size_t size = mActiveLayers.size();
if (CC_UNLIKELY(size != 0)) {
ALOGE("Crashing, have %d contexts and %d layers at context destruction. isempty %d",
@@ -146,5 +148,34 @@ void RenderState::debugOverdraw(bool enable, bool clear) {
}
}
+void RenderState::requireGLContext() {
+ assertOnGLThread();
+ mRenderThread.eglManager().requireGlContext();
+}
+
+void RenderState::assertOnGLThread() {
+ pthread_t curr = pthread_self();
+ LOG_ALWAYS_FATAL_IF(!pthread_equal(mThreadId, curr), "Wrong thread!");
+}
+
+
+class DecStrongTask : public renderthread::RenderTask {
+public:
+ DecStrongTask(VirtualLightRefBase* object) : mObject(object) {}
+
+ virtual void run() {
+ mObject->decStrong(0);
+ mObject = 0;
+ delete this;
+ }
+
+private:
+ VirtualLightRefBase* mObject;
+};
+
+void RenderState::postDecStrong(VirtualLightRefBase* object) {
+ mRenderThread.queue(new DecStrongTask(object));
+}
+
} /* namespace uirenderer */
} /* namespace android */
diff --git a/libs/hwui/RenderState.h b/libs/hwui/RenderState.h
index cbe7cfc..afeef95 100644
--- a/libs/hwui/RenderState.h
+++ b/libs/hwui/RenderState.h
@@ -53,16 +53,10 @@ public:
void debugOverdraw(bool enable, bool clear);
void registerLayer(const Layer* layer) {
- /*
- AutoMutex _lock(mLayerLock);
mActiveLayers.insert(layer);
- */
}
void unregisterLayer(const Layer* layer) {
- /*
- AutoMutex _lock(mLayerLock);
mActiveLayers.erase(layer);
- */
}
void registerCanvasContext(renderthread::CanvasContext* context) {
@@ -73,16 +67,24 @@ public:
mRegisteredContexts.erase(context);
}
+ void requireGLContext();
+
+ // TODO: This system is a little clunky feeling, this could use some
+ // more thinking...
+ void postDecStrong(VirtualLightRefBase* object);
+
private:
friend class renderthread::RenderThread;
friend class Caches;
void interruptForFunctorInvoke();
void resumeFromFunctorInvoke();
+ void assertOnGLThread();
- RenderState();
+ RenderState(renderthread::RenderThread& thread);
~RenderState();
+ renderthread::RenderThread& mRenderThread;
Caches* mCaches;
std::set<const Layer*> mActiveLayers;
std::set<renderthread::CanvasContext*> mRegisteredContexts;
@@ -90,7 +92,8 @@ private:
GLsizei mViewportWidth;
GLsizei mViewportHeight;
GLuint mFramebuffer;
- Mutex mLayerLock;
+
+ pthread_t mThreadId;
};
} /* namespace uirenderer */
diff --git a/libs/hwui/Renderer.h b/libs/hwui/Renderer.h
index 9cedd5a..a2f8c05 100644
--- a/libs/hwui/Renderer.h
+++ b/libs/hwui/Renderer.h
@@ -17,12 +17,13 @@
#ifndef ANDROID_HWUI_RENDERER_H
#define ANDROID_HWUI_RENDERER_H
+#include <SkColorFilter.h>
+#include <SkPaint.h>
#include <SkRegion.h>
#include <utils/String8.h>
#include "AssetAtlas.h"
-#include "SkPaint.h"
namespace android {
@@ -81,6 +82,14 @@ public:
&& !paint.getColorFilter()
&& getXfermode(paint.getXfermode()) == SkXfermode::kSrcOver_Mode;
}
+
+ static bool isBlendedColorFilter(const SkColorFilter* filter) {
+ if (filter == NULL) {
+ return false;
+ }
+ return (filter->getFlags() & SkColorFilter::kAlphaUnchanged_Flag) == 0;
+ }
+
// ----------------------------------------------------------------------------
// Frame state operations
// ----------------------------------------------------------------------------
diff --git a/libs/hwui/ResourceCache.cpp b/libs/hwui/ResourceCache.cpp
index 8b553d1..329d92f 100644
--- a/libs/hwui/ResourceCache.cpp
+++ b/libs/hwui/ResourceCache.cpp
@@ -75,10 +75,6 @@ void ResourceCache::incrementRefcount(const Res_png_9patch* patchResource) {
incrementRefcount((void*) patchResource, kNinePatch);
}
-void ResourceCache::incrementRefcount(Layer* layerResource) {
- incrementRefcount((void*) layerResource, kLayer);
-}
-
void ResourceCache::incrementRefcountLocked(void* resource, ResourceType resourceType) {
ssize_t index = mCache->indexOfKey(resource);
ResourceReference* ref = index >= 0 ? mCache->valueAt(index) : NULL;
@@ -103,10 +99,6 @@ void ResourceCache::incrementRefcountLocked(const Res_png_9patch* patchResource)
incrementRefcountLocked((void*) patchResource, kNinePatch);
}
-void ResourceCache::incrementRefcountLocked(Layer* layerResource) {
- incrementRefcountLocked((void*) layerResource, kLayer);
-}
-
void ResourceCache::decrementRefcount(void* resource) {
Mutex::Autolock _l(mLock);
decrementRefcountLocked(resource);
@@ -126,10 +118,6 @@ void ResourceCache::decrementRefcount(const Res_png_9patch* patchResource) {
decrementRefcount((void*) patchResource);
}
-void ResourceCache::decrementRefcount(Layer* layerResource) {
- decrementRefcount((void*) layerResource);
-}
-
void ResourceCache::decrementRefcountLocked(void* resource) {
ssize_t index = mCache->indexOfKey(resource);
ResourceReference* ref = index >= 0 ? mCache->valueAt(index) : NULL;
@@ -157,10 +145,6 @@ void ResourceCache::decrementRefcountLocked(const Res_png_9patch* patchResource)
decrementRefcountLocked((void*) patchResource);
}
-void ResourceCache::decrementRefcountLocked(Layer* layerResource) {
- decrementRefcountLocked((void*) layerResource);
-}
-
void ResourceCache::destructor(SkPath* resource) {
Mutex::Autolock _l(mLock);
destructorLocked(resource);
@@ -274,7 +258,7 @@ void ResourceCache::deleteResourceReferenceLocked(const void* resource, Resource
if (ref->recycled && ref->resourceType == kBitmap) {
((SkBitmap*) resource)->setPixels(NULL, NULL);
}
- if (ref->destroyed || ref->resourceType == kLayer) {
+ if (ref->destroyed) {
switch (ref->resourceType) {
case kBitmap: {
SkBitmap* bitmap = (SkBitmap*) resource;
@@ -305,11 +289,6 @@ void ResourceCache::deleteResourceReferenceLocked(const void* resource, Resource
}
}
break;
- case kLayer: {
- Layer* layer = (Layer*) resource;
- Caches::getInstance().deleteLayerDeferred(layer);
- }
- break;
}
}
mCache->removeItem(resource);
diff --git a/libs/hwui/ResourceCache.h b/libs/hwui/ResourceCache.h
index 3864d4b..8539d12 100644
--- a/libs/hwui/ResourceCache.h
+++ b/libs/hwui/ResourceCache.h
@@ -36,8 +36,7 @@ namespace uirenderer {
enum ResourceType {
kBitmap,
kNinePatch,
- kPath,
- kLayer
+ kPath
};
class ResourceReference {
@@ -69,22 +68,18 @@ public:
void incrementRefcount(const SkPath* resource);
void incrementRefcount(const SkBitmap* resource);
void incrementRefcount(const Res_png_9patch* resource);
- void incrementRefcount(Layer* resource);
void incrementRefcountLocked(const SkPath* resource);
void incrementRefcountLocked(const SkBitmap* resource);
void incrementRefcountLocked(const Res_png_9patch* resource);
- void incrementRefcountLocked(Layer* resource);
void decrementRefcount(const SkBitmap* resource);
void decrementRefcount(const SkPath* resource);
void decrementRefcount(const Res_png_9patch* resource);
- void decrementRefcount(Layer* resource);
void decrementRefcountLocked(const SkBitmap* resource);
void decrementRefcountLocked(const SkPath* resource);
void decrementRefcountLocked(const Res_png_9patch* resource);
- void decrementRefcountLocked(Layer* resource);
void destructor(SkPath* resource);
void destructor(const SkBitmap* resource);
diff --git a/libs/hwui/SpotShadow.cpp b/libs/hwui/SpotShadow.cpp
index dbedf94..df28ae8 100644
--- a/libs/hwui/SpotShadow.cpp
+++ b/libs/hwui/SpotShadow.cpp
@@ -60,7 +60,7 @@
namespace android {
namespace uirenderer {
-static const double EPSILON = 1e-7;
+static const float EPSILON = 1e-7;
/**
* For each polygon's vertex, the light center will project it to the receiver
@@ -118,17 +118,17 @@ static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
// intersection point should stay on both the ray and the edge of (p1, p2).
// solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
- double divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
+ float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
if (divisor == 0) return -1.0f; // error, invalid divisor
#if DEBUG_SHADOW
- double interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
+ float interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
if (interpVal < 0 || interpVal > 1) {
ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
}
#endif
- double distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
+ float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
rayOrigin.x * (p2.y - p1.y)) / divisor;
return distance; // may be negative in error cases
@@ -217,146 +217,12 @@ int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
*
* @return true if a right hand turn
*/
-bool SpotShadow::ccw(double ax, double ay, double bx, double by,
- double cx, double cy) {
+bool SpotShadow::ccw(float ax, float ay, float bx, float by,
+ float cx, float cy) {
return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
}
/**
- * Calculates the intersection of poly1 with poly2 and put in poly2.
- * Note that both poly1 and poly2 must be in CW order already!
- *
- * @param poly1 The 1st polygon, as a Vector2 array.
- * @param poly1Length The number of vertices of 1st polygon.
- * @param poly2 The 2nd and output polygon, as a Vector2 array.
- * @param poly2Length The number of vertices of 2nd polygon.
- * @return number of vertices in output polygon as poly2.
- */
-int SpotShadow::intersection(const Vector2* poly1, int poly1Length,
- Vector2* poly2, int poly2Length) {
-#if DEBUG_SHADOW
- if (!ShadowTessellator::isClockwise(poly1, poly1Length)) {
- ALOGW("Poly1 is not clockwise! Intersection is wrong!");
- }
- if (!ShadowTessellator::isClockwise(poly2, poly2Length)) {
- ALOGW("Poly2 is not clockwise! Intersection is wrong!");
- }
-#endif
- Vector2 poly[poly1Length * poly2Length + 2];
- int count = 0;
- int pcount = 0;
-
- // If one vertex from one polygon sits inside another polygon, add it and
- // count them.
- for (int i = 0; i < poly1Length; i++) {
- if (testPointInsidePolygon(poly1[i], poly2, poly2Length)) {
- poly[count] = poly1[i];
- count++;
- pcount++;
-
- }
- }
-
- int insidePoly2 = pcount;
- for (int i = 0; i < poly2Length; i++) {
- if (testPointInsidePolygon(poly2[i], poly1, poly1Length)) {
- poly[count] = poly2[i];
- count++;
- }
- }
-
- int insidePoly1 = count - insidePoly2;
- // If all vertices from poly1 are inside poly2, then just return poly1.
- if (insidePoly2 == poly1Length) {
- memcpy(poly2, poly1, poly1Length * sizeof(Vector2));
- return poly1Length;
- }
-
- // If all vertices from poly2 are inside poly1, then just return poly2.
- if (insidePoly1 == poly2Length) {
- return poly2Length;
- }
-
- // Since neither polygon fully contain the other one, we need to add all the
- // intersection points.
- Vector2 intersection = {0, 0};
- for (int i = 0; i < poly2Length; i++) {
- for (int j = 0; j < poly1Length; j++) {
- int poly2LineStart = i;
- int poly2LineEnd = ((i + 1) % poly2Length);
- int poly1LineStart = j;
- int poly1LineEnd = ((j + 1) % poly1Length);
- bool found = lineIntersection(
- poly2[poly2LineStart].x, poly2[poly2LineStart].y,
- poly2[poly2LineEnd].x, poly2[poly2LineEnd].y,
- poly1[poly1LineStart].x, poly1[poly1LineStart].y,
- poly1[poly1LineEnd].x, poly1[poly1LineEnd].y,
- intersection);
- if (found) {
- poly[count].x = intersection.x;
- poly[count].y = intersection.y;
- count++;
- } else {
- Vector2 delta = poly2[i] - poly1[j];
- if (delta.lengthSquared() < EPSILON) {
- poly[count] = poly2[i];
- count++;
- }
- }
- }
- }
-
- if (count == 0) {
- return 0;
- }
-
- // Sort the result polygon around the center.
- Vector2 center = {0.0f, 0.0f};
- for (int i = 0; i < count; i++) {
- center += poly[i];
- }
- center /= count;
- sort(poly, count, center);
-
-#if DEBUG_SHADOW
- // Since poly2 is overwritten as the result, we need to save a copy to do
- // our verification.
- Vector2 oldPoly2[poly2Length];
- int oldPoly2Length = poly2Length;
- memcpy(oldPoly2, poly2, sizeof(Vector2) * poly2Length);
-#endif
-
- // Filter the result out from poly and put it into poly2.
- poly2[0] = poly[0];
- int lastOutputIndex = 0;
- for (int i = 1; i < count; i++) {
- Vector2 delta = poly[i] - poly2[lastOutputIndex];
- if (delta.lengthSquared() >= EPSILON) {
- poly2[++lastOutputIndex] = poly[i];
- } else {
- // If the vertices are too close, pick the inner one, because the
- // inner one is more likely to be an intersection point.
- Vector2 delta1 = poly[i] - center;
- Vector2 delta2 = poly2[lastOutputIndex] - center;
- if (delta1.lengthSquared() < delta2.lengthSquared()) {
- poly2[lastOutputIndex] = poly[i];
- }
- }
- }
- int resultLength = lastOutputIndex + 1;
-
-#if DEBUG_SHADOW
- testConvex(poly2, resultLength, "intersection");
- testConvex(poly1, poly1Length, "input poly1");
- testConvex(oldPoly2, oldPoly2Length, "input poly2");
-
- testIntersection(poly1, poly1Length, oldPoly2, oldPoly2Length, poly2, resultLength);
-#endif
-
- return resultLength;
-}
-
-/**
* Sort points about a center point
*
* @param poly The in and out polyogon as a Vector2 array.
@@ -441,13 +307,13 @@ void SpotShadow::quicksortX(Vector2* points, int low, int high) {
bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
const Vector2* poly, int len) {
bool c = false;
- double testx = testPoint.x;
- double testy = testPoint.y;
+ float testx = testPoint.x;
+ float testy = testPoint.y;
for (int i = 0, j = len - 1; i < len; j = i++) {
- double startX = poly[j].x;
- double startY = poly[j].y;
- double endX = poly[i].x;
- double endY = poly[i].y;
+ float startX = poly[j].x;
+ float startY = poly[j].y;
+ float endX = poly[i].x;
+ float endY = poly[i].y;
if (((endY > testy) != (startY > testy))
&& (testx < (startX - endX) * (testy - endY)
@@ -490,46 +356,6 @@ void SpotShadow::reverse(Vector2* polygon, int len) {
}
/**
- * Intersects two lines in parametric form. This function is called in a tight
- * loop, and we need double precision to get things right.
- *
- * @param x1 the x coordinate point 1 of line 1
- * @param y1 the y coordinate point 1 of line 1
- * @param x2 the x coordinate point 2 of line 1
- * @param y2 the y coordinate point 2 of line 1
- * @param x3 the x coordinate point 1 of line 2
- * @param y3 the y coordinate point 1 of line 2
- * @param x4 the x coordinate point 2 of line 2
- * @param y4 the y coordinate point 2 of line 2
- * @param ret the x,y location of the intersection
- * @return true if it found an intersection
- */
-inline bool SpotShadow::lineIntersection(double x1, double y1, double x2, double y2,
- double x3, double y3, double x4, double y4, Vector2& ret) {
- double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
- if (d == 0.0) return false;
-
- double dx = (x1 * y2 - y1 * x2);
- double dy = (x3 * y4 - y3 * x4);
- double x = (dx * (x3 - x4) - (x1 - x2) * dy) / d;
- double y = (dx * (y3 - y4) - (y1 - y2) * dy) / d;
-
- // The intersection should be in the middle of the point 1 and point 2,
- // likewise point 3 and point 4.
- if (((x - x1) * (x - x2) > EPSILON)
- || ((x - x3) * (x - x4) > EPSILON)
- || ((y - y1) * (y - y2) > EPSILON)
- || ((y - y3) * (y - y4) > EPSILON)) {
- // Not interesected
- return false;
- }
- ret.x = x;
- ret.y = y;
- return true;
-
-}
-
-/**
* Compute a horizontal circular polygon about point (x , y , height) of radius
* (size)
*
@@ -542,7 +368,7 @@ void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
float size, Vector3* ret) {
// TODO: Caching all the sin / cos values and store them in a look up table.
for (int i = 0; i < points; i++) {
- double angle = 2 * i * M_PI / points;
+ float angle = 2 * i * M_PI / points;
ret[i].x = cosf(angle) * size + lightCenter.x;
ret[i].y = sinf(angle) * size + lightCenter.y;
ret[i].z = lightCenter.z;
@@ -853,21 +679,6 @@ bool convertPolyToRayDist(const Vector2* poly, int polyLength, const Vector2& po
return true;
}
-int SpotShadow::calculateOccludedUmbra(const Vector2* umbra, int umbraLength,
- const Vector3* poly, int polyLength, Vector2* occludedUmbra) {
- // Occluded umbra area is computed as the intersection of the projected 2D
- // poly and umbra.
- for (int i = 0; i < polyLength; i++) {
- occludedUmbra[i].x = poly[i].x;
- occludedUmbra[i].y = poly[i].y;
- }
-
- // Both umbra and incoming polygon are guaranteed to be CW, so we can call
- // intersection() directly.
- return intersection(umbra, umbraLength,
- occludedUmbra, polyLength);
-}
-
/**
* This is only for experimental purpose.
* After intersections are calculated, we could smooth the polygon if needed.
@@ -1585,8 +1396,8 @@ bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
Vector2 middle = polygon[(i + 1) % polygonLength];
Vector2 end = polygon[(i + 2) % polygonLength];
- double delta = (double(middle.x) - start.x) * (double(end.y) - start.y) -
- (double(middle.y) - start.y) * (double(end.x) - start.x);
+ float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) -
+ (float(middle.y) - start.y) * (float(end.x) - start.x);
bool isCCWOrCoLinear = (delta >= EPSILON);
if (isCCWOrCoLinear) {
@@ -1621,8 +1432,8 @@ void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
bool dumpPoly = false;
for (int k = 0; k < TEST_POINT_NUMBER; k++) {
// Generate a random point between minX, minY and maxX, maxY.
- double randomX = rand() / double(RAND_MAX);
- double randomY = rand() / double(RAND_MAX);
+ float randomX = rand() / float(RAND_MAX);
+ float randomY = rand() / float(RAND_MAX);
Vector2 testPoint;
testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
diff --git a/libs/hwui/SpotShadow.h b/libs/hwui/SpotShadow.h
index 23fdca9..6fa2028 100644
--- a/libs/hwui/SpotShadow.h
+++ b/libs/hwui/SpotShadow.h
@@ -35,8 +35,6 @@ private:
static float projectCasterToOutline(Vector2& outline,
const Vector3& lightCenter, const Vector3& polyVertex);
- static int calculateOccludedUmbra(const Vector2* umbra, int umbraLength,
- const Vector3* poly, int polyLength, Vector2* occludedUmbra);
static int setupAngleList(VertexAngleData* angleDataList,
int polyLength, const Vector2* polygon, const Vector2& centroid,
@@ -81,8 +79,7 @@ private:
static void xsort(Vector2* points, int pointsLength);
static int hull(Vector2* points, int pointsLength, Vector2* retPoly);
- static bool ccw(double ax, double ay, double bx, double by, double cx, double cy);
- static int intersection(const Vector2* poly1, int poly1length, Vector2* poly2, int poly2length);
+ static bool ccw(float ax, float ay, float bx, float by, float cx, float cy);
static void sort(Vector2* poly, int polyLength, const Vector2& center);
static void swap(Vector2* points, int i, int j);
@@ -92,8 +89,6 @@ private:
static bool testPointInsidePolygon(const Vector2 testPoint, const Vector2* poly, int len);
static void makeClockwise(Vector2* polygon, int len);
static void reverse(Vector2* polygon, int len);
- static inline bool lineIntersection(double x1, double y1, double x2, double y2,
- double x3, double y3, double x4, double y4, Vector2& ret);
static void generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale,
Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength,
diff --git a/libs/hwui/renderthread/CanvasContext.cpp b/libs/hwui/renderthread/CanvasContext.cpp
index b50a433..b499dd0 100644
--- a/libs/hwui/renderthread/CanvasContext.cpp
+++ b/libs/hwui/renderthread/CanvasContext.cpp
@@ -42,7 +42,8 @@ CanvasContext::CanvasContext(RenderThread& thread, bool translucent,
: mRenderThread(thread)
, mEglManager(thread.eglManager())
, mEglSurface(EGL_NO_SURFACE)
- , mDirtyRegionsEnabled(false)
+ , mBufferPreserved(false)
+ , mSwapBehavior(kSwap_default)
, mOpaque(!translucent)
, mCanvas(NULL)
, mHaveNewSurface(false)
@@ -82,7 +83,8 @@ void CanvasContext::setSurface(ANativeWindow* window) {
}
if (mEglSurface != EGL_NO_SURFACE) {
- mDirtyRegionsEnabled = mEglManager.enableDirtyRegions(mEglSurface);
+ const bool preserveBuffer = (mSwapBehavior != kSwap_discardBuffer);
+ mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer);
mHaveNewSurface = true;
makeCurrent();
} else {
@@ -103,6 +105,10 @@ void CanvasContext::requireSurface() {
makeCurrent();
}
+void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) {
+ mSwapBehavior = swapBehavior;
+}
+
bool CanvasContext::initialize(ANativeWindow* window) {
setSurface(window);
if (mCanvas) return false;
@@ -200,7 +206,7 @@ void CanvasContext::draw() {
if (width != mCanvas->getViewportWidth() || height != mCanvas->getViewportHeight()) {
mCanvas->setViewport(width, height);
dirty.setEmpty();
- } else if (!mDirtyRegionsEnabled || mHaveNewSurface) {
+ } else if (!mBufferPreserved || mHaveNewSurface) {
dirty.setEmpty();
} else {
if (!dirty.isEmpty() && !dirty.intersect(0, 0, width, height)) {
@@ -230,6 +236,8 @@ void CanvasContext::draw() {
if (status & DrawGlInfo::kStatusDrew) {
swapBuffers();
+ } else {
+ mEglManager.cancelFrame();
}
profiler().finishFrame();
@@ -330,6 +338,7 @@ void CanvasContext::trimMemory(RenderThread& thread, int level) {
// No context means nothing to free
if (!thread.eglManager().hasEglContext()) return;
+ ATRACE_CALL();
thread.eglManager().requireGlContext();
if (level >= TRIM_MEMORY_COMPLETE) {
Caches::getInstance().flush(Caches::kFlushMode_Full);
diff --git a/libs/hwui/renderthread/CanvasContext.h b/libs/hwui/renderthread/CanvasContext.h
index d4282fa..e20564b 100644
--- a/libs/hwui/renderthread/CanvasContext.h
+++ b/libs/hwui/renderthread/CanvasContext.h
@@ -48,6 +48,11 @@ namespace renderthread {
class EglManager;
+enum SwapBehavior {
+ kSwap_default,
+ kSwap_discardBuffer,
+};
+
// This per-renderer class manages the bridge between the global EGL context
// and the render surface.
// TODO: Rename to Renderer or some other per-window, top-level manager
@@ -57,6 +62,9 @@ public:
IContextFactory* contextFactory);
virtual ~CanvasContext();
+ // Won't take effect until next EGLSurface creation
+ void setSwapBehavior(SwapBehavior swapBehavior);
+
bool initialize(ANativeWindow* window);
void updateSurface(ANativeWindow* window);
void pauseSurface(ANativeWindow* window);
@@ -111,7 +119,8 @@ private:
EglManager& mEglManager;
sp<ANativeWindow> mNativeWindow;
EGLSurface mEglSurface;
- bool mDirtyRegionsEnabled;
+ bool mBufferPreserved;
+ SwapBehavior mSwapBehavior;
bool mOpaque;
OpenGLRenderer* mCanvas;
diff --git a/libs/hwui/renderthread/EglManager.cpp b/libs/hwui/renderthread/EglManager.cpp
index a87834e..9bd6f41 100644
--- a/libs/hwui/renderthread/EglManager.cpp
+++ b/libs/hwui/renderthread/EglManager.cpp
@@ -70,12 +70,13 @@ EglManager::EglManager(RenderThread& thread)
, mEglConfig(0)
, mEglContext(EGL_NO_CONTEXT)
, mPBufferSurface(EGL_NO_SURFACE)
- , mRequestDirtyRegions(load_dirty_regions_property())
+ , mAllowPreserveBuffer(load_dirty_regions_property())
, mCurrentSurface(EGL_NO_SURFACE)
, mAtlasMap(NULL)
- , mAtlasMapSize(0) {
- mCanSetDirtyRegions = mRequestDirtyRegions;
- ALOGD("Render dirty regions requested: %s", mRequestDirtyRegions ? "true" : "false");
+ , mAtlasMapSize(0)
+ , mInFrame(false) {
+ mCanSetPreserveBuffer = mAllowPreserveBuffer;
+ ALOGD("Use EGL_SWAP_BEHAVIOR_PRESERVED: %s", mAllowPreserveBuffer ? "true" : "false");
}
void EglManager::initialize() {
@@ -105,15 +106,16 @@ bool EglManager::hasEglContext() {
void EglManager::requireGlContext() {
LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY, "No EGL context");
- // We don't care *WHAT* surface is active, just that one is active to give
- // us access to the GL context
- if (mCurrentSurface == EGL_NO_SURFACE) {
+ if (!mInFrame) {
+ // We can't be certain about the state of the current surface (whether
+ // or not it is destroyed, for example), so err on the side of using
+ // the pbuffer surface which we fully control
usePBufferSurface();
}
}
void EglManager::loadConfig() {
- EGLint swapBehavior = mCanSetDirtyRegions ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
+ EGLint swapBehavior = mCanSetPreserveBuffer ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
EGLint attribs[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_RED_SIZE, 8,
@@ -131,10 +133,10 @@ void EglManager::loadConfig() {
if (!eglChooseConfig(mEglDisplay, attribs, &mEglConfig, num_configs, &num_configs)
|| num_configs != 1) {
// Failed to get a valid config
- if (mCanSetDirtyRegions) {
+ if (mCanSetPreserveBuffer) {
ALOGW("Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...");
// Try again without dirty regions enabled
- mCanSetDirtyRegions = false;
+ mCanSetPreserveBuffer = false;
loadConfig();
} else {
LOG_ALWAYS_FATAL("Failed to choose config, error = %s", egl_error_str());
@@ -252,9 +254,11 @@ void EglManager::beginFrame(EGLSurface surface, EGLint* width, EGLint* height) {
eglQuerySurface(mEglDisplay, surface, EGL_HEIGHT, height);
}
eglBeginFrame(mEglDisplay, surface);
+ mInFrame = true;
}
bool EglManager::swapBuffers(EGLSurface surface) {
+ mInFrame = false;
eglSwapBuffers(mEglDisplay, surface);
EGLint err = eglGetError();
if (CC_LIKELY(err == EGL_SUCCESS)) {
@@ -273,25 +277,34 @@ bool EglManager::swapBuffers(EGLSurface surface) {
return false;
}
-bool EglManager::enableDirtyRegions(EGLSurface surface) {
- if (!mRequestDirtyRegions) return false;
+void EglManager::cancelFrame() {
+ mInFrame = false;
+}
+
+bool EglManager::setPreserveBuffer(EGLSurface surface, bool preserve) {
+ if (CC_UNLIKELY(!mAllowPreserveBuffer)) return false;
- if (mCanSetDirtyRegions) {
- if (!eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, EGL_BUFFER_PRESERVED)) {
+ bool preserved = false;
+ if (mCanSetPreserveBuffer) {
+ preserved = eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
+ preserve ? EGL_BUFFER_PRESERVED : EGL_BUFFER_DESTROYED);
+ if (CC_UNLIKELY(!preserved)) {
ALOGW("Failed to set EGL_SWAP_BEHAVIOR on surface %p, error=%s",
(void*) surface, egl_error_str());
- return false;
}
- return true;
}
- // Perhaps it is already enabled?
- EGLint value;
- if (!eglQuerySurface(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, &value)) {
- ALOGW("Failed to query EGL_SWAP_BEHAVIOR on surface %p, error=%p",
- (void*) surface, egl_error_str());
- return false;
+ if (CC_UNLIKELY(!preserved)) {
+ // Maybe it's already set?
+ EGLint swapBehavior;
+ if (eglQuerySurface(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, &swapBehavior)) {
+ preserved = (swapBehavior == EGL_BUFFER_PRESERVED);
+ } else {
+ ALOGW("Failed to query EGL_SWAP_BEHAVIOR on surface %p, error=%p",
+ (void*) surface, egl_error_str());
+ }
}
- return value == EGL_BUFFER_PRESERVED;
+
+ return preserved;
}
} /* namespace renderthread */
diff --git a/libs/hwui/renderthread/EglManager.h b/libs/hwui/renderthread/EglManager.h
index 71213fb..e12db3a 100644
--- a/libs/hwui/renderthread/EglManager.h
+++ b/libs/hwui/renderthread/EglManager.h
@@ -48,8 +48,10 @@ public:
bool makeCurrent(EGLSurface surface);
void beginFrame(EGLSurface surface, EGLint* width, EGLint* height);
bool swapBuffers(EGLSurface surface);
+ void cancelFrame();
- bool enableDirtyRegions(EGLSurface surface);
+ // Returns true iff the surface is now preserving buffers.
+ bool setPreserveBuffer(EGLSurface surface, bool preserve);
void setTextureAtlas(const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize);
@@ -71,14 +73,20 @@ private:
EGLContext mEglContext;
EGLSurface mPBufferSurface;
- const bool mRequestDirtyRegions;
- bool mCanSetDirtyRegions;
+ const bool mAllowPreserveBuffer;
+ bool mCanSetPreserveBuffer;
EGLSurface mCurrentSurface;
sp<GraphicBuffer> mAtlasBuffer;
int64_t* mAtlasMap;
size_t mAtlasMapSize;
+
+ // Whether or not we are in the middle of drawing a frame. This is used
+ // to avoid switching surfaces mid-frame if requireGlContext() is called
+ // TODO: Need to be better about surface/context management so that this isn't
+ // necessary
+ bool mInFrame;
};
} /* namespace renderthread */
diff --git a/libs/hwui/renderthread/RenderProxy.cpp b/libs/hwui/renderthread/RenderProxy.cpp
index 047819d..5d55ea6 100644
--- a/libs/hwui/renderthread/RenderProxy.cpp
+++ b/libs/hwui/renderthread/RenderProxy.cpp
@@ -103,6 +103,18 @@ void RenderProxy::setFrameInterval(nsecs_t frameIntervalNanos) {
post(task);
}
+CREATE_BRIDGE2(setSwapBehavior, CanvasContext* context, SwapBehavior swapBehavior) {
+ args->context->setSwapBehavior(args->swapBehavior);
+ return NULL;
+}
+
+void RenderProxy::setSwapBehavior(SwapBehavior swapBehavior) {
+ SETUP_TASK(setSwapBehavior);
+ args->context = mContext;
+ args->swapBehavior = swapBehavior;
+ post(task);
+}
+
CREATE_BRIDGE1(loadSystemProperties, CanvasContext* context) {
bool needsRedraw = false;
if (Caches::hasInstance()) {
@@ -223,12 +235,7 @@ void RenderProxy::invokeFunctor(Functor* functor, bool waitForCompletion) {
// waitForCompletion = true is expected to be fairly rare and only
// happen in destruction. Thus it should be fine to temporarily
// create a Mutex
- Mutex mutex;
- Condition condition;
- SignalingRenderTask syncTask(task, &mutex, &condition);
- AutoMutex _lock(mutex);
- thread.queue(&syncTask);
- condition.wait(mutex);
+ staticPostAndWait(task);
} else {
thread.queue(task);
}
@@ -246,17 +253,6 @@ void RenderProxy::runWithGlContext(RenderTask* gltask) {
postAndWait(task);
}
-CREATE_BRIDGE1(destroyLayer, Layer* layer) {
- LayerRenderer::destroyLayer(args->layer);
- return NULL;
-}
-
-void RenderProxy::enqueueDestroyLayer(Layer* layer) {
- SETUP_TASK(destroyLayer);
- args->layer = layer;
- RenderThread::getInstance().queue(task);
-}
-
CREATE_BRIDGE2(createTextureLayer, RenderThread* thread, CanvasContext* context) {
Layer* layer = args->context->createTextureLayer();
if (!layer) return 0;
@@ -388,6 +384,17 @@ void RenderProxy::dumpProfileInfo(int fd) {
postAndWait(task);
}
+CREATE_BRIDGE1(outputLogBuffer, int fd) {
+ RenderNode::outputLogBuffer(args->fd);
+ return NULL;
+}
+
+void RenderProxy::outputLogBuffer(int fd) {
+ SETUP_TASK(outputLogBuffer);
+ args->fd = fd;
+ staticPostAndWait(task);
+}
+
CREATE_BRIDGE4(setTextureAtlas, RenderThread* thread, GraphicBuffer* buffer, int64_t* map, size_t size) {
CanvasContext::setTextureAtlas(*args->thread, args->buffer, args->map, args->size);
args->buffer->decStrong(0);
@@ -418,6 +425,19 @@ void* RenderProxy::postAndWait(MethodInvokeRenderTask* task) {
return retval;
}
+void* RenderProxy::staticPostAndWait(MethodInvokeRenderTask* task) {
+ RenderThread& thread = RenderThread::getInstance();
+ void* retval;
+ task->setReturnPtr(&retval);
+ Mutex mutex;
+ Condition condition;
+ SignalingRenderTask syncTask(task, &mutex, &condition);
+ AutoMutex _lock(mutex);
+ thread.queue(&syncTask);
+ condition.wait(mutex);
+ return retval;
+}
+
} /* namespace renderthread */
} /* namespace uirenderer */
} /* namespace android */
diff --git a/libs/hwui/renderthread/RenderProxy.h b/libs/hwui/renderthread/RenderProxy.h
index 678e7e2..4989b14 100644
--- a/libs/hwui/renderthread/RenderProxy.h
+++ b/libs/hwui/renderthread/RenderProxy.h
@@ -31,6 +31,7 @@
#include "../Caches.h"
#include "../IContextFactory.h"
+#include "CanvasContext.h"
#include "DrawFrameTask.h"
namespace android {
@@ -44,7 +45,6 @@ class Rect;
namespace renderthread {
-class CanvasContext;
class ErrorChannel;
class RenderThread;
class RenderProxyBridge;
@@ -63,6 +63,8 @@ public:
ANDROID_API virtual ~RenderProxy();
ANDROID_API void setFrameInterval(nsecs_t frameIntervalNanos);
+ // Won't take effect until next EGLSurface creation
+ ANDROID_API void setSwapBehavior(SwapBehavior swapBehavior);
ANDROID_API bool loadSystemProperties();
ANDROID_API bool initialize(const sp<ANativeWindow>& window);
@@ -79,7 +81,6 @@ public:
ANDROID_API void runWithGlContext(RenderTask* task);
- static void enqueueDestroyLayer(Layer* layer);
ANDROID_API DeferredLayerUpdater* createTextureLayer();
ANDROID_API void buildLayer(RenderNode* node);
ANDROID_API bool copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap);
@@ -95,6 +96,7 @@ public:
ANDROID_API void notifyFramePending();
ANDROID_API void dumpProfileInfo(int fd);
+ ANDROID_API static void outputLogBuffer(int fd);
ANDROID_API void setTextureAtlas(const sp<GraphicBuffer>& buffer, int64_t* map, size_t size);
@@ -112,6 +114,8 @@ private:
void post(RenderTask* task);
void* postAndWait(MethodInvokeRenderTask* task);
+ static void* staticPostAndWait(MethodInvokeRenderTask* task);
+
// Friend class to help with bridging
friend class RenderProxyBridge;
};
diff --git a/libs/hwui/renderthread/RenderThread.cpp b/libs/hwui/renderthread/RenderThread.cpp
index 403e164..f887103 100644
--- a/libs/hwui/renderthread/RenderThread.cpp
+++ b/libs/hwui/renderthread/RenderThread.cpp
@@ -168,7 +168,7 @@ void RenderThread::initializeDisplayEventReceiver() {
void RenderThread::initThreadLocals() {
initializeDisplayEventReceiver();
mEglManager = new EglManager(*this);
- mRenderState = new RenderState();
+ mRenderState = new RenderState(*this);
}
int RenderThread::displayEventReceiverCallback(int fd, int events, void* data) {
diff --git a/libs/hwui/tests/Android.mk b/libs/hwui/tests/Android.mk
new file mode 100644
index 0000000..9622073
--- /dev/null
+++ b/libs/hwui/tests/Android.mk
@@ -0,0 +1,55 @@
+#
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+local_target_dir := $(TARGET_OUT_DATA)/local/tmp
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_CFLAGS += -DUSE_OPENGL_RENDERER -DEGL_EGLEXT_PROTOTYPES -DGL_GLEXT_PROTOTYPES
+LOCAL_CFLAGS += -DATRACE_TAG=ATRACE_TAG_VIEW -DLOG_TAG=\"OpenGLRenderer\"
+
+LOCAL_SRC_FILES:= \
+ TestContext.cpp \
+ main.cpp
+
+LOCAL_C_INCLUDES += \
+ $(LOCAL_PATH)/.. \
+ external/skia/src/core
+
+LOCAL_SHARED_LIBRARIES := \
+ liblog \
+ libcutils \
+ libutils \
+ libskia \
+ libgui \
+ libui \
+ libhwui
+
+ifeq ($(WITH_MALLOC_LEAK_CHECK),true)
+ LOCAL_CFLAGS += -DMALLOC_LEAK_CHECK
+endif
+
+LOCAL_MODULE_PATH := $(local_target_dir)
+LOCAL_MODULE:= hwuitest
+LOCAL_MODULE_TAGS := tests
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := hwuitest
+LOCAL_MODULE_STEM_64 := hwuitest64
+
+include external/stlport/libstlport.mk
+include $(BUILD_EXECUTABLE)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/libs/hwui/tests/TestContext.cpp b/libs/hwui/tests/TestContext.cpp
new file mode 100644
index 0000000..35e402d
--- /dev/null
+++ b/libs/hwui/tests/TestContext.cpp
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "TestContext.h"
+
+#include <gui/ISurfaceComposer.h>
+#include <gui/SurfaceComposerClient.h>
+
+using namespace android;
+
+DisplayInfo gDisplay;
+sp<SurfaceComposerClient> gSession;
+
+void createTestEnvironment() {
+ gSession = new SurfaceComposerClient();
+ sp<IBinder> dtoken(SurfaceComposerClient::getBuiltInDisplay(
+ ISurfaceComposer::eDisplayIdMain));
+ status_t status = SurfaceComposerClient::getDisplayInfo(dtoken, &gDisplay);
+ LOG_ALWAYS_FATAL_IF(status, "Failed to get display info\n");
+}
+
+sp<SurfaceControl> createWindow(int width, int height) {
+ sp<SurfaceControl> control = gSession->createSurface(String8("HwuiTest"),
+ width, height, PIXEL_FORMAT_RGBX_8888);
+
+ SurfaceComposerClient::openGlobalTransaction();
+ control->setLayer(0x7FFFFFF);
+ control->show();
+ SurfaceComposerClient::closeGlobalTransaction();
+
+ return control;
+}
diff --git a/libs/hwui/tests/TestContext.h b/libs/hwui/tests/TestContext.h
new file mode 100644
index 0000000..8a5d530
--- /dev/null
+++ b/libs/hwui/tests/TestContext.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef TESTCONTEXT_H
+#define TESTCONTEXT_H
+
+#include <ui/DisplayInfo.h>
+#include <gui/SurfaceControl.h>
+
+extern android::DisplayInfo gDisplay;
+#define dp(x) ((x) * gDisplay.density)
+
+// Initializes all the static globals that are shared across all contexts
+// such as display info
+void createTestEnvironment();
+
+// Defaults to fullscreen
+android::sp<android::SurfaceControl> createWindow(int width = -1, int height = -1);
+
+#endif
diff --git a/libs/hwui/tests/main.cpp b/libs/hwui/tests/main.cpp
new file mode 100644
index 0000000..2d99e9f
--- /dev/null
+++ b/libs/hwui/tests/main.cpp
@@ -0,0 +1,131 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+
+#include <cutils/log.h>
+#include <gui/Surface.h>
+#include <ui/PixelFormat.h>
+
+#include <AnimationContext.h>
+#include <DisplayListRenderer.h>
+#include <RenderNode.h>
+#include <renderthread/RenderProxy.h>
+
+#include "TestContext.h"
+
+using namespace android;
+using namespace android::uirenderer;
+using namespace android::uirenderer::renderthread;
+
+class ContextFactory : public IContextFactory {
+public:
+ virtual AnimationContext* createAnimationContext(renderthread::TimeLord& clock) {
+ return new AnimationContext(clock);
+ }
+};
+
+static DisplayListRenderer* startRecording(RenderNode* node) {
+ DisplayListRenderer* renderer = new DisplayListRenderer();
+ renderer->setViewport(node->getWidth(), node->getHeight());
+ renderer->prepare(false);
+ return renderer;
+}
+
+static void endRecording(DisplayListRenderer* renderer, RenderNode* node) {
+ renderer->finish();
+ node->setStagingDisplayList(renderer->finishRecording());
+ delete renderer;
+}
+
+sp<RenderNode> createCard(int x, int y, int width, int height) {
+ sp<RenderNode> node = new RenderNode();
+ node->mutateStagingProperties().setLeftTopRightBottom(x, y, x + width, y + height);
+ node->mutateStagingProperties().setElevation(dp(16));
+ node->mutateStagingProperties().mutableOutline().setRoundRect(0, 0, width, height, dp(10), 1);
+ node->mutateStagingProperties().mutableOutline().setShouldClip(true);
+ node->setPropertyFieldsDirty(RenderNode::X | RenderNode::Y | RenderNode::Z);
+
+ DisplayListRenderer* renderer = startRecording(node.get());
+ renderer->drawColor(0xFFEEEEEE, SkXfermode::kSrcOver_Mode);
+ endRecording(renderer, node.get());
+
+ return node;
+}
+
+int main(int argc, char* argv[]) {
+ createTestEnvironment();
+
+ // create the native surface
+ const int width = gDisplay.w;
+ const int height = gDisplay.h;
+ sp<SurfaceControl> control = createWindow(width, height);
+ sp<Surface> surface = control->getSurface();
+
+ RenderNode* rootNode = new RenderNode();
+ rootNode->incStrong(0);
+ rootNode->mutateStagingProperties().setLeftTopRightBottom(0, 0, width, height);
+ rootNode->setPropertyFieldsDirty(RenderNode::X | RenderNode::Y);
+ rootNode->mutateStagingProperties().setClipToBounds(false);
+ rootNode->setPropertyFieldsDirty(RenderNode::GENERIC);
+
+ ContextFactory factory;
+ RenderProxy* proxy = new RenderProxy(false, rootNode, &factory);
+ proxy->loadSystemProperties();
+ proxy->initialize(surface);
+ float lightX = width / 2.0;
+ proxy->setup(width, height, (Vector3){lightX, dp(-200.0f), dp(800.0f)},
+ dp(800.0f), 255 * 0.075, 255 * 0.15);
+
+ android::uirenderer::Rect DUMMY;
+
+ std::vector< sp<RenderNode> > cards;
+
+ DisplayListRenderer* renderer = startRecording(rootNode);
+ renderer->drawColor(0xFFFFFFFF, SkXfermode::kSrcOver_Mode);
+ renderer->insertReorderBarrier(true);
+
+ for (int x = dp(16); x < (width - dp(116)); x += dp(116)) {
+ for (int y = dp(16); y < (height - dp(116)); y += dp(116)) {
+ sp<RenderNode> card = createCard(x, y, dp(100), dp(100));
+ renderer->drawRenderNode(card.get(), DUMMY, 0);
+ cards.push_back(card);
+ }
+ }
+
+ renderer->insertReorderBarrier(false);
+ endRecording(renderer, rootNode);
+
+ for (int i = 0; i < 150; i++) {
+ ATRACE_NAME("UI-Draw Frame");
+ for (int ci = 0; ci < cards.size(); ci++) {
+ cards[ci]->mutateStagingProperties().setTranslationX(i);
+ cards[ci]->mutateStagingProperties().setTranslationY(i);
+ cards[ci]->setPropertyFieldsDirty(RenderNode::X | RenderNode::Y);
+ }
+ nsecs_t frameTimeNs = systemTime(CLOCK_MONOTONIC);
+ proxy->syncAndDrawFrame(frameTimeNs, 0, gDisplay.density);
+ usleep(12000);
+ }
+
+ sleep(5);
+
+ delete proxy;
+ rootNode->decStrong(0);
+
+ printf("Success!\n");
+ return 0;
+}