tiled_layer.cc revision eb525c5499e34cc9c4b825d6d9e75bb07cc06ace
1// Copyright 2011 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "cc/layers/tiled_layer.h"
6
7#include <algorithm>
8#include <vector>
9
10#include "base/auto_reset.h"
11#include "base/basictypes.h"
12#include "build/build_config.h"
13#include "cc/debug/overdraw_metrics.h"
14#include "cc/layers/layer_impl.h"
15#include "cc/layers/tiled_layer_impl.h"
16#include "cc/resources/layer_updater.h"
17#include "cc/resources/prioritized_resource.h"
18#include "cc/resources/priority_calculator.h"
19#include "cc/trees/layer_tree_host.h"
20#include "third_party/khronos/GLES2/gl2.h"
21#include "ui/gfx/rect_conversions.h"
22
23namespace cc {
24
25// Maximum predictive expansion of the visible area.
26static const int kMaxPredictiveTilesCount = 2;
27
28// Number of rows/columns of tiles to pre-paint.
29// We should increase these further as all textures are
30// prioritized and we insure performance doesn't suffer.
31static const int kPrepaintRows = 4;
32static const int kPrepaintColumns = 2;
33
34class UpdatableTile : public LayerTilingData::Tile {
35 public:
36  static scoped_ptr<UpdatableTile> Create(
37      scoped_ptr<LayerUpdater::Resource> updater_resource) {
38    return make_scoped_ptr(new UpdatableTile(updater_resource.Pass()));
39  }
40
41  LayerUpdater::Resource* updater_resource() { return updater_resource_.get(); }
42  PrioritizedResource* managed_resource() {
43    return updater_resource_->texture();
44  }
45
46  bool is_dirty() const { return !dirty_rect.IsEmpty(); }
47
48  // Reset update state for the current frame. This should occur before painting
49  // for all layers. Since painting one layer can invalidate another layer after
50  // it has already painted, mark all non-dirty tiles as valid before painting
51  // such that invalidations during painting won't prevent them from being
52  // pushed.
53  void ResetUpdateState() {
54    update_rect = gfx::Rect();
55    occluded = false;
56    partial_update = false;
57    valid_for_frame = !is_dirty();
58  }
59
60  // This promises to update the tile and therefore also guarantees the tile
61  // will be valid for this frame. dirty_rect is copied into update_rect so we
62  // can continue to track re-entrant invalidations that occur during painting.
63  void MarkForUpdate() {
64    valid_for_frame = true;
65    update_rect = dirty_rect;
66    dirty_rect = gfx::Rect();
67  }
68
69  gfx::Rect dirty_rect;
70  gfx::Rect update_rect;
71  bool partial_update;
72  bool valid_for_frame;
73  bool occluded;
74
75 private:
76  explicit UpdatableTile(scoped_ptr<LayerUpdater::Resource> updater_resource)
77      : partial_update(false),
78        valid_for_frame(false),
79        occluded(false),
80        updater_resource_(updater_resource.Pass()) {}
81
82  scoped_ptr<LayerUpdater::Resource> updater_resource_;
83
84  DISALLOW_COPY_AND_ASSIGN(UpdatableTile);
85};
86
87TiledLayer::TiledLayer()
88    : ContentsScalingLayer(),
89      texture_format_(GL_INVALID_ENUM),
90      skips_draw_(false),
91      failed_update_(false),
92      tiling_option_(AUTO_TILE) {
93  tiler_ =
94      LayerTilingData::Create(gfx::Size(), LayerTilingData::HAS_BORDER_TEXELS);
95}
96
97TiledLayer::~TiledLayer() {}
98
99scoped_ptr<LayerImpl> TiledLayer::CreateLayerImpl(LayerTreeImpl* tree_impl) {
100  return TiledLayerImpl::Create(tree_impl, id()).PassAs<LayerImpl>();
101}
102
103void TiledLayer::UpdateTileSizeAndTilingOption() {
104  DCHECK(layer_tree_host());
105
106  gfx::Size default_tile_size = layer_tree_host()->settings().default_tile_size;
107  gfx::Size max_untiled_layer_size =
108      layer_tree_host()->settings().max_untiled_layer_size;
109  int layer_width = content_bounds().width();
110  int layer_height = content_bounds().height();
111
112  gfx::Size tile_size(std::min(default_tile_size.width(), layer_width),
113                      std::min(default_tile_size.height(), layer_height));
114
115  // Tile if both dimensions large, or any one dimension large and the other
116  // extends into a second tile but the total layer area isn't larger than that
117  // of the largest possible untiled layer. This heuristic allows for long
118  // skinny layers (e.g. scrollbars) that are Nx1 tiles to minimize wasted
119  // texture space but still avoids creating very large tiles.
120  bool any_dimension_large = layer_width > max_untiled_layer_size.width() ||
121                             layer_height > max_untiled_layer_size.height();
122  bool any_dimension_one_tile =
123      (layer_width <= default_tile_size.width() ||
124       layer_height <= default_tile_size.height()) &&
125      (layer_width * layer_height) <= (max_untiled_layer_size.width() *
126                                       max_untiled_layer_size.height());
127  bool auto_tiled = any_dimension_large && !any_dimension_one_tile;
128
129  bool is_tiled;
130  if (tiling_option_ == ALWAYS_TILE)
131    is_tiled = true;
132  else if (tiling_option_ == NEVER_TILE)
133    is_tiled = false;
134  else
135    is_tiled = auto_tiled;
136
137  gfx::Size requested_size = is_tiled ? tile_size : content_bounds();
138  const int max_size =
139      layer_tree_host()->GetRendererCapabilities().max_texture_size;
140  requested_size.SetToMin(gfx::Size(max_size, max_size));
141  SetTileSize(requested_size);
142}
143
144void TiledLayer::UpdateBounds() {
145  gfx::Size old_bounds = tiler_->bounds();
146  gfx::Size new_bounds = content_bounds();
147  if (old_bounds == new_bounds)
148    return;
149  tiler_->SetBounds(new_bounds);
150
151  // Invalidate any areas that the new bounds exposes.
152  Region old_region = gfx::Rect(old_bounds);
153  Region new_region = gfx::Rect(new_bounds);
154  new_region.Subtract(old_region);
155  for (Region::Iterator new_rects(new_region);
156       new_rects.has_rect();
157       new_rects.next())
158    InvalidateContentRect(new_rects.rect());
159}
160
161void TiledLayer::SetTileSize(gfx::Size size) { tiler_->SetTileSize(size); }
162
163void TiledLayer::SetBorderTexelOption(
164    LayerTilingData::BorderTexelOption border_texel_option) {
165  tiler_->SetBorderTexelOption(border_texel_option);
166}
167
168bool TiledLayer::DrawsContent() const {
169  if (!ContentsScalingLayer::DrawsContent())
170    return false;
171
172  bool has_more_than_one_tile =
173      tiler_->num_tiles_x() > 1 || tiler_->num_tiles_y() > 1;
174  if (tiling_option_ == NEVER_TILE && has_more_than_one_tile)
175    return false;
176
177  return true;
178}
179
180void TiledLayer::ReduceMemoryUsage() {
181  if (Updater())
182    Updater()->ReduceMemoryUsage();
183}
184
185void TiledLayer::SetIsMask(bool is_mask) {
186  set_tiling_option(is_mask ? NEVER_TILE : AUTO_TILE);
187}
188
189void TiledLayer::PushPropertiesTo(LayerImpl* layer) {
190  ContentsScalingLayer::PushPropertiesTo(layer);
191
192  TiledLayerImpl* tiled_layer = static_cast<TiledLayerImpl*>(layer);
193
194  tiled_layer->set_skips_draw(skips_draw_);
195  tiled_layer->SetTilingData(*tiler_);
196  std::vector<UpdatableTile*> invalid_tiles;
197
198  for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
199       iter != tiler_->tiles().end();
200       ++iter) {
201    int i = iter->first.first;
202    int j = iter->first.second;
203    UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
204    // TODO(enne): This should not ever be null.
205    if (!tile)
206      continue;
207
208    if (!tile->managed_resource()->have_backing_texture()) {
209      // Evicted tiles get deleted from both layers
210      invalid_tiles.push_back(tile);
211      continue;
212    }
213
214    if (!tile->valid_for_frame) {
215      // Invalidated tiles are set so they can get different debug colors.
216      tiled_layer->PushInvalidTile(i, j);
217      continue;
218    }
219
220    tiled_layer->PushTileProperties(
221        i,
222        j,
223        tile->managed_resource()->resource_id(),
224        tile->opaque_rect(),
225        tile->managed_resource()->contents_swizzled());
226  }
227  for (std::vector<UpdatableTile*>::const_iterator iter = invalid_tiles.begin();
228       iter != invalid_tiles.end();
229       ++iter)
230    tiler_->TakeTile((*iter)->i(), (*iter)->j());
231}
232
233bool TiledLayer::BlocksPendingCommit() const { return true; }
234
235PrioritizedResourceManager* TiledLayer::ResourceManager() const {
236  if (!layer_tree_host())
237    return NULL;
238  return layer_tree_host()->contents_texture_manager();
239}
240
241const PrioritizedResource* TiledLayer::ResourceAtForTesting(int i,
242                                                            int j) const {
243  UpdatableTile* tile = TileAt(i, j);
244  if (!tile)
245    return NULL;
246  return tile->managed_resource();
247}
248
249void TiledLayer::SetLayerTreeHost(LayerTreeHost* host) {
250  if (host && host != layer_tree_host()) {
251    for (LayerTilingData::TileMap::const_iterator
252             iter = tiler_->tiles().begin();
253         iter != tiler_->tiles().end();
254         ++iter) {
255      UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
256      // TODO(enne): This should not ever be null.
257      if (!tile)
258        continue;
259      tile->managed_resource()->SetTextureManager(
260          host->contents_texture_manager());
261    }
262  }
263  ContentsScalingLayer::SetLayerTreeHost(host);
264}
265
266UpdatableTile* TiledLayer::TileAt(int i, int j) const {
267  return static_cast<UpdatableTile*>(tiler_->TileAt(i, j));
268}
269
270UpdatableTile* TiledLayer::CreateTile(int i, int j) {
271  CreateUpdaterIfNeeded();
272
273  scoped_ptr<UpdatableTile> tile(
274      UpdatableTile::Create(Updater()->CreateResource(ResourceManager())));
275  tile->managed_resource()->SetDimensions(tiler_->tile_size(), texture_format_);
276
277  UpdatableTile* added_tile = tile.get();
278  tiler_->AddTile(tile.PassAs<LayerTilingData::Tile>(), i, j);
279
280  added_tile->dirty_rect = tiler_->TileRect(added_tile);
281
282  // Temporary diagnostic crash.
283  CHECK(added_tile);
284  CHECK(TileAt(i, j));
285
286  return added_tile;
287}
288
289void TiledLayer::SetNeedsDisplayRect(const gfx::RectF& dirty_rect) {
290  InvalidateContentRect(LayerRectToContentRect(dirty_rect));
291  ContentsScalingLayer::SetNeedsDisplayRect(dirty_rect);
292}
293
294void TiledLayer::InvalidateContentRect(gfx::Rect content_rect) {
295  UpdateBounds();
296  if (tiler_->is_empty() || content_rect.IsEmpty() || skips_draw_)
297    return;
298
299  for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
300       iter != tiler_->tiles().end();
301       ++iter) {
302    UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
303    DCHECK(tile);
304    // TODO(enne): This should not ever be null.
305    if (!tile)
306      continue;
307    gfx::Rect bound = tiler_->TileRect(tile);
308    bound.Intersect(content_rect);
309    tile->dirty_rect.Union(bound);
310  }
311}
312
313// Returns true if tile is dirty and only part of it needs to be updated.
314bool TiledLayer::TileOnlyNeedsPartialUpdate(UpdatableTile* tile) {
315  return !tile->dirty_rect.Contains(tiler_->TileRect(tile)) &&
316         tile->managed_resource()->have_backing_texture();
317}
318
319bool TiledLayer::UpdateTiles(int left,
320                             int top,
321                             int right,
322                             int bottom,
323                             ResourceUpdateQueue* queue,
324                             const OcclusionTracker* occlusion,
325                             bool* did_paint) {
326  *did_paint = false;
327  CreateUpdaterIfNeeded();
328
329  bool ignore_occlusions = !occlusion;
330  if (!HaveTexturesForTiles(left, top, right, bottom, ignore_occlusions)) {
331    failed_update_ = true;
332    return false;
333  }
334
335  gfx::Rect paint_rect =
336      MarkTilesForUpdate(left, top, right, bottom, ignore_occlusions);
337
338  if (occlusion)
339    occlusion->overdraw_metrics()->DidPaint(paint_rect);
340
341  if (paint_rect.IsEmpty())
342    return true;
343
344  *did_paint = true;
345  UpdateTileTextures(
346      paint_rect, left, top, right, bottom, queue, occlusion);
347  return true;
348}
349
350void TiledLayer::MarkOcclusionsAndRequestTextures(
351    int left,
352    int top,
353    int right,
354    int bottom,
355    const OcclusionTracker* occlusion) {
356  // There is some difficult dependancies between occlusions, recording
357  // occlusion metrics and requesting memory so those are encapsulated in this
358  // function: - We only want to call RequestLate on unoccluded textures (to
359  // preserve memory for other layers when near OOM).  - We only want to record
360  // occlusion metrics if all memory requests succeed.
361
362  int occluded_tile_count = 0;
363  bool succeeded = true;
364  for (int j = top; j <= bottom; ++j) {
365    for (int i = left; i <= right; ++i) {
366      UpdatableTile* tile = TileAt(i, j);
367      DCHECK(tile);  // Did SetTexturePriorities get skipped?
368      // TODO(enne): This should not ever be null.
369      if (!tile)
370        continue;
371      // Did ResetUpdateState get skipped? Are we doing more than one occlusion
372      // pass?
373      DCHECK(!tile->occluded);
374      gfx::Rect visible_tile_rect = gfx::IntersectRects(
375          tiler_->tile_bounds(i, j), visible_content_rect());
376      if (occlusion && occlusion->Occluded(render_target(),
377                                           visible_tile_rect,
378                                           draw_transform(),
379                                           draw_transform_is_animating(),
380                                           is_clipped(),
381                                           clip_rect(),
382                                           NULL)) {
383        tile->occluded = true;
384        occluded_tile_count++;
385      } else {
386        succeeded &= tile->managed_resource()->RequestLate();
387      }
388    }
389  }
390
391  if (!succeeded)
392    return;
393  if (occlusion)
394    occlusion->overdraw_metrics()->DidCullTilesForUpload(occluded_tile_count);
395}
396
397bool TiledLayer::HaveTexturesForTiles(int left,
398                                      int top,
399                                      int right,
400                                      int bottom,
401                                      bool ignore_occlusions) {
402  for (int j = top; j <= bottom; ++j) {
403    for (int i = left; i <= right; ++i) {
404      UpdatableTile* tile = TileAt(i, j);
405      DCHECK(tile);  // Did SetTexturePriorites get skipped?
406                     // TODO(enne): This should not ever be null.
407      if (!tile)
408        continue;
409
410      // Ensure the entire tile is dirty if we don't have the texture.
411      if (!tile->managed_resource()->have_backing_texture())
412        tile->dirty_rect = tiler_->TileRect(tile);
413
414      // If using occlusion and the visible region of the tile is occluded,
415      // don't reserve a texture or update the tile.
416      if (tile->occluded && !ignore_occlusions)
417        continue;
418
419      if (!tile->managed_resource()->can_acquire_backing_texture())
420        return false;
421    }
422  }
423  return true;
424}
425
426gfx::Rect TiledLayer::MarkTilesForUpdate(int left,
427                                         int top,
428                                         int right,
429                                         int bottom,
430                                         bool ignore_occlusions) {
431  gfx::Rect paint_rect;
432  for (int j = top; j <= bottom; ++j) {
433    for (int i = left; i <= right; ++i) {
434      UpdatableTile* tile = TileAt(i, j);
435      DCHECK(tile);  // Did SetTexturePriorites get skipped?
436                     // TODO(enne): This should not ever be null.
437      if (!tile)
438        continue;
439      if (tile->occluded && !ignore_occlusions)
440        continue;
441      // TODO(reveman): Decide if partial update should be allowed based on cost
442      // of update. https://bugs.webkit.org/show_bug.cgi?id=77376
443      if (tile->is_dirty() && layer_tree_host() &&
444          layer_tree_host()->buffered_updates()) {
445        // If we get a partial update, we use the same texture, otherwise return
446        // the current texture backing, so we don't update visible textures
447        // non-atomically.  If the current backing is in-use, it won't be
448        // deleted until after the commit as the texture manager will not allow
449        // deletion or recycling of in-use textures.
450        if (TileOnlyNeedsPartialUpdate(tile) &&
451            layer_tree_host()->RequestPartialTextureUpdate()) {
452          tile->partial_update = true;
453        } else {
454          tile->dirty_rect = tiler_->TileRect(tile);
455          tile->managed_resource()->ReturnBackingTexture();
456        }
457      }
458
459      paint_rect.Union(tile->dirty_rect);
460      tile->MarkForUpdate();
461    }
462  }
463  return paint_rect;
464}
465
466void TiledLayer::UpdateTileTextures(gfx::Rect paint_rect,
467                                    int left,
468                                    int top,
469                                    int right,
470                                    int bottom,
471                                    ResourceUpdateQueue* queue,
472                                    const OcclusionTracker* occlusion) {
473  // The update_rect should be in layer space. So we have to convert the
474  // paint_rect from content space to layer space.
475  float width_scale =
476      paint_properties().bounds.width() /
477      static_cast<float>(content_bounds().width());
478  float height_scale =
479      paint_properties().bounds.height() /
480      static_cast<float>(content_bounds().height());
481  update_rect_ = gfx::ScaleRect(paint_rect, width_scale, height_scale);
482
483  // Calling PrepareToUpdate() calls into WebKit to paint, which may have the
484  // side effect of disabling compositing, which causes our reference to the
485  // texture updater to be deleted.  However, we can't free the memory backing
486  // the SkCanvas until the paint finishes, so we grab a local reference here to
487  // hold the updater alive until the paint completes.
488  scoped_refptr<LayerUpdater> protector(Updater());
489  gfx::Rect painted_opaque_rect;
490  Updater()->PrepareToUpdate(paint_rect,
491                             tiler_->tile_size(),
492                             1.f / width_scale,
493                             1.f / height_scale,
494                             &painted_opaque_rect);
495
496  for (int j = top; j <= bottom; ++j) {
497    for (int i = left; i <= right; ++i) {
498      UpdatableTile* tile = TileAt(i, j);
499      DCHECK(tile);  // Did SetTexturePriorites get skipped?
500                     // TODO(enne): This should not ever be null.
501      if (!tile)
502        continue;
503
504      gfx::Rect tile_rect = tiler_->tile_bounds(i, j);
505
506      // Use update_rect as the above loop copied the dirty rect for this frame
507      // to update_rect.
508      gfx::Rect dirty_rect = tile->update_rect;
509      if (dirty_rect.IsEmpty())
510        continue;
511
512      // Save what was painted opaque in the tile. Keep the old area if the
513      // paint didn't touch it, and didn't paint some other part of the tile
514      // opaque.
515      gfx::Rect tile_painted_rect = gfx::IntersectRects(tile_rect, paint_rect);
516      gfx::Rect tile_painted_opaque_rect =
517          gfx::IntersectRects(tile_rect, painted_opaque_rect);
518      if (!tile_painted_rect.IsEmpty()) {
519        gfx::Rect paint_inside_tile_opaque_rect =
520            gfx::IntersectRects(tile->opaque_rect(), tile_painted_rect);
521        bool paint_inside_tile_opaque_rect_is_non_opaque =
522            !paint_inside_tile_opaque_rect.IsEmpty() &&
523            !tile_painted_opaque_rect.Contains(paint_inside_tile_opaque_rect);
524        bool opaque_paint_not_inside_tile_opaque_rect =
525            !tile_painted_opaque_rect.IsEmpty() &&
526            !tile->opaque_rect().Contains(tile_painted_opaque_rect);
527
528        if (paint_inside_tile_opaque_rect_is_non_opaque ||
529            opaque_paint_not_inside_tile_opaque_rect)
530          tile->set_opaque_rect(tile_painted_opaque_rect);
531      }
532
533      // source_rect starts as a full-sized tile with border texels included.
534      gfx::Rect source_rect = tiler_->TileRect(tile);
535      source_rect.Intersect(dirty_rect);
536      // Paint rect not guaranteed to line up on tile boundaries, so
537      // make sure that source_rect doesn't extend outside of it.
538      source_rect.Intersect(paint_rect);
539
540      tile->update_rect = source_rect;
541
542      if (source_rect.IsEmpty())
543        continue;
544
545      const gfx::Point anchor = tiler_->TileRect(tile).origin();
546
547      // Calculate tile-space rectangle to upload into.
548      gfx::Vector2d dest_offset = source_rect.origin() - anchor;
549      CHECK_GE(dest_offset.x(), 0);
550      CHECK_GE(dest_offset.y(), 0);
551
552      // Offset from paint rectangle to this tile's dirty rectangle.
553      gfx::Vector2d paint_offset = source_rect.origin() - paint_rect.origin();
554      CHECK_GE(paint_offset.x(), 0);
555      CHECK_GE(paint_offset.y(), 0);
556      CHECK_LE(paint_offset.x() + source_rect.width(), paint_rect.width());
557      CHECK_LE(paint_offset.y() + source_rect.height(), paint_rect.height());
558
559      tile->updater_resource()->Update(
560          queue, source_rect, dest_offset, tile->partial_update);
561      if (occlusion) {
562        occlusion->overdraw_metrics()->
563            DidUpload(gfx::Transform(), source_rect, tile->opaque_rect());
564      }
565    }
566  }
567}
568
569// This picks a small animated layer to be anything less than one viewport. This
570// is specifically for page transitions which are viewport-sized layers. The
571// extra tile of padding is due to these layers being slightly larger than the
572// viewport in some cases.
573bool TiledLayer::IsSmallAnimatedLayer() const {
574  if (!draw_transform_is_animating() && !screen_space_transform_is_animating())
575    return false;
576  gfx::Size viewport_size =
577      layer_tree_host() ? layer_tree_host()->device_viewport_size()
578                        : gfx::Size();
579  gfx::Rect content_rect(content_bounds());
580  return content_rect.width() <=
581         viewport_size.width() + tiler_->tile_size().width() &&
582         content_rect.height() <=
583         viewport_size.height() + tiler_->tile_size().height();
584}
585
586namespace {
587// TODO(epenner): Remove this and make this based on distance once distance can
588// be calculated for offscreen layers. For now, prioritize all small animated
589// layers after 512 pixels of pre-painting.
590void SetPriorityForTexture(gfx::Rect visible_rect,
591                           gfx::Rect tile_rect,
592                           bool draws_to_root,
593                           bool is_small_animated_layer,
594                           PrioritizedResource* texture) {
595  int priority = PriorityCalculator::LowestPriority();
596  if (!visible_rect.IsEmpty()) {
597    priority = PriorityCalculator::PriorityFromDistance(
598        visible_rect, tile_rect, draws_to_root);
599  }
600
601  if (is_small_animated_layer) {
602    priority = PriorityCalculator::max_priority(
603        priority, PriorityCalculator::SmallAnimatedLayerMinPriority());
604  }
605
606  if (priority != PriorityCalculator::LowestPriority())
607    texture->set_request_priority(priority);
608}
609}  // namespace
610
611void TiledLayer::SetTexturePriorities(const PriorityCalculator& priority_calc) {
612  UpdateBounds();
613  ResetUpdateState();
614  UpdateScrollPrediction();
615
616  if (tiler_->has_empty_bounds())
617    return;
618
619  bool draws_to_root = !render_target()->parent();
620  bool small_animated_layer = IsSmallAnimatedLayer();
621
622  // Minimally create the tiles in the desired pre-paint rect.
623  gfx::Rect create_tiles_rect = IdlePaintRect();
624  if (small_animated_layer)
625    create_tiles_rect = gfx::Rect(content_bounds());
626  if (!create_tiles_rect.IsEmpty()) {
627    int left, top, right, bottom;
628    tiler_->ContentRectToTileIndices(
629        create_tiles_rect, &left, &top, &right, &bottom);
630    for (int j = top; j <= bottom; ++j) {
631      for (int i = left; i <= right; ++i) {
632        if (!TileAt(i, j))
633          CreateTile(i, j);
634      }
635    }
636  }
637
638  // Now update priorities on all tiles we have in the layer, no matter where
639  // they are.
640  for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
641       iter != tiler_->tiles().end();
642       ++iter) {
643    UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
644    // TODO(enne): This should not ever be null.
645    if (!tile)
646      continue;
647    gfx::Rect tile_rect = tiler_->TileRect(tile);
648    SetPriorityForTexture(predicted_visible_rect_,
649                          tile_rect,
650                          draws_to_root,
651                          small_animated_layer,
652                          tile->managed_resource());
653  }
654}
655
656Region TiledLayer::VisibleContentOpaqueRegion() const {
657  if (skips_draw_)
658    return Region();
659  if (contents_opaque())
660    return visible_content_rect();
661  return tiler_->OpaqueRegionInContentRect(visible_content_rect());
662}
663
664void TiledLayer::ResetUpdateState() {
665  skips_draw_ = false;
666  failed_update_ = false;
667
668  LayerTilingData::TileMap::const_iterator end = tiler_->tiles().end();
669  for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
670       iter != end;
671       ++iter) {
672    UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
673    // TODO(enne): This should not ever be null.
674    if (!tile)
675      continue;
676    tile->ResetUpdateState();
677  }
678}
679
680namespace {
681gfx::Rect ExpandRectByDelta(gfx::Rect rect, gfx::Vector2d delta) {
682  int width = rect.width() + std::abs(delta.x());
683  int height = rect.height() + std::abs(delta.y());
684  int x = rect.x() + ((delta.x() < 0) ? delta.x() : 0);
685  int y = rect.y() + ((delta.y() < 0) ? delta.y() : 0);
686  return gfx::Rect(x, y, width, height);
687}
688}
689
690void TiledLayer::UpdateScrollPrediction() {
691  // This scroll prediction is very primitive and should be replaced by a
692  // a recursive calculation on all layers which uses actual scroll/animation
693  // velocities. To insure this doesn't miss-predict, we only use it to predict
694  // the visible_rect if:
695  // - content_bounds() hasn't changed.
696  // - visible_rect.size() hasn't changed.
697  // These two conditions prevent rotations, scales, pinch-zooms etc. where
698  // the prediction would be incorrect.
699  gfx::Vector2d delta = visible_content_rect().CenterPoint() -
700                        previous_visible_rect_.CenterPoint();
701  predicted_scroll_ = -delta;
702  predicted_visible_rect_ = visible_content_rect();
703  if (previous_content_bounds_ == content_bounds() &&
704      previous_visible_rect_.size() == visible_content_rect().size()) {
705    // Only expand the visible rect in the major scroll direction, to prevent
706    // massive paints due to diagonal scrolls.
707    gfx::Vector2d major_scroll_delta =
708        (std::abs(delta.x()) > std::abs(delta.y())) ?
709        gfx::Vector2d(delta.x(), 0) :
710        gfx::Vector2d(0, delta.y());
711    predicted_visible_rect_ =
712        ExpandRectByDelta(visible_content_rect(), major_scroll_delta);
713
714    // Bound the prediction to prevent unbounded paints, and clamp to content
715    // bounds.
716    gfx::Rect bound = visible_content_rect();
717    bound.Inset(-tiler_->tile_size().width() * kMaxPredictiveTilesCount,
718                -tiler_->tile_size().height() * kMaxPredictiveTilesCount);
719    bound.Intersect(gfx::Rect(content_bounds()));
720    predicted_visible_rect_.Intersect(bound);
721  }
722  previous_content_bounds_ = content_bounds();
723  previous_visible_rect_ = visible_content_rect();
724}
725
726void TiledLayer::Update(ResourceUpdateQueue* queue,
727                        const OcclusionTracker* occlusion) {
728  DCHECK(!skips_draw_ && !failed_update_);  // Did ResetUpdateState get skipped?
729  {
730    base::AutoReset<bool> ignore_set_needs_commit(&ignore_set_needs_commit_,
731                                                  true);
732
733    ContentsScalingLayer::Update(queue, occlusion);
734    UpdateBounds();
735  }
736
737  if (tiler_->has_empty_bounds() || !DrawsContent())
738    return;
739
740  bool did_paint = false;
741
742  // Animation pre-paint. If the layer is small, try to paint it all
743  // immediately whether or not it is occluded, to avoid paint/upload
744  // hiccups while it is animating.
745  if (IsSmallAnimatedLayer()) {
746    int left, top, right, bottom;
747    tiler_->ContentRectToTileIndices(gfx::Rect(content_bounds()),
748                                     &left,
749                                     &top,
750                                     &right,
751                                     &bottom);
752    UpdateTiles(left, top, right, bottom, queue, NULL, &did_paint);
753    if (did_paint)
754      return;
755    // This was an attempt to paint the entire layer so if we fail it's okay,
756    // just fallback on painting visible etc. below.
757    failed_update_ = false;
758  }
759
760  if (predicted_visible_rect_.IsEmpty())
761    return;
762
763  // Visible painting. First occlude visible tiles and paint the non-occluded
764  // tiles.
765  int left, top, right, bottom;
766  tiler_->ContentRectToTileIndices(
767      predicted_visible_rect_, &left, &top, &right, &bottom);
768  MarkOcclusionsAndRequestTextures(left, top, right, bottom, occlusion);
769  skips_draw_ = !UpdateTiles(
770      left, top, right, bottom, queue, occlusion, &did_paint);
771  if (skips_draw_)
772    tiler_->reset();
773  if (skips_draw_ || did_paint)
774    return;
775
776  // If we have already painting everything visible. Do some pre-painting while
777  // idle.
778  gfx::Rect idle_paint_content_rect = IdlePaintRect();
779  if (idle_paint_content_rect.IsEmpty())
780    return;
781
782  // Prepaint anything that was occluded but inside the layer's visible region.
783  if (!UpdateTiles(left, top, right, bottom, queue, NULL, &did_paint) ||
784      did_paint)
785    return;
786
787  int prepaint_left, prepaint_top, prepaint_right, prepaint_bottom;
788  tiler_->ContentRectToTileIndices(idle_paint_content_rect,
789                                   &prepaint_left,
790                                   &prepaint_top,
791                                   &prepaint_right,
792                                   &prepaint_bottom);
793
794  // Then expand outwards one row/column at a time until we find a dirty
795  // row/column to update. Increment along the major and minor scroll directions
796  // first.
797  gfx::Vector2d delta = -predicted_scroll_;
798  delta = gfx::Vector2d(delta.x() == 0 ? 1 : delta.x(),
799                        delta.y() == 0 ? 1 : delta.y());
800  gfx::Vector2d major_delta =
801      (abs(delta.x()) > abs(delta.y())) ? gfx::Vector2d(delta.x(), 0)
802                                        : gfx::Vector2d(0, delta.y());
803  gfx::Vector2d minor_delta =
804      (abs(delta.x()) <= abs(delta.y())) ? gfx::Vector2d(delta.x(), 0)
805                                         : gfx::Vector2d(0, delta.y());
806  gfx::Vector2d deltas[4] = { major_delta, minor_delta, -major_delta,
807                              -minor_delta };
808  for (int i = 0; i < 4; i++) {
809    if (deltas[i].y() > 0) {
810      while (bottom < prepaint_bottom) {
811        ++bottom;
812        if (!UpdateTiles(
813                left, bottom, right, bottom, queue, NULL, &did_paint) ||
814            did_paint)
815          return;
816      }
817    }
818    if (deltas[i].y() < 0) {
819      while (top > prepaint_top) {
820        --top;
821        if (!UpdateTiles(
822                left, top, right, top, queue, NULL, &did_paint) ||
823            did_paint)
824          return;
825      }
826    }
827    if (deltas[i].x() < 0) {
828      while (left > prepaint_left) {
829        --left;
830        if (!UpdateTiles(
831                left, top, left, bottom, queue, NULL, &did_paint) ||
832            did_paint)
833          return;
834      }
835    }
836    if (deltas[i].x() > 0) {
837      while (right < prepaint_right) {
838        ++right;
839        if (!UpdateTiles(
840                right, top, right, bottom, queue, NULL, &did_paint) ||
841            did_paint)
842          return;
843      }
844    }
845  }
846}
847
848bool TiledLayer::NeedsIdlePaint() {
849  // Don't trigger more paints if we failed (as we'll just fail again).
850  if (failed_update_ || visible_content_rect().IsEmpty() ||
851      tiler_->has_empty_bounds() || !DrawsContent())
852    return false;
853
854  gfx::Rect idle_paint_content_rect = IdlePaintRect();
855  if (idle_paint_content_rect.IsEmpty())
856    return false;
857
858  int left, top, right, bottom;
859  tiler_->ContentRectToTileIndices(
860      idle_paint_content_rect, &left, &top, &right, &bottom);
861
862  for (int j = top; j <= bottom; ++j) {
863    for (int i = left; i <= right; ++i) {
864      UpdatableTile* tile = TileAt(i, j);
865      DCHECK(tile);  // Did SetTexturePriorities get skipped?
866      if (!tile)
867        continue;
868
869      bool updated = !tile->update_rect.IsEmpty();
870      bool can_acquire =
871          tile->managed_resource()->can_acquire_backing_texture();
872      bool dirty =
873          tile->is_dirty() || !tile->managed_resource()->have_backing_texture();
874      if (!updated && can_acquire && dirty)
875        return true;
876    }
877  }
878  return false;
879}
880
881gfx::Rect TiledLayer::IdlePaintRect() {
882  // Don't inflate an empty rect.
883  if (visible_content_rect().IsEmpty())
884    return gfx::Rect();
885
886  gfx::Rect prepaint_rect = visible_content_rect();
887  prepaint_rect.Inset(-tiler_->tile_size().width() * kPrepaintColumns,
888                      -tiler_->tile_size().height() * kPrepaintRows);
889  gfx::Rect content_rect(content_bounds());
890  prepaint_rect.Intersect(content_rect);
891
892  return prepaint_rect;
893}
894
895}  // namespace cc
896