Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/ImageSharp.Drawing.WebGPU/Shaders/WgslSource/fine.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,9 @@ fn image_extend_mode_i32(t: f32, mode: u32, max: i32) -> i32 {
// Flag bit indicating the gradient carries an explicit center color, which
// disables the single-triangle barycentric shortcut.
const PATH_GRAD_HAS_EXPLICIT_CENTER_COLOR = 1u;
// This flag bit shows that the payload colors are unassociated. The shader interpolates
// these colors, and then it premultiplies the result.
const PATH_GRAD_UNASSOCIATED_INTERPOLATION = 2u;
// Info-stream layout: a 7-word header (center point, max ray distance, and four
// center-color components) followed by 12-word edge records (start point, end
// point, and four components for each endpoint color).
Expand All @@ -447,7 +450,8 @@ fn path_grad_load_point(offset: u32) -> vec2<f32> {
return vec2<f32>(bitcast<f32>(info[offset]), bitcast<f32>(info[offset + 1u]));
}

// Loads an associated color stored as four f32 words in the info stream.
// Loads a color stored as four f32 words in the info stream. The flags of the
// gradient give the alpha representation of the color.
fn path_grad_load_color(offset: u32) -> vec4<f32> {
return vec4<f32>(
bitcast<f32>(info[offset]),
Expand Down Expand Up @@ -509,15 +513,28 @@ fn path_grad_point_on_triangle(v1: vec2<f32>, v2: vec2<f32>, v3: vec2<f32>, poin
}

// Evaluates the path gradient brush at a point, returning an associated color.
// Payload colors are associated before interpolation as required by CSS Color 4:
// CSS Color 4 interpolates associated colors. SVG 2 interpolates unassociated colors,
// so the shader premultiplies the result of an unassociated gradient.
// https://www.w3.org/TR/css-color-4/#interpolation-alpha
// https://www.w3.org/TR/SVG2/pservers.html#StopColorProperties
fn evaluate_path_gradient(path_grad: CmdPathGrad, point: vec2<f32>) -> vec4<f32> {
let color = interpolate_path_gradient(path_grad, point);
if (path_grad.flags & PATH_GRAD_UNASSOCIATED_INTERPOLATION) != 0u {
return premul_alpha(color);
}

return color;
}

// Interpolates the path gradient brush at a point. The result has the alpha
// representation of the payload colors.
// A three-edge gradient without an explicit center color interpolates
// its vertex colors barycentrically. Otherwise a ray is cast from the point
// away from the gradient center to find the nearest edge intersection; the
// interpolated edge color is then mixed toward the center color by the ratio
// of the point's distance from the edge to the center's distance from the
// edge. Returns transparent when the point is not covered by any edge.
fn evaluate_path_gradient(path_grad: CmdPathGrad, point: vec2<f32>) -> vec4<f32> {
fn interpolate_path_gradient(path_grad: CmdPathGrad, point: vec2<f32>) -> vec4<f32> {
let center = path_grad_load_point(path_grad.data_offset);
let center_color = path_grad_load_color(path_grad.data_offset + 3u);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public WebGPUBackdropAcrylicLayerEffect(float sigma, Color tint)
/// <param name="color">The acrylic tint.</param>
private void AddPasses(float sigma, Color color)
{
Vector4 vector = color.ToScaledVector4(PixelAlphaRepresentation.Unassociated);
Vector4 vector = color.ToScaledVector4(PixelAlphaRepresentation.Associated);

// Source RGB is retained by (1 - tint alpha), while the constant row contributes the
// premultiplied tint. Alpha is preserved so the backdrop keeps its existing coverage.
Expand All @@ -58,9 +58,9 @@ private void AddPasses(float sigma, Color color)
tint.M22 = keep;
tint.M33 = keep;
tint.M44 = 1F;
tint.M51 = vector.X * vector.W;
tint.M52 = vector.Y * vector.W;
tint.M53 = vector.Z * vector.W;
tint.M51 = vector.X;
tint.M52 = vector.Y;
tint.M53 = vector.Z;

WebGPUColorMatrixLayerEffect tintEffect = new(tint);
ReadOnlySpan<WebGPUShaderPass> tintPasses = tintEffect.GetShaderPasses();
Expand Down
122 changes: 59 additions & 63 deletions src/ImageSharp.Drawing.WebGPU/WebGPUSceneEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6398,6 +6398,7 @@ public static WebGPUEncodedScene Resolve(

gradientRamps.Add(new GpuGradientRampDescriptor(
gradientRamp.ColorStops,
gradientRamp.AlphaRepresentation,
gradientRowOffset + gradientRamp.RowIndex));
}

Expand Down Expand Up @@ -9229,7 +9230,7 @@ private static void AppendLinearGradientData(
{
uint indexMode = ((uint)gradientRowCount << 2) | MapExtendMode(brush.RepetitionMode);
AppendGradientRamp(ref gradientPixels);
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), gradientRowCount));
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), brush.AlphaRepresentation, gradientRowCount));
gradientRowCount++;

drawData.Add(indexMode);
Expand Down Expand Up @@ -9280,7 +9281,7 @@ private static void AppendRadialGradientData(
{
uint indexMode = ((uint)gradientRowCount << 2) | MapExtendMode(brush.RepetitionMode);
AppendGradientRamp(ref gradientPixels);
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), gradientRowCount));
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), brush.AlphaRepresentation, gradientRowCount));
gradientRowCount++;

PointF center0;
Expand Down Expand Up @@ -9330,7 +9331,7 @@ private static void AppendEllipticGradientData(
{
uint indexMode = ((uint)gradientRowCount << 2) | MapExtendMode(brush.RepetitionMode);
AppendGradientRamp(ref gradientPixels);
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), gradientRowCount));
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), brush.AlphaRepresentation, gradientRowCount));
gradientRowCount++;

// Brushes reach the encoder after batcher normalization, so gradient payload points are
Expand Down Expand Up @@ -9369,7 +9370,7 @@ private static void AppendSweepGradientData(
{
uint indexMode = ((uint)gradientRowCount << 2) | MapExtendMode(brush.RepetitionMode);
AppendGradientRamp(ref gradientPixels);
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), gradientRowCount));
gradientRamps.Add(new GpuGradientRampDescriptor(brush.ColorStops.ToArray(), brush.AlphaRepresentation, gradientRowCount));
gradientRowCount++;

float sweepDegrees = brush.EndAngleDegrees - brush.StartAngleDegrees;
Expand Down Expand Up @@ -9407,6 +9408,7 @@ private static void AppendPathGradientData(
{
ReadOnlySpan<PointF> points = brush.Points;
ReadOnlySpan<Color> colors = brush.Colors;
PixelAlphaRepresentation alphaRepresentation = brush.AlphaRepresentation;
int edgeCount = points.Length;
PointF center = default;

Expand All @@ -9432,7 +9434,7 @@ private static void AppendPathGradientData(
payload[0] = BitcastSingle(center.X);
payload[1] = BitcastSingle(center.Y);
payload[2] = BitcastSingle(maxDistance);
WriteAssociatedColor(payload, 3, brush.CenterColor);
WritePathGradientColor(payload, 3, brush.CenterColor, alphaRepresentation);

for (int i = 0; i < edgeCount; i++)
{
Expand All @@ -9446,14 +9448,22 @@ private static void AppendPathGradientData(
payload[payloadOffset + 1] = BitcastSingle(start.Y);
payload[payloadOffset + 2] = BitcastSingle(end.X);
payload[payloadOffset + 3] = BitcastSingle(end.Y);
WriteAssociatedColor(payload, payloadOffset + 4, colors[i % colors.Length]);
WriteAssociatedColor(payload, payloadOffset + 8, colors[(i + 1) % colors.Length]);
WritePathGradientColor(payload, payloadOffset + 4, colors[i % colors.Length], alphaRepresentation);
WritePathGradientColor(payload, payloadOffset + 8, colors[(i + 1) % colors.Length], alphaRepresentation);
}

// These bits match PATH_GRAD_HAS_EXPLICIT_CENTER_COLOR and PATH_GRAD_UNASSOCIATED_INTERPOLATION
// in fine.wgsl.
uint flags = brush.HasExplicitCenterColor ? 1U : 0U;
if (alphaRepresentation != PixelAlphaRepresentation.Associated)
{
flags |= 2U;
}

pathGradientData.Advance(payload.Length);
drawData.Add((uint)dataOffset);
drawData.Add((uint)edgeCount);
drawData.Add(brush.HasExplicitCenterColor ? 1U : 0U);
drawData.Add(flags);
drawData.Add(0U);
}

Expand All @@ -9475,12 +9485,13 @@ private static void AppendGradientRamp(ref OwnedStream<uint> gradientPixels)
}

/// <summary>
/// Evaluates the premultiplied gradient color at the normalized parameter.
/// Evaluates the gradient color at the normalized parameter.
/// </summary>
/// <param name="colorStops">The gradient color stops, ordered by ratio.</param>
/// <param name="alphaRepresentation">The alpha representation of the stop colors during interpolation.</param>
/// <param name="t">The normalized sample position in the range [0, 1].</param>
/// <returns>The associated floating-point sample.</returns>
public static Vector4 EvaluateGradientColor(ReadOnlySpan<ColorStop> colorStops, float t)
/// <returns>The floating-point sample in <paramref name="alphaRepresentation"/>.</returns>
public static Vector4 EvaluateGradientColor(ReadOnlySpan<ColorStop> colorStops, PixelAlphaRepresentation alphaRepresentation, float t)
{
// Walk the stop list once to find the enclosing interval, then interpolate within it.
ColorStop from = colorStops[0];
Expand All @@ -9498,16 +9509,16 @@ public static Vector4 EvaluateGradientColor(ReadOnlySpan<ColorStop> colorStops,

if (from.Color.Equals(to.Color) || to.Ratio == from.Ratio)
{
return from.Color.ToScaledVector4(PixelAlphaRepresentation.Associated);
return from.Color.ToScaledVector4(alphaRepresentation);
}

float localT = (t - from.Ratio) / (to.Ratio - from.Ratio);

// CSS Color 4 requires alpha premultiplication before interpolation. The ramp stores
// associated RGBA16Float directly, matching the fine shader's internal composition space.
// CSS Color 4 interpolates associated colors. SVG 2 interpolates unassociated colors.
// The stops use the alpha representation of the brush.
return Vector4.Lerp(
from.Color.ToScaledVector4(PixelAlphaRepresentation.Associated),
to.Color.ToScaledVector4(PixelAlphaRepresentation.Associated),
from.Color.ToScaledVector4(alphaRepresentation),
to.Color.ToScaledVector4(alphaRepresentation),
localT);
}

Expand All @@ -9533,16 +9544,17 @@ public static uint PackHalf2(float x, float y)
=> BitConverter.HalfToUInt16Bits((Half)x) | ((uint)BitConverter.HalfToUInt16Bits((Half)y) << 16);

/// <summary>
/// Writes one associated color to the path-gradient payload without reducing it to RGBA8 first.
/// Writes one color to the path-gradient payload without reducing it to RGBA8 first.
/// </summary>
/// <param name="destination">The payload receiving four consecutive floating-point words.</param>
/// <param name="offset">The destination word offset.</param>
/// <param name="color">The color to convert to associated components.</param>
private static void WriteAssociatedColor(Span<uint> destination, int offset, in Color color)
/// <param name="color">The color to write.</param>
/// <param name="alphaRepresentation">The alpha representation of the colors during interpolation.</param>
private static void WritePathGradientColor(Span<uint> destination, int offset, in Color color, PixelAlphaRepresentation alphaRepresentation)
{
// Path gradients interpolate endpoint colors directly in the shader. Keeping the source
// precision here matches the CPU renderer and defers quantization until target encoding.
Vector4 vector = color.ToScaledVector4(PixelAlphaRepresentation.Associated);
Vector4 vector = color.ToScaledVector4(alphaRepresentation);
destination[offset] = BitcastSingle(vector.X);
destination[offset + 1] = BitcastSingle(vector.Y);
destination[offset + 2] = BitcastSingle(vector.Z);
Expand Down Expand Up @@ -10430,9 +10442,8 @@ public void SpecializeBrushColors<TPixel>()
return;
}

PixelAlphaRepresentation alphaRepresentation = TPixel.GetPixelTypeInfo().AlphaRepresentation;
this.SpecializeSolidColors<TPixel>(alphaRepresentation);
this.SpecializeGradientRamps<TPixel>(alphaRepresentation);
this.SpecializeSolidColors<TPixel>();
this.SpecializeGradientRamps<TPixel>();
this.specializedPixelType = typeof(TPixel);
}

Expand All @@ -10442,22 +10453,16 @@ public void SpecializeBrushColors<TPixel>()
/// it creates its CPU renderer.
/// </summary>
/// <typeparam name="TPixel">The pixel format of the target.</typeparam>
/// <param name="alphaRepresentation">The alpha representation of <typeparamref name="TPixel"/>.</param>
private void SpecializeSolidColors<TPixel>(PixelAlphaRepresentation alphaRepresentation)
private void SpecializeSolidColors<TPixel>()
where TPixel : unmanaged, IPixel<TPixel>
{
for (int i = 0; i < this.solidColors.Count; i++)
{
GpuSolidColorDescriptor descriptor = this.solidColors[i];
Vector4 color = descriptor.Color.ToPixel<TPixel>().ToScaledVector4();
if (alphaRepresentation != PixelAlphaRepresentation.Associated)
{
// Associating rounds the product into binary16; see the precision contract on
// SpecializeBrushColors.
float alpha = color.W;
color *= alpha;
color.W = alpha;
}

// For a TPixel with unassociated alpha, the associated product rounds to binary16.
// The precision contract on SpecializeBrushColors gives the effect.
Vector4 color = descriptor.Color.ToPixel<TPixel>().ToAssociatedScaledVector4();

int wordIndex = checked((int)this.Layout.DrawDataBase + descriptor.DrawDataWordOffset);
this.SetSceneWord(wordIndex, WebGPUSceneEncoder.PackHalf2(color.X, color.Y));
Expand All @@ -10471,8 +10476,7 @@ private void SpecializeSolidColors<TPixel>(PixelAlphaRepresentation alphaReprese
/// encoders perform before blending.
/// </summary>
/// <typeparam name="TPixel">The pixel format of the target.</typeparam>
/// <param name="alphaRepresentation">The alpha representation of <typeparamref name="TPixel"/>.</param>
private void SpecializeGradientRamps<TPixel>(PixelAlphaRepresentation alphaRepresentation)
private void SpecializeGradientRamps<TPixel>()
where TPixel : unmanaged, IPixel<TPixel>
{
if (this.gradientPixelsOwner is null)
Expand All @@ -10484,37 +10488,22 @@ private void SpecializeGradientRamps<TPixel>(PixelAlphaRepresentation alphaRepre
for (int i = 0; i < this.gradientRamps.Count; i++)
{
GpuGradientRampDescriptor descriptor = this.gradientRamps[i];
bool associated = descriptor.AlphaRepresentation == PixelAlphaRepresentation.Associated;
int rowBase = descriptor.RowIndex * WebGPUSceneEncoder.GradientRowWordCount;
for (int x = 0; x < WebGPUSceneEncoder.GradientWidth; x++)
{
float t = x / (float)(WebGPUSceneEncoder.GradientWidth - 1);
Vector4 color = WebGPUSceneEncoder.EvaluateGradientColor(descriptor.ColorStops, t);
if (alphaRepresentation == PixelAlphaRepresentation.Associated)
{
color = TPixel.FromScaledVector4(color).ToScaledVector4();
}
else
{
// The CPU's straight-alpha encoder undoes the interpolation-time
// premultiplication before converting to TPixel, so the same division
// precedes the snap. Re-associating rounds the product into binary16;
// see the precision contract on SpecializeBrushColors.
float alpha = color.W;
if (alpha > 0)
{
color /= alpha;
color.W = alpha;
}
else
{
color = Vector4.Zero;
}
Vector4 color = WebGPUSceneEncoder.EvaluateGradientColor(descriptor.ColorStops, descriptor.AlphaRepresentation, t);

color = TPixel.FromScaledVector4(color).ToScaledVector4();
float snappedAlpha = color.W;
color *= snappedAlpha;
color.W = snappedAlpha;
}
// The texel snaps through TPixel, as in the CPU gradient encoders. The ramp stores
// associated RGBA16Float, which is the composition space of the fine shader.
// For a TPixel with unassociated alpha, the associated product rounds to binary16.
// The precision contract on SpecializeBrushColors gives the effect.
TPixel pixel = associated
? TPixel.FromAssociatedScaledVector4(color)
: TPixel.FromUnassociatedScaledVector4(color);

color = pixel.ToAssociatedScaledVector4();

gradientPixels[rowBase + (x * 2)] = WebGPUSceneEncoder.PackHalf2(color.X, color.Y);
gradientPixels[rowBase + (x * 2) + 1] = WebGPUSceneEncoder.PackHalf2(color.Z, color.W);
Expand Down Expand Up @@ -10749,10 +10738,12 @@ internal readonly struct GpuGradientRampDescriptor
/// Initializes a new instance of the <see cref="GpuGradientRampDescriptor"/> struct.
/// </summary>
/// <param name="colorStops">The gradient color stops, ordered by ratio.</param>
/// <param name="alphaRepresentation">The alpha representation of the stop colors during interpolation.</param>
/// <param name="rowIndex">The ramp texture row the gradient occupies.</param>
public GpuGradientRampDescriptor(ColorStop[] colorStops, int rowIndex)
public GpuGradientRampDescriptor(ColorStop[] colorStops, PixelAlphaRepresentation alphaRepresentation, int rowIndex)
{
this.ColorStops = colorStops;
this.AlphaRepresentation = alphaRepresentation;
this.RowIndex = rowIndex;
}

Expand All @@ -10761,6 +10752,11 @@ public GpuGradientRampDescriptor(ColorStop[] colorStops, int rowIndex)
/// </summary>
public ColorStop[] ColorStops { get; }

/// <summary>
/// Gets the alpha representation of the stop colors during interpolation.
/// </summary>
public PixelAlphaRepresentation AlphaRepresentation { get; }

/// <summary>
/// Gets the ramp texture row the gradient occupies.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/ImageSharp.Drawing/ImageSharp.Drawing.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="SixLabors.Fonts" Version="3.2.1" />
<PackageReference Include="SixLabors.ImageSharp" Version="4.1.2" />
<PackageReference Include="SixLabors.ImageSharp" Version="5.0.0-alpha.0.38" />
<PackageReference Include="SixLabors.PolygonClipper" Version="2.0.0-alpha.0.2" />
</ItemGroup>
<ItemGroup>
Expand Down
Loading
Loading