diff --git a/engine/src/flutter/lib/web_ui/dev/goldens_lock.yaml b/engine/src/flutter/lib/web_ui/dev/goldens_lock.yaml index c8a0aa3e31..c89bd196e6 100644 --- a/engine/src/flutter/lib/web_ui/dev/goldens_lock.yaml +++ b/engine/src/flutter/lib/web_ui/dev/goldens_lock.yaml @@ -1,2 +1,2 @@ repository: https://github.com/flutter/goldens.git -revision: 56a0296bba9bd614b4e16173f7ec7cfc2b2b284d +revision: 1e65186b73045bb1034ade9f12b810caabd00462 diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/layer.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/layer.dart index 0ca0a2f162..c8b4c32091 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/layer.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/layer.dart @@ -388,60 +388,7 @@ class PhysicalShapeLayer extends ContainerLayer @override void preroll(PrerollContext prerollContext, Matrix4 matrix) { prerollChildren(prerollContext, matrix); - - paintBounds = _path.getBounds(); - if (_elevation == 0.0) { - // No need to extend the paint bounds if there is no shadow. - return; - } else { - // Add some margin to the paint bounds to leave space for the shadow. - // We fill this whole region and clip children to it so we don't need to - // join the child paint bounds. - // The offset is calculated as follows: - - // .--- (kLightRadius) - // -------/ (light) - // | / - // | / - // |/ - // |O - // /| (kLightHeight) - // / | - // / | - // / | - // / | - // ------------- (layer) - // /| | - // / | | (elevation) - // A / | |B - // ------------------------------------------------ (canvas) - // --- (extent of shadow) - // - // E = lt } t = (r + w/2)/h - // } => - // r + w/2 = ht } E = (l/h)(r + w/2) - // - // Where: E = extent of shadow - // l = elevation of layer - // r = radius of the light source - // w = width of the layer - // h = light height - // t = tangent of AOB, i.e., multiplier for elevation to extent - final double devicePixelRatio = ui.window.devicePixelRatio; - - final double radius = kLightRadius * devicePixelRatio; - // tangent for x - double tx = (radius + paintBounds.width * 0.5) / kLightHeight; - // tangent for y - double ty = (radius + paintBounds.height * 0.5) / kLightHeight; - - paintBounds = ui.Rect.fromLTRB( - paintBounds.left - tx, - paintBounds.top - ty, - paintBounds.right + tx, - paintBounds.bottom + ty, - ); - } + paintBounds = computeSkShadowBounds(_path, _elevation, ui.window.devicePixelRatio, matrix); } @override diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/util.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/util.dart index 8e96c3ea19..ed99cb7a1b 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/util.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/util.dart @@ -34,6 +34,113 @@ ui.TextPosition fromPositionWithAffinity(SkTextPosition positionWithAffinity) { ); } +/// Shadow flag constants derived from Skia's SkShadowFlags.h. +class SkiaShadowFlags { + /// The occluding object is opaque, making the part of the shadow under the + /// occluder invisible. This allows some optimizations because some parts of + /// the shadow do not need to be accurate. + static const int kNone_ShadowFlag = 0x00; + + /// The occluding object is not opaque, making the part of the shadow under the + /// occluder visible. This requires that the shadow is rendered more accurately + /// and therefore is slightly more expensive. + static const int kTransparentOccluder_ShadowFlag = 0x01; + + /// Light position represents a direction, light radius is blur radius at + /// elevation 1. + /// + /// This makes the shadow to have a fixed position relative to the shape that + /// casts it. + static const int kDirectionalLight_ShadowFlag = 0x04; + + /// Complete value for the `flags` argument for opaque occluder. + static const int kDefaultShadowFlags = kDirectionalLight_ShadowFlag | kNone_ShadowFlag; + + /// Complete value for the `flags` argument for transparent occluder. + static const int kTransparentOccluderShadowFlags = kDirectionalLight_ShadowFlag | kTransparentOccluder_ShadowFlag; +} + +// These numbers have been chosen empirically to give a result closest to the +// material spec. +const double ckShadowAmbientAlpha = 0.039; +const double ckShadowSpotAlpha = 0.25; +const double ckShadowLightRadius = 1.1; +const double ckShadowLightHeight = 600.0; +const double ckShadowLightXOffset = 0; +const double ckShadowLightYOffset = -450; +const double ckShadowLightXTangent = ckShadowLightXOffset / ckShadowLightHeight; +const double ckShadowLightYTangent = ckShadowLightYOffset / ckShadowLightHeight; + +/// Computes the smallest rectangle that contains the shadow. +// Most of this logic is borrowed from SkDrawShadowInfo.cpp in Skia. +// TODO(yjbanov): switch to SkDrawShadowMetrics::GetLocalBounds when available +// See: +// - https://bugs.chromium.org/p/skia/issues/detail?id=11146 +// - https://github.com/flutter/flutter/issues/73492 +ui.Rect computeSkShadowBounds( + CkPath path, + double elevation, + double devicePixelRatio, + Matrix4 matrix, +) { + ui.Rect pathBounds = path.getBounds(); + + if (elevation == 0) { + return pathBounds; + } + + // For visual correctness the shadow offset and blur does not change with + // parent transforms. Therefore, in general case we have to first transform + // the shape bounds to device coordinates, then compute the shadow bounds, + // then transform the bounds back to local coordinates. However, if the + // transform is an identity or translation (a common case), we can skip this + // step. With directional lighting translation does not affect the size or + // shape of the shadow. Skipping this step saves us two transformRects and + // one matrix inverse. + final bool isComplex = !matrix.isIdentityOrTranslation(); + if (isComplex) { + pathBounds = transformRect(matrix, pathBounds); + } + + double left = pathBounds.left; + double top = pathBounds.top; + double right = pathBounds.right; + double bottom = pathBounds.bottom; + + final double ambientBlur = ambientBlurRadius(elevation); + final double spotBlur = ckShadowLightRadius * elevation; + final double spotOffsetX = -elevation * ckShadowLightXTangent; + final double spotOffsetY = -elevation * ckShadowLightYTangent; + + // The extra +1/-1 are to cover possible floating point errors. + left = left - 1 + (spotOffsetX - ambientBlur - spotBlur) * devicePixelRatio; + top = top - 1 + (spotOffsetY - ambientBlur - spotBlur) * devicePixelRatio; + right = right + 1 + (spotOffsetX + ambientBlur + spotBlur) * devicePixelRatio; + bottom = bottom + 1 + (spotOffsetY + ambientBlur + spotBlur) * devicePixelRatio; + + final ui.Rect shadowBounds = ui.Rect.fromLTRB(left, top, right, bottom); + + if (isComplex) { + final Matrix4 inverse = Matrix4.zero(); + // The inverse only makes sense if the determinat is non-zero. + if (inverse.copyInverse(matrix) != 0.0) { + return transformRect(inverse, shadowBounds); + } else { + return shadowBounds; + } + } else { + return shadowBounds; + } +} + +const double kAmbientHeightFactor = 1.0 / 128.0; +const double kAmbientGeomFactor = 64.0; +const double kMaxAmbientRadius = 300 * kAmbientHeightFactor * kAmbientGeomFactor; + +double ambientBlurRadius(double height) { + return math.min(height * kAmbientHeightFactor * kAmbientGeomFactor, kMaxAmbientRadius); +} + void drawSkShadow( SkCanvas skCanvas, CkPath path, @@ -42,17 +149,12 @@ void drawSkShadow( bool transparentOccluder, double devicePixelRatio, ) { - const double ambientAlpha = 0.039; - const double spotAlpha = 0.25; + final int flags = transparentOccluder + ? SkiaShadowFlags.kTransparentOccluderShadowFlags + : SkiaShadowFlags.kDefaultShadowFlags; - final int flags = transparentOccluder ? 0x01 : 0x00; - - final ui.Rect bounds = path.getBounds(); - final double shadowX = (bounds.left + bounds.right) / 2.0; - final double shadowY = bounds.top - 600.0; - - ui.Color inAmbient = color.withAlpha((color.alpha * ambientAlpha).round()); - ui.Color inSpot = color.withAlpha((color.alpha * spotAlpha).round()); + ui.Color inAmbient = color.withAlpha((color.alpha * ckShadowAmbientAlpha).round()); + ui.Color inSpot = color.withAlpha((color.alpha * ckShadowSpotAlpha).round()); final SkTonalColors inTonalColors = SkTonalColors( ambient: makeFreshSkColor(inAmbient), @@ -67,10 +169,10 @@ void drawSkShadow( Float32List(3) ..[2] = devicePixelRatio * elevation, Float32List(3) - ..[0] = shadowX - ..[1] = shadowY - ..[2] = devicePixelRatio * kLightHeight, - devicePixelRatio * kLightRadius, + ..[0] = ckShadowLightXOffset + ..[1] = ckShadowLightYOffset + ..[2] = devicePixelRatio * ckShadowLightHeight, + devicePixelRatio * ckShadowLightRadius, tonalColors.ambient, tonalColors.spot, flags, diff --git a/engine/src/flutter/lib/web_ui/test/canvaskit/canvas_golden_test.dart b/engine/src/flutter/lib/web_ui/test/canvaskit/canvas_golden_test.dart index ca957dbd36..b722916697 100644 --- a/engine/src/flutter/lib/web_ui/test/canvaskit/canvas_golden_test.dart +++ b/engine/src/flutter/lib/web_ui/test/canvaskit/canvas_golden_test.dart @@ -20,17 +20,15 @@ void main() { internalBootstrapBrowserTest(() => testMain); } -const ui.Rect region = const ui.Rect.fromLTRB(0, 0, 500, 250); +const ui.Rect kDefaultRegion = const ui.Rect.fromLTRB(0, 0, 500, 250); -Future matchPictureGolden(String goldenFile, CkPicture picture, - {bool write = false}) async { - final EnginePlatformDispatcher dispatcher = - ui.window.platformDispatcher as EnginePlatformDispatcher; +Future matchPictureGolden(String goldenFile, CkPicture picture, { ui.Rect region = kDefaultRegion, bool write = false }) async { + final EnginePlatformDispatcher dispatcher = ui.window.platformDispatcher as EnginePlatformDispatcher; final LayerSceneBuilder sb = LayerSceneBuilder(); sb.pushOffset(0, 0); sb.addPicture(ui.Offset.zero, picture); dispatcher.rasterizer!.draw(sb.build().layerTree); - await matchGoldenFile(goldenFile, region: region, write: write); + await matchGoldenFile(goldenFile, region: region, maxDiffRatePercent: 0.0, write: write); } void testMain() { @@ -43,24 +41,24 @@ void testMain() { reason: 'This test specifically tests non-recording canvas, which ' 'only works if FinalizationRegistry is available.'); final CkPictureRecorder recorder = CkPictureRecorder(); - final CkCanvas canvas = recorder.beginRecording(region); + final CkCanvas canvas = recorder.beginRecording(kDefaultRegion); expect(canvas.runtimeType, CkCanvas); drawTestPicture(canvas); await matchPictureGolden( - 'canvaskit_picture_original.png', recorder.endRecording()); + 'canvaskit_picture.png', recorder.endRecording()); }); test('renders using a recording canvas if weak refs are not supported', () async { browserSupportsFinalizationRegistry = false; final CkPictureRecorder recorder = CkPictureRecorder(); - final CkCanvas canvas = recorder.beginRecording(region); + final CkCanvas canvas = recorder.beginRecording(kDefaultRegion); expect(canvas, isA()); drawTestPicture(canvas); final CkPicture originalPicture = recorder.endRecording(); await matchPictureGolden( - 'canvaskit_picture_original.png', originalPicture); + 'canvaskit_picture.png', originalPicture); final ByteData originalPixels = await (await originalPicture.toImage(50, 50)).toByteData() @@ -78,10 +76,142 @@ void testMain() { as ByteData; await matchPictureGolden( - 'canvaskit_picture_restored.png', restoredPicture); + 'canvaskit_picture.png', restoredPicture); expect(restoredPixels.buffer.asUint8List(), originalPixels.buffer.asUint8List()); }); + + // Regression test for https://github.com/flutter/flutter/issues/51237 + // Draws a grid of shadows at different offsets. Prior to directional + // light the shadows would shift depending on the offset. With directional + // light the cells in the grid must look identical. + test('uses directional shadows', () async { + const ui.Rect region = ui.Rect.fromLTRB(0, 0, 820, 420); + final CkPicture picture = paintPicture(region, (CkCanvas canvas) { + final CkPath shape = CkPath() + ..addRect(const ui.Rect.fromLTRB(0, 0, 40, 40)); + final CkPaint shapePaint = CkPaint() + ..style = ui.PaintingStyle.stroke + ..strokeWidth = 1 + ..color = const ui.Color(0xFF009900); + final CkPaint shadowBoundsPaint = CkPaint() + ..style = ui.PaintingStyle.stroke + ..strokeWidth = 1 + ..color = const ui.Color(0xFF000099); + canvas.translate(20, 20); + + for (int row = 0; row < 5; row += 1) { + canvas.save(); + for (int col = 0; col < 10; col += 1) { + final double elevation = 2 * (col % 5).toDouble(); + canvas.drawShadow(shape, ui.Color(0xFFFF0000), elevation, true); + canvas.drawPath(shape, shapePaint); + + final PhysicalShapeLayer psl = PhysicalShapeLayer( + elevation, + const ui.Color(0xFF000000), + const ui.Color(0xFF000000), + shape, + ui.Clip.antiAlias, + ); + psl.preroll( + PrerollContext( + RasterCache(), + HtmlViewEmbedder(), + ), + Matrix4.identity(), + ); + canvas.drawRect(psl.paintBounds, shadowBoundsPaint); + + final CkParagraphBuilder pb = CkParagraphBuilder( + CkParagraphStyle(), + ); + pb.addText('$elevation'); + final CkParagraph p = pb.build(); + p.layout(const ui.ParagraphConstraints(width: 1000)); + canvas.drawParagraph(p, ui.Offset(20 - p.maxIntrinsicWidth / 2, 20 - p.height / 2)); + canvas.translate(80, 0); + } + canvas.restore(); + canvas.translate(0, 80); + } + }); + await matchPictureGolden('canvaskit_directional_shadows.png', picture, region: region); + }); + + test('computes shadow bounds correctly with parent transforms', () async { + const double rectSize = 50; + const double halfSize = rectSize / 2; + const double padding = 110; + const ui.Rect region = ui.Rect.fromLTRB( + 0, + 0, + (rectSize + padding) * 3 + padding, + (rectSize + padding) * 2 + padding, + ); + late List physicalShapeLayers; + + LayerTree buildTestScene({ required bool paintShadowBounds }) { + final Iterator? shadowBounds = paintShadowBounds + ? physicalShapeLayers.iterator : null; + physicalShapeLayers = []; + + final LayerSceneBuilder builder = LayerSceneBuilder(); + builder.pushOffset(padding + halfSize, padding + halfSize); + + final CkPath shape = CkPath() + ..addRect(const ui.Rect.fromLTRB(-halfSize, -halfSize, halfSize, halfSize)); + final CkPaint shadowBoundsPaint = CkPaint() + ..style = ui.PaintingStyle.stroke + ..strokeWidth = 1 + ..color = const ui.Color(0xFF000099); + + for (int row = 0; row < 2; row += 1) { + for (int col = 0; col < 3; col += 1) { + builder.pushOffset(col * (rectSize + padding), row * (rectSize + padding)); + builder.pushTransform(Float64List.fromList(Matrix4.rotationZ(row * math.pi / 4).storage)); + final double scale = 1 / (1 + col); + builder.pushTransform(Float64List.fromList(Matrix4.diagonal3Values(scale, scale, 1).storage)); + physicalShapeLayers.add(builder.pushPhysicalShape( + path: shape, + elevation: 6, + color: const ui.Color(0xFF009900), + shadowColor: const ui.Color(0xFF000000), + ) as PhysicalShapeLayer); + if (shadowBounds != null) { + shadowBounds.moveNext(); + final ui.Rect bounds = shadowBounds.current.paintBounds; + builder.addPicture(ui.Offset.zero, paintPicture(region, (CkCanvas canvas) { + canvas.drawRect(bounds, shadowBoundsPaint); + })); + } + builder.pop(); + builder.pop(); + builder.pop(); + builder.pop(); + } + } + builder.pop(); + return builder.build().layerTree; + } + + // Render the scene once without painting the shadow bounds just to + // preroll the scene to compute the shadow bounds. + buildTestScene(paintShadowBounds: false).rootLayer!.preroll( + PrerollContext( + RasterCache(), + HtmlViewEmbedder(), + ), + Matrix4.identity(), + ); + + // Render again, this time with the shadow bounds. + final LayerTree layerTree = buildTestScene(paintShadowBounds: true); + + final EnginePlatformDispatcher dispatcher = ui.window.platformDispatcher as EnginePlatformDispatcher; + dispatcher.rasterizer!.draw(layerTree); + await matchGoldenFile('canvaskit_shadow_bounds.png', region: region); + }); // TODO: https://github.com/flutter/flutter/issues/60040 // TODO: https://github.com/flutter/flutter/issues/71520 }, skip: isIosSafari || isFirefox); @@ -305,7 +435,7 @@ void drawTestPicture(CkCanvas canvas) { ..strokeWidth = 20; final CkPaint semitransparent = CkPaint()..color = ui.Color(0x66000000); - canvas.saveLayer(region, semitransparent); + canvas.saveLayer(kDefaultRegion, semitransparent); canvas.drawLine(ui.Offset(10, 10), ui.Offset(50, 50), thickStroke); canvas.drawLine(ui.Offset(50, 10), ui.Offset(10, 50), thickStroke); canvas.restore(); @@ -319,11 +449,11 @@ void drawTestPicture(CkCanvas canvas) { // To test saveLayerWithFilter we draw three circles with only the middle one // blurred using the layer image filter. canvas.translate(60, 0); - canvas.saveLayer(region, CkPaint()); + canvas.saveLayer(kDefaultRegion, CkPaint()); canvas.drawCircle(ui.Offset(30, 30), 10, CkPaint()); { canvas.saveLayerWithFilter( - region, ui.ImageFilter.blur(sigmaX: 5, sigmaY: 10)); + kDefaultRegion, ui.ImageFilter.blur(sigmaX: 5, sigmaY: 10)); canvas.drawCircle(ui.Offset(10, 10), 10, CkPaint()); canvas.drawCircle(ui.Offset(50, 50), 10, CkPaint()); canvas.restore();