cc: Adding DidFinishImplFrame to LTHI.
[chromium-blink-merge.git] / cc / resources / picture_layer_tiling.cc
blob21c1417e5b4fd891e7e16df8dd23fa87ed63fdda
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"
7 #include <algorithm>
8 #include <cmath>
9 #include <limits>
10 #include <set>
12 #include "base/logging.h"
13 #include "base/trace_event/trace_event.h"
14 #include "base/trace_event/trace_event_argument.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"
23 namespace cc {
24 namespace {
26 const float kSoonBorderDistanceViewportPercentage = 0.15f;
27 const float kMaxSoonBorderDistanceInScreenPixels = 312.f;
29 } // namespace
31 scoped_ptr<PictureLayerTiling> PictureLayerTiling::Create(
32 WhichTree tree,
33 float contents_scale,
34 scoped_refptr<RasterSource> raster_source,
35 PictureLayerTilingClient* client,
36 size_t max_tiles_for_interest_area,
37 float skewport_target_time_in_seconds,
38 int skewport_extrapolation_limit_in_content_pixels) {
39 return make_scoped_ptr(new PictureLayerTiling(
40 tree, contents_scale, raster_source, client, max_tiles_for_interest_area,
41 skewport_target_time_in_seconds,
42 skewport_extrapolation_limit_in_content_pixels));
45 PictureLayerTiling::PictureLayerTiling(
46 WhichTree tree,
47 float contents_scale,
48 scoped_refptr<RasterSource> raster_source,
49 PictureLayerTilingClient* client,
50 size_t max_tiles_for_interest_area,
51 float skewport_target_time_in_seconds,
52 int skewport_extrapolation_limit_in_content_pixels)
53 : max_tiles_for_interest_area_(max_tiles_for_interest_area),
54 skewport_target_time_in_seconds_(skewport_target_time_in_seconds),
55 skewport_extrapolation_limit_in_content_pixels_(
56 skewport_extrapolation_limit_in_content_pixels),
57 contents_scale_(contents_scale),
58 client_(client),
59 tree_(tree),
60 raster_source_(raster_source),
61 resolution_(NON_IDEAL_RESOLUTION),
62 tiling_data_(gfx::Size(), gfx::Size(), kBorderTexels),
63 can_require_tiles_for_activation_(false),
64 current_content_to_screen_scale_(0.f),
65 has_visible_rect_tiles_(false),
66 has_skewport_rect_tiles_(false),
67 has_soon_border_rect_tiles_(false),
68 has_eventually_rect_tiles_(false) {
69 DCHECK(!raster_source->IsSolidColor());
70 gfx::Size content_bounds = gfx::ToCeiledSize(
71 gfx::ScaleSize(raster_source_->GetSize(), contents_scale));
72 gfx::Size tile_size = client_->CalculateTileSize(content_bounds);
74 DCHECK(!gfx::ToFlooredSize(gfx::ScaleSize(raster_source_->GetSize(),
75 contents_scale)).IsEmpty())
76 << "Tiling created with scale too small as contents become empty."
77 << " Layer bounds: " << raster_source_->GetSize().ToString()
78 << " Contents scale: " << contents_scale;
80 tiling_data_.SetTilingSize(content_bounds);
81 tiling_data_.SetMaxTextureSize(tile_size);
84 PictureLayerTiling::~PictureLayerTiling() {
87 // static
88 float PictureLayerTiling::CalculateSoonBorderDistance(
89 const gfx::Rect& visible_rect_in_content_space,
90 float content_to_screen_scale) {
91 float max_dimension = std::max(visible_rect_in_content_space.width(),
92 visible_rect_in_content_space.height());
93 return std::min(
94 kMaxSoonBorderDistanceInScreenPixels / content_to_screen_scale,
95 max_dimension * kSoonBorderDistanceViewportPercentage);
98 Tile* PictureLayerTiling::CreateTile(int i, int j) {
99 TileMapKey key(i, j);
100 DCHECK(tiles_.find(key) == tiles_.end());
102 gfx::Rect paint_rect = tiling_data_.TileBoundsWithBorder(i, j);
103 gfx::Rect tile_rect = paint_rect;
104 tile_rect.set_size(tiling_data_.max_texture_size());
106 if (!raster_source_->CoversRect(tile_rect, contents_scale_))
107 return nullptr;
109 ScopedTilePtr tile = client_->CreateTile(contents_scale_, tile_rect);
110 Tile* raw_ptr = tile.get();
111 tile->set_tiling_index(i, j);
112 tiles_.add(key, tile.Pass());
113 return raw_ptr;
116 void PictureLayerTiling::CreateMissingTilesInLiveTilesRect() {
117 bool include_borders = false;
118 for (TilingData::Iterator iter(&tiling_data_, live_tiles_rect_,
119 include_borders);
120 iter; ++iter) {
121 TileMapKey key = iter.index();
122 TileMap::iterator find = tiles_.find(key);
123 if (find != tiles_.end())
124 continue;
126 if (ShouldCreateTileAt(key.first, key.second))
127 CreateTile(key.first, key.second);
129 VerifyLiveTilesRect(false);
132 void PictureLayerTiling::TakeTilesAndPropertiesFrom(
133 PictureLayerTiling* pending_twin,
134 const Region& layer_invalidation) {
135 TRACE_EVENT0("cc", "TakeTilesAndPropertiesFrom");
136 SetRasterSourceAndResize(pending_twin->raster_source_);
138 RemoveTilesInRegion(layer_invalidation, false /* recreate tiles */);
140 for (TileMap::value_type& tile_pair : tiles_)
141 tile_pair.second->set_raster_source(raster_source_.get());
143 resolution_ = pending_twin->resolution_;
144 bool create_missing_tiles = false;
145 if (live_tiles_rect_.IsEmpty()) {
146 live_tiles_rect_ = pending_twin->live_tiles_rect();
147 create_missing_tiles = true;
148 } else {
149 SetLiveTilesRect(pending_twin->live_tiles_rect());
152 if (tiles_.empty()) {
153 tiles_.swap(pending_twin->tiles_);
154 } else {
155 while (!pending_twin->tiles_.empty()) {
156 TileMapKey key = pending_twin->tiles_.begin()->first;
157 tiles_.set(key, pending_twin->tiles_.take_and_erase(key));
158 DCHECK(tiles_.get(key)->raster_source() == raster_source_.get());
161 DCHECK(pending_twin->tiles_.empty());
163 if (create_missing_tiles)
164 CreateMissingTilesInLiveTilesRect();
166 VerifyLiveTilesRect(false);
168 SetTilePriorityRects(pending_twin->current_content_to_screen_scale_,
169 pending_twin->current_visible_rect_,
170 pending_twin->current_skewport_rect_,
171 pending_twin->current_soon_border_rect_,
172 pending_twin->current_eventually_rect_,
173 pending_twin->current_occlusion_in_layer_space_);
176 void PictureLayerTiling::SetRasterSourceAndResize(
177 scoped_refptr<RasterSource> raster_source) {
178 DCHECK(!raster_source->IsSolidColor());
179 gfx::Size old_layer_bounds = raster_source_->GetSize();
180 raster_source_.swap(raster_source);
181 gfx::Size new_layer_bounds = raster_source_->GetSize();
182 gfx::Size content_bounds =
183 gfx::ToCeiledSize(gfx::ScaleSize(new_layer_bounds, contents_scale_));
184 gfx::Size tile_size = client_->CalculateTileSize(content_bounds);
186 if (tile_size != tiling_data_.max_texture_size()) {
187 tiling_data_.SetTilingSize(content_bounds);
188 tiling_data_.SetMaxTextureSize(tile_size);
189 // When the tile size changes, the TilingData positions no longer work
190 // as valid keys to the TileMap, so just drop all tiles and clear the live
191 // tiles rect.
192 Reset();
193 return;
196 if (old_layer_bounds == new_layer_bounds)
197 return;
199 // The SetLiveTilesRect() method would drop tiles outside the new bounds,
200 // but may do so incorrectly if resizing the tiling causes the number of
201 // tiles in the tiling_data_ to change.
202 gfx::Rect content_rect(content_bounds);
203 int before_left = tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.x());
204 int before_top = tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.y());
205 int before_right =
206 tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.right() - 1);
207 int before_bottom =
208 tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.bottom() - 1);
210 // The live_tiles_rect_ is clamped to stay within the tiling size as we
211 // change it.
212 live_tiles_rect_.Intersect(content_rect);
213 tiling_data_.SetTilingSize(content_bounds);
215 int after_right = -1;
216 int after_bottom = -1;
217 if (!live_tiles_rect_.IsEmpty()) {
218 after_right =
219 tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.right() - 1);
220 after_bottom =
221 tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.bottom() - 1);
224 // There is no recycled twin since this is run on the pending tiling
225 // during commit, and on the active tree during activate.
226 // Drop tiles outside the new layer bounds if the layer shrank.
227 for (int i = after_right + 1; i <= before_right; ++i) {
228 for (int j = before_top; j <= before_bottom; ++j)
229 RemoveTileAt(i, j);
231 for (int i = before_left; i <= after_right; ++i) {
232 for (int j = after_bottom + 1; j <= before_bottom; ++j)
233 RemoveTileAt(i, j);
236 if (after_right > before_right) {
237 DCHECK_EQ(after_right, before_right + 1);
238 for (int j = before_top; j <= after_bottom; ++j) {
239 if (ShouldCreateTileAt(after_right, j))
240 CreateTile(after_right, j);
243 if (after_bottom > before_bottom) {
244 DCHECK_EQ(after_bottom, before_bottom + 1);
245 for (int i = before_left; i <= before_right; ++i) {
246 if (ShouldCreateTileAt(i, after_bottom))
247 CreateTile(i, after_bottom);
252 void PictureLayerTiling::Invalidate(const Region& layer_invalidation) {
253 DCHECK_IMPLIES(tree_ == ACTIVE_TREE,
254 !client_->GetPendingOrActiveTwinTiling(this));
255 RemoveTilesInRegion(layer_invalidation, true /* recreate tiles */);
258 void PictureLayerTiling::RemoveTilesInRegion(const Region& layer_invalidation,
259 bool recreate_tiles) {
260 // We only invalidate the active tiling when it's orphaned: it has no pending
261 // twin, so it's slated for removal in the future.
262 if (live_tiles_rect_.IsEmpty())
263 return;
264 std::vector<TileMapKey> new_tile_keys;
265 gfx::Rect expanded_live_tiles_rect =
266 tiling_data_.ExpandRectIgnoringBordersToTileBounds(live_tiles_rect_);
267 for (Region::Iterator iter(layer_invalidation); iter.has_rect();
268 iter.next()) {
269 gfx::Rect layer_rect = iter.rect();
270 gfx::Rect content_rect =
271 gfx::ScaleToEnclosingRect(layer_rect, contents_scale_);
272 // Consider tiles inside the live tiles rect even if only their border
273 // pixels intersect the invalidation. But don't consider tiles outside
274 // the live tiles rect with the same conditions, as they won't exist.
275 int border_pixels = tiling_data_.border_texels();
276 content_rect.Inset(-border_pixels, -border_pixels);
277 // Avoid needless work by not bothering to invalidate where there aren't
278 // tiles.
279 content_rect.Intersect(expanded_live_tiles_rect);
280 if (content_rect.IsEmpty())
281 continue;
282 // Since the content_rect includes border pixels already, don't include
283 // borders when iterating to avoid double counting them.
284 bool include_borders = false;
285 for (
286 TilingData::Iterator iter(&tiling_data_, content_rect, include_borders);
287 iter; ++iter) {
288 if (RemoveTileAt(iter.index_x(), iter.index_y())) {
289 if (recreate_tiles)
290 new_tile_keys.push_back(iter.index());
295 for (const auto& key : new_tile_keys)
296 CreateTile(key.first, key.second);
299 void PictureLayerTiling::SetRasterSourceOnTiles() {
300 if (tree_ == PENDING_TREE)
301 return;
303 for (TileMap::value_type& tile_pair : tiles_)
304 tile_pair.second->set_raster_source(raster_source_.get());
307 bool PictureLayerTiling::ShouldCreateTileAt(int i, int j) const {
308 // Active tree should always create a tile. The reason for this is that active
309 // tree represents content that we draw on screen, which means that whenever
310 // we check whether a tile should exist somewhere, the answer is yes. This
311 // doesn't mean it will actually be created (if raster source doesn't cover
312 // the tile for instance). Pending tree, on the other hand, should only be
313 // creating tiles that are different from the current active tree, which is
314 // represented by the logic in the rest of the function.
315 if (tree_ == ACTIVE_TREE)
316 return true;
318 // If the pending tree has no active twin, then it needs to create all tiles.
319 const PictureLayerTiling* active_twin =
320 client_->GetPendingOrActiveTwinTiling(this);
321 if (!active_twin)
322 return true;
324 // Pending tree will override the entire active tree if indices don't match.
325 if (!TilingMatchesTileIndices(active_twin))
326 return true;
328 gfx::Rect paint_rect = tiling_data_.TileBoundsWithBorder(i, j);
329 gfx::Rect tile_rect = paint_rect;
330 tile_rect.set_size(tiling_data_.max_texture_size());
332 // If the active tree can't create a tile, because of its raster source, then
333 // the pending tree should create one.
334 if (!active_twin->raster_source()->CoversRect(tile_rect, contents_scale()))
335 return true;
337 const Region* layer_invalidation = client_->GetPendingInvalidation();
338 gfx::Rect layer_rect =
339 gfx::ScaleToEnclosingRect(tile_rect, 1.f / contents_scale());
341 // If this tile is invalidated, then the pending tree should create one.
342 if (layer_invalidation && layer_invalidation->Intersects(layer_rect))
343 return true;
345 // If the active tree doesn't have a tile here, but it's in the pending tree's
346 // visible rect, then the pending tree should create a tile. This can happen
347 // if the pending visible rect is outside of the active tree's live tiles
348 // rect. In those situations, we need to block activation until we're ready to
349 // display content, which will have to come from the pending tree.
350 if (!active_twin->TileAt(i, j) && current_visible_rect_.Intersects(tile_rect))
351 return true;
353 // In all other cases, the pending tree doesn't need to create a tile.
354 return false;
357 bool PictureLayerTiling::TilingMatchesTileIndices(
358 const PictureLayerTiling* twin) const {
359 return tiling_data_.max_texture_size() ==
360 twin->tiling_data_.max_texture_size();
363 PictureLayerTiling::CoverageIterator::CoverageIterator()
364 : tiling_(NULL),
365 current_tile_(NULL),
366 tile_i_(0),
367 tile_j_(0),
368 left_(0),
369 top_(0),
370 right_(-1),
371 bottom_(-1) {
374 PictureLayerTiling::CoverageIterator::CoverageIterator(
375 const PictureLayerTiling* tiling,
376 float dest_scale,
377 const gfx::Rect& dest_rect)
378 : tiling_(tiling),
379 dest_rect_(dest_rect),
380 dest_to_content_scale_(0),
381 current_tile_(NULL),
382 tile_i_(0),
383 tile_j_(0),
384 left_(0),
385 top_(0),
386 right_(-1),
387 bottom_(-1) {
388 DCHECK(tiling_);
389 if (dest_rect_.IsEmpty())
390 return;
392 dest_to_content_scale_ = tiling_->contents_scale_ / dest_scale;
394 gfx::Rect content_rect =
395 gfx::ScaleToEnclosingRect(dest_rect_,
396 dest_to_content_scale_,
397 dest_to_content_scale_);
398 // IndexFromSrcCoord clamps to valid tile ranges, so it's necessary to
399 // check for non-intersection first.
400 content_rect.Intersect(gfx::Rect(tiling_->tiling_size()));
401 if (content_rect.IsEmpty())
402 return;
404 left_ = tiling_->tiling_data_.TileXIndexFromSrcCoord(content_rect.x());
405 top_ = tiling_->tiling_data_.TileYIndexFromSrcCoord(content_rect.y());
406 right_ = tiling_->tiling_data_.TileXIndexFromSrcCoord(
407 content_rect.right() - 1);
408 bottom_ = tiling_->tiling_data_.TileYIndexFromSrcCoord(
409 content_rect.bottom() - 1);
411 tile_i_ = left_ - 1;
412 tile_j_ = top_;
413 ++(*this);
416 PictureLayerTiling::CoverageIterator::~CoverageIterator() {
419 PictureLayerTiling::CoverageIterator&
420 PictureLayerTiling::CoverageIterator::operator++() {
421 if (tile_j_ > bottom_)
422 return *this;
424 bool first_time = tile_i_ < left_;
425 bool new_row = false;
426 tile_i_++;
427 if (tile_i_ > right_) {
428 tile_i_ = left_;
429 tile_j_++;
430 new_row = true;
431 if (tile_j_ > bottom_) {
432 current_tile_ = NULL;
433 return *this;
437 current_tile_ = tiling_->TileAt(tile_i_, tile_j_);
439 // Calculate the current geometry rect. Due to floating point rounding
440 // and ToEnclosingRect, tiles might overlap in destination space on the
441 // edges.
442 gfx::Rect last_geometry_rect = current_geometry_rect_;
444 gfx::Rect content_rect = tiling_->tiling_data_.TileBounds(tile_i_, tile_j_);
446 current_geometry_rect_ =
447 gfx::ScaleToEnclosingRect(content_rect,
448 1 / dest_to_content_scale_,
449 1 / dest_to_content_scale_);
451 current_geometry_rect_.Intersect(dest_rect_);
453 if (first_time)
454 return *this;
456 // Iteration happens left->right, top->bottom. Running off the bottom-right
457 // edge is handled by the intersection above with dest_rect_. Here we make
458 // sure that the new current geometry rect doesn't overlap with the last.
459 int min_left;
460 int min_top;
461 if (new_row) {
462 min_left = dest_rect_.x();
463 min_top = last_geometry_rect.bottom();
464 } else {
465 min_left = last_geometry_rect.right();
466 min_top = last_geometry_rect.y();
469 int inset_left = std::max(0, min_left - current_geometry_rect_.x());
470 int inset_top = std::max(0, min_top - current_geometry_rect_.y());
471 current_geometry_rect_.Inset(inset_left, inset_top, 0, 0);
473 if (!new_row) {
474 DCHECK_EQ(last_geometry_rect.right(), current_geometry_rect_.x());
475 DCHECK_EQ(last_geometry_rect.bottom(), current_geometry_rect_.bottom());
476 DCHECK_EQ(last_geometry_rect.y(), current_geometry_rect_.y());
479 return *this;
482 gfx::Rect PictureLayerTiling::CoverageIterator::geometry_rect() const {
483 return current_geometry_rect_;
486 gfx::RectF PictureLayerTiling::CoverageIterator::texture_rect() const {
487 gfx::PointF tex_origin =
488 tiling_->tiling_data_.TileBoundsWithBorder(tile_i_, tile_j_).origin();
490 // Convert from dest space => content space => texture space.
491 gfx::RectF texture_rect(current_geometry_rect_);
492 texture_rect.Scale(dest_to_content_scale_,
493 dest_to_content_scale_);
494 texture_rect.Intersect(gfx::Rect(tiling_->tiling_size()));
495 if (texture_rect.IsEmpty())
496 return texture_rect;
497 texture_rect.Offset(-tex_origin.OffsetFromOrigin());
499 return texture_rect;
502 bool PictureLayerTiling::RemoveTileAt(int i, int j) {
503 TileMap::iterator found = tiles_.find(TileMapKey(i, j));
504 if (found == tiles_.end())
505 return false;
506 tiles_.erase(found);
507 return true;
510 void PictureLayerTiling::Reset() {
511 live_tiles_rect_ = gfx::Rect();
512 tiles_.clear();
515 gfx::Rect PictureLayerTiling::ComputeSkewport(
516 double current_frame_time_in_seconds,
517 const gfx::Rect& visible_rect_in_content_space) const {
518 gfx::Rect skewport = visible_rect_in_content_space;
519 if (skewport.IsEmpty())
520 return skewport;
522 if (visible_rect_history_[1].frame_time_in_seconds == 0.0)
523 return skewport;
525 double time_delta = current_frame_time_in_seconds -
526 visible_rect_history_[1].frame_time_in_seconds;
527 if (time_delta == 0.0)
528 return skewport;
530 double extrapolation_multiplier =
531 skewport_target_time_in_seconds_ / time_delta;
533 int old_x = visible_rect_history_[1].visible_rect_in_content_space.x();
534 int old_y = visible_rect_history_[1].visible_rect_in_content_space.y();
535 int old_right =
536 visible_rect_history_[1].visible_rect_in_content_space.right();
537 int old_bottom =
538 visible_rect_history_[1].visible_rect_in_content_space.bottom();
540 int new_x = visible_rect_in_content_space.x();
541 int new_y = visible_rect_in_content_space.y();
542 int new_right = visible_rect_in_content_space.right();
543 int new_bottom = visible_rect_in_content_space.bottom();
545 // Compute the maximum skewport based on
546 // |skewport_extrapolation_limit_in_content_pixels_|.
547 gfx::Rect max_skewport = skewport;
548 max_skewport.Inset(-skewport_extrapolation_limit_in_content_pixels_,
549 -skewport_extrapolation_limit_in_content_pixels_);
551 // Inset the skewport by the needed adjustment.
552 skewport.Inset(extrapolation_multiplier * (new_x - old_x),
553 extrapolation_multiplier * (new_y - old_y),
554 extrapolation_multiplier * (old_right - new_right),
555 extrapolation_multiplier * (old_bottom - new_bottom));
557 // Ensure that visible rect is contained in the skewport.
558 skewport.Union(visible_rect_in_content_space);
560 // Clip the skewport to |max_skewport|. This needs to happen after the
561 // union in case intersecting would have left the empty rect.
562 skewport.Intersect(max_skewport);
564 return skewport;
567 bool PictureLayerTiling::ComputeTilePriorityRects(
568 const gfx::Rect& viewport_in_layer_space,
569 float ideal_contents_scale,
570 double current_frame_time_in_seconds,
571 const Occlusion& occlusion_in_layer_space) {
572 if (!NeedsUpdateForFrameAtTimeAndViewport(current_frame_time_in_seconds,
573 viewport_in_layer_space)) {
574 // This should never be zero for the purposes of has_ever_been_updated().
575 DCHECK_NE(current_frame_time_in_seconds, 0.0);
576 return false;
579 gfx::Rect visible_rect_in_content_space =
580 gfx::ScaleToEnclosingRect(viewport_in_layer_space, contents_scale_);
582 if (tiling_size().IsEmpty()) {
583 UpdateVisibleRectHistory(current_frame_time_in_seconds,
584 visible_rect_in_content_space);
585 last_viewport_in_layer_space_ = viewport_in_layer_space;
586 return false;
589 // Calculate the skewport.
590 gfx::Rect skewport = ComputeSkewport(current_frame_time_in_seconds,
591 visible_rect_in_content_space);
592 DCHECK(skewport.Contains(visible_rect_in_content_space));
594 // Calculate the eventually/live tiles rect.
595 gfx::Size tile_size = tiling_data_.max_texture_size();
596 int64 eventually_rect_area =
597 max_tiles_for_interest_area_ * tile_size.width() * tile_size.height();
599 gfx::Rect eventually_rect =
600 ExpandRectEquallyToAreaBoundedBy(visible_rect_in_content_space,
601 eventually_rect_area,
602 gfx::Rect(tiling_size()),
603 &expansion_cache_);
605 DCHECK(eventually_rect.IsEmpty() ||
606 gfx::Rect(tiling_size()).Contains(eventually_rect))
607 << "tiling_size: " << tiling_size().ToString()
608 << " eventually_rect: " << eventually_rect.ToString();
610 // Calculate the soon border rect.
611 float content_to_screen_scale = ideal_contents_scale / contents_scale_;
612 gfx::Rect soon_border_rect = visible_rect_in_content_space;
613 float border = CalculateSoonBorderDistance(visible_rect_in_content_space,
614 content_to_screen_scale);
615 soon_border_rect.Inset(-border, -border, -border, -border);
617 UpdateVisibleRectHistory(current_frame_time_in_seconds,
618 visible_rect_in_content_space);
619 last_viewport_in_layer_space_ = viewport_in_layer_space;
621 SetTilePriorityRects(content_to_screen_scale, visible_rect_in_content_space,
622 skewport, soon_border_rect, eventually_rect,
623 occlusion_in_layer_space);
624 SetLiveTilesRect(eventually_rect);
625 return true;
628 void PictureLayerTiling::SetTilePriorityRects(
629 float content_to_screen_scale,
630 const gfx::Rect& visible_rect_in_content_space,
631 const gfx::Rect& skewport,
632 const gfx::Rect& soon_border_rect,
633 const gfx::Rect& eventually_rect,
634 const Occlusion& occlusion_in_layer_space) {
635 current_visible_rect_ = visible_rect_in_content_space;
636 current_skewport_rect_ = skewport;
637 current_soon_border_rect_ = soon_border_rect;
638 current_eventually_rect_ = eventually_rect;
639 current_occlusion_in_layer_space_ = occlusion_in_layer_space;
640 current_content_to_screen_scale_ = content_to_screen_scale;
642 gfx::Rect tiling_rect(tiling_size());
643 has_visible_rect_tiles_ = tiling_rect.Intersects(current_visible_rect_);
644 has_skewport_rect_tiles_ = tiling_rect.Intersects(current_skewport_rect_);
645 has_soon_border_rect_tiles_ =
646 tiling_rect.Intersects(current_soon_border_rect_);
647 has_eventually_rect_tiles_ = tiling_rect.Intersects(current_eventually_rect_);
650 void PictureLayerTiling::SetLiveTilesRect(
651 const gfx::Rect& new_live_tiles_rect) {
652 DCHECK(new_live_tiles_rect.IsEmpty() ||
653 gfx::Rect(tiling_size()).Contains(new_live_tiles_rect))
654 << "tiling_size: " << tiling_size().ToString()
655 << " new_live_tiles_rect: " << new_live_tiles_rect.ToString();
656 if (live_tiles_rect_ == new_live_tiles_rect)
657 return;
659 // Iterate to delete all tiles outside of our new live_tiles rect.
660 for (TilingData::DifferenceIterator iter(&tiling_data_, live_tiles_rect_,
661 new_live_tiles_rect);
662 iter; ++iter) {
663 RemoveTileAt(iter.index_x(), iter.index_y());
666 // Iterate to allocate new tiles for all regions with newly exposed area.
667 for (TilingData::DifferenceIterator iter(&tiling_data_, new_live_tiles_rect,
668 live_tiles_rect_);
669 iter; ++iter) {
670 TileMapKey key(iter.index());
671 if (ShouldCreateTileAt(key.first, key.second))
672 CreateTile(key.first, key.second);
675 live_tiles_rect_ = new_live_tiles_rect;
676 VerifyLiveTilesRect(false);
679 void PictureLayerTiling::VerifyLiveTilesRect(bool is_on_recycle_tree) const {
680 #if DCHECK_IS_ON()
681 for (auto it = tiles_.begin(); it != tiles_.end(); ++it) {
682 if (!it->second)
683 continue;
684 DCHECK(it->first.first < tiling_data_.num_tiles_x())
685 << this << " " << it->first.first << "," << it->first.second
686 << " num_tiles_x " << tiling_data_.num_tiles_x() << " live_tiles_rect "
687 << live_tiles_rect_.ToString();
688 DCHECK(it->first.second < tiling_data_.num_tiles_y())
689 << this << " " << it->first.first << "," << it->first.second
690 << " num_tiles_y " << tiling_data_.num_tiles_y() << " live_tiles_rect "
691 << live_tiles_rect_.ToString();
692 DCHECK(tiling_data_.TileBounds(it->first.first, it->first.second)
693 .Intersects(live_tiles_rect_))
694 << this << " " << it->first.first << "," << it->first.second
695 << " tile bounds "
696 << tiling_data_.TileBounds(it->first.first, it->first.second).ToString()
697 << " live_tiles_rect " << live_tiles_rect_.ToString();
699 #endif
702 bool PictureLayerTiling::IsTileOccluded(const Tile* tile) const {
703 // If this tile is not occluded on this tree, then it is not occluded.
704 if (!IsTileOccludedOnCurrentTree(tile))
705 return false;
707 // Otherwise, if this is the pending tree, we're done and the tile is
708 // occluded.
709 if (tree_ == PENDING_TREE)
710 return true;
712 // On the active tree however, we need to check if this tile will be
713 // unoccluded upon activation, in which case it has to be considered
714 // unoccluded.
715 const PictureLayerTiling* pending_twin =
716 client_->GetPendingOrActiveTwinTiling(this);
717 if (pending_twin) {
718 // If there's a pending tile in the same position. Or if the pending twin
719 // would have to be creating all tiles, then we don't need to worry about
720 // occlusion on the twin.
721 if (!TilingMatchesTileIndices(pending_twin) ||
722 pending_twin->TileAt(tile->tiling_i_index(), tile->tiling_j_index())) {
723 return true;
725 return pending_twin->IsTileOccludedOnCurrentTree(tile);
727 return true;
730 bool PictureLayerTiling::IsTileOccludedOnCurrentTree(const Tile* tile) const {
731 if (!current_occlusion_in_layer_space_.HasOcclusion())
732 return false;
733 gfx::Rect tile_query_rect =
734 gfx::IntersectRects(tile->content_rect(), current_visible_rect_);
735 // Explicitly check if the tile is outside the viewport. If so, we need to
736 // return false, since occlusion for this tile is unknown.
737 if (tile_query_rect.IsEmpty())
738 return false;
740 if (contents_scale_ != 1.f) {
741 tile_query_rect =
742 gfx::ScaleToEnclosingRect(tile_query_rect, 1.f / contents_scale_);
744 return current_occlusion_in_layer_space_.IsOccluded(tile_query_rect);
747 bool PictureLayerTiling::IsTileRequiredForActivation(const Tile* tile) const {
748 if (tree_ == PENDING_TREE) {
749 if (!can_require_tiles_for_activation_)
750 return false;
752 if (resolution_ != HIGH_RESOLUTION)
753 return false;
755 if (IsTileOccluded(tile))
756 return false;
758 bool tile_is_visible =
759 tile->content_rect().Intersects(current_visible_rect_);
760 if (!tile_is_visible)
761 return false;
763 if (client_->RequiresHighResToDraw())
764 return true;
766 const PictureLayerTiling* active_twin =
767 client_->GetPendingOrActiveTwinTiling(this);
768 if (!active_twin || !TilingMatchesTileIndices(active_twin))
769 return true;
771 if (active_twin->raster_source()->GetSize() != raster_source()->GetSize())
772 return true;
774 if (active_twin->current_visible_rect_ != current_visible_rect_)
775 return true;
777 Tile* twin_tile =
778 active_twin->TileAt(tile->tiling_i_index(), tile->tiling_j_index());
779 if (!twin_tile)
780 return false;
781 return true;
784 DCHECK_EQ(tree_, ACTIVE_TREE);
785 const PictureLayerTiling* pending_twin =
786 client_->GetPendingOrActiveTwinTiling(this);
787 // If we don't have a pending tree, or the pending tree will overwrite the
788 // given tile, then it is not required for activation.
789 if (!pending_twin || !TilingMatchesTileIndices(pending_twin) ||
790 pending_twin->TileAt(tile->tiling_i_index(), tile->tiling_j_index())) {
791 return false;
793 // Otherwise, ask the pending twin if this tile is required for activation.
794 return pending_twin->IsTileRequiredForActivation(tile);
797 bool PictureLayerTiling::IsTileRequiredForDraw(const Tile* tile) const {
798 if (tree_ == PENDING_TREE)
799 return false;
801 if (resolution_ != HIGH_RESOLUTION)
802 return false;
804 bool tile_is_visible = current_visible_rect_.Intersects(tile->content_rect());
805 if (!tile_is_visible)
806 return false;
808 if (IsTileOccludedOnCurrentTree(tile))
809 return false;
810 return true;
813 void PictureLayerTiling::UpdateTilePriority(Tile* tile) const {
814 tile->set_priority(ComputePriorityForTile(tile));
815 tile->set_is_occluded(IsTileOccluded(tile));
816 tile->set_required_for_activation(IsTileRequiredForActivation(tile));
817 tile->set_required_for_draw(IsTileRequiredForDraw(tile));
820 void PictureLayerTiling::VerifyAllTilesHaveCurrentRasterSource() const {
821 #if DCHECK_IS_ON()
822 for (const auto& tile_pair : tiles_)
823 DCHECK_EQ(raster_source_.get(), tile_pair.second->raster_source());
824 #endif
827 TilePriority PictureLayerTiling::ComputePriorityForTile(
828 const Tile* tile) const {
829 // TODO(vmpstr): See if this can be moved to iterators.
830 TilePriority::PriorityBin max_tile_priority_bin =
831 client_->GetMaxTilePriorityBin();
833 DCHECK_EQ(TileAt(tile->tiling_i_index(), tile->tiling_j_index()), tile);
834 gfx::Rect tile_bounds =
835 tiling_data_.TileBounds(tile->tiling_i_index(), tile->tiling_j_index());
837 if (max_tile_priority_bin <= TilePriority::NOW &&
838 current_visible_rect_.Intersects(tile_bounds)) {
839 return TilePriority(resolution_, TilePriority::NOW, 0);
842 if (max_tile_priority_bin <= TilePriority::SOON &&
843 pending_visible_rect().Intersects(tile_bounds)) {
844 return TilePriority(resolution_, TilePriority::SOON, 0);
847 DCHECK_GT(current_content_to_screen_scale_, 0.f);
848 float distance_to_visible =
849 current_visible_rect_.ManhattanInternalDistance(tile_bounds) *
850 current_content_to_screen_scale_;
852 if (max_tile_priority_bin <= TilePriority::SOON &&
853 (current_soon_border_rect_.Intersects(tile_bounds) ||
854 current_skewport_rect_.Intersects(tile_bounds))) {
855 return TilePriority(resolution_, TilePriority::SOON, distance_to_visible);
858 return TilePriority(resolution_, TilePriority::EVENTUALLY,
859 distance_to_visible);
862 void PictureLayerTiling::GetAllTilesAndPrioritiesForTracing(
863 std::map<const Tile*, TilePriority>* tile_map) const {
864 for (const auto& tile_pair : tiles_) {
865 const Tile* tile = tile_pair.second;
866 const TilePriority& priority = ComputePriorityForTile(tile);
867 // Store combined priority.
868 (*tile_map)[tile] = priority;
872 void PictureLayerTiling::AsValueInto(
873 base::trace_event::TracedValue* state) const {
874 state->SetInteger("num_tiles", tiles_.size());
875 state->SetDouble("content_scale", contents_scale_);
876 MathUtil::AddToTracedValue("visible_rect", current_visible_rect_, state);
877 MathUtil::AddToTracedValue("skewport_rect", current_skewport_rect_, state);
878 MathUtil::AddToTracedValue("soon_rect", current_soon_border_rect_, state);
879 MathUtil::AddToTracedValue("eventually_rect", current_eventually_rect_,
880 state);
881 MathUtil::AddToTracedValue("tiling_size", tiling_size(), state);
884 size_t PictureLayerTiling::GPUMemoryUsageInBytes() const {
885 size_t amount = 0;
886 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
887 const Tile* tile = it->second;
888 amount += tile->GPUMemoryUsageInBytes();
890 return amount;
893 PictureLayerTiling::RectExpansionCache::RectExpansionCache()
894 : previous_target(0) {
897 namespace {
899 // This struct represents an event at which the expending rect intersects
900 // one of its boundaries. 4 intersection events will occur during expansion.
901 struct EdgeEvent {
902 enum { BOTTOM, TOP, LEFT, RIGHT } edge;
903 int* num_edges;
904 int distance;
907 // Compute the delta to expand from edges to cover target_area.
908 int ComputeExpansionDelta(int num_x_edges, int num_y_edges,
909 int width, int height,
910 int64 target_area) {
911 // Compute coefficients for the quadratic equation:
912 // a*x^2 + b*x + c = 0
913 int a = num_y_edges * num_x_edges;
914 int b = num_y_edges * width + num_x_edges * height;
915 int64 c = static_cast<int64>(width) * height - target_area;
917 // Compute the delta for our edges using the quadratic equation.
918 int delta =
919 (a == 0) ? -c / b : (-b + static_cast<int>(std::sqrt(
920 static_cast<int64>(b) * b - 4.0 * a * c))) /
921 (2 * a);
922 return std::max(0, delta);
925 } // namespace
927 gfx::Rect PictureLayerTiling::ExpandRectEquallyToAreaBoundedBy(
928 const gfx::Rect& starting_rect,
929 int64 target_area,
930 const gfx::Rect& bounding_rect,
931 RectExpansionCache* cache) {
932 if (starting_rect.IsEmpty())
933 return starting_rect;
935 if (cache &&
936 cache->previous_start == starting_rect &&
937 cache->previous_bounds == bounding_rect &&
938 cache->previous_target == target_area)
939 return cache->previous_result;
941 if (cache) {
942 cache->previous_start = starting_rect;
943 cache->previous_bounds = bounding_rect;
944 cache->previous_target = target_area;
947 DCHECK(!bounding_rect.IsEmpty());
948 DCHECK_GT(target_area, 0);
950 // Expand the starting rect to cover target_area, if it is smaller than it.
951 int delta = ComputeExpansionDelta(
952 2, 2, starting_rect.width(), starting_rect.height(), target_area);
953 gfx::Rect expanded_starting_rect = starting_rect;
954 if (delta > 0)
955 expanded_starting_rect.Inset(-delta, -delta);
957 gfx::Rect rect = IntersectRects(expanded_starting_rect, bounding_rect);
958 if (rect.IsEmpty()) {
959 // The starting_rect and bounding_rect are far away.
960 if (cache)
961 cache->previous_result = rect;
962 return rect;
964 if (delta >= 0 && rect == expanded_starting_rect) {
965 // The starting rect already covers the entire bounding_rect and isn't too
966 // large for the target_area.
967 if (cache)
968 cache->previous_result = rect;
969 return rect;
972 // Continue to expand/shrink rect to let it cover target_area.
974 // These values will be updated by the loop and uses as the output.
975 int origin_x = rect.x();
976 int origin_y = rect.y();
977 int width = rect.width();
978 int height = rect.height();
980 // In the beginning we will consider 2 edges in each dimension.
981 int num_y_edges = 2;
982 int num_x_edges = 2;
984 // Create an event list.
985 EdgeEvent events[] = {
986 { EdgeEvent::BOTTOM, &num_y_edges, rect.y() - bounding_rect.y() },
987 { EdgeEvent::TOP, &num_y_edges, bounding_rect.bottom() - rect.bottom() },
988 { EdgeEvent::LEFT, &num_x_edges, rect.x() - bounding_rect.x() },
989 { EdgeEvent::RIGHT, &num_x_edges, bounding_rect.right() - rect.right() }
992 // Sort the events by distance (closest first).
993 if (events[0].distance > events[1].distance) std::swap(events[0], events[1]);
994 if (events[2].distance > events[3].distance) std::swap(events[2], events[3]);
995 if (events[0].distance > events[2].distance) std::swap(events[0], events[2]);
996 if (events[1].distance > events[3].distance) std::swap(events[1], events[3]);
997 if (events[1].distance > events[2].distance) std::swap(events[1], events[2]);
999 for (int event_index = 0; event_index < 4; event_index++) {
1000 const EdgeEvent& event = events[event_index];
1002 int delta = ComputeExpansionDelta(
1003 num_x_edges, num_y_edges, width, height, target_area);
1005 // Clamp delta to our event distance.
1006 if (delta > event.distance)
1007 delta = event.distance;
1009 // Adjust the edge count for this kind of edge.
1010 --*event.num_edges;
1012 // Apply the delta to the edges and edge events.
1013 for (int i = event_index; i < 4; i++) {
1014 switch (events[i].edge) {
1015 case EdgeEvent::BOTTOM:
1016 origin_y -= delta;
1017 height += delta;
1018 break;
1019 case EdgeEvent::TOP:
1020 height += delta;
1021 break;
1022 case EdgeEvent::LEFT:
1023 origin_x -= delta;
1024 width += delta;
1025 break;
1026 case EdgeEvent::RIGHT:
1027 width += delta;
1028 break;
1030 events[i].distance -= delta;
1033 // If our delta is less then our event distance, we're done.
1034 if (delta < event.distance)
1035 break;
1038 gfx::Rect result(origin_x, origin_y, width, height);
1039 if (cache)
1040 cache->previous_result = result;
1041 return result;
1044 } // namespace cc