[web] Implement Canvas.drawPicture (flutter/engine#24574)

This commit is contained in:
Ferhat
2021-02-24 13:01:44 -08:00
committed by GitHub
parent 3ebc2d354b
commit c694e1d965
6 changed files with 381 additions and 174 deletions

View File

@@ -1,2 +1,2 @@
repository: https://github.com/flutter/goldens.git
revision: 041056fc3ae057574586fa6f69b2cc9465c4a5bf
revision: bb55871d3803337053f7200b8690a4c1322e82ea

View File

@@ -923,12 +923,6 @@ class BitmapCanvas extends EngineCanvas {
_closeCurrentCanvas();
}
/// Paints the [picture] into this canvas.
void drawPicture(ui.Picture picture) {
final EnginePicture enginePicture = picture as EnginePicture;
enginePicture.recordingCanvas!.apply(this, bounds);
}
/// Draws vertices on a gl context.
///
/// If both colors and textures is specified in paint data,

View File

@@ -444,8 +444,7 @@ class SurfaceCanvas implements ui.Canvas {
void drawPicture(ui.Picture picture) {
// ignore: unnecessary_null_comparison
assert(picture != null); // picture is checked on the engine side
// TODO(het): Support this
throw UnimplementedError();
_canvas.drawPicture(picture);
}
@override

View File

@@ -120,13 +120,25 @@ class RecordingCanvas {
_recordingEnded = true;
}
/// Applies the recorded commands onto an [engineCanvas].
/// Applies the recorded commands onto an [engineCanvas] and signals to
/// canvas that all painting is completed for garbage collection/reuse.
///
/// The [clipRect] specifies the clip applied to the picture (screen clip at
/// a minimum). The commands that fall outside the clip are skipped and are
/// not applied to the [engineCanvas]. A command must have a non-zero
/// intersection with the clip in order to be applied.
void apply(EngineCanvas engineCanvas, ui.Rect clipRect) {
applyCommands(engineCanvas, clipRect);
engineCanvas.endOfPaint();
}
/// Applies the recorded commands onto an [engineCanvas].
///
/// The [clipRect] specifies the clip applied to the picture (screen clip at
/// a minimum). The commands that fall outside the clip are skipped and are
/// not applied to the [engineCanvas]. A command must have a non-zero
/// intersection with the clip in order to be applied.
void applyCommands(EngineCanvas engineCanvas, ui.Rect clipRect) {
assert(_recordingEnded);
if (_debugDumpPaintCommands) {
final StringBuffer debugBuf = StringBuffer();
@@ -183,7 +195,6 @@ class RecordingCanvas {
}
}
}
engineCanvas.endOfPaint();
}
/// Prints recorded commands.
@@ -511,6 +522,29 @@ class RecordingCanvas {
_commands.add(command);
}
void drawPicture(ui.Picture picture) {
assert(!_recordingEnded);
final EnginePicture enginePicture = picture as EnginePicture;
// TODO apply renderStrategy of picture recording to this recording.
if (enginePicture.recordingCanvas == null) {
// No contents / nothing to draw.
return;
}
final RecordingCanvas pictureRecording = enginePicture.recordingCanvas!;
if (pictureRecording._didDraw == true) {
_didDraw = true;
}
renderStrategy.merge(pictureRecording.renderStrategy);
// Need to save to make sure we don't pick up leftover clips and
// transforms from running commands in picture.
save();
_commands.addAll(pictureRecording._commands);
restore();
if (pictureRecording._pictureBounds != null) {
_paintBounds.growBounds(pictureRecording._pictureBounds!);
}
}
void drawImageRect(
ui.Image image, ui.Rect src, ui.Rect dst, SurfacePaint paint) {
assert(!_recordingEnded);
@@ -1746,7 +1780,8 @@ class _PaintBounds {
growLTRB(r.left, r.top, r.right, r.bottom, command);
}
/// Grow painted area to include given rectangle.
/// Grow painted area to include given rectangle and precompute
/// clipped out state for command.
void growLTRB(double left, double top, double right, double bottom,
DrawCommand command) {
if (left == right || top == bottom) {
@@ -1826,6 +1861,52 @@ class _PaintBounds {
_didPaintInsideClipArea = true;
}
/// Grow painted area to include given rectangle.
void growBounds(ui.Rect bounds) {
final double left = bounds.left;
final double top = bounds.top;
final double right = bounds.right;
final double bottom = bounds.bottom;
if (left == right || top == bottom) {
return;
}
double transformedPointLeft = left;
double transformedPointTop = top;
double transformedPointRight = right;
double transformedPointBottom = bottom;
if (!_currentMatrixIsIdentity) {
_tempRectData[0] = left;
_tempRectData[1] = top;
_tempRectData[2] = right;
_tempRectData[3] = bottom;
transformLTRB(_currentMatrix, _tempRectData);
transformedPointLeft = _tempRectData[0];
transformedPointTop = _tempRectData[1];
transformedPointRight = _tempRectData[2];
transformedPointBottom = _tempRectData[3];
}
if (_didPaintInsideClipArea) {
_left = math.min(
math.min(_left, transformedPointLeft), transformedPointRight);
_right = math.max(
math.max(_right, transformedPointLeft), transformedPointRight);
_top =
math.min(math.min(_top, transformedPointTop), transformedPointBottom);
_bottom = math.max(
math.max(_bottom, transformedPointTop), transformedPointBottom);
} else {
_left = math.min(transformedPointLeft, transformedPointRight);
_right = math.max(transformedPointLeft, transformedPointRight);
_top = math.min(transformedPointTop, transformedPointBottom);
_bottom = math.max(transformedPointTop, transformedPointBottom);
}
_didPaintInsideClipArea = true;
}
void saveTransformsAndClip() {
_transforms.add(_currentMatrix.clone());
_clipStack.add(_clipRectInitialized
@@ -1942,4 +2023,11 @@ class RenderStrategy {
bool isInsideShaderMask = false;
RenderStrategy();
/// Merges render strategy settings from a child recording.
void merge(RenderStrategy childStrategy) {
hasImageElements |= childStrategy.hasImageElements;
hasParagraphs |= childStrategy.hasParagraphs;
hasArbitraryPaint |= childStrategy.hasArbitraryPaint;
}
}

View File

@@ -14,8 +14,8 @@ abstract class EngineGradient implements ui.Gradient {
ui.Rect? shaderBounds, double density);
/// Creates a CanvasImageSource to paint gradient.
Object createImageBitmap(ui.Rect? shaderBounds, double density,
bool createDataUrl);
Object createImageBitmap(
ui.Rect? shaderBounds, double density, bool createDataUrl);
}
class GradientSweep extends EngineGradient {
@@ -32,8 +32,8 @@ class GradientSweep extends EngineGradient {
}
@override
Object createImageBitmap(ui.Rect? shaderBounds, double density,
bool createDataUrl) {
Object createImageBitmap(
ui.Rect? shaderBounds, double density, bool createDataUrl) {
assert(shaderBounds != null);
int widthInPixels = shaderBounds!.width.ceil();
int heightInPixels = shaderBounds.height.ceil();
@@ -45,39 +45,47 @@ class GradientSweep extends EngineGradient {
_OffScreenCanvas(widthInPixels, heightInPixels);
_GlContext gl = _OffScreenCanvas.supported
? _GlContext.fromOffscreenCanvas(offScreenCanvas._canvas!)
: _GlContext.fromCanvas(offScreenCanvas._glCanvas!,
webGLVersion == WebGLVersion.webgl1);
: _GlContext.fromCanvas(
offScreenCanvas._glCanvas!, webGLVersion == WebGLVersion.webgl1);
gl.setViewportSize(widthInPixels, heightInPixels);
NormalizedGradient normalizedGradient = NormalizedGradient(
colors, stops: colorStops);
NormalizedGradient normalizedGradient =
NormalizedGradient(colors, stops: colorStops);
_GlProgram glProgram = gl.useAndCacheProgram(
_WebGlRenderer.writeBaseVertexShader(),
_createSweepFragmentShader(normalizedGradient, tileMode));
Object tileOffset = gl.getUniformLocation(glProgram.program, 'u_tile_offset');
Object tileOffset =
gl.getUniformLocation(glProgram.program, 'u_tile_offset');
double centerX = (center.dx - shaderBounds.left) / (shaderBounds.width);
double centerY = (center.dy - shaderBounds.top) / (shaderBounds.height);
gl.setUniform2f(tileOffset,
2 * (shaderBounds.width * (centerX - 0.5)),
gl.setUniform2f(tileOffset, 2 * (shaderBounds.width * (centerX - 0.5)),
2 * (shaderBounds.height * (centerY - 0.5)));
Object angleRange = gl.getUniformLocation(glProgram.program, 'angle_range');
gl.setUniform2f(angleRange, startAngle, endAngle);
normalizedGradient.setupUniforms(gl, glProgram);
if (matrix4 != null) {
Object gradientMatrix = gl.getUniformLocation(
glProgram.program, 'm_gradient');
Object gradientMatrix =
gl.getUniformLocation(glProgram.program, 'm_gradient');
gl.setUniformMatrix4fv(gradientMatrix, false, matrix4!);
}
if (createDataUrl) {
return _glRenderer!.drawRectToImageUrl(
ui.Rect.fromLTWH(0, 0, shaderBounds.width, shaderBounds.height),
gl, glProgram, normalizedGradient, widthInPixels, heightInPixels);
gl,
glProgram,
normalizedGradient,
widthInPixels,
heightInPixels);
} else {
return _glRenderer!.drawRect(
ui.Rect.fromLTWH(0, 0, shaderBounds.width, shaderBounds.height),
gl, glProgram, normalizedGradient, widthInPixels, heightInPixels)!;
gl,
glProgram,
normalizedGradient,
widthInPixels,
heightInPixels)!;
}
}
@@ -88,8 +96,8 @@ class GradientSweep extends EngineGradient {
return ctx!.createPattern(imageBitmap, 'no-repeat')!;
}
String _createSweepFragmentShader(NormalizedGradient gradient,
ui.TileMode tileMode) {
String _createSweepFragmentShader(
NormalizedGradient gradient, ui.TileMode tileMode) {
ShaderBuilder builder = ShaderBuilder.fragment(webGLVersion);
builder.floatPrecision = ShaderPrecision.kMedium;
builder.addIn(ShaderType.kVec4, name: 'v_color');
@@ -100,21 +108,18 @@ class GradientSweep extends EngineGradient {
ShaderDeclaration fragColor = builder.fragmentColor;
ShaderMethod method = builder.addMethod('main');
// Sweep gradient
method.addStatement(
'vec2 center = 0.5 * (u_resolution + u_tile_offset);');
method.addStatement('vec2 center = 0.5 * (u_resolution + u_tile_offset);');
method.addStatement(
'vec4 localCoord = vec4(gl_FragCoord.x - center.x, center.y - gl_FragCoord.y, 0, 1) * m_gradient;');
method.addStatement(
'float angle = atan(-localCoord.y, -localCoord.x) + ${math.pi};');
method.addStatement(
'float sweep = angle_range.y - angle_range.x;');
method.addStatement(
'angle = (angle - angle_range.x) / sweep;');
method.addStatement('float sweep = angle_range.y - angle_range.x;');
method.addStatement('angle = (angle - angle_range.x) / sweep;');
method.addStatement(''
'float st = angle;');
final String probeName =
_writeSharedGradientShader(builder, method, gradient, tileMode);
_writeSharedGradientShader(builder, method, gradient, tileMode);
method.addStatement('${fragColor.name} = ${probeName} * scale + bias;');
String shader = builder.build();
@@ -131,13 +136,14 @@ class GradientSweep extends EngineGradient {
}
class GradientLinear extends EngineGradient {
GradientLinear(this.from,
this.to,
this.colors,
this.colorStops,
this.tileMode,
Float32List? matrix,)
: assert(_offsetIsValid(from)),
GradientLinear(
this.from,
this.to,
this.colors,
this.colorStops,
this.tileMode,
Float32List? matrix,
) : assert(_offsetIsValid(from)),
assert(_offsetIsValid(to)),
assert(colors != null), // ignore: unnecessary_null_comparison
assert(tileMode != null), // ignore: unnecessary_null_comparison
@@ -178,22 +184,23 @@ class GradientLinear extends EngineGradient {
final double fromX = matrix4.transformedX + centerX;
final double fromY = matrix4.transformedY + centerY;
matrix4.transform(to.dx - centerX, to.dy - centerY);
gradient = ctx!.createLinearGradient(fromX - offsetX, fromY - offsetY,
gradient = ctx!.createLinearGradient(
fromX - offsetX,
fromY - offsetY,
matrix4.transformedX + centerX - offsetX,
matrix4.transformedY - offsetY + centerY);
} else {
gradient = ctx!.createLinearGradient(
from.dx - offsetX, from.dy - offsetY, to.dx - offsetX,
to.dy - offsetY);
gradient = ctx!.createLinearGradient(from.dx - offsetX, from.dy - offsetY,
to.dx - offsetX, to.dy - offsetY);
}
_addColorStopsToCanvasGradient(gradient, colors, colorStops,
tileMode == ui.TileMode.decal);
_addColorStopsToCanvasGradient(
gradient, colors, colorStops, tileMode == ui.TileMode.decal);
return gradient;
}
@override
Object createImageBitmap(ui.Rect? shaderBounds, double density,
bool createDataUrl) {
Object createImageBitmap(
ui.Rect? shaderBounds, double density, bool createDataUrl) {
assert(shaderBounds != null);
int widthInPixels = shaderBounds!.width.ceil();
int heightInPixels = shaderBounds.height.ceil();
@@ -201,15 +208,15 @@ class GradientLinear extends EngineGradient {
initWebGl();
// Render gradient into a bitmap and create a canvas pattern.
_OffScreenCanvas offScreenCanvas =
_OffScreenCanvas(widthInPixels, heightInPixels);
_OffScreenCanvas(widthInPixels, heightInPixels);
_GlContext gl = _OffScreenCanvas.supported
? _GlContext.fromOffscreenCanvas(offScreenCanvas._canvas!)
: _GlContext.fromCanvas(offScreenCanvas._glCanvas!,
webGLVersion == WebGLVersion.webgl1);
: _GlContext.fromCanvas(
offScreenCanvas._glCanvas!, webGLVersion == WebGLVersion.webgl1);
gl.setViewportSize(widthInPixels, heightInPixels);
NormalizedGradient normalizedGradient = NormalizedGradient(
colors, stops: colorStops);
NormalizedGradient normalizedGradient =
NormalizedGradient(colors, stops: colorStops);
_GlProgram glProgram = gl.useAndCacheProgram(
_WebGlRenderer.writeBaseVertexShader(),
@@ -248,7 +255,8 @@ class GradientLinear extends EngineGradient {
? (shaderBounds.height / 2)
: (fromY + toY) / 2.0 - shaderBounds.top;
final Matrix4 translateToOrigin = Matrix4.translationValues(-originX, -originY, 0);
final Matrix4 translateToOrigin =
Matrix4.translationValues(-originX, -originY, 0);
// Rotate around Z axis.
final Matrix4 rotationZ = Matrix4.identity();
final Float32List storage = rotationZ.storage;
@@ -274,9 +282,11 @@ class GradientLinear extends EngineGradient {
// and flip back so it is applied correctly.
final Matrix4 m4 = Matrix4.fromFloat32List(matrix4!.matrix);
gradientTransform.scale(1, -1);
gradientTransform.translate(-shaderBounds.center.dx, -shaderBounds.center.dy);
gradientTransform.translate(
-shaderBounds.center.dx, -shaderBounds.center.dy);
gradientTransform.multiply(m4);
gradientTransform.translate(shaderBounds.center.dx, shaderBounds.center.dy);
gradientTransform.translate(
shaderBounds.center.dx, shaderBounds.center.dy);
gradientTransform.scale(1, -1);
}
@@ -285,25 +295,32 @@ class GradientLinear extends EngineGradient {
// Setup gradient uniforms for t search.
normalizedGradient.setupUniforms(gl, glProgram);
// Setup matrix transform uniform.
Object gradientMatrix = gl.getUniformLocation(
glProgram.program, 'm_gradient');
Object gradientMatrix =
gl.getUniformLocation(glProgram.program, 'm_gradient');
gl.setUniformMatrix4fv(gradientMatrix, false, gradientTransform.storage);
Object uRes = gl.getUniformLocation(glProgram.program, 'u_resolution');
gl.setUniform2f(
uRes, widthInPixels.toDouble(), heightInPixels.toDouble());
gl.setUniform2f(uRes, widthInPixels.toDouble(), heightInPixels.toDouble());
if (createDataUrl) {
return _glRenderer!.drawRectToImageUrl(ui.Rect.fromLTWH(
0, 0, shaderBounds.width, shaderBounds.height) /* !! shaderBounds */,
return _glRenderer!.drawRectToImageUrl(
ui.Rect.fromLTWH(0, 0, shaderBounds.width,
shaderBounds.height) /* !! shaderBounds */,
gl,
glProgram, normalizedGradient, widthInPixels, heightInPixels,
glProgram,
normalizedGradient,
widthInPixels,
heightInPixels,
);
} else {
return _glRenderer!.drawRect(ui.Rect.fromLTWH(
0, 0, shaderBounds.width, shaderBounds.height) /* !! shaderBounds */,
return _glRenderer!.drawRect(
ui.Rect.fromLTWH(0, 0, shaderBounds.width,
shaderBounds.height) /* !! shaderBounds */,
gl,
glProgram, normalizedGradient, widthInPixels, heightInPixels,
glProgram,
normalizedGradient,
widthInPixels,
heightInPixels,
)!;
}
}
@@ -315,8 +332,8 @@ class GradientLinear extends EngineGradient {
return ctx!.createPattern(imageBitmap, 'no-repeat')!;
}
String _createLinearFragmentShader(NormalizedGradient gradient,
ui.TileMode tileMode) {
String _createLinearFragmentShader(
NormalizedGradient gradient, ui.TileMode tileMode) {
ShaderBuilder builder = ShaderBuilder.fragment(webGLVersion);
builder.floatPrecision = ShaderPrecision.kMedium;
builder.addIn(ShaderType.kVec4, name: 'v_color');
@@ -327,9 +344,8 @@ class GradientLinear extends EngineGradient {
// Linear gradient.
// Multiply with m_gradient transform to convert from fragment coordinate to
// distance on the from-to line.
method.addStatement(
'vec4 localCoord = m_gradient * vec4(gl_FragCoord.x, '
'u_resolution.y - gl_FragCoord.y, 0, 1);');
method.addStatement('vec4 localCoord = m_gradient * vec4(gl_FragCoord.x, '
'u_resolution.y - gl_FragCoord.y, 0, 1);');
method.addStatement('float st = localCoord.x;');
final String probeName =
_writeSharedGradientShader(builder, method, gradient, tileMode);
@@ -356,7 +372,8 @@ void _addColorStopsToCanvasGradient(html.CanvasGradient gradient,
gradient.addColorStop(1 - offset, colorToCssString(colors[1])!);
} else {
for (int i = 0; i < colors.length; i++) {
gradient.addColorStop(colorStops[i] * scale + offset, colorToCssString(colors[i])!);
gradient.addColorStop(
colorStops[i] * scale + offset, colorToCssString(colors[i])!);
}
}
if (isDecal) {
@@ -367,10 +384,8 @@ void _addColorStopsToCanvasGradient(html.CanvasGradient gradient,
/// Writes shader code to map fragment value to gradient color.
///
/// Returns name of gradient treshold variable to use to compute color.
String _writeSharedGradientShader(ShaderBuilder builder,
ShaderMethod method,
NormalizedGradient gradient,
ui.TileMode tileMode) {
String _writeSharedGradientShader(ShaderBuilder builder, ShaderMethod method,
NormalizedGradient gradient, ui.TileMode tileMode) {
method.addStatement('vec4 bias;');
method.addStatement('vec4 scale;');
// Write uniforms for each threshold, bias and scale.
@@ -407,16 +422,17 @@ String _writeSharedGradientShader(ShaderBuilder builder,
break;
}
_writeUnrolledBinarySearch(method, 0, gradient.thresholdCount - 1,
probe: probeName, sourcePrefix: 'threshold',
biasName: 'bias', scaleName: 'scale');
probe: probeName,
sourcePrefix: 'threshold',
biasName: 'bias',
scaleName: 'scale');
return probeName;
}
class GradientRadial extends EngineGradient {
GradientRadial(this.center, this.radius, this.colors, this.colorStops,
this.tileMode, this.matrix4)
: super._() {
}
: super._() {}
final ui.Offset center;
final double radius;
@@ -440,15 +456,20 @@ class GradientRadial extends EngineGradient {
final double offsetX = shaderBounds!.left;
final double offsetY = shaderBounds.top;
final html.CanvasGradient gradient = ctx!.createRadialGradient(
center.dx - offsetX, center.dy - offsetY, 0,
center.dx - offsetX, center.dy - offsetY, radius);
_addColorStopsToCanvasGradient(gradient, colors, colorStops, tileMode == ui.TileMode.decal);
center.dx - offsetX,
center.dy - offsetY,
0,
center.dx - offsetX,
center.dy - offsetY,
radius);
_addColorStopsToCanvasGradient(
gradient, colors, colorStops, tileMode == ui.TileMode.decal);
return gradient;
}
@override
Object createImageBitmap(ui.Rect? shaderBounds, double density,
bool createDataUrl) {
Object createImageBitmap(
ui.Rect? shaderBounds, double density, bool createDataUrl) {
assert(shaderBounds != null);
int widthInPixels = shaderBounds!.width.ceil();
int heightInPixels = shaderBounds.height.ceil();
@@ -457,41 +478,52 @@ class GradientRadial extends EngineGradient {
initWebGl();
// Render gradient into a bitmap and create a canvas pattern.
_OffScreenCanvas offScreenCanvas =
_OffScreenCanvas(widthInPixels, heightInPixels);
_OffScreenCanvas(widthInPixels, heightInPixels);
_GlContext gl = _OffScreenCanvas.supported
? _GlContext.fromOffscreenCanvas(offScreenCanvas._canvas!)
: _GlContext.fromCanvas(offScreenCanvas._glCanvas!,
webGLVersion == WebGLVersion.webgl1);
: _GlContext.fromCanvas(
offScreenCanvas._glCanvas!, webGLVersion == WebGLVersion.webgl1);
gl.setViewportSize(widthInPixels, heightInPixels);
NormalizedGradient normalizedGradient = NormalizedGradient(
colors, stops: colorStops);
NormalizedGradient normalizedGradient =
NormalizedGradient(colors, stops: colorStops);
_GlProgram glProgram = gl.useAndCacheProgram(
_WebGlRenderer.writeBaseVertexShader(),
_createRadialFragmentShader(normalizedGradient, tileMode));
_createRadialFragmentShader(
normalizedGradient, shaderBounds, tileMode));
Object tileOffset = gl.getUniformLocation(glProgram.program, 'u_tile_offset');
Object tileOffset =
gl.getUniformLocation(glProgram.program, 'u_tile_offset');
double centerX = (center.dx - shaderBounds.left) / (shaderBounds.width);
double centerY = (center.dy - shaderBounds.top) / (shaderBounds.height);
gl.setUniform2f(tileOffset,
2 * (shaderBounds.width * (centerX - 0.5)),
gl.setUniform2f(tileOffset, 2 * (shaderBounds.width * (centerX - 0.5)),
2 * (shaderBounds.height * (centerY - 0.5)));
Object radiusUniform = gl.getUniformLocation(glProgram.program, 'u_radius');
gl.setUniform1f(radiusUniform, radius);
normalizedGradient.setupUniforms(gl, glProgram);
Object gradientMatrix = gl.getUniformLocation(
glProgram.program, 'm_gradient');
gl.setUniformMatrix4fv(gradientMatrix, false, matrix4 == null ? Matrix4.identity().storage : matrix4!);
Object gradientMatrix =
gl.getUniformLocation(glProgram.program, 'm_gradient');
gl.setUniformMatrix4fv(gradientMatrix, false,
matrix4 == null ? Matrix4.identity().storage : matrix4!);
if (createDataUrl) {
return _glRenderer!.drawRectToImageUrl(ui.Rect.fromLTWH(0, 0, shaderBounds.width,
shaderBounds.height),
gl, glProgram, normalizedGradient, widthInPixels, heightInPixels);
return _glRenderer!.drawRectToImageUrl(
ui.Rect.fromLTWH(0, 0, shaderBounds.width, shaderBounds.height),
gl,
glProgram,
normalizedGradient,
widthInPixels,
heightInPixels);
} else {
return _glRenderer!.drawRect(ui.Rect.fromLTWH(0, 0, shaderBounds.width,
shaderBounds.height),
gl, glProgram, normalizedGradient, widthInPixels, heightInPixels)!;
return _glRenderer!.drawRect(
ui.Rect.fromLTWH(0, 0, shaderBounds.width, shaderBounds.height),
gl,
glProgram,
normalizedGradient,
widthInPixels,
heightInPixels)!;
}
}
@@ -502,8 +534,8 @@ class GradientRadial extends EngineGradient {
return ctx!.createPattern(imageBitmap, 'no-repeat')!;
}
String _createRadialFragmentShader(NormalizedGradient gradient,
ui.TileMode tileMode) {
String _createRadialFragmentShader(
NormalizedGradient gradient, ui.Rect shaderBounds, ui.TileMode tileMode) {
ShaderBuilder builder = ShaderBuilder.fragment(webGLVersion);
builder.floatPrecision = ShaderPrecision.kMedium;
builder.addIn(ShaderType.kVec4, name: 'v_color');
@@ -514,46 +546,102 @@ class GradientRadial extends EngineGradient {
ShaderDeclaration fragColor = builder.fragmentColor;
ShaderMethod method = builder.addMethod('main');
// Sweep gradient
method.addStatement(
'vec2 center = 0.5 * (u_resolution + u_tile_offset);');
method.addStatement('vec2 center = 0.5 * (u_resolution + u_tile_offset);');
method.addStatement(
'vec4 localCoord = vec4(gl_FragCoord.x - center.x, center.y - gl_FragCoord.y, 0, 1) * m_gradient;');
method.addStatement(
'float dist = length(localCoord);');
method.addStatement('float dist = length(localCoord);');
method.addStatement(''
'float st = abs(dist / u_radius);');
final String probeName =
_writeSharedGradientShader(builder, method, gradient, tileMode);
_writeSharedGradientShader(builder, method, gradient, tileMode);
method.addStatement('${fragColor.name} = ${probeName} * scale + bias;');
String shader = builder.build();
return shader;
}
}
class GradientConical extends EngineGradient {
GradientConical(this.focal, this.focalRadius, this.center, this.radius,
this.colors, this.colorStops, this.tileMode, this.matrix4)
: super._();
/// TODO: Implement focal https://github.com/flutter/flutter/issues/76643.
class GradientConical extends GradientRadial {
GradientConical(
this.focal,
this.focalRadius,
ui.Offset center,
double radius,
List<ui.Color> colors,
List<double>? colorStops,
ui.TileMode tileMode,
Float32List? matrix4)
: super(center, radius, colors, colorStops, tileMode, matrix4);
final ui.Offset focal;
final double focalRadius;
final ui.Offset center;
final double radius;
final List<ui.Color> colors;
final List<double>? colorStops;
final ui.TileMode tileMode;
final Float32List? matrix4;
@override
Object createPaintStyle(html.CanvasRenderingContext2D? ctx,
ui.Rect? shaderBounds, double density) {
throw UnimplementedError();
if ((tileMode == ui.TileMode.clamp || tileMode == ui.TileMode.decal) &&
focalRadius == 0.0 &&
focal == const ui.Offset(0, 0)) {
return _createCanvasGradient(ctx, shaderBounds, density);
} else {
initWebGl();
return _createGlGradient(ctx, shaderBounds, density);
}
}
@override
Object createImageBitmap(ui.Rect? shaderBounds, double density,
bool createDataUrl) {
throw UnimplementedError();
String _createRadialFragmentShader(
NormalizedGradient gradient, ui.Rect shaderBounds, ui.TileMode tileMode) {
/// If distance between centers is nearly zero we can pretend we're radial
/// to prevent divide by zero in computing gradient.
final double centerDistanceX = center.dx - focal.dx;
final double centerDistanceY = center.dy - focal.dy;
final double centerDistanceSq =
centerDistanceX * centerDistanceX + centerDistanceY * centerDistanceY;
if (centerDistanceSq < kFltEpsilonSquared) {
return super
._createRadialFragmentShader(gradient, shaderBounds, tileMode);
}
double centerDistance = math.sqrt(centerDistanceSq);
double r0 = focalRadius / centerDistance;
double r1 = radius / centerDistance;
double fFocalX = r0 / (r0 - r1);
if ((fFocalX - 1).abs() < SPath.scalarNearlyZero) {
// swap r0, r1
double temp = r0;
r0 = r1;
r1 = temp;
fFocalX = 0.0; // because r0 is now 0
}
ShaderBuilder builder = ShaderBuilder.fragment(webGLVersion);
builder.floatPrecision = ShaderPrecision.kMedium;
builder.addIn(ShaderType.kVec4, name: 'v_color');
builder.addUniform(ShaderType.kVec2, name: 'u_resolution');
builder.addUniform(ShaderType.kVec2, name: 'u_tile_offset');
builder.addUniform(ShaderType.kFloat, name: 'u_radius');
builder.addUniform(ShaderType.kMat4, name: 'm_gradient');
ShaderDeclaration fragColor = builder.fragmentColor;
ShaderMethod method = builder.addMethod('main');
// Sweep gradient
method.addStatement('vec2 center = 0.5 * (u_resolution + u_tile_offset);');
method.addStatement(
'vec4 localCoord = vec4(gl_FragCoord.x - center.x, center.y - gl_FragCoord.y, 0, 1) * m_gradient;');
method.addStatement('float dist = length(localCoord);');
final String f = (focalRadius /
(math.min(shaderBounds.width, shaderBounds.height) / 2.0))
.toStringAsPrecision(8);
method.addStatement(focalRadius == 0.0
? 'float st = dist / u_radius;'
: 'float st = ((dist / u_radius) - $f) / (1.0 - $f);');
if (tileMode == ui.TileMode.clamp) {
method.addStatement('if (st < 0.0) { st = -1.0; }');
}
final String probeName =
_writeSharedGradientShader(builder, method, gradient, tileMode);
method.addStatement('${fragColor.name} = ${probeName} * scale + bias;');
return builder.build();
}
}
@@ -568,9 +656,9 @@ class EngineImageFilter implements ui.ImageFilter {
@override
bool operator ==(Object other) {
return other is EngineImageFilter
&& other.sigmaX == sigmaX
&& other.sigmaY == sigmaY;
return other is EngineImageFilter &&
other.sigmaX == sigmaX &&
other.sigmaY == sigmaY;
}
@override

View File

@@ -31,61 +31,90 @@ void testMain() async {
await webOnlyFontCollection.ensureFontsLoaded();
});
test('draw growing picture across frames', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
builder.pushClipRect(
const Rect.fromLTRB(0, 0, 100, 100),
);
group('Add picture to scene', () {
test('draw growing picture across frames', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
builder.pushClipRect(
const Rect.fromLTRB(0, 0, 100, 100),
);
_drawTestPicture(builder, 100, false);
builder.pop();
_drawTestPicture(builder, 100, false);
builder.pop();
html.Element elm1 = builder.build().webOnlyRootElement;
html.document.body.append(elm1);
html.Element elm1 = builder
.build()
.webOnlyRootElement;
html.document.body.append(elm1);
// Now draw picture again but at larger size.
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
builder2.pushClipRect(
const Rect.fromLTRB(0, 0, 100, 100),
);
// Now draw the picture at original target size, which will use a
// different code path that should normally not have width/height set
// on image element.
_drawTestPicture(builder2, 20, false);
builder2.pop();
// Now draw picture again but at larger size.
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
builder2.pushClipRect(
const Rect.fromLTRB(0, 0, 100, 100),
);
// Now draw the picture at original target size, which will use a
// different code path that should normally not have width/height set
// on image element.
_drawTestPicture(builder2, 20, false);
builder2.pop();
elm1.remove();
html.document.body.append(builder2.build().webOnlyRootElement);
elm1.remove();
html.document.body.append(builder2
.build()
.webOnlyRootElement);
await matchGoldenFile('canvas_draw_picture_acrossframes.png',
region: region);
});
await matchGoldenFile('canvas_draw_picture_acrossframes.png',
region: region);
});
test('draw growing picture across frames clipped', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
builder.pushClipRect(
const Rect.fromLTRB(0, 0, 100, 100),
);
test('draw growing picture across frames clipped', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
builder.pushClipRect(
const Rect.fromLTRB(0, 0, 100, 100),
);
_drawTestPicture(builder, 100, true);
builder.pop();
_drawTestPicture(builder, 100, true);
builder.pop();
html.Element elm1 = builder.build().webOnlyRootElement;
html.document.body.append(elm1);
html.Element elm1 = builder
.build()
.webOnlyRootElement;
html.document.body.append(elm1);
// Now draw picture again but at larger size.
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
builder2.pushClipRect(
const Rect.fromLTRB(0, 0, 100, 100),
);
_drawTestPicture(builder2, 20, true);
builder2.pop();
// Now draw picture again but at larger size.
final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder();
builder2.pushClipRect(
const Rect.fromLTRB(0, 0, 100, 100),
);
_drawTestPicture(builder2, 20, true);
builder2.pop();
elm1.remove();
html.document.body.append(builder2.build().webOnlyRootElement);
elm1.remove();
html.document.body.append(builder2
.build()
.webOnlyRootElement);
await matchGoldenFile('canvas_draw_picture_acrossframes_clipped.png',
region: region);
await matchGoldenFile('canvas_draw_picture_acrossframes_clipped.png',
region: region);
});
test('PictureInPicture', () async {
final SurfaceSceneBuilder builder = SurfaceSceneBuilder();
final Picture greenRectPicture = _drawGreenRectIntoPicture();
final EnginePictureRecorder recorder = PictureRecorder();
final RecordingCanvas canvas =
recorder.beginRecording(const Rect.fromLTRB(0, 0, 100, 100));
canvas.drawPicture(greenRectPicture);
builder.addPicture(Offset(10, 10), recorder.endRecording());
html.Element elm1 = builder
.build()
.webOnlyRootElement;
html.document.body.append(elm1);
await matchGoldenFile('canvas_draw_picture_in_picture_rect.png',
region: region);
});
});
}
@@ -110,6 +139,15 @@ void _drawTestPicture(SceneBuilder builder, double targetSize, bool clipped) {
);
}
Picture _drawGreenRectIntoPicture() {
final EnginePictureRecorder recorder = PictureRecorder();
final RecordingCanvas canvas =
recorder.beginRecording(const Rect.fromLTRB(0, 0, 100, 100));
canvas.drawRect(Rect.fromLTWH(20, 20, 50, 50),
Paint()..color = const Color(0xFF00FF00));
return recorder.endRecording();
}
typedef PaintCallback = void Function(RecordingCanvas canvas);
const String _base64Encoded20x20TestImage =