• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 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 <SkBitmap.h>
21 #include <SkCanvas.h>
22 #include <SkPaint.h>
23 #include <SkPath.h>
24 #include <SkRect.h>
25 
26 #include <utils/JenkinsHash.h>
27 #include <utils/Trace.h>
28 
29 #include "Caches.h"
30 #include "PathCache.h"
31 
32 #include "thread/Signal.h"
33 #include "thread/Task.h"
34 #include "thread/TaskProcessor.h"
35 
36 namespace android {
37 namespace uirenderer {
38 
39 ///////////////////////////////////////////////////////////////////////////////
40 // Cache entries
41 ///////////////////////////////////////////////////////////////////////////////
42 
PathDescription()43 PathDescription::PathDescription():
44         type(kShapeNone),
45         join(SkPaint::kDefault_Join),
46         cap(SkPaint::kDefault_Cap),
47         style(SkPaint::kFill_Style),
48         miter(4.0f),
49         strokeWidth(1.0f),
50         pathEffect(NULL) {
51     memset(&shape, 0, sizeof(Shape));
52 }
53 
PathDescription(ShapeType type,SkPaint * paint)54 PathDescription::PathDescription(ShapeType type, SkPaint* paint):
55         type(type),
56         join(paint->getStrokeJoin()),
57         cap(paint->getStrokeCap()),
58         style(paint->getStyle()),
59         miter(paint->getStrokeMiter()),
60         strokeWidth(paint->getStrokeWidth()),
61         pathEffect(paint->getPathEffect()) {
62     memset(&shape, 0, sizeof(Shape));
63 }
64 
hash() const65 hash_t PathDescription::hash() const {
66     uint32_t hash = JenkinsHashMix(0, type);
67     hash = JenkinsHashMix(hash, join);
68     hash = JenkinsHashMix(hash, cap);
69     hash = JenkinsHashMix(hash, style);
70     hash = JenkinsHashMix(hash, android::hash_type(miter));
71     hash = JenkinsHashMix(hash, android::hash_type(strokeWidth));
72     hash = JenkinsHashMix(hash, android::hash_type(pathEffect));
73     hash = JenkinsHashMixBytes(hash, (uint8_t*) &shape, sizeof(Shape));
74     return JenkinsHashWhiten(hash);
75 }
76 
compare(const PathDescription & rhs) const77 int PathDescription::compare(const PathDescription& rhs) const {
78     return memcmp(this, &rhs, sizeof(PathDescription));
79 }
80 
81 ///////////////////////////////////////////////////////////////////////////////
82 // Utilities
83 ///////////////////////////////////////////////////////////////////////////////
84 
canDrawAsConvexPath(SkPath * path,SkPaint * paint)85 bool PathCache::canDrawAsConvexPath(SkPath* path, SkPaint* paint) {
86     // NOTE: This should only be used after PathTessellator handles joins properly
87     return paint->getPathEffect() == NULL && path->getConvexity() == SkPath::kConvex_Convexity;
88 }
89 
computePathBounds(const SkPath * path,const SkPaint * paint,float & left,float & top,float & offset,uint32_t & width,uint32_t & height)90 void PathCache::computePathBounds(const SkPath* path, const SkPaint* paint,
91         float& left, float& top, float& offset, uint32_t& width, uint32_t& height) {
92     const SkRect& bounds = path->getBounds();
93     PathCache::computeBounds(bounds, paint, left, top, offset, width, height);
94 }
95 
computeBounds(const SkRect & bounds,const SkPaint * paint,float & left,float & top,float & offset,uint32_t & width,uint32_t & height)96 void PathCache::computeBounds(const SkRect& bounds, const SkPaint* paint,
97         float& left, float& top, float& offset, uint32_t& width, uint32_t& height) {
98     const float pathWidth = fmax(bounds.width(), 1.0f);
99     const float pathHeight = fmax(bounds.height(), 1.0f);
100 
101     left = bounds.fLeft;
102     top = bounds.fTop;
103 
104     offset = (int) floorf(fmax(paint->getStrokeWidth(), 1.0f) * 1.5f + 0.5f);
105 
106     width = uint32_t(pathWidth + offset * 2.0 + 0.5);
107     height = uint32_t(pathHeight + offset * 2.0 + 0.5);
108 }
109 
initBitmap(SkBitmap & bitmap,uint32_t width,uint32_t height)110 static void initBitmap(SkBitmap& bitmap, uint32_t width, uint32_t height) {
111     bitmap.setConfig(SkBitmap::kA8_Config, width, height);
112     bitmap.allocPixels();
113     bitmap.eraseColor(0);
114 }
115 
initPaint(SkPaint & paint)116 static void initPaint(SkPaint& paint) {
117     // Make sure the paint is opaque, color, alpha, filter, etc.
118     // will be applied later when compositing the alpha8 texture
119     paint.setColor(0xff000000);
120     paint.setAlpha(255);
121     paint.setColorFilter(NULL);
122     paint.setMaskFilter(NULL);
123     paint.setShader(NULL);
124     SkXfermode* mode = SkXfermode::Create(SkXfermode::kSrc_Mode);
125     SkSafeUnref(paint.setXfermode(mode));
126 }
127 
drawPath(const SkPath * path,const SkPaint * paint,SkBitmap & bitmap,float left,float top,float offset,uint32_t width,uint32_t height)128 static void drawPath(const SkPath *path, const SkPaint* paint, SkBitmap& bitmap,
129         float left, float top, float offset, uint32_t width, uint32_t height) {
130     initBitmap(bitmap, width, height);
131 
132     SkPaint pathPaint(*paint);
133     initPaint(pathPaint);
134 
135     SkCanvas canvas(bitmap);
136     canvas.translate(-left + offset, -top + offset);
137     canvas.drawPath(*path, pathPaint);
138 }
139 
createTexture(float left,float top,float offset,uint32_t width,uint32_t height,uint32_t id)140 static PathTexture* createTexture(float left, float top, float offset,
141         uint32_t width, uint32_t height, uint32_t id) {
142     PathTexture* texture = new PathTexture();
143     texture->left = left;
144     texture->top = top;
145     texture->offset = offset;
146     texture->width = width;
147     texture->height = height;
148     texture->generation = id;
149     return texture;
150 }
151 
152 ///////////////////////////////////////////////////////////////////////////////
153 // Cache constructor/destructor
154 ///////////////////////////////////////////////////////////////////////////////
155 
PathCache()156 PathCache::PathCache():
157         mCache(LruCache<PathDescription, PathTexture*>::kUnlimitedCapacity),
158         mSize(0), mMaxSize(MB(DEFAULT_PATH_CACHE_SIZE)) {
159     char property[PROPERTY_VALUE_MAX];
160     if (property_get(PROPERTY_PATH_CACHE_SIZE, property, NULL) > 0) {
161         INIT_LOGD("  Setting %s cache size to %sMB", name, property);
162         setMaxSize(MB(atof(property)));
163     } else {
164         INIT_LOGD("  Using default %s cache size of %.2fMB", name, DEFAULT_PATH_CACHE_SIZE);
165     }
166     init();
167 }
168 
~PathCache()169 PathCache::~PathCache() {
170     mCache.clear();
171 }
172 
init()173 void PathCache::init() {
174     mCache.setOnEntryRemovedListener(this);
175 
176     GLint maxTextureSize;
177     glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
178     mMaxTextureSize = maxTextureSize;
179 
180     mDebugEnabled = readDebugLevel() & kDebugCaches;
181 }
182 
183 ///////////////////////////////////////////////////////////////////////////////
184 // Size management
185 ///////////////////////////////////////////////////////////////////////////////
186 
getSize()187 uint32_t PathCache::getSize() {
188     return mSize;
189 }
190 
getMaxSize()191 uint32_t PathCache::getMaxSize() {
192     return mMaxSize;
193 }
194 
setMaxSize(uint32_t maxSize)195 void PathCache::setMaxSize(uint32_t maxSize) {
196     mMaxSize = maxSize;
197     while (mSize > mMaxSize) {
198         mCache.removeOldest();
199     }
200 }
201 
202 ///////////////////////////////////////////////////////////////////////////////
203 // Callbacks
204 ///////////////////////////////////////////////////////////////////////////////
205 
operator ()(PathDescription & entry,PathTexture * & texture)206 void PathCache::operator()(PathDescription& entry, PathTexture*& texture) {
207     removeTexture(texture);
208 }
209 
210 ///////////////////////////////////////////////////////////////////////////////
211 // Caching
212 ///////////////////////////////////////////////////////////////////////////////
213 
removeTexture(PathTexture * texture)214 void PathCache::removeTexture(PathTexture* texture) {
215     if (texture) {
216         const uint32_t size = texture->width * texture->height;
217         mSize -= size;
218 
219         PATH_LOGD("PathCache::delete name, size, mSize = %d, %d, %d",
220                 texture->id, size, mSize);
221         if (mDebugEnabled) {
222             ALOGD("Shape deleted, size = %d", size);
223         }
224 
225         if (texture->id) {
226             glDeleteTextures(1, &texture->id);
227         }
228         delete texture;
229     }
230 }
231 
purgeCache(uint32_t width,uint32_t height)232 void PathCache::purgeCache(uint32_t width, uint32_t height) {
233     const uint32_t size = width * height;
234     // Don't even try to cache a bitmap that's bigger than the cache
235     if (size < mMaxSize) {
236         while (mSize + size > mMaxSize) {
237             mCache.removeOldest();
238         }
239     }
240 }
241 
trim()242 void PathCache::trim() {
243     while (mSize > mMaxSize) {
244         mCache.removeOldest();
245     }
246 }
247 
addTexture(const PathDescription & entry,const SkPath * path,const SkPaint * paint)248 PathTexture* PathCache::addTexture(const PathDescription& entry, const SkPath *path,
249         const SkPaint* paint) {
250     ATRACE_CALL();
251 
252     float left, top, offset;
253     uint32_t width, height;
254     computePathBounds(path, paint, left, top, offset, width, height);
255 
256     if (!checkTextureSize(width, height)) return NULL;
257 
258     purgeCache(width, height);
259 
260     SkBitmap bitmap;
261     drawPath(path, paint, bitmap, left, top, offset, width, height);
262 
263     PathTexture* texture = createTexture(left, top, offset, width, height,
264             path->getGenerationID());
265     generateTexture(entry, &bitmap, texture);
266 
267     return texture;
268 }
269 
generateTexture(const PathDescription & entry,SkBitmap * bitmap,PathTexture * texture,bool addToCache)270 void PathCache::generateTexture(const PathDescription& entry, SkBitmap* bitmap,
271         PathTexture* texture, bool addToCache) {
272     generateTexture(*bitmap, texture);
273 
274     uint32_t size = texture->width * texture->height;
275     if (size < mMaxSize) {
276         mSize += size;
277         PATH_LOGD("PathCache::get/create: name, size, mSize = %d, %d, %d",
278                 texture->id, size, mSize);
279         if (mDebugEnabled) {
280             ALOGD("Shape created, size = %d", size);
281         }
282         if (addToCache) {
283             mCache.put(entry, texture);
284         }
285     } else {
286         texture->cleanup = true;
287     }
288 }
289 
clear()290 void PathCache::clear() {
291     mCache.clear();
292 }
293 
generateTexture(SkBitmap & bitmap,Texture * texture)294 void PathCache::generateTexture(SkBitmap& bitmap, Texture* texture) {
295     SkAutoLockPixels alp(bitmap);
296     if (!bitmap.readyToDraw()) {
297         ALOGE("Cannot generate texture from bitmap");
298         return;
299     }
300 
301     glGenTextures(1, &texture->id);
302 
303     glBindTexture(GL_TEXTURE_2D, texture->id);
304     // Textures are Alpha8
305     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
306 
307     texture->blend = true;
308     glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, texture->width, texture->height, 0,
309             GL_ALPHA, GL_UNSIGNED_BYTE, bitmap.getPixels());
310 
311     texture->setFilter(GL_LINEAR);
312     texture->setWrap(GL_CLAMP_TO_EDGE);
313 }
314 
315 ///////////////////////////////////////////////////////////////////////////////
316 // Path precaching
317 ///////////////////////////////////////////////////////////////////////////////
318 
PathProcessor(Caches & caches)319 PathCache::PathProcessor::PathProcessor(Caches& caches):
320         TaskProcessor<SkBitmap*>(&caches.tasks), mMaxTextureSize(caches.maxTextureSize) {
321 }
322 
onProcess(const sp<Task<SkBitmap * >> & task)323 void PathCache::PathProcessor::onProcess(const sp<Task<SkBitmap*> >& task) {
324     sp<PathTask> t = static_cast<PathTask* >(task.get());
325     ATRACE_NAME("pathPrecache");
326 
327     float left, top, offset;
328     uint32_t width, height;
329     PathCache::computePathBounds(t->path, t->paint, left, top, offset, width, height);
330 
331     PathTexture* texture = t->texture;
332     texture->left = left;
333     texture->top = top;
334     texture->offset = offset;
335     texture->width = width;
336     texture->height = height;
337 
338     if (width <= mMaxTextureSize && height <= mMaxTextureSize) {
339         SkBitmap* bitmap = new SkBitmap();
340         drawPath(t->path, t->paint, *bitmap, left, top, offset, width, height);
341         t->setResult(bitmap);
342     } else {
343         texture->width = 0;
344         texture->height = 0;
345         t->setResult(NULL);
346     }
347 }
348 
349 ///////////////////////////////////////////////////////////////////////////////
350 // Paths
351 ///////////////////////////////////////////////////////////////////////////////
352 
remove(const path_pair_t & pair)353 void PathCache::remove(const path_pair_t& pair) {
354     Vector<PathDescription> pathsToRemove;
355     LruCache<PathDescription, PathTexture*>::Iterator i(mCache);
356 
357     while (i.next()) {
358         const PathDescription& key = i.key();
359         if (key.type == kShapePath &&
360                 (key.shape.path.mPath == pair.getFirst() ||
361                         key.shape.path.mPath == pair.getSecond())) {
362             pathsToRemove.push(key);
363         }
364     }
365 
366     for (size_t i = 0; i < pathsToRemove.size(); i++) {
367         mCache.remove(pathsToRemove.itemAt(i));
368     }
369 }
370 
removeDeferred(SkPath * path)371 void PathCache::removeDeferred(SkPath* path) {
372     Mutex::Autolock l(mLock);
373     mGarbage.push(path_pair_t(path, const_cast<SkPath*>(path->getSourcePath())));
374 }
375 
clearGarbage()376 void PathCache::clearGarbage() {
377     Mutex::Autolock l(mLock);
378     size_t count = mGarbage.size();
379     for (size_t i = 0; i < count; i++) {
380         remove(mGarbage.itemAt(i));
381     }
382     mGarbage.clear();
383 }
384 
385 /**
386  * To properly handle path mutations at draw time we always make a copy
387  * of paths objects when recording display lists. The source path points
388  * to the path we originally copied the path from. This ensures we use
389  * the original path as a cache key the first time a path is inserted
390  * in the cache. The source path is also used to reclaim garbage when a
391  * Dalvik Path object is collected.
392  */
getSourcePath(SkPath * path)393 static SkPath* getSourcePath(SkPath* path) {
394     const SkPath* sourcePath = path->getSourcePath();
395     if (sourcePath && sourcePath->getGenerationID() == path->getGenerationID()) {
396         return const_cast<SkPath*>(sourcePath);
397     }
398     return path;
399 }
400 
get(SkPath * path,SkPaint * paint)401 PathTexture* PathCache::get(SkPath* path, SkPaint* paint) {
402     path = getSourcePath(path);
403 
404     PathDescription entry(kShapePath, paint);
405     entry.shape.path.mPath = path;
406 
407     PathTexture* texture = mCache.get(entry);
408 
409     if (!texture) {
410         texture = addTexture(entry, path, paint);
411     } else {
412         // A bitmap is attached to the texture, this means we need to
413         // upload it as a GL texture
414         const sp<Task<SkBitmap*> >& task = texture->task();
415         if (task != NULL) {
416             // But we must first wait for the worker thread to be done
417             // producing the bitmap, so let's wait
418             SkBitmap* bitmap = task->getResult();
419             if (bitmap) {
420                 generateTexture(entry, bitmap, texture, false);
421                 texture->clearTask();
422             } else {
423                 ALOGW("Path too large to be rendered into a texture");
424                 texture->clearTask();
425                 texture = NULL;
426                 mCache.remove(entry);
427             }
428         } else if (path->getGenerationID() != texture->generation) {
429             // The size of the path might have changed so we first
430             // remove the entry from the cache
431             mCache.remove(entry);
432             texture = addTexture(entry, path, paint);
433         }
434     }
435 
436     return texture;
437 }
438 
precache(SkPath * path,SkPaint * paint)439 void PathCache::precache(SkPath* path, SkPaint* paint) {
440     if (!Caches::getInstance().tasks.canRunTasks()) {
441         return;
442     }
443 
444     path = getSourcePath(path);
445 
446     PathDescription entry(kShapePath, paint);
447     entry.shape.path.mPath = path;
448 
449     PathTexture* texture = mCache.get(entry);
450 
451     bool generate = false;
452     if (!texture) {
453         generate = true;
454     } else if (path->getGenerationID() != texture->generation) {
455         mCache.remove(entry);
456         generate = true;
457     }
458 
459     if (generate) {
460         // It is important to specify the generation ID so we do not
461         // attempt to precache the same path several times
462         texture = createTexture(0.0f, 0.0f, 0.0f, 0, 0, path->getGenerationID());
463         sp<PathTask> task = new PathTask(path, paint, texture);
464         texture->setTask(task);
465 
466         // During the precaching phase we insert path texture objects into
467         // the cache that do not point to any GL texture. They are instead
468         // treated as a task for the precaching worker thread. This is why
469         // we do not check the cache limit when inserting these objects.
470         // The conversion into GL texture will happen in get(), when a client
471         // asks for a path texture. This is also when the cache limit will
472         // be enforced.
473         mCache.put(entry, texture);
474 
475         if (mProcessor == NULL) {
476             mProcessor = new PathProcessor(Caches::getInstance());
477         }
478         mProcessor->add(task);
479     }
480 }
481 
482 ///////////////////////////////////////////////////////////////////////////////
483 // Rounded rects
484 ///////////////////////////////////////////////////////////////////////////////
485 
getRoundRect(float width,float height,float rx,float ry,SkPaint * paint)486 PathTexture* PathCache::getRoundRect(float width, float height,
487         float rx, float ry, SkPaint* paint) {
488     PathDescription entry(kShapeRoundRect, paint);
489     entry.shape.roundRect.mWidth = width;
490     entry.shape.roundRect.mHeight = height;
491     entry.shape.roundRect.mRx = rx;
492     entry.shape.roundRect.mRy = ry;
493 
494     PathTexture* texture = get(entry);
495 
496     if (!texture) {
497         SkPath path;
498         SkRect r;
499         r.set(0.0f, 0.0f, width, height);
500         path.addRoundRect(r, rx, ry, SkPath::kCW_Direction);
501 
502         texture = addTexture(entry, &path, paint);
503     }
504 
505     return texture;
506 }
507 
508 ///////////////////////////////////////////////////////////////////////////////
509 // Circles
510 ///////////////////////////////////////////////////////////////////////////////
511 
getCircle(float radius,SkPaint * paint)512 PathTexture* PathCache::getCircle(float radius, SkPaint* paint) {
513     PathDescription entry(kShapeCircle, paint);
514     entry.shape.circle.mRadius = radius;
515 
516     PathTexture* texture = get(entry);
517 
518     if (!texture) {
519         SkPath path;
520         path.addCircle(radius, radius, radius, SkPath::kCW_Direction);
521 
522         texture = addTexture(entry, &path, paint);
523     }
524 
525     return texture;
526 }
527 
528 ///////////////////////////////////////////////////////////////////////////////
529 // Ovals
530 ///////////////////////////////////////////////////////////////////////////////
531 
getOval(float width,float height,SkPaint * paint)532 PathTexture* PathCache::getOval(float width, float height, SkPaint* paint) {
533     PathDescription entry(kShapeOval, paint);
534     entry.shape.oval.mWidth = width;
535     entry.shape.oval.mHeight = height;
536 
537     PathTexture* texture = get(entry);
538 
539     if (!texture) {
540         SkPath path;
541         SkRect r;
542         r.set(0.0f, 0.0f, width, height);
543         path.addOval(r, SkPath::kCW_Direction);
544 
545         texture = addTexture(entry, &path, paint);
546     }
547 
548     return texture;
549 }
550 
551 ///////////////////////////////////////////////////////////////////////////////
552 // Rects
553 ///////////////////////////////////////////////////////////////////////////////
554 
getRect(float width,float height,SkPaint * paint)555 PathTexture* PathCache::getRect(float width, float height, SkPaint* paint) {
556     PathDescription entry(kShapeRect, paint);
557     entry.shape.rect.mWidth = width;
558     entry.shape.rect.mHeight = height;
559 
560     PathTexture* texture = get(entry);
561 
562     if (!texture) {
563         SkPath path;
564         SkRect r;
565         r.set(0.0f, 0.0f, width, height);
566         path.addRect(r, SkPath::kCW_Direction);
567 
568         texture = addTexture(entry, &path, paint);
569     }
570 
571     return texture;
572 }
573 
574 ///////////////////////////////////////////////////////////////////////////////
575 // Arcs
576 ///////////////////////////////////////////////////////////////////////////////
577 
getArc(float width,float height,float startAngle,float sweepAngle,bool useCenter,SkPaint * paint)578 PathTexture* PathCache::getArc(float width, float height,
579         float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) {
580     PathDescription entry(kShapeArc, paint);
581     entry.shape.arc.mWidth = width;
582     entry.shape.arc.mHeight = height;
583     entry.shape.arc.mStartAngle = startAngle;
584     entry.shape.arc.mSweepAngle = sweepAngle;
585     entry.shape.arc.mUseCenter = useCenter;
586 
587     PathTexture* texture = get(entry);
588 
589     if (!texture) {
590         SkPath path;
591         SkRect r;
592         r.set(0.0f, 0.0f, width, height);
593         if (useCenter) {
594             path.moveTo(r.centerX(), r.centerY());
595         }
596         path.arcTo(r, startAngle, sweepAngle, !useCenter);
597         if (useCenter) {
598             path.close();
599         }
600 
601         texture = addTexture(entry, &path, paint);
602     }
603 
604     return texture;
605 }
606 
607 }; // namespace uirenderer
608 }; // namespace android
609