Implement multiple alternative services per origin.
[chromium-blink-merge.git] / cc / tiles / picture_layer_tiling.cc
blobef31f58256b1dc3e3bba06a7a2ad7fa80ef2ddce
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/tiles/picture_layer_tiling.h"
7 #include <algorithm>
8 #include <cmath>
9 #include <limits>
10 #include <set>
12 #include "base/containers/hash_tables.h"
13 #include "base/containers/small_map.h"
14 #include "base/logging.h"
15 #include "base/numerics/safe_conversions.h"
16 #include "base/trace_event/trace_event.h"
17 #include "base/trace_event/trace_event_argument.h"
18 #include "cc/base/math_util.h"
19 #include "cc/playback/raster_source.h"
20 #include "cc/tiles/prioritized_tile.h"
21 #include "cc/tiles/tile.h"
22 #include "cc/tiles/tile_priority.h"
23 #include "ui/gfx/geometry/point_conversions.h"
24 #include "ui/gfx/geometry/rect_conversions.h"
25 #include "ui/gfx/geometry/safe_integer_conversions.h"
26 #include "ui/gfx/geometry/size_conversions.h"
28 namespace cc {
29 namespace {
31 const float kSoonBorderDistanceViewportPercentage = 0.15f;
32 const float kMaxSoonBorderDistanceInScreenPixels = 312.f;
34 } // namespace
36 scoped_ptr<PictureLayerTiling> PictureLayerTiling::Create(
37 WhichTree tree,
38 float contents_scale,
39 scoped_refptr<RasterSource> raster_source,
40 PictureLayerTilingClient* client,
41 size_t max_tiles_for_interest_area,
42 float skewport_target_time_in_seconds,
43 int skewport_extrapolation_limit_in_content_pixels) {
44 return make_scoped_ptr(new PictureLayerTiling(
45 tree, contents_scale, raster_source, client, max_tiles_for_interest_area,
46 skewport_target_time_in_seconds,
47 skewport_extrapolation_limit_in_content_pixels));
50 PictureLayerTiling::PictureLayerTiling(
51 WhichTree tree,
52 float contents_scale,
53 scoped_refptr<RasterSource> raster_source,
54 PictureLayerTilingClient* client,
55 size_t max_tiles_for_interest_area,
56 float skewport_target_time_in_seconds,
57 int skewport_extrapolation_limit_in_content_pixels)
58 : max_tiles_for_interest_area_(max_tiles_for_interest_area),
59 skewport_target_time_in_seconds_(skewport_target_time_in_seconds),
60 skewport_extrapolation_limit_in_content_pixels_(
61 skewport_extrapolation_limit_in_content_pixels),
62 contents_scale_(contents_scale),
63 client_(client),
64 tree_(tree),
65 raster_source_(raster_source),
66 resolution_(NON_IDEAL_RESOLUTION),
67 tiling_data_(gfx::Size(), gfx::Size(), kBorderTexels),
68 can_require_tiles_for_activation_(false),
69 current_content_to_screen_scale_(0.f),
70 has_visible_rect_tiles_(false),
71 has_skewport_rect_tiles_(false),
72 has_soon_border_rect_tiles_(false),
73 has_eventually_rect_tiles_(false),
74 all_tiles_done_(true) {
75 DCHECK(!raster_source->IsSolidColor());
76 gfx::Size content_bounds = gfx::ToCeiledSize(
77 gfx::ScaleSize(raster_source_->GetSize(), contents_scale));
78 gfx::Size tile_size = client_->CalculateTileSize(content_bounds);
80 DCHECK(!gfx::ToFlooredSize(gfx::ScaleSize(raster_source_->GetSize(),
81 contents_scale)).IsEmpty())
82 << "Tiling created with scale too small as contents become empty."
83 << " Layer bounds: " << raster_source_->GetSize().ToString()
84 << " Contents scale: " << contents_scale;
86 tiling_data_.SetTilingSize(content_bounds);
87 tiling_data_.SetMaxTextureSize(tile_size);
90 PictureLayerTiling::~PictureLayerTiling() {
93 // static
94 float PictureLayerTiling::CalculateSoonBorderDistance(
95 const gfx::Rect& visible_rect_in_content_space,
96 float content_to_screen_scale) {
97 float max_dimension = std::max(visible_rect_in_content_space.width(),
98 visible_rect_in_content_space.height());
99 return std::min(
100 kMaxSoonBorderDistanceInScreenPixels / content_to_screen_scale,
101 max_dimension * kSoonBorderDistanceViewportPercentage);
104 Tile* PictureLayerTiling::CreateTile(int i, int j) {
105 TileMapKey key(i, j);
106 DCHECK(tiles_.find(key) == tiles_.end());
108 gfx::Rect paint_rect = tiling_data_.TileBoundsWithBorder(i, j);
109 gfx::Rect tile_rect = paint_rect;
110 tile_rect.set_size(tiling_data_.max_texture_size());
112 if (!raster_source_->CoversRect(tile_rect, contents_scale_))
113 return nullptr;
115 all_tiles_done_ = false;
116 ScopedTilePtr tile = client_->CreateTile(contents_scale_, tile_rect);
117 Tile* raw_ptr = tile.get();
118 tile->set_tiling_index(i, j);
119 tiles_.add(key, tile.Pass());
120 return raw_ptr;
123 void PictureLayerTiling::CreateMissingTilesInLiveTilesRect() {
124 bool include_borders = false;
125 for (TilingData::Iterator iter(&tiling_data_, live_tiles_rect_,
126 include_borders);
127 iter; ++iter) {
128 TileMapKey key(iter.index());
129 TileMap::iterator find = tiles_.find(key);
130 if (find != tiles_.end())
131 continue;
133 if (ShouldCreateTileAt(key.index_x, key.index_y))
134 CreateTile(key.index_x, key.index_y);
136 VerifyLiveTilesRect(false);
139 void PictureLayerTiling::TakeTilesAndPropertiesFrom(
140 PictureLayerTiling* pending_twin,
141 const Region& layer_invalidation) {
142 TRACE_EVENT0("cc", "TakeTilesAndPropertiesFrom");
143 SetRasterSourceAndResize(pending_twin->raster_source_);
145 RemoveTilesInRegion(layer_invalidation, false /* recreate tiles */);
147 resolution_ = pending_twin->resolution_;
148 bool create_missing_tiles = false;
149 if (live_tiles_rect_.IsEmpty()) {
150 live_tiles_rect_ = pending_twin->live_tiles_rect();
151 create_missing_tiles = true;
152 } else {
153 SetLiveTilesRect(pending_twin->live_tiles_rect());
156 if (tiles_.empty()) {
157 tiles_.swap(pending_twin->tiles_);
158 all_tiles_done_ = pending_twin->all_tiles_done_;
159 } else {
160 while (!pending_twin->tiles_.empty()) {
161 TileMapKey key = pending_twin->tiles_.begin()->first;
162 tiles_.set(key, pending_twin->tiles_.take_and_erase(key));
164 all_tiles_done_ &= pending_twin->all_tiles_done_;
166 DCHECK(pending_twin->tiles_.empty());
167 pending_twin->all_tiles_done_ = true;
169 if (create_missing_tiles)
170 CreateMissingTilesInLiveTilesRect();
172 VerifyLiveTilesRect(false);
174 SetTilePriorityRects(pending_twin->current_content_to_screen_scale_,
175 pending_twin->current_visible_rect_,
176 pending_twin->current_skewport_rect_,
177 pending_twin->current_soon_border_rect_,
178 pending_twin->current_eventually_rect_,
179 pending_twin->current_occlusion_in_layer_space_);
182 void PictureLayerTiling::SetRasterSourceAndResize(
183 scoped_refptr<RasterSource> raster_source) {
184 DCHECK(!raster_source->IsSolidColor());
185 gfx::Size old_layer_bounds = raster_source_->GetSize();
186 raster_source_.swap(raster_source);
187 gfx::Size new_layer_bounds = raster_source_->GetSize();
188 gfx::Size content_bounds =
189 gfx::ToCeiledSize(gfx::ScaleSize(new_layer_bounds, contents_scale_));
190 gfx::Size tile_size = client_->CalculateTileSize(content_bounds);
192 if (tile_size != tiling_data_.max_texture_size()) {
193 tiling_data_.SetTilingSize(content_bounds);
194 tiling_data_.SetMaxTextureSize(tile_size);
195 // When the tile size changes, the TilingData positions no longer work
196 // as valid keys to the TileMap, so just drop all tiles and clear the live
197 // tiles rect.
198 Reset();
199 return;
202 if (old_layer_bounds == new_layer_bounds)
203 return;
205 // The SetLiveTilesRect() method would drop tiles outside the new bounds,
206 // but may do so incorrectly if resizing the tiling causes the number of
207 // tiles in the tiling_data_ to change.
208 gfx::Rect content_rect(content_bounds);
209 int before_left = tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.x());
210 int before_top = tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.y());
211 int before_right =
212 tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.right() - 1);
213 int before_bottom =
214 tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.bottom() - 1);
216 // The live_tiles_rect_ is clamped to stay within the tiling size as we
217 // change it.
218 live_tiles_rect_.Intersect(content_rect);
219 tiling_data_.SetTilingSize(content_bounds);
221 int after_right = -1;
222 int after_bottom = -1;
223 if (!live_tiles_rect_.IsEmpty()) {
224 after_right =
225 tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.right() - 1);
226 after_bottom =
227 tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.bottom() - 1);
230 // There is no recycled twin since this is run on the pending tiling
231 // during commit, and on the active tree during activate.
232 // Drop tiles outside the new layer bounds if the layer shrank.
233 for (int i = after_right + 1; i <= before_right; ++i) {
234 for (int j = before_top; j <= before_bottom; ++j)
235 RemoveTileAt(i, j);
237 for (int i = before_left; i <= after_right; ++i) {
238 for (int j = after_bottom + 1; j <= before_bottom; ++j)
239 RemoveTileAt(i, j);
242 if (after_right > before_right) {
243 DCHECK_EQ(after_right, before_right + 1);
244 for (int j = before_top; j <= after_bottom; ++j) {
245 if (ShouldCreateTileAt(after_right, j))
246 CreateTile(after_right, j);
249 if (after_bottom > before_bottom) {
250 DCHECK_EQ(after_bottom, before_bottom + 1);
251 for (int i = before_left; i <= before_right; ++i) {
252 if (ShouldCreateTileAt(i, after_bottom))
253 CreateTile(i, after_bottom);
258 void PictureLayerTiling::Invalidate(const Region& layer_invalidation) {
259 DCHECK_IMPLIES(tree_ == ACTIVE_TREE,
260 !client_->GetPendingOrActiveTwinTiling(this));
261 RemoveTilesInRegion(layer_invalidation, true /* recreate tiles */);
264 void PictureLayerTiling::RemoveTilesInRegion(const Region& layer_invalidation,
265 bool recreate_tiles) {
266 // We only invalidate the active tiling when it's orphaned: it has no pending
267 // twin, so it's slated for removal in the future.
268 if (live_tiles_rect_.IsEmpty())
269 return;
270 // Pick 16 for the size of the SmallMap before it promotes to a hash_map.
271 // 4x4 tiles should cover most small invalidations, and walking a vector of
272 // 16 is fast enough. If an invalidation is huge we will fall back to a
273 // hash_map instead of a vector in the SmallMap.
274 base::SmallMap<base::hash_map<TileMapKey, gfx::Rect>, 16> remove_tiles;
275 gfx::Rect expanded_live_tiles_rect =
276 tiling_data_.ExpandRectIgnoringBordersToTileBounds(live_tiles_rect_);
277 for (Region::Iterator iter(layer_invalidation); iter.has_rect();
278 iter.next()) {
279 gfx::Rect layer_rect = iter.rect();
280 // The pixels which are invalid in content space.
281 gfx::Rect invalid_content_rect =
282 gfx::ScaleToEnclosingRect(layer_rect, contents_scale_);
283 // Consider tiles inside the live tiles rect even if only their border
284 // pixels intersect the invalidation. But don't consider tiles outside
285 // the live tiles rect with the same conditions, as they won't exist.
286 gfx::Rect coverage_content_rect = invalid_content_rect;
287 int border_pixels = tiling_data_.border_texels();
288 coverage_content_rect.Inset(-border_pixels, -border_pixels);
289 // Avoid needless work by not bothering to invalidate where there aren't
290 // tiles.
291 coverage_content_rect.Intersect(expanded_live_tiles_rect);
292 if (coverage_content_rect.IsEmpty())
293 continue;
294 // Since the content_rect includes border pixels already, don't include
295 // borders when iterating to avoid double counting them.
296 bool include_borders = false;
297 for (TilingData::Iterator iter(&tiling_data_, coverage_content_rect,
298 include_borders);
299 iter; ++iter) {
300 // This also adds the TileMapKey to the map.
301 remove_tiles[TileMapKey(iter.index())].Union(invalid_content_rect);
305 for (const auto& pair : remove_tiles) {
306 const TileMapKey& key = pair.first;
307 const gfx::Rect& invalid_content_rect = pair.second;
308 // TODO(danakj): This old_tile will not exist if we are committing to a
309 // pending tree since there is no tile there to remove, which prevents
310 // tiles from knowing the invalidation rect and content id. crbug.com/490847
311 ScopedTilePtr old_tile = TakeTileAt(key.index_x, key.index_y);
312 if (recreate_tiles && old_tile) {
313 if (Tile* tile = CreateTile(key.index_x, key.index_y))
314 tile->SetInvalidated(invalid_content_rect, old_tile->id());
319 bool PictureLayerTiling::ShouldCreateTileAt(int i, int j) const {
320 // Active tree should always create a tile. The reason for this is that active
321 // tree represents content that we draw on screen, which means that whenever
322 // we check whether a tile should exist somewhere, the answer is yes. This
323 // doesn't mean it will actually be created (if raster source doesn't cover
324 // the tile for instance). Pending tree, on the other hand, should only be
325 // creating tiles that are different from the current active tree, which is
326 // represented by the logic in the rest of the function.
327 if (tree_ == ACTIVE_TREE)
328 return true;
330 // If the pending tree has no active twin, then it needs to create all tiles.
331 const PictureLayerTiling* active_twin =
332 client_->GetPendingOrActiveTwinTiling(this);
333 if (!active_twin)
334 return true;
336 // Pending tree will override the entire active tree if indices don't match.
337 if (!TilingMatchesTileIndices(active_twin))
338 return true;
340 gfx::Rect paint_rect = tiling_data_.TileBoundsWithBorder(i, j);
341 gfx::Rect tile_rect = paint_rect;
342 tile_rect.set_size(tiling_data_.max_texture_size());
344 // If the active tree can't create a tile, because of its raster source, then
345 // the pending tree should create one.
346 if (!active_twin->raster_source()->CoversRect(tile_rect, contents_scale()))
347 return true;
349 const Region* layer_invalidation = client_->GetPendingInvalidation();
350 gfx::Rect layer_rect =
351 gfx::ScaleToEnclosingRect(tile_rect, 1.f / contents_scale());
353 // If this tile is invalidated, then the pending tree should create one.
354 if (layer_invalidation && layer_invalidation->Intersects(layer_rect))
355 return true;
357 // If the active tree doesn't have a tile here, but it's in the pending tree's
358 // visible rect, then the pending tree should create a tile. This can happen
359 // if the pending visible rect is outside of the active tree's live tiles
360 // rect. In those situations, we need to block activation until we're ready to
361 // display content, which will have to come from the pending tree.
362 if (!active_twin->TileAt(i, j) && current_visible_rect_.Intersects(tile_rect))
363 return true;
365 // In all other cases, the pending tree doesn't need to create a tile.
366 return false;
369 bool PictureLayerTiling::TilingMatchesTileIndices(
370 const PictureLayerTiling* twin) const {
371 return tiling_data_.max_texture_size() ==
372 twin->tiling_data_.max_texture_size();
375 PictureLayerTiling::CoverageIterator::CoverageIterator()
376 : tiling_(NULL),
377 current_tile_(NULL),
378 tile_i_(0),
379 tile_j_(0),
380 left_(0),
381 top_(0),
382 right_(-1),
383 bottom_(-1) {
386 PictureLayerTiling::CoverageIterator::CoverageIterator(
387 const PictureLayerTiling* tiling,
388 float dest_scale,
389 const gfx::Rect& dest_rect)
390 : tiling_(tiling),
391 dest_rect_(dest_rect),
392 dest_to_content_scale_(0),
393 current_tile_(NULL),
394 tile_i_(0),
395 tile_j_(0),
396 left_(0),
397 top_(0),
398 right_(-1),
399 bottom_(-1) {
400 DCHECK(tiling_);
401 if (dest_rect_.IsEmpty())
402 return;
404 dest_to_content_scale_ = tiling_->contents_scale_ / dest_scale;
406 gfx::Rect content_rect =
407 gfx::ScaleToEnclosingRect(dest_rect_,
408 dest_to_content_scale_,
409 dest_to_content_scale_);
410 // IndexFromSrcCoord clamps to valid tile ranges, so it's necessary to
411 // check for non-intersection first.
412 content_rect.Intersect(gfx::Rect(tiling_->tiling_size()));
413 if (content_rect.IsEmpty())
414 return;
416 left_ = tiling_->tiling_data_.TileXIndexFromSrcCoord(content_rect.x());
417 top_ = tiling_->tiling_data_.TileYIndexFromSrcCoord(content_rect.y());
418 right_ = tiling_->tiling_data_.TileXIndexFromSrcCoord(
419 content_rect.right() - 1);
420 bottom_ = tiling_->tiling_data_.TileYIndexFromSrcCoord(
421 content_rect.bottom() - 1);
423 tile_i_ = left_ - 1;
424 tile_j_ = top_;
425 ++(*this);
428 PictureLayerTiling::CoverageIterator::~CoverageIterator() {
431 PictureLayerTiling::CoverageIterator&
432 PictureLayerTiling::CoverageIterator::operator++() {
433 if (tile_j_ > bottom_)
434 return *this;
436 bool first_time = tile_i_ < left_;
437 bool new_row = false;
438 tile_i_++;
439 if (tile_i_ > right_) {
440 tile_i_ = left_;
441 tile_j_++;
442 new_row = true;
443 if (tile_j_ > bottom_) {
444 current_tile_ = NULL;
445 return *this;
449 current_tile_ = tiling_->TileAt(tile_i_, tile_j_);
451 // Calculate the current geometry rect. Due to floating point rounding
452 // and ToEnclosingRect, tiles might overlap in destination space on the
453 // edges.
454 gfx::Rect last_geometry_rect = current_geometry_rect_;
456 gfx::Rect content_rect = tiling_->tiling_data_.TileBounds(tile_i_, tile_j_);
458 current_geometry_rect_ =
459 gfx::ScaleToEnclosingRect(content_rect,
460 1 / dest_to_content_scale_,
461 1 / dest_to_content_scale_);
463 current_geometry_rect_.Intersect(dest_rect_);
465 if (first_time)
466 return *this;
468 // Iteration happens left->right, top->bottom. Running off the bottom-right
469 // edge is handled by the intersection above with dest_rect_. Here we make
470 // sure that the new current geometry rect doesn't overlap with the last.
471 int min_left;
472 int min_top;
473 if (new_row) {
474 min_left = dest_rect_.x();
475 min_top = last_geometry_rect.bottom();
476 } else {
477 min_left = last_geometry_rect.right();
478 min_top = last_geometry_rect.y();
481 int inset_left = std::max(0, min_left - current_geometry_rect_.x());
482 int inset_top = std::max(0, min_top - current_geometry_rect_.y());
483 current_geometry_rect_.Inset(inset_left, inset_top, 0, 0);
485 if (!new_row) {
486 DCHECK_EQ(last_geometry_rect.right(), current_geometry_rect_.x());
487 DCHECK_EQ(last_geometry_rect.bottom(), current_geometry_rect_.bottom());
488 DCHECK_EQ(last_geometry_rect.y(), current_geometry_rect_.y());
491 return *this;
494 gfx::Rect PictureLayerTiling::CoverageIterator::geometry_rect() const {
495 return current_geometry_rect_;
498 gfx::RectF PictureLayerTiling::CoverageIterator::texture_rect() const {
499 gfx::PointF tex_origin =
500 tiling_->tiling_data_.TileBoundsWithBorder(tile_i_, tile_j_).origin();
502 // Convert from dest space => content space => texture space.
503 gfx::RectF texture_rect(current_geometry_rect_);
504 texture_rect.Scale(dest_to_content_scale_,
505 dest_to_content_scale_);
506 texture_rect.Intersect(gfx::Rect(tiling_->tiling_size()));
507 if (texture_rect.IsEmpty())
508 return texture_rect;
509 texture_rect.Offset(-tex_origin.OffsetFromOrigin());
511 return texture_rect;
514 ScopedTilePtr PictureLayerTiling::TakeTileAt(int i, int j) {
515 TileMap::iterator found = tiles_.find(TileMapKey(i, j));
516 if (found == tiles_.end())
517 return nullptr;
518 return tiles_.take_and_erase(found);
521 bool PictureLayerTiling::RemoveTileAt(int i, int j) {
522 TileMap::iterator found = tiles_.find(TileMapKey(i, j));
523 if (found == tiles_.end())
524 return false;
525 tiles_.erase(found);
526 return true;
529 void PictureLayerTiling::Reset() {
530 live_tiles_rect_ = gfx::Rect();
531 tiles_.clear();
532 all_tiles_done_ = true;
535 gfx::Rect PictureLayerTiling::ComputeSkewport(
536 double current_frame_time_in_seconds,
537 const gfx::Rect& visible_rect_in_content_space) const {
538 gfx::Rect skewport = visible_rect_in_content_space;
539 if (skewport.IsEmpty())
540 return skewport;
542 if (visible_rect_history_[1].frame_time_in_seconds == 0.0)
543 return skewport;
545 double time_delta = current_frame_time_in_seconds -
546 visible_rect_history_[1].frame_time_in_seconds;
547 if (time_delta == 0.0)
548 return skewport;
550 double extrapolation_multiplier =
551 skewport_target_time_in_seconds_ / time_delta;
553 int old_x = visible_rect_history_[1].visible_rect_in_content_space.x();
554 int old_y = visible_rect_history_[1].visible_rect_in_content_space.y();
555 int old_right =
556 visible_rect_history_[1].visible_rect_in_content_space.right();
557 int old_bottom =
558 visible_rect_history_[1].visible_rect_in_content_space.bottom();
560 int new_x = visible_rect_in_content_space.x();
561 int new_y = visible_rect_in_content_space.y();
562 int new_right = visible_rect_in_content_space.right();
563 int new_bottom = visible_rect_in_content_space.bottom();
565 // Compute the maximum skewport based on
566 // |skewport_extrapolation_limit_in_content_pixels_|.
567 gfx::Rect max_skewport = skewport;
568 max_skewport.Inset(-skewport_extrapolation_limit_in_content_pixels_,
569 -skewport_extrapolation_limit_in_content_pixels_);
571 // Inset the skewport by the needed adjustment.
572 skewport.Inset(extrapolation_multiplier * (new_x - old_x),
573 extrapolation_multiplier * (new_y - old_y),
574 extrapolation_multiplier * (old_right - new_right),
575 extrapolation_multiplier * (old_bottom - new_bottom));
577 // Ensure that visible rect is contained in the skewport.
578 skewport.Union(visible_rect_in_content_space);
580 // Clip the skewport to |max_skewport|. This needs to happen after the
581 // union in case intersecting would have left the empty rect.
582 skewport.Intersect(max_skewport);
584 // Due to limits in int's representation, it is possible that the two
585 // operations above (union and intersect) result in an empty skewport. To
586 // avoid any unpleasant situations like that, union the visible rect again to
587 // ensure that skewport.Contains(visible_rect_in_content_space) is always
588 // true.
589 skewport.Union(visible_rect_in_content_space);
591 return skewport;
594 bool PictureLayerTiling::ComputeTilePriorityRects(
595 const gfx::Rect& viewport_in_layer_space,
596 float ideal_contents_scale,
597 double current_frame_time_in_seconds,
598 const Occlusion& occlusion_in_layer_space) {
599 // If we have, or had occlusions, mark the tiles as 'not done' to ensure that
600 // we reiterate the tiles for rasterization.
601 if (occlusion_in_layer_space.HasOcclusion() ||
602 current_occlusion_in_layer_space_.HasOcclusion()) {
603 set_all_tiles_done(false);
606 if (!NeedsUpdateForFrameAtTimeAndViewport(current_frame_time_in_seconds,
607 viewport_in_layer_space)) {
608 // This should never be zero for the purposes of has_ever_been_updated().
609 DCHECK_NE(current_frame_time_in_seconds, 0.0);
610 return false;
612 gfx::Rect visible_rect_in_content_space =
613 gfx::ScaleToEnclosingRect(viewport_in_layer_space, contents_scale_);
615 if (tiling_size().IsEmpty()) {
616 UpdateVisibleRectHistory(current_frame_time_in_seconds,
617 visible_rect_in_content_space);
618 last_viewport_in_layer_space_ = viewport_in_layer_space;
619 return false;
622 // Calculate the skewport.
623 gfx::Rect skewport = ComputeSkewport(current_frame_time_in_seconds,
624 visible_rect_in_content_space);
625 DCHECK(skewport.Contains(visible_rect_in_content_space));
627 // Calculate the eventually/live tiles rect.
628 gfx::Size tile_size = tiling_data_.max_texture_size();
629 int64 eventually_rect_area =
630 max_tiles_for_interest_area_ * tile_size.width() * tile_size.height();
632 gfx::Rect eventually_rect =
633 ExpandRectEquallyToAreaBoundedBy(visible_rect_in_content_space,
634 eventually_rect_area,
635 gfx::Rect(tiling_size()),
636 &expansion_cache_);
638 DCHECK(eventually_rect.IsEmpty() ||
639 gfx::Rect(tiling_size()).Contains(eventually_rect))
640 << "tiling_size: " << tiling_size().ToString()
641 << " eventually_rect: " << eventually_rect.ToString();
643 // Calculate the soon border rect.
644 float content_to_screen_scale = ideal_contents_scale / contents_scale_;
645 gfx::Rect soon_border_rect = visible_rect_in_content_space;
646 float border = CalculateSoonBorderDistance(visible_rect_in_content_space,
647 content_to_screen_scale);
648 soon_border_rect.Inset(-border, -border, -border, -border);
650 UpdateVisibleRectHistory(current_frame_time_in_seconds,
651 visible_rect_in_content_space);
652 last_viewport_in_layer_space_ = viewport_in_layer_space;
654 SetTilePriorityRects(content_to_screen_scale, visible_rect_in_content_space,
655 skewport, soon_border_rect, eventually_rect,
656 occlusion_in_layer_space);
657 SetLiveTilesRect(eventually_rect);
658 return true;
661 void PictureLayerTiling::SetTilePriorityRects(
662 float content_to_screen_scale,
663 const gfx::Rect& visible_rect_in_content_space,
664 const gfx::Rect& skewport,
665 const gfx::Rect& soon_border_rect,
666 const gfx::Rect& eventually_rect,
667 const Occlusion& occlusion_in_layer_space) {
668 current_visible_rect_ = visible_rect_in_content_space;
669 current_skewport_rect_ = skewport;
670 current_soon_border_rect_ = soon_border_rect;
671 current_eventually_rect_ = eventually_rect;
672 current_occlusion_in_layer_space_ = occlusion_in_layer_space;
673 current_content_to_screen_scale_ = content_to_screen_scale;
675 gfx::Rect tiling_rect(tiling_size());
676 has_visible_rect_tiles_ = tiling_rect.Intersects(current_visible_rect_);
677 has_skewport_rect_tiles_ = tiling_rect.Intersects(current_skewport_rect_);
678 has_soon_border_rect_tiles_ =
679 tiling_rect.Intersects(current_soon_border_rect_);
680 has_eventually_rect_tiles_ = tiling_rect.Intersects(current_eventually_rect_);
683 void PictureLayerTiling::SetLiveTilesRect(
684 const gfx::Rect& new_live_tiles_rect) {
685 DCHECK(new_live_tiles_rect.IsEmpty() ||
686 gfx::Rect(tiling_size()).Contains(new_live_tiles_rect))
687 << "tiling_size: " << tiling_size().ToString()
688 << " new_live_tiles_rect: " << new_live_tiles_rect.ToString();
689 if (live_tiles_rect_ == new_live_tiles_rect)
690 return;
692 // Iterate to delete all tiles outside of our new live_tiles rect.
693 for (TilingData::DifferenceIterator iter(&tiling_data_, live_tiles_rect_,
694 new_live_tiles_rect);
695 iter; ++iter) {
696 RemoveTileAt(iter.index_x(), iter.index_y());
699 // Iterate to allocate new tiles for all regions with newly exposed area.
700 for (TilingData::DifferenceIterator iter(&tiling_data_, new_live_tiles_rect,
701 live_tiles_rect_);
702 iter; ++iter) {
703 TileMapKey key(iter.index());
704 if (ShouldCreateTileAt(key.index_x, key.index_y))
705 CreateTile(key.index_x, key.index_y);
708 live_tiles_rect_ = new_live_tiles_rect;
709 VerifyLiveTilesRect(false);
712 void PictureLayerTiling::VerifyLiveTilesRect(bool is_on_recycle_tree) const {
713 #if DCHECK_IS_ON()
714 for (auto it = tiles_.begin(); it != tiles_.end(); ++it) {
715 if (!it->second)
716 continue;
717 TileMapKey key = it->first;
718 DCHECK(key.index_x < tiling_data_.num_tiles_x())
719 << this << " " << key.index_x << "," << key.index_y << " num_tiles_x "
720 << tiling_data_.num_tiles_x() << " live_tiles_rect "
721 << live_tiles_rect_.ToString();
722 DCHECK(key.index_y < tiling_data_.num_tiles_y())
723 << this << " " << key.index_x << "," << key.index_y << " num_tiles_y "
724 << tiling_data_.num_tiles_y() << " live_tiles_rect "
725 << live_tiles_rect_.ToString();
726 DCHECK(tiling_data_.TileBounds(key.index_x, key.index_y)
727 .Intersects(live_tiles_rect_))
728 << this << " " << key.index_x << "," << key.index_y << " tile bounds "
729 << tiling_data_.TileBounds(key.index_x, key.index_y).ToString()
730 << " live_tiles_rect " << live_tiles_rect_.ToString();
732 #endif
735 bool PictureLayerTiling::IsTileOccluded(const Tile* tile) const {
736 // If this tile is not occluded on this tree, then it is not occluded.
737 if (!IsTileOccludedOnCurrentTree(tile))
738 return false;
740 // Otherwise, if this is the pending tree, we're done and the tile is
741 // occluded.
742 if (tree_ == PENDING_TREE)
743 return true;
745 // On the active tree however, we need to check if this tile will be
746 // unoccluded upon activation, in which case it has to be considered
747 // unoccluded.
748 const PictureLayerTiling* pending_twin =
749 client_->GetPendingOrActiveTwinTiling(this);
750 if (pending_twin) {
751 // If there's a pending tile in the same position. Or if the pending twin
752 // would have to be creating all tiles, then we don't need to worry about
753 // occlusion on the twin.
754 if (!TilingMatchesTileIndices(pending_twin) ||
755 pending_twin->TileAt(tile->tiling_i_index(), tile->tiling_j_index())) {
756 return true;
758 return pending_twin->IsTileOccludedOnCurrentTree(tile);
760 return true;
763 bool PictureLayerTiling::IsTileOccludedOnCurrentTree(const Tile* tile) const {
764 if (!current_occlusion_in_layer_space_.HasOcclusion())
765 return false;
766 gfx::Rect tile_query_rect =
767 gfx::IntersectRects(tile->content_rect(), current_visible_rect_);
768 // Explicitly check if the tile is outside the viewport. If so, we need to
769 // return false, since occlusion for this tile is unknown.
770 if (tile_query_rect.IsEmpty())
771 return false;
773 if (contents_scale_ != 1.f) {
774 tile_query_rect =
775 gfx::ScaleToEnclosingRect(tile_query_rect, 1.f / contents_scale_);
777 return current_occlusion_in_layer_space_.IsOccluded(tile_query_rect);
780 bool PictureLayerTiling::IsTileRequiredForActivation(const Tile* tile) const {
781 if (tree_ == PENDING_TREE) {
782 if (!can_require_tiles_for_activation_)
783 return false;
785 if (resolution_ != HIGH_RESOLUTION)
786 return false;
788 if (IsTileOccluded(tile))
789 return false;
791 bool tile_is_visible =
792 tile->content_rect().Intersects(current_visible_rect_);
793 if (!tile_is_visible)
794 return false;
796 if (client_->RequiresHighResToDraw())
797 return true;
799 const PictureLayerTiling* active_twin =
800 client_->GetPendingOrActiveTwinTiling(this);
801 if (!active_twin || !TilingMatchesTileIndices(active_twin))
802 return true;
804 if (active_twin->raster_source()->GetSize() != raster_source()->GetSize())
805 return true;
807 if (active_twin->current_visible_rect_ != current_visible_rect_)
808 return true;
810 Tile* twin_tile =
811 active_twin->TileAt(tile->tiling_i_index(), tile->tiling_j_index());
812 if (!twin_tile)
813 return false;
814 return true;
817 DCHECK_EQ(tree_, ACTIVE_TREE);
818 const PictureLayerTiling* pending_twin =
819 client_->GetPendingOrActiveTwinTiling(this);
820 // If we don't have a pending tree, or the pending tree will overwrite the
821 // given tile, then it is not required for activation.
822 if (!pending_twin || !TilingMatchesTileIndices(pending_twin) ||
823 pending_twin->TileAt(tile->tiling_i_index(), tile->tiling_j_index())) {
824 return false;
826 // Otherwise, ask the pending twin if this tile is required for activation.
827 return pending_twin->IsTileRequiredForActivation(tile);
830 bool PictureLayerTiling::IsTileRequiredForDraw(const Tile* tile) const {
831 if (tree_ == PENDING_TREE)
832 return false;
834 if (resolution_ != HIGH_RESOLUTION)
835 return false;
837 bool tile_is_visible = current_visible_rect_.Intersects(tile->content_rect());
838 if (!tile_is_visible)
839 return false;
841 if (IsTileOccludedOnCurrentTree(tile))
842 return false;
843 return true;
846 void PictureLayerTiling::UpdateRequiredStatesOnTile(Tile* tile) const {
847 DCHECK(tile);
848 tile->set_required_for_activation(IsTileRequiredForActivation(tile));
849 tile->set_required_for_draw(IsTileRequiredForDraw(tile));
852 PrioritizedTile PictureLayerTiling::MakePrioritizedTile(
853 Tile* tile,
854 PriorityRectType priority_rect_type) const {
855 DCHECK(tile);
856 DCHECK(
857 raster_source()->CoversRect(tile->content_rect(), tile->contents_scale()))
858 << "Recording rect: "
859 << gfx::ScaleToEnclosingRect(tile->content_rect(),
860 1.f / tile->contents_scale()).ToString();
862 return PrioritizedTile(tile, raster_source(),
863 ComputePriorityForTile(tile, priority_rect_type),
864 IsTileOccluded(tile));
867 std::map<const Tile*, PrioritizedTile>
868 PictureLayerTiling::UpdateAndGetAllPrioritizedTilesForTesting() const {
869 std::map<const Tile*, PrioritizedTile> result;
870 for (const auto& key_tile_pair : tiles_) {
871 Tile* tile = key_tile_pair.second;
872 UpdateRequiredStatesOnTile(tile);
873 PrioritizedTile prioritized_tile =
874 MakePrioritizedTile(tile, ComputePriorityRectTypeForTile(tile));
875 result.insert(std::make_pair(prioritized_tile.tile(), prioritized_tile));
877 return result;
880 TilePriority PictureLayerTiling::ComputePriorityForTile(
881 const Tile* tile,
882 PriorityRectType priority_rect_type) const {
883 // TODO(vmpstr): See if this can be moved to iterators.
884 DCHECK_EQ(ComputePriorityRectTypeForTile(tile), priority_rect_type);
885 DCHECK_EQ(TileAt(tile->tiling_i_index(), tile->tiling_j_index()), tile);
887 TilePriority::PriorityBin priority_bin = client_->HasValidTilePriorities()
888 ? TilePriority::NOW
889 : TilePriority::EVENTUALLY;
890 switch (priority_rect_type) {
891 case VISIBLE_RECT:
892 return TilePriority(resolution_, priority_bin, 0);
893 case PENDING_VISIBLE_RECT:
894 if (priority_bin < TilePriority::SOON)
895 priority_bin = TilePriority::SOON;
896 return TilePriority(resolution_, priority_bin, 0);
897 case SKEWPORT_RECT:
898 case SOON_BORDER_RECT:
899 if (priority_bin < TilePriority::SOON)
900 priority_bin = TilePriority::SOON;
901 break;
902 case EVENTUALLY_RECT:
903 priority_bin = TilePriority::EVENTUALLY;
904 break;
907 gfx::Rect tile_bounds =
908 tiling_data_.TileBounds(tile->tiling_i_index(), tile->tiling_j_index());
909 DCHECK_GT(current_content_to_screen_scale_, 0.f);
910 float distance_to_visible =
911 current_visible_rect_.ManhattanInternalDistance(tile_bounds) *
912 current_content_to_screen_scale_;
914 return TilePriority(resolution_, priority_bin, distance_to_visible);
917 PictureLayerTiling::PriorityRectType
918 PictureLayerTiling::ComputePriorityRectTypeForTile(const Tile* tile) const {
919 DCHECK_EQ(TileAt(tile->tiling_i_index(), tile->tiling_j_index()), tile);
920 gfx::Rect tile_bounds =
921 tiling_data_.TileBounds(tile->tiling_i_index(), tile->tiling_j_index());
923 if (current_visible_rect_.Intersects(tile_bounds))
924 return VISIBLE_RECT;
926 if (pending_visible_rect().Intersects(tile_bounds))
927 return PENDING_VISIBLE_RECT;
929 if (current_skewport_rect_.Intersects(tile_bounds))
930 return SKEWPORT_RECT;
932 if (current_soon_border_rect_.Intersects(tile_bounds))
933 return SOON_BORDER_RECT;
935 DCHECK(current_eventually_rect_.Intersects(tile_bounds));
936 return EVENTUALLY_RECT;
939 void PictureLayerTiling::GetAllPrioritizedTilesForTracing(
940 std::vector<PrioritizedTile>* prioritized_tiles) const {
941 for (const auto& tile_pair : tiles_) {
942 Tile* tile = tile_pair.second;
943 prioritized_tiles->push_back(
944 MakePrioritizedTile(tile, ComputePriorityRectTypeForTile(tile)));
948 void PictureLayerTiling::AsValueInto(
949 base::trace_event::TracedValue* state) const {
950 state->SetInteger("num_tiles", base::saturated_cast<int>(tiles_.size()));
951 state->SetDouble("content_scale", contents_scale_);
952 MathUtil::AddToTracedValue("visible_rect", current_visible_rect_, state);
953 MathUtil::AddToTracedValue("skewport_rect", current_skewport_rect_, state);
954 MathUtil::AddToTracedValue("soon_rect", current_soon_border_rect_, state);
955 MathUtil::AddToTracedValue("eventually_rect", current_eventually_rect_,
956 state);
957 MathUtil::AddToTracedValue("tiling_size", tiling_size(), state);
960 size_t PictureLayerTiling::GPUMemoryUsageInBytes() const {
961 size_t amount = 0;
962 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
963 const Tile* tile = it->second;
964 amount += tile->GPUMemoryUsageInBytes();
966 return amount;
969 PictureLayerTiling::RectExpansionCache::RectExpansionCache()
970 : previous_target(0) {
973 namespace {
975 // This struct represents an event at which the expending rect intersects
976 // one of its boundaries. 4 intersection events will occur during expansion.
977 struct EdgeEvent {
978 enum { BOTTOM, TOP, LEFT, RIGHT } edge;
979 int* num_edges;
980 int distance;
983 // Compute the delta to expand from edges to cover target_area.
984 int ComputeExpansionDelta(int num_x_edges, int num_y_edges,
985 int width, int height,
986 int64 target_area) {
987 // Compute coefficients for the quadratic equation:
988 // a*x^2 + b*x + c = 0
989 int a = num_y_edges * num_x_edges;
990 int b = num_y_edges * width + num_x_edges * height;
991 int64 c = static_cast<int64>(width) * height - target_area;
993 // Compute the delta for our edges using the quadratic equation.
994 int delta =
995 (a == 0) ? -c / b : (-b + static_cast<int>(std::sqrt(
996 static_cast<int64>(b) * b - 4.0 * a * c))) /
997 (2 * a);
998 return std::max(0, delta);
1001 } // namespace
1003 gfx::Rect PictureLayerTiling::ExpandRectEquallyToAreaBoundedBy(
1004 const gfx::Rect& starting_rect,
1005 int64 target_area,
1006 const gfx::Rect& bounding_rect,
1007 RectExpansionCache* cache) {
1008 if (starting_rect.IsEmpty())
1009 return starting_rect;
1011 if (cache &&
1012 cache->previous_start == starting_rect &&
1013 cache->previous_bounds == bounding_rect &&
1014 cache->previous_target == target_area)
1015 return cache->previous_result;
1017 if (cache) {
1018 cache->previous_start = starting_rect;
1019 cache->previous_bounds = bounding_rect;
1020 cache->previous_target = target_area;
1023 DCHECK(!bounding_rect.IsEmpty());
1024 DCHECK_GT(target_area, 0);
1026 // Expand the starting rect to cover target_area, if it is smaller than it.
1027 int delta = ComputeExpansionDelta(
1028 2, 2, starting_rect.width(), starting_rect.height(), target_area);
1029 gfx::Rect expanded_starting_rect = starting_rect;
1030 if (delta > 0)
1031 expanded_starting_rect.Inset(-delta, -delta);
1033 gfx::Rect rect = IntersectRects(expanded_starting_rect, bounding_rect);
1034 if (rect.IsEmpty()) {
1035 // The starting_rect and bounding_rect are far away.
1036 if (cache)
1037 cache->previous_result = rect;
1038 return rect;
1040 if (delta >= 0 && rect == expanded_starting_rect) {
1041 // The starting rect already covers the entire bounding_rect and isn't too
1042 // large for the target_area.
1043 if (cache)
1044 cache->previous_result = rect;
1045 return rect;
1048 // Continue to expand/shrink rect to let it cover target_area.
1050 // These values will be updated by the loop and uses as the output.
1051 int origin_x = rect.x();
1052 int origin_y = rect.y();
1053 int width = rect.width();
1054 int height = rect.height();
1056 // In the beginning we will consider 2 edges in each dimension.
1057 int num_y_edges = 2;
1058 int num_x_edges = 2;
1060 // Create an event list.
1061 EdgeEvent events[] = {
1062 { EdgeEvent::BOTTOM, &num_y_edges, rect.y() - bounding_rect.y() },
1063 { EdgeEvent::TOP, &num_y_edges, bounding_rect.bottom() - rect.bottom() },
1064 { EdgeEvent::LEFT, &num_x_edges, rect.x() - bounding_rect.x() },
1065 { EdgeEvent::RIGHT, &num_x_edges, bounding_rect.right() - rect.right() }
1068 // Sort the events by distance (closest first).
1069 if (events[0].distance > events[1].distance) std::swap(events[0], events[1]);
1070 if (events[2].distance > events[3].distance) std::swap(events[2], events[3]);
1071 if (events[0].distance > events[2].distance) std::swap(events[0], events[2]);
1072 if (events[1].distance > events[3].distance) std::swap(events[1], events[3]);
1073 if (events[1].distance > events[2].distance) std::swap(events[1], events[2]);
1075 for (int event_index = 0; event_index < 4; event_index++) {
1076 const EdgeEvent& event = events[event_index];
1078 int delta = ComputeExpansionDelta(
1079 num_x_edges, num_y_edges, width, height, target_area);
1081 // Clamp delta to our event distance.
1082 if (delta > event.distance)
1083 delta = event.distance;
1085 // Adjust the edge count for this kind of edge.
1086 --*event.num_edges;
1088 // Apply the delta to the edges and edge events.
1089 for (int i = event_index; i < 4; i++) {
1090 switch (events[i].edge) {
1091 case EdgeEvent::BOTTOM:
1092 origin_y -= delta;
1093 height += delta;
1094 break;
1095 case EdgeEvent::TOP:
1096 height += delta;
1097 break;
1098 case EdgeEvent::LEFT:
1099 origin_x -= delta;
1100 width += delta;
1101 break;
1102 case EdgeEvent::RIGHT:
1103 width += delta;
1104 break;
1106 events[i].distance -= delta;
1109 // If our delta is less then our event distance, we're done.
1110 if (delta < event.distance)
1111 break;
1114 gfx::Rect result(origin_x, origin_y, width, height);
1115 if (cache)
1116 cache->previous_result = result;
1117 return result;
1120 } // namespace cc