picture_layer_impl.cc 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117
  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.
  4. #include "cc/layers/picture_layer_impl.h"
  5. #include <stddef.h>
  6. #include <stdint.h>
  7. #include <algorithm>
  8. #include <cmath>
  9. #include <limits>
  10. #include <memory>
  11. #include <set>
  12. #include <utility>
  13. #include "base/containers/contains.h"
  14. #include "base/cxx17_backports.h"
  15. #include "base/metrics/histogram_macros.h"
  16. #include "base/no_destructor.h"
  17. #include "base/system/sys_info.h"
  18. #include "base/time/time.h"
  19. #include "base/trace_event/traced_value.h"
  20. #include "build/build_config.h"
  21. #include "cc/base/math_util.h"
  22. #include "cc/benchmarks/micro_benchmark_impl.h"
  23. #include "cc/debug/debug_colors.h"
  24. #include "cc/layers/append_quads_data.h"
  25. #include "cc/layers/solid_color_layer_impl.h"
  26. #include "cc/paint/display_item_list.h"
  27. #include "cc/tiles/tile_manager.h"
  28. #include "cc/tiles/tiling_set_raster_queue_all.h"
  29. #include "cc/trees/effect_node.h"
  30. #include "cc/trees/layer_tree_impl.h"
  31. #include "cc/trees/occlusion.h"
  32. #include "cc/trees/transform_node.h"
  33. #include "components/viz/common/frame_sinks/begin_frame_args.h"
  34. #include "components/viz/common/quads/debug_border_draw_quad.h"
  35. #include "components/viz/common/quads/picture_draw_quad.h"
  36. #include "components/viz/common/quads/solid_color_draw_quad.h"
  37. #include "components/viz/common/quads/tile_draw_quad.h"
  38. #include "components/viz/common/traced_value.h"
  39. #include "ui/gfx/geometry/quad_f.h"
  40. #include "ui/gfx/geometry/rect_conversions.h"
  41. #include "ui/gfx/geometry/size_conversions.h"
  42. namespace cc {
  43. namespace {
  44. // This must be > 1 as we multiply or divide by this to find a new raster
  45. // scale during pinch.
  46. const float kMaxScaleRatioDuringPinch = 2.0f;
  47. // When creating a new tiling during pinch, snap to an existing
  48. // tiling's scale if the desired scale is within this ratio.
  49. const float kSnapToExistingTilingRatio = 1.2f;
  50. // Large contents scale can cause overflow issues. Cap the ideal contents scale
  51. // by this constant, since scales larger than this are usually not correct or
  52. // their scale doesn't matter as long as it's large. Content scales usually
  53. // closely match the default device-scale factor (so it's usually <= 5). See
  54. // Renderer4.IdealContentsScale UMA (deprecated) for distribution of content
  55. // scales.
  56. const float kMaxIdealContentsScale = 10000.f;
  57. // We try to avoid raster scale adjustment for will-change:transform for
  58. // performance, unless the scale is too small compared to the ideal scale and
  59. // the native scale.
  60. const float kMinScaleRatioForWillChangeTransform = 0.25f;
  61. // Used to avoid raster scale adjustment during a transform animation by
  62. // using the maximum animation scale, but sometimes the maximum animation scale
  63. // can't be accurately calculated (e.g. with nested scale transforms). We'll
  64. // adjust raster scale if it is not affected by invalid scale and is smaller
  65. // than the ideal scale divided by this ratio. The situation is rare.
  66. // See PropertyTrees::MaximumAnimationToScreenScale() and
  67. // AnimationAffectedByInvalidScale().
  68. const float kRatioToAdjustRasterScaleForTransformAnimation = 1.5f;
  69. // Intersect rects which may have right() and bottom() that overflow integer
  70. // boundaries. This code is similar to gfx::Rect::Intersect with the exception
  71. // that the types are promoted to int64_t when there is a chance of overflow.
  72. gfx::Rect SafeIntersectRects(const gfx::Rect& one, const gfx::Rect& two) {
  73. if (one.IsEmpty() || two.IsEmpty())
  74. return gfx::Rect();
  75. int rx = std::max(one.x(), two.x());
  76. int ry = std::max(one.y(), two.y());
  77. int64_t rr = std::min(static_cast<int64_t>(one.x()) + one.width(),
  78. static_cast<int64_t>(two.x()) + two.width());
  79. int64_t rb = std::min(static_cast<int64_t>(one.y()) + one.height(),
  80. static_cast<int64_t>(two.y()) + two.height());
  81. if (rx > rr || ry > rb)
  82. return gfx::Rect();
  83. return gfx::Rect(rx, ry, static_cast<int>(rr - rx),
  84. static_cast<int>(rb - ry));
  85. }
  86. } // namespace
  87. PictureLayerImpl::PictureLayerImpl(LayerTreeImpl* tree_impl, int id)
  88. : LayerImpl(tree_impl, id, /*will_always_push_properties=*/true),
  89. is_backdrop_filter_mask_(false),
  90. was_screen_space_transform_animating_(false),
  91. only_used_low_res_last_append_quads_(false),
  92. nearest_neighbor_(false),
  93. raster_source_size_changed_(false),
  94. directly_composited_image_default_raster_scale_changed_(false) {
  95. layer_tree_impl()->RegisterPictureLayerImpl(this);
  96. }
  97. PictureLayerImpl::~PictureLayerImpl() {
  98. if (twin_layer_)
  99. twin_layer_->twin_layer_ = nullptr;
  100. // We only track PaintWorklet-containing PictureLayerImpls on the pending
  101. // tree. However this deletion may happen outside the commit flow when we are
  102. // on the recycle tree instead, so just check !IsActiveTree().
  103. if (!paint_worklet_records_.empty() && !layer_tree_impl()->IsActiveTree())
  104. layer_tree_impl()->NotifyLayerHasPaintWorkletsChanged(this, false);
  105. // Similarly, AnimatedPaintWorkletTracker is only valid on the pending tree.
  106. if (!layer_tree_impl()->IsActiveTree()) {
  107. layer_tree_impl()
  108. ->paint_worklet_tracker()
  109. .UpdatePaintWorkletInputProperties({}, this);
  110. }
  111. layer_tree_impl()->UnregisterPictureLayerImpl(this);
  112. // Unregister for all images on the current raster source.
  113. UnregisterAnimatedImages();
  114. }
  115. const char* PictureLayerImpl::LayerTypeAsString() const {
  116. return "cc::PictureLayerImpl";
  117. }
  118. std::unique_ptr<LayerImpl> PictureLayerImpl::CreateLayerImpl(
  119. LayerTreeImpl* tree_impl) const {
  120. return PictureLayerImpl::Create(tree_impl, id());
  121. }
  122. void PictureLayerImpl::PushPropertiesTo(LayerImpl* base_layer) {
  123. PictureLayerImpl* layer_impl = static_cast<PictureLayerImpl*>(base_layer);
  124. LayerImpl::PushPropertiesTo(base_layer);
  125. // Twin relationships should never change once established.
  126. DCHECK(!twin_layer_ || twin_layer_ == layer_impl);
  127. DCHECK(!twin_layer_ || layer_impl->twin_layer_ == this);
  128. // The twin relationship does not need to exist before the first
  129. // PushPropertiesTo from pending to active layer since before that the active
  130. // layer can not have a pile or tilings, it has only been created and inserted
  131. // into the tree at that point.
  132. twin_layer_ = layer_impl;
  133. layer_impl->twin_layer_ = this;
  134. layer_impl->SetNearestNeighbor(nearest_neighbor_);
  135. layer_impl->SetDirectlyCompositedImageDefaultRasterScale(
  136. directly_composited_image_default_raster_scale_);
  137. layer_impl->SetIsBackdropFilterMask(is_backdrop_filter_mask_);
  138. // Solid color layers have no tilings.
  139. DCHECK(!raster_source_->IsSolidColor() || tilings_->num_tilings() == 0);
  140. // The pending tree should only have a high res (and possibly low res) tiling.
  141. DCHECK_LE(tilings_->num_tilings(),
  142. layer_tree_impl()->create_low_res_tiling() ? 2u : 1u);
  143. layer_impl->set_gpu_raster_max_texture_size(gpu_raster_max_texture_size_);
  144. layer_impl->UpdateRasterSource(raster_source_, &invalidation_, tilings_.get(),
  145. &paint_worklet_records_);
  146. DCHECK(invalidation_.IsEmpty());
  147. // After syncing a solid color layer, the active layer has no tilings.
  148. DCHECK(!raster_source_->IsSolidColor() ||
  149. layer_impl->tilings_->num_tilings() == 0);
  150. layer_impl->raster_page_scale_ = raster_page_scale_;
  151. layer_impl->raster_device_scale_ = raster_device_scale_;
  152. layer_impl->raster_source_scale_ = raster_source_scale_;
  153. layer_impl->raster_contents_scale_ = raster_contents_scale_;
  154. layer_impl->low_res_raster_contents_scale_ = low_res_raster_contents_scale_;
  155. // Simply push the value to the active tree without any extra invalidations,
  156. // since the pending tree tiles would have this handled. This is here to
  157. // ensure the state is consistent for future raster.
  158. layer_impl->lcd_text_disallowed_reason_ = lcd_text_disallowed_reason_;
  159. layer_impl->SanityCheckTilingState();
  160. }
  161. void PictureLayerImpl::AppendQuads(viz::CompositorRenderPass* render_pass,
  162. AppendQuadsData* append_quads_data) {
  163. // RenderSurfaceImpl::AppendQuads sets mask properties in the DrawQuad for
  164. // the masked surface, which will apply to both the backdrop filter and the
  165. // contents of the masked surface, so we should not append quads of the mask
  166. // layer in DstIn blend mode which would apply the mask in another codepath.
  167. if (is_backdrop_filter_mask_)
  168. return;
  169. // The bounds and the pile size may differ if the pile wasn't updated (ie.
  170. // PictureLayer::Update didn't happen). In that case the pile will be empty.
  171. DCHECK(raster_source_->GetSize().IsEmpty() ||
  172. bounds() == raster_source_->GetSize())
  173. << " bounds " << bounds().ToString() << " pile "
  174. << raster_source_->GetSize().ToString();
  175. viz::SharedQuadState* shared_quad_state =
  176. render_pass->CreateAndAppendSharedQuadState();
  177. if (raster_source_->IsSolidColor()) {
  178. // TODO(979672): This is still hard-coded at 1.0. This has some history:
  179. // - for crbug.com/769319, the contents scale was allowed to change, to
  180. // avoid blurring on high-dpi screens.
  181. // - for crbug.com/796558, the max device scale was hard-coded back to 1.0
  182. // for single-tile masks, to avoid problems with transforms.
  183. // To avoid those transform/scale bugs, this is currently left at 1.0. See
  184. // crbug.com/979672 for more context and test links.
  185. float max_contents_scale = 1;
  186. // The downstream CA layers use shared_quad_state to generate resources of
  187. // the right size even if it is a solid color picture layer.
  188. PopulateScaledSharedQuadState(shared_quad_state, max_contents_scale,
  189. contents_opaque());
  190. AppendDebugBorderQuad(render_pass, gfx::Rect(bounds()), shared_quad_state,
  191. append_quads_data);
  192. gfx::Rect scaled_visible_layer_rect =
  193. shared_quad_state->visible_quad_layer_rect;
  194. Occlusion occlusion = draw_properties().occlusion_in_content_space;
  195. EffectNode* effect_node = GetEffectTree().Node(effect_tree_index());
  196. SolidColorLayerImpl::AppendSolidQuads(
  197. render_pass, occlusion, shared_quad_state, scaled_visible_layer_rect,
  198. raster_source_->GetSolidColor(),
  199. !layer_tree_impl()->settings().enable_edge_anti_aliasing,
  200. effect_node->blend_mode, append_quads_data);
  201. return;
  202. }
  203. float device_scale_factor = layer_tree_impl()->device_scale_factor();
  204. // If we don't have tilings, we're likely going to append a checkerboard quad
  205. // the size of the layer. In that case, use scale 1 for more stable
  206. // to-screen-space mapping.
  207. float max_contents_scale =
  208. tilings_->num_tilings() ? MaximumTilingContentsScale() : 1.f;
  209. PopulateScaledSharedQuadState(shared_quad_state, max_contents_scale,
  210. contents_opaque());
  211. if (IsDirectlyCompositedImage()) {
  212. // Directly composited images should be clipped to the layer's content rect.
  213. // When a PictureLayerTiling is created for a directly composited image, the
  214. // layer bounds are multiplied by the raster scale in order to compute the
  215. // tile size. If the aspect ratio of the layer doesn't match that of the
  216. // image, it's possible that one of the dimensions of the resulting size
  217. // (layer bounds * raster scale) is a fractional number, as raster scale
  218. // does not scale x and y independently.
  219. // When this happens, the ToEnclosingRect() operation in
  220. // |PictureLayerTiling::EnclosingContentsRectFromLayer()| will
  221. // create a tiling that, when scaled by |max_contents_scale| above, is
  222. // larger than the layer bounds by a fraction of a pixel.
  223. gfx::Rect bounds_in_target_space = MathUtil::MapEnclosingClippedRect(
  224. draw_properties().target_space_transform, gfx::Rect(bounds()));
  225. if (is_clipped())
  226. bounds_in_target_space.Intersect(draw_properties().clip_rect);
  227. if (shared_quad_state->clip_rect)
  228. bounds_in_target_space.Intersect(*shared_quad_state->clip_rect);
  229. shared_quad_state->clip_rect = bounds_in_target_space;
  230. #if DCHECK_IS_ON()
  231. // Validate that the tile and bounds size are always within one pixel.
  232. PictureLayerTiling* high_res =
  233. tilings_->FindTilingWithResolution(HIGH_RESOLUTION);
  234. if (high_res) {
  235. const float epsilon = 1.f;
  236. gfx::SizeF scaled_tiling_size(high_res->tiling_size());
  237. scaled_tiling_size.Scale(1 / raster_contents_scale_.x(),
  238. 1 / raster_contents_scale_.y());
  239. if (raster_contents_scale_.x() >= 1.f)
  240. DCHECK(std::abs(bounds().width() - scaled_tiling_size.width()) <
  241. epsilon);
  242. if (raster_contents_scale_.y() >= 1.f)
  243. DCHECK(std::abs(bounds().height() - scaled_tiling_size.height()) <
  244. epsilon);
  245. }
  246. #endif
  247. }
  248. Occlusion scaled_occlusion =
  249. draw_properties()
  250. .occlusion_in_content_space.GetOcclusionWithGivenDrawTransform(
  251. shared_quad_state->quad_to_target_transform);
  252. if (current_draw_mode_ == DRAW_MODE_RESOURCELESS_SOFTWARE) {
  253. DCHECK(shared_quad_state->quad_layer_rect.origin() == gfx::Point(0, 0));
  254. AppendDebugBorderQuad(
  255. render_pass, shared_quad_state->quad_layer_rect, shared_quad_state,
  256. append_quads_data, DebugColors::DirectPictureBorderColor(),
  257. DebugColors::DirectPictureBorderWidth(device_scale_factor));
  258. gfx::Rect geometry_rect = shared_quad_state->visible_quad_layer_rect;
  259. gfx::Rect visible_geometry_rect =
  260. scaled_occlusion.GetUnoccludedContentRect(geometry_rect);
  261. bool needs_blending = !contents_opaque();
  262. // The raster source may not be valid over the entire visible rect,
  263. // and rastering outside of that may cause incorrect pixels.
  264. gfx::Rect scaled_recorded_viewport = gfx::ScaleToEnclosingRect(
  265. raster_source_->RecordedViewport(), max_contents_scale);
  266. geometry_rect.Intersect(scaled_recorded_viewport);
  267. visible_geometry_rect.Intersect(scaled_recorded_viewport);
  268. if (visible_geometry_rect.IsEmpty())
  269. return;
  270. DCHECK(raster_source_->HasRecordings());
  271. gfx::Rect quad_content_rect = shared_quad_state->visible_quad_layer_rect;
  272. gfx::Size texture_size = quad_content_rect.size();
  273. gfx::RectF texture_rect = gfx::RectF(gfx::SizeF(texture_size));
  274. viz::PictureDrawQuad::ImageAnimationMap image_animation_map;
  275. const auto* controller = layer_tree_impl()->image_animation_controller();
  276. WhichTree tree = layer_tree_impl()->IsPendingTree()
  277. ? WhichTree::PENDING_TREE
  278. : WhichTree::ACTIVE_TREE;
  279. for (const auto& image_data : raster_source_->GetDisplayItemList()
  280. ->discardable_image_map()
  281. .animated_images_metadata()) {
  282. image_animation_map[image_data.paint_image_id] =
  283. controller->GetFrameIndexForImage(image_data.paint_image_id, tree);
  284. }
  285. auto* quad = render_pass->CreateAndAppendDrawQuad<viz::PictureDrawQuad>();
  286. quad->SetNew(shared_quad_state, geometry_rect, visible_geometry_rect,
  287. needs_blending, texture_rect, texture_size, nearest_neighbor_,
  288. viz::RGBA_8888, quad_content_rect, max_contents_scale,
  289. std::move(image_animation_map),
  290. raster_source_->GetDisplayItemList());
  291. ValidateQuadResources(quad);
  292. return;
  293. }
  294. // If we're doing a regular AppendQuads (ie, not solid color or resourceless
  295. // software draw, and if the visible rect is scrolled far enough away, then we
  296. // may run into a floating point precision in AA calculations in the renderer.
  297. // See crbug.com/765297. In order to avoid this, we shift the quads up from
  298. // where they logically reside and adjust the shared_quad_state's transform
  299. // instead. We only do this in a scale/translate matrices to ensure the math
  300. // is correct.
  301. gfx::Vector2d quad_offset;
  302. if (shared_quad_state->quad_to_target_transform.IsScaleOrTranslation()) {
  303. const auto& visible_rect = shared_quad_state->visible_quad_layer_rect;
  304. quad_offset = gfx::Vector2d(-visible_rect.x(), -visible_rect.y());
  305. }
  306. gfx::Rect debug_border_rect(shared_quad_state->quad_layer_rect);
  307. debug_border_rect.Offset(quad_offset);
  308. AppendDebugBorderQuad(render_pass, debug_border_rect, shared_quad_state,
  309. append_quads_data);
  310. if (ShowDebugBorders(DebugBorderType::LAYER)) {
  311. for (PictureLayerTilingSet::CoverageIterator iter(
  312. tilings_.get(), max_contents_scale,
  313. shared_quad_state->visible_quad_layer_rect,
  314. ideal_contents_scale_key());
  315. iter; ++iter) {
  316. SkColor4f color;
  317. float width;
  318. if (*iter && iter->draw_info().IsReadyToDraw()) {
  319. TileDrawInfo::Mode mode = iter->draw_info().mode();
  320. if (mode == TileDrawInfo::SOLID_COLOR_MODE) {
  321. color = DebugColors::SolidColorTileBorderColor();
  322. width = DebugColors::SolidColorTileBorderWidth(device_scale_factor);
  323. } else if (mode == TileDrawInfo::OOM_MODE) {
  324. color = DebugColors::OOMTileBorderColor();
  325. width = DebugColors::OOMTileBorderWidth(device_scale_factor);
  326. } else if (iter.resolution() == HIGH_RESOLUTION) {
  327. color = DebugColors::HighResTileBorderColor();
  328. width = DebugColors::HighResTileBorderWidth(device_scale_factor);
  329. } else if (iter.resolution() == LOW_RESOLUTION) {
  330. color = DebugColors::LowResTileBorderColor();
  331. width = DebugColors::LowResTileBorderWidth(device_scale_factor);
  332. } else if (iter->contents_scale_key() > max_contents_scale) {
  333. color = DebugColors::ExtraHighResTileBorderColor();
  334. width = DebugColors::ExtraHighResTileBorderWidth(device_scale_factor);
  335. } else {
  336. color = DebugColors::ExtraLowResTileBorderColor();
  337. width = DebugColors::ExtraLowResTileBorderWidth(device_scale_factor);
  338. }
  339. } else {
  340. color = DebugColors::MissingTileBorderColor();
  341. width = DebugColors::MissingTileBorderWidth(device_scale_factor);
  342. }
  343. auto* debug_border_quad =
  344. render_pass->CreateAndAppendDrawQuad<viz::DebugBorderDrawQuad>();
  345. gfx::Rect geometry_rect = iter.geometry_rect();
  346. geometry_rect.Offset(quad_offset);
  347. gfx::Rect visible_geometry_rect = geometry_rect;
  348. debug_border_quad->SetNew(shared_quad_state, geometry_rect,
  349. visible_geometry_rect, color, width);
  350. }
  351. }
  352. if (layer_tree_impl()->debug_state().highlight_non_lcd_text_layers) {
  353. SkColor4f color =
  354. DebugColors::NonLCDTextHighlightColor(lcd_text_disallowed_reason());
  355. if (color != SkColors::kTransparent &&
  356. GetRasterSource()->GetDisplayItemList()->AreaOfDrawText(
  357. gfx::Rect(bounds()))) {
  358. render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>()->SetNew(
  359. shared_quad_state, debug_border_rect, debug_border_rect, color,
  360. append_quads_data);
  361. }
  362. }
  363. // Keep track of the tilings that were used so that tilings that are
  364. // unused can be considered for removal.
  365. last_append_quads_tilings_.clear();
  366. // Ignore missing tiles outside of viewport for tile priority. This is
  367. // normally the same as draw viewport but can be independently overridden by
  368. // embedders like Android WebView with SetExternalTilePriorityConstraints.
  369. gfx::Rect scaled_viewport_for_tile_priority = gfx::ScaleToEnclosingRect(
  370. viewport_rect_for_tile_priority_in_content_space_, max_contents_scale);
  371. size_t missing_tile_count = 0u;
  372. size_t on_demand_missing_tile_count = 0u;
  373. only_used_low_res_last_append_quads_ = true;
  374. gfx::Rect scaled_recorded_viewport = gfx::ScaleToEnclosingRect(
  375. raster_source_->RecordedViewport(), max_contents_scale);
  376. for (PictureLayerTilingSet::CoverageIterator iter(
  377. tilings_.get(), max_contents_scale,
  378. shared_quad_state->visible_quad_layer_rect,
  379. ideal_contents_scale_key());
  380. iter; ++iter) {
  381. gfx::Rect geometry_rect = iter.geometry_rect();
  382. gfx::Rect visible_geometry_rect =
  383. scaled_occlusion.GetUnoccludedContentRect(geometry_rect);
  384. gfx::Rect offset_geometry_rect = geometry_rect;
  385. offset_geometry_rect.Offset(quad_offset);
  386. gfx::Rect offset_visible_geometry_rect = visible_geometry_rect;
  387. offset_visible_geometry_rect.Offset(quad_offset);
  388. bool needs_blending = !contents_opaque();
  389. if (visible_geometry_rect.IsEmpty())
  390. continue;
  391. int64_t visible_geometry_area =
  392. static_cast<int64_t>(visible_geometry_rect.width()) *
  393. visible_geometry_rect.height();
  394. append_quads_data->visible_layer_area += visible_geometry_area;
  395. bool has_draw_quad = false;
  396. if (*iter && iter->draw_info().IsReadyToDraw()) {
  397. const TileDrawInfo& draw_info = iter->draw_info();
  398. switch (draw_info.mode()) {
  399. case TileDrawInfo::RESOURCE_MODE: {
  400. gfx::RectF texture_rect = iter.texture_rect();
  401. // The raster_contents_scale_ is the best scale that the layer is
  402. // trying to produce, even though it may not be ideal. Since that's
  403. // the best the layer can promise in the future, consider those as
  404. // complete. But if a tile is ideal scale, we don't want to consider
  405. // it incomplete and trying to replace it with a tile at a worse
  406. // scale.
  407. if (iter->contents_scale_key() != raster_contents_scale_key() &&
  408. iter->contents_scale_key() != ideal_contents_scale_key() &&
  409. geometry_rect.Intersects(scaled_viewport_for_tile_priority)) {
  410. append_quads_data->num_incomplete_tiles++;
  411. }
  412. auto* quad =
  413. render_pass->CreateAndAppendDrawQuad<viz::TileDrawQuad>();
  414. quad->SetNew(
  415. shared_quad_state, offset_geometry_rect,
  416. offset_visible_geometry_rect, needs_blending,
  417. draw_info.resource_id_for_export(), texture_rect,
  418. draw_info.resource_size(), draw_info.is_premultiplied(),
  419. nearest_neighbor_,
  420. !layer_tree_impl()->settings().enable_edge_anti_aliasing);
  421. ValidateQuadResources(quad);
  422. has_draw_quad = true;
  423. break;
  424. }
  425. case TileDrawInfo::SOLID_COLOR_MODE: {
  426. float alpha = draw_info.solid_color().fA * shared_quad_state->opacity;
  427. if (alpha >= std::numeric_limits<float>::epsilon()) {
  428. auto* quad =
  429. render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>();
  430. quad->SetNew(
  431. shared_quad_state, offset_geometry_rect,
  432. offset_visible_geometry_rect, draw_info.solid_color(),
  433. !layer_tree_impl()->settings().enable_edge_anti_aliasing);
  434. ValidateQuadResources(quad);
  435. }
  436. has_draw_quad = true;
  437. break;
  438. }
  439. case TileDrawInfo::OOM_MODE:
  440. break; // Checkerboard.
  441. }
  442. }
  443. if (!has_draw_quad) {
  444. // Checkerboard.
  445. SkColor4f color = safe_opaque_background_color();
  446. if (ShowDebugBorders(DebugBorderType::LAYER)) {
  447. // Fill the whole tile with the missing tile color.
  448. color = DebugColors::DefaultCheckerboardColor();
  449. }
  450. auto* quad =
  451. render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>();
  452. quad->SetNew(shared_quad_state, offset_geometry_rect,
  453. offset_visible_geometry_rect, color, false);
  454. ValidateQuadResources(quad);
  455. if (geometry_rect.Intersects(scaled_viewport_for_tile_priority)) {
  456. append_quads_data->num_missing_tiles++;
  457. ++missing_tile_count;
  458. }
  459. append_quads_data->checkerboarded_visible_content_area +=
  460. visible_geometry_area;
  461. // Intersect checkerboard rect with interest rect to generate rect where
  462. // we checkerboarded and has recording. The area where we don't have
  463. // recording is not necessarily a Rect, and its area is calculated using
  464. // subtraction.
  465. gfx::Rect visible_rect_has_recording = visible_geometry_rect;
  466. visible_rect_has_recording.Intersect(scaled_recorded_viewport);
  467. int64_t checkerboarded_has_recording_area =
  468. static_cast<int64_t>(visible_rect_has_recording.width()) *
  469. visible_rect_has_recording.height();
  470. append_quads_data->checkerboarded_needs_raster_content_area +=
  471. checkerboarded_has_recording_area;
  472. append_quads_data->checkerboarded_no_recording_content_area +=
  473. visible_geometry_area - checkerboarded_has_recording_area;
  474. // Report data on any missing images that might be the largest
  475. // contentful image.
  476. if (*iter) {
  477. UMA_HISTOGRAM_BOOLEAN(
  478. "Compositing.DecodeLCPCandidateImage.MissedDeadline",
  479. iter->HasMissingLCPCandidateImages());
  480. }
  481. continue;
  482. }
  483. if (iter.resolution() != HIGH_RESOLUTION) {
  484. append_quads_data->approximated_visible_content_area +=
  485. visible_geometry_area;
  486. }
  487. // If we have a draw quad, but it's not low resolution, then
  488. // mark that we've used something other than low res to draw.
  489. if (iter.resolution() != LOW_RESOLUTION)
  490. only_used_low_res_last_append_quads_ = false;
  491. if (last_append_quads_tilings_.empty() ||
  492. last_append_quads_tilings_.back() != iter.CurrentTiling()) {
  493. last_append_quads_tilings_.push_back(iter.CurrentTiling());
  494. }
  495. }
  496. // Adjust shared_quad_state with the quad_offset, since we've adjusted each
  497. // quad we've appended by it.
  498. shared_quad_state->quad_to_target_transform.Translate(-quad_offset);
  499. shared_quad_state->quad_layer_rect.Offset(quad_offset);
  500. shared_quad_state->visible_quad_layer_rect.Offset(quad_offset);
  501. if (missing_tile_count) {
  502. TRACE_EVENT_INSTANT2("cc",
  503. "PictureLayerImpl::AppendQuads checkerboard",
  504. TRACE_EVENT_SCOPE_THREAD,
  505. "missing_tile_count",
  506. missing_tile_count,
  507. "on_demand_missing_tile_count",
  508. on_demand_missing_tile_count);
  509. }
  510. // Aggressively remove any tilings that are not seen to save memory. Note
  511. // that this is at the expense of doing cause more frequent re-painting. A
  512. // better scheme would be to maintain a tighter visible_layer_rect for the
  513. // finer tilings.
  514. CleanUpTilingsOnActiveLayer(last_append_quads_tilings_);
  515. SanityCheckTilingState();
  516. }
  517. bool PictureLayerImpl::UpdateTiles() {
  518. if (!CanHaveTilings()) {
  519. ideal_page_scale_ = 0.f;
  520. ideal_device_scale_ = 0.f;
  521. ideal_contents_scale_ = gfx::Vector2dF(0.f, 0.f);
  522. ideal_source_scale_ = gfx::Vector2dF(0.f, 0.f);
  523. SanityCheckTilingState();
  524. return false;
  525. }
  526. // Remove any non-ideal tilings that were not used last time we generated
  527. // quads to save memory and processing time. Note that pending tree should
  528. // only have one or two tilings (high and low res), so only clean up the
  529. // active layer. This cleans it up here in case AppendQuads didn't run.
  530. // If it did run, this would not remove any additional tilings.
  531. if (layer_tree_impl()->IsActiveTree())
  532. CleanUpTilingsOnActiveLayer(last_append_quads_tilings_);
  533. UpdateIdealScales();
  534. const bool should_adjust_raster_scale = ShouldAdjustRasterScale();
  535. if (should_adjust_raster_scale)
  536. RecalculateRasterScales();
  537. UpdateTilingsForRasterScaleAndTranslation(should_adjust_raster_scale);
  538. raster_source_size_changed_ = false;
  539. if (layer_tree_impl()->IsActiveTree())
  540. AddLowResolutionTilingIfNeeded();
  541. DCHECK(raster_page_scale_);
  542. DCHECK(raster_device_scale_);
  543. DCHECK(raster_source_scale_.x());
  544. DCHECK(raster_source_scale_.y());
  545. DCHECK(raster_contents_scale_.x());
  546. DCHECK(raster_contents_scale_.y());
  547. DCHECK(low_res_raster_contents_scale_);
  548. was_screen_space_transform_animating_ =
  549. draw_properties().screen_space_transform_is_animating;
  550. double current_frame_time_in_seconds =
  551. (layer_tree_impl()->CurrentBeginFrameArgs().frame_time -
  552. base::TimeTicks()).InSecondsF();
  553. UpdateViewportRectForTilePriorityInContentSpace();
  554. // The tiling set can require tiles for activation any of the following
  555. // conditions are true:
  556. // - This layer produced a high-res or non-ideal-res tile last frame.
  557. // - We're in requires high res to draw mode.
  558. // - We're not in smoothness takes priority mode.
  559. // To put different, the tiling set can't require tiles for activation if
  560. // we're in smoothness mode and only used low-res or checkerboard to draw last
  561. // frame and we don't need high res to draw.
  562. //
  563. // The reason for this is that we should be able to activate sooner and get a
  564. // more up to date recording, so we don't run out of recording on the active
  565. // tree.
  566. // A layer must be a drawing layer for it to require tiles for activation.
  567. bool can_require_tiles_for_activation = false;
  568. if (contributes_to_drawn_render_surface()) {
  569. can_require_tiles_for_activation =
  570. !only_used_low_res_last_append_quads_ || RequiresHighResToDraw() ||
  571. !layer_tree_impl()->SmoothnessTakesPriority();
  572. }
  573. static const base::NoDestructor<Occlusion> kEmptyOcclusion;
  574. const Occlusion& occlusion_in_content_space =
  575. layer_tree_impl()->settings().use_occlusion_for_tile_prioritization
  576. ? draw_properties().occlusion_in_content_space
  577. : *kEmptyOcclusion;
  578. // Pass |occlusion_in_content_space| for |occlusion_in_layer_space| since
  579. // they are the same space in picture layer, as contents scale is always 1.
  580. bool updated = tilings_->UpdateTilePriorities(
  581. viewport_rect_for_tile_priority_in_content_space_,
  582. ideal_contents_scale_key(), current_frame_time_in_seconds,
  583. occlusion_in_content_space, can_require_tiles_for_activation);
  584. DCHECK_GT(tilings_->num_tilings(), 0u);
  585. SanityCheckTilingState();
  586. return updated;
  587. }
  588. void PictureLayerImpl::UpdateViewportRectForTilePriorityInContentSpace() {
  589. // If visible_layer_rect() is empty or viewport_rect_for_tile_priority is
  590. // set to be different from the device viewport, try to inverse project the
  591. // viewport into layer space and use that. Otherwise just use
  592. // visible_layer_rect().
  593. gfx::Rect visible_rect_in_content_space = visible_layer_rect();
  594. gfx::Rect viewport_rect_for_tile_priority =
  595. layer_tree_impl()->ViewportRectForTilePriority();
  596. if (visible_rect_in_content_space.IsEmpty() ||
  597. layer_tree_impl()->GetDeviceViewport() !=
  598. viewport_rect_for_tile_priority) {
  599. gfx::Transform view_to_layer(gfx::Transform::kSkipInitialization);
  600. if (ScreenSpaceTransform().GetInverse(&view_to_layer)) {
  601. // Transform from view space to content space.
  602. visible_rect_in_content_space = MathUtil::ProjectEnclosingClippedRect(
  603. view_to_layer, viewport_rect_for_tile_priority);
  604. // We have to allow for a viewport that is outside of the layer bounds in
  605. // order to compute tile priorities correctly for offscreen content that
  606. // is going to make it on screen. However, we also have to limit the
  607. // viewport since it can be very large due to screen_space_transforms. As
  608. // a heuristic, we clip to bounds padded by skewport_extrapolation_limit *
  609. // maximum tiling scale, since this should allow sufficient room for
  610. // skewport calculations.
  611. gfx::Rect padded_bounds(bounds());
  612. int padding_amount = layer_tree_impl()
  613. ->settings()
  614. .skewport_extrapolation_limit_in_screen_pixels *
  615. MaximumTilingContentsScale();
  616. padded_bounds.Inset(-padding_amount);
  617. visible_rect_in_content_space =
  618. SafeIntersectRects(visible_rect_in_content_space, padded_bounds);
  619. }
  620. }
  621. viewport_rect_for_tile_priority_in_content_space_ =
  622. visible_rect_in_content_space;
  623. }
  624. PictureLayerImpl* PictureLayerImpl::GetPendingOrActiveTwinLayer() const {
  625. if (!twin_layer_ || !twin_layer_->IsOnActiveOrPendingTree())
  626. return nullptr;
  627. return twin_layer_;
  628. }
  629. void PictureLayerImpl::UpdateRasterSource(
  630. scoped_refptr<RasterSource> raster_source,
  631. Region* new_invalidation,
  632. const PictureLayerTilingSet* pending_set,
  633. const PaintWorkletRecordMap* pending_paint_worklet_records) {
  634. // The bounds and the pile size may differ if the pile wasn't updated (ie.
  635. // PictureLayer::Update didn't happen). In that case the pile will be empty.
  636. DCHECK(raster_source->GetSize().IsEmpty() ||
  637. bounds() == raster_source->GetSize())
  638. << " bounds " << bounds().ToString() << " pile "
  639. << raster_source->GetSize().ToString();
  640. if (!raster_source_ || raster_source_->GetSize() != raster_source->GetSize())
  641. raster_source_size_changed_ = true;
  642. // We have an updated recording if the DisplayItemList in the new RasterSource
  643. // is different.
  644. const bool recording_updated =
  645. !raster_source_ || raster_source_->GetDisplayItemList() !=
  646. raster_source->GetDisplayItemList();
  647. // Unregister for all images on the current raster source, if the recording
  648. // was updated.
  649. if (recording_updated) {
  650. UnregisterAnimatedImages();
  651. // When the display list changes, the set of PaintWorklets may also change.
  652. if (pending_paint_worklet_records) {
  653. paint_worklet_records_ = *pending_paint_worklet_records;
  654. } else {
  655. if (raster_source->GetDisplayItemList()) {
  656. SetPaintWorkletInputs(raster_source->GetDisplayItemList()
  657. ->discardable_image_map()
  658. .paint_worklet_inputs());
  659. } else {
  660. SetPaintWorkletInputs({});
  661. }
  662. }
  663. // If the MSAA sample count has changed, we need to re-raster the complete
  664. // layer.
  665. if (raster_source_) {
  666. const auto& current_display_item_list =
  667. raster_source_->GetDisplayItemList();
  668. const auto& new_display_item_list = raster_source->GetDisplayItemList();
  669. if (current_display_item_list && new_display_item_list) {
  670. bool needs_full_invalidation =
  671. layer_tree_impl()->GetMSAASampleCountForRaster(
  672. current_display_item_list) !=
  673. layer_tree_impl()->GetMSAASampleCountForRaster(
  674. new_display_item_list);
  675. needs_full_invalidation |=
  676. layer_tree_impl()->GetTargetColorParams(
  677. current_display_item_list->discardable_image_map()
  678. .content_color_usage()) !=
  679. layer_tree_impl()->GetTargetColorParams(
  680. new_display_item_list->discardable_image_map()
  681. .content_color_usage());
  682. if (needs_full_invalidation)
  683. new_invalidation->Union(gfx::Rect(raster_source->GetSize()));
  684. }
  685. }
  686. }
  687. // The |raster_source_| is initially null, so have to check for that for the
  688. // first frame.
  689. bool could_have_tilings = CanHaveTilings();
  690. raster_source_.swap(raster_source);
  691. raster_source_->set_debug_name(DebugName());
  692. // Register images from the new raster source, if the recording was updated.
  693. // TODO(khushalsagar): UMA the number of animated images in layer?
  694. if (recording_updated)
  695. RegisterAnimatedImages();
  696. // The |new_invalidation| must be cleared before updating tilings since they
  697. // access the invalidation through the PictureLayerTilingClient interface.
  698. invalidation_.Clear();
  699. invalidation_.Swap(new_invalidation);
  700. bool can_have_tilings = CanHaveTilings();
  701. DCHECK(!pending_set ||
  702. can_have_tilings == GetPendingOrActiveTwinLayer()->CanHaveTilings());
  703. // Need to call UpdateTiles again if CanHaveTilings changed.
  704. if (could_have_tilings != can_have_tilings)
  705. layer_tree_impl()->set_needs_update_draw_properties();
  706. if (!can_have_tilings) {
  707. RemoveAllTilings();
  708. return;
  709. }
  710. // We could do this after doing UpdateTiles, which would avoid doing this for
  711. // tilings that are going to disappear on the pending tree (if scale changed).
  712. // But that would also be more complicated, so we just do it here for now.
  713. //
  714. // TODO(crbug.com/843787): If the LayerTreeFrameSink is lost, and we activate,
  715. // this ends up running with the old LayerTreeFrameSink, or possibly with a
  716. // null LayerTreeFrameSink, which can give incorrect results or maybe crash.
  717. if (pending_set) {
  718. tilings_->UpdateTilingsToCurrentRasterSourceForActivation(
  719. raster_source_, pending_set, invalidation_, MinimumContentsScale(),
  720. MaximumContentsScale());
  721. } else {
  722. tilings_->UpdateTilingsToCurrentRasterSourceForCommit(
  723. raster_source_, invalidation_, MinimumContentsScale(),
  724. MaximumContentsScale());
  725. // We're in a commit, make sure to update the state of the checker image
  726. // tracker with the new async attribute data.
  727. layer_tree_impl()->UpdateImageDecodingHints(
  728. raster_source_->TakeDecodingModeMap());
  729. }
  730. }
  731. void PictureLayerImpl::UpdateCanUseLCDText(
  732. bool raster_translation_aligns_pixels) {
  733. // If we have pending/active trees, the active tree doesn't update lcd text
  734. // status but copies it from the pending tree.
  735. if (!layer_tree_impl()->IsSyncTree())
  736. return;
  737. lcd_text_disallowed_reason_ =
  738. ComputeLCDTextDisallowedReason(raster_translation_aligns_pixels);
  739. }
  740. bool PictureLayerImpl::AffectedByWillChangeTransformHint() const {
  741. TransformNode* transform_node =
  742. GetTransformTree().Node(transform_tree_index());
  743. return transform_node &&
  744. transform_node->node_or_ancestors_will_change_transform;
  745. }
  746. LCDTextDisallowedReason PictureLayerImpl::ComputeLCDTextDisallowedReason(
  747. bool raster_translation_aligns_pixels) const {
  748. // No need to use LCD text if there is no text.
  749. if (!raster_source_ || !raster_source_->GetDisplayItemList() ||
  750. !raster_source_->GetDisplayItemList()->has_draw_text_ops()) {
  751. return LCDTextDisallowedReason::kNoText;
  752. }
  753. if (layer_tree_impl()->settings().layers_always_allowed_lcd_text)
  754. return LCDTextDisallowedReason::kNone;
  755. if (!layer_tree_impl()->settings().can_use_lcd_text)
  756. return LCDTextDisallowedReason::kSetting;
  757. if (!contents_opaque_for_text()) {
  758. if (!background_color().isOpaque())
  759. return LCDTextDisallowedReason::kBackgroundColorNotOpaque;
  760. return LCDTextDisallowedReason::kContentsNotOpaque;
  761. }
  762. // If raster translation aligns pixels, we can ignore fractional layer offset
  763. // and transform for LCD text.
  764. if (!raster_translation_aligns_pixels) {
  765. if (static_cast<int>(offset_to_transform_parent().x()) !=
  766. offset_to_transform_parent().x())
  767. return LCDTextDisallowedReason::kNonIntegralXOffset;
  768. if (static_cast<int>(offset_to_transform_parent().y()) !=
  769. offset_to_transform_parent().y())
  770. return LCDTextDisallowedReason::kNonIntegralYOffset;
  771. return LCDTextDisallowedReason::kNonIntegralTranslation;
  772. }
  773. TransformNode* transform_node =
  774. GetTransformTree().Node(transform_tree_index());
  775. if (transform_node->node_or_ancestors_will_change_transform)
  776. return LCDTextDisallowedReason::kWillChangeTransform;
  777. if (screen_space_transform_is_animating())
  778. return LCDTextDisallowedReason::kTransformAnimation;
  779. EffectNode* effect_node = GetEffectTree().Node(effect_tree_index());
  780. if (effect_node->node_or_ancestor_has_filters ||
  781. effect_node->affected_by_backdrop_filter)
  782. return LCDTextDisallowedReason::kPixelOrColorEffect;
  783. return LCDTextDisallowedReason::kNone;
  784. }
  785. LCDTextDisallowedReason
  786. PictureLayerImpl::ComputeLCDTextDisallowedReasonForTesting() const {
  787. gfx::Vector2dF raster_translation;
  788. return ComputeLCDTextDisallowedReason(
  789. CalculateRasterTranslation(raster_translation));
  790. }
  791. void PictureLayerImpl::NotifyTileStateChanged(const Tile* tile) {
  792. if (layer_tree_impl()->IsActiveTree())
  793. damage_rect_.Union(tile->enclosing_layer_rect());
  794. if (tile->draw_info().NeedsRaster()) {
  795. PictureLayerTiling* tiling =
  796. tilings_->FindTilingWithScaleKey(tile->contents_scale_key());
  797. if (tiling)
  798. tiling->set_all_tiles_done(false);
  799. }
  800. }
  801. gfx::Rect PictureLayerImpl::GetDamageRect() const {
  802. return damage_rect_;
  803. }
  804. void PictureLayerImpl::ResetChangeTracking() {
  805. LayerImpl::ResetChangeTracking();
  806. damage_rect_.SetRect(0, 0, 0, 0);
  807. }
  808. void PictureLayerImpl::DidBeginTracing() {
  809. raster_source_->DidBeginTracing();
  810. }
  811. void PictureLayerImpl::ReleaseResources() {
  812. tilings_->ReleaseAllResources();
  813. ResetRasterScale();
  814. }
  815. void PictureLayerImpl::ReleaseTileResources() {
  816. // All resources are tile resources.
  817. ReleaseResources();
  818. }
  819. void PictureLayerImpl::RecreateTileResources() {
  820. // Recreate tilings with new settings, since some of those might change when
  821. // we release resources.
  822. tilings_ = CreatePictureLayerTilingSet();
  823. }
  824. Region PictureLayerImpl::GetInvalidationRegionForDebugging() {
  825. // |invalidation_| gives the invalidation contained in the source frame, but
  826. // is not cleared after drawing from the layer. However, update_rect() is
  827. // cleared once the invalidation is drawn, which is useful for debugging
  828. // visualizations. This method intersects the two to give a more exact
  829. // representation of what was invalidated that is cleared after drawing.
  830. return IntersectRegions(invalidation_, update_rect());
  831. }
  832. std::unique_ptr<Tile> PictureLayerImpl::CreateTile(
  833. const Tile::CreateInfo& info) {
  834. int flags = 0;
  835. // We don't handle solid color single texture masks for backdrop filters,
  836. // so we shouldn't bother analyzing those.
  837. // Otherwise, always analyze to maximize memory savings.
  838. if (!is_backdrop_filter_mask_)
  839. flags = Tile::USE_PICTURE_ANALYSIS;
  840. if (contents_opaque())
  841. flags |= Tile::IS_OPAQUE;
  842. return layer_tree_impl()->tile_manager()->CreateTile(
  843. info, id(), layer_tree_impl()->source_frame_number(), flags);
  844. }
  845. const Region* PictureLayerImpl::GetPendingInvalidation() {
  846. if (layer_tree_impl()->IsPendingTree())
  847. return &invalidation_;
  848. if (layer_tree_impl()->IsRecycleTree())
  849. return nullptr;
  850. DCHECK(layer_tree_impl()->IsActiveTree());
  851. if (PictureLayerImpl* twin_layer = GetPendingOrActiveTwinLayer())
  852. return &twin_layer->invalidation_;
  853. return nullptr;
  854. }
  855. const PictureLayerTiling* PictureLayerImpl::GetPendingOrActiveTwinTiling(
  856. const PictureLayerTiling* tiling) const {
  857. PictureLayerImpl* twin_layer = GetPendingOrActiveTwinLayer();
  858. if (!twin_layer)
  859. return nullptr;
  860. const PictureLayerTiling* twin_tiling =
  861. twin_layer->tilings_->FindTilingWithScaleKey(
  862. tiling->contents_scale_key());
  863. if (twin_tiling &&
  864. twin_tiling->raster_transform() == tiling->raster_transform())
  865. return twin_tiling;
  866. return nullptr;
  867. }
  868. bool PictureLayerImpl::RequiresHighResToDraw() const {
  869. return layer_tree_impl()->RequiresHighResToDraw();
  870. }
  871. const PaintWorkletRecordMap& PictureLayerImpl::GetPaintWorkletRecords() const {
  872. return paint_worklet_records_;
  873. }
  874. bool PictureLayerImpl::IsDirectlyCompositedImage() const {
  875. return directly_composited_image_default_raster_scale_ > 0.f;
  876. }
  877. bool PictureLayerImpl::ScrollInteractionInProgress() const {
  878. return layer_tree_impl()->GetActivelyScrollingType() !=
  879. ActivelyScrollingType::kNone;
  880. }
  881. bool PictureLayerImpl::CurrentScrollCheckerboardsDueToNoRecording() const {
  882. return layer_tree_impl()->CurrentScrollCheckerboardsDueToNoRecording();
  883. }
  884. gfx::Rect PictureLayerImpl::GetEnclosingVisibleRectInTargetSpace() const {
  885. return GetScaledEnclosingVisibleRectInTargetSpace(
  886. MaximumTilingContentsScale());
  887. }
  888. bool PictureLayerImpl::ShouldAnimate(PaintImage::Id paint_image_id) const {
  889. // If we are registered with the animation controller, which queries whether
  890. // the image should be animated, then we must have recordings with this image.
  891. DCHECK(raster_source_);
  892. DCHECK(raster_source_->GetDisplayItemList());
  893. DCHECK(
  894. !raster_source_->GetDisplayItemList()->discardable_image_map().empty());
  895. // Only animate images for layers which HasValidTilePriorities. This check is
  896. // important for 2 reasons:
  897. // 1) It avoids doing additional work for layers we don't plan to rasterize
  898. // and/or draw. The updated state will be pulled by the animation system
  899. // if the draw properties change.
  900. // 2) It eliminates considering layers on the recycle tree. Once the pending
  901. // tree is activated, the layers on the recycle tree remain registered as
  902. // animation drivers, but should not drive animations since they don't have
  903. // updated draw properties.
  904. //
  905. // Additionally only animate images which are on-screen, animations are
  906. // paused once they are not visible.
  907. if (!HasValidTilePriorities())
  908. return false;
  909. const auto& rects = raster_source_->GetDisplayItemList()
  910. ->discardable_image_map()
  911. .GetRectsForImage(paint_image_id);
  912. for (const auto& r : rects.container()) {
  913. if (r.Intersects(visible_layer_rect()))
  914. return true;
  915. }
  916. return false;
  917. }
  918. gfx::Size PictureLayerImpl::CalculateTileSize(const gfx::Size& content_bounds) {
  919. content_bounds_ = content_bounds;
  920. return tile_size_calculator_.CalculateTileSize();
  921. }
  922. void PictureLayerImpl::GetContentsResourceId(
  923. viz::ResourceId* resource_id,
  924. gfx::Size* resource_size,
  925. gfx::SizeF* resource_uv_size) const {
  926. // We need contents resource for backdrop filter masks only.
  927. if (!is_backdrop_filter_mask()) {
  928. *resource_id = viz::kInvalidResourceId;
  929. return;
  930. }
  931. // The bounds and the pile size may differ if the pile wasn't updated (ie.
  932. // PictureLayer::Update didn't happen). In that case the pile will be empty.
  933. DCHECK(raster_source_->GetSize().IsEmpty() ||
  934. bounds() == raster_source_->GetSize())
  935. << " bounds " << bounds().ToString() << " pile "
  936. << raster_source_->GetSize().ToString();
  937. float dest_scale = MaximumTilingContentsScale();
  938. gfx::Rect content_rect =
  939. gfx::ScaleToEnclosingRect(gfx::Rect(bounds()), dest_scale);
  940. PictureLayerTilingSet::CoverageIterator iter(
  941. tilings_.get(), dest_scale, content_rect, ideal_contents_scale_key());
  942. // Mask resource not ready yet.
  943. if (!iter || !*iter) {
  944. *resource_id = viz::kInvalidResourceId;
  945. return;
  946. }
  947. // Masks only supported if they fit on exactly one tile.
  948. DCHECK(iter.geometry_rect() == content_rect)
  949. << "iter rect " << iter.geometry_rect().ToString() << " content rect "
  950. << content_rect.ToString();
  951. const TileDrawInfo& draw_info = iter->draw_info();
  952. if (!draw_info.IsReadyToDraw() ||
  953. draw_info.mode() != TileDrawInfo::RESOURCE_MODE) {
  954. *resource_id = viz::kInvalidResourceId;
  955. return;
  956. }
  957. *resource_id = draw_info.resource_id_for_export();
  958. *resource_size = draw_info.resource_size();
  959. // |resource_uv_size| represents the range of UV coordinates that map to the
  960. // content being drawn. Typically, we draw to the entire texture, so these
  961. // coordinates are (1.0f, 1.0f). However, if we are rasterizing to an
  962. // over-large texture, this size will be smaller, mapping to the subset of the
  963. // texture being used.
  964. gfx::SizeF requested_tile_size =
  965. gfx::SizeF(iter->tiling()->tiling_data()->tiling_size());
  966. DCHECK_LE(requested_tile_size.width(), draw_info.resource_size().width());
  967. DCHECK_LE(requested_tile_size.height(), draw_info.resource_size().height());
  968. *resource_uv_size = gfx::SizeF(
  969. requested_tile_size.width() / draw_info.resource_size().width(),
  970. requested_tile_size.height() / draw_info.resource_size().height());
  971. }
  972. void PictureLayerImpl::SetNearestNeighbor(bool nearest_neighbor) {
  973. if (nearest_neighbor_ == nearest_neighbor)
  974. return;
  975. nearest_neighbor_ = nearest_neighbor;
  976. NoteLayerPropertyChanged();
  977. }
  978. void PictureLayerImpl::SetDirectlyCompositedImageDefaultRasterScale(
  979. const gfx::Vector2dF& scale) {
  980. SetDirectlyCompositedImageDefaultRasterScale(GetPreferredRasterScale(scale));
  981. }
  982. void PictureLayerImpl::SetDirectlyCompositedImageDefaultRasterScale(
  983. float scale) {
  984. DCHECK_GE(scale, 0.f);
  985. if (directly_composited_image_default_raster_scale_ == scale)
  986. return;
  987. directly_composited_image_default_raster_scale_ = scale;
  988. directly_composited_image_default_raster_scale_changed_ = true;
  989. NoteLayerPropertyChanged();
  990. }
  991. bool PictureLayerImpl::ShouldDirectlyCompositeImage(float raster_scale) const {
  992. // Even if there are minor rendering differences, we want to apply directly
  993. // compositing images in cases where doing so is going to save memory.
  994. if (raster_scale < 0.1f)
  995. return true;
  996. // If the results of scaling the bounds by the expected raster scale
  997. // would end up with a content rect whose width/height are more than one
  998. // pixel different from the layer bounds, don't directly composite the image
  999. // to avoid incorrect rendering.
  1000. gfx::SizeF layer_bounds(bounds());
  1001. gfx::RectF scaled_bounds_rect(layer_bounds);
  1002. scaled_bounds_rect.Scale(raster_scale);
  1003. // Take the scaled bounds, get the enclosing rect then scale it back down -
  1004. // this is the same set of operations that will happen when using the tiling
  1005. // at that raster scale.
  1006. gfx::RectF content_rect(gfx::ToEnclosingRect(scaled_bounds_rect));
  1007. content_rect.Scale(1 / raster_scale);
  1008. return std::abs(layer_bounds.width() - content_rect.width()) < 1.f &&
  1009. std::abs(layer_bounds.height() - content_rect.height()) < 1.f;
  1010. }
  1011. float PictureLayerImpl::CalculateDirectlyCompositedImageRasterScale() const {
  1012. DCHECK(IsDirectlyCompositedImage());
  1013. // If the default raster scale didn't change, we will calculate based on the
  1014. // previous raster source scale. The calculation may change based on updated
  1015. // ideal source scale.
  1016. float adjusted_raster_scale =
  1017. directly_composited_image_default_raster_scale_changed_
  1018. ? directly_composited_image_default_raster_scale_
  1019. : raster_source_scale_key();
  1020. // We never want a raster scale larger than the default, since that uses more
  1021. // memory but can't result it better quality (upscaling will happen in the
  1022. // display compositor instead).
  1023. float max_scale = std::max(directly_composited_image_default_raster_scale_,
  1024. MinimumContentsScale());
  1025. float min_scale = MinimumContentsScale();
  1026. float clamped_ideal_source_scale =
  1027. base::clamp(ideal_source_scale_key(), min_scale, max_scale);
  1028. // Use clamped_ideal_source_scale if adjusted_raster_scale is too far away.
  1029. constexpr float kFarAwayFactor = 32.f;
  1030. if (adjusted_raster_scale < clamped_ideal_source_scale / kFarAwayFactor) {
  1031. adjusted_raster_scale = clamped_ideal_source_scale;
  1032. } else if (adjusted_raster_scale >
  1033. clamped_ideal_source_scale * kFarAwayFactor) {
  1034. adjusted_raster_scale = clamped_ideal_source_scale;
  1035. } else {
  1036. while (adjusted_raster_scale < clamped_ideal_source_scale)
  1037. adjusted_raster_scale *= 2.f;
  1038. // Make sure the adjusted scale is not more than 2x away from the ideal
  1039. // scale in order to save memory. Note that ShouldAdjustRasterScale() uses
  1040. // factor 4 to determine when the scale needs to be updated. This means that
  1041. // the layer may need to be re-rasterized if scale is increased by factor
  1042. // of 2, but not again when it's scaled back to the original size.
  1043. while (adjusted_raster_scale >= 2 * clamped_ideal_source_scale)
  1044. adjusted_raster_scale /= 2.f;
  1045. }
  1046. adjusted_raster_scale =
  1047. base::clamp(adjusted_raster_scale, min_scale, max_scale);
  1048. return adjusted_raster_scale;
  1049. }
  1050. PictureLayerTiling* PictureLayerImpl::AddTiling(
  1051. const gfx::AxisTransform2d& raster_transform) {
  1052. DCHECK(CanHaveTilings());
  1053. DCHECK_GE(raster_transform.scale().x(), MinimumContentsScale());
  1054. DCHECK_GE(raster_transform.scale().y(), MinimumContentsScale());
  1055. DCHECK_LE(raster_transform.scale().x(), MaximumContentsScale());
  1056. DCHECK_LE(raster_transform.scale().y(), MaximumContentsScale());
  1057. DCHECK(raster_source_->HasRecordings());
  1058. bool tiling_can_use_lcd_text =
  1059. can_use_lcd_text() && raster_transform.scale() == raster_contents_scale_;
  1060. return tilings_->AddTiling(raster_transform, raster_source_,
  1061. tiling_can_use_lcd_text);
  1062. }
  1063. void PictureLayerImpl::RemoveAllTilings() {
  1064. tilings_->RemoveAllTilings();
  1065. // If there are no tilings, then raster scales are no longer meaningful.
  1066. ResetRasterScale();
  1067. }
  1068. bool PictureLayerImpl::CanRecreateHighResTilingForLCDTextAndRasterTransform(
  1069. const PictureLayerTiling& high_res) const {
  1070. // We can recreate the tiling if we would invalidate all of its tiles.
  1071. if (high_res.may_contain_low_resolution_tiles())
  1072. return true;
  1073. // Keep the non-ideal raster translation unchanged for transform animations
  1074. // to avoid re-rasterization during animation.
  1075. if (draw_properties().screen_space_transform_is_animating ||
  1076. AffectedByWillChangeTransformHint())
  1077. return false;
  1078. // Also avoid re-rasterization during pinch-zoom.
  1079. if (layer_tree_impl()->PinchGestureActive())
  1080. return false;
  1081. // Keep the current LCD text and raster translation if there is no text and
  1082. // the raster scale is ideal.
  1083. if (lcd_text_disallowed_reason_ == LCDTextDisallowedReason::kNoText &&
  1084. high_res.raster_transform().scale() == raster_contents_scale_)
  1085. return false;
  1086. // If ReadyToActivate() is already scheduled, recreating tiling should be
  1087. // delayed until the activation is executed. Otherwise the tiles in viewport
  1088. // will be deleted.
  1089. if (layer_tree_impl()->IsSyncTree() && layer_tree_impl()->IsReadyToActivate())
  1090. return false;
  1091. // To reduce memory usage, don't recreate highres tiling during scroll
  1092. if (ScrollInteractionInProgress())
  1093. return false;
  1094. return true;
  1095. }
  1096. void PictureLayerImpl::UpdateTilingsForRasterScaleAndTranslation(
  1097. bool has_adjusted_raster_scale) {
  1098. PictureLayerTiling* high_res =
  1099. tilings_->FindTilingWithScaleKey(raster_contents_scale_key());
  1100. gfx::Vector2dF raster_translation;
  1101. bool raster_translation_aligns_pixels =
  1102. CalculateRasterTranslation(raster_translation);
  1103. UpdateCanUseLCDText(raster_translation_aligns_pixels);
  1104. if (high_res) {
  1105. bool raster_transform_is_not_ideal =
  1106. high_res->raster_transform().scale() != raster_contents_scale_ ||
  1107. high_res->raster_transform().translation() != raster_translation;
  1108. bool can_use_lcd_text_changed =
  1109. high_res->can_use_lcd_text() != can_use_lcd_text();
  1110. bool can_recreate_highres_tiling =
  1111. CanRecreateHighResTilingForLCDTextAndRasterTransform(*high_res);
  1112. // Only for the sync tree to avoid flickering.
  1113. bool should_recreate_high_res =
  1114. (raster_transform_is_not_ideal || can_use_lcd_text_changed) &&
  1115. layer_tree_impl()->IsSyncTree() && can_recreate_highres_tiling;
  1116. // Only request an invalidation if we don't already have a pending tree.
  1117. bool can_request_invalidation_for_high_res =
  1118. (raster_transform_is_not_ideal || can_use_lcd_text_changed) &&
  1119. !layer_tree_impl()->settings().commit_to_active_tree &&
  1120. layer_tree_impl()->IsActiveTree() && can_recreate_highres_tiling &&
  1121. !layer_tree_impl()->HasPendingTree();
  1122. if (should_recreate_high_res) {
  1123. tilings_->Remove(high_res);
  1124. high_res = nullptr;
  1125. } else if (can_request_invalidation_for_high_res) {
  1126. // Anytime a condition which flips whether we can recreate the tiling
  1127. // changes, we'll get a call to UpdateDrawProperties. We check whether we
  1128. // could recreate the tiling when this runs on the active tree to trigger
  1129. // an impl-side invalidation (if needed).
  1130. layer_tree_impl()->RequestImplSideInvalidationForRerasterTiling();
  1131. } else if (!has_adjusted_raster_scale) {
  1132. // Nothing changed, no need to update tilings.
  1133. DCHECK_EQ(HIGH_RESOLUTION, high_res->resolution());
  1134. SanityCheckTilingState();
  1135. return;
  1136. }
  1137. }
  1138. // Reset all resolution enums on tilings, we'll be setting new values in this
  1139. // function.
  1140. tilings_->MarkAllTilingsNonIdeal();
  1141. if (!high_res) {
  1142. // We always need a high res tiling, so create one if it doesn't exist.
  1143. high_res = AddTiling(
  1144. gfx::AxisTransform2d(raster_contents_scale_, raster_translation));
  1145. } else if (high_res->may_contain_low_resolution_tiles()) {
  1146. // If the tiling we find here was LOW_RESOLUTION previously, it may not be
  1147. // fully rastered, so destroy the old tiles.
  1148. high_res->Reset();
  1149. // Reset the flag now that we'll make it high res, it will have fully
  1150. // rastered content.
  1151. high_res->reset_may_contain_low_resolution_tiles();
  1152. }
  1153. high_res->set_resolution(HIGH_RESOLUTION);
  1154. if (layer_tree_impl()->IsPendingTree() ||
  1155. (layer_tree_impl()->settings().commit_to_active_tree &&
  1156. IsDirectlyCompositedImage())) {
  1157. // On the pending tree, drop any tilings that are non-ideal since we don't
  1158. // need them to activate anyway.
  1159. // For DirectlyCompositedImages, if we recomputed a new raster scale, we
  1160. // should drop the non-ideal ones if we're committing to the active tree.
  1161. // Otherwise a non-ideal scale that is _larger_ than the HIGH_RESOLUTION
  1162. // tile will be used as the coverage scale, and we'll produce a slightly
  1163. // different rendering. We don't drop the tilings on the active tree if
  1164. // we're not committing to the active tree to prevent checkerboarding.
  1165. tilings_->RemoveNonIdealTilings();
  1166. }
  1167. SanityCheckTilingState();
  1168. }
  1169. bool PictureLayerImpl::ShouldAdjustRasterScale() const {
  1170. if (!raster_contents_scale_.x() || !raster_contents_scale_.y())
  1171. return true;
  1172. // Adjust raster scale if the raster source size changed. This is mainly to
  1173. // reset the preserved scale for will-change:transform but may also help in
  1174. // other cases, which won't affect performance much because the change has
  1175. // involved the main thread and/or we'll (at least partly) re-raster anyway.
  1176. if (raster_source_size_changed_)
  1177. return true;
  1178. if (IsDirectlyCompositedImage()) {
  1179. // If the default raster scale changed, that means the bounds or image size
  1180. // changed. We should recalculate in order to raster at the intrinsic image
  1181. // size. Note that this is not a comparison of the used raster_source_scale_
  1182. // and desired because of the adjustments in RecalculateRasterScales.
  1183. if (directly_composited_image_default_raster_scale_changed_)
  1184. return true;
  1185. // First check to see if we need to adjust based on ideal_source_scale_
  1186. // changing (i.e. scale transform has been modified). These limits exist
  1187. // so that we don't raster at the intrinsic image size if the layer will
  1188. // be scaled down more than 4x ideal. This saves memory without sacrificing
  1189. // noticeable quality. We'll also bump the scale back up in the case where
  1190. // the ideal scale is increased.
  1191. float max_scale = std::max(directly_composited_image_default_raster_scale_,
  1192. MinimumContentsScale());
  1193. if (raster_source_scale_key() <
  1194. std::min(ideal_source_scale_key(), max_scale))
  1195. return true;
  1196. if (raster_source_scale_key() > 4 * ideal_source_scale_key())
  1197. return true;
  1198. return false;
  1199. }
  1200. if (was_screen_space_transform_animating_ !=
  1201. draw_properties().screen_space_transform_is_animating) {
  1202. // Skip adjusting raster scale when animations finish if we have a
  1203. // will-change: transform hint to preserve maximum resolution tiles
  1204. // needed.
  1205. if (draw_properties().screen_space_transform_is_animating ||
  1206. !AffectedByWillChangeTransformHint())
  1207. return true;
  1208. }
  1209. bool is_pinching = layer_tree_impl()->PinchGestureActive();
  1210. if (is_pinching && raster_page_scale_) {
  1211. // We change our raster scale when it is:
  1212. // - Higher than ideal (need a lower-res tiling available)
  1213. // - Too far from ideal (need a higher-res tiling available)
  1214. float ratio = ideal_page_scale_ / raster_page_scale_;
  1215. if (raster_page_scale_ > ideal_page_scale_ ||
  1216. ratio > kMaxScaleRatioDuringPinch)
  1217. return true;
  1218. }
  1219. if (!is_pinching) {
  1220. // When not pinching, match the ideal page scale factor.
  1221. if (raster_page_scale_ != ideal_page_scale_)
  1222. return true;
  1223. }
  1224. // Always match the ideal device scale factor.
  1225. if (raster_device_scale_ != ideal_device_scale_)
  1226. return true;
  1227. float max_scale = MaximumContentsScale();
  1228. if (raster_contents_scale_.x() > max_scale ||
  1229. raster_contents_scale_.y() > max_scale)
  1230. return true;
  1231. float min_scale = MinimumContentsScale();
  1232. if (raster_contents_scale_.x() < min_scale ||
  1233. raster_contents_scale_.y() < min_scale)
  1234. return true;
  1235. // Avoid frequent raster scale changes if we have an animating transform.
  1236. if (draw_properties().screen_space_transform_is_animating) {
  1237. // Except when the device viewport rect has changed because the raster scale
  1238. // may depend on the rect.
  1239. if (layer_tree_impl()->device_viewport_rect_changed()) {
  1240. return true;
  1241. }
  1242. // Or when the raster scale is not affected by invalid scale and is too
  1243. // small compared to the ideal scale.
  1244. if (ideal_contents_scale_.x() >
  1245. raster_contents_scale_.x() *
  1246. kRatioToAdjustRasterScaleForTransformAnimation ||
  1247. ideal_contents_scale_.y() >
  1248. raster_contents_scale_.y() *
  1249. kRatioToAdjustRasterScaleForTransformAnimation) {
  1250. auto* property_trees = layer_tree_impl()->property_trees();
  1251. int transform_id = transform_tree_index();
  1252. if (property_trees->AnimationScaleCacheIsInvalid(transform_id) ||
  1253. !property_trees->AnimationAffectedByInvalidScale(transform_id)) {
  1254. return true;
  1255. }
  1256. }
  1257. return false;
  1258. }
  1259. // Don't change the raster scale if the raster scale is already ideal.
  1260. if (raster_source_scale_ == ideal_source_scale_)
  1261. return false;
  1262. // Don't update will-change: transform layers if the raster contents scale is
  1263. // bigger than the minimum scale.
  1264. if (AffectedByWillChangeTransformHint()) {
  1265. float min_raster_scale = MinimumRasterContentsScaleForWillChangeTransform();
  1266. if (raster_contents_scale_.x() >= min_raster_scale &&
  1267. raster_contents_scale_.y() >= min_raster_scale)
  1268. return false;
  1269. }
  1270. // Match the raster scale in all other cases.
  1271. return true;
  1272. }
  1273. void PictureLayerImpl::AddLowResolutionTilingIfNeeded() {
  1274. DCHECK(layer_tree_impl()->IsActiveTree());
  1275. if (!layer_tree_impl()->create_low_res_tiling())
  1276. return;
  1277. // We should have a high resolution tiling at raster_contents_scale, so if the
  1278. // low res one is the same then we shouldn't try to override this tiling by
  1279. // marking it as a low res.
  1280. if (raster_contents_scale_key() == low_res_raster_contents_scale_)
  1281. return;
  1282. PictureLayerTiling* low_res =
  1283. tilings_->FindTilingWithScaleKey(low_res_raster_contents_scale_);
  1284. DCHECK(!low_res || low_res->resolution() != HIGH_RESOLUTION);
  1285. // Only create new low res tilings when the transform is static. This
  1286. // prevents wastefully creating a paired low res tiling for every new high
  1287. // res tiling during a pinch or a CSS animation.
  1288. bool is_pinching = layer_tree_impl()->PinchGestureActive();
  1289. bool is_animating = draw_properties().screen_space_transform_is_animating;
  1290. if (!is_pinching && !is_animating) {
  1291. if (!low_res)
  1292. low_res = AddTiling(gfx::AxisTransform2d(low_res_raster_contents_scale_,
  1293. gfx::Vector2dF()));
  1294. low_res->set_resolution(LOW_RESOLUTION);
  1295. }
  1296. }
  1297. void PictureLayerImpl::RecalculateRasterScales() {
  1298. if (IsDirectlyCompositedImage()) {
  1299. // TODO(crbug.com/1196414): Support 2D scales in directly composited images.
  1300. float used_raster_scale = CalculateDirectlyCompositedImageRasterScale();
  1301. directly_composited_image_default_raster_scale_changed_ = false;
  1302. if (ShouldDirectlyCompositeImage(used_raster_scale)) {
  1303. raster_source_scale_ =
  1304. gfx::Vector2dF(used_raster_scale, used_raster_scale);
  1305. raster_page_scale_ = 1.f;
  1306. raster_device_scale_ = 1.f;
  1307. raster_contents_scale_ = raster_source_scale_;
  1308. low_res_raster_contents_scale_ = used_raster_scale;
  1309. return;
  1310. }
  1311. // If we should not directly composite this image, reset values and fall
  1312. // back to normal raster scale calculations below.
  1313. directly_composited_image_default_raster_scale_ = 0.f;
  1314. }
  1315. gfx::Vector2dF old_raster_contents_scale = raster_contents_scale_;
  1316. float old_raster_page_scale = raster_page_scale_;
  1317. // The raster scale if previous tilings should be preserved.
  1318. gfx::Vector2dF preserved_raster_contents_scale = old_raster_contents_scale;
  1319. raster_device_scale_ = ideal_device_scale_;
  1320. raster_page_scale_ = ideal_page_scale_;
  1321. raster_source_scale_ = ideal_source_scale_;
  1322. raster_contents_scale_ = ideal_contents_scale_;
  1323. // During pinch we completely ignore the current ideal scale, and just use
  1324. // a multiple of the previous scale.
  1325. bool is_pinching = layer_tree_impl()->PinchGestureActive();
  1326. if (is_pinching && !old_raster_contents_scale.IsZero()) {
  1327. // See ShouldAdjustRasterScale:
  1328. // - When zooming out, preemptively create new tiling at lower resolution.
  1329. // - When zooming in, approximate ideal using multiple of kMaxScaleRatio.
  1330. bool zooming_out = old_raster_page_scale > ideal_page_scale_;
  1331. float desired_contents_scale =
  1332. std::max(old_raster_contents_scale.x(), old_raster_contents_scale.y());
  1333. float ideal_scale = ideal_contents_scale_key();
  1334. if (zooming_out) {
  1335. while (desired_contents_scale > ideal_scale)
  1336. desired_contents_scale /= kMaxScaleRatioDuringPinch;
  1337. } else {
  1338. while (desired_contents_scale < ideal_scale)
  1339. desired_contents_scale *= kMaxScaleRatioDuringPinch;
  1340. }
  1341. if (const auto* snapped_to_tiling = tilings_->FindTilingWithNearestScaleKey(
  1342. desired_contents_scale, kSnapToExistingTilingRatio)) {
  1343. raster_contents_scale_ = snapped_to_tiling->raster_transform().scale();
  1344. } else {
  1345. raster_contents_scale_ = old_raster_contents_scale;
  1346. raster_contents_scale_.Scale(desired_contents_scale /
  1347. raster_contents_scale_key());
  1348. }
  1349. preserved_raster_contents_scale = raster_contents_scale_;
  1350. raster_page_scale_ =
  1351. std::max(raster_contents_scale_.x() / raster_source_scale_.x(),
  1352. raster_contents_scale_.y() / raster_source_scale_.y()) /
  1353. raster_device_scale_;
  1354. }
  1355. if (draw_properties().screen_space_transform_is_animating)
  1356. AdjustRasterScaleForTransformAnimation(preserved_raster_contents_scale);
  1357. if (AffectedByWillChangeTransformHint()) {
  1358. float min_scale = MinimumRasterContentsScaleForWillChangeTransform();
  1359. raster_contents_scale_.SetToMax(gfx::Vector2dF(min_scale, min_scale));
  1360. }
  1361. float min_scale = MinimumContentsScale();
  1362. float max_scale = MaximumContentsScale();
  1363. raster_contents_scale_.SetToMax(gfx::Vector2dF(min_scale, min_scale));
  1364. raster_contents_scale_.SetToMin(gfx::Vector2dF(max_scale, max_scale));
  1365. DCHECK_GE(raster_contents_scale_.x(), min_scale);
  1366. DCHECK_GE(raster_contents_scale_.y(), min_scale);
  1367. DCHECK_LE(raster_contents_scale_.x(), max_scale);
  1368. DCHECK_LE(raster_contents_scale_.y(), max_scale);
  1369. // If this layer would create zero or one tiles at this content scale,
  1370. // don't create a low res tiling.
  1371. gfx::Size raster_bounds = gfx::ScaleToCeiledSize(raster_source_->GetSize(),
  1372. raster_contents_scale_.x(),
  1373. raster_contents_scale_.y());
  1374. gfx::Size tile_size = CalculateTileSize(raster_bounds);
  1375. bool tile_covers_bounds = tile_size.width() >= raster_bounds.width() &&
  1376. tile_size.height() >= raster_bounds.height();
  1377. if (tile_size.IsEmpty() || tile_covers_bounds) {
  1378. low_res_raster_contents_scale_ = raster_contents_scale_key();
  1379. return;
  1380. }
  1381. float low_res_factor =
  1382. layer_tree_impl()->settings().low_res_contents_scale_factor;
  1383. low_res_raster_contents_scale_ =
  1384. std::max(raster_contents_scale_key() * low_res_factor, min_scale);
  1385. DCHECK_LE(low_res_raster_contents_scale_, raster_contents_scale_key());
  1386. DCHECK_GE(low_res_raster_contents_scale_, min_scale);
  1387. DCHECK_LE(low_res_raster_contents_scale_, max_scale);
  1388. }
  1389. void PictureLayerImpl::AdjustRasterScaleForTransformAnimation(
  1390. const gfx::Vector2dF& preserved_raster_contents_scale) {
  1391. DCHECK(draw_properties().screen_space_transform_is_animating);
  1392. float maximum_animation_scale =
  1393. layer_tree_impl()->property_trees()->MaximumAnimationToScreenScale(
  1394. transform_tree_index());
  1395. raster_contents_scale_.SetToMax(
  1396. gfx::Vector2dF(maximum_animation_scale, maximum_animation_scale));
  1397. if (AffectedByWillChangeTransformHint()) {
  1398. // If we have a will-change: transform hint, do not shrink the content
  1399. // raster scale, otherwise we will end up throwing away larger tiles we may
  1400. // need again.
  1401. raster_contents_scale_.SetToMax(preserved_raster_contents_scale);
  1402. }
  1403. // However we want to avoid excessive memory use. Choose a scale at which this
  1404. // layer's rastered content is not larger than the viewport.
  1405. gfx::Size viewport = layer_tree_impl()->GetDeviceViewport().size();
  1406. // To avoid too small scale in a small viewport.
  1407. constexpr int kMinViewportDimension = 500;
  1408. float max_viewport_dimension =
  1409. std::max({viewport.width(), viewport.height(), kMinViewportDimension});
  1410. DCHECK(max_viewport_dimension);
  1411. // Use square to compensate for viewports with different aspect ratios.
  1412. float squared_viewport_area = max_viewport_dimension * max_viewport_dimension;
  1413. gfx::SizeF raster_source_size(raster_source_->GetSize());
  1414. // Clamp raster_source_size by max_viewport_dimension to avoid too small
  1415. // scale for huge layers for which the far from viewport area won't be
  1416. // rasterized and out of viewport area is rasterized in low priority.
  1417. gfx::SizeF max_visible_bounds(
  1418. std::min(raster_source_size.width(), max_viewport_dimension),
  1419. std::min(raster_source_size.height(), max_viewport_dimension));
  1420. gfx::SizeF max_visible_bounds_at_max_scale =
  1421. gfx::ScaleSize(max_visible_bounds, raster_contents_scale_.x(),
  1422. raster_contents_scale_.y());
  1423. float maximum_area = max_visible_bounds_at_max_scale.width() *
  1424. max_visible_bounds_at_max_scale.height();
  1425. // Clamp the scale to make the rastered content not larger than the viewport.
  1426. if (UNLIKELY(maximum_area > squared_viewport_area)) {
  1427. raster_contents_scale_.Scale(
  1428. 1.f / std::sqrt(maximum_area / squared_viewport_area));
  1429. }
  1430. }
  1431. void PictureLayerImpl::CleanUpTilingsOnActiveLayer(
  1432. const std::vector<PictureLayerTiling*>& used_tilings) {
  1433. DCHECK(layer_tree_impl()->IsActiveTree());
  1434. if (tilings_->num_tilings() == 0)
  1435. return;
  1436. float min_acceptable_high_res_scale =
  1437. std::min(raster_contents_scale_key(), ideal_contents_scale_key());
  1438. float max_acceptable_high_res_scale =
  1439. std::max(raster_contents_scale_key(), ideal_contents_scale_key());
  1440. PictureLayerImpl* twin = GetPendingOrActiveTwinLayer();
  1441. if (twin && twin->CanHaveTilings()) {
  1442. min_acceptable_high_res_scale = std::min(
  1443. {min_acceptable_high_res_scale, twin->raster_contents_scale_key(),
  1444. twin->ideal_contents_scale_key()});
  1445. max_acceptable_high_res_scale = std::max(
  1446. {max_acceptable_high_res_scale, twin->raster_contents_scale_key(),
  1447. twin->ideal_contents_scale_key()});
  1448. }
  1449. PictureLayerTilingSet* twin_set = twin ? twin->tilings_.get() : nullptr;
  1450. tilings_->CleanUpTilings(min_acceptable_high_res_scale,
  1451. max_acceptable_high_res_scale, used_tilings,
  1452. twin_set);
  1453. }
  1454. float PictureLayerImpl::MinimumRasterContentsScaleForWillChangeTransform()
  1455. const {
  1456. DCHECK(AffectedByWillChangeTransformHint());
  1457. float native_scale = ideal_device_scale_ * ideal_page_scale_;
  1458. float ideal_scale = ideal_contents_scale_key();
  1459. // Clamp will-change: transform layers to be at least the native scale,
  1460. // unless the scale is too small to avoid too many tiles using too much tile
  1461. // memory.
  1462. if (ideal_scale < native_scale * kMinScaleRatioForWillChangeTransform) {
  1463. // Don't let the scale too small compared to the ideal scale.
  1464. return ideal_scale * kMinScaleRatioForWillChangeTransform;
  1465. }
  1466. return native_scale;
  1467. }
  1468. bool PictureLayerImpl::CalculateRasterTranslation(
  1469. gfx::Vector2dF& raster_translation) const {
  1470. // If this setting is set, the client (e.g. the Chromium UI) is sure that it
  1471. // can almost always align raster pixels to physical pixels, and doesn't care
  1472. // about temporary misalignment, so don't bother raster translation.
  1473. if (layer_tree_impl()->settings().layers_always_allowed_lcd_text)
  1474. return true;
  1475. // No need to use raster translation if there is no text.
  1476. if (!raster_source_ || !raster_source_->GetDisplayItemList() ||
  1477. !raster_source_->GetDisplayItemList()->has_draw_text_ops()) {
  1478. return false;
  1479. }
  1480. const gfx::Transform& screen_transform = ScreenSpaceTransform();
  1481. gfx::Transform draw_transform = DrawTransform();
  1482. if (!screen_transform.IsScaleOrTranslation() ||
  1483. !draw_transform.IsScaleOrTranslation()) {
  1484. return false;
  1485. }
  1486. // It is only useful to align the content space to the target space if their
  1487. // relative pixel ratio is some small rational number. Currently we only
  1488. // align if the relative pixel ratio is 1:1 (i.e. the scale components of
  1489. // both the screen transform and the draw transform are approximately the same
  1490. // as |raster_contents_scale_|). Good match if the maximum alignment error on
  1491. // a layer of size 10000px does not exceed 0.001px.
  1492. static constexpr float kPixelErrorThreshold = 0.001f;
  1493. static constexpr float kScaleErrorThreshold = kPixelErrorThreshold / 10000;
  1494. auto is_raster_scale = [this](const gfx::Transform& transform) -> bool {
  1495. // The matrix has the X scale at (0,0), and the Y scale at (1,1).
  1496. return std::abs(transform.matrix().rc(0, 0) - raster_contents_scale_.x()) <=
  1497. kScaleErrorThreshold &&
  1498. std::abs(transform.matrix().rc(1, 1) - raster_contents_scale_.y()) <=
  1499. kScaleErrorThreshold;
  1500. };
  1501. if (!is_raster_scale(screen_transform) || !is_raster_scale(draw_transform))
  1502. return false;
  1503. // Extract the fractional part of layer origin in the screen space and in the
  1504. // target space.
  1505. auto fraction = [](float f) -> float { return f - floorf(f); };
  1506. float screen_x_fraction = fraction(screen_transform.matrix().rc(0, 3));
  1507. float screen_y_fraction = fraction(screen_transform.matrix().rc(1, 3));
  1508. float target_x_fraction = fraction(draw_transform.matrix().rc(0, 3));
  1509. float target_y_fraction = fraction(draw_transform.matrix().rc(1, 3));
  1510. // If the origin is different in the screen space and in the target space,
  1511. // it means the render target is not aligned to physical pixels, and the
  1512. // text content will be blurry regardless of raster translation.
  1513. if (std::abs(screen_x_fraction - target_x_fraction) > kPixelErrorThreshold ||
  1514. std::abs(screen_y_fraction - target_y_fraction) > kPixelErrorThreshold) {
  1515. return false;
  1516. }
  1517. raster_translation = gfx::Vector2dF(target_x_fraction, target_y_fraction);
  1518. return true;
  1519. }
  1520. float PictureLayerImpl::MinimumContentsScale() const {
  1521. // If the contents scale is less than 1 / width (also for height),
  1522. // then it will end up having less than one pixel of content in that
  1523. // dimension. Bump the minimum contents scale up in this case to prevent
  1524. // this from happening.
  1525. int min_dimension = std::min(raster_source_->GetSize().width(),
  1526. raster_source_->GetSize().height());
  1527. return min_dimension ? 1.f / min_dimension : 1.f;
  1528. }
  1529. float PictureLayerImpl::MaximumContentsScale() const {
  1530. if (bounds().IsEmpty())
  1531. return 0;
  1532. // When mask tiling is disabled or the mask is single textured, masks can not
  1533. // have tilings that would become larger than the max_texture_size since they
  1534. // use a single tile for the entire tiling. Other layers can have tilings such
  1535. // that dimension * scale does not overflow.
  1536. float max_dimension = static_cast<float>(
  1537. is_backdrop_filter_mask_ ? layer_tree_impl()->max_texture_size()
  1538. : std::numeric_limits<int>::max());
  1539. int higher_dimension = std::max(bounds().width(), bounds().height());
  1540. float max_scale = max_dimension / higher_dimension;
  1541. // We require that multiplying the layer size by the contents scale and
  1542. // ceiling produces a value <= |max_dimension|. Because for large layer
  1543. // sizes floating point ambiguity may crop up, making the result larger or
  1544. // smaller than expected, we use a slightly smaller floating point value for
  1545. // the scale, to help ensure that the resulting content bounds will never end
  1546. // up larger than |max_dimension|.
  1547. return nextafterf(max_scale, 0.f);
  1548. }
  1549. void PictureLayerImpl::ResetRasterScale() {
  1550. raster_page_scale_ = 0.f;
  1551. raster_device_scale_ = 0.f;
  1552. raster_source_scale_ = gfx::Vector2dF(0.f, 0.f);
  1553. raster_contents_scale_ = gfx::Vector2dF(0.f, 0.f);
  1554. low_res_raster_contents_scale_ = 0.f;
  1555. directly_composited_image_default_raster_scale_ = 0.f;
  1556. }
  1557. bool PictureLayerImpl::CanHaveTilings() const {
  1558. if (!raster_source_)
  1559. return false;
  1560. if (raster_source_->IsSolidColor())
  1561. return false;
  1562. if (!draws_content())
  1563. return false;
  1564. if (!raster_source_->HasRecordings())
  1565. return false;
  1566. // If the |raster_source_| has a recording it should have non-empty bounds.
  1567. DCHECK(!raster_source_->GetSize().IsEmpty());
  1568. if (MaximumContentsScale() < MinimumContentsScale())
  1569. return false;
  1570. return true;
  1571. }
  1572. void PictureLayerImpl::SanityCheckTilingState() const {
  1573. #if DCHECK_IS_ON()
  1574. if (!CanHaveTilings()) {
  1575. DCHECK_EQ(0u, tilings_->num_tilings());
  1576. return;
  1577. }
  1578. if (tilings_->num_tilings() == 0)
  1579. return;
  1580. // We should only have one high res tiling.
  1581. DCHECK_EQ(1, tilings_->NumHighResTilings());
  1582. #endif
  1583. }
  1584. float PictureLayerImpl::MaximumTilingContentsScale() const {
  1585. float max_contents_scale = tilings_->GetMaximumContentsScale();
  1586. return std::max(max_contents_scale, MinimumContentsScale());
  1587. }
  1588. std::unique_ptr<PictureLayerTilingSet>
  1589. PictureLayerImpl::CreatePictureLayerTilingSet() {
  1590. const LayerTreeSettings& settings = layer_tree_impl()->settings();
  1591. return PictureLayerTilingSet::Create(
  1592. IsActive() ? ACTIVE_TREE : PENDING_TREE, this,
  1593. settings.tiling_interest_area_padding,
  1594. layer_tree_impl()->use_gpu_rasterization()
  1595. ? settings.gpu_rasterization_skewport_target_time_in_seconds
  1596. : settings.skewport_target_time_in_seconds,
  1597. settings.skewport_extrapolation_limit_in_screen_pixels,
  1598. settings.max_preraster_distance_in_screen_pixels);
  1599. }
  1600. void PictureLayerImpl::UpdateIdealScales() {
  1601. DCHECK(CanHaveTilings());
  1602. float min_contents_scale = MinimumContentsScale();
  1603. DCHECK_GT(min_contents_scale, 0.f);
  1604. ideal_device_scale_ = layer_tree_impl()->device_scale_factor();
  1605. ideal_page_scale_ = 1.f;
  1606. ideal_contents_scale_ = GetIdealContentsScale();
  1607. if (layer_tree_impl()->PageScaleTransformNode()) {
  1608. DCHECK(layer_tree_impl()->settings().is_for_scalable_page);
  1609. ideal_page_scale_ = IsAffectedByPageScale()
  1610. ? layer_tree_impl()->current_page_scale_factor()
  1611. : 1.f;
  1612. }
  1613. // This layer may be in a layer tree embedded in a hierarchy that has its own
  1614. // page scale factor. We represent that here as 'external_page_scale_factor',
  1615. // a value that affects raster scale in the same way that page_scale_factor
  1616. // does, but doesn't affect any geometry calculations. In a normal main frame,
  1617. // fenced frame, or OOPIF, only one of current or external page scale factor
  1618. // is ever used but not both. The only exception to this is a main frame in a
  1619. // portal or a guest view. In these cases we may have a
  1620. // current_page_scale_factor (e.g. due to a viewport <meta> tag) as well as an
  1621. // external_page_scale_factor coming from the page scale of its embedder page.
  1622. float external_page_scale_factor =
  1623. layer_tree_impl() ? layer_tree_impl()->external_page_scale_factor() : 1.f;
  1624. DCHECK(!layer_tree_impl() ||
  1625. layer_tree_impl()->settings().is_for_scalable_page ||
  1626. external_page_scale_factor == 1.f ||
  1627. layer_tree_impl()->current_page_scale_factor() == 1.f);
  1628. ideal_page_scale_ *= external_page_scale_factor;
  1629. ideal_contents_scale_.Scale(external_page_scale_factor);
  1630. ideal_contents_scale_.SetToMax(
  1631. gfx::Vector2dF(min_contents_scale, min_contents_scale));
  1632. ideal_contents_scale_.SetToMin(
  1633. gfx::Vector2dF(kMaxIdealContentsScale, kMaxIdealContentsScale));
  1634. ideal_source_scale_ = {ideal_contents_scale_.x() / ideal_page_scale_,
  1635. ideal_contents_scale_.y() / ideal_page_scale_};
  1636. }
  1637. void PictureLayerImpl::GetDebugBorderProperties(SkColor4f* color,
  1638. float* width) const {
  1639. float device_scale_factor =
  1640. layer_tree_impl() ? layer_tree_impl()->device_scale_factor() : 1;
  1641. if (IsDirectlyCompositedImage()) {
  1642. *color = DebugColors::ImageLayerBorderColor();
  1643. *width = DebugColors::ImageLayerBorderWidth(device_scale_factor);
  1644. } else {
  1645. *color = DebugColors::TiledContentLayerBorderColor();
  1646. *width = DebugColors::TiledContentLayerBorderWidth(device_scale_factor);
  1647. }
  1648. }
  1649. void PictureLayerImpl::GetAllPrioritizedTilesForTracing(
  1650. std::vector<PrioritizedTile>* prioritized_tiles) const {
  1651. if (!tilings_)
  1652. return;
  1653. tilings_->GetAllPrioritizedTilesForTracing(prioritized_tiles);
  1654. }
  1655. void PictureLayerImpl::AsValueInto(
  1656. base::trace_event::TracedValue* state) const {
  1657. LayerImpl::AsValueInto(state);
  1658. state->SetDouble("ideal_contents_scale", ideal_contents_scale_key());
  1659. state->SetDouble("geometry_contents_scale", MaximumTilingContentsScale());
  1660. state->BeginArray("tilings");
  1661. tilings_->AsValueInto(state);
  1662. state->EndArray();
  1663. MathUtil::AddToTracedValue("tile_priority_rect",
  1664. viewport_rect_for_tile_priority_in_content_space_,
  1665. state);
  1666. MathUtil::AddToTracedValue("visible_rect", visible_layer_rect(), state);
  1667. state->SetString(
  1668. "lcd_text_disallowed_reason",
  1669. LCDTextDisallowedReasonToString(lcd_text_disallowed_reason_));
  1670. state->BeginArray("pictures");
  1671. raster_source_->AsValueInto(state);
  1672. state->EndArray();
  1673. state->BeginArray("invalidation");
  1674. invalidation_.AsValueInto(state);
  1675. state->EndArray();
  1676. state->BeginArray("coverage_tiles");
  1677. for (PictureLayerTilingSet::CoverageIterator iter(
  1678. tilings_.get(), MaximumTilingContentsScale(),
  1679. gfx::Rect(raster_source_->GetSize()), ideal_contents_scale_key());
  1680. iter; ++iter) {
  1681. state->BeginDictionary();
  1682. MathUtil::AddToTracedValue("geometry_rect", iter.geometry_rect(), state);
  1683. if (*iter)
  1684. viz::TracedValue::SetIDRef(*iter, state, "tile");
  1685. state->EndDictionary();
  1686. }
  1687. state->EndArray();
  1688. state->BeginDictionary("can_have_tilings_state");
  1689. state->SetBoolean("can_have_tilings", CanHaveTilings());
  1690. state->SetBoolean("raster_source_solid_color",
  1691. raster_source_->IsSolidColor());
  1692. state->SetBoolean("draws_content", draws_content());
  1693. state->SetBoolean("raster_source_has_recordings",
  1694. raster_source_->HasRecordings());
  1695. state->SetDouble("max_contents_scale", MaximumTilingContentsScale());
  1696. state->SetDouble("min_contents_scale", MinimumContentsScale());
  1697. state->EndDictionary();
  1698. state->BeginDictionary("raster_scales");
  1699. state->SetDouble("page_scale", raster_page_scale_);
  1700. state->SetDouble("device_scale", raster_device_scale_);
  1701. state->BeginArray("source_scale");
  1702. state->AppendDouble(raster_source_scale_.x());
  1703. state->AppendDouble(raster_source_scale_.y());
  1704. state->EndArray();
  1705. state->BeginArray("contents_scale");
  1706. state->AppendDouble(raster_contents_scale_.x());
  1707. state->AppendDouble(raster_contents_scale_.y());
  1708. state->EndArray();
  1709. state->SetDouble("low_res_contents_scale", low_res_raster_contents_scale_);
  1710. state->EndDictionary();
  1711. state->BeginDictionary("ideal_scales");
  1712. state->SetDouble("page_scale", ideal_page_scale_);
  1713. state->SetDouble("device_scale", ideal_device_scale_);
  1714. state->BeginArray("source_scale");
  1715. state->AppendDouble(ideal_source_scale_.x());
  1716. state->AppendDouble(ideal_source_scale_.y());
  1717. state->EndArray();
  1718. state->BeginArray("contents_scale");
  1719. state->AppendDouble(ideal_contents_scale_.x());
  1720. state->AppendDouble(ideal_contents_scale_.y());
  1721. state->EndArray();
  1722. state->EndDictionary();
  1723. }
  1724. size_t PictureLayerImpl::GPUMemoryUsageInBytes() const {
  1725. return tilings_->GPUMemoryUsageInBytes();
  1726. }
  1727. void PictureLayerImpl::RunMicroBenchmark(MicroBenchmarkImpl* benchmark) {
  1728. benchmark->RunOnLayer(this);
  1729. }
  1730. bool PictureLayerImpl::IsOnActiveOrPendingTree() const {
  1731. return !layer_tree_impl()->IsRecycleTree();
  1732. }
  1733. bool PictureLayerImpl::HasValidTilePriorities() const {
  1734. return IsOnActiveOrPendingTree() &&
  1735. (contributes_to_drawn_render_surface() || raster_even_if_not_drawn());
  1736. }
  1737. PictureLayerImpl::ImageInvalidationResult
  1738. PictureLayerImpl::InvalidateRegionForImages(
  1739. const PaintImageIdFlatSet& images_to_invalidate) {
  1740. if (!raster_source_ || !raster_source_->GetDisplayItemList() ||
  1741. raster_source_->GetDisplayItemList()->discardable_image_map().empty()) {
  1742. return ImageInvalidationResult::kNoImages;
  1743. }
  1744. InvalidationRegion image_invalidation;
  1745. for (auto image_id : images_to_invalidate) {
  1746. const auto& rects = raster_source_->GetDisplayItemList()
  1747. ->discardable_image_map()
  1748. .GetRectsForImage(image_id);
  1749. for (const auto& r : rects.container())
  1750. image_invalidation.Union(r);
  1751. }
  1752. Region invalidation;
  1753. image_invalidation.Swap(&invalidation);
  1754. if (invalidation.IsEmpty())
  1755. return ImageInvalidationResult::kNoInvalidation;
  1756. // Note: We can use a rect here since this is only used to track damage for a
  1757. // frame and not raster invalidation.
  1758. UnionUpdateRect(invalidation.bounds());
  1759. invalidation_.Union(invalidation);
  1760. tilings_->Invalidate(invalidation);
  1761. // TODO(crbug.com/303943): SetNeedsPushProperties() would be needed here if
  1762. // PictureLayerImpl didn't always push properties every activation.
  1763. return ImageInvalidationResult::kInvalidated;
  1764. }
  1765. void PictureLayerImpl::SetPaintWorkletRecord(
  1766. scoped_refptr<const PaintWorkletInput> input,
  1767. sk_sp<PaintRecord> record) {
  1768. DCHECK(paint_worklet_records_.find(input) != paint_worklet_records_.end());
  1769. paint_worklet_records_[input].second = std::move(record);
  1770. }
  1771. void PictureLayerImpl::RegisterAnimatedImages() {
  1772. if (!raster_source_ || !raster_source_->GetDisplayItemList())
  1773. return;
  1774. auto* controller = layer_tree_impl()->image_animation_controller();
  1775. const auto& metadata = raster_source_->GetDisplayItemList()
  1776. ->discardable_image_map()
  1777. .animated_images_metadata();
  1778. for (const auto& data : metadata) {
  1779. // Only update the metadata from updated recordings received from a commit.
  1780. if (layer_tree_impl()->IsSyncTree())
  1781. controller->UpdateAnimatedImage(data);
  1782. controller->RegisterAnimationDriver(data.paint_image_id, this);
  1783. }
  1784. }
  1785. void PictureLayerImpl::UnregisterAnimatedImages() {
  1786. if (!raster_source_ || !raster_source_->GetDisplayItemList())
  1787. return;
  1788. auto* controller = layer_tree_impl()->image_animation_controller();
  1789. const auto& metadata = raster_source_->GetDisplayItemList()
  1790. ->discardable_image_map()
  1791. .animated_images_metadata();
  1792. for (const auto& data : metadata)
  1793. controller->UnregisterAnimationDriver(data.paint_image_id, this);
  1794. }
  1795. void PictureLayerImpl::SetPaintWorkletInputs(
  1796. const std::vector<DiscardableImageMap::PaintWorkletInputWithImageId>&
  1797. inputs) {
  1798. // PaintWorklets are not supported when committing directly to the active
  1799. // tree, so in that case the |inputs| should always be empty.
  1800. DCHECK(layer_tree_impl()->IsPendingTree() || inputs.empty());
  1801. bool had_paint_worklets = !paint_worklet_records_.empty();
  1802. PaintWorkletRecordMap new_records;
  1803. for (const auto& input_with_id : inputs) {
  1804. const auto& input = input_with_id.first;
  1805. const auto& paint_image_id = input_with_id.second;
  1806. auto it = new_records.find(input);
  1807. // We should never have multiple PaintImages sharing the same paint worklet.
  1808. DCHECK(it == new_records.end() || it->second.first == paint_image_id);
  1809. // Attempt to re-use an existing PaintRecord if possible.
  1810. new_records[input] = std::make_pair(
  1811. paint_image_id, std::move(paint_worklet_records_[input].second));
  1812. }
  1813. paint_worklet_records_.swap(new_records);
  1814. // The pending tree tracks which PictureLayerImpls have PaintWorkletInputs as
  1815. // an optimization to avoid walking all picture layers.
  1816. bool has_paint_worklets = !paint_worklet_records_.empty();
  1817. if ((has_paint_worklets != had_paint_worklets) &&
  1818. layer_tree_impl()->IsPendingTree()) {
  1819. // TODO(xidachen): We don't need additional tracking on LayerTreeImpl. The
  1820. // tracking in AnimatedPaintWorkletTracker should be enough.
  1821. layer_tree_impl()->NotifyLayerHasPaintWorkletsChanged(this,
  1822. has_paint_worklets);
  1823. }
  1824. if (layer_tree_impl()->IsPendingTree()) {
  1825. layer_tree_impl()
  1826. ->paint_worklet_tracker()
  1827. .UpdatePaintWorkletInputProperties(inputs, this);
  1828. }
  1829. }
  1830. void PictureLayerImpl::InvalidatePaintWorklets(
  1831. const PaintWorkletInput::PropertyKey& key) {
  1832. for (auto& entry : paint_worklet_records_) {
  1833. const std::vector<PaintWorkletInput::PropertyKey>& prop_ids =
  1834. entry.first->GetPropertyKeys();
  1835. // If the PaintWorklet depends on the property whose value was changed by
  1836. // the animation system, then invalidate its associated PaintRecord so that
  1837. // we can repaint the PaintWorklet during impl side invalidation.
  1838. if (base::Contains(prop_ids, key))
  1839. entry.second.second = nullptr;
  1840. }
  1841. }
  1842. gfx::ContentColorUsage PictureLayerImpl::GetContentColorUsage() const {
  1843. auto display_item_list = raster_source_->GetDisplayItemList();
  1844. if (!display_item_list)
  1845. return gfx::ContentColorUsage::kSRGB;
  1846. return display_item_list->discardable_image_map().content_color_usage();
  1847. }
  1848. } // namespace cc