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