From c4c545215ad9ef09fd14c1cd9e5d078eae0889f8 Mon Sep 17 00:00:00 2001 From: Jonah Williams Date: Fri, 25 Oct 2024 09:27:51 -0700 Subject: [PATCH] Support backdrop key in flutter framework. (#157278) The backdrop key functionality allows multiple backdrop filters to share the same input filter, dramatically improving raster performance. This is only supported on the Impeller backend. The backdrop key class allocates a new int from a static and passes this to the engine layer. with 64 bit integers, we can allocate many backdrop filter ids per frame and never run out. See also: https://github.com/flutter/flutter/issues/156455 ```dart import 'dart:math'; import 'dart:ui'; import 'package:flutter/material.dart'; final _random = Random(); void main() => runApp(const BackdropFilterDemo()); class BackdropFilterDemo extends StatelessWidget { const BackdropFilterDemo({super.key}); static final listKey = BackdropKey(); static final overlayKey = BackdropKey(); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.white, body: Stack( children: [ ListView.builder( itemCount: 120, // 60 pairs of red and blue containers itemBuilder: (context, index) { return Container( height: 100, color: index % 2 == 0 ? Colors.red : Colors.blue, ); }, ), Center( child: Container( width: 400, height: 400, decoration: BoxDecoration( border: Border.all(color: Colors.black), ), child: Image.network('https://picsum.photos/400'), ), ), ListView.separated( separatorBuilder: (_, __) => const SizedBox(height: 8), itemBuilder: (context, index) => BlurEffect( backdropKey: listKey, child: SizedBox( height: 50, child: Center( child: Text(index.toString(), style: const TextStyle(color: Colors.white)), ), ), ), itemCount: 200, ), Positioned.fill( bottom: null, child: BlurEffect( backdropKey: overlayKey, child: Padding( padding: EdgeInsets.only( top: MediaQuery.of(context).viewPadding.top, ), child: const SizedBox(height: 45), ), ), ), Positioned.fill( top: null, child: BlurEffect( backdropKey: overlayKey, child: Padding( padding: EdgeInsets.only( top: MediaQuery.of(context).viewPadding.bottom, ), child: const SizedBox(height: 50), ), ), ), ], ), ), ); } } class BlurEffect extends StatelessWidget { final Widget child; const BlurEffect({ required this.child, required this.backdropKey, super.key, }); final BackdropKey backdropKey; @override Widget build(BuildContext context) { return ClipRect( child: BackdropFilter( backdropKey: backdropKey, filter: ImageFilter.blur( sigmaX: 40, sigmaY: 40, // tileMode: TileMode.mirror, ), child: DecoratedBox( decoration: BoxDecoration(color: Colors.black.withOpacity(.65)), child: child, ), ), ); } } ``` ### Skia ### Impeller --- packages/flutter/lib/src/rendering/layer.dart | 40 +++++++ .../flutter/lib/src/rendering/proxy_box.dart | 16 +++ packages/flutter/lib/src/widgets/basic.dart | 112 +++++++++++++++++- .../test/widgets/backdrop_filter_test.dart | 96 +++++++++++++++ 4 files changed, 261 insertions(+), 3 deletions(-) diff --git a/packages/flutter/lib/src/rendering/layer.dart b/packages/flutter/lib/src/rendering/layer.dart index 32946d3738..e099925f31 100644 --- a/packages/flutter/lib/src/rendering/layer.dart +++ b/packages/flutter/lib/src/rendering/layer.dart @@ -2193,6 +2193,28 @@ class ShaderMaskLayer extends ContainerLayer { } } +/// A backdrop key uniquely identifies the backdrop that a [BackdropFilterLayer] +/// samples from. +/// +/// When multiple backdrop filters share the same key, the Flutter engine can +/// more efficiently perform the backdrop operations. +/// +/// Instead of using a backdrop key directly, consider using a [BackdropGroup] +/// and the [BackdropFilter.grouped] constructor. The framework will +/// automatically group child backdrop filters that use the `.grouped` +/// constructor when they are placed as children of a [BackdropGroup]. +/// +/// For more information, see [BackdropFilter]. +@immutable +final class BackdropKey { + /// Create a new [BackdropKey]. + BackdropKey() : _key = _nextKey++; + + static int _nextKey = 0; + + final int _key; +} + /// A composited layer that applies a filter to the existing contents of the scene. class BackdropFilterLayer extends ContainerLayer { /// Creates a backdrop filter layer. @@ -2237,6 +2259,22 @@ class BackdropFilterLayer extends ContainerLayer { } } + /// The backdrop key that identifies the [BackdropGroup] this filter will apply to. + /// + /// The default value for the backdrop key is `null`, meaning that it's not + /// part of a [BackdropGroup]. + /// + /// The scene must be explicitly recomposited after this property is changed + /// (as described at [Layer]). + BackdropKey? get backdropKey => _backdropKey; + BackdropKey? _backdropKey; + set backdropKey(BackdropKey? value) { + if (value != _backdropKey) { + _backdropKey = value; + markNeedsAddToScene(); + } + } + @override void addToScene(ui.SceneBuilder builder) { assert(filter != null); @@ -2244,6 +2282,7 @@ class BackdropFilterLayer extends ContainerLayer { filter!, blendMode: blendMode, oldLayer: _engineLayer as ui.BackdropFilterEngineLayer?, + backdropId: _backdropKey?._key ); addChildrenToScene(builder); builder.pop(); @@ -2254,6 +2293,7 @@ class BackdropFilterLayer extends ContainerLayer { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('filter', filter)); properties.add(EnumProperty('blendMode', blendMode)); + properties.add(IntProperty('backdropKey', _backdropKey?._key)); } } diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index cde0c4cfb1..b3f4c37a32 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -1213,10 +1213,12 @@ class RenderBackdropFilter extends RenderProxyBox { required ui.ImageFilter filter, BlendMode blendMode = BlendMode.srcOver, bool enabled = true, + BackdropKey? backdropKey, }) : _filter = filter, _enabled = enabled, _blendMode = blendMode, + _backdropKey = backdropKey, super(child); @override @@ -1261,6 +1263,19 @@ class RenderBackdropFilter extends RenderProxyBox { _blendMode = value; markNeedsPaint(); } + /// The backdrop key that identifies the [BackdropGroup] this filter will + /// read from. + /// + /// The default value for the backdrop key is `null`. + BackdropKey? get backdropKey => _backdropKey; + BackdropKey? _backdropKey; + set backdropKey(BackdropKey? value) { + if (value == _backdropKey) { + return; + } + _backdropKey = value; + markNeedsPaint(); + } @override bool get alwaysNeedsCompositing => child != null; @@ -1277,6 +1292,7 @@ class RenderBackdropFilter extends RenderProxyBox { layer ??= BackdropFilterLayer(); layer!.filter = _filter; layer!.blendMode = _blendMode; + layer!.backdropKey = _backdropKey; context.pushLayer(layer!, super.paint, offset); assert(() { layer!.debugCreator = debugCreator; diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index 7b2e53e11b..bcb9e0693b 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -36,6 +36,7 @@ export 'package:flutter/rendering.dart' show AlignmentGeometryTween, AlignmentTween, Axis, + BackdropKey, BoxConstraints, BoxConstraintsTransform, CrossAxisAlignment, @@ -466,6 +467,34 @@ class ShaderMask extends SingleChildRenderObjectWidget { } } +/// A widget that establishes a shared backdrop layer for all child [BackdropFilter] +/// widgets that opt into using it. +/// +/// Sharing a backdrop filter layer will improve the performance of multiple +/// backdrop filters. To opt into using a shared [BackdropGroup], the special +/// [BackdropFilter.grouped] constructor must be used. +class BackdropGroup extends InheritedWidget { + /// Create a new [BackdropGroup] widget. + BackdropGroup({ + super.key, + required super.child, + BackdropKey? backdropKey, + }) : backdropKey = backdropKey ?? BackdropKey(); + + /// The backdrop key this backdrop group will use with shared child layers. + final BackdropKey backdropKey; + + @override + bool updateShouldNotify(covariant BackdropGroup oldWidget) { + return oldWidget.backdropKey != backdropKey; + } + + /// Look up the nearest [BackdropGroup], or `null` if there is not one. + static BackdropGroup? of(BuildContext context) { + return context.dependOnInheritedWidgetOfExactType(); + } +} + /// A widget that applies a filter to the existing painted content and then /// paints [child]. /// @@ -485,6 +514,48 @@ class ShaderMask extends SingleChildRenderObjectWidget { /// html renderer for web applications. /// {@endtemplate} /// +/// Multiple backdrop filters can be combined into a single rendering operation +/// by the Flutter engine if these backdrop filters widgets all share a common +/// [BackdropKey]. The backdrop key uniquely identifies the input for a backdrop +/// filter, and when shared, indicates the filtering can be performed once. This +/// can significantly reduce the overhead of using multiple backdrop filters in +/// a scene. The key can either be provided manually via the `backdropKey` +/// constructor parameter or looked up from a [BackdropGroup] inherited widget +/// via the `.grouped` constructor. +/// +/// Backdrop filters that overlap with each other should not use the same +/// backdrop key, otherwise the results may look as if only one filter is +/// applied in the overlapping regions. +/// +/// The following snippet demonstrates how to use the backdrop key to allow each +/// list item to have an efficient blur. The engine will perform only one +/// backdrop blur but the results will be visually identical to multiple blurs. +/// +/// ```dart +/// Widget build(BuildContext context) { +/// return BackdropGroup( +/// child: ListView.builder( +/// itemCount: 60, +/// itemBuilder: (BuildContext context, int index) { +/// return ClipRect( +/// child: BackdropFilter.grouped( +/// filter: ui.ImageFilter.blur( +/// sigmaX: 40, +/// sigmaY: 40, +/// ), +/// child: Container( +/// color: Colors.black.withOpacity(0.2), +/// height: 200, +/// child: const Text('Blur item'), +/// ), +/// ), +/// ); +/// } +/// ), +/// ); +/// } +/// ``` +/// /// {@youtube 560 315 https://www.youtube.com/watch?v=dYRs7Q1vfYI} /// /// {@tool snippet} @@ -582,7 +653,26 @@ class BackdropFilter extends SingleChildRenderObjectWidget { super.child, this.blendMode = BlendMode.srcOver, this.enabled = true, - }); + this.backdropGroupKey, + }) : _useSharedKey = false; + + /// Creates a backdrop filter that groups itself with the nearest parent + /// [BackdropGroup]. + /// + /// The [blendMode] argument will default to [BlendMode.srcOver] and must not be + /// null if provided. + /// + /// This constructor will automatically look up the nearest [BackdropGroup] + /// and will share the backdrop input with sibling and child [BackdropFilter] + /// widgets. + const BackdropFilter.grouped({ + super.key, + required this.filter, + super.child, + this.blendMode = BlendMode.srcOver, + this.enabled = true, + }) : backdropGroupKey = null, + _useSharedKey = true; /// The image filter to apply to the existing painted content before painting the child. /// @@ -603,9 +693,24 @@ class BackdropFilter extends SingleChildRenderObjectWidget { /// type for performance reasons. final bool enabled; + /// The [BackdropKey] that identifies the backdrop this filter will apply to. + /// + /// The default value for the backdrop key is `null`. + final BackdropKey? backdropGroupKey; + + // Whether to look up the [backdropKey] from a parent [BackdropGroup]. + final bool _useSharedKey; + + BackdropKey? _getBackdropGroupKey(BuildContext context) { + if (_useSharedKey) { + return BackdropGroup.of(context)?.backdropKey; + } + return backdropGroupKey; + } + @override RenderBackdropFilter createRenderObject(BuildContext context) { - return RenderBackdropFilter(filter: filter, blendMode: blendMode, enabled: enabled); + return RenderBackdropFilter(filter: filter, blendMode: blendMode, enabled: enabled, backdropKey: _getBackdropGroupKey(context)); } @override @@ -613,7 +718,8 @@ class BackdropFilter extends SingleChildRenderObjectWidget { renderObject ..filter = filter ..enabled = enabled - ..blendMode = blendMode; + ..blendMode = blendMode + ..backdropKey = _getBackdropGroupKey(context); } } diff --git a/packages/flutter/test/widgets/backdrop_filter_test.dart b/packages/flutter/test/widgets/backdrop_filter_test.dart index a112fe9e66..b257dc1f45 100644 --- a/packages/flutter/test/widgets/backdrop_filter_test.dart +++ b/packages/flutter/test/widgets/backdrop_filter_test.dart @@ -10,9 +10,105 @@ library; import 'dart:ui'; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { + testWidgets('Backdrop key is passed to backdrop Layer', (WidgetTester tester) async { + final BackdropKey backdropKey = BackdropKey(); + + Widget build({required bool enableKeys}) { + return MaterialApp( + home: Scaffold( + body: ListView( + children: [ + ClipRect( + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 40, sigmaY: 40), + backdropGroupKey: enableKeys ? backdropKey : null, + child: Container( + color: Colors.black.withAlpha(40), + height: 200, + child: const Text('Item 1'), + ), + ), + ), + ClipRect( + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 40, sigmaY: 40), + backdropGroupKey: enableKeys ? backdropKey : null, + child: Container( + color: Colors.black.withAlpha(40), + height: 200, + child: const Text('Item 1'), + ), + ), + ), + ], + ) + ), + ); + } + + await tester.pumpWidget(build(enableKeys: true)); + + List layers = tester.layers.whereType().toList(); + + expect(layers.length, 2); + expect(layers[0].backdropKey, backdropKey); + expect(layers[1].backdropKey, backdropKey); + + await tester.pumpWidget(build(enableKeys: false)); + + layers = tester.layers.whereType().toList(); + + expect(layers.length, 2); + expect(layers[0].backdropKey, null); + expect(layers[1].backdropKey, null); + }); + + testWidgets('Backdrop key is passed to backdrop Layer via backdrop group', (WidgetTester tester) async { + Widget build() { + return MaterialApp( + home: Scaffold( + body: BackdropGroup( + child: ListView( + children: [ + ClipRect( + child: BackdropFilter.grouped( + filter: ImageFilter.blur(sigmaX: 40, sigmaY: 40), + child: Container( + color: Colors.black.withAlpha(40), + height: 200, + child: const Text('Item 1'), + ), + ), + ), + ClipRect( + child: BackdropFilter.grouped( + filter: ImageFilter.blur(sigmaX: 40, sigmaY: 40), + child: Container( + color: Colors.black.withAlpha(40), + height: 200, + child: const Text('Item 1'), + ), + ), + ), + ], + ) + ), + ), + ); + } + + await tester.pumpWidget(build()); + + final List layers = tester.layers.whereType().toList(); + + expect(layers.length, 2); + expect(layers[0].backdropKey, layers[1].backdropKey); + }); + testWidgets("Material2 - BackdropFilter's cull rect does not shrink", (WidgetTester tester) async { await tester.pumpWidget( MaterialApp(