d4f8b70b393858cf8db77f1f116fe893a551b5dd
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / gpu / GrLayerCache.cpp
1 /*
2  * Copyright 2014 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7
8 #include "GrAtlas.h"
9 #include "GrGpu.h"
10 #include "GrLayerCache.h"
11 #include "GrSurfacePriv.h"
12
13 DECLARE_SKMESSAGEBUS_MESSAGE(GrPictureDeletedMessage);
14
15 #ifdef SK_DEBUG
16 void GrCachedLayer::validate(const GrTexture* backingTexture) const {
17     SkASSERT(SK_InvalidGenID != fKey.pictureID());
18     SkASSERT(fKey.start() >= 0);
19
20     if (fTexture) {
21         // If the layer is in some texture then it must occupy some rectangle
22         SkASSERT(!fRect.isEmpty());
23         if (!this->isAtlased()) {
24             // If it isn't atlased then the rectangle should start at the origin
25             SkASSERT(0.0f == fRect.fLeft && 0.0f == fRect.fTop);
26         }
27     } else {
28         SkASSERT(fRect.isEmpty());
29         SkASSERT(NULL == fPlot);
30         SkASSERT(!fLocked);     // layers without a texture cannot be locked
31     }
32
33     if (fPlot) {
34         // If a layer has a plot (i.e., is atlased) then it must point to
35         // the backing texture. Additionally, its rect should be non-empty.
36         SkASSERT(fTexture && backingTexture == fTexture);
37         SkASSERT(!fRect.isEmpty());
38     }
39
40     if (fLocked) {
41         // If a layer is locked it must have a texture (though it need not be
42         // the atlas-backing texture) and occupy some space.
43         SkASSERT(fTexture);
44         SkASSERT(!fRect.isEmpty());
45     }
46
47     // Unfortunately there is a brief time where a layer can be locked
48     // but not used, so we can only check the "used implies locked"
49     // invariant.
50     if (fUses > 0) {
51         SkASSERT(fLocked);
52     } else {
53         SkASSERT(0 == fUses);
54     }
55 }
56
57 class GrAutoValidateLayer : ::SkNoncopyable {
58 public:
59     GrAutoValidateLayer(GrTexture* backingTexture, const GrCachedLayer* layer) 
60         : fBackingTexture(backingTexture)
61         , fLayer(layer) {
62         if (fLayer) {
63             fLayer->validate(backingTexture);
64         }
65     }
66     ~GrAutoValidateLayer() {
67         if (fLayer) {
68             fLayer->validate(fBackingTexture);
69         }
70     }
71     void setBackingTexture(GrTexture* backingTexture) {
72         SkASSERT(NULL == fBackingTexture || fBackingTexture == backingTexture);
73         fBackingTexture = backingTexture;
74     }
75
76 private:
77     const GrTexture* fBackingTexture;
78     const GrCachedLayer* fLayer;
79 };
80 #endif
81
82 GrLayerCache::GrLayerCache(GrContext* context)
83     : fContext(context) {
84     memset(fPlotLocks, 0, sizeof(fPlotLocks));
85 }
86
87 GrLayerCache::~GrLayerCache() {
88
89     SkTDynamicHash<GrCachedLayer, GrCachedLayer::Key>::Iter iter(&fLayerHash);
90     for (; !iter.done(); ++iter) {
91         GrCachedLayer* layer = &(*iter);
92         SkASSERT(0 == layer->uses());
93         this->unlock(layer);
94         SkDELETE(layer);
95     }
96
97     SkASSERT(0 == fPictureHash.count());
98
99     // The atlas only lets go of its texture when the atlas is deleted. 
100     fAtlas.free();    
101 }
102
103 void GrLayerCache::initAtlas() {
104     SkASSERT(NULL == fAtlas.get());
105     GR_STATIC_ASSERT(kNumPlotsX*kNumPlotsX == GrPictureInfo::kNumPlots);
106
107     SkISize textureSize = SkISize::Make(kAtlasTextureWidth, kAtlasTextureHeight);
108     fAtlas.reset(SkNEW_ARGS(GrAtlas, (fContext->getGpu(), kSkia8888_GrPixelConfig,
109                                       kRenderTarget_GrSurfaceFlag,
110                                       textureSize, kNumPlotsX, kNumPlotsY, false)));
111 }
112
113 void GrLayerCache::freeAll() {
114
115     SkTDynamicHash<GrCachedLayer, GrCachedLayer::Key>::Iter iter(&fLayerHash);
116     for (; !iter.done(); ++iter) {
117         GrCachedLayer* layer = &(*iter);
118         this->unlock(layer);
119         SkDELETE(layer);
120     }
121     fLayerHash.rewind();
122
123     // The atlas only lets go of its texture when the atlas is deleted. 
124     fAtlas.free();
125 }
126
127 GrCachedLayer* GrLayerCache::createLayer(uint32_t pictureID, 
128                                          int start, int stop, 
129                                          const SkIRect& bounds,
130                                          const SkMatrix& ctm,
131                                          const SkPaint* paint) {
132     SkASSERT(pictureID != SK_InvalidGenID && start >= 0 && stop > 0);
133
134     GrCachedLayer* layer = SkNEW_ARGS(GrCachedLayer, (pictureID, start, stop, bounds, ctm, paint));
135     fLayerHash.add(layer);
136     return layer;
137 }
138
139 GrCachedLayer* GrLayerCache::findLayer(uint32_t pictureID,
140                                        int start, 
141                                        const SkIRect& bounds,
142                                        const SkMatrix& ctm) {
143     SkASSERT(pictureID != SK_InvalidGenID && start > 0);
144     return fLayerHash.find(GrCachedLayer::Key(pictureID, start, bounds, ctm));
145 }
146
147 GrCachedLayer* GrLayerCache::findLayerOrCreate(uint32_t pictureID,
148                                                int start, int stop,
149                                                const SkIRect& bounds,
150                                                const SkMatrix& ctm,
151                                                const SkPaint* paint) {
152     SkASSERT(pictureID != SK_InvalidGenID && start >= 0 && stop > 0);
153     GrCachedLayer* layer = fLayerHash.find(GrCachedLayer::Key(pictureID, start, bounds, ctm));
154     if (NULL == layer) {
155         layer = this->createLayer(pictureID, start, stop, bounds, ctm, paint);
156     }
157
158     return layer;
159 }
160
161 bool GrLayerCache::tryToAtlas(GrCachedLayer* layer, 
162                               const GrSurfaceDesc& desc, 
163                               bool* needsRendering) {
164     SkDEBUGCODE(GrAutoValidateLayer avl(fAtlas ? fAtlas->getTexture() : NULL, layer);)
165
166     SkASSERT(PlausiblyAtlasable(desc.fWidth, desc.fHeight));
167
168     if (layer->locked()) {
169         // This layer is already locked
170         SkASSERT(fAtlas);
171         SkASSERT(layer->isAtlased());
172         SkASSERT(layer->rect().width() == desc.fWidth);
173         SkASSERT(layer->rect().height() == desc.fHeight);
174         *needsRendering = false;
175         return true;
176     }
177
178     if (layer->isAtlased()) {
179         SkASSERT(fAtlas);
180         // Hooray it is still in the atlas - make sure it stays there
181         layer->setLocked(true);
182         this->incPlotLock(layer->plot()->id());
183         *needsRendering = false;
184         return true;
185     } else {
186         if (!fAtlas) {
187             this->initAtlas();
188             if (!fAtlas) {
189                 return false;
190             }
191         }
192         // Not in the atlas - will it fit?
193         GrPictureInfo* pictInfo = fPictureHash.find(layer->pictureID());
194         if (NULL == pictInfo) {
195             pictInfo = SkNEW_ARGS(GrPictureInfo, (layer->pictureID()));
196             fPictureHash.add(pictInfo);
197         }
198
199         SkIPoint16 loc;
200         for (int i = 0; i < 2; ++i) { // extra pass in case we fail to add but are able to purge
201             GrPlot* plot = fAtlas->addToAtlas(&pictInfo->fPlotUsage,
202                                               desc.fWidth, desc.fHeight,
203                                               NULL, &loc);
204             // addToAtlas can allocate the backing texture
205             SkDEBUGCODE(avl.setBackingTexture(fAtlas->getTexture()));
206             if (plot) {
207 #if !GR_CACHE_HOISTED_LAYERS
208                 pictInfo->incPlotUsage(plot->id());
209 #endif
210                 // The layer was successfully added to the atlas
211                 GrIRect16 bounds = GrIRect16::MakeXYWH(loc.fX, loc.fY,
212                                                        SkToS16(desc.fWidth),
213                                                        SkToS16(desc.fHeight));
214                 layer->setTexture(fAtlas->getTexture(), bounds);
215                 layer->setPlot(plot);
216                 layer->setLocked(true);
217                 this->incPlotLock(layer->plot()->id());
218                 *needsRendering = true;
219                 return true;
220             }
221
222             // The layer was rejected by the atlas (even though we know it is 
223             // plausibly atlas-able). See if a plot can be purged and try again.
224             if (!this->purgePlot()) {
225                 break;  // We weren't able to purge any plots
226             }
227         }
228     }
229
230     return false;
231 }
232
233 bool GrLayerCache::lock(GrCachedLayer* layer, const GrSurfaceDesc& desc, bool* needsRendering) {
234     if (layer->locked()) {
235         // This layer is already locked
236         *needsRendering = false;
237         return true;
238     }
239
240     SkAutoTUnref<GrTexture> tex(
241         fContext->refScratchTexture(desc, GrContext::kApprox_ScratchTexMatch));
242
243     if (!tex) {
244         return false;
245     }
246
247     layer->setTexture(tex, GrIRect16::MakeWH(SkToS16(desc.fWidth), SkToS16(desc.fHeight)));
248     layer->setLocked(true);
249     *needsRendering = true;
250     return true;
251 }
252
253 void GrLayerCache::unlock(GrCachedLayer* layer) {
254     SkDEBUGCODE(GrAutoValidateLayer avl(fAtlas ? fAtlas->getTexture() : NULL, layer);)
255
256     if (NULL == layer || !layer->locked()) {
257         // invalid or not locked
258         return;
259     }
260
261     if (layer->isAtlased()) {
262         const int plotID = layer->plot()->id();
263
264         this->decPlotLock(plotID);
265         // At this point we could aggressively clear out un-locked plots but
266         // by delaying we may be able to reuse some of the atlased layers later.
267 #if !GR_CACHE_HOISTED_LAYERS
268         // This testing code aggressively removes the atlased layers. This
269         // can be used to separate the performance contribution of less
270         // render target pingponging from that due to the re-use of cached layers
271         GrPictureInfo* pictInfo = fPictureHash.find(layer->pictureID());
272         SkASSERT(pictInfo);
273
274         pictInfo->decPlotUsage(plotID);
275
276         if (0 == pictInfo->plotUsage(plotID)) {
277             GrAtlas::RemovePlot(&pictInfo->fPlotUsage, layer->plot());
278
279             if (pictInfo->fPlotUsage.isEmpty()) {
280                 fPictureHash.remove(pictInfo->fPictureID);
281                 SkDELETE(pictInfo);
282             }
283         }
284         
285         layer->setPlot(NULL);
286         layer->setTexture(NULL, GrIRect16::MakeEmpty());
287 #endif
288
289     } else {
290         layer->setTexture(NULL, GrIRect16::MakeEmpty());
291     }
292
293     layer->setLocked(false);
294 }
295
296 #ifdef SK_DEBUG
297 void GrLayerCache::validate() const {
298     int plotLocks[kNumPlotsX * kNumPlotsY];
299     memset(plotLocks, 0, sizeof(plotLocks));
300
301     SkTDynamicHash<GrCachedLayer, GrCachedLayer::Key>::ConstIter iter(&fLayerHash);
302     for (; !iter.done(); ++iter) {
303         const GrCachedLayer* layer = &(*iter);
304
305         layer->validate(fAtlas.get() ? fAtlas->getTexture() : NULL);
306
307         const GrPictureInfo* pictInfo = fPictureHash.find(layer->pictureID());
308         if (!pictInfo) {
309             // If there is no picture info for this picture then all of its
310             // layers should be non-atlased.
311             SkASSERT(!layer->isAtlased());
312         }
313
314         if (layer->plot()) {
315             SkASSERT(pictInfo);
316             SkASSERT(pictInfo->fPictureID == layer->pictureID());
317
318             SkASSERT(pictInfo->fPlotUsage.contains(layer->plot()));
319 #if !GR_CACHE_HOISTED_LAYERS
320             SkASSERT(pictInfo->plotUsage(layer->plot()->id()) > 0);
321 #endif
322
323             if (layer->locked()) {
324                 plotLocks[layer->plot()->id()]++;
325             }
326         } 
327     }
328
329     for (int i = 0; i < kNumPlotsX*kNumPlotsY; ++i) {
330         SkASSERT(plotLocks[i] == fPlotLocks[i]);
331     }
332 }
333
334 class GrAutoValidateCache : ::SkNoncopyable {
335 public:
336     explicit GrAutoValidateCache(GrLayerCache* cache)
337         : fCache(cache) {
338         fCache->validate();
339     }
340     ~GrAutoValidateCache() {
341         fCache->validate();
342     }
343 private:
344     GrLayerCache* fCache;
345 };
346 #endif
347
348 void GrLayerCache::purge(uint32_t pictureID) {
349
350     SkDEBUGCODE(GrAutoValidateCache avc(this);)
351
352     // We need to find all the layers associated with 'picture' and remove them.
353     SkTDArray<GrCachedLayer*> toBeRemoved;
354
355     SkTDynamicHash<GrCachedLayer, GrCachedLayer::Key>::Iter iter(&fLayerHash);
356     for (; !iter.done(); ++iter) {
357         if (pictureID == (*iter).pictureID()) {
358             *toBeRemoved.append() = &(*iter);
359         }
360     }
361
362     for (int i = 0; i < toBeRemoved.count(); ++i) {
363         SkASSERT(0 == toBeRemoved[i]->uses());
364         this->unlock(toBeRemoved[i]);
365         fLayerHash.remove(GrCachedLayer::GetKey(*toBeRemoved[i]));
366         SkDELETE(toBeRemoved[i]);
367     }
368
369     GrPictureInfo* pictInfo = fPictureHash.find(pictureID);
370     if (pictInfo) {
371         fPictureHash.remove(pictureID);
372         SkDELETE(pictInfo);
373     }
374 }
375
376 bool GrLayerCache::purgePlot() {
377     SkDEBUGCODE(GrAutoValidateCache avc(this);)
378     SkASSERT(fAtlas);
379
380     GrAtlas::PlotIter iter;
381     GrPlot* plot;
382     for (plot = fAtlas->iterInit(&iter, GrAtlas::kLRUFirst_IterOrder);
383          plot;
384          plot = iter.prev()) {
385         if (fPlotLocks[plot->id()] > 0) {
386             continue;
387         }
388
389         this->purgePlot(plot);
390         return true;
391     }
392
393     return false;
394 }
395
396 void GrLayerCache::purgePlot(GrPlot* plot) {
397     SkASSERT(0 == fPlotLocks[plot->id()]);
398
399     // We need to find all the layers in 'plot' and remove them.
400     SkTDArray<GrCachedLayer*> toBeRemoved;
401
402     SkTDynamicHash<GrCachedLayer, GrCachedLayer::Key>::Iter iter(&fLayerHash);
403     for (; !iter.done(); ++iter) {
404         if (plot == (*iter).plot()) {
405             *toBeRemoved.append() = &(*iter);
406         }
407     }
408
409     for (int i = 0; i < toBeRemoved.count(); ++i) {
410         SkASSERT(0 == toBeRemoved[i]->uses());
411         SkASSERT(!toBeRemoved[i]->locked());
412
413         uint32_t pictureIDToRemove = toBeRemoved[i]->pictureID();
414
415         // Aggressively remove layers and, if it becomes totally uncached, delete the picture info
416         fLayerHash.remove(GrCachedLayer::GetKey(*toBeRemoved[i]));
417         SkDELETE(toBeRemoved[i]);
418
419         GrPictureInfo* pictInfo = fPictureHash.find(pictureIDToRemove);
420         if (pictInfo) {
421 #if !GR_CACHE_HOISTED_LAYERS
422             SkASSERT(0 == pictInfo->plotUsage(plot->id()));
423 #endif
424             GrAtlas::RemovePlot(&pictInfo->fPlotUsage, plot);
425
426             if (pictInfo->fPlotUsage.isEmpty()) {
427                 fPictureHash.remove(pictInfo->fPictureID);
428                 SkDELETE(pictInfo);
429             }
430         }
431     }
432
433     plot->resetRects();
434 }
435
436 #if !GR_CACHE_HOISTED_LAYERS
437 void GrLayerCache::purgeAll() {
438     if (!fAtlas) {
439         return;
440     }
441
442     GrAtlas::PlotIter iter;
443     GrPlot* plot;
444     for (plot = fAtlas->iterInit(&iter, GrAtlas::kLRUFirst_IterOrder);
445          plot;
446          plot = iter.prev()) {
447         SkASSERT(0 == fPlotLocks[plot->id()]);
448
449         this->purgePlot(plot);
450     }
451
452     SkASSERT(0 == fPictureHash.count());
453
454     fContext->discardRenderTarget(fAtlas->getTexture()->asRenderTarget());
455 }
456 #endif
457
458 class GrPictureDeletionListener : public SkPicture::DeletionListener {
459     virtual void onDeletion(uint32_t pictureID) SK_OVERRIDE{
460         const GrPictureDeletedMessage message = { pictureID };
461         SkMessageBus<GrPictureDeletedMessage>::Post(message);
462     }
463 };
464
465 void GrLayerCache::trackPicture(const SkPicture* picture) {
466     if (NULL == fDeletionListener) {
467         fDeletionListener.reset(SkNEW(GrPictureDeletionListener));
468     }
469
470     picture->addDeletionListener(fDeletionListener);
471 }
472
473 void GrLayerCache::processDeletedPictures() {
474     SkTDArray<GrPictureDeletedMessage> deletedPictures;
475     fPictDeletionInbox.poll(&deletedPictures);
476
477     for (int i = 0; i < deletedPictures.count(); i++) {
478         this->purge(deletedPictures[i].pictureID);
479     }
480 }
481
482 #ifdef SK_DEVELOPER
483 void GrLayerCache::writeLayersToDisk(const SkString& dirName) {
484
485     if (fAtlas) {
486         GrTexture* atlasTexture = fAtlas->getTexture();
487         if (NULL != atlasTexture) {
488             SkString fileName(dirName);
489             fileName.append("\\atlas.png");
490
491             atlasTexture->surfacePriv().savePixels(fileName.c_str());
492         }
493     }
494
495     SkTDynamicHash<GrCachedLayer, GrCachedLayer::Key>::Iter iter(&fLayerHash);
496     for (; !iter.done(); ++iter) {
497         GrCachedLayer* layer = &(*iter);
498
499         if (layer->isAtlased() || !layer->texture()) {
500             continue;
501         }
502
503         SkString fileName(dirName);
504         fileName.appendf("\\%d-%d.png", layer->fKey.pictureID(), layer->fKey.start());
505
506         layer->texture()->surfacePriv().savePixels(fileName.c_str());
507     }
508 }
509 #endif