1 // Copyright 2012 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.
5 #include "cc/resources/picture_layer_tiling.h"
12 #include "base/debug/trace_event.h"
13 #include "base/debug/trace_event_argument.h"
14 #include "base/logging.h"
15 #include "cc/base/math_util.h"
16 #include "cc/resources/tile.h"
17 #include "cc/resources/tile_priority.h"
18 #include "ui/gfx/geometry/point_conversions.h"
19 #include "ui/gfx/geometry/rect_conversions.h"
20 #include "ui/gfx/geometry/safe_integer_conversions.h"
21 #include "ui/gfx/geometry/size_conversions.h"
26 const float kSoonBorderDistanceInScreenPixels = 312.f;
28 class TileEvictionOrder {
30 explicit TileEvictionOrder(TreePriority tree_priority)
31 : tree_priority_(tree_priority) {}
32 ~TileEvictionOrder() {}
34 bool operator()(const Tile* a, const Tile* b) {
35 const TilePriority& a_priority =
36 a->priority_for_tree_priority(tree_priority_);
37 const TilePriority& b_priority =
38 b->priority_for_tree_priority(tree_priority_);
40 DCHECK(a_priority.priority_bin == b_priority.priority_bin);
41 DCHECK(a->required_for_activation() == b->required_for_activation());
43 // Or if a is occluded and b is unoccluded.
44 bool a_is_occluded = a->is_occluded_for_tree_priority(tree_priority_);
45 bool b_is_occluded = b->is_occluded_for_tree_priority(tree_priority_);
46 if (a_is_occluded != b_is_occluded)
49 // Or if a is farther away from visible.
50 return a_priority.distance_to_visible > b_priority.distance_to_visible;
54 TreePriority tree_priority_;
59 scoped_ptr<PictureLayerTiling> PictureLayerTiling::Create(
61 const gfx::Size& layer_bounds,
62 PictureLayerTilingClient* client) {
63 return make_scoped_ptr(new PictureLayerTiling(contents_scale,
68 PictureLayerTiling::PictureLayerTiling(float contents_scale,
69 const gfx::Size& layer_bounds,
70 PictureLayerTilingClient* client)
71 : contents_scale_(contents_scale),
72 layer_bounds_(layer_bounds),
73 resolution_(NON_IDEAL_RESOLUTION),
75 tiling_data_(gfx::Size(), gfx::Size(), kBorderTexels),
76 last_impl_frame_time_in_seconds_(0.0),
77 content_to_screen_scale_(0.f),
78 can_require_tiles_for_activation_(false),
79 has_visible_rect_tiles_(false),
80 has_skewport_rect_tiles_(false),
81 has_soon_border_rect_tiles_(false),
82 has_eventually_rect_tiles_(false),
83 eviction_tiles_cache_valid_(false),
84 eviction_cache_tree_priority_(SAME_PRIORITY_FOR_BOTH_TREES) {
85 gfx::Size content_bounds =
86 gfx::ToCeiledSize(gfx::ScaleSize(layer_bounds, contents_scale));
87 gfx::Size tile_size = client_->CalculateTileSize(content_bounds);
88 if (tile_size.IsEmpty()) {
89 layer_bounds_ = gfx::Size();
90 content_bounds = gfx::Size();
93 DCHECK(!gfx::ToFlooredSize(
94 gfx::ScaleSize(layer_bounds, contents_scale)).IsEmpty()) <<
95 "Tiling created with scale too small as contents become empty." <<
96 " Layer bounds: " << layer_bounds.ToString() <<
97 " Contents scale: " << contents_scale;
99 tiling_data_.SetTilingSize(content_bounds);
100 tiling_data_.SetMaxTextureSize(tile_size);
103 PictureLayerTiling::~PictureLayerTiling() {
104 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it)
105 it->second->set_shared(false);
108 void PictureLayerTiling::SetClient(PictureLayerTilingClient* client) {
112 Tile* PictureLayerTiling::CreateTile(int i,
114 const PictureLayerTiling* twin_tiling) {
115 TileMapKey key(i, j);
116 DCHECK(tiles_.find(key) == tiles_.end());
118 gfx::Rect paint_rect = tiling_data_.TileBoundsWithBorder(i, j);
119 gfx::Rect tile_rect = paint_rect;
120 tile_rect.set_size(tiling_data_.max_texture_size());
122 // Check our twin for a valid tile.
124 tiling_data_.max_texture_size() ==
125 twin_tiling->tiling_data_.max_texture_size()) {
126 if (Tile* candidate_tile = twin_tiling->TileAt(i, j)) {
128 gfx::ScaleToEnclosingRect(paint_rect, 1.0f / contents_scale_);
129 const Region* invalidation = client_->GetPendingInvalidation();
130 if (!invalidation || !invalidation->Intersects(rect)) {
131 DCHECK(!candidate_tile->is_shared());
132 DCHECK_EQ(i, candidate_tile->tiling_i_index());
133 DCHECK_EQ(j, candidate_tile->tiling_j_index());
134 candidate_tile->set_shared(true);
135 tiles_[key] = candidate_tile;
136 return candidate_tile;
141 // Create a new tile because our twin didn't have a valid one.
142 scoped_refptr<Tile> tile = client_->CreateTile(this, tile_rect);
144 DCHECK(!tile->is_shared());
145 tile->set_tiling_index(i, j);
148 eviction_tiles_cache_valid_ = false;
152 void PictureLayerTiling::CreateMissingTilesInLiveTilesRect() {
153 const PictureLayerTiling* twin_tiling =
154 client_->GetPendingOrActiveTwinTiling(this);
155 bool include_borders = false;
156 for (TilingData::Iterator iter(
157 &tiling_data_, live_tiles_rect_, include_borders);
160 TileMapKey key = iter.index();
161 TileMap::iterator find = tiles_.find(key);
162 if (find != tiles_.end())
164 CreateTile(key.first, key.second, twin_tiling);
167 VerifyLiveTilesRect();
170 void PictureLayerTiling::UpdateTilesToCurrentPile(
171 const Region& layer_invalidation,
172 const gfx::Size& new_layer_bounds) {
173 DCHECK(!new_layer_bounds.IsEmpty());
175 gfx::Size tile_size = tiling_data_.max_texture_size();
177 if (new_layer_bounds != layer_bounds_) {
178 gfx::Size content_bounds =
179 gfx::ToCeiledSize(gfx::ScaleSize(new_layer_bounds, contents_scale_));
181 tile_size = client_->CalculateTileSize(content_bounds);
182 if (tile_size.IsEmpty()) {
183 layer_bounds_ = gfx::Size();
184 content_bounds = gfx::Size();
186 layer_bounds_ = new_layer_bounds;
189 // The SetLiveTilesRect() method would drop tiles outside the new bounds,
190 // but may do so incorrectly if resizing the tiling causes the number of
191 // tiles in the tiling_data_ to change.
192 gfx::Rect content_rect(content_bounds);
193 int before_left = tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.x());
194 int before_top = tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.y());
196 tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.right() - 1);
198 tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.bottom() - 1);
200 // The live_tiles_rect_ is clamped to stay within the tiling size as we
202 live_tiles_rect_.Intersect(content_rect);
203 tiling_data_.SetTilingSize(content_bounds);
205 int after_right = -1;
206 int after_bottom = -1;
207 if (!live_tiles_rect_.IsEmpty()) {
209 tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.right() - 1);
211 tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.bottom() - 1);
214 // There is no recycled twin since this is run on the pending tiling.
215 PictureLayerTiling* recycled_twin = NULL;
216 DCHECK_EQ(recycled_twin, client_->GetRecycledTwinTiling(this));
217 DCHECK_EQ(PENDING_TREE, client_->GetTree());
219 // Drop tiles outside the new layer bounds if the layer shrank.
220 for (int i = after_right + 1; i <= before_right; ++i) {
221 for (int j = before_top; j <= before_bottom; ++j)
222 RemoveTileAt(i, j, recycled_twin);
224 for (int i = before_left; i <= after_right; ++i) {
225 for (int j = after_bottom + 1; j <= before_bottom; ++j)
226 RemoveTileAt(i, j, recycled_twin);
229 // If the layer grew, the live_tiles_rect_ is not changed, but a new row
230 // and/or column of tiles may now exist inside the same live_tiles_rect_.
231 const PictureLayerTiling* twin_tiling =
232 client_->GetPendingOrActiveTwinTiling(this);
233 if (after_right > before_right) {
234 DCHECK_EQ(after_right, before_right + 1);
235 for (int j = before_top; j <= after_bottom; ++j)
236 CreateTile(after_right, j, twin_tiling);
238 if (after_bottom > before_bottom) {
239 DCHECK_EQ(after_bottom, before_bottom + 1);
240 for (int i = before_left; i <= before_right; ++i)
241 CreateTile(i, after_bottom, twin_tiling);
245 if (tile_size != tiling_data_.max_texture_size()) {
246 tiling_data_.SetMaxTextureSize(tile_size);
247 // When the tile size changes, the TilingData positions no longer work
248 // as valid keys to the TileMap, so just drop all tiles.
251 Invalidate(layer_invalidation);
254 RasterSource* raster_source = client_->GetRasterSource();
255 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it)
256 it->second->set_raster_source(raster_source);
257 VerifyLiveTilesRect();
260 void PictureLayerTiling::RemoveTilesInRegion(const Region& layer_region) {
261 bool recreate_invalidated_tiles = false;
262 DoInvalidate(layer_region, recreate_invalidated_tiles);
265 void PictureLayerTiling::Invalidate(const Region& layer_region) {
266 bool recreate_invalidated_tiles = true;
267 DoInvalidate(layer_region, recreate_invalidated_tiles);
270 void PictureLayerTiling::DoInvalidate(const Region& layer_region,
271 bool recreate_invalidated_tiles) {
272 std::vector<TileMapKey> new_tile_keys;
273 gfx::Rect expanded_live_tiles_rect =
274 tiling_data_.ExpandRectIgnoringBordersToTileBounds(live_tiles_rect_);
275 for (Region::Iterator iter(layer_region); iter.has_rect(); iter.next()) {
276 gfx::Rect layer_rect = iter.rect();
277 gfx::Rect content_rect =
278 gfx::ScaleToEnclosingRect(layer_rect, contents_scale_);
279 // Consider tiles inside the live tiles rect even if only their border
280 // pixels intersect the invalidation. But don't consider tiles outside
281 // the live tiles rect with the same conditions, as they won't exist.
282 int border_pixels = tiling_data_.border_texels();
283 content_rect.Inset(-border_pixels, -border_pixels);
284 // Avoid needless work by not bothering to invalidate where there aren't
286 content_rect.Intersect(expanded_live_tiles_rect);
287 if (content_rect.IsEmpty())
289 // Since the content_rect includes border pixels already, don't include
290 // borders when iterating to avoid double counting them.
291 bool include_borders = false;
292 for (TilingData::Iterator iter(
293 &tiling_data_, content_rect, include_borders);
296 // There is no recycled twin since this is run on the pending tiling.
297 PictureLayerTiling* recycled_twin = NULL;
298 DCHECK_EQ(recycled_twin, client_->GetRecycledTwinTiling(this));
299 DCHECK_EQ(PENDING_TREE, client_->GetTree());
300 if (RemoveTileAt(iter.index_x(), iter.index_y(), recycled_twin))
301 new_tile_keys.push_back(iter.index());
305 if (recreate_invalidated_tiles && !new_tile_keys.empty()) {
306 for (size_t i = 0; i < new_tile_keys.size(); ++i) {
307 // Don't try to share a tile with the twin layer, it's been invalidated so
308 // we have to make our own tile here.
309 const PictureLayerTiling* twin_tiling = NULL;
310 CreateTile(new_tile_keys[i].first, new_tile_keys[i].second, twin_tiling);
315 PictureLayerTiling::CoverageIterator::CoverageIterator()
326 PictureLayerTiling::CoverageIterator::CoverageIterator(
327 const PictureLayerTiling* tiling,
329 const gfx::Rect& dest_rect)
331 dest_rect_(dest_rect),
332 dest_to_content_scale_(0),
341 if (dest_rect_.IsEmpty())
344 dest_to_content_scale_ = tiling_->contents_scale_ / dest_scale;
346 gfx::Rect content_rect =
347 gfx::ScaleToEnclosingRect(dest_rect_,
348 dest_to_content_scale_,
349 dest_to_content_scale_);
350 // IndexFromSrcCoord clamps to valid tile ranges, so it's necessary to
351 // check for non-intersection first.
352 content_rect.Intersect(gfx::Rect(tiling_->tiling_size()));
353 if (content_rect.IsEmpty())
356 left_ = tiling_->tiling_data_.TileXIndexFromSrcCoord(content_rect.x());
357 top_ = tiling_->tiling_data_.TileYIndexFromSrcCoord(content_rect.y());
358 right_ = tiling_->tiling_data_.TileXIndexFromSrcCoord(
359 content_rect.right() - 1);
360 bottom_ = tiling_->tiling_data_.TileYIndexFromSrcCoord(
361 content_rect.bottom() - 1);
368 PictureLayerTiling::CoverageIterator::~CoverageIterator() {
371 PictureLayerTiling::CoverageIterator&
372 PictureLayerTiling::CoverageIterator::operator++() {
373 if (tile_j_ > bottom_)
376 bool first_time = tile_i_ < left_;
377 bool new_row = false;
379 if (tile_i_ > right_) {
383 if (tile_j_ > bottom_) {
384 current_tile_ = NULL;
389 current_tile_ = tiling_->TileAt(tile_i_, tile_j_);
391 // Calculate the current geometry rect. Due to floating point rounding
392 // and ToEnclosingRect, tiles might overlap in destination space on the
394 gfx::Rect last_geometry_rect = current_geometry_rect_;
396 gfx::Rect content_rect = tiling_->tiling_data_.TileBounds(tile_i_, tile_j_);
398 current_geometry_rect_ =
399 gfx::ScaleToEnclosingRect(content_rect,
400 1 / dest_to_content_scale_,
401 1 / dest_to_content_scale_);
403 current_geometry_rect_.Intersect(dest_rect_);
408 // Iteration happens left->right, top->bottom. Running off the bottom-right
409 // edge is handled by the intersection above with dest_rect_. Here we make
410 // sure that the new current geometry rect doesn't overlap with the last.
414 min_left = dest_rect_.x();
415 min_top = last_geometry_rect.bottom();
417 min_left = last_geometry_rect.right();
418 min_top = last_geometry_rect.y();
421 int inset_left = std::max(0, min_left - current_geometry_rect_.x());
422 int inset_top = std::max(0, min_top - current_geometry_rect_.y());
423 current_geometry_rect_.Inset(inset_left, inset_top, 0, 0);
426 DCHECK_EQ(last_geometry_rect.right(), current_geometry_rect_.x());
427 DCHECK_EQ(last_geometry_rect.bottom(), current_geometry_rect_.bottom());
428 DCHECK_EQ(last_geometry_rect.y(), current_geometry_rect_.y());
434 gfx::Rect PictureLayerTiling::CoverageIterator::geometry_rect() const {
435 return current_geometry_rect_;
439 PictureLayerTiling::CoverageIterator::full_tile_geometry_rect() const {
440 gfx::Rect rect = tiling_->tiling_data_.TileBoundsWithBorder(tile_i_, tile_j_);
441 rect.set_size(tiling_->tiling_data_.max_texture_size());
445 gfx::RectF PictureLayerTiling::CoverageIterator::texture_rect() const {
446 gfx::PointF tex_origin =
447 tiling_->tiling_data_.TileBoundsWithBorder(tile_i_, tile_j_).origin();
449 // Convert from dest space => content space => texture space.
450 gfx::RectF texture_rect(current_geometry_rect_);
451 texture_rect.Scale(dest_to_content_scale_,
452 dest_to_content_scale_);
453 texture_rect.Intersect(gfx::Rect(tiling_->tiling_size()));
454 if (texture_rect.IsEmpty())
456 texture_rect.Offset(-tex_origin.OffsetFromOrigin());
461 gfx::Size PictureLayerTiling::CoverageIterator::texture_size() const {
462 return tiling_->tiling_data_.max_texture_size();
465 bool PictureLayerTiling::RemoveTileAt(int i,
467 PictureLayerTiling* recycled_twin) {
468 TileMap::iterator found = tiles_.find(TileMapKey(i, j));
469 if (found == tiles_.end())
471 found->second->set_shared(false);
473 eviction_tiles_cache_valid_ = false;
475 // Recycled twin does not also have a recycled twin, so pass NULL.
476 recycled_twin->RemoveTileAt(i, j, NULL);
481 void PictureLayerTiling::Reset() {
482 live_tiles_rect_ = gfx::Rect();
483 PictureLayerTiling* recycled_twin = client_->GetRecycledTwinTiling(this);
484 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
485 it->second->set_shared(false);
487 recycled_twin->RemoveTileAt(it->first.first, it->first.second, NULL);
490 eviction_tiles_cache_valid_ = false;
493 gfx::Rect PictureLayerTiling::ComputeSkewport(
494 double current_frame_time_in_seconds,
495 const gfx::Rect& visible_rect_in_content_space) const {
496 gfx::Rect skewport = visible_rect_in_content_space;
497 if (last_impl_frame_time_in_seconds_ == 0.0)
501 current_frame_time_in_seconds - last_impl_frame_time_in_seconds_;
502 if (time_delta == 0.0)
505 float skewport_target_time_in_seconds =
506 client_->GetSkewportTargetTimeInSeconds();
507 double extrapolation_multiplier =
508 skewport_target_time_in_seconds / time_delta;
510 int old_x = last_visible_rect_in_content_space_.x();
511 int old_y = last_visible_rect_in_content_space_.y();
512 int old_right = last_visible_rect_in_content_space_.right();
513 int old_bottom = last_visible_rect_in_content_space_.bottom();
515 int new_x = visible_rect_in_content_space.x();
516 int new_y = visible_rect_in_content_space.y();
517 int new_right = visible_rect_in_content_space.right();
518 int new_bottom = visible_rect_in_content_space.bottom();
520 int skewport_limit = client_->GetSkewportExtrapolationLimitInContentPixels();
522 // Compute the maximum skewport based on |skewport_limit|.
523 gfx::Rect max_skewport = skewport;
525 -skewport_limit, -skewport_limit, -skewport_limit, -skewport_limit);
527 // Inset the skewport by the needed adjustment.
528 skewport.Inset(extrapolation_multiplier * (new_x - old_x),
529 extrapolation_multiplier * (new_y - old_y),
530 extrapolation_multiplier * (old_right - new_right),
531 extrapolation_multiplier * (old_bottom - new_bottom));
533 // Clip the skewport to |max_skewport|.
534 skewport.Intersect(max_skewport);
536 // Finally, ensure that visible rect is contained in the skewport.
537 skewport.Union(visible_rect_in_content_space);
541 void PictureLayerTiling::ComputeTilePriorityRects(
543 const gfx::Rect& viewport_in_layer_space,
544 float ideal_contents_scale,
545 double current_frame_time_in_seconds,
546 const Occlusion& occlusion_in_layer_space) {
547 if (!NeedsUpdateForFrameAtTimeAndViewport(current_frame_time_in_seconds,
548 viewport_in_layer_space)) {
549 // This should never be zero for the purposes of has_ever_been_updated().
550 DCHECK_NE(current_frame_time_in_seconds, 0.0);
554 gfx::Rect visible_rect_in_content_space =
555 gfx::ScaleToEnclosingRect(viewport_in_layer_space, contents_scale_);
557 if (tiling_size().IsEmpty()) {
558 last_impl_frame_time_in_seconds_ = current_frame_time_in_seconds;
559 last_viewport_in_layer_space_ = viewport_in_layer_space;
560 last_visible_rect_in_content_space_ = visible_rect_in_content_space;
564 // Calculate the skewport.
565 gfx::Rect skewport = ComputeSkewport(current_frame_time_in_seconds,
566 visible_rect_in_content_space);
567 DCHECK(skewport.Contains(visible_rect_in_content_space));
569 // Calculate the eventually/live tiles rect.
570 size_t max_tiles_for_interest_area = client_->GetMaxTilesForInterestArea();
572 gfx::Size tile_size = tiling_data_.max_texture_size();
573 int64 eventually_rect_area =
574 max_tiles_for_interest_area * tile_size.width() * tile_size.height();
576 gfx::Rect eventually_rect =
577 ExpandRectEquallyToAreaBoundedBy(visible_rect_in_content_space,
578 eventually_rect_area,
579 gfx::Rect(tiling_size()),
582 DCHECK(eventually_rect.IsEmpty() ||
583 gfx::Rect(tiling_size()).Contains(eventually_rect))
584 << "tiling_size: " << tiling_size().ToString()
585 << " eventually_rect: " << eventually_rect.ToString();
587 // Calculate the soon border rect.
588 content_to_screen_scale_ = ideal_contents_scale / contents_scale_;
589 gfx::Rect soon_border_rect = visible_rect_in_content_space;
590 float border = kSoonBorderDistanceInScreenPixels / content_to_screen_scale_;
591 soon_border_rect.Inset(-border, -border, -border, -border);
593 // Update the tiling state.
594 SetLiveTilesRect(eventually_rect);
596 last_impl_frame_time_in_seconds_ = current_frame_time_in_seconds;
597 last_viewport_in_layer_space_ = viewport_in_layer_space;
598 last_visible_rect_in_content_space_ = visible_rect_in_content_space;
600 eviction_tiles_cache_valid_ = false;
602 current_visible_rect_ = visible_rect_in_content_space;
603 current_skewport_rect_ = skewport;
604 current_soon_border_rect_ = soon_border_rect;
605 current_eventually_rect_ = eventually_rect;
606 current_occlusion_in_layer_space_ = occlusion_in_layer_space;
608 // Update has_*_tiles state.
609 gfx::Rect tiling_rect(tiling_size());
611 has_visible_rect_tiles_ = tiling_rect.Intersects(current_visible_rect_);
612 has_skewport_rect_tiles_ = tiling_rect.Intersects(current_skewport_rect_);
613 has_soon_border_rect_tiles_ =
614 tiling_rect.Intersects(current_soon_border_rect_);
615 has_eventually_rect_tiles_ = tiling_rect.Intersects(current_eventually_rect_);
618 void PictureLayerTiling::SetLiveTilesRect(
619 const gfx::Rect& new_live_tiles_rect) {
620 DCHECK(new_live_tiles_rect.IsEmpty() ||
621 gfx::Rect(tiling_size()).Contains(new_live_tiles_rect))
622 << "tiling_size: " << tiling_size().ToString()
623 << " new_live_tiles_rect: " << new_live_tiles_rect.ToString();
624 if (live_tiles_rect_ == new_live_tiles_rect)
627 // Iterate to delete all tiles outside of our new live_tiles rect.
628 PictureLayerTiling* recycled_twin = client_->GetRecycledTwinTiling(this);
629 for (TilingData::DifferenceIterator iter(&tiling_data_,
631 new_live_tiles_rect);
634 RemoveTileAt(iter.index_x(), iter.index_y(), recycled_twin);
637 const PictureLayerTiling* twin_tiling =
638 client_->GetPendingOrActiveTwinTiling(this);
640 // Iterate to allocate new tiles for all regions with newly exposed area.
641 for (TilingData::DifferenceIterator iter(&tiling_data_,
646 TileMapKey key(iter.index());
647 CreateTile(key.first, key.second, twin_tiling);
650 live_tiles_rect_ = new_live_tiles_rect;
651 VerifyLiveTilesRect();
654 void PictureLayerTiling::VerifyLiveTilesRect() {
656 for (TileMap::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
657 if (!it->second.get())
659 DCHECK(it->first.first < tiling_data_.num_tiles_x())
660 << this << " " << it->first.first << "," << it->first.second
661 << " num_tiles_x " << tiling_data_.num_tiles_x() << " live_tiles_rect "
662 << live_tiles_rect_.ToString();
663 DCHECK(it->first.second < tiling_data_.num_tiles_y())
664 << this << " " << it->first.first << "," << it->first.second
665 << " num_tiles_y " << tiling_data_.num_tiles_y() << " live_tiles_rect "
666 << live_tiles_rect_.ToString();
667 DCHECK(tiling_data_.TileBounds(it->first.first, it->first.second)
668 .Intersects(live_tiles_rect_))
669 << this << " " << it->first.first << "," << it->first.second
671 << tiling_data_.TileBounds(it->first.first, it->first.second).ToString()
672 << " live_tiles_rect " << live_tiles_rect_.ToString();
677 bool PictureLayerTiling::IsTileOccluded(const Tile* tile) const {
680 if (!current_occlusion_in_layer_space_.HasOcclusion())
683 gfx::Rect tile_query_rect =
684 gfx::IntersectRects(tile->content_rect(), current_visible_rect_);
686 // Explicitly check if the tile is outside the viewport. If so, we need to
687 // return false, since occlusion for this tile is unknown.
688 // TODO(vmpstr): Since the current visible rect is really a viewport in
689 // layer space, we should probably clip tile query rect to tiling bounds
690 // or live tiles rect.
691 if (tile_query_rect.IsEmpty())
694 if (contents_scale_ != 1.f) {
696 gfx::ScaleToEnclosingRect(tile_query_rect, 1.0f / contents_scale_);
699 return current_occlusion_in_layer_space_.IsOccluded(tile_query_rect);
702 bool PictureLayerTiling::IsTileRequiredForActivation(const Tile* tile) const {
703 DCHECK_EQ(PENDING_TREE, client_->GetTree());
705 // Note that although this function will determine whether tile is required
706 // for activation assuming that it is in visible (ie in the viewport). That is
707 // to say, even if the tile is outside of the viewport, it will be treated as
708 // if it was inside (there are no explicit checks for this). Hence, this
709 // function is only called for visible tiles to ensure we don't block
710 // activation on tiles outside of the viewport.
712 // If we are not allowed to mark tiles as required for activation, then don't
714 if (!can_require_tiles_for_activation_)
717 if (resolution_ != HIGH_RESOLUTION)
720 if (IsTileOccluded(tile))
723 if (client_->RequiresHighResToDraw())
726 const PictureLayerTiling* twin_tiling =
727 client_->GetPendingOrActiveTwinTiling(this);
731 if (twin_tiling->layer_bounds() != layer_bounds())
734 if (twin_tiling->current_visible_rect_ != current_visible_rect_)
738 twin_tiling->TileAt(tile->tiling_i_index(), tile->tiling_j_index());
739 // If twin tile is missing, it might not have a recording, so we don't need
740 // this tile to be required for activation.
747 void PictureLayerTiling::UpdateTileAndTwinPriority(Tile* tile) const {
748 UpdateTilePriority(tile);
750 const PictureLayerTiling* twin_tiling =
751 client_->GetPendingOrActiveTwinTiling(this);
752 if (!tile->is_shared() || !twin_tiling) {
753 WhichTree tree = client_->GetTree();
754 WhichTree twin_tree = tree == ACTIVE_TREE ? PENDING_TREE : ACTIVE_TREE;
755 tile->SetPriority(twin_tree, TilePriority());
756 tile->set_is_occluded(twin_tree, false);
757 if (twin_tree == PENDING_TREE)
758 tile->set_required_for_activation(false);
762 twin_tiling->UpdateTilePriority(tile);
765 void PictureLayerTiling::UpdateTilePriority(Tile* tile) const {
766 // TODO(vmpstr): This code should return the priority instead of setting it on
767 // the tile. This should be a part of the change to move tile priority from
768 // tiles into iterators.
769 WhichTree tree = client_->GetTree();
771 DCHECK_EQ(TileAt(tile->tiling_i_index(), tile->tiling_j_index()), tile);
772 gfx::Rect tile_bounds =
773 tiling_data_.TileBounds(tile->tiling_i_index(), tile->tiling_j_index());
775 if (current_visible_rect_.Intersects(tile_bounds)) {
776 tile->SetPriority(tree, TilePriority(resolution_, TilePriority::NOW, 0));
777 if (tree == PENDING_TREE)
778 tile->set_required_for_activation(IsTileRequiredForActivation(tile));
779 tile->set_is_occluded(tree, IsTileOccluded(tile));
783 if (tree == PENDING_TREE)
784 tile->set_required_for_activation(false);
785 tile->set_is_occluded(tree, false);
787 DCHECK_GT(content_to_screen_scale_, 0.f);
788 float distance_to_visible =
789 current_visible_rect_.ManhattanInternalDistance(tile_bounds) *
790 content_to_screen_scale_;
792 if (current_soon_border_rect_.Intersects(tile_bounds) ||
793 current_skewport_rect_.Intersects(tile_bounds)) {
796 TilePriority(resolution_, TilePriority::SOON, distance_to_visible));
802 TilePriority(resolution_, TilePriority::EVENTUALLY, distance_to_visible));
805 void PictureLayerTiling::GetAllTilesForTracing(
806 std::set<const Tile*>* tiles) const {
807 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it)
808 tiles->insert(it->second.get());
811 void PictureLayerTiling::AsValueInto(base::debug::TracedValue* state) const {
812 state->SetInteger("num_tiles", tiles_.size());
813 state->SetDouble("content_scale", contents_scale_);
814 state->BeginDictionary("tiling_size");
815 MathUtil::AddToTracedValue(tiling_size(), state);
816 state->EndDictionary();
819 size_t PictureLayerTiling::GPUMemoryUsageInBytes() const {
821 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
822 const Tile* tile = it->second.get();
823 amount += tile->GPUMemoryUsageInBytes();
828 PictureLayerTiling::RectExpansionCache::RectExpansionCache()
829 : previous_target(0) {
834 // This struct represents an event at which the expending rect intersects
835 // one of its boundaries. 4 intersection events will occur during expansion.
837 enum { BOTTOM, TOP, LEFT, RIGHT } edge;
842 // Compute the delta to expand from edges to cover target_area.
843 int ComputeExpansionDelta(int num_x_edges, int num_y_edges,
844 int width, int height,
846 // Compute coefficients for the quadratic equation:
847 // a*x^2 + b*x + c = 0
848 int a = num_y_edges * num_x_edges;
849 int b = num_y_edges * width + num_x_edges * height;
850 int64 c = static_cast<int64>(width) * height - target_area;
852 // Compute the delta for our edges using the quadratic equation.
854 (a == 0) ? -c / b : (-b + static_cast<int>(std::sqrt(
855 static_cast<int64>(b) * b - 4.0 * a * c))) /
857 return std::max(0, delta);
862 gfx::Rect PictureLayerTiling::ExpandRectEquallyToAreaBoundedBy(
863 const gfx::Rect& starting_rect,
865 const gfx::Rect& bounding_rect,
866 RectExpansionCache* cache) {
867 if (starting_rect.IsEmpty())
868 return starting_rect;
871 cache->previous_start == starting_rect &&
872 cache->previous_bounds == bounding_rect &&
873 cache->previous_target == target_area)
874 return cache->previous_result;
877 cache->previous_start = starting_rect;
878 cache->previous_bounds = bounding_rect;
879 cache->previous_target = target_area;
882 DCHECK(!bounding_rect.IsEmpty());
883 DCHECK_GT(target_area, 0);
885 // Expand the starting rect to cover target_area, if it is smaller than it.
886 int delta = ComputeExpansionDelta(
887 2, 2, starting_rect.width(), starting_rect.height(), target_area);
888 gfx::Rect expanded_starting_rect = starting_rect;
890 expanded_starting_rect.Inset(-delta, -delta);
892 gfx::Rect rect = IntersectRects(expanded_starting_rect, bounding_rect);
893 if (rect.IsEmpty()) {
894 // The starting_rect and bounding_rect are far away.
896 cache->previous_result = rect;
899 if (delta >= 0 && rect == expanded_starting_rect) {
900 // The starting rect already covers the entire bounding_rect and isn't too
901 // large for the target_area.
903 cache->previous_result = rect;
907 // Continue to expand/shrink rect to let it cover target_area.
909 // These values will be updated by the loop and uses as the output.
910 int origin_x = rect.x();
911 int origin_y = rect.y();
912 int width = rect.width();
913 int height = rect.height();
915 // In the beginning we will consider 2 edges in each dimension.
919 // Create an event list.
920 EdgeEvent events[] = {
921 { EdgeEvent::BOTTOM, &num_y_edges, rect.y() - bounding_rect.y() },
922 { EdgeEvent::TOP, &num_y_edges, bounding_rect.bottom() - rect.bottom() },
923 { EdgeEvent::LEFT, &num_x_edges, rect.x() - bounding_rect.x() },
924 { EdgeEvent::RIGHT, &num_x_edges, bounding_rect.right() - rect.right() }
927 // Sort the events by distance (closest first).
928 if (events[0].distance > events[1].distance) std::swap(events[0], events[1]);
929 if (events[2].distance > events[3].distance) std::swap(events[2], events[3]);
930 if (events[0].distance > events[2].distance) std::swap(events[0], events[2]);
931 if (events[1].distance > events[3].distance) std::swap(events[1], events[3]);
932 if (events[1].distance > events[2].distance) std::swap(events[1], events[2]);
934 for (int event_index = 0; event_index < 4; event_index++) {
935 const EdgeEvent& event = events[event_index];
937 int delta = ComputeExpansionDelta(
938 num_x_edges, num_y_edges, width, height, target_area);
940 // Clamp delta to our event distance.
941 if (delta > event.distance)
942 delta = event.distance;
944 // Adjust the edge count for this kind of edge.
947 // Apply the delta to the edges and edge events.
948 for (int i = event_index; i < 4; i++) {
949 switch (events[i].edge) {
950 case EdgeEvent::BOTTOM:
957 case EdgeEvent::LEFT:
961 case EdgeEvent::RIGHT:
965 events[i].distance -= delta;
968 // If our delta is less then our event distance, we're done.
969 if (delta < event.distance)
973 gfx::Rect result(origin_x, origin_y, width, height);
975 cache->previous_result = result;
979 void PictureLayerTiling::UpdateEvictionCacheIfNeeded(
980 TreePriority tree_priority) {
981 if (eviction_tiles_cache_valid_ &&
982 eviction_cache_tree_priority_ == tree_priority)
985 eviction_tiles_now_.clear();
986 eviction_tiles_now_and_required_for_activation_.clear();
987 eviction_tiles_soon_.clear();
988 eviction_tiles_soon_and_required_for_activation_.clear();
989 eviction_tiles_eventually_.clear();
990 eviction_tiles_eventually_and_required_for_activation_.clear();
992 for (TileMap::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
993 Tile* tile = it->second.get();
994 UpdateTileAndTwinPriority(tile);
995 const TilePriority& priority =
996 tile->priority_for_tree_priority(tree_priority);
997 switch (priority.priority_bin) {
998 case TilePriority::EVENTUALLY:
999 if (tile->required_for_activation())
1000 eviction_tiles_eventually_and_required_for_activation_.push_back(
1003 eviction_tiles_eventually_.push_back(tile);
1005 case TilePriority::SOON:
1006 if (tile->required_for_activation())
1007 eviction_tiles_soon_and_required_for_activation_.push_back(tile);
1009 eviction_tiles_soon_.push_back(tile);
1011 case TilePriority::NOW:
1012 if (tile->required_for_activation())
1013 eviction_tiles_now_and_required_for_activation_.push_back(tile);
1015 eviction_tiles_now_.push_back(tile);
1020 // TODO(vmpstr): Do this lazily. One option is to have a "sorted" flag that
1021 // can be updated for each of the queues.
1022 TileEvictionOrder sort_order(tree_priority);
1023 std::sort(eviction_tiles_now_.begin(), eviction_tiles_now_.end(), sort_order);
1024 std::sort(eviction_tiles_now_and_required_for_activation_.begin(),
1025 eviction_tiles_now_and_required_for_activation_.end(),
1028 eviction_tiles_soon_.begin(), eviction_tiles_soon_.end(), sort_order);
1029 std::sort(eviction_tiles_soon_and_required_for_activation_.begin(),
1030 eviction_tiles_soon_and_required_for_activation_.end(),
1032 std::sort(eviction_tiles_eventually_.begin(),
1033 eviction_tiles_eventually_.end(),
1035 std::sort(eviction_tiles_eventually_and_required_for_activation_.begin(),
1036 eviction_tiles_eventually_and_required_for_activation_.end(),
1039 eviction_tiles_cache_valid_ = true;
1040 eviction_cache_tree_priority_ = tree_priority;
1043 const std::vector<Tile*>* PictureLayerTiling::GetEvictionTiles(
1044 TreePriority tree_priority,
1045 EvictionCategory category) {
1046 UpdateEvictionCacheIfNeeded(tree_priority);
1049 return &eviction_tiles_eventually_;
1050 case EVENTUALLY_AND_REQUIRED_FOR_ACTIVATION:
1051 return &eviction_tiles_eventually_and_required_for_activation_;
1053 return &eviction_tiles_soon_;
1054 case SOON_AND_REQUIRED_FOR_ACTIVATION:
1055 return &eviction_tiles_soon_and_required_for_activation_;
1057 return &eviction_tiles_now_;
1058 case NOW_AND_REQUIRED_FOR_ACTIVATION:
1059 return &eviction_tiles_now_and_required_for_activation_;
1062 return &eviction_tiles_eventually_;
1065 PictureLayerTiling::TilingRasterTileIterator::TilingRasterTileIterator()
1066 : tiling_(NULL), current_tile_(NULL) {}
1068 PictureLayerTiling::TilingRasterTileIterator::TilingRasterTileIterator(
1069 PictureLayerTiling* tiling)
1070 : tiling_(tiling), phase_(VISIBLE_RECT), current_tile_(NULL) {
1071 if (!tiling_->has_visible_rect_tiles_) {
1076 visible_iterator_ = TilingData::Iterator(&tiling_->tiling_data_,
1077 tiling_->current_visible_rect_,
1078 false /* include_borders */);
1079 if (!visible_iterator_) {
1085 tiling_->TileAt(visible_iterator_.index_x(), visible_iterator_.index_y());
1086 if (!current_tile_ || !TileNeedsRaster(current_tile_)) {
1090 tiling_->UpdateTileAndTwinPriority(current_tile_);
1093 PictureLayerTiling::TilingRasterTileIterator::~TilingRasterTileIterator() {}
1095 void PictureLayerTiling::TilingRasterTileIterator::AdvancePhase() {
1096 DCHECK_LT(phase_, EVENTUALLY_RECT);
1099 phase_ = static_cast<Phase>(phase_ + 1);
1105 if (!tiling_->has_skewport_rect_tiles_)
1108 spiral_iterator_ = TilingData::SpiralDifferenceIterator(
1109 &tiling_->tiling_data_,
1110 tiling_->current_skewport_rect_,
1111 tiling_->current_visible_rect_,
1112 tiling_->current_visible_rect_);
1114 case SOON_BORDER_RECT:
1115 if (!tiling_->has_soon_border_rect_tiles_)
1118 spiral_iterator_ = TilingData::SpiralDifferenceIterator(
1119 &tiling_->tiling_data_,
1120 tiling_->current_soon_border_rect_,
1121 tiling_->current_skewport_rect_,
1122 tiling_->current_visible_rect_);
1124 case EVENTUALLY_RECT:
1125 if (!tiling_->has_eventually_rect_tiles_) {
1126 current_tile_ = NULL;
1130 spiral_iterator_ = TilingData::SpiralDifferenceIterator(
1131 &tiling_->tiling_data_,
1132 tiling_->current_eventually_rect_,
1133 tiling_->current_skewport_rect_,
1134 tiling_->current_soon_border_rect_);
1138 while (spiral_iterator_) {
1139 current_tile_ = tiling_->TileAt(spiral_iterator_.index_x(),
1140 spiral_iterator_.index_y());
1141 if (current_tile_ && TileNeedsRaster(current_tile_))
1146 if (!spiral_iterator_ && phase_ == EVENTUALLY_RECT) {
1147 current_tile_ = NULL;
1150 } while (!spiral_iterator_);
1153 tiling_->UpdateTileAndTwinPriority(current_tile_);
1156 PictureLayerTiling::TilingRasterTileIterator&
1157 PictureLayerTiling::TilingRasterTileIterator::
1159 current_tile_ = NULL;
1160 while (!current_tile_ || !TileNeedsRaster(current_tile_)) {
1161 std::pair<int, int> next_index;
1164 ++visible_iterator_;
1165 if (!visible_iterator_) {
1169 next_index = visible_iterator_.index();
1172 case SOON_BORDER_RECT:
1174 if (!spiral_iterator_) {
1178 next_index = spiral_iterator_.index();
1180 case EVENTUALLY_RECT:
1182 if (!spiral_iterator_) {
1183 current_tile_ = NULL;
1186 next_index = spiral_iterator_.index();
1189 current_tile_ = tiling_->TileAt(next_index.first, next_index.second);
1193 tiling_->UpdateTileAndTwinPriority(current_tile_);
1197 PictureLayerTiling::TilingEvictionTileIterator::TilingEvictionTileIterator()
1198 : eviction_tiles_(NULL), current_eviction_tiles_index_(0u) {
1201 PictureLayerTiling::TilingEvictionTileIterator::TilingEvictionTileIterator(
1202 PictureLayerTiling* tiling,
1203 TreePriority tree_priority,
1204 EvictionCategory category)
1205 : eviction_tiles_(tiling->GetEvictionTiles(tree_priority, category)),
1206 // Note: initializing to "0 - 1" works as overflow is well defined for
1207 // unsigned integers.
1208 current_eviction_tiles_index_(static_cast<size_t>(0) - 1) {
1209 DCHECK(eviction_tiles_);
1213 PictureLayerTiling::TilingEvictionTileIterator::~TilingEvictionTileIterator() {
1216 PictureLayerTiling::TilingEvictionTileIterator::operator bool() const {
1217 return eviction_tiles_ &&
1218 current_eviction_tiles_index_ != eviction_tiles_->size();
1221 Tile* PictureLayerTiling::TilingEvictionTileIterator::operator*() {
1223 return (*eviction_tiles_)[current_eviction_tiles_index_];
1226 const Tile* PictureLayerTiling::TilingEvictionTileIterator::operator*() const {
1228 return (*eviction_tiles_)[current_eviction_tiles_index_];
1231 PictureLayerTiling::TilingEvictionTileIterator&
1232 PictureLayerTiling::TilingEvictionTileIterator::
1236 ++current_eviction_tiles_index_;
1237 } while (current_eviction_tiles_index_ != eviction_tiles_->size() &&
1238 !(*eviction_tiles_)[current_eviction_tiles_index_]->HasResources());