blob: 79fe4d3137413e17f7b7dbf056dcbb11935a4e93 [file] [log] [blame]
Chris Craik05f3d6e2014-06-02 16:27:04 -07001/*
2 * Copyright (C) 2014 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#define LOG_TAG "OpenGLRenderer"
18#define ATRACE_TAG ATRACE_TAG_VIEW
19
20#include <utils/JenkinsHash.h>
21#include <utils/Trace.h>
22
23#include "Caches.h"
24#include "OpenGLRenderer.h"
25#include "PathTessellator.h"
26#include "ShadowTessellator.h"
27#include "TessellationCache.h"
28
29#include "thread/Signal.h"
30#include "thread/Task.h"
31#include "thread/TaskProcessor.h"
32
33namespace android {
34namespace uirenderer {
35
36///////////////////////////////////////////////////////////////////////////////
37// Cache entries
38///////////////////////////////////////////////////////////////////////////////
39
40TessellationCache::Description::Description()
41 : type(kNone)
42 , cap(SkPaint::kDefault_Cap)
43 , style(SkPaint::kFill_Style)
44 , strokeWidth(1.0f) {
45 memset(&shape, 0, sizeof(Shape));
46}
47
48TessellationCache::Description::Description(Type type)
49 : type(type)
50 , cap(SkPaint::kDefault_Cap)
51 , style(SkPaint::kFill_Style)
52 , strokeWidth(1.0f) {
53 memset(&shape, 0, sizeof(Shape));
54}
55
56TessellationCache::Description::Description(Type type, const SkPaint* paint)
57 : type(type)
58 , cap(paint->getStrokeCap())
59 , style(paint->getStyle())
60 , strokeWidth(paint->getStrokeWidth()) {
61 memset(&shape, 0, sizeof(Shape));
62}
63
64hash_t TessellationCache::Description::hash() const {
65 uint32_t hash = JenkinsHashMix(0, type);
66 hash = JenkinsHashMix(hash, cap);
67 hash = JenkinsHashMix(hash, style);
68 hash = JenkinsHashMix(hash, android::hash_type(strokeWidth));
69 hash = JenkinsHashMixBytes(hash, (uint8_t*) &shape, sizeof(Shape));
70 return JenkinsHashWhiten(hash);
71}
72
73TessellationCache::ShadowDescription::ShadowDescription()
74 : nodeKey(NULL) {
75 memset(&matrixData, 0, 16 * sizeof(float));
76}
77
78TessellationCache::ShadowDescription::ShadowDescription(const void* nodeKey, const Matrix4* drawTransform)
79 : nodeKey(nodeKey) {
80 memcpy(&matrixData, drawTransform->data, 16 * sizeof(float));
81}
82
83hash_t TessellationCache::ShadowDescription::hash() const {
84 uint32_t hash = JenkinsHashMixBytes(0, (uint8_t*) &nodeKey, sizeof(const void*));
85 hash = JenkinsHashMixBytes(hash, (uint8_t*) &matrixData, 16 * sizeof(float));
86 return JenkinsHashWhiten(hash);
87}
88
89///////////////////////////////////////////////////////////////////////////////
90// General purpose tessellation task processing
91///////////////////////////////////////////////////////////////////////////////
92
93class TessellationCache::TessellationTask : public Task<VertexBuffer*> {
94public:
95 TessellationTask(Tessellator tessellator, const Description& description,
96 const SkPaint* paint)
97 : tessellator(tessellator)
98 , description(description)
99 , paint(*paint) {
100 }
101
102 ~TessellationTask() {}
103
104 Tessellator tessellator;
105 Description description;
106
107 //copied, since input paint may not be immutable
108 const SkPaint paint;
109};
110
111class TessellationCache::TessellationProcessor : public TaskProcessor<VertexBuffer*> {
112public:
113 TessellationProcessor(Caches& caches)
114 : TaskProcessor<VertexBuffer*>(&caches.tasks) {}
115 ~TessellationProcessor() {}
116
117 virtual void onProcess(const sp<Task<VertexBuffer*> >& task) {
118 TessellationTask* t = static_cast<TessellationTask*>(task.get());
119 ATRACE_NAME("shape tessellation");
120 VertexBuffer* buffer = t->tessellator(t->description, t->paint);
121 t->setResult(buffer);
122 }
123};
124
125struct TessellationCache::Buffer {
126public:
127 Buffer(const sp<Task<VertexBuffer*> >& task)
128 : mTask(task)
129 , mBuffer(NULL) {
130 }
131
132 ~Buffer() {
133 mTask.clear();
134 delete mBuffer;
135 }
136
137 unsigned int getSize() {
138 blockOnPrecache();
139 return mBuffer->getSize();
140 }
141
142 const VertexBuffer* getVertexBuffer() {
143 blockOnPrecache();
144 return mBuffer;
145 }
146
147private:
148 void blockOnPrecache() {
149 if (mTask != NULL) {
150 mBuffer = mTask->getResult();
151 LOG_ALWAYS_FATAL_IF(mBuffer == NULL, "Failed to precache");
152 mTask.clear();
153 }
154 }
155 sp<Task<VertexBuffer*> > mTask;
156 VertexBuffer* mBuffer;
157};
158
159///////////////////////////////////////////////////////////////////////////////
160// Shadow tessellation task processing
161///////////////////////////////////////////////////////////////////////////////
162
163class ShadowTask : public Task<TessellationCache::vertexBuffer_pair_t*> {
164public:
165 ShadowTask(const Matrix4* drawTransform, const Rect& localClip, bool opaque,
166 const SkPath* casterPerimeter, const Matrix4* transformXY, const Matrix4* transformZ,
167 const Vector3& lightCenter, float lightRadius)
Chris Craik1b3be082014-06-11 13:44:19 -0700168 : drawTransform(*drawTransform)
Chris Craik05f3d6e2014-06-02 16:27:04 -0700169 , localClip(localClip)
170 , opaque(opaque)
Chris Craik1b3be082014-06-11 13:44:19 -0700171 , casterPerimeter(*casterPerimeter)
172 , transformXY(*transformXY)
173 , transformZ(*transformZ)
Chris Craik05f3d6e2014-06-02 16:27:04 -0700174 , lightCenter(lightCenter)
175 , lightRadius(lightRadius) {
176 }
177
178 ~ShadowTask() {
179 TessellationCache::vertexBuffer_pair_t* bufferPair = getResult();
180 delete bufferPair->getFirst();
181 delete bufferPair->getSecond();
182 delete bufferPair;
183 }
184
Chris Craik1b3be082014-06-11 13:44:19 -0700185 /* Note - we deep copy all task parameters, because *even though* pointers into Allocator
186 * controlled objects (like the SkPath and Matrix4s) should be safe for the entire frame,
187 * certain Allocators are destroyed before trim() is called to flush incomplete tasks.
188 *
189 * These deep copies could be avoided, long term, by cancelling or flushing outstanding tasks
190 * before tearning down single-frame LinearAllocators.
191 */
192 const Matrix4 drawTransform;
Chris Craik05f3d6e2014-06-02 16:27:04 -0700193 const Rect localClip;
194 bool opaque;
Chris Craik1b3be082014-06-11 13:44:19 -0700195 const SkPath casterPerimeter;
196 const Matrix4 transformXY;
197 const Matrix4 transformZ;
Chris Craik05f3d6e2014-06-02 16:27:04 -0700198 const Vector3 lightCenter;
199 const float lightRadius;
200};
201
202static void mapPointFakeZ(Vector3& point, const mat4* transformXY, const mat4* transformZ) {
203 // map z coordinate with true 3d matrix
204 point.z = transformZ->mapZ(point);
205
206 // map x,y coordinates with draw/Skia matrix
207 transformXY->mapPoint(point.x, point.y);
208}
209
210static void tessellateShadows(
211 const Matrix4* drawTransform, const Rect* localClip,
212 bool isCasterOpaque, const SkPath* casterPerimeter,
213 const Matrix4* casterTransformXY, const Matrix4* casterTransformZ,
214 const Vector3& lightCenter, float lightRadius,
215 VertexBuffer& ambientBuffer, VertexBuffer& spotBuffer) {
216
217 // tessellate caster outline into a 2d polygon
218 Vector<Vertex> casterVertices2d;
219 const float casterRefinementThresholdSquared = 20.0f; // TODO: experiment with this value
220 PathTessellator::approximatePathOutlineVertices(*casterPerimeter,
221 casterRefinementThresholdSquared, casterVertices2d);
222 if (!ShadowTessellator::isClockwisePath(*casterPerimeter)) {
223 ShadowTessellator::reverseVertexArray(casterVertices2d.editArray(),
224 casterVertices2d.size());
225 }
226
227 if (casterVertices2d.size() == 0) return;
228
229 // map 2d caster poly into 3d
230 const int casterVertexCount = casterVertices2d.size();
231 Vector3 casterPolygon[casterVertexCount];
232 float minZ = FLT_MAX;
233 float maxZ = -FLT_MAX;
234 for (int i = 0; i < casterVertexCount; i++) {
235 const Vertex& point2d = casterVertices2d[i];
236 casterPolygon[i] = Vector3(point2d.x, point2d.y, 0);
237 mapPointFakeZ(casterPolygon[i], casterTransformXY, casterTransformZ);
238 minZ = fmin(minZ, casterPolygon[i].z);
239 maxZ = fmax(maxZ, casterPolygon[i].z);
240 }
241
242 // map the centroid of the caster into 3d
243 Vector2 centroid = ShadowTessellator::centroid2d(
244 reinterpret_cast<const Vector2*>(casterVertices2d.array()),
245 casterVertexCount);
246 Vector3 centroid3d(centroid.x, centroid.y, 0);
247 mapPointFakeZ(centroid3d, casterTransformXY, casterTransformZ);
248
249 // if the caster intersects the z=0 plane, lift it in Z so it doesn't
250 if (minZ < SHADOW_MIN_CASTER_Z) {
251 float casterLift = SHADOW_MIN_CASTER_Z - minZ;
252 for (int i = 0; i < casterVertexCount; i++) {
253 casterPolygon[i].z += casterLift;
254 }
255 centroid3d.z += casterLift;
256 }
257
258 // Check whether we want to draw the shadow at all by checking the caster's bounds against clip.
259 // We only have ortho projection, so we can just ignore the Z in caster for
260 // simple rejection calculation.
261 Rect casterBounds(casterPerimeter->getBounds());
262 casterTransformXY->mapRect(casterBounds);
263
264 // actual tessellation of both shadows
265 ShadowTessellator::tessellateAmbientShadow(
266 isCasterOpaque, casterPolygon, casterVertexCount, centroid3d,
267 casterBounds, *localClip, maxZ, ambientBuffer);
268
269 ShadowTessellator::tessellateSpotShadow(
270 isCasterOpaque, casterPolygon, casterVertexCount,
271 *drawTransform, lightCenter, lightRadius, casterBounds, *localClip,
272 spotBuffer);
273
274 // TODO: set ambientBuffer & spotBuffer's bounds for correct layer damage
275}
276
277class ShadowProcessor : public TaskProcessor<TessellationCache::vertexBuffer_pair_t*> {
278public:
279 ShadowProcessor(Caches& caches)
280 : TaskProcessor<TessellationCache::vertexBuffer_pair_t*>(&caches.tasks) {}
281 ~ShadowProcessor() {}
282
283 virtual void onProcess(const sp<Task<TessellationCache::vertexBuffer_pair_t*> >& task) {
284 ShadowTask* t = static_cast<ShadowTask*>(task.get());
285 ATRACE_NAME("shadow tessellation");
286
287 VertexBuffer* ambientBuffer = new VertexBuffer;
288 VertexBuffer* spotBuffer = new VertexBuffer;
Chris Craik1b3be082014-06-11 13:44:19 -0700289 tessellateShadows(&t->drawTransform, &t->localClip, t->opaque, &t->casterPerimeter,
290 &t->transformXY, &t->transformZ, t->lightCenter, t->lightRadius,
Chris Craik05f3d6e2014-06-02 16:27:04 -0700291 *ambientBuffer, *spotBuffer);
292
293 t->setResult(new TessellationCache::vertexBuffer_pair_t(ambientBuffer, spotBuffer));
294 }
295};
296
297///////////////////////////////////////////////////////////////////////////////
298// Cache constructor/destructor
299///////////////////////////////////////////////////////////////////////////////
300
301TessellationCache::TessellationCache()
302 : mSize(0)
303 , mMaxSize(MB(DEFAULT_VERTEX_CACHE_SIZE))
304 , mCache(LruCache<Description, Buffer*>::kUnlimitedCapacity)
305 , mShadowCache(LruCache<ShadowDescription, Task<vertexBuffer_pair_t*>*>::kUnlimitedCapacity) {
306 char property[PROPERTY_VALUE_MAX];
307 if (property_get(PROPERTY_VERTEX_CACHE_SIZE, property, NULL) > 0) {
308 INIT_LOGD(" Setting %s cache size to %sMB", name, property);
309 setMaxSize(MB(atof(property)));
310 } else {
311 INIT_LOGD(" Using default %s cache size of %.2fMB", name, DEFAULT_VERTEX_CACHE_SIZE);
312 }
313
314 mCache.setOnEntryRemovedListener(&mBufferRemovedListener);
315 mShadowCache.setOnEntryRemovedListener(&mBufferPairRemovedListener);
316 mDebugEnabled = readDebugLevel() & kDebugCaches;
317}
318
319TessellationCache::~TessellationCache() {
320 mCache.clear();
321}
322
323///////////////////////////////////////////////////////////////////////////////
324// Size management
325///////////////////////////////////////////////////////////////////////////////
326
327uint32_t TessellationCache::getSize() {
328 LruCache<Description, Buffer*>::Iterator iter(mCache);
329 uint32_t size = 0;
330 while (iter.next()) {
331 size += iter.value()->getSize();
332 }
333 return size;
334}
335
336uint32_t TessellationCache::getMaxSize() {
337 return mMaxSize;
338}
339
340void TessellationCache::setMaxSize(uint32_t maxSize) {
341 mMaxSize = maxSize;
342 while (mSize > mMaxSize) {
343 mCache.removeOldest();
344 }
345}
346
347///////////////////////////////////////////////////////////////////////////////
348// Caching
349///////////////////////////////////////////////////////////////////////////////
350
351
352void TessellationCache::trim() {
353 uint32_t size = getSize();
354 while (size > mMaxSize) {
355 size -= mCache.peekOldestValue()->getSize();
356 mCache.removeOldest();
357 }
358 mShadowCache.clear();
359}
360
361void TessellationCache::clear() {
362 mCache.clear();
363 mShadowCache.clear();
364}
365
366///////////////////////////////////////////////////////////////////////////////
367// Callbacks
368///////////////////////////////////////////////////////////////////////////////
369
370void TessellationCache::BufferRemovedListener::operator()(Description& description,
371 Buffer*& buffer) {
372 delete buffer;
373}
374
375///////////////////////////////////////////////////////////////////////////////
376// Shadows
377///////////////////////////////////////////////////////////////////////////////
378
379void TessellationCache::precacheShadows(const Matrix4* drawTransform, const Rect& localClip,
380 bool opaque, const SkPath* casterPerimeter,
381 const Matrix4* transformXY, const Matrix4* transformZ,
382 const Vector3& lightCenter, float lightRadius) {
383 ShadowDescription key(casterPerimeter, drawTransform);
384
385 sp<ShadowTask> task = new ShadowTask(drawTransform, localClip, opaque,
386 casterPerimeter, transformXY, transformZ, lightCenter, lightRadius);
387 if (mShadowProcessor == NULL) {
388 mShadowProcessor = new ShadowProcessor(Caches::getInstance());
389 }
390 mShadowProcessor->add(task);
391
392 task->incStrong(NULL); // not using sp<>s, so manually ref while in the cache
393 mShadowCache.put(key, task.get());
394}
395
396void TessellationCache::getShadowBuffers(const Matrix4* drawTransform, const Rect& localClip,
397 bool opaque, const SkPath* casterPerimeter,
398 const Matrix4* transformXY, const Matrix4* transformZ,
399 const Vector3& lightCenter, float lightRadius, vertexBuffer_pair_t& outBuffers) {
400 ShadowDescription key(casterPerimeter, drawTransform);
401 ShadowTask* task = static_cast<ShadowTask*>(mShadowCache.get(key));
402 if (!task) {
403 precacheShadows(drawTransform, localClip, opaque, casterPerimeter,
404 transformXY, transformZ, lightCenter, lightRadius);
405 task = static_cast<ShadowTask*>(mShadowCache.get(key));
406 }
407 LOG_ALWAYS_FATAL_IF(task == NULL, "shadow not precached");
408 outBuffers = *(task->getResult());
409}
410
411///////////////////////////////////////////////////////////////////////////////
412// Tessellation precaching
413///////////////////////////////////////////////////////////////////////////////
414
415static VertexBuffer* tessellatePath(const SkPath& path, const SkPaint* paint,
416 float scaleX, float scaleY) {
417 VertexBuffer* buffer = new VertexBuffer();
418 Matrix4 matrix;
419 matrix.loadScale(scaleX, scaleY, 1);
420 PathTessellator::tessellatePath(path, paint, matrix, *buffer);
421 return buffer;
422}
423
424TessellationCache::Buffer* TessellationCache::getOrCreateBuffer(
425 const Description& entry, Tessellator tessellator, const SkPaint* paint) {
426 Buffer* buffer = mCache.get(entry);
427 if (!buffer) {
428 // not cached, enqueue a task to fill the buffer
429 sp<TessellationTask> task = new TessellationTask(tessellator, entry, paint);
430 buffer = new Buffer(task);
431
432 if (mProcessor == NULL) {
433 mProcessor = new TessellationProcessor(Caches::getInstance());
434 }
435 mProcessor->add(task);
436 mCache.put(entry, buffer);
437 }
438 return buffer;
439}
440
441///////////////////////////////////////////////////////////////////////////////
442// Rounded rects
443///////////////////////////////////////////////////////////////////////////////
444
445static VertexBuffer* tessellateRoundRect(const TessellationCache::Description& description,
446 const SkPaint& paint) {
447 SkRect rect = SkRect::MakeWH(description.shape.roundRect.mWidth,
448 description.shape.roundRect.mHeight);
449 float rx = description.shape.roundRect.mRx;
450 float ry = description.shape.roundRect.mRy;
451 if (paint.getStyle() == SkPaint::kStrokeAndFill_Style) {
452 float outset = paint.getStrokeWidth() / 2;
453 rect.outset(outset, outset);
454 rx += outset;
455 ry += outset;
456 }
457 SkPath path;
458 path.addRoundRect(rect, rx, ry);
459 return tessellatePath(path, &paint,
460 description.shape.roundRect.mScaleX, description.shape.roundRect.mScaleY);
461}
462
463TessellationCache::Buffer* TessellationCache::getRoundRectBuffer(const Matrix4& transform,
464 float width, float height, float rx, float ry, const SkPaint* paint) {
465 Description entry(Description::kRoundRect, paint);
466 entry.shape.roundRect.mWidth = width;
467 entry.shape.roundRect.mHeight = height;
468 entry.shape.roundRect.mRx = rx;
469 entry.shape.roundRect.mRy = ry;
470 PathTessellator::extractTessellationScales(transform,
471 &entry.shape.roundRect.mScaleX, &entry.shape.roundRect.mScaleY);
472
473 return getOrCreateBuffer(entry, &tessellateRoundRect, paint);
474}
475const VertexBuffer* TessellationCache::getRoundRect(const Matrix4& transform,
476 float width, float height, float rx, float ry, const SkPaint* paint) {
477 return getRoundRectBuffer(transform, width, height, rx, ry, paint)->getVertexBuffer();
478}
479
480}; // namespace uirenderer
481}; // namespace android