blob: c5a40d46dbd0c02b4fda474d7c58ba969f5338b7 [file] [log] [blame]
Stan Iliev500a0c32016-10-26 10:30:09 -04001/*
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 "SkiaPipeline.h"
18
19#include "utils/TraceUtils.h"
20#include <SkOSFile.h>
21#include <SkPicture.h>
22#include <SkPictureRecorder.h>
23#include <SkPixelSerializer.h>
24#include <SkStream.h>
25
26using namespace android::uirenderer::renderthread;
27
28namespace android {
29namespace uirenderer {
30namespace skiapipeline {
31
32float SkiaPipeline::mLightRadius = 0;
33uint8_t SkiaPipeline::mAmbientShadowAlpha = 0;
34uint8_t SkiaPipeline::mSpotShadowAlpha = 0;
35
36Vector3 SkiaPipeline::mLightCenter = {FLT_MIN, FLT_MIN, FLT_MIN};
37
38SkiaPipeline::SkiaPipeline(RenderThread& thread) : mRenderThread(thread) { }
39
40TaskManager* SkiaPipeline::getTaskManager() {
41 return &mTaskManager;
42}
43
44void SkiaPipeline::onDestroyHardwareResources() {
45 // No need to flush the caches here. There is a timer
46 // which will flush temporary resources over time.
47}
48
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040049bool SkiaPipeline::pinImages(std::vector<SkImage*>& mutableImages) {
50 for (SkImage* image : mutableImages) {
Derek Sollenberger189e8742016-11-16 16:00:17 -050051 if (SkImage_pinAsTexture(image, mRenderThread.getGrContext())) {
52 mPinnedImages.emplace_back(sk_ref_sp(image));
53 } else {
54 return false;
55 }
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040056 }
57 return true;
58}
59
60void SkiaPipeline::unpinImages() {
61 for (auto& image : mPinnedImages) {
62 SkImage_unpinAsTexture(image.get(), mRenderThread.getGrContext());
63 }
64 mPinnedImages.clear();
65}
66
Stan Iliev500a0c32016-10-26 10:30:09 -040067void SkiaPipeline::renderLayers(const FrameBuilder::LightGeometry& lightGeometry,
68 LayerUpdateQueue* layerUpdateQueue, bool opaque,
69 const BakedOpRenderer::LightInfo& lightInfo) {
70 updateLighting(lightGeometry, lightInfo);
71 ATRACE_NAME("draw layers");
72 renderLayersImpl(*layerUpdateQueue, opaque);
73 layerUpdateQueue->clear();
74}
75
76void SkiaPipeline::renderLayersImpl(const LayerUpdateQueue& layers, bool opaque) {
77 // Render all layers that need to be updated, in order.
78 for (size_t i = 0; i < layers.entries().size(); i++) {
79 RenderNode* layerNode = layers.entries()[i].renderNode;
80 // only schedule repaint if node still on layer - possible it may have been
81 // removed during a dropped frame, but layers may still remain scheduled so
82 // as not to lose info on what portion is damaged
83 if (CC_LIKELY(layerNode->getLayerSurface() != nullptr)) {
84 SkASSERT(layerNode->getLayerSurface());
85 SkASSERT(layerNode->getDisplayList()->isSkiaDL());
86 SkiaDisplayList* displayList = (SkiaDisplayList*)layerNode->getDisplayList();
87 if (!displayList || displayList->isEmpty()) {
88 SkDEBUGF(("%p drawLayers(%s) : missing drawable", this, layerNode->getName()));
89 return;
90 }
91
92 const Rect& layerDamage = layers.entries()[i].damage;
93
94 SkCanvas* layerCanvas = layerNode->getLayerSurface()->getCanvas();
95
96 int saveCount = layerCanvas->save();
97 SkASSERT(saveCount == 1);
98
99 layerCanvas->clipRect(layerDamage.toSkRect(), SkRegion::kReplace_Op);
100
101 auto savedLightCenter = mLightCenter;
102 // map current light center into RenderNode's coordinate space
103 layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(mLightCenter);
104
105 const RenderProperties& properties = layerNode->properties();
106 const SkRect bounds = SkRect::MakeWH(properties.getWidth(), properties.getHeight());
107 if (properties.getClipToBounds() && layerCanvas->quickReject(bounds)) {
108 return;
109 }
110
Matt Sarett79756be2016-11-09 16:13:54 -0500111 layerNode->getSkiaLayer()->hasRenderedSinceRepaint = false;
Stan Iliev500a0c32016-10-26 10:30:09 -0400112 layerCanvas->clear(SK_ColorTRANSPARENT);
113
114 RenderNodeDrawable root(layerNode, layerCanvas, false);
115 root.forceDraw(layerCanvas);
116 layerCanvas->restoreToCount(saveCount);
117 layerCanvas->flush();
118 mLightCenter = savedLightCenter;
119 }
120 }
121}
122
123bool SkiaPipeline::createOrUpdateLayer(RenderNode* node,
124 const DamageAccumulator& damageAccumulator) {
125 SkSurface* layer = node->getLayerSurface();
126 if (!layer || layer->width() != node->getWidth() || layer->height() != node->getHeight()) {
127 SkImageInfo info = SkImageInfo::MakeN32Premul(node->getWidth(), node->getHeight());
128 SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
129 SkASSERT(mRenderThread.getGrContext() != nullptr);
130 node->setLayerSurface(
131 SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
132 info, 0, &props));
133 if (node->getLayerSurface()) {
134 // update the transform in window of the layer to reset its origin wrt light source
135 // position
136 Matrix4 windowTransform;
137 damageAccumulator.computeCurrentTransform(&windowTransform);
138 node->getSkiaLayer()->inverseTransformInWindow = windowTransform;
139 }
140 return true;
141 }
142 return false;
143}
144
145void SkiaPipeline::destroyLayer(RenderNode* node) {
146 node->setLayerSurface(nullptr);
147}
148
149void SkiaPipeline::prepareToDraw(const RenderThread& thread, Bitmap* bitmap) {
150 GrContext* context = thread.getGrContext();
151 if (context) {
152 ATRACE_FORMAT("Bitmap#prepareToDraw %dx%d", bitmap->width(), bitmap->height());
153 SkBitmap skiaBitmap;
154 bitmap->getSkBitmap(&skiaBitmap);
155 sk_sp<SkImage> image = SkMakeImageFromRasterBitmap(skiaBitmap, kNever_SkCopyPixelsMode);
156 SkImage_pinAsTexture(image.get(), context);
157 SkImage_unpinAsTexture(image.get(), context);
158 }
159}
160
161// Encodes to PNG, unless there is already encoded data, in which case that gets
162// used.
163class PngPixelSerializer : public SkPixelSerializer {
164public:
165 bool onUseEncodedData(const void*, size_t) override { return true; }
166 SkData* onEncode(const SkPixmap& pixmap) override {
167 return SkImageEncoder::EncodeData(pixmap.info(), pixmap.addr(), pixmap.rowBytes(),
168 SkImageEncoder::kPNG_Type, 100);
169 }
170};
171
172void SkiaPipeline::renderFrame(const LayerUpdateQueue& layers, const SkRect& clip,
173 const std::vector<sp<RenderNode>>& nodes, bool opaque, const Rect &contentDrawBounds,
174 sk_sp<SkSurface> surface) {
175
Stan Iliev500a0c32016-10-26 10:30:09 -0400176 // draw all layers up front
177 renderLayersImpl(layers, opaque);
178
179 // initialize the canvas for the current frame
180 SkCanvas* canvas = surface->getCanvas();
181
182 std::unique_ptr<SkPictureRecorder> recorder;
183 bool recordingPicture = false;
184 char prop[PROPERTY_VALUE_MAX];
185 if (skpCaptureEnabled()) {
186 property_get("debug.hwui.capture_frame_as_skp", prop, "0");
187 recordingPicture = prop[0] != '0' && !sk_exists(prop);
188 if (recordingPicture) {
189 recorder.reset(new SkPictureRecorder());
190 canvas = recorder->beginRecording(surface->width(), surface->height(),
191 nullptr, SkPictureRecorder::kPlaybackDrawPicture_RecordFlag);
192 }
193 }
194
195 canvas->clipRect(clip, SkRegion::kReplace_Op);
196
197 if (!opaque) {
198 canvas->clear(SK_ColorTRANSPARENT);
199 }
200
201 // If there are multiple render nodes, they are laid out as follows:
202 // #0 - backdrop (content + caption)
203 // #1 - content (positioned at (0,0) and clipped to - its bounds mContentDrawBounds)
204 // #2 - additional overlay nodes
205 // Usually the backdrop cannot be seen since it will be entirely covered by the content. While
206 // resizing however it might become partially visible. The following render loop will crop the
207 // backdrop against the content and draw the remaining part of it. It will then draw the content
208 // cropped to the backdrop (since that indicates a shrinking of the window).
209 //
210 // Additional nodes will be drawn on top with no particular clipping semantics.
211
212 // The bounds of the backdrop against which the content should be clipped.
213 Rect backdropBounds = contentDrawBounds;
214 // Usually the contents bounds should be mContentDrawBounds - however - we will
215 // move it towards the fixed edge to give it a more stable appearance (for the moment).
216 // If there is no content bounds we ignore the layering as stated above and start with 2.
217 int layer = (contentDrawBounds.isEmpty() || nodes.size() == 1) ? 2 : 0;
218
219 for (const sp<RenderNode>& node : nodes) {
220 if (node->nothingToDraw()) continue;
221
222 SkASSERT(node->getDisplayList()->isSkiaDL());
223
224 int count = canvas->save();
225
226 if (layer == 0) {
227 const RenderProperties& properties = node->properties();
228 Rect targetBounds(properties.getLeft(), properties.getTop(),
229 properties.getRight(), properties.getBottom());
230 // Move the content bounds towards the fixed corner of the backdrop.
231 const int x = targetBounds.left;
232 const int y = targetBounds.top;
233 // Remember the intersection of the target bounds and the intersection bounds against
234 // which we have to crop the content.
235 backdropBounds.set(x, y, x + backdropBounds.getWidth(), y + backdropBounds.getHeight());
236 backdropBounds.doIntersect(targetBounds);
237 } else if (layer == 1) {
238 // We shift and clip the content to match its final location in the window.
239 const SkRect clip = SkRect::MakeXYWH(contentDrawBounds.left, contentDrawBounds.top,
240 backdropBounds.getWidth(), backdropBounds.getHeight());
241 const float dx = backdropBounds.left - contentDrawBounds.left;
242 const float dy = backdropBounds.top - contentDrawBounds.top;
243 canvas->translate(dx, dy);
244 // It gets cropped against the bounds of the backdrop to stay inside.
245 canvas->clipRect(clip, SkRegion::kIntersect_Op);
246 }
247
248 RenderNodeDrawable root(node.get(), canvas);
249 root.draw(canvas);
250 canvas->restoreToCount(count);
251 layer++;
252 }
253
254 if (skpCaptureEnabled() && recordingPicture) {
255 sk_sp<SkPicture> picture = recorder->finishRecordingAsPicture();
256 if (picture->approximateOpCount() > 0) {
257 SkFILEWStream stream(prop);
258 if (stream.isValid()) {
259 PngPixelSerializer serializer;
260 picture->serialize(&stream, &serializer);
261 stream.flush();
262 SkDebugf("Captured Drawing Output (%d bytes) for frame. %s", stream.bytesWritten(), prop);
263 }
264 }
265 surface->getCanvas()->drawPicture(picture);
266 }
267
268 ATRACE_NAME("flush commands");
269 canvas->flush();
270}
271
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500272void SkiaPipeline::dumpResourceCacheUsage() const {
273 int resources, maxResources;
274 size_t bytes, maxBytes;
275 mRenderThread.getGrContext()->getResourceCacheUsage(&resources, &bytes);
276 mRenderThread.getGrContext()->getResourceCacheLimits(&maxResources, &maxBytes);
277
278 SkString log("Resource Cache Usage:\n");
279 log.appendf("%8d items out of %d maximum items\n", resources, maxResources);
280 log.appendf("%8zu bytes (%.2f MB) out of %.2f MB maximum\n",
281 bytes, bytes * (1.0f / (1024.0f * 1024.0f)), maxBytes * (1.0f / (1024.0f * 1024.0f)));
282
283 ALOGD("%s", log.c_str());
284}
285
Stan Iliev500a0c32016-10-26 10:30:09 -0400286} /* namespace skiapipeline */
287} /* namespace uirenderer */
288} /* namespace android */