[canvaskit] Round physical size to nearest whole number pixels (flutter/engine#52467)

The physical size is computed by multiplying the browser's `innerWidth`
and `innerHeight` by the `devicePixelRatio`. The physical size should be
an integer number of pixels. However, there may be some imprecision and
the result of the multiplication is not quite an integer. This change
rounds the physical size to integers before using them for drawing the
scene.

Fixes https://github.com/flutter/flutter/issues/144869

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide] and the [C++,
Objective-C, Java style guides].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I added new tests to check the change I am making or feature I am
adding, or the PR is [test-exempt]. See [testing the engine] for
instructions on writing and running engine tests.
- [x] I updated/added relevant documentation (doc comments with `///`).
- [x] I signed the [CLA].
- [x] All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel
on [Discord].

<!-- Links -->
[Contributor Guide]:
https://github.com/flutter/flutter/wiki/Tree-hygiene#overview
[Tree Hygiene]: https://github.com/flutter/flutter/wiki/Tree-hygiene
[test-exempt]:
https://github.com/flutter/flutter/wiki/Tree-hygiene#tests
[Flutter Style Guide]:
https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo
[C++, Objective-C, Java style guides]:
https://github.com/flutter/engine/blob/main/CONTRIBUTING.md#style
[testing the engine]:
https://github.com/flutter/flutter/wiki/Testing-the-engine
[CLA]: https://cla.developers.google.com/
[flutter/tests]: https://github.com/flutter/tests
[breaking change policy]:
https://github.com/flutter/flutter/wiki/Tree-hygiene#handling-breaking-changes
[Discord]: https://github.com/flutter/flutter/wiki/Chat
This commit is contained in:
Harry Terkelsen
2024-05-02 16:16:50 -07:00
committed by GitHub
parent 3892592ee1
commit b28f8f5c42
8 changed files with 122 additions and 64 deletions

View File

@@ -66,9 +66,9 @@ class HtmlViewEmbedder {
DisplayCanvas? debugBoundsCanvas;
/// The size of the frame, in physical pixels.
late ui.Size _frameSize;
late BitmapSize _frameSize;
set frameSize(ui.Size size) {
set frameSize(BitmapSize size) {
_frameSize = size;
}
@@ -90,7 +90,7 @@ class HtmlViewEmbedder {
void prerollCompositeEmbeddedView(int viewId, EmbeddedViewParams params) {
final CkPictureRecorder pictureRecorder = CkPictureRecorder();
pictureRecorder.beginRecording(ui.Offset.zero & _frameSize);
pictureRecorder.beginRecording(ui.Offset.zero & _frameSize.toSize());
_context.pictureRecordersCreatedDuringPreroll.add(pictureRecorder);
// Do nothing if the params didn't change.
@@ -390,7 +390,13 @@ class HtmlViewEmbedder {
debugBoundsCanvas ??= rasterizer.displayFactory.getCanvas();
final CkPictureRecorder boundsRecorder = CkPictureRecorder();
final CkCanvas boundsCanvas = boundsRecorder.beginRecording(
ui.Rect.fromLTWH(0, 0, _frameSize.width, _frameSize.height));
ui.Rect.fromLTWH(
0,
0,
_frameSize.width.toDouble(),
_frameSize.height.toDouble(),
),
);
final CkPaint platformViewBoundsPaint = CkPaint()
..color = const ui.Color.fromARGB(100, 0, 255, 0);
final CkPaint pictureBoundsPaint = CkPaint()

View File

@@ -7,6 +7,7 @@ import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../scene_painting.dart';
import '../util.dart';
import 'canvas.dart';
import 'canvaskit_api.dart';
import 'image.dart';
@@ -101,7 +102,7 @@ class CkPicture implements ScenePicture {
final Surface surface = CanvasKitRenderer.instance.pictureToImageSurface;
final CkSurface ckSurface = surface
.createOrUpdateSurface(ui.Size(width.toDouble(), height.toDouble()));
.createOrUpdateSurface(BitmapSize(width, height));
final CkCanvas ckCanvas = ckSurface.getCanvas();
ckCanvas.clear(const ui.Color(0x00000000));
ckCanvas.drawPicture(this);

View File

@@ -27,7 +27,7 @@ abstract class ViewRasterizer {
final RenderQueue queue = RenderQueue();
/// The size of the current frame being rasterized.
ui.Size currentFrameSize = ui.Size.zero;
BitmapSize currentFrameSize = BitmapSize.zero;
/// The context which is persisted between frames.
final CompositorContext context = CompositorContext();
@@ -50,11 +50,19 @@ abstract class ViewRasterizer {
return;
}
currentFrameSize = frameSize;
// The [frameSize] may be slightly imprecise if the `devicePixelRatio` isn't
// an integer. For example, is you zoom to 110% in Chrome on a Macbook, the
// `devicePixelRatio` is `2.200000047683716`, so when the physical size is
// computed by multiplying the logical size by the devie pixel ratio, the
// result is slightly imprecise as well. Nevertheless, the number should
// be close to an integer, so round the frame size to be more precice.
final BitmapSize bitmapSize = BitmapSize.fromSize(frameSize);
currentFrameSize = bitmapSize;
prepareToDraw();
viewEmbedder.frameSize = currentFrameSize;
final CkPictureRecorder pictureRecorder = CkPictureRecorder();
pictureRecorder.beginRecording(ui.Offset.zero & currentFrameSize);
pictureRecorder.beginRecording(ui.Offset.zero & currentFrameSize.toSize());
final Frame compositorFrame =
context.acquireFrame(pictureRecorder.recordingCanvas!, viewEmbedder);

View File

@@ -4,10 +4,9 @@
import 'dart:js_interop';
import 'package:ui/ui.dart' as ui;
import '../display.dart';
import '../dom.dart';
import '../util.dart';
import 'rasterizer.dart';
/// A visible (on-screen) canvas that can display bitmaps produced by CanvasKit
@@ -62,13 +61,6 @@ class RenderCanvas extends DisplayCanvas {
/// Sets the CSS size of the canvas so that canvas pixels are 1:1 with device
/// pixels.
///
/// The logical size of the canvas is not based on the size of the window
/// but on the size of the canvas, which, due to `ceil()` above, may not be
/// the same as the window. We do not round/floor/ceil the logical size as
/// CSS pixels can contain more than one physical pixel and therefore to
/// match the size of the window precisely we use the most precise floating
/// point value we can get.
void _updateLogicalHtmlCanvasSize() {
final double devicePixelRatio =
EngineFlutterDisplay.instance.devicePixelRatio;
@@ -85,14 +77,14 @@ class RenderCanvas extends DisplayCanvas {
/// The canvas will be resized to accomodate the bitmap immediately before
/// rendering it.
void render(DomImageBitmap bitmap) {
_ensureSize(ui.Size(bitmap.width.toDartDouble, bitmap.height.toDartDouble));
_ensureSize(BitmapSize(bitmap.width.toDartInt, bitmap.height.toDartInt));
renderContext.transferFromImageBitmap(bitmap);
}
void renderWithNoBitmapSupport(
DomCanvasImageSource imageSource,
int sourceHeight,
ui.Size size,
BitmapSize size,
) {
_ensureSize(size);
renderContext2d.drawImage(
@@ -109,11 +101,10 @@ class RenderCanvas extends DisplayCanvas {
}
/// Ensures that this canvas can draw a frame of the given [size].
void _ensureSize(ui.Size size) {
void _ensureSize(BitmapSize size) {
// Check if the frame is the same size as before, and if so, we don't need
// to resize the canvas.
if (size.width.ceil() == _pixelWidth &&
size.height.ceil() == _pixelHeight) {
if (size.width == _pixelWidth && size.height == _pixelHeight) {
// The existing canvas doesn't need to be resized (unless the device pixel
// ratio changed).
if (EngineFlutterDisplay.instance.devicePixelRatio !=
@@ -127,8 +118,8 @@ class RenderCanvas extends DisplayCanvas {
// the frame. We cannot allow the canvas to be larger than the screen
// because then when we call `transferFromImageBitmap()` the bitmap will
// be scaled to cover the entire canvas.
_pixelWidth = size.width.ceil();
_pixelHeight = size.height.ceil();
_pixelWidth = size.width;
_pixelHeight = size.height;
canvasElement.width = _pixelWidth.toDouble();
canvasElement.height = _pixelHeight.toDouble();
_updateLogicalHtmlCanvasSize();

View File

@@ -132,8 +132,8 @@ class Surface extends DisplayCanvas {
_surface!.flush();
}
Future<void> rasterizeToCanvas(
ui.Size frameSize, RenderCanvas canvas, List<CkPicture> pictures) async {
Future<void> rasterizeToCanvas(BitmapSize bitmapSize, RenderCanvas canvas,
List<CkPicture> pictures) async {
final CkCanvas skCanvas = getCanvas();
skCanvas.clear(const ui.Color(0x00000000));
pictures.forEach(skCanvas.drawPicture);
@@ -148,9 +148,9 @@ class Surface extends DisplayCanvas {
}
final DomImageBitmap bitmap = await createImageBitmap(bitmapSource, (
x: 0,
y: _pixelHeight - frameSize.height.toInt(),
width: frameSize.width.toInt(),
height: frameSize.height.toInt(),
y: _pixelHeight - bitmapSize.height,
width: bitmapSize.width,
height: bitmapSize.height,
));
canvas.render(bitmap);
} else {
@@ -162,7 +162,7 @@ class Surface extends DisplayCanvas {
} else {
imageSource = _canvasElement! as DomCanvasImageSource;
}
canvas.renderWithNoBitmapSupport(imageSource, _pixelHeight, frameSize);
canvas.renderWithNoBitmapSupport(imageSource, _pixelHeight, bitmapSize);
}
}
@@ -170,7 +170,7 @@ class Surface extends DisplayCanvas {
///
/// The given [size] is in physical pixels.
SurfaceFrame acquireFrame(ui.Size size) {
final CkSurface surface = createOrUpdateSurface(size);
final CkSurface surface = createOrUpdateSurface(BitmapSize.fromSize(size));
// ignore: prefer_function_declarations_over_variables
final SubmitCallback submitCallback =
@@ -181,18 +181,11 @@ class Surface extends DisplayCanvas {
return SurfaceFrame(surface, submitCallback);
}
ui.Size? _currentCanvasPhysicalSize;
ui.Size? _currentSurfaceSize;
BitmapSize? _currentCanvasPhysicalSize;
BitmapSize? _currentSurfaceSize;
/// Sets the CSS size of the canvas so that canvas pixels are 1:1 with device
/// pixels.
///
/// The logical size of the canvas is not based on the size of the window
/// but on the size of the canvas, which, due to `ceil()` above, may not be
/// the same as the window. We do not round/floor/ceil the logical size as
/// CSS pixels can contain more than one physical pixel and therefore to
/// match the size of the window precisely we use the most precise floating
/// point value we can get.
void _updateLogicalHtmlCanvasSize() {
final double devicePixelRatio =
EngineFlutterDisplay.instance.devicePixelRatio;
@@ -209,7 +202,7 @@ class Surface extends DisplayCanvas {
/// the <canvas> is, by default, positioned so that the top left corner is in
/// the top left of the window. We need to shift the canvas down so that the
/// bottom left of the <canvas> is the the bottom left corner of the window.
void positionToShowFrame(ui.Size frameSize) {
void positionToShowFrame(BitmapSize frameSize) {
assert(isDisplayCanvas,
'Should not position Surface if not used as a render canvas');
final double devicePixelRatio =
@@ -236,7 +229,7 @@ class Surface extends DisplayCanvas {
///
/// This also ensures that the gl/grcontext have been populated so
/// that software rendering can be detected.
void ensureSurface([ui.Size size = const ui.Size(1, 1)]) {
void ensureSurface([BitmapSize size = const BitmapSize(1, 1)]) {
// If the GrContext hasn't been setup yet then we need to force initialization
// of the canvas and initial surface.
if (_surface != null) {
@@ -249,7 +242,7 @@ class Surface extends DisplayCanvas {
}
/// Creates a <canvas> and SkSurface for the given [size].
CkSurface createOrUpdateSurface(ui.Size size) {
CkSurface createOrUpdateSurface(BitmapSize size) {
if (size.isEmpty) {
throw CanvasKitError('Cannot create surfaces of empty size.');
}
@@ -257,7 +250,7 @@ class Surface extends DisplayCanvas {
if (!_forceNewContext) {
// Check if the window is the same size as before, and if so, don't allocate
// a new canvas as the previous canvas is big enough to fit everything.
final ui.Size? previousSurfaceSize = _currentSurfaceSize;
final BitmapSize? previousSurfaceSize = _currentSurfaceSize;
if (previousSurfaceSize != null &&
size.width == previousSurfaceSize.width &&
size.height == previousSurfaceSize.height) {
@@ -269,17 +262,17 @@ class Surface extends DisplayCanvas {
return _surface!;
}
final ui.Size? previousCanvasSize = _currentCanvasPhysicalSize;
final BitmapSize? previousCanvasSize = _currentCanvasPhysicalSize;
// Initialize a new, larger, canvas. If the size is growing, then make the
// new canvas larger than required to avoid many canvas creations.
if (previousCanvasSize != null &&
(size.width > previousCanvasSize.width ||
size.height > previousCanvasSize.height)) {
final ui.Size newSize = size * 1.4;
final BitmapSize newSize = BitmapSize.fromSize(size.toSize() * 1.4);
_surface?.dispose();
_surface = null;
_pixelWidth = newSize.width.ceil();
_pixelHeight = newSize.height.ceil();
_pixelWidth = newSize.width;
_pixelHeight = newSize.height;
if (useOffscreenCanvas) {
_offscreenCanvas!.width = _pixelWidth.toDouble();
_offscreenCanvas!.height = _pixelHeight.toDouble();
@@ -287,8 +280,7 @@ class Surface extends DisplayCanvas {
_canvasElement!.width = _pixelWidth.toDouble();
_canvasElement!.height = _pixelHeight.toDouble();
}
_currentCanvasPhysicalSize =
ui.Size(_pixelWidth.toDouble(), _pixelHeight.toDouble());
_currentCanvasPhysicalSize = BitmapSize(_pixelWidth, _pixelHeight);
if (isDisplayCanvas) {
_updateLogicalHtmlCanvasSize();
}
@@ -336,7 +328,7 @@ class Surface extends DisplayCanvas {
/// This function is expensive.
///
/// It's better to reuse canvas if possible.
void _createNewCanvas(ui.Size physicalSize) {
void _createNewCanvas(BitmapSize physicalSize) {
// Clear the container, if it's not empty. We're going to create a new <canvas>.
if (_offscreenCanvas != null) {
_offscreenCanvas!.removeEventListener(
@@ -371,8 +363,8 @@ class Surface extends DisplayCanvas {
// If `physicalSize` is not precise, use a slightly bigger canvas. This way
// we ensure that the rendred picture covers the entire browser window.
_pixelWidth = physicalSize.width.ceil();
_pixelHeight = physicalSize.height.ceil();
_pixelWidth = physicalSize.width;
_pixelHeight = physicalSize.height;
DomEventTarget htmlCanvas;
if (useOffscreenCanvas) {
final DomOffscreenCanvas offscreenCanvas = createDomOffscreenCanvas(
@@ -467,7 +459,7 @@ class Surface extends DisplayCanvas {
_stencilBits = gl.getParameter(gl.stencilBits);
}
CkSurface _createNewSurface(ui.Size size) {
CkSurface _createNewSurface(BitmapSize size) {
assert(_offscreenCanvas != null || _canvasElement != null);
if (webGLVersion == -1) {
return _makeSoftwareCanvasSurface('WebGL support not detected');
@@ -478,8 +470,8 @@ class Surface extends DisplayCanvas {
} else {
final SkSurface? skSurface = canvasKit.MakeOnScreenGLSurface(
_grContext!,
size.width.ceilToDouble(),
size.height.ceilToDouble(),
size.width.toDouble(),
size.height.toDouble(),
SkColorSpaceSRGB,
_sampleCount,
_stencilBits);

View File

@@ -886,3 +886,35 @@ String tileModeString(ui.TileMode tileMode) {
return 'decal';
}
}
/// A size where both the width and height are integers.
class BitmapSize {
const BitmapSize(this.width, this.height);
/// Returns a [BitmapSize] by rounding the width and height of a [ui.Size] to
/// the nearest integer.
BitmapSize.fromSize(ui.Size size)
: width = size.width.round(),
height = size.height.round();
final int width;
final int height;
@override
bool operator ==(Object other) {
return other is BitmapSize &&
other.width == width &&
other.height == height;
}
@override
int get hashCode => Object.hash(width, height);
ui.Size toSize() {
return ui.Size(width.toDouble(), height.toDouble());
}
bool get isEmpty => width == 0 || height == 0;
static const BitmapSize zero = BitmapSize(0, 0);
}

View File

@@ -6,6 +6,7 @@ import 'dart:js_interop';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'common.dart';
@@ -15,7 +16,7 @@ void main() {
void testMain() {
group('CanvasKit', () {
setUpCanvasKitTest();
setUpCanvasKitTest(withImplicitView: true);
setUp(() async {
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(1.0);
});
@@ -59,5 +60,32 @@ void testMain() {
expect(canvas.canvasElement.style.width, '20px');
expect(canvas.canvasElement.style.height, '32px');
});
test('rounds physical size to nearest integer size', () async {
final EngineFlutterWindow implicitView =
EnginePlatformDispatcher.instance.implicitView!;
implicitView.debugPhysicalSizeOverride =
const ui.Size(199.999999, 200.000001);
final ui.SceneBuilder sceneBuilder = LayerSceneBuilder();
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.drawPaint(CkPaint()..color = const ui.Color(0xff00ff00));
final CkPicture picture = recorder.endRecording();
sceneBuilder.addPicture(ui.Offset.zero, picture);
final ui.Scene scene = sceneBuilder.build();
await renderScene(scene);
expect(
CanvasKitRenderer.instance
.debugGetRasterizerForView(implicitView)!
.currentFrameSize,
const BitmapSize(200, 200),
);
implicitView.debugPhysicalSizeOverride = null;
implicitView.debugForceResize();
});
});
}

View File

@@ -110,7 +110,7 @@ void testMain() {
test('Surface used as DisplayCanvas resizes correctly', () {
final Surface surface = Surface(isDisplayCanvas: true);
surface.createOrUpdateSurface(const ui.Size(9, 19));
surface.createOrUpdateSurface(const BitmapSize(9, 19));
final DomCanvasElement original = getDisplayCanvas(surface);
ui.Size canvasSize = getCssSize(surface);
@@ -122,7 +122,7 @@ void testMain() {
// Shrinking reuses the existing canvas but translates it so
// Skia renders into the visible area.
surface.createOrUpdateSurface(const ui.Size(5, 15));
surface.createOrUpdateSurface(const BitmapSize(5, 15));
final DomCanvasElement shrunk = getDisplayCanvas(surface);
canvasSize = getCssSize(surface);
expect(shrunk.width, 9);
@@ -132,7 +132,7 @@ void testMain() {
// The first increase will allocate a new surface, but will overallocate
// by 40% to accommodate future increases.
surface.createOrUpdateSurface(const ui.Size(10, 20));
surface.createOrUpdateSurface(const BitmapSize(10, 20));
final DomCanvasElement firstIncrease = getDisplayCanvas(surface);
canvasSize = getCssSize(surface);
@@ -145,7 +145,7 @@ void testMain() {
expect(canvasSize.height, 28);
// Subsequent increases within 40% reuse the old canvas.
surface.createOrUpdateSurface(const ui.Size(11, 22));
surface.createOrUpdateSurface(const BitmapSize(11, 22));
final DomCanvasElement secondIncrease = getDisplayCanvas(surface);
canvasSize = getCssSize(surface);
@@ -156,7 +156,7 @@ void testMain() {
expect(canvasSize.height, 28);
// Increases beyond the 40% limit will cause a new allocation.
surface.createOrUpdateSurface(const ui.Size(20, 40));
surface.createOrUpdateSurface(const BitmapSize(20, 40));
final DomCanvasElement huge = getDisplayCanvas(surface);
canvasSize = getCssSize(surface);
@@ -169,7 +169,7 @@ void testMain() {
expect(canvasSize.height, 56);
// Shrink again. Reuse the last allocated surface.
surface.createOrUpdateSurface(const ui.Size(5, 15));
surface.createOrUpdateSurface(const BitmapSize(5, 15));
final DomCanvasElement shrunk2 = getDisplayCanvas(surface);
canvasSize = getCssSize(surface);
@@ -182,7 +182,7 @@ void testMain() {
// Doubling the DPR should halve the CSS width, height, and translation of the canvas.
// This tests https://github.com/flutter/flutter/issues/77084
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(2.0);
surface.createOrUpdateSurface(const ui.Size(5, 15));
surface.createOrUpdateSurface(const BitmapSize(5, 15));
final DomCanvasElement dpr2Canvas = getDisplayCanvas(surface);
canvasSize = getCssSize(surface);