From 9ae0a88829a81b19ff951843b1eb295707d14c8b Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 09:14:26 -0400 Subject: [PATCH 01/16] Add Surface.Resize/ResizeToFit and smooth image resampling Add ResamplingMode and a separable, premultiplied-alpha resampling engine; route PDF, PPTX, SVG images and tile paints through it, with tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../PdfDocument.Images.cs | 110 +++-- .../PptxDocument.Images.cs | 108 +++- .../SvgCodec.Elements.cs | 27 +- .../SvgCodec.Filters.FeImage.cs | 4 +- .../SvgCodec.Image.cs | 64 ++- .../SvgCodec.Patterns.cs | 81 ++- .../Canvas/ResamplingMode.cs | 50 ++ .../Canvas/Surface.cs | 118 +++++ .../Canvas/SurfaceResampler.Engine.cs | 465 ++++++++++++++++++ .../Canvas/SurfaceResampler.cs | 74 +-- .../DemaConsulting.CanvasNet.csproj | 4 + .../Drawing/ScanlineRasterizer.cs | 14 +- .../Drawing/TilePaintEvaluator.cs | 75 ++- .../PdfDocumentImageDownscaleTests.cs | 30 +- .../PdfDocumentJpxTests.cs | 42 +- .../PdfDocumentTests.cs | 88 ++-- .../PdfImageResamplingTests.cs | 90 ++++ .../PdfSystemIntegrationTests.cs | 21 +- .../SvgImageResamplingTests.cs | 95 ++++ .../Canvas/SurfaceResamplerTests.cs | 69 +++ .../SurfaceResizeCodecRoundTripTests.cs | 77 +++ .../Canvas/SurfaceResizeTests.cs | 332 +++++++++++++ .../Drawing/TilePaintEvaluatorTests.cs | 69 +++ 23 files changed, 1889 insertions(+), 218 deletions(-) create mode 100644 src/DemaConsulting.CanvasNet/Canvas/ResamplingMode.cs create mode 100644 src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs create mode 100644 test/DemaConsulting.CanvasNet.Pdf.Tests/PdfImageResamplingTests.cs create mode 100644 test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs create mode 100644 test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeCodecRoundTripTests.cs create mode 100644 test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs diff --git a/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs b/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs index b43b98a13..7c3bccbdc 100644 --- a/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs +++ b/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs @@ -269,7 +269,7 @@ private Matrix3x2 ReadOptionalMatrix(PdfObject dictionary, string key = "Matrix" /// byte, and /Indexed images may not be 16-bit). A /Filter /JPXDecode image (and no other filter) is decoded /// by . An explicit /SMask image (any supported /// encoding, including JPXDecode) supplies the alpha channel, resampled to the - /// base image with nearest-neighbor sampling (the mask must be a single-component, + /// base image with bilinear resampling when the sizes differ (the mask must be a single-component, /// non-/Indexed image and is multiplied into the base surface in place); the /// /Decode array is applied to the samples of every encoding (including soft-mask /// images and DCTDecode images; 4-channel CMYK/YCCK JPEGs are rejected outright by @@ -339,21 +339,32 @@ private Surface DecodeImageXObject(PdfObject stream) /// /// Multiplies the alpha channel of , in place, by the luminance /// (red channel of the DeviceGray-decoded mask) of , resampling the - /// mask to the image's dimensions with nearest-neighbor sampling. + /// mask to the image's dimensions with bilinear resampling when the sizes differ. /// private static void ApplySoftMask(Surface image, Surface mask) { - for (var y = 0; y < image.Height; y++) + // A mask of a different size is smoothly resampled (bilinear) to the image size first so + // a low-resolution soft mask produces smooth edges rather than blocks + var resized = mask.Width == image.Width && mask.Height == image.Height + ? null + : mask.Resize(image.Width, image.Height, ResamplingMode.Bilinear); + try { - var my = (int)((long)y * mask.Height / image.Height); - for (var x = 0; x < image.Width; x++) + var effective = resized ?? mask; + for (var y = 0; y < image.Height; y++) { - var mx = (int)((long)x * mask.Width / image.Width); - var pixel = image[x, y]; - var opacity = mask[mx, my].R; - image[x, y] = new Rgba32(pixel.R, pixel.G, pixel.B, (byte)(((pixel.A * opacity) + 127) / 255)); + for (var x = 0; x < image.Width; x++) + { + var pixel = image[x, y]; + var opacity = effective[x, y].R; + image[x, y] = new Rgba32(pixel.R, pixel.G, pixel.B, (byte)(((pixel.A * opacity) + 127) / 255)); + } } } + finally + { + resized?.Dispose(); + } } /// @@ -910,10 +921,12 @@ private static Rgba32 SamplesToColor(PdfColorSpace colorSpace, byte[] decoded, i /// device-space bounding box. /// /// - /// When the image is enlarged or drawn 1:1, the nearest source pixel is sampled (no - /// interpolation). When it is shrunk, it is first (when the reduction is 1.5:1 or more) area-averaged once per draw by - /// SurfaceResampler (an integer box prefilter) and is then sampled bilinearly, so thin - /// features such as one-pixel rules are attenuated rather than dropped. A non-invertible (degenerate) silently paints + /// An axis-aligned image (no rotation or skew) is resampled once per draw by + /// SurfaceResampler to exactly the device pixels it covers (area averaging when + /// shrunk, Catmull-Rom bicubic when enlarged, an exact copy at whole-pixel 1:1) and that + /// window is composited 1:1, so thin features such as one-pixel rules are attenuated rather + /// than dropped. A rotated or skewed image is prefiltered (box reduction when shrunk) and + /// inverse-mapped with bilinear sampling. A non-invertible (degenerate) silently paints /// nothing, rather than throwing. Per the PDF specification's image-space convention, /// image sample row 0 is the top of the unit square (the opposite of /// user-space's y-up convention): row = floor((1 - v) * image.Height). Each sampled @@ -943,11 +956,29 @@ private void CompositeImageOntoSurface(Surface image, Matrix3x2 ctm) } var pixelToDevice = Matrix3x2.CreateScale(1f / image.Width, -1f / image.Height) * Matrix3x2.CreateTranslation(0f, 1f) * ctm; - var sampled = SurfaceResampler.Prefilter(image, pixelToDevice, out var bilinear); + + // Axis-aligned placement (the overwhelmingly common case): resample once to the exact + // device-pixel rectangle the image covers, then composite that window 1:1 + if (SurfaceResampler.TryResampleToDevice(image, pixelToDevice, _surface.Width, _surface.Height, ResamplingMode.Auto, out var window, out var originX, out var originY)) + { + using (window) + { + if (window is not null) + { + CompositeWindow(window, originX, originY); + } + } + + return; + } + + // Rotated or skewed placement: inverse-map each destination pixel and sample a + // prefiltered source bilinearly + var sampled = SurfaceResampler.Prefilter(image, pixelToDevice, out _); var reduced = !ReferenceEquals(sampled, image); try { - CompositeSampledImage(image, sampled, bilinear, ctm, inverse); + CompositeSampledImage(sampled, ctm, inverse); } finally { @@ -958,8 +989,41 @@ private void CompositeImageOntoSurface(Surface image, Matrix3x2 ctm) } } - /// Paints (the original or its prefiltered reduction) through . - private void CompositeSampledImage(Surface image, Surface sampled, bool bilinear, Matrix3x2 ctm, Matrix3x2 inverse) + /// + /// Composites a device-aligned resampled image window 1:1 at (, + /// ), scaling each pixel's alpha by the current clip coverage. + /// + private void CompositeWindow(Surface window, int originX, int originY) + { + var clip = _gs?.Clip; + for (var y = 0; y < window.Height; y++) + { + for (var x = 0; x < window.Width; x++) + { + var dx = originX + x; + var dy = originY + y; + var clipCoverage = clip?.GetCoverage(dx, dy) ?? 1f; + if (clipCoverage <= 0f) + { + continue; + } + + var sourcePixel = window[x, y]; + if (clipCoverage < 1f) + { + // Round the same way Surface's own compositing pipeline does (AwayFromZero) + sourcePixel = new Rgba32( + sourcePixel.R, sourcePixel.G, sourcePixel.B, + (byte)Math.Round(sourcePixel.A * clipCoverage, MidpointRounding.AwayFromZero)); + } + + _surface[dx, dy] = Rgba32.CompositeOver(_surface[dx, dy], sourcePixel); + } + } + } + + /// Paints (the original or its prefiltered reduction) through with bilinear sampling (the rotated/skewed fallback). + private void CompositeSampledImage(Surface sampled, Matrix3x2 ctm, Matrix3x2 inverse) { var clip = _gs?.Clip; var corner00 = Vector2.Transform(new Vector2(0, 0), ctm); @@ -996,17 +1060,7 @@ private void CompositeSampledImage(Surface image, Surface sampled, bool bilinear continue; } - Rgba32 sourcePixel; - if (bilinear) - { - sourcePixel = SurfaceResampler.SampleBilinear(sampled, u, 1 - v); - } - else - { - var column = Math.Clamp((int)Math.Floor(u * image.Width), 0, image.Width - 1); - var row = Math.Clamp((int)Math.Floor((1 - v) * image.Height), 0, image.Height - 1); - sourcePixel = image[column, row]; - } + var sourcePixel = SurfaceResampler.SampleBilinear(sampled, u, 1 - v); if (clipCoverage < 1f) { diff --git a/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs b/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs index 8b3425187..e5b7f969c 100644 --- a/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs +++ b/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs @@ -598,10 +598,14 @@ internal static Path ResolvePictureGeometryPath(XElement spPrElement, float widt /// Composites a decoded picture onto , /// mapping its (optionally -cropped) unit square through a /// CreateScale(widthEmu, heightEmu) * shapeToSurfaceTransform transform and - /// nearest-neighbor sampling the source pixel for every destination pixel in the - /// transformed footprint's device-space bounding box - mirroring + /// smoothly resampling the source for every destination pixel in the transformed + /// footprint's device-space bounding box: an axis-aligned picture is resampled once + /// (: area averaging when shrunk, Catmull-Rom bicubic when + /// enlarged) to the exact device rectangle it covers, while a rotated or skewed picture + /// inverse-maps each destination pixel and samples a prefiltered source bilinearly - + /// mirroring /// DemaConsulting.CanvasNet.Pdf's PdfDocument.Images.cs's own - /// CompositeImageOntoSurface bounding-box rasterization loop exactly, with one + /// CompositeImageOntoSurface approach, with one /// deliberate difference: no (1 - v) row flip is applied, because /// (unlike PDF's own y-up image-space convention) this package's shape-local/surface space /// is already y-down (see PaintTextLayout's own documented y-down convention) - @@ -697,46 +701,96 @@ internal static void PaintPicture( PathFiller.Fill(clipMask, transformedClip, new Rgba32(255, 255, 255, 255)); } - for (var y = startY; y <= endY; y++) + // Axis-aligned pictures (the overwhelmingly common case) are resampled once to the exact + // device-pixel rectangle they cover and composited 1:1; the srcRect crop becomes part of + // the pixel-to-device mapping. + var cropWidth = Math.Max(1e-6f, 1f - left - right); + var cropHeight = Math.Max(1e-6f, 1f - top - bottom); + var pixelToUnit = new Matrix3x2( + 1f / (image.Width * cropWidth), 0f, + 0f, 1f / (image.Height * cropHeight), + -left / cropWidth, -top / cropHeight); + var pixelToSurface = pixelToUnit * unitToSurface; + if (SurfaceResampler.TryResampleToDevice(image, pixelToSurface, surface.Width, surface.Height, ResamplingMode.Auto, out var window, out var originX, out var originY)) { - for (var x = startX; x <= endX; x++) + using (window) { - var devicePoint = new Vector2(x + 0.5f, y + 0.5f); - var unitPoint = Vector2.Transform(devicePoint, surfaceToUnit); - var u = unitPoint.X; - var v = unitPoint.Y; - if (u < 0 || u >= 1 || v < 0 || v >= 1) + if (window is not null) { - continue; + CompositeWindow(surface, window, originX, originY, clipMask); } + } - byte maskAlpha = 255; - if (clipMask is not null) + return; + } + + // Rotated or skewed pictures: inverse-map each destination pixel and sample the + // source (prefiltered when shrinking) bilinearly. + var prefiltered = SurfaceResampler.Prefilter(image, pixelToSurface, out _); + try + { + for (var y = startY; y <= endY; y++) + { + for (var x = startX; x <= endX; x++) { - maskAlpha = clipMask[x, y].A; + var devicePoint = new Vector2(x + 0.5f, y + 0.5f); + var unitPoint = Vector2.Transform(devicePoint, surfaceToUnit); + var u = unitPoint.X; + var v = unitPoint.Y; + if (u < 0 || u >= 1 || v < 0 || v >= 1) + { + continue; + } + + var maskAlpha = clipMask is null ? (byte)255 : clipMask[x, y].A; if (maskAlpha == 0) { continue; } - } - // Remap the unit-square sample point through the srcRect crop: imageU/imageV are - // the fraction of the way across the *uncropped* source image this destination - // pixel samples from - no (1 - v) flip, per this method's own remarks. - var imageU = left + u * (1f - left - right); - var imageV = top + v * (1f - top - bottom); + // Remap the unit-square sample point through the srcRect crop; no (1 - v) flip + var imageU = left + (u * (1f - left - right)); + var imageV = top + (v * (1f - top - bottom)); + var sourcePixel = SurfaceResampler.SampleBilinear(prefiltered, imageU, imageV); + surface[x, y] = Rgba32.CompositeOver(surface[x, y], ScaleAlpha(sourcePixel, maskAlpha)); + } + } + } + finally + { + if (!ReferenceEquals(prefiltered, image)) + { + prefiltered.Dispose(); + } + } + } - var column = Math.Clamp((int)MathF.Floor(imageU * image.Width), 0, image.Width - 1); - var row = Math.Clamp((int)MathF.Floor(imageV * image.Height), 0, image.Height - 1); - var sourcePixel = image[column, row]; - if (maskAlpha != 255) + /// + /// Composites a device-aligned resampled picture window onto + /// one pixel at a time (Porter-Duff "over"), scaling alpha by the optional clip mask. + /// + private static void CompositeWindow(Surface surface, Surface window, int originX, int originY, Surface? clipMask) + { + for (var y = 0; y < window.Height; y++) + { + for (var x = 0; x < window.Width; x++) + { + var dx = originX + x; + var dy = originY + y; + var maskAlpha = clipMask is null ? (byte)255 : clipMask[dx, dy].A; + if (maskAlpha == 0) { - var scaledAlpha = (byte)Math.Clamp(MathF.Round(sourcePixel.A * (maskAlpha / 255f)), 0, 255); - sourcePixel = new Rgba32(sourcePixel.R, sourcePixel.G, sourcePixel.B, scaledAlpha); + continue; } - surface[x, y] = Rgba32.CompositeOver(surface[x, y], sourcePixel); + surface[dx, dy] = Rgba32.CompositeOver(surface[dx, dy], ScaleAlpha(window[x, y], maskAlpha)); } } } + + /// Scales a pixel's alpha by / 255. + private static Rgba32 ScaleAlpha(Rgba32 pixel, byte maskAlpha) => + maskAlpha == 255 + ? pixel + : new Rgba32(pixel.R, pixel.G, pixel.B, (byte)Math.Clamp(MathF.Round(pixel.A * (maskAlpha / 255f)), 0, 255)); } diff --git a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Elements.cs b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Elements.cs index 798354c3c..f88c8a03a 100644 --- a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Elements.cs +++ b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Elements.cs @@ -116,6 +116,11 @@ private enum TextAnchor /// percentage resolves against. See /// 's remarks. /// + /// + /// when the inherited image-rendering property selects + /// pixelated, crisp-edges or optimizeSpeed, so a raster image + /// is drawn with nearest-neighbor sampling instead of smooth resampling. + /// private sealed record RenderState( string Fill, string Stroke, @@ -138,7 +143,8 @@ private sealed record RenderState( string MarkerMid, string MarkerEnd, float ViewportWidth, - float ViewportHeight) + float ViewportHeight, + bool PixelatedImages = false) { /// /// The default render state every document starts with, matching the SVG/CSS initial @@ -175,7 +181,8 @@ private sealed record RenderState( MarkerMid: "none", MarkerEnd: "none", ViewportWidth: 300f, - ViewportHeight: 150f); + ViewportHeight: 150f, + PixelatedImages: false); } /// @@ -631,7 +638,8 @@ _ when string.Equals(dashArrayAttr.Trim(), "none", StringComparison.OrdinalIgnor TextAnchor = ParseTextAnchor(Styled("text-anchor")) ?? parent.TextAnchor, MarkerStart = Styled("marker-start") ?? parent.MarkerStart, MarkerMid = Styled("marker-mid") ?? parent.MarkerMid, - MarkerEnd = Styled("marker-end") ?? parent.MarkerEnd + MarkerEnd = Styled("marker-end") ?? parent.MarkerEnd, + PixelatedImages = ParseImageRendering(Styled("image-rendering")) ?? parent.PixelatedImages }; } @@ -650,6 +658,19 @@ _ when string.Equals(dashArrayAttr.Trim(), "none", StringComparison.OrdinalIgnor /// private static float? ParseStyledOptionalOpacity(string? raw) => raw == null ? null : ParseOpacityValue(raw); + /// Parses an image-rendering keyword into "draw nearest-neighbor" (true) or "smooth" (false). + /// The raw value, or if absent. + /// + /// for pixelated/crisp-edges/optimizeSpeed, + /// for any other recognized keyword, if absent (inherit). + /// + private static bool? ParseImageRendering(string? raw) => raw?.Trim().ToLowerInvariant() switch + { + null => null, + "pixelated" or "crisp-edges" or "optimizespeed" => true, + _ => false + }; + /// Parses a fill-rule/clip-rule-style keyword. /// The attribute's raw value, or if absent. /// The matching , or if unrecognized/absent. diff --git a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.FeImage.cs b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.FeImage.cs index fb8e868c6..d247c90e8 100644 --- a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.FeImage.cs +++ b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.FeImage.cs @@ -95,7 +95,9 @@ private static Surface ApplyFeImage( primitiveSubregion.Y, primitiveSubregion.Width, primitiveSubregion.Height, - pixelToImage); + imageToPixel, + pixelToImage, + nearest: false); CopySurfaceInto(sampled, output, primitiveSubregion.X, primitiveSubregion.Y); return output; } diff --git a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs index 356dc6aa7..8e698dbec 100644 --- a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs +++ b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs @@ -65,10 +65,12 @@ public static partial class SvgCodec // (or shared - itself a non-trivial design question) work budgets, and a new // recursion-depth guard distinct from MaxElementDepth/MaxUseDepth - a disproportionate cost // for a rarely-used feature, deferred to a future phase. - // - Only nearest-neighbor sampling is performed (see SampleImageIntoRegion below), matching - // this codec's one existing raster-resampling precedent (SampleTileIntoRegion in - // SvgCodec.Patterns.cs) rather than introducing a second, inconsistent bilinear/bicubic - // quality tier solely for . + // - The raster is resampled smoothly (see SampleImageIntoRegion below): an axis-aligned + // placement is resampled once to its device-pixel rectangle by the shared SurfaceResampler + // engine (area averaging when shrunk, Catmull-Rom bicubic when enlarged); a rotated or + // skewed placement falls back to inverse-mapped bilinear sampling of a prefiltered source. + // The CSS "image-rendering" property values pixelated, crisp-edges and optimizeSpeed select + // nearest-neighbor sampling instead. // - An with no explicit width/height (or an explicit "0") renders nothing: this codec // does not implement SVG2's "auto" intrinsic-size resolution from the decoded raster (i.e. // inferring width/height from the decoded image when the attribute is absent) - a @@ -247,7 +249,7 @@ private static void RenderImageWithEffects( // Sample the decoded raster into a fresh region-sized buffer via non-tiling // inverse-transform sampling (see SampleImageIntoRegion), then apply clip-path -> mask -> // filter in SVG's defined order, exactly like RenderShapeEffectsPipeline - var content = SampleImageIntoRegion(decodedSurface, pixelX, pixelY, pixelWidth, pixelHeight, pixelToImage); + var content = SampleImageIntoRegion(decodedSurface, pixelX, pixelY, pixelWidth, pixelHeight, imageToPixel, pixelToImage, state.PixelatedImages); if (clipPathElement != null) { @@ -369,7 +371,8 @@ private static bool TryParseDataUri(string href, out string mimeType, out string /// Samples into a fresh region-sized buffer, one pixel at /// a time: each destination pixel is inverse-mapped through /// back into the decoded raster's own intrinsic pixel - /// space and sampled nearest-neighbor, or left fully transparent when the inverse-mapped + /// space and sampled smoothly (nearest-neighbor only for image-rendering: pixelated + /// and its synonyms), or left fully transparent when the inverse-mapped /// point falls outside [0, decodedSurface.Width) x [0, decodedSurface.Height) - the /// letterboxed/pillarboxed (or sliced-away) area a non-none/non-exactly-matching /// preserveAspectRatio fit can leave within the placement rect. @@ -379,7 +382,9 @@ private static bool TryParseDataUri(string href, out string mimeType, out string /// The painted region's own pixel-space Y origin. /// The painted region's own pixel width. /// The painted region's own pixel height. - /// The inverse of the composed image-content-space-to-pixel-space transform. + /// The composed image-content-space-to-pixel-space transform. + /// The inverse of . + /// to sample nearest-neighbor (image-rendering: pixelated) instead of smoothing. /// A new region-sized buffer, ready for (after any clip/mask/filter is applied). /// /// Deliberately distinct from SampleTileIntoRegion (SvgCodec.Patterns.cs): a @@ -397,12 +402,37 @@ private static Surface SampleImageIntoRegion( int pixelY, int pixelWidth, int pixelHeight, - Matrix3x2 pixelToImage) + Matrix3x2 imageToPixel, + Matrix3x2 pixelToImage, + bool nearest) { var result = new Surface(pixelWidth, pixelHeight); var decodedWidth = decodedSurface.Width; var decodedHeight = decodedSurface.Height; + // Axis-aligned placement: resample once to the exact device rectangle and copy it in + var imageToRegion = imageToPixel * Matrix3x2.CreateTranslation(-pixelX, -pixelY); + if (SurfaceResampler.TryResampleToDevice( + decodedSurface, imageToRegion, pixelWidth, pixelHeight, + nearest ? ResamplingMode.Nearest : ResamplingMode.Auto, out var window, out var originX, out var originY)) + { + using (window) + { + if (window is not null) + { + for (var row = 0; row < window.Height; row++) + { + window.GetRowSpan(row).CopyTo(result.GetRowSpan(originY + row).Slice(originX, window.Width)); + } + } + } + + return result; + } + + // Rotated or skewed: inverse-map each pixel; smooth mode samples a prefiltered source bilinearly + var smooth = nearest ? decodedSurface : SurfaceResampler.Prefilter(decodedSurface, imageToRegion, out _); + for (var row = 0; row < pixelHeight; row++) { var resultRow = result.GetRowSpan(row); @@ -425,12 +455,24 @@ private static Surface SampleImageIntoRegion( continue; } - var sourceX = Math.Clamp((int)imagePoint.X, 0, decodedWidth - 1); - var sourceY = Math.Clamp((int)imagePoint.Y, 0, decodedHeight - 1); - resultRow[col] = decodedSurface.GetRowSpan(sourceY)[sourceX]; + if (nearest) + { + var sourceX = Math.Clamp((int)imagePoint.X, 0, decodedWidth - 1); + var sourceY = Math.Clamp((int)imagePoint.Y, 0, decodedHeight - 1); + resultRow[col] = decodedSurface.GetRowSpan(sourceY)[sourceX]; + } + else + { + resultRow[col] = SurfaceResampler.SampleBilinear(smooth, imagePoint.X / decodedWidth, imagePoint.Y / decodedHeight); + } } } + if (!ReferenceEquals(smooth, decodedSurface)) + { + smooth.Dispose(); + } + return result; } } diff --git a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs index c85d8d7af..e91f89cb8 100644 --- a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs +++ b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs @@ -71,10 +71,11 @@ public static partial class SvgCodec // through the ordinary recursive RenderElement walk with elementDepth + 1 - exactly the // same reliance ApplyMask's own remarks document for a mask-reference cycle. No separate // pattern-specific cycle/depth guard is implemented. - // - Tile sampling is nearest-neighbor only (matching this codec's existing "no bilinear - // resampling anywhere" convention); a rotated/skewed patternTransform therefore produces a - // tiled result with the same per-tile-pixel aliasing any other nearest-neighbor sampler - // would. + // - Tile sampling is nearest-neighbor when the rendered tile buffer is drawn at about one + // device pixel per buffer pixel (within 5 percent, the usual device-scale case, which stays + // exact); a magnified tile (for example a rotated/skewed or scaled patternTransform) is + // sampled bilinearly with wrap-around, and a minified tile is first area-averaged to its + // device size by the shared SurfaceResampler engine so thin features are not dropped. /// /// The maximum pixel-space dimension (either axis) a single rendered pattern tile buffer @@ -509,7 +510,8 @@ private static bool TryComputeContentRenderTransform( /// time: each destination pixel is inverse-mapped through /// back into grid space, wrapped (modulo) by the tile's own / /// , rescaled into 's own pixel - /// coordinates, and sampled nearest-neighbor - then that sample's own alpha is multiplied by + /// coordinates, and sampled (nearest-neighbor at about 1:1, bilinear when magnified, from an + /// area-averaged copy when minified) - then that sample's own alpha is multiplied by /// 's own alpha at the same destination pixel (a fractional, /// antialiased generalization of 's binary coverage-multiply). /// @@ -539,6 +541,59 @@ private static Surface SampleTileIntoRegion( Matrix3x2 inverseGridTransform) { var result = new Surface(pixelWidth, pixelHeight); + + // Classify the device scale of one tile-buffer pixel (see this file's sampling remarks) + var magnified = false; + Surface? minified = null; + if (Matrix3x2.Invert(inverseGridTransform, out var gridToPixel)) + { + var deviceX = Math.Sqrt(((double)gridToPixel.M11 * gridToPixel.M11) + ((double)gridToPixel.M12 * gridToPixel.M12)) * tileWidth / tileBuffer.Width; + var deviceY = Math.Sqrt(((double)gridToPixel.M21 * gridToPixel.M21) + ((double)gridToPixel.M22 * gridToPixel.M22)) * tileHeight / tileBuffer.Height; + if (double.IsFinite(deviceX) && double.IsFinite(deviceY) && deviceX > 0 && deviceY > 0) + { + if (deviceX > 1.05 || deviceY > 1.05) + { + magnified = true; + } + else if (deviceX < 0.95 || deviceY < 0.95) + { + minified = tileBuffer.Resize( + deviceX < 0.95 ? Math.Max(1, (int)Math.Round(tileBuffer.Width * deviceX)) : tileBuffer.Width, + deviceY < 0.95 ? Math.Max(1, (int)Math.Round(tileBuffer.Height * deviceY)) : tileBuffer.Height, + ResamplingMode.Area); + } + } + } + + var source = minified ?? tileBuffer; + try + { + FillTileRegion(result, source, coverage, magnified, pixelX, pixelY, tileX, tileY, tileWidth, tileHeight, inverseGridTransform); + } + finally + { + minified?.Dispose(); + } + + return result; + } + + /// The per-pixel loop of , sampling into . + private static void FillTileRegion( + Surface result, + Surface tileBuffer, + Surface coverage, + bool magnified, + int pixelX, + int pixelY, + float tileX, + float tileY, + float tileWidth, + float tileHeight, + Matrix3x2 inverseGridTransform) + { + var pixelWidth = result.Width; + var pixelHeight = result.Height; var tilePixelWidth = tileBuffer.Width; var tilePixelHeight = tileBuffer.Height; @@ -574,16 +629,22 @@ private static Surface SampleTileIntoRegion( // are related by a single uniform translate-then-scale (see // TryComputeContentRenderTransform's remarks) - so no further transform is needed // beyond this direct fraction rescale - var bufferX = Math.Clamp((int)(wrappedX / tileWidth * tilePixelWidth), 0, tilePixelWidth - 1); - var bufferY = Math.Clamp((int)(wrappedY / tileHeight * tilePixelHeight), 0, tilePixelHeight - 1); + Rgba32 sample; + if (magnified) + { + sample = SurfaceResampler.SampleBilinearWrapped(tileBuffer, (double)wrappedX / tileWidth * tilePixelWidth, (double)wrappedY / tileHeight * tilePixelHeight); + } + else + { + var bufferX = Math.Clamp((int)(wrappedX / tileWidth * tilePixelWidth), 0, tilePixelWidth - 1); + var bufferY = Math.Clamp((int)(wrappedY / tileHeight * tilePixelHeight), 0, tilePixelHeight - 1); + sample = tileBuffer.GetRowSpan(bufferY)[bufferX]; + } - var sample = tileBuffer.GetRowSpan(bufferY)[bufferX]; var combinedAlpha = (byte)Math.Clamp(MathF.Round(sample.A * (coverageAlpha / 255f)), 0, 255); resultRow[col] = new Rgba32(sample.R, sample.G, sample.B, combinedAlpha); } } - - return result; } /// diff --git a/src/DemaConsulting.CanvasNet/Canvas/ResamplingMode.cs b/src/DemaConsulting.CanvasNet/Canvas/ResamplingMode.cs new file mode 100644 index 000000000..1415626ff --- /dev/null +++ b/src/DemaConsulting.CanvasNet/Canvas/ResamplingMode.cs @@ -0,0 +1,50 @@ +namespace DemaConsulting.CanvasNet.Canvas; + +/// +/// Selects the reconstruction filter used by and +/// . +/// +/// +/// Every mode other than works in premultiplied alpha, clamps its +/// result to the valid byte range, and clamps at the image edges. The smooth modes +/// (, , ) widen their +/// kernel by the reduction ratio when an axis is shrunk, so they act as a true prefilter +/// and do not drop thin features the way point sampling does. +/// +public enum ResamplingMode +{ + /// + /// Chooses a filter independently for each axis: when the axis is + /// reduced, when it is enlarged. An axis that keeps its size is + /// copied exactly. + /// + Auto = 0, + + /// + /// Point sampling: each output pixel copies the nearest source pixel. Fastest, keeps hard + /// edges (pixel art), but aliases and can drop thin features when shrinking. + /// + Nearest = 1, + + /// Triangle (linear) filter; smooth, with no overshoot. + Bilinear = 2, + + /// + /// Catmull-Rom cubic filter; sharper than and may overshoot + /// slightly near sharp edges (the overshoot is clamped). + /// + Bicubic = 3, + + /// + /// Lanczos windowed-sinc filter with three lobes; the sharpest smooth filter, with mild + /// ringing near hard edges (clamped to the valid range). + /// + Lanczos3 = 4, + + /// + /// Exact area averaging (box filter over the footprint of each output pixel). The best + /// choice for large reductions because it conserves total ink; when enlarging it behaves + /// like pixel replication with blended boundary pixels. + /// + Area = 5, +} diff --git a/src/DemaConsulting.CanvasNet/Canvas/Surface.cs b/src/DemaConsulting.CanvasNet/Canvas/Surface.cs index b8c9535d3..8386b1951 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/Surface.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/Surface.cs @@ -436,6 +436,124 @@ public Surface Crop(int x, int y, int width, int height) return result; } + /// + /// Returns a new surface containing this surface resampled to the given size. + /// + /// The width, in pixels, of the result. Must be between 1 and . + /// The height, in pixels, of the result. Must be between 1 and . + /// + /// The reconstruction filter. (the default) uses area + /// averaging on an axis that shrinks and Catmull-Rom bicubic on an axis that grows. + /// + /// + /// A new, independent of size by + /// . When the size equals this surface's size the result is an + /// exact copy for every mode. + /// + /// + /// Thrown when or is less than one or + /// greater than , or is not a defined + /// value. + /// + /// Thrown when this surface has been disposed. + /// + /// Resizing never changes this surface. Filtering is performed in premultiplied alpha, + /// results are clamped to the valid range, and the image edges are clamped (not wrapped). + /// When an axis is reduced the filter support is widened by the reduction ratio, so thin + /// features are attenuated rather than dropped. Working memory is bounded independently + /// of the image size. The aspect ratio is not preserved; use for that. + /// + /// + /// + /// var surface = new Surface(200, 100); + /// var thumbnail = surface.Resize(100, 50); + /// Console.WriteLine(thumbnail.Width); // Output: 100 + /// Console.WriteLine(thumbnail.Height); // Output: 50 + /// + /// + public Surface Resize(int width, int height, ResamplingMode mode = ResamplingMode.Auto) + { + ObjectDisposedException.ThrowIf(_disposed, this); + + // Validate each argument individually so callers get a precise parameter name + if (width < 1 || width > MaxDimension) + { + throw new ArgumentOutOfRangeException(nameof(width), width, $"Width must be between 1 and {MaxDimension}."); + } + + if (height < 1 || height > MaxDimension) + { + throw new ArgumentOutOfRangeException(nameof(height), height, $"Height must be between 1 and {MaxDimension}."); + } + + if (!Enum.IsDefined(mode)) + { + throw new ArgumentOutOfRangeException(nameof(mode), mode, "Mode is not a defined resampling mode."); + } + + // The same size is an exact independent copy for every filter + if (width == Width && height == Height) + { + return Crop(0, 0, Width, Height); + } + + return SurfaceResampler.ResizeFull(this, width, height, mode); + } + + /// + /// Returns a new surface containing this surface resampled, keeping its aspect ratio, to + /// the largest size that fits inside the given box (enlarging or shrinking). + /// + /// The width of the box. Must be between 1 and . + /// The height of the box. Must be between 1 and . + /// The reconstruction filter; see . + /// + /// A new, independent no larger than the box on either axis, at + /// least one pixel in each dimension, with the aspect ratio preserved to within pixel rounding. + /// + /// + /// Thrown when or is less than one + /// or greater than , or is not defined. + /// + /// Thrown when this surface has been disposed. + /// + /// One axis of the result always touches the box (up to rounding); a small image is + /// enlarged to fill the box. Very elongated images are clamped to one pixel on the short axis. + /// + /// + /// + /// var surface = new Surface(100, 50); + /// var fitted = surface.ResizeToFit(20, 20); + /// Console.WriteLine($"{fitted.Width}x{fitted.Height}"); // Output: 20x10 + /// + /// + public Surface ResizeToFit(int maxWidth, int maxHeight, ResamplingMode mode = ResamplingMode.Auto) + { + ObjectDisposedException.ThrowIf(_disposed, this); + + if (maxWidth < 1 || maxWidth > MaxDimension) + { + throw new ArgumentOutOfRangeException(nameof(maxWidth), maxWidth, $"Width must be between 1 and {MaxDimension}."); + } + + if (maxHeight < 1 || maxHeight > MaxDimension) + { + throw new ArgumentOutOfRangeException(nameof(maxHeight), maxHeight, $"Height must be between 1 and {MaxDimension}."); + } + + if (!Enum.IsDefined(mode)) + { + throw new ArgumentOutOfRangeException(nameof(mode), mode, "Mode is not a defined resampling mode."); + } + + // Pick the uniform scale that makes the tighter axis exactly fit, then round and clamp each + // dimension into [1, box] so rounding can never exceed the box or produce an empty image + var scale = Math.Min((double)maxWidth / Width, (double)maxHeight / Height); + var width = (int)Math.Clamp(Math.Round(Width * scale, MidpointRounding.AwayFromZero), 1, maxWidth); + var height = (int)Math.Clamp(Math.Round(Height * scale, MidpointRounding.AwayFromZero), 1, maxHeight); + return Resize(width, height, mode); + } + /// /// The value 255 as a , used throughout the vectorized bulk /// pixel operations to convert between byte-scale ([0, 255]) and normalized diff --git a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs new file mode 100644 index 000000000..07414a1ec --- /dev/null +++ b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs @@ -0,0 +1,465 @@ +using System.Numerics; +using System.Numerics.Tensors; + +namespace DemaConsulting.CanvasNet.Canvas; + +/// +/// The general-purpose resampling engine of the unit: separable +/// two-pass filtering with precomputed per-axis weight tables, used by +/// and by every document renderer that draws a raster image. +/// +/// +/// +/// Each axis is described by a fractional source interval: output pixel o has its +/// center at source position start + ((o + 0.5) * extent / outDim) (source pixel +/// i covers [i, i + 1) so its center is i + 0.5). A negative extent +/// mirrors the axis. This one description serves a plain resize (the full source range) and +/// the device-space draw of an image at a fractional offset and scale. +/// +/// +/// Weight tables are built once per axis. For the smooth kernels the support is multiplied +/// by the reduction ratio when the axis is shrunk, which makes the kernel a true low-pass +/// prefilter (a one-pixel line is attenuated, never skipped). Taps that fall outside the +/// image are folded into the edge pixel (edge clamp) and each row of weights is normalized +/// to sum to one. All filtering is performed in premultiplied alpha so transparent pixels +/// never bleed their (meaningless) color into their neighbors. +/// +/// +/// Memory is bounded: the horizontal pass writes a float intermediate for a strip of output +/// columns across the source rows that the vertical pass needs, and the strip width is chosen +/// so the intermediate fits a byte budget, so the working set is the destination surface plus +/// one strip regardless of image size. +/// +/// +internal static partial class SurfaceResampler +{ + /// The default budget, in bytes, for the float intermediate of the horizontal pass (8 MiB). + internal const int DefaultIntermediateBudgetBytes = 8 * 1024 * 1024; + + /// Floats stored per intermediate pixel (premultiplied R, G, B and alpha). + private const int Channels = 4; + + /// Per-axis weight table: for each output index a first source index, a tap count and the weights. + /// First source index of each output pixel's taps. + /// Number of consecutive taps of each output pixel. + /// Offset of each output pixel's weights in . + /// All normalized weights, concatenated. + /// Smallest source index referenced by any output pixel. + /// Largest source index referenced by any output pixel. + private sealed record AxisWeights(int[] First, int[] Count, int[] Offset, float[] Weights, int MinIndex, int MaxIndex); + + /// + /// Resamples a fractional source window of to a new + /// by surface. + /// + /// The source surface (not modified). + /// Source x of the left edge of the first output column. + /// Signed source width covered by all output columns. + /// Source y of the top edge of the first output row. + /// Signed source height covered by all output rows. + /// Output width in pixels (at least one). + /// Output height in pixels (at least one). + /// The filter; is resolved per axis. + /// Budget for the float intermediate; at least one column is always processed. + /// A new surface owned by the caller. + internal static Surface Resample( + Surface source, + double startX, + double extentX, + double startY, + double extentY, + int outWidth, + int outHeight, + ResamplingMode mode, + int intermediateBudgetBytes = DefaultIntermediateBudgetBytes) + { + var xs = BuildAxis(source.Width, startX, extentX, outWidth, mode); + var ys = BuildAxis(source.Height, startY, extentY, outHeight, mode); + var result = new Surface(outWidth, outHeight); + + // Choose the strip width so the intermediate (needed rows x strip columns x 16 bytes) fits the budget + var rows = ys.MaxIndex - ys.MinIndex + 1; + var bytesPerColumn = (long)rows * Channels * sizeof(float); + var strip = (int)Math.Clamp(intermediateBudgetBytes / bytesPerColumn, 1L, outWidth); + var rowStride = checked(strip * Channels); + var intermediate = new float[checked(rows * rowStride)]; + var accumulator = new float[rowStride]; + + for (var column0 = 0; column0 < outWidth; column0 += strip) + { + var columns = Math.Min(strip, outWidth - column0); + + // Horizontal pass: filter every needed source row into the intermediate strip + for (var r = 0; r < rows; r++) + { + HorizontalRow(source.GetRowSpan(ys.MinIndex + r), xs, column0, columns, intermediate.AsSpan(r * rowStride, columns * Channels)); + } + + // Vertical pass: each output row is a weighted sum of intermediate rows + var acc = accumulator.AsSpan(0, columns * Channels); + for (var oy = 0; oy < outHeight; oy++) + { + var first = ys.First[oy]; + var count = ys.Count[oy]; + var offset = ys.Offset[oy]; + for (var t = 0; t < count; t++) + { + var row = intermediate.AsSpan((first + t - ys.MinIndex) * rowStride, columns * Channels); + if (t == 0) + { + TensorPrimitives.Multiply(row, ys.Weights[offset], acc); + } + else + { + TensorPrimitives.MultiplyAdd(row, ys.Weights[offset + t], acc, acc); + } + } + + StoreRow(acc, result.GetRowSpan(oy).Slice(column0, columns)); + } + } + + return result; + } + + /// + /// Filters one source row horizontally into premultiplied float pixels for output columns + /// .. + - 1. + /// + private static void HorizontalRow(ReadOnlySpan row, AxisWeights xs, int column0, int columns, Span destination) + { + for (var j = 0; j < columns; j++) + { + var ox = column0 + j; + var first = xs.First[ox]; + var count = xs.Count[ox]; + var offset = xs.Offset[ox]; + float sumR = 0, sumG = 0, sumB = 0, sumA = 0; + for (var t = 0; t < count; t++) + { + var pixel = row[first + t]; + if (pixel.A == 0) + { + continue; + } + + // Premultiply on the fly: w * a is the pixel's alpha contribution, /255 scales colors by alpha + var weightedAlpha = xs.Weights[offset + t] * pixel.A; + var f = weightedAlpha / 255f; + sumA += weightedAlpha; + sumR += pixel.R * f; + sumG += pixel.G * f; + sumB += pixel.B * f; + } + + var d = j * Channels; + destination[d] = sumR; + destination[d + 1] = sumG; + destination[d + 2] = sumB; + destination[d + 3] = sumA; + } + } + + /// Clamps premultiplied float pixels, un-premultiplies them and stores them as bytes. + private static void StoreRow(ReadOnlySpan source, Span destination) + { + for (var j = 0; j < destination.Length; j++) + { + var d = j * Channels; + + // Clamp alpha first (kills negative kernel lobes), then color to [0, alpha] + var alpha = Math.Clamp(source[d + 3], 0f, 255f); + var alphaByte = (int)MathF.Round(alpha, MidpointRounding.AwayFromZero); + if (alphaByte == 0) + { + destination[j] = new Rgba32(0, 0, 0, 0); + continue; + } + + var scale = 255f / alpha; + destination[j] = new Rgba32( + ToByte(Math.Clamp(source[d], 0f, alpha) * scale), + ToByte(Math.Clamp(source[d + 1], 0f, alpha) * scale), + ToByte(Math.Clamp(source[d + 2], 0f, alpha) * scale), + (byte)alphaByte); + } + } + + /// + /// Builds the weight table for one axis. + /// + /// Source pixels along the axis. + /// Source coordinate of the first output pixel's leading edge. + /// Signed source length covered by all output pixels. + /// Output pixels along the axis. + /// Requested filter ( is resolved here). + private static AxisWeights BuildAxis(int sourceSize, double start, double extent, int outSize, ResamplingMode mode) + { + var step = extent / outSize; + var scale = Math.Abs(step); + var last = sourceSize - 1; + + // Resolve Auto per axis: area averaging when reducing, Catmull-Rom otherwise + if (mode == ResamplingMode.Auto) + { + mode = scale > 1.0 ? ResamplingMode.Area : ResamplingMode.Bicubic; + } + + // An axis that maps pixels 1:1 onto whole source pixels is an exact copy for every filter + if (Math.Abs(scale - 1.0) < 1e-9 && Math.Abs(start - Math.Round(start)) < 1e-9) + { + mode = ResamplingMode.Nearest; + } + + var radius = mode switch + { + ResamplingMode.Bilinear => 1.0, + ResamplingMode.Bicubic => 2.0, + ResamplingMode.Lanczos3 => 3.0, + _ => 0.0, + }; + + // Pass 1: the tap interval [lo, hi] (before edge folding) of every output pixel + var firsts = new int[outSize]; + var counts = new int[outSize]; + var offsets = new int[outSize]; + var los = new long[outSize]; + var his = new long[outSize]; + long total = 0; + var minIndex = int.MaxValue; + var maxIndex = int.MinValue; + for (var o = 0; o < outSize; o++) + { + var c = start + ((o + 0.5) * step); + long lo, hi; + switch (mode) + { + case ResamplingMode.Nearest: + lo = hi = (long)Math.Floor(c); + break; + case ResamplingMode.Area: + lo = (long)Math.Floor(c - (scale / 2)); + hi = (long)Math.Ceiling(c + (scale / 2)) - 1; + break; + default: + var support = radius * Math.Max(1.0, scale); + lo = (long)Math.Ceiling(c - support - 0.5); + hi = (long)Math.Floor(c + support - 0.5); + break; + } + + if (hi < lo) + { + lo = hi = (long)Math.Floor(c); + } + + los[o] = lo; + his[o] = hi; + var first = (int)Math.Clamp(lo, 0, last); + var end = (int)Math.Clamp(hi, 0, last); + firsts[o] = first; + counts[o] = end - first + 1; + offsets[o] = checked((int)total); + total = checked(total + counts[o]); + minIndex = Math.Min(minIndex, first); + maxIndex = Math.Max(maxIndex, end); + } + + // Pass 2: fill the weights, folding out-of-range taps into the edge pixel, then normalize + var weights = new float[checked((int)total)]; + var buffer = new double[counts.Max()]; + for (var o = 0; o < outSize; o++) + { + var c = start + ((o + 0.5) * step); + var count = counts[o]; + var first = firsts[o]; + var w = buffer.AsSpan(0, count); + w.Clear(); + for (var i = los[o]; i <= his[o]; i++) + { + var index = (int)Math.Clamp(i, 0, last); + w[index - first] += Weight(mode, i + 0.5 - c, scale); + } + + var sum = 0.0; + foreach (var v in w) + { + sum += v; + } + + if (!(sum > 1e-9)) + { + // Degenerate (no overlap or cancelling lobes): fall back to the nearest source pixel + w.Clear(); + var nearest = (int)Math.Clamp((long)Math.Floor(c), 0, last) - first; + w[Math.Clamp(nearest, 0, count - 1)] = 1.0; + sum = 1.0; + } + + for (var t = 0; t < count; t++) + { + weights[offsets[o] + t] = (float)(w[t] / sum); + } + } + + return new AxisWeights(firsts, counts, offsets, weights, minIndex, maxIndex); + } + + /// + /// Evaluates the filter weight of one source pixel. + /// + /// The resolved (non-Auto) filter. + /// Source-space distance from the output sample center to the source pixel center. + /// Absolute source pixels per output pixel (the kernel is widened when above one). + private static double Weight(ResamplingMode mode, double distance, double scale) + { + if (mode == ResamplingMode.Nearest) + { + return 1.0; + } + + if (mode == ResamplingMode.Area) + { + // Exact overlap of the output footprint [c - scale/2, c + scale/2] with the pixel [d - 0.5, d + 0.5] + var half = scale / 2; + var overlap = Math.Min(distance + 0.5, half) - Math.Max(distance - 0.5, -half); + return Math.Max(0.0, overlap); + } + + var x = Math.Abs(distance) / Math.Max(1.0, scale); + return mode switch + { + ResamplingMode.Bilinear => x < 1.0 ? 1.0 - x : 0.0, + ResamplingMode.Bicubic => CatmullRom(x), + _ => x < 3.0 ? Sinc(x) * Sinc(x / 3.0) : 0.0, + }; + } + + /// The Catmull-Rom cubic kernel (support two) at non-negative distance . + private static double CatmullRom(double x) + { + if (x < 1.0) + { + return (((1.5 * x) - 2.5) * x * x) + 1.0; + } + + return x < 2.0 ? (((((-0.5 * x) + 2.5) * x) - 4.0) * x) + 2.0 : 0.0; + } + + /// The normalized sinc function. + private static double Sinc(double x) => x < 1e-12 ? 1.0 : Math.Sin(Math.PI * x) / (Math.PI * x); + + /// + /// Resamples the whole of to a new size (the engine behind + /// ); sizes must already be validated. + /// + internal static Surface ResizeFull(Surface source, int width, int height, ResamplingMode mode) => + Resample(source, 0, source.Width, 0, source.Height, width, height, mode); + + /// + /// Resamples for an axis-aligned draw: when + /// contains no rotation or skew, produces a surface whose + /// pixels are exactly the device pixels (clipped to the visible area) covered by the image, + /// so the caller composites it 1:1. + /// + /// The source image (not modified). + /// Affine map from source pixel coordinates to device coordinates. + /// Width of the device area that is visible. + /// Height of the device area that is visible. + /// The filter to use. + /// + /// Receives a new surface the caller must dispose, or when the image + /// covers no visible device pixel center. + /// + /// Device x of the window's left column. + /// Device y of the window's top row. + /// + /// when the transform is rotated, skewed, flipped to a degenerate + /// size or non-finite (the caller must use an inverse-mapped fallback); otherwise + /// . + /// + internal static bool TryResampleToDevice( + Surface source, + Matrix3x2 pixelToDevice, + int visibleWidth, + int visibleHeight, + ResamplingMode mode, + out Surface? window, + out int originX, + out int originY) + { + window = null; + originX = 0; + originY = 0; + double m11 = pixelToDevice.M11, m12 = pixelToDevice.M12, m21 = pixelToDevice.M21, m22 = pixelToDevice.M22; + double m31 = pixelToDevice.M31, m32 = pixelToDevice.M32; + if (!double.IsFinite(m11) || !double.IsFinite(m12) || !double.IsFinite(m21) || !double.IsFinite(m22) + || !double.IsFinite(m31) || !double.IsFinite(m32) || m11 == 0 || m22 == 0) + { + return false; + } + + // Rotation/skew is tolerated only while it moves no pixel by more than a hundredth of a device pixel + if (Math.Abs(m12) * source.Height > 0.01 || Math.Abs(m21) * source.Width > 0.01) + { + return false; + } + + // Device pixels whose centers fall inside the image's device rectangle, clipped to the visible area + var (x0, x1) = DevicePixelRange(m31, m11 * source.Width, visibleWidth); + var (y0, y1) = DevicePixelRange(m32, m22 * source.Height, visibleHeight); + if (x1 <= x0 || y1 <= y0) + { + return true; + } + + window = Resample( + source, + (x0 - m31) / m11, + (x1 - x0) / m11, + (y0 - m32) / m22, + (y1 - y0) / m22, + x1 - x0, + y1 - y0, + mode); + originX = x0; + originY = y0; + return true; + } + + /// + /// Returns the half-open range of device pixels whose centers lie within + /// [origin, origin + length) (either sign of ), clipped to + /// [0, visible). + /// + private static (int Start, int End) DevicePixelRange(double origin, double length, int visible) + { + var low = Math.Min(origin, origin + length); + var high = Math.Max(origin, origin + length); + var start = Math.Max(0.0, Math.Ceiling(low - 0.5)); + var end = Math.Min((double)visible, Math.Ceiling(high - 0.5)); + return end <= start ? (0, 0) : ((int)start, (int)end); + } + + /// + /// Samples bilinearly at a continuous pixel position, wrapping + /// around both edges (for repeating tiles). + /// + /// The tile image. + /// Horizontal position in pixels (pixel i has its center at i + 0.5). + /// Vertical position in pixels. + internal static Rgba32 SampleBilinearWrapped(Surface image, double x, double y) + { + var fx = x - 0.5; + var fy = y - 0.5; + var x0f = Math.Floor(fx); + var y0f = Math.Floor(fy); + var tx = (float)(fx - x0f); + var ty = (float)(fy - y0f); + var x0 = (int)(((long)x0f % image.Width + image.Width) % image.Width); + var y0 = (int)(((long)y0f % image.Height + image.Height) % image.Height); + var x1 = (x0 + 1) % image.Width; + var y1 = (y0 + 1) % image.Height; + return Blend(image[x0, y0], image[x1, y0], image[x0, y1], image[x1, y1], tx, ty); + } +} diff --git a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs index b7aa68951..c88bfa36a 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs @@ -18,7 +18,7 @@ namespace DemaConsulting.CanvasNet.Canvas; /// shrunk (or the shrink is too mild for any block reduction), the source surface is returned /// unchanged so the upscale path is untouched. /// -internal static class SurfaceResampler +internal static partial class SurfaceResampler { /// /// Computes the integer box-filter factors for a pixel-space to device-space transform. @@ -79,61 +79,11 @@ internal static Surface BoxReduce(Surface source, int fx, int fy) ArgumentOutOfRangeException.ThrowIfLessThan(fx, 1); ArgumentOutOfRangeException.ThrowIfLessThan(fy, 1); + // Each output pixel covers an fx-by-fy block; blocks that overhang the image edge average + // only the pixels they cover (the Area filter drops out-of-image coverage and renormalizes) var outWidth = checked((source.Width + fx - 1) / fx); var outHeight = checked((source.Height + fy - 1) / fy); - var result = new Surface(outWidth, outHeight); - var sumR = new long[outWidth]; - var sumG = new long[outWidth]; - var sumB = new long[outWidth]; - var sumA = new long[outWidth]; - - for (var oy = 0; oy < outHeight; oy++) - { - Array.Clear(sumR); - Array.Clear(sumG); - Array.Clear(sumB); - Array.Clear(sumA); - - var y0 = oy * fy; - var y1 = Math.Min(source.Height, y0 + fy); - for (var y = y0; y < y1; y++) - { - var row = source.GetRowSpan(y); - for (var x = 0; x < row.Length; x++) - { - var ox = x / fx; - var pixel = row[x]; - long a = pixel.A; - checked - { - sumA[ox] += a; - sumR[ox] += pixel.R * a; - sumG[ox] += pixel.G * a; - sumB[ox] += pixel.B * a; - } - } - } - - var outRow = result.GetRowSpan(oy); - for (var ox = 0; ox < outWidth; ox++) - { - var count = (long)(y1 - y0) * (Math.Min(source.Width, (ox * fx) + fx) - (ox * fx)); - var alphaSum = sumA[ox]; - if (alphaSum == 0) - { - outRow[ox] = new Rgba32(0, 0, 0, 0); - continue; - } - - outRow[ox] = new Rgba32( - DivideRound(sumR[ox], alphaSum), - DivideRound(sumG[ox], alphaSum), - DivideRound(sumB[ox], alphaSum), - DivideRound(alphaSum, count)); - } - } - - return result; + return Resample(source, 0, (double)outWidth * fx, 0, (double)outHeight * fy, outWidth, outHeight, ResamplingMode.Area); } /// @@ -154,11 +104,15 @@ internal static Rgba32 SampleBilinear(Surface image, float u, float v) var y0 = Math.Clamp((int)y0f, 0, image.Height - 1); var y1 = Math.Clamp((int)y0f + 1, 0, image.Height - 1); - var p00 = image[x0, y0]; - var p10 = image[x1, y0]; - var p01 = image[x0, y1]; - var p11 = image[x1, y1]; + return Blend(image[x0, y0], image[x1, y0], image[x0, y1], image[x1, y1], tx, ty); + } + /// + /// Blends four pixels bilinearly in premultiplied alpha with fractional offsets + /// (, ) from . + /// + private static Rgba32 Blend(Rgba32 p00, Rgba32 p10, Rgba32 p01, Rgba32 p11, float tx, float ty) + { var w00 = (1 - tx) * (1 - ty); var w10 = tx * (1 - ty); var w01 = (1 - tx) * ty; @@ -201,10 +155,6 @@ private static int FactorFor(double scale, int size) return factor >= size ? Math.Max(1, size) : Math.Max(1, (int)factor); } - /// Divides rounding half away from zero (non-negative operands). - private static byte DivideRound(long numerator, long denominator) => - (byte)Math.Min(255L, ((numerator * 2) + denominator) / (denominator * 2)); - /// Rounds a float channel to a byte (half away from zero, clamped). private static byte ToByte(float value) => (byte)Math.Clamp((int)MathF.Round(value, MidpointRounding.AwayFromZero), 0, 255); diff --git a/src/DemaConsulting.CanvasNet/DemaConsulting.CanvasNet.csproj b/src/DemaConsulting.CanvasNet/DemaConsulting.CanvasNet.csproj index a6cce6052..56a9dc9cd 100644 --- a/src/DemaConsulting.CanvasNet/DemaConsulting.CanvasNet.csproj +++ b/src/DemaConsulting.CanvasNet/DemaConsulting.CanvasNet.csproj @@ -92,6 +92,10 @@ image-compositing loop - the same Porter-Duff "over" helper DemaConsulting.CanvasNet.Pdf's PdfDocument.Images.cs's CompositeImageOntoSurface also reuses. --> + + diff --git a/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs b/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs index 3557870e6..4f386c84a 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs @@ -336,10 +336,18 @@ internal static void Fill(Surface surface, IReadOnlyList> polygons // precomputation" remarks. var plan = TilePaintEvaluator.CreatePlan(paint); - while (sweep.MoveNext(out var y, out var rowCoverage)) + try { - TilePaintEvaluator.EvaluateRow(in plan, y, sweep.ClipMinX, sweep.Width, rowColors); - surface.CompositeOverSpan(y, sweep.ClipMinX, rowCoverage, rowColors, compositeWorkspace); + while (sweep.MoveNext(out var y, out var rowCoverage)) + { + TilePaintEvaluator.EvaluateRow(in plan, y, sweep.ClipMinX, sweep.Width, rowColors); + surface.CompositeOverSpan(y, sweep.ClipMinX, rowCoverage, rowColors, compositeWorkspace); + } + } + finally + { + // A minified tile copy is owned by the plan + plan.Release(); } } diff --git a/src/DemaConsulting.CanvasNet/Drawing/TilePaintEvaluator.cs b/src/DemaConsulting.CanvasNet/Drawing/TilePaintEvaluator.cs index 209ebf515..402a11f26 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/TilePaintEvaluator.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/TilePaintEvaluator.cs @@ -43,7 +43,11 @@ namespace DemaConsulting.CanvasNet.Drawing; /// surface's pixel dimensions to /, /// clamped into [0, Width - 1] x [0, Height - 1] (guarding a floating-point edge case /// landing exactly on the width/height boundary), and sampled via nearest-neighbor -/// (tile.Surface[tx, ty]) - bilinear interpolation is explicitly out of scope. +/// (tile.Surface[tx, ty]) when the tile is drawn at roughly one device pixel per tile +/// pixel (within 5 percent, which keeps device-scale pattern cells exact). A magnified tile +/// is instead sampled bilinearly (wrapping at the tile edges) and a minified tile is replaced, +/// once per fill, by an area-averaged smaller copy (Minified) that is then sampled +/// nearest-neighbor, so one-pixel features survive and enlarged tiles are not blocky. /// /// internal static class TilePaintEvaluator @@ -68,8 +72,34 @@ internal readonly record struct TilePaintPlan /// The inverse of , when . public Matrix3x2 InverseTransform { get; init; } + + /// + /// When the tile is drawn smaller than one device pixel per tile pixel, a smaller + /// area-averaged copy of the tile owned by this plan (the caller must dispose it via + /// once the fill is finished); otherwise . + /// + public Surface? Minified { get; init; } + + /// + /// when the tile is magnified and must be sampled bilinearly + /// (wrapping at the tile edges) instead of nearest-neighbor. + /// + public bool Magnified { get; init; } + + /// Releases the plan's owned surface, if any. + public void Release() => Minified?.Dispose(); } + /// + /// Device pixels per tile pixel above which the tile is considered magnified (smoothed). + /// + private const double MagnifiedThreshold = 1.05; + + /// + /// Device pixels per tile pixel below which the tile is considered minified (prefiltered). + /// + private const double MinifiedThreshold = 0.95; + /// /// Computes every per- (never per-point) quantity once, for reuse /// across an entire fill operation (every row of a tile @@ -83,11 +113,44 @@ internal static TilePaintPlan CreatePlan(TilePaint tile) var hasInverse = Matrix3x2.Invert(tile.Transform, out var inverse) && IsFinite(inverse); + if (!hasInverse) + { + return new TilePaintPlan { Tile = tile, HasInverseTransform = false, InverseTransform = inverse }; + } + + // Classify the device scale of one tile pixel. A tile drawn near 1:1 (the usual case for + // device-scale pattern cells) keeps exact nearest sampling; a magnified tile is sampled + // bilinearly; a minified tile is replaced by an area-averaged smaller copy so thin + // features survive. + var surface = tile.Surface; + var tilePixelsPerUnitX = surface.Width / Math.Abs((double)tile.XStep); + var tilePixelsPerUnitY = surface.Height / Math.Abs((double)tile.YStep); + var m = tile.Transform; + var deviceX = Math.Sqrt(((double)m.M11 * m.M11) + ((double)m.M12 * m.M12)) / tilePixelsPerUnitX; + var deviceY = Math.Sqrt(((double)m.M21 * m.M21) + ((double)m.M22 * m.M22)) / tilePixelsPerUnitY; + Surface? minified = null; + var magnified = false; + if (double.IsFinite(deviceX) && double.IsFinite(deviceY) && deviceX > 0 && deviceY > 0) + { + if (deviceX > MagnifiedThreshold || deviceY > MagnifiedThreshold) + { + magnified = true; + } + else if (deviceX < MinifiedThreshold || deviceY < MinifiedThreshold) + { + var width = deviceX < MinifiedThreshold ? Math.Max(1, (int)Math.Round(surface.Width * deviceX)) : surface.Width; + var height = deviceY < MinifiedThreshold ? Math.Max(1, (int)Math.Round(surface.Height * deviceY)) : surface.Height; + minified = surface.Resize(width, height, ResamplingMode.Area); + } + } + return new TilePaintPlan { Tile = tile, - HasInverseTransform = hasInverse, + HasInverseTransform = true, InverseTransform = inverse, + Minified = minified, + Magnified = magnified, }; } @@ -123,7 +186,7 @@ internal static void EvaluateRow(in TilePaintPlan plan, int y, int x, int count, } var tile = plan.Tile; - var surface = tile.Surface; + var surface = plan.Minified ?? tile.Surface; var xStep = Math.Abs((double)tile.XStep); var yStep = Math.Abs((double)tile.YStep); var scaleX = surface.Width / xStep; @@ -137,6 +200,12 @@ internal static void EvaluateRow(in TilePaintPlan plan, int y, int x, int count, var wrappedX = FloorMod(patternPoint.X, xStep); var wrappedY = FloorMod(patternPoint.Y, yStep); + if (plan.Magnified) + { + destination[i] = SurfaceResampler.SampleBilinearWrapped(surface, wrappedX * scaleX, wrappedY * scaleY); + continue; + } + var tx = Math.Clamp((int)(wrappedX * scaleX), 0, surface.Width - 1); var ty = Math.Clamp((int)(wrappedY * scaleY), 0, surface.Height - 1); diff --git a/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageDownscaleTests.cs b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageDownscaleTests.cs index 861d4763c..c5d4ae74e 100644 --- a/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageDownscaleTests.cs +++ b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageDownscaleTests.cs @@ -6,7 +6,7 @@ namespace DemaConsulting.CanvasNet.Pdf.Tests; /// /// End-to-end tests proving area-averages (rather than point-samples) /// a raster image that is shrunk on the page, so one-pixel lines are never dropped, and that -/// enlarged images keep their exact nearest-neighbor blocks. Timing is deliberately not asserted. +/// enlarged images are smoothly interpolated (no blocks). Timing is deliberately not asserted. /// public class PdfDocumentImageDownscaleTests { @@ -18,7 +18,7 @@ public class PdfDocumentImageDownscaleTests private static readonly PdfRenderOptions White = new() { BackgroundColor = new(255, 255, 255, 255) }; /// Builds a one-page PDF drawing a raw 8-bit gray image through . - private static byte[] BuildPdf(int pageWidth, int pageHeight, string cm, int imageWidth, int imageHeight, byte[] gray) + internal static byte[] BuildPdf(int pageWidth, int pageHeight, string cm, int imageWidth, int imageHeight, byte[] gray) { var content = Encoding.ASCII.GetBytes($"{cm} /Im0 Do"); var bodies = new List @@ -54,7 +54,7 @@ private static byte[] BuildPdf(int pageWidth, int pageHeight, string cm, int ima } /// Wraps a dictionary and payload as a stream object body. - private static byte[] Stream(string dictionary, byte[] data) + internal static byte[] Stream(string dictionary, byte[] data) { var bytes = new List(); bytes.AddRange(Encoding.ASCII.GetBytes(dictionary + "\nstream\n")); @@ -152,18 +152,28 @@ public void Render_ShrunkRotatedImage_KeepsEveryLine() } } - /// An enlarged image is still painted as exact nearest-neighbor blocks (no blending). + /// An enlarged image is smoothly interpolated: centers keep the source values and the boundary blends them. [Fact] - public void Render_EnlargedImage_RemainsExactBlocks() + public void Render_EnlargedImage_IsSmoothlyInterpolated() { var pdf = BuildPdf(400, 10, "400 0 0 10 0 0 cm", 4, 1, [0, 80, 160, 240]); using var document = PdfDocument.Open(new MemoryStream(pdf)); using var surface = document.Render(0, 400, 10, White); - Assert.Equal(0, surface[99, 5].R); - Assert.Equal(80, surface[100, 5].R); - Assert.Equal(80, surface[199, 5].R); - Assert.Equal(160, surface[200, 5].R); - Assert.Equal(240, surface[399, 5].R); + // Source pixel centers (50, 150, 250, 350) keep (nearly) their exact values + Assert.InRange(surface[49, 5].R, 0, 4); + Assert.InRange(surface[149, 5].R, 76, 84); + Assert.InRange(surface[249, 5].R, 156, 164); + Assert.InRange(surface[350, 5].R, 236, 244); + + // The boundary between source pixels 0 and 1 blends them (point sampling would jump 0 -> 80) + Assert.InRange(surface[99, 5].R, 30, 50); + Assert.InRange(surface[100, 5].R, 30, 50); + + // The ramp never decreases between the first and last source centers (edge taps may overshoot) + for (var x = 51; x <= 350; x++) + { + Assert.True(surface[x, 5].R >= surface[x - 1, 5].R, $"ramp decreased at x={x}"); + } } } diff --git a/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentJpxTests.cs b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentJpxTests.cs index c2bd975dd..ac341d124 100644 --- a/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentJpxTests.cs +++ b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentJpxTests.cs @@ -86,6 +86,10 @@ private static Surface Render(params byte[][] extraObjects) return document.Render(0, 100, 100, Transparent); } + /// Asserts that a channel value is within of (images are smoothly resampled). + private static void AssertChannelNear(int expected, int actual, int tolerance = 4) => + Assert.True(Math.Abs(expected - actual) <= tolerance, $"expected {expected} actual {actual}"); + private static void AssertNear(Rgba32 expected, Rgba32 actual, int tolerance = 2) { Assert.True(Math.Abs(expected.R - actual.R) <= tolerance, $"R expected {expected.R} actual {actual.R}"); @@ -269,8 +273,8 @@ public void PdfDocument_Images_Jpx_JpxSMask_AppliesLuminanceAsAlpha() "/Type /XObject /Subtype /Image /Width 2 /Height 1 /BitsPerComponent 8 /ColorSpace /DeviceGray /Filter /JPXDecode", maskJpx); using var surface = Render(ImageObject("/SMask 6 0 R", baseJpx), maskObject); - Assert.Equal(0, surface[25, 50].A); - AssertNear(new Rgba32(200, 50, 10, 255), surface[75, 50], 0); + AssertChannelNear(0, surface[25, 50].A, 16); // soft mask is smoothly resized, so the edge bleeds slightly + AssertNear(new Rgba32(200, 50, 10, 255), surface[75, 50], 16); } /// Proves a JPX /SMask honours its own /Decode inversion. @@ -543,8 +547,8 @@ public void PdfDocument_Images_SMaskOneBit_AppliesBinaryAlpha() "/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 1", [0b0100_0000]); using var surface = Render(image, mask); - Assert.Equal(0, surface[25, 50].A); - Assert.Equal(255, surface[75, 50].A); + AssertChannelNear(0, surface[25, 50].A, 16); // soft mask is smoothly resized, so the edge bleeds slightly + AssertChannelNear(255, surface[75, 50].A); } /// Proves a 16-bit /SMask is applied through its high byte. @@ -579,8 +583,8 @@ public void PdfDocument_Images_RawOneBitGray_UnpacksSamples() "/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 1", [0b0100_0000]); using var surface = Render(image); - AssertNear(new Rgba32(0, 0, 0, 255), surface[25, 50], 0); - AssertNear(new Rgba32(255, 255, 255, 255), surface[75, 50], 0); + AssertNear(new Rgba32(0, 0, 0, 255), surface[25, 50], 3); + AssertNear(new Rgba32(255, 255, 255, 255), surface[75, 50], 3); } /// Proves rows of a sub-byte image are padded to whole bytes independently (width 9, height 2). @@ -594,12 +598,12 @@ public void PdfDocument_Images_RawOneBitMultiRowPadding_UnpacksEachRowFromItsOwn using var surface = Render(image); var black = new Rgba32(0, 0, 0, 255); var white = new Rgba32(255, 255, 255, 255); - AssertNear(white, surface[5, 25], 0); - AssertNear(black, surface[16, 25], 0); - AssertNear(black, surface[94, 25], 0); - AssertNear(black, surface[5, 75], 0); - AssertNear(black, surface[83, 75], 0); - AssertNear(white, surface[94, 75], 0); + AssertNear(white, surface[5, 25], 3); + AssertNear(black, surface[16, 25], 3); + AssertNear(black, surface[94, 25], 3); + AssertNear(black, surface[5, 75], 3); + AssertNear(black, surface[83, 75], 3); + AssertNear(white, surface[94, 75], 3); } /// Proves a 4-bit DeviceRGB base image keeps its three components per pixel. @@ -610,8 +614,8 @@ public void PdfDocument_Images_RawFourBitRgb_UnpacksComponents() "/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceRGB /BitsPerComponent 4", [0xF0, 0x00, 0xFF]); using var surface = Render(image); - AssertNear(new Rgba32(255, 0, 0, 255), surface[25, 50], 0); - AssertNear(new Rgba32(0, 255, 255, 255), surface[75, 50], 0); + AssertNear(new Rgba32(255, 0, 0, 255), surface[25, 50], 3); + AssertNear(new Rgba32(0, 255, 255, 255), surface[75, 50], 3); } /// Proves a 2-bit DeviceRGB base image is padded per row (3 samples of 2 bits fit in one byte, 2 rows). @@ -623,8 +627,8 @@ public void PdfDocument_Images_RawTwoBitRgbTwoRows_PadsEachRow() "/Type /XObject /Subtype /Image /Width 1 /Height 2 /ColorSpace /DeviceRGB /BitsPerComponent 2", [0b1100_0011, 0b0011_1100]); using var surface = Render(image); - AssertNear(new Rgba32(255, 0, 0, 255), surface[50, 25], 0); - AssertNear(new Rgba32(0, 255, 255, 255), surface[50, 75], 0); + AssertNear(new Rgba32(255, 0, 0, 255), surface[50, 25], 3); + AssertNear(new Rgba32(0, 255, 255, 255), surface[50, 75], 3); } /// Proves 16-bit gray and RGB base images keep the high byte of each sample. @@ -657,9 +661,9 @@ public void PdfDocument_Images_RawFourBitIndexed_LooksUpPalette() + "/ColorSpace [/Indexed /DeviceRGB 2 ] /BitsPerComponent 4", [0x01, 0x20]); using var surface = Render(image); - AssertNear(new Rgba32(255, 0, 0, 255), surface[16, 50], 0); - AssertNear(new Rgba32(0, 255, 0, 255), surface[50, 50], 0); - AssertNear(new Rgba32(0, 0, 255, 255), surface[83, 50], 0); + AssertNear(new Rgba32(255, 0, 0, 255), surface[16, 50], 3); + AssertNear(new Rgba32(0, 255, 0, 255), surface[50, 50], 3); + AssertNear(new Rgba32(0, 0, 255, 255), surface[83, 50], 3); } /// Proves a truncated sub-byte image fails closed. diff --git a/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentTests.cs b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentTests.cs index 003964f72..6f49a0bc3 100644 --- a/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentTests.cs +++ b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentTests.cs @@ -21,6 +21,20 @@ namespace DemaConsulting.CanvasNet.Pdf.Tests; /// public class PdfDocumentTests { + /// + /// Asserts that every channel of is within + /// levels of . Images are now smoothly resampled (Catmull-Rom + /// when enlarged) rather than point sampled, so a sample taken just off the center of an + /// enlarged source pixel differs from that pixel's exact value by a couple of levels. + /// + private static void AssertNear(Canvas.Rgba32 expected, Canvas.Rgba32 actual, int tolerance = 4) + { + Assert.True(Math.Abs(expected.R - actual.R) <= tolerance, $"R expected {expected.R} actual {actual.R}"); + Assert.True(Math.Abs(expected.G - actual.G) <= tolerance, $"G expected {expected.G} actual {actual.G}"); + Assert.True(Math.Abs(expected.B - actual.B) <= tolerance, $"B expected {expected.B} actual {actual.B}"); + Assert.True(Math.Abs(expected.A - actual.A) <= tolerance, $"A expected {expected.A} actual {actual.A}"); + } + /// The directory containing the hand-authored PDF fixtures (see PdfFixtures\README.md). private static string FixturesPath => Path.Join(AppContext.BaseDirectory, "PdfFixtures"); @@ -5114,7 +5128,7 @@ public void PdfDocument_Clipping_ClipThenImageDo_RestrictsImageToClipRegion() // Assert: inside the clip (left half), the image's own top-right-quadrant-adjacent pixel // still paints its expected sample value. - Assert.Equal(new Canvas.Rgba32(0, 0, 0, 255), surface[25, 25]); + AssertNear(new Canvas.Rgba32(0, 0, 0, 255), surface[25, 25]); // Assert: outside the clip (right half), the image no longer paints - compare against // PdfDocument_Images_DoOperator_DeviceGrayFlateDecode_PlacesExpectedPixels, where this @@ -5854,10 +5868,10 @@ public void PdfDocument_Images_FlateDecodePngPredictor_DecodesExpectedPixels() using var surface = RenderPdfBytes(bytes); // Assert: row 0 (top of unit square) -> device top half; row 1 -> device bottom half. - Assert.Equal(new Canvas.Rgba32(255, 0, 0, 255), surface[25, 25]); - Assert.Equal(new Canvas.Rgba32(0, 255, 0, 255), surface[75, 25]); - Assert.Equal(new Canvas.Rgba32(0, 0, 255, 255), surface[25, 75]); - Assert.Equal(new Canvas.Rgba32(255, 255, 0, 255), surface[75, 75]); + AssertNear(new Canvas.Rgba32(255, 0, 0, 255), surface[25, 25]); + AssertNear(new Canvas.Rgba32(0, 255, 0, 255), surface[75, 25]); + AssertNear(new Canvas.Rgba32(0, 0, 255, 255), surface[25, 75]); + AssertNear(new Canvas.Rgba32(255, 255, 0, 255), surface[75, 75]); } /// @@ -5898,10 +5912,10 @@ public void PdfDocument_Images_FlateDecodePngFixedPredictor_DecodesExpectedPixel using var surface = RenderPdfBytes(bytes); // Assert: row 0 (top of unit square) -> device top half; row 1 -> device bottom half. - Assert.Equal(new Canvas.Rgba32(10, 10, 10, 255), surface[25, 25]); - Assert.Equal(new Canvas.Rgba32(200, 200, 200, 255), surface[75, 25]); - Assert.Equal(new Canvas.Rgba32(50, 50, 50, 255), surface[25, 75]); - Assert.Equal(new Canvas.Rgba32(90, 90, 90, 255), surface[75, 75]); + AssertNear(new Canvas.Rgba32(10, 10, 10, 255), surface[25, 25]); + AssertNear(new Canvas.Rgba32(200, 200, 200, 255), surface[75, 25]); + AssertNear(new Canvas.Rgba32(50, 50, 50, 255), surface[25, 75]); + AssertNear(new Canvas.Rgba32(90, 90, 90, 255), surface[75, 75]); } /// @@ -5962,10 +5976,10 @@ public void PdfDocument_Images_FlateDecodeTiffPredictor_DecodesExpectedPixels() using var surface = RenderPdfBytes(bytes); // Assert: both source pixels in a row decode to (10) then (200); both rows identical. - Assert.Equal(new Canvas.Rgba32(10, 10, 10, 255), surface[25, 25]); - Assert.Equal(new Canvas.Rgba32(200, 200, 200, 255), surface[75, 25]); - Assert.Equal(new Canvas.Rgba32(10, 10, 10, 255), surface[25, 75]); - Assert.Equal(new Canvas.Rgba32(200, 200, 200, 255), surface[75, 75]); + AssertNear(new Canvas.Rgba32(10, 10, 10, 255), surface[25, 25]); + AssertNear(new Canvas.Rgba32(200, 200, 200, 255), surface[75, 25]); + AssertNear(new Canvas.Rgba32(10, 10, 10, 255), surface[25, 75]); + AssertNear(new Canvas.Rgba32(200, 200, 200, 255), surface[75, 75]); } /// @@ -6143,10 +6157,10 @@ public void PdfDocument_Images_LzwDecodePngPredictor_DecodesExpectedPixels() using var surface = RenderPdfBytes(bytes); // Assert: row 0 (top of unit square) -> device top half; row 1 -> device bottom half. - Assert.Equal(new Canvas.Rgba32(255, 0, 0, 255), surface[25, 25]); - Assert.Equal(new Canvas.Rgba32(0, 255, 0, 255), surface[75, 25]); - Assert.Equal(new Canvas.Rgba32(0, 0, 255, 255), surface[25, 75]); - Assert.Equal(new Canvas.Rgba32(255, 255, 0, 255), surface[75, 75]); + AssertNear(new Canvas.Rgba32(255, 0, 0, 255), surface[25, 25]); + AssertNear(new Canvas.Rgba32(0, 255, 0, 255), surface[75, 25]); + AssertNear(new Canvas.Rgba32(0, 0, 255, 255), surface[25, 75]); + AssertNear(new Canvas.Rgba32(255, 255, 0, 255), surface[75, 75]); } /// Proves that a plain (unpredicted) LZWDecode image XObject decodes and places the expected pixels via Do. @@ -6172,8 +6186,8 @@ public void PdfDocument_Images_DoOperator_DeviceGrayLzwDecode_PlacesExpectedPixe using var surface = RenderPdfBytes(bytes); // Assert - Assert.Equal(new Canvas.Rgba32(10, 10, 10, 255), surface[25, 50]); - Assert.Equal(new Canvas.Rgba32(200, 200, 200, 255), surface[75, 50]); + AssertNear(new Canvas.Rgba32(10, 10, 10, 255), surface[25, 50]); + AssertNear(new Canvas.Rgba32(200, 200, 200, 255), surface[75, 50]); } /// @@ -6821,10 +6835,10 @@ public void PdfDocument_Images_DoOperator_DeviceGrayFlateDecode_PlacesExpectedPi using var surface = RenderPdfBytes(bytes); // Assert - Assert.Equal(new Canvas.Rgba32(0, 0, 0, 255), surface[25, 25]); - Assert.Equal(new Canvas.Rgba32(255, 255, 255, 255), surface[75, 25]); - Assert.Equal(new Canvas.Rgba32(64, 64, 64, 255), surface[25, 75]); - Assert.Equal(new Canvas.Rgba32(192, 192, 192, 255), surface[75, 75]); + AssertNear(new Canvas.Rgba32(0, 0, 0, 255), surface[25, 25]); + AssertNear(new Canvas.Rgba32(255, 255, 255, 255), surface[75, 25]); + AssertNear(new Canvas.Rgba32(64, 64, 64, 255), surface[25, 75]); + AssertNear(new Canvas.Rgba32(192, 192, 192, 255), surface[75, 75]); } /// @@ -6857,10 +6871,10 @@ public void PdfDocument_Images_DeviceGrayFlateDecode_CorruptAdlerChecksum_StillD using var surface = RenderPdfBytes(bytes); // Assert: decoded exactly as if the checksum had been correct. - Assert.Equal(new Canvas.Rgba32(0, 0, 0, 255), surface[25, 25]); - Assert.Equal(new Canvas.Rgba32(255, 255, 255, 255), surface[75, 25]); - Assert.Equal(new Canvas.Rgba32(64, 64, 64, 255), surface[25, 75]); - Assert.Equal(new Canvas.Rgba32(192, 192, 192, 255), surface[75, 75]); + AssertNear(new Canvas.Rgba32(0, 0, 0, 255), surface[25, 25]); + AssertNear(new Canvas.Rgba32(255, 255, 255, 255), surface[75, 25]); + AssertNear(new Canvas.Rgba32(64, 64, 64, 255), surface[25, 75]); + AssertNear(new Canvas.Rgba32(192, 192, 192, 255), surface[75, 75]); } /// Proves that Do decodes and places a raw 8-bit DeviceRGB FlateDecode image XObject at the expected device pixels. @@ -6886,10 +6900,10 @@ public void PdfDocument_Images_DoOperator_DeviceRgbFlateDecode_PlacesExpectedPix using var surface = RenderPdfBytes(bytes); // Assert - Assert.Equal(new Canvas.Rgba32(255, 0, 0, 255), surface[25, 25]); - Assert.Equal(new Canvas.Rgba32(0, 255, 0, 255), surface[75, 25]); - Assert.Equal(new Canvas.Rgba32(0, 0, 255, 255), surface[25, 75]); - Assert.Equal(new Canvas.Rgba32(255, 255, 255, 255), surface[75, 75]); + AssertNear(new Canvas.Rgba32(255, 0, 0, 255), surface[25, 25]); + AssertNear(new Canvas.Rgba32(0, 255, 0, 255), surface[75, 25]); + AssertNear(new Canvas.Rgba32(0, 0, 255, 255), surface[25, 75]); + AssertNear(new Canvas.Rgba32(255, 255, 255, 255), surface[75, 75]); } /// Proves that Do decodes and places a raw 8-bit DeviceCMYK FlateDecode image XObject at the expected device pixels. @@ -6943,10 +6957,10 @@ public void PdfDocument_Images_DoOperator_IndexedColorSpace_PlacesExpectedPalett using var surface = RenderPdfBytes(bytes); // Assert - Assert.Equal(new Canvas.Rgba32(255, 0, 0, 255), surface[25, 25]); - Assert.Equal(new Canvas.Rgba32(0, 255, 0, 255), surface[75, 25]); - Assert.Equal(new Canvas.Rgba32(0, 0, 255, 255), surface[25, 75]); - Assert.Equal(new Canvas.Rgba32(0, 0, 255, 255), surface[75, 75]); + AssertNear(new Canvas.Rgba32(255, 0, 0, 255), surface[25, 25]); + AssertNear(new Canvas.Rgba32(0, 255, 0, 255), surface[75, 25]); + AssertNear(new Canvas.Rgba32(0, 0, 255, 255), surface[25, 75]); + AssertNear(new Canvas.Rgba32(0, 0, 255, 255), surface[75, 75]); } /// Proves that Do decodes a bare DCTDecode (JPEG) image XObject via and places the expected (solid-color, lossless-for-flat-blocks) pixels. @@ -7165,8 +7179,8 @@ public void PdfDocument_Images_DoOperator_IndexedWithDecode_RemapsIndices() using var surface = RenderPdfBytes(bytes); // Assert - Assert.Equal(new Canvas.Rgba32(0, 0, 255, 255), surface[25, 50]); - Assert.Equal(new Canvas.Rgba32(255, 0, 0, 255), surface[75, 50]); + AssertNear(new Canvas.Rgba32(0, 0, 255, 255), surface[25, 50]); + AssertNear(new Canvas.Rgba32(255, 0, 0, 255), surface[75, 50]); } /// Proves that the default (absent) /BlackIs1 maps a physically black pixel to packed bit 0 (and a decoded gray value of 0). diff --git a/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfImageResamplingTests.cs b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfImageResamplingTests.cs new file mode 100644 index 000000000..00e6d781f --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfImageResamplingTests.cs @@ -0,0 +1,90 @@ +using DemaConsulting.CanvasNet.Canvas; + +namespace DemaConsulting.CanvasNet.Pdf.Tests; + +/// +/// Grid-line regression tests for PDF raster images drawn at many reduction ratios (the "nine sizes" +/// scenario): no one-pixel line may disappear and the darkness must stay consistent. Timing is never asserted. +/// +public class PdfImageResamplingTests +{ + private const int SourceWidth = 1940; + private const int SourceHeight = 40; + private const int FirstLine = 15; + private const int LineSpacing = 24; + private const int PageWidth = 612; + + private static readonly PdfRenderOptions White = new() { BackgroundColor = new(255, 255, 255, 255) }; + + /// Renders the synthetic grid image at and returns the minimum and maximum per-line ink. + private static (int Missing, double MinInk, double MaxInk) Measure(int pixelWidth) + { + var gray = new byte[SourceWidth * SourceHeight]; + Array.Fill(gray, (byte)255); + for (var c = FirstLine; c < SourceWidth; c += LineSpacing) + { + for (var y = 0; y < SourceHeight; y++) + { + gray[(y * SourceWidth) + c] = 0; + } + } + + var pageHeight = 792; + var pdf = PdfDocumentImageDownscaleTests.BuildPdf(PageWidth, pageHeight, "468 0 0 40 72 700 cm", SourceWidth, SourceHeight, gray); + using var document = PdfDocument.Open(new MemoryStream(pdf)); + var pixelHeight = pixelWidth * pageHeight / PageWidth; + using var surface = document.Render(0, pixelWidth, pixelHeight, White); + + var scale = (double)pixelWidth / PageWidth; + var imageLeft = 72 * scale; + var pixelsPerSourceColumn = 468.0 * scale / SourceWidth; + var y0 = (int)((792 - 720) * scale); + var missing = 0; + double min = double.MaxValue; + double max = 0; + for (var c = FirstLine; c < SourceWidth; c += LineSpacing) + { + var center = imageLeft + ((c + 0.5) * pixelsPerSourceColumn); + var darkest = 0; + double ink = 0; + for (var x = (int)Math.Floor(center - 2); x <= (int)Math.Ceiling(center + 2); x++) + { + var v = 255 - surface[x, y0].R; + darkest = Math.Max(darkest, v); + ink += v; + } + + if (darkest < 16) + { + missing++; + } + + min = Math.Min(min, ink); + max = Math.Max(max, ink); + } + + return (missing, min, max); + } + + /// No grid line goes missing at any of nine output sizes and the ink per line tracks the scale. + [Theory] + [InlineData(765)] + [InlineData(900)] + [InlineData(1020)] + [InlineData(1275)] + [InlineData(1530)] + [InlineData(1836)] + [InlineData(2448)] + [InlineData(3060)] + [InlineData(3672)] + public void Render_GridImage_NoLineMissingAtAnySize(int pixelWidth) + { + var (missing, min, max) = Measure(pixelWidth); + Assert.Equal(0, missing); + + // Each source line covers (468 * scale / 1940) device pixels of full black + var expected = 255.0 * 468.0 * pixelWidth / PageWidth / SourceWidth; + Assert.True(min >= 0.6 * expected, $"min ink {min:F1} below 0.6 * {expected:F1}"); + Assert.True(max <= 1.6 * expected + 8, $"max ink {max:F1} above 1.6 * {expected:F1}"); + } +} diff --git a/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfSystemIntegrationTests.cs b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfSystemIntegrationTests.cs index 0ed9271a1..d75fa71f7 100644 --- a/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfSystemIntegrationTests.cs +++ b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfSystemIntegrationTests.cs @@ -15,6 +15,19 @@ namespace DemaConsulting.CanvasNet.Pdf.Tests; /// public class PdfSystemIntegrationTests { + /// + /// Asserts every channel of is within + /// levels of ; enlarged images are smoothly resampled, so a + /// sample just off a source pixel's center differs from its exact value by a few levels. + /// + private static void AssertNear(Canvas.Rgba32 expected, Canvas.Rgba32 actual, int tolerance = 4) + { + Assert.True(Math.Abs(expected.R - actual.R) <= tolerance, $"R expected {expected.R} actual {actual.R}"); + Assert.True(Math.Abs(expected.G - actual.G) <= tolerance, $"G expected {expected.G} actual {actual.G}"); + Assert.True(Math.Abs(expected.B - actual.B) <= tolerance, $"B expected {expected.B} actual {actual.B}"); + Assert.True(Math.Abs(expected.A - actual.A) <= tolerance, $"A expected {expected.A} actual {actual.A}"); + } + private static string FixturesPath => Path.Join(AppContext.BaseDirectory, "PdfFixtures"); private static string Fixture(string name) => Path.Join(FixturesPath, name); @@ -301,10 +314,10 @@ public void CanvasNetPdf_SystemIntegration_PdfRender_ImageXObjectPlacement_Compo using var surface = document.Render(0, 100, 100, Transparent); // Assert: the four source quadrants land in their mathematically correct device pixels. - Assert.Equal(new Canvas.Rgba32(255, 0, 0, 255), surface[25, 40]); - Assert.Equal(new Canvas.Rgba32(0, 255, 0, 255), surface[55, 40]); - Assert.Equal(new Canvas.Rgba32(0, 0, 255, 255), surface[25, 75]); - Assert.Equal(new Canvas.Rgba32(255, 255, 0, 255), surface[55, 75]); + AssertNear(new Canvas.Rgba32(255, 0, 0, 255), surface[25, 40]); + AssertNear(new Canvas.Rgba32(0, 255, 0, 255), surface[55, 40]); + AssertNear(new Canvas.Rgba32(0, 0, 255, 255), surface[25, 75]); + AssertNear(new Canvas.Rgba32(255, 255, 0, 255), surface[55, 75]); // Assert: a pixel outside the placed image's device-space footprint remains transparent. Assert.Equal(default, surface[5, 5]); diff --git a/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs b/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs new file mode 100644 index 000000000..3c7c38775 --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs @@ -0,0 +1,95 @@ +using System.Text; +using DemaConsulting.CanvasNet.Canvas; +using DemaConsulting.CanvasNet.Codecs; + +namespace DemaConsulting.CanvasNet.Svg.Tests; + +/// +/// Tests that SVG <image> elements are smoothly resampled and that the +/// image-rendering property selects nearest-neighbor sampling. Timing is never asserted. +/// +public class SvgImageResamplingTests +{ + /// Builds a 2x1 black/white PNG data URI. + private static string TwoPixelPng() + { + using var source = new Surface(2, 1); + source[0, 0] = new Rgba32(0, 0, 0, 255); + source[1, 0] = new Rgba32(255, 255, 255, 255); + using var stream = new MemoryStream(); + PngCodec.Save(source, stream); + return "data:image/png;base64," + Convert.ToBase64String(stream.ToArray()); + } + + /// Renders a 2x1 image enlarged to 40x4 using the given extra markup. + private static Surface Render(string imageAttributes, string styleBlock = "") + { + var svg = $"{styleBlock}" + + $""; + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(svg)); + return SvgCodec.Load(stream, 40, 4); + } + + /// Counts distinct gray levels in the middle row. + private static int DistinctLevels(Surface surface) => + Enumerable.Range(0, surface.Width).Select(x => (int)surface[x, 2].R).Distinct().Count(); + + /// By default an enlarged image is smoothly interpolated. + [Fact] + public void Image_Enlarged_IsSmooth() + { + using var surface = Render(string.Empty); + Assert.True(DistinctLevels(surface) > 8); + } + + /// image-rendering as an attribute selects nearest-neighbor. + [Theory] + [InlineData("pixelated")] + [InlineData("crisp-edges")] + public void Image_RenderingAttribute_IsNearest(string value) + { + using var surface = Render($"image-rendering='{value}'"); + Assert.True(DistinctLevels(surface) <= 2); + Assert.Equal(0, surface[5, 2].R); + Assert.Equal(255, surface[35, 2].R); + } + + /// image-rendering in a style attribute selects nearest-neighbor. + [Fact] + public void Image_RenderingStyle_IsNearest() + { + using var surface = Render("style='image-rendering:pixelated'"); + Assert.True(DistinctLevels(surface) <= 2); + } + + /// image-rendering from a stylesheet selects nearest-neighbor. + [Fact] + public void Image_RenderingStylesheet_IsNearest() + { + using var surface = Render("class='px'", ""); + Assert.True(DistinctLevels(surface) <= 2); + } + + /// A shrunken image keeps a one-pixel line instead of dropping it. + [Fact] + public void Image_Shrunk_KeepsOnePixelLine() + { + using var source = new Surface(100, 1); + source.Clear(new Rgba32(255, 255, 255, 255)); + source[37, 0] = new Rgba32(0, 0, 0, 255); + using var stream = new MemoryStream(); + PngCodec.Save(source, stream); + var uri = "data:image/png;base64," + Convert.ToBase64String(stream.ToArray()); + var svg = $""; + using var svgStream = new MemoryStream(Encoding.UTF8.GetBytes(svg)); + using var surface = SvgCodec.Load(svgStream, 17, 1); + + double ink = 0; + for (var x = 0; x < 17; x++) + { + ink += 255 - surface[x, 0].R; + } + + Assert.InRange(ink, 255 * 0.17 * 0.8, 255 * 0.17 * 1.2 + 1); + } +} diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs index 079a1db09..cb1be5cfc 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs @@ -173,4 +173,73 @@ public void SampleBilinear_CentreAndMidpoint_InterpolatesAndClampsEdges() Assert.Equal(new Rgba32(0, 0, 0, 255), SurfaceResampler.SampleBilinear(image, 0f, 0f)); Assert.Equal(new Rgba32(200, 100, 50, 255), SurfaceResampler.SampleBilinear(image, 0.999f, 0.999f)); } + /// Rotation or skew is rejected so callers use the inverse-mapped fallback. + [Fact] + public void TryResampleToDevice_RotatedMatrix_ReturnsFalse() + { + using var source = new Surface(4, 4); + Assert.False(SurfaceResampler.TryResampleToDevice(source, Matrix3x2.CreateRotation(0.5f), 20, 20, ResamplingMode.Auto, out var window, out _, out _)); + Assert.Null(window); + } + + /// An axis-aligned enlargement yields a window covering exactly the image rectangle. + [Fact] + public void TryResampleToDevice_AxisAligned_ReturnsWindowAtOrigin() + { + using var source = new Surface(2, 2); + source.Clear(new Rgba32(10, 20, 30, 255)); + var matrix = Matrix3x2.CreateScale(5f) * Matrix3x2.CreateTranslation(3f, 4f); + Assert.True(SurfaceResampler.TryResampleToDevice(source, matrix, 40, 40, ResamplingMode.Auto, out var window, out var ox, out var oy)); + using (window) + { + Assert.NotNull(window); + Assert.Equal((3, 4), (ox, oy)); + Assert.Equal((10, 10), (window.Width, window.Height)); + } + } + + /// An image entirely outside the visible area succeeds with no window. + [Fact] + public void TryResampleToDevice_OffScreen_ReturnsTrueWithNullWindow() + { + using var source = new Surface(2, 2); + var matrix = Matrix3x2.CreateScale(5f) * Matrix3x2.CreateTranslation(100f, 100f); + Assert.True(SurfaceResampler.TryResampleToDevice(source, matrix, 40, 40, ResamplingMode.Auto, out var window, out _, out _)); + Assert.Null(window); + } + + /// BoxReduce matches an explicit Area resize. + [Fact] + public void BoxReduce_MatchesAreaResize() + { + using var source = new Surface(6, 4); + for (var y = 0; y < 4; y++) + { + for (var x = 0; x < 6; x++) + { + source[x, y] = new Rgba32((byte)(x * 40), (byte)(y * 60), 9, 255); + } + } + + using var reduced = SurfaceResampler.BoxReduce(source, 2, 2); + using var area = source.Resize(3, 2, ResamplingMode.Area); + for (var y = 0; y < 2; y++) + { + for (var x = 0; x < 3; x++) + { + Assert.Equal(area[x, y], reduced[x, y]); + } + } + } + + /// Wrapped bilinear sampling wraps across the tile edge. + [Fact] + public void SampleBilinearWrapped_AtEdge_BlendsWithOppositeSide() + { + using var source = new Surface(2, 1); + source[0, 0] = new Rgba32(0, 0, 0, 255); + source[1, 0] = new Rgba32(200, 200, 200, 255); + var p = SurfaceResampler.SampleBilinearWrapped(source, 0.0, 0.5); + Assert.InRange(p.R, 99, 101); + } } diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeCodecRoundTripTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeCodecRoundTripTests.cs new file mode 100644 index 000000000..af0ed91e1 --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeCodecRoundTripTests.cs @@ -0,0 +1,77 @@ +using DemaConsulting.CanvasNet.Canvas; +using DemaConsulting.CanvasNet.Codecs; + +namespace DemaConsulting.CanvasNet.Tests.Canvas; + +/// +/// Round-trip tests for the documented load, crop, resize, save workflow using the BMP and PNG codecs. +/// +public class SurfaceResizeCodecRoundTripTests +{ + /// Builds a 40x30 opaque gradient. + private static Surface Gradient() + { + var surface = new Surface(40, 30); + for (var y = 0; y < 30; y++) + { + for (var x = 0; x < 40; x++) + { + surface[x, y] = new Rgba32((byte)(x * 6), (byte)(y * 8), 100, 255); + } + } + + return surface; + } + + /// Asserts the cropped-then-resized result matches the expected size and gradient direction. + private static void AssertResized(Surface reloaded) + { + Assert.Equal(20, reloaded.Width); + Assert.Equal(10, reloaded.Height); + Assert.True(reloaded[19, 5].R > reloaded[0, 5].R); + Assert.True(reloaded[10, 9].G > reloaded[10, 0].G); + } + + /// BMP load, crop, resize, save and reload keeps the resized content. + [Fact] + public void Resize_BmpCodec_RoundTrip() + { + using var original = Gradient(); + using var stream = new MemoryStream(); + BmpCodec.Save(original, stream); + stream.Position = 0; + + using var loaded = BmpCodec.Load(stream); + using var cropped = loaded.Crop(5, 5, 30, 20); + using var resized = cropped.Resize(20, 10); + using var output = new MemoryStream(); + BmpCodec.Save(resized, output); + output.Position = 0; + + using var reloaded = BmpCodec.Load(output); + AssertResized(reloaded); + } + + /// PNG load, crop, resize, save and reload keeps the resized content. + [Fact] + public void Resize_PngCodec_RoundTrip() + { + using var original = Gradient(); + using var stream = new MemoryStream(); + PngCodec.Save(original, stream); + stream.Position = 0; + + using var loaded = PngCodec.Load(stream); + using var cropped = loaded.Crop(5, 5, 30, 20); + using var fitted = cropped.ResizeToFit(20, 20, ResamplingMode.Lanczos3); + Assert.Equal(20, fitted.Width); + using var resized = cropped.Resize(20, 10, ResamplingMode.Lanczos3); + using var output = new MemoryStream(); + PngCodec.Save(resized, output); + output.Position = 0; + + using var reloaded = PngCodec.Load(output); + AssertResized(reloaded); + Assert.Equal(resized[7, 3], reloaded[7, 3]); + } +} diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs new file mode 100644 index 000000000..f5e1ca32c --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs @@ -0,0 +1,332 @@ +using DemaConsulting.CanvasNet.Canvas; + +namespace DemaConsulting.CanvasNet.Tests.Canvas; + +/// +/// Unit tests for , and +/// . Timing is deliberately never asserted. +/// +public class SurfaceResizeTests +{ + private static readonly ResamplingMode[] ConcreteModes = + [ + ResamplingMode.Nearest, + ResamplingMode.Bilinear, + ResamplingMode.Bicubic, + ResamplingMode.Lanczos3, + ResamplingMode.Area, + ]; + + /// Builds an opaque gray row surface from the given levels. + private static Surface GrayRow(params byte[] levels) + { + var surface = new Surface(levels.Length, 1); + for (var x = 0; x < levels.Length; x++) + { + surface[x, 0] = new Rgba32(levels[x], levels[x], levels[x], 255); + } + + return surface; + } + + /// Returns the red channel of every pixel in row 0. + private static int[] Reds(Surface surface) => + [.. Enumerable.Range(0, surface.Width).Select(x => (int)surface[x, 0].R)]; + + /// Nearest enlarges by replicating pixels. + [Fact] + public void Resize_Nearest_Upscale_ReplicatesPixels() + { + using var source = GrayRow(0, 255); + using var result = source.Resize(4, 1, ResamplingMode.Nearest); + Assert.Equal([0, 0, 255, 255], Reds(result)); + } + + /// Bilinear enlarges by linear interpolation with clamped edges. + [Fact] + public void Resize_Bilinear_Upscale_InterpolatesLinearly() + { + using var source = GrayRow(0, 100); + using var result = source.Resize(4, 1, ResamplingMode.Bilinear); + var reds = Reds(result); + Assert.InRange(reds[0], 0, 1); + Assert.InRange(reds[1], 24, 26); + Assert.InRange(reds[2], 74, 76); + Assert.InRange(reds[3], 99, 100); + } + + /// Area averages each covered source pixel exactly on an integer reduction. + [Fact] + public void Resize_Area_IntegerReduction_AveragesBlocks() + { + using var source = GrayRow(0, 100, 200, 40); + using var result = source.Resize(2, 1, ResamplingMode.Area); + var reds = Reds(result); + Assert.InRange(reds[0], 49, 51); + Assert.InRange(reds[1], 119, 121); + } + + /// Bicubic and Lanczos3 keep source values at the pixel centers of an exact 2x enlargement's constant regions and never leave the byte range. + [Theory] + [InlineData(ResamplingMode.Bicubic)] + [InlineData(ResamplingMode.Lanczos3)] + public void Resize_SharpFilters_StepEdge_ClampsToByteRange(ResamplingMode mode) + { + using var source = GrayRow(0, 0, 0, 255, 255, 255); + using var result = source.Resize(24, 1, mode); + var reds = Reds(result); + Assert.Equal(0, reds[0]); + Assert.Equal(255, reds[^1]); + Assert.All(reds, v => Assert.InRange(v, 0, 255)); + } + + /// Every filter returns an exact, independent copy when the size does not change. + [Theory] + [InlineData(ResamplingMode.Auto)] + [InlineData(ResamplingMode.Nearest)] + [InlineData(ResamplingMode.Bilinear)] + [InlineData(ResamplingMode.Bicubic)] + [InlineData(ResamplingMode.Lanczos3)] + [InlineData(ResamplingMode.Area)] + public void Resize_SameSize_IsExactIndependentCopy(ResamplingMode mode) + { + using var source = GrayRow(1, 50, 99, 250, 7); + source[2, 0] = new Rgba32(10, 20, 30, 128); + using var result = source.Resize(5, 1, mode); + Assert.NotSame(source, result); + for (var x = 0; x < 5; x++) + { + Assert.Equal(source[x, 0], result[x, 0]); + } + + result[0, 0] = new Rgba32(9, 9, 9, 9); + Assert.Equal(new Rgba32(1, 1, 1, 255), source[0, 0]); + } + + /// A constant opaque image stays constant for every filter and ratio. + [Theory] + [InlineData(ResamplingMode.Auto, 7, 5)] + [InlineData(ResamplingMode.Nearest, 33, 3)] + [InlineData(ResamplingMode.Bilinear, 3, 40)] + [InlineData(ResamplingMode.Bicubic, 90, 90)] + [InlineData(ResamplingMode.Lanczos3, 13, 2)] + [InlineData(ResamplingMode.Area, 5, 61)] + public void Resize_ConstantImage_StaysConstant(ResamplingMode mode, int width, int height) + { + using var source = new Surface(20, 17); + source.Clear(new Rgba32(77, 130, 201, 255)); + using var result = source.Resize(width, height, mode); + Assert.Equal(width, result.Width); + Assert.Equal(height, result.Height); + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var p = result[x, y]; + Assert.InRange(p.R, 76, 78); + Assert.InRange(p.G, 129, 131); + Assert.InRange(p.B, 200, 202); + Assert.Equal(255, p.A); + } + } + } + + /// A one-pixel line is never lost at many reduction ratios, and Area conserves its ink. + [Theory] + [InlineData(ResamplingMode.Auto)] + [InlineData(ResamplingMode.Bilinear)] + [InlineData(ResamplingMode.Bicubic)] + [InlineData(ResamplingMode.Lanczos3)] + [InlineData(ResamplingMode.Area)] + public void Resize_Downscale_PreservesOnePixelLine(ResamplingMode mode) + { + const int sourceWidth = 1000; + foreach (var width in new[] { 999, 800, 765, 500, 333, 250, 100, 37, 10 }) + { + using var source = new Surface(sourceWidth, 2); + source.Clear(new Rgba32(255, 255, 255, 255)); + for (var y = 0; y < 2; y++) + { + source[417, y] = new Rgba32(0, 0, 0, 255); + } + + using var result = source.Resize(width, 2, mode); + double ink = 0; + for (var x = 0; x < width; x++) + { + ink += 255 - result[x, 0].R; + } + + Assert.True(ink > 0, $"line lost at width {width} with {mode}"); + if (mode == ResamplingMode.Area) + { + var expected = 255.0 * width / sourceWidth; + Assert.InRange(ink, expected * 0.9, expected * 1.1 + 1); + } + } + } + + /// An enlargement with a smooth filter has no blocky jumps between neighbors. + [Theory] + [InlineData(ResamplingMode.Auto)] + [InlineData(ResamplingMode.Bilinear)] + [InlineData(ResamplingMode.Bicubic)] + public void Resize_Upscale_IsSmooth(ResamplingMode mode) + { + using var source = GrayRow(0, 80, 160, 240); + using var result = source.Resize(400, 1, mode); + var reds = Reds(result); + for (var x = 1; x < reds.Length; x++) + { + Assert.InRange(Math.Abs(reds[x] - reds[x - 1]), 0, 3); + } + } + + /// Transparent pixels contribute no color, so there is no dark fringe at an alpha edge. + [Theory] + [InlineData(ResamplingMode.Bilinear)] + [InlineData(ResamplingMode.Bicubic)] + [InlineData(ResamplingMode.Area)] + public void Resize_AlphaEdge_HasNoColorFringe(ResamplingMode mode) + { + using var source = new Surface(4, 1); + source[0, 0] = new Rgba32(255, 0, 0, 255); + source[1, 0] = new Rgba32(255, 0, 0, 255); + source[2, 0] = new Rgba32(0, 0, 0, 0); + source[3, 0] = new Rgba32(0, 0, 0, 0); + using var result = source.Resize(9, 1, mode); + for (var x = 0; x < 9; x++) + { + var p = result[x, 0]; + if (p.A > 0) + { + Assert.InRange(p.R, 250, 255); + Assert.InRange(p.G, 0, 5); + Assert.InRange(p.B, 0, 5); + } + } + } + + /// Auto picks Area when shrinking one axis and Bicubic when enlarging the other. + [Fact] + public void Resize_Auto_ChoosesPerAxis() + { + using var source = new Surface(4, 2); + for (var y = 0; y < 2; y++) + { + for (var x = 0; x < 4; x++) + { + source[x, y] = new Rgba32((byte)(x * 60), (byte)(x * 60), (byte)(x * 60), 255); + } + } + + using var auto = source.Resize(2, 4); + using var explicitArea = source.Resize(2, 2, ResamplingMode.Area); + Assert.Equal(2, auto.Width); + Assert.Equal(4, auto.Height); + + // The shrunken axis averages pairs: (0+60)/2 and (120+180)/2 + Assert.InRange(auto[0, 1].R, 29, 31); + Assert.InRange(auto[1, 1].R, 149, 151); + using var autoSame = source.Resize(2, 2); + Assert.Equal(explicitArea[0, 0], autoSame[0, 0]); + } + + /// The extreme 8192x1 to 1x8192 resize works within bounded memory. + [Fact] + public void Resize_LargeAndWide_ProducesExpectedShape() + { + using var wide = new Surface(8192, 1); + wide.Clear(new Rgba32(10, 20, 30, 255)); + using var tall = wide.Resize(1, 8192); + Assert.Equal(1, tall.Width); + Assert.Equal(8192, tall.Height); + Assert.InRange(tall[0, 4000].R, 9, 11); + Assert.InRange(tall[0, 4000].B, 29, 31); + } + + /// Invalid sizes report the offending parameter. + [Theory] + [InlineData(0, 1, "width")] + [InlineData(-3, 1, "width")] + [InlineData(Surface.MaxDimension + 1, 1, "width")] + [InlineData(1, 0, "height")] + [InlineData(1, -1, "height")] + [InlineData(1, Surface.MaxDimension + 1, "height")] + public void Resize_InvalidDimensions_Throws(int width, int height, string parameter) + { + using var source = new Surface(4, 4); + var ex = Assert.Throws(() => source.Resize(width, height)); + Assert.Equal(parameter, ex.ParamName); + } + + /// An undefined mode is rejected for both entry points. + [Fact] + public void Resize_UndefinedMode_Throws() + { + using var source = new Surface(4, 4); + Assert.Equal("mode", Assert.Throws(() => source.Resize(2, 2, (ResamplingMode)99)).ParamName); + Assert.Equal("mode", Assert.Throws(() => source.ResizeToFit(2, 2, (ResamplingMode)(-1))).ParamName); + } + + /// A disposed surface cannot be resized. + [Fact] + public void Resize_Disposed_Throws() + { + var source = new Surface(4, 4); + source.Dispose(); + Assert.Throws(() => source.Resize(2, 2)); + Assert.Throws(() => source.ResizeToFit(2, 2)); + } + + /// ResizeToFit keeps the aspect ratio, fits the box, and works up and down. + [Theory] + [InlineData(100, 50, 20, 20, 20, 10)] + [InlineData(50, 100, 20, 20, 10, 20)] + [InlineData(10, 10, 40, 30, 30, 30)] + [InlineData(4, 2, 100, 100, 100, 50)] + [InlineData(300, 300, 7, 7, 7, 7)] + public void ResizeToFit_KeepsAspectAndFitsBox(int w, int h, int boxW, int boxH, int expectedW, int expectedH) + { + using var source = new Surface(w, h); + using var result = source.ResizeToFit(boxW, boxH); + Assert.Equal(expectedW, result.Width); + Assert.Equal(expectedH, result.Height); + } + + /// Extremely elongated images clamp the short axis to one pixel. + [Fact] + public void ResizeToFit_VeryElongated_ClampsToOnePixel() + { + using var source = new Surface(8000, 2); + using var result = source.ResizeToFit(10, 10); + Assert.Equal(10, result.Width); + Assert.Equal(1, result.Height); + } + + /// ResizeToFit validates the box. + [Theory] + [InlineData(0, 5, "maxWidth")] + [InlineData(Surface.MaxDimension + 1, 5, "maxWidth")] + [InlineData(5, 0, "maxHeight")] + [InlineData(5, Surface.MaxDimension + 1, "maxHeight")] + public void ResizeToFit_InvalidBox_Throws(int maxW, int maxH, string parameter) + { + using var source = new Surface(4, 4); + var ex = Assert.Throws(() => source.ResizeToFit(maxW, maxH)); + Assert.Equal(parameter, ex.ParamName); + } + + /// Every concrete mode produces the requested size. + [Fact] + public void Resize_AllModes_ProduceRequestedSize() + { + using var source = GrayRow(0, 64, 128, 192, 255); + foreach (var mode in ConcreteModes) + { + using var result = source.Resize(7, 3, mode); + Assert.Equal(7, result.Width); + Assert.Equal(3, result.Height); + } + } +} diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/TilePaintEvaluatorTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/TilePaintEvaluatorTests.cs index 7480424f9..c655b1836 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/TilePaintEvaluatorTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/TilePaintEvaluatorTests.cs @@ -115,4 +115,73 @@ public void EvaluateRow_NegativeSteps_SamplesUsingAbsoluteValueWraparound() Assert.Equal(positiveRow[0], negativeRow[0]); Assert.Equal(positiveRow[1], negativeRow[1]); } + /// A tile enlarged 4x is smoothly interpolated instead of showing hard blocks. + [Fact] + public void EvaluateRow_MagnifiedTile_IsSmooth() + { + using var tileSurface = CreateCheckerboardTileSurface(); + var tile = new TilePaint(tileSurface, Matrix3x2.CreateScale(4f), 2f, 2f); + var plan = TilePaintEvaluator.CreatePlan(tile); + try + { + Assert.True(plan.Magnified); + Span row = stackalloc Rgba32[8]; + TilePaintEvaluator.EvaluateRow(in plan, 0, 0, 8, row); + var distinct = new HashSet(); + foreach (var pixel in row) + { + distinct.Add(pixel.R); + } + + Assert.True(distinct.Count > 2); + } + finally + { + plan.Release(); + } + } + + /// A tile at exactly one device pixel per tile pixel keeps exact pixel values. + [Fact] + public void CreatePlan_OneToOneTile_IsNeitherMagnifiedNorMinified() + { + using var tileSurface = CreateCheckerboardTileSurface(); + var plan = TilePaintEvaluator.CreatePlan(new TilePaint(tileSurface, Matrix3x2.Identity, 2f, 2f)); + try + { + Assert.False(plan.Magnified); + Assert.Null(plan.Minified); + } + finally + { + plan.Release(); + } + } + + /// A tile shrunk to a quarter is replaced by an area-averaged copy that averages the checkerboard. + [Fact] + public void EvaluateRow_MinifiedTile_AveragesColors() + { + using var tileSurface = new Surface(8, 8); + for (var y = 0; y < 8; y++) + { + for (var x = 0; x < 8; x++) + { + tileSurface[x, y] = ((x + y) & 1) == 0 ? new Rgba32(255, 255, 255, 255) : new Rgba32(0, 0, 0, 255); + } + } + + var plan = TilePaintEvaluator.CreatePlan(new TilePaint(tileSurface, Matrix3x2.CreateScale(0.25f), 8f, 8f)); + try + { + Assert.NotNull(plan.Minified); + Span row = stackalloc Rgba32[2]; + TilePaintEvaluator.EvaluateRow(in plan, 0, 0, 2, row); + Assert.InRange(row[0].R, 100, 155); + } + finally + { + plan.Release(); + } + } } From 50a49de0e2b2c5e91ac51ef5c8b8dcdd09b88b77 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 09:28:41 -0400 Subject: [PATCH 02/16] Document and verify image resampling; add reqs, review sets, tests Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .cspell.yaml | 4 + .reviewmark.yaml | 6 + README.md | 10 +- docs/design/canvas-net-pdf/pdf-document.md | 31 +-- docs/design/canvas-net-pptx/pptx-document.md | 12 +- docs/design/canvas-net-svg/svg-codec.md | 23 ++- docs/design/canvas-net.md | 5 + docs/design/canvas-net/canvas/surface.md | 71 ++++--- docs/design/canvas-net/drawing/tile-paint.md | 13 +- docs/reqstream/canvas-net-pdf.yaml | 1 + .../canvas-net-pdf/pdf-document.yaml | 22 +- docs/reqstream/canvas-net-pptx.yaml | 1 + .../canvas-net-pptx/pptx-document.yaml | 11 + docs/reqstream/canvas-net-svg.yaml | 1 + docs/reqstream/canvas-net-svg/svg-codec.yaml | 15 ++ docs/reqstream/canvas-net.yaml | 45 +++++ docs/reqstream/canvas-net/canvas.yaml | 43 ++++ docs/reqstream/canvas-net/canvas/surface.yaml | 97 +++++++++ docs/reqstream/canvas-net/drawing.yaml | 1 + .../canvas-net/drawing/tile-paint.yaml | 12 ++ docs/user_guide/introduction.md | 44 ++++ .../canvas-net-pdf/pdf-document.md | 19 +- .../canvas-net-pptx/pptx-document.md | 6 + docs/verification/canvas-net-svg/svg-codec.md | 10 + .../verification/canvas-net/canvas/surface.md | 67 ++++++ .../canvas-net/drawing/tile-paint.md | 9 + .../PptxImagesTests.cs | 19 ++ .../SvgImageResamplingTests.cs | 191 +++++++++--------- 28 files changed, 629 insertions(+), 160 deletions(-) diff --git a/.cspell.yaml b/.cspell.yaml index 3a9f38dc0..9a2e3b2e7 100644 --- a/.cspell.yaml +++ b/.cspell.yaml @@ -20,6 +20,10 @@ words: - prefilter - prefiltered - resampler + - Catmull + - Lanczos + - optimizespeed + - sinc - Strikethru - Strikethrough - linepattern diff --git a/.reviewmark.yaml b/.reviewmark.yaml index 1db226245..ca8758b0d 100644 --- a/.reviewmark.yaml +++ b/.reviewmark.yaml @@ -128,9 +128,13 @@ reviews: - "docs/verification/canvas-net/canvas/surface.md" # unit verification - "src/DemaConsulting.CanvasNet/Canvas/Surface.cs" # unit source - "src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs" # internal image resampling helper + - "src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs" # separable resampling engine + - "src/DemaConsulting.CanvasNet/Canvas/ResamplingMode.cs" # public resampling filter enum - "src/DemaConsulting.CanvasNet/Canvas/NamespaceDoc.cs" # Canvas namespace documentation - "test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceTests.cs" # unit tests - "test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs" # resampler unit tests + - "test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs" # resize unit tests + - "test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeCodecRoundTripTests.cs" # round-trip tests # CanvasNet-Canvas-Rgba32 Review (one per unit) - id: CanvasNet-Canvas-Rgba32 @@ -708,6 +712,7 @@ reviews: - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Blend.cs" # phase 8 filter partial - "src/DemaConsulting.CanvasNet.Svg/NamespaceDoc.cs" # Svg namespace documentation - "test/DemaConsulting.CanvasNet.Svg.Tests/SvgCodecTests.cs" # unit tests + - "test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs" # image resampling unit tests - "test/DemaConsulting.CanvasNet.Svg.Tests/SvgFixtureTests.cs" # fixture conformance tests # CanvasNetPdf-Architecture Review (one per system) @@ -801,6 +806,7 @@ reviews: - "test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentJpxTests.cs" # JPXDecode/SMask unit tests - "test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentThinRuleInkTests.cs" # thin-rule ink unit tests - "test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageDownscaleTests.cs" # image downscale unit tests + - "test/DemaConsulting.CanvasNet.Pdf.Tests/PdfImageResamplingTests.cs" # image resampling grid unit tests - "test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentHairlineStrokeTests.cs" # hairline stroke unit tests - "test/DemaConsulting.CanvasNet.Tests/Jpeg2000Fixtures/gray.jp2" # gray JPX fixture - "test/DemaConsulting.CanvasNet.Tests/Jpeg2000Fixtures/source_gray.png" # source pixels of gray.jp2 diff --git a/README.md b/README.md index 3fffa1ff2..47d39f6aa 100644 --- a/README.md +++ b/README.md @@ -19,12 +19,14 @@ CanvasNet is a .NET library providing a mutable, span-based 32-bit RGBA pixel buffer along with codecs for loading and saving images in common file formats. It's designed for fast, allocation-conscious -image operations using `Span`, and supports independent-copy cropping for load/crop/save workflows. +image operations using `Span`, and supports independent-copy cropping and high-quality resizing for +load/crop/resize/save workflows. ## Features - 🖼️ **Pixel Buffer** - Mutable 32-bit RGBA surface with span access - ✂️ **Cropping** - Independent-copy crop for load/crop/save workflows +- 📐 **Resizing** - `Resize`/`ResizeToFit` with Nearest, Bilinear, Bicubic, Lanczos3 and Area filters - 🌈 **Compositing** - Alpha premultiply and Porter-Duff "over" compositing - 📀 **BMP Codec** - Load/save 24-bit/32-bit uncompressed BMP files - 🎨 **PNG Codec** - Load non-interlaced PNGs; save 8-bit RGB/RGBA @@ -87,6 +89,12 @@ using var cropped = surface.Crop(0, 0, 2, 2); // Save as PNG and load it back PngCodec.Save(surface, "surface.png"); using var reloaded = PngCodec.Load("surface.png"); + +// Load, crop, resize to fit a 64x64 box, and save +using var photo = PngCodec.Load("photo.png"); +using var region = photo.Crop(10, 10, 200, 100); +using var thumbnail = region.ResizeToFit(64, 64, ResamplingMode.Lanczos3); +PngCodec.Save(thumbnail, "thumbnail.png"); ``` Open a PDF and render a page (BMP/TIFF/JPEG/GIF/JPEG 2000/SVG codecs, header-only probing, and diff --git a/docs/design/canvas-net-pdf/pdf-document.md b/docs/design/canvas-net-pdf/pdf-document.md index 0ac3e5786..5e048e812 100644 --- a/docs/design/canvas-net-pdf/pdf-document.md +++ b/docs/design/canvas-net-pdf/pdf-document.md @@ -768,24 +768,24 @@ its own distinguishable `Feature` token. `pdf-jpx-smaskindata-indexed`) and then applies it; other values throw `InvalidDataException`. An explicit `/SMask` image (any filter, including `JPXDecode`; decoded through the same `DecodeImageSamples` path without nested masks, and required to be a - single-component non-`/Indexed` image, else `InvalidDataException`) is nearest-neighbor resampled + single-component non-`/Indexed` image, else `InvalidDataException`) is resized smoothly (bilinear) to the base image and its luminance multiplies the base alpha in place on the base surface (`ApplySoftMask`), taking precedence over `/SMaskInData`; `/Mask` and `/Matte` are not consulted. Inline images (`BI`) are not supported at all, which satisfies the PDF rule that `JPXDecode` is not permitted inline. `CompositeImageOntoSurface` inverts the CTM (a non-invertible/degenerate CTM silently paints - nothing), computes the device-space bounding box of the transformed unit square, and for every - destination pixel in that box nearest-neighbor-samples the source image (`row = floor((1 - v) * - image.Height)`, since image sample row `0` is the _top_ of the unit square per the PDF - specification's image-space convention, the opposite of user-space's y-up convention). When the - image is enlarged or drawn 1:1 this nearest-neighbor lookup is unchanged. When the pixel-to-device - mapping shrinks the image on either axis (local scales are the column norms of the 2x2 part of - the matrix), the internal `Canvas.SurfaceResampler` first area-averages the image once per draw - (an integer box prefilter, factor = nearest integer to the reduction ratio, premultiplied alpha, - output no larger than the source, so memory is bounded by the decoded image) and the result is - sampled bilinearly (centre-aligned, edge-clamped); mild shrinks below 1.5:1 use bilinear on the - source directly. Thin features such as one-pixel rules are therefore attenuated rather than - dropped. `/Interpolate` is not consulted. Each sampled source pixel is alpha-blended "over" the + nothing), computes the device-space bounding box of the transformed unit square, and when the + placement is axis-aligned (including flips) the internal `Canvas.SurfaceResampler.TryResampleToDevice` + resamples the image once per draw to exactly the device window it covers (the shared separable, + premultiplied-alpha engine: `Area` when shrinking, `Bicubic` when enlarging, kernel support scaled + by the reduction ratio, window clipped to the page so memory is bounded) and the window is composited + 1:1, with the clip coverage applied (image sample row `0` is the _top_ of the unit square per the PDF + specification's image-space convention, the opposite of user-space's y-up convention). A rotated or + skewed placement falls back to inverse-mapped bilinear sampling of an area-prefiltered source + (`Prefilter` + `SampleBilinear`). Thin features such as one-pixel rules are therefore attenuated + rather than dropped, and enlarged images are interpolated rather than shown as blocks. Stencil + `/ImageMask` images are not implemented, so no `Nearest` special case exists yet. `/Interpolate` is not consulted. + Each sampled source pixel is alpha-blended "over" the existing destination pixel via the shared internal `Canvas.Rgba32.CompositeOver(Rgba32, Rgba32)` helper (standard Porter-Duff "over" alpha compositing — straight/unassociated alpha in and out, `outA = fgA + bgA * (1 - fgA)`, each color channel `outC = (fgC * fgA + bgC * bgA * (1 - fgA)) / @@ -1446,8 +1446,9 @@ its own distinguishable `Feature` token. caller-supplied tint before compositing, preserving each pixel's own painted alpha exactly (so a partially transparent cell stays partially transparent, just recolored). The rendered cell becomes a `Drawing.TilePaint` (new `Drawing` subsystem unit — see _Introduction_ and - `Drawing/TilePaint.cs`/`Drawing/TilePaintEvaluator.cs`), sampled nearest-neighbor per destination - pixel by `Drawing.PathFiller`'s new `TilePaint` fill overload, mirroring the existing `Gradient` + `Drawing/TilePaint.cs`/`Drawing/TilePaintEvaluator.cs`), sampled per destination + pixel (exact lookup at 1:1, smoothed when magnified or minified) by `Drawing.PathFiller`'s new `TilePaint` fill + overload, mirroring the existing `Gradient` overload's structure exactly. - **Mesh shadings (`PdfDocument.Patterns.Shading.Mesh.cs`, `/ShadingType` 4-7)** — `ResolveMeshShading` requires the shading to be a stream and validates `/BitsPerCoordinate` (1/2/4/8/12/16/24/32), diff --git a/docs/design/canvas-net-pptx/pptx-document.md b/docs/design/canvas-net-pptx/pptx-document.md index 3f4a3bb81..a21bb1883 100644 --- a/docs/design/canvas-net-pptx/pptx-document.md +++ b/docs/design/canvas-net-pptx/pptx-document.md @@ -848,11 +848,13 @@ resolves a `` shape's `/` into a decoded core `Surfac - **Painting**: `PaintPicture(Surface destination, Surface image, PptxSrcRect? srcRect, Matrix3x2 shapeTransform, float widthEmu, float heightEmu, Path? clipPath = null)` composes the crop rectangle's own crop-to-unit-square mapping with `shapeTransform` into a single - image-to-surface matrix, inverts it once, and for every destination pixel whose inverse-mapped - coordinate falls within `[0,1]x[0,1]` samples the source image with nearest-neighbor filtering - (no bilinear/anti-aliased resampling this phase - a documented simplification, consistent with - this package's existing "no anti-aliasing yet" posture established by `PaintTextLayout`'s own - glyph-ink fill). Each sampled source pixel is alpha-blended "over" the existing destination + image-to-surface matrix, and for an axis-aligned placement resamples the cropped region once with + `SurfaceResampler.TryResampleToDevice` (shared separable engine: `Area` when shrinking, `Bicubic` when + enlarging) and composites the resulting device window 1:1. The `srcRect` crop is folded into the + mapping, so kernel taps next to a crop edge may read a little from outside the crop (a documented + minor limitation). A rotated picture inverts the matrix once and bilinear-samples an area-prefiltered + source per destination pixel whose inverse-mapped coordinate falls within `[0,1]x[0,1]`. Each sampled source pixel is + alpha-blended "over" the existing destination pixel via the shared internal `Canvas.Rgba32.CompositeOver(Rgba32, Rgba32)` helper (standard Porter-Duff "over" alpha compositing - straight/unassociated alpha in and out, `outA = fgA + bgA * (1 - fgA)`, each color channel `outC = (fgC * fgA + bgC * bgA * (1 - fgA)) / outA` when diff --git a/docs/design/canvas-net-svg/svg-codec.md b/docs/design/canvas-net-svg/svg-codec.md index 32a055423..7d2369d4b 100644 --- a/docs/design/canvas-net-svg/svg-codec.md +++ b/docs/design/canvas-net-svg/svg-codec.md @@ -154,9 +154,9 @@ inherited, only stops/content are" simplification); a rendered tile-buffer cache fill/stroke re-renders its own tile from scratch, since a tile's own pixel size depends on the referencing shape's own bounding box, not only the `pattern` element itself); a dedicated pattern-reference cycle-depth counter (a pattern-content cycle is instead caught for free by the -pre-existing `MaxElementDepth` guard, mirroring `mask`'s identical reliance); and bilinear/other -non-nearest-neighbor tile resampling (matching this codec's existing "no resampling filter -anywhere" convention). Within the supported `image` feature itself, the following are explicitly +pre-existing `MaxElementDepth` guard, mirroring `mask`'s identical reliance); and per-element +control of tile resampling beyond the automatic magnified/minified smoothing described below. Within the supported +`image` feature itself, the following are explicitly out of scope (see _Image_ below for the full rationale behind each): an `href`/`xlink:href` that is not a base64-encoded `data:` URI - an external file path or URL is tolerantly rendered as nothing, since resolving it would require introducing a base-path/resolver mechanism that does @@ -166,8 +166,8 @@ nested SVG document, whether base64-encoded or not) - tolerantly rendered as not same recursive-parsing-complexity reasoning that already excludes `feImage`'s own referenced-element case; auto-sizing from the decoded raster's own intrinsic dimensions when `width`/`height` are absent (both default to `0`, rendering nothing, rather than inferring a size -from the decoded content); and bilinear/other non-nearest-neighbor image resampling (matching -`pattern`'s identical "no resampling filter anywhere" convention). +from the decoded content); and `image-rendering` values other than the automatic, `pixelated`, +`crisp-edges` and `optimizeSpeed` keywords. A percentage value on a shape/text geometry attribute (`x`, `y`, `width`, `height`, `rx`, `ry`, `cx`, `cy`, `r`, `x1`/`y1`/`x2`/`y2`, `font-size`, `stroke-width`, `stroke-dasharray`, @@ -1103,8 +1103,9 @@ genuinely independent attributes elsewhere in this codec. Third, `SampleTileInto the rendered tile buffer into a region-sized destination, one destination pixel at a time: each pixel's own center is inverse-transformed back into grid space, wrapped (modulo) into the tile's own `[0, width) x [0, height)` extent via `WrapCoordinate`, rescaled into the tile buffer's own -pixel coordinates, and sampled nearest-neighbor (matching this codec's existing "no bilinear -resampling anywhere" convention) - new, isolated, well-commented arithmetic with no existing +pixel coordinates, and sampled according to the tile scale: exact nearest lookup when the tile is drawn at about one +device pixel per tile pixel (within 5 percent), wrapped bilinear when magnified, and an `Area`-resized copy of the tile +(disposed after the fill) when minified - new, isolated, well-commented arithmetic with no existing precedent to reuse, since this is a pure C# rasterizer with no native tiled/bitmap-shader primitive of any kind. That sample's own alpha is then multiplied by a freshly rasterized antialiased fill/stroke coverage buffer (`PathFiller.Fill` into a fresh `Surface`, the same @@ -1173,8 +1174,12 @@ to compute a fit transform from the decoded image's own intrinsic pixel size int rect, composed as `fitTransform * Matrix3x2.CreateTranslation(x, y) * elementTransform` (matching this codec's established left-to-right `A * B` "apply `A` first" composition convention). Each destination pixel within the placement rect's own pixel bounds is inverse-transformed back into -the decoded image's own pixel space and sampled nearest-neighbor (matching this codec's existing -"no bilinear resampling anywhere" convention) - a pixel whose inverse-transformed coordinate falls +the decoded image's own pixel space and resampled through the shared engine (`SurfaceResampler.TryResampleToDevice`: +`Area` when shrinking, +`Bicubic` when enlarging) for axis-aligned placements, with an inverse-mapped bilinear fallback on a +prefiltered source for rotated or skewed ones; the `image-rendering` property (attribute, style +declaration or stylesheet, inherited) set to `pixelated`, `crisp-edges` or `optimizeSpeed` selects +`Nearest` instead (`feImage` always smooths) - a pixel whose inverse-transformed coordinate falls outside the decoded image's own `[0, width) x [0, height)` extent (possible under a `slice` fit, or simply near the fit rect's own edges) is left untouched rather than wrapped, unlike `pattern`'s own deliberate wrap-around tiling. The result is composited onto the real canvas via diff --git a/docs/design/canvas-net.md b/docs/design/canvas-net.md index 9b9d2881a..bbf0259cd 100644 --- a/docs/design/canvas-net.md +++ b/docs/design/canvas-net.md @@ -176,6 +176,9 @@ The system exposes the following public API to external consumers: - **Surface.Crop(int x, int y, int width, int height)**: Returns a new, independent `Surface` containing a copy of the specified sub-region. Throws `ArgumentOutOfRangeException` if any argument is invalid or the region exceeds the source bounds. +- **Surface.Resize(int width, int height, ResamplingMode mode = Auto)** / **Surface.ResizeToFit(int maxWidth, + int maxHeight, ResamplingMode mode = Auto)**: Return a new, independent, resampled Surface. + Throw `ArgumentOutOfRangeException` for dimensions outside 1 to `MaxDimension` or an undefined mode. - **Surface.PremultiplyAlpha()**: Converts the surface's pixels from straight (unassociated) alpha to premultiplied alpha in place. - **Surface.UnpremultiplyAlpha()**: Converts the surface's pixels from premultiplied alpha back to @@ -355,6 +358,8 @@ The system exposes the following public API to external consumers: | `Surface.GetRowSpanBytes(int)` | Outbound | `Span` return | `y` within bounds | | `Surface.GetRowSpan(int)` | Outbound | `Span` return | `y` within bounds | | `Surface.Crop(int,int,int,int)` | Inbound/Outbound | Method call / `Surface` return | Region within source bounds | +| `Surface.Resize(int,int,ResamplingMode)` | Inbound/Outbound | Method call / `Surface` return | 1..MaxDimension, defined mode | +| `Surface.ResizeToFit(int,int,ResamplingMode)`| Inbound/Outbound | Method call / `Surface` return | 1..MaxDimension, defined mode | | `Surface.PremultiplyAlpha()` | Inbound | Method call | None | | `Surface.UnpremultiplyAlpha()` | Inbound | Method call | None | | `Surface.CompositeOver(Surface)` | Inbound | Method call | Equal dimensions, non-null | diff --git a/docs/design/canvas-net/canvas/surface.md b/docs/design/canvas-net/canvas/surface.md index c3d6860eb..d5fc2174b 100644 --- a/docs/design/canvas-net/canvas/surface.md +++ b/docs/design/canvas-net/canvas/surface.md @@ -3,7 +3,8 @@ ![Canvas Structure](CanvasView.svg) The `Surface` class is the second software unit in CanvasNet. It provides a mutable, in-memory -32-bit RGBA pixel buffer with allocation-free row access, independent-copy cropping, and +32-bit RGBA pixel buffer with allocation-free row access, independent-copy cropping, resampling (`Resize` / +`ResizeToFit`), and vectorized bulk pixel operations, forming the core pixel-storage primitive on which future drawing and codec functionality will build. @@ -171,6 +172,27 @@ both simpler and faster than iterating pixel by pixel for contiguous row data. - `ArgumentOutOfRangeException` — for any of the six invalid conditions listed above +##### Resize(int width, int height, ResamplingMode mode = Auto) + +Returns a new, independent `Surface` of size `width` by `height` resampled from this surface. +Validation order: disposed check (`ObjectDisposedException`), `width` outside `[1, MaxDimension]` +(`ArgumentOutOfRangeException(nameof(width))`), `height` outside `[1, MaxDimension]` +(`ArgumentOutOfRangeException(nameof(height))`), then an undefined `mode` +(`ArgumentOutOfRangeException(nameof(mode))`). A same-size request returns `Crop(0, 0, Width, Height)`, +an exact independent copy for every filter. Otherwise the work is delegated to the internal +`SurfaceResampler` engine (see below). + +`ResamplingMode` is a public enum: `Auto` (default), `Nearest`, `Bilinear`, `Bicubic` +(Catmull-Rom), `Lanczos3` and `Area`. `Auto` chooses per axis: `Area` when that axis shrinks and +`Bicubic` when it enlarges or stays the same. + +##### ResizeToFit(int maxWidth, int maxHeight, ResamplingMode mode = Auto) + +Validates the box like `Resize` (parameter names `maxWidth` / `maxHeight`), picks the uniform +scale `min(maxWidth / Width, maxHeight / Height)`, rounds each result dimension and clamps it into +`[1, box]`, then calls `Resize`. The image is enlarged or shrunk so that one axis touches the box +(up to rounding) and the aspect ratio is preserved to within pixel rounding. + ##### PremultiplyAlpha() Converts this surface's pixel buffer, in place, from straight (unassociated) alpha to @@ -452,25 +474,28 @@ versus supplied workspace) differs between the public and internal forms. A dedi (`Surface_CompositeOverSpan_PerPixelColors_MatchesConstantColorOverload_WhenAllColorsEqual`) proves the pre-existing constant-color overload's output is unchanged by this refactor. -#### Internal image-resampling helper (SurfaceResampler) - -`Canvas/SurfaceResampler.cs` is an `internal static` helper owned by this unit (visible to the -`Pdf` and `Pptx` packages) that lets callers draw a decoded raster image while shrinking it -without dropping thin features. `ComputeFactors` derives per-axis scales from the column norms of -the pixel-to-device affine matrix and returns integer block sizes (the nearest integer to the -reduction ratio, at least 1; non-finite, zero or enlarging scales yield 1). `Prefilter` returns -the source surface unchanged when the image is enlarged or drawn 1:1, when the mapping is -degenerate or non-finite, or when a shrink is too mild to round to a block factor above 1 (in the -shrink case it still sets the flag asking the caller to sample bilinearly; for enlargement and 1:1 -the caller keeps its nearest-neighbor lookup, so that path is bit-identical), and otherwise sets -that flag and returns a new surface -produced by `BoxReduce`. `BoxReduce` rejects block factors below 1 with -`ArgumentOutOfRangeException`, makes one O(W x H) pass accumulating premultiplied channel -sums in checked `long` arithmetic (an overflow throws `OverflowException`), un-premultiplies on -output (round half away from zero), and -averages only covered pixels in partial edge blocks; its output is at most the source size, so it -never exceeds `Surface.MaxDimension` and memory is bounded by one extra surface per draw. -`SampleBilinear` interpolates the four nearest pixels (centre-aligned, edge-clamped) in -premultiplied space. The caller builds the reduced surface once per draw, not per destination -pixel, and disposes it afterwards. `Pptx` and `Svg` keep their own nearest-neighbor loops; adopting -this helper is a possible follow-up. +#### Internal image-resampling engine (SurfaceResampler) + +`Canvas/SurfaceResampler.cs` and `Canvas/SurfaceResampler.Engine.cs` hold an `internal static +partial class` owned by this unit (visible to the `Pdf`, `Pptx` and `Svg` packages through +`InternalsVisibleTo`) that implements `Surface.Resize` and lets the renderers draw decoded raster +images smoothly. + +**Engine.** `Resample` maps the center of output pixel `o` to source coordinate +`start + (o + 0.5) * extent / outDim` (a negative extent flips the axis) and builds, per axis, a table +of tap indices and normalized weights for the chosen filter. When shrinking, the kernel support is +multiplied by the reduction ratio so every source pixel contributes (thin lines cannot be skipped). +Taps outside the image fold into the edge pixel, except `Area`, which drops them and renormalizes. An +axis with scale 1 and an integer start is an exact copy. Work is done in premultiplied alpha as two +separable passes: a horizontal pass over strips of columns into a float intermediate sized by an +8 MiB budget, then a vertical pass using `TensorPrimitives` multiply-add. Results are clamped to +`[0, 255]`, un-premultiplied and rounded; all index and size arithmetic uses `long`/checked math, so +the working memory is bounded regardless of aspect ratio (8192x1 to 1x8192 included). + +**Renderer entry points.** `TryResampleToDevice` resamples a source to the device window covered by +an axis-aligned image placement (the window is clipped to the visible area) so the renderer can +composite it 1:1; it returns `false` for rotation, skew or non-finite/degenerate matrices, and `true` +with no window when nothing is visible. Rotated or skewed placements use `Prefilter` (area-reduce +by an integer factor) plus `SampleBilinear` (inverse mapped, premultiplied, edge-clamped). +`SampleBilinearWrapped` is the wrap-around bilinear sampler used for magnified pattern tiles. +`BoxReduce` is the `Area` mode with integer factors. diff --git a/docs/design/canvas-net/drawing/tile-paint.md b/docs/design/canvas-net/drawing/tile-paint.md index 292d0612b..14fe8e622 100644 --- a/docs/design/canvas-net/drawing/tile-paint.md +++ b/docs/design/canvas-net/drawing/tile-paint.md @@ -6,8 +6,9 @@ The `TilePaint` unit is the public `TilePaint` type - a pre-rendered one-cell tile `Surface` plus a device-space `Transform` and a pattern-space `XStep`/`YStep` repeat pitch - and the internal -`TilePaintEvaluator` helper that resolves a tiled pattern's color per pixel by nearest-neighbor -sampling the wrapped-around tile bitmap. It has no independent externally visible behavior of its +`TilePaintEvaluator` helper that resolves a tiled pattern's color per pixel by sampling the wrapped-around tile bitmap +(exact pixel lookup at 1:1 scale, wrapped bilinear when magnified, an area-averaged copy when minified). It has no +independent externally visible behavior of its own: it exists to be consumed by `PathFiller`'s tile-paint `Fill(Surface, Path, TilePaint, FillRule, float)` overload (see _PathFiller Unit Design_, `path-filler.md`), mirroring `GradientPaint`'s own public-type-plus-internal-evaluator shape (see `gradient-paint.md`). @@ -77,8 +78,12 @@ every row of that fill. The per-pixel evaluation pipeline: the ratio of the tile surface's pixel dimensions to `XStep`/`YStep`, clamped into `[0, Width - 1] x [0, Height - 1]` (guarding a floating-point edge case landing exactly on the width/height boundary). -4. **Sample the tile `Surface` by nearest-neighbor** at the resolved integer pixel coordinate. - Bilinear interpolation is explicitly out of scope. +4. **Sample the tile `Surface`.** The plan classifies the tile scale (device pixels per tile pixel) + once per fill: above 1.05 the tile is _magnified_ and sampled bilinearly with wrap-around + (`SurfaceResampler.SampleBilinearWrapped`); below 0.95 it is _minified_ and replaced for the fill by + an `Area`-resized copy (owned by the plan and released by `plan.Release()` in a `finally` block + of the rasterizer); otherwise the exact tile pixel at the resolved integer coordinate is used, so + device-scale pattern cells stay bit-exact. **Degenerate Transform policy - deliberate divergence from `Gradient`.** When `TilePaint.Transform` is not invertible (or its inverse has a non-finite component), every pixel in diff --git a/docs/reqstream/canvas-net-pdf.yaml b/docs/reqstream/canvas-net-pdf.yaml index 345675c7e..8d1babd8f 100644 --- a/docs/reqstream/canvas-net-pdf.yaml +++ b/docs/reqstream/canvas-net-pdf.yaml @@ -247,6 +247,7 @@ sections: - CanvasNetPdf-PdfDocument-ImageDecodeArray - CanvasNetPdf-PdfDocument-ImageDecodeArrayInvalid - CanvasNetPdf-PdfDocument-ImageDownscale + - CanvasNetPdf-PdfDocument-ImageSmoothResample - CanvasNetPdf-PdfDocument-JpxDecode - CanvasNetPdf-PdfDocument-JpxColorSpace - CanvasNetPdf-PdfDocument-JpxSMaskInData diff --git a/docs/reqstream/canvas-net-pdf/pdf-document.yaml b/docs/reqstream/canvas-net-pdf/pdf-document.yaml index 900f2b681..005adc2a4 100644 --- a/docs/reqstream/canvas-net-pdf/pdf-document.yaml +++ b/docs/reqstream/canvas-net-pdf/pdf-document.yaml @@ -2024,9 +2024,9 @@ sections: - id: CanvasNetPdf-PdfDocument-ImageDownscale title: >- The PdfDocument class shall filter a raster image that is shrunk on the page, - area-averaging it once per draw and sampling the result bilinearly, so one-pixel - features are attenuated rather than dropped, while an enlarged or 1:1 image keeps - exact nearest-neighbor sampling. + resampling it once per draw with a reduction-scaled filter, so one-pixel + features are attenuated rather than dropped, while an enlarged image is smoothly + interpolated rather than shown as hard blocks. justification: | Real-world PDFs embed high-resolution raster scans (for example drawing grids) that are rendered at a fraction of their native size. Point sampling makes thin lines @@ -2035,4 +2035,18 @@ sections: - Render_ShrunkImageWithOnePixelLines_KeepsEveryLine - Render_ShrunkFlippedImage_KeepsEveryLine - Render_ShrunkRotatedImage_KeepsEveryLine - - Render_EnlargedImage_RemainsExactBlocks + - Render_EnlargedImage_IsSmoothlyInterpolated + + - id: CanvasNetPdf-PdfDocument-ImageSmoothResample + title: >- + The PdfDocument class shall resample a raster image placed axis-aligned on the page + once per draw with the shared engine (area filter when shrinking, bicubic when + enlarging), falling back to inverse-mapped bilinear sampling of a prefiltered + source for rotated or skewed placements, and resize a soft mask smoothly to the + image size, so no one-pixel line disappears at any output size. + justification: | + A single high-quality resample removes the phase-dependent loss of thin grid lines + seen when a high-resolution scan is rendered at many zoom levels. + tests: + - Render_GridImage_NoLineMissingAtAnySize + - Render_ShrunkRotatedImage_KeepsEveryLine diff --git a/docs/reqstream/canvas-net-pptx.yaml b/docs/reqstream/canvas-net-pptx.yaml index 4e5815547..bd5709472 100644 --- a/docs/reqstream/canvas-net-pptx.yaml +++ b/docs/reqstream/canvas-net-pptx.yaml @@ -268,6 +268,7 @@ sections: children: - CanvasNetPptx-PptxDocument-PictureDecodeAndCrop - CanvasNetPptx-PptxDocument-PicturePainting + - CanvasNetPptx-PptxDocument-PictureSmoothResample - CanvasNetPptx-PptxDocument-PictureGeometryClipping - CanvasNetPptx-PptxDocument-PictureStrokeOutline tests: diff --git a/docs/reqstream/canvas-net-pptx/pptx-document.yaml b/docs/reqstream/canvas-net-pptx/pptx-document.yaml index d143d42d0..a19db4661 100644 --- a/docs/reqstream/canvas-net-pptx/pptx-document.yaml +++ b/docs/reqstream/canvas-net-pptx/pptx-document.yaml @@ -2233,3 +2233,14 @@ sections: - ResolveTextLayout_TabCharacter_ExpandsToNextDefaultTabStop - ResolveTextLayout_TabCharacter_WrapDecisionUsesExpandedWidthNotGlyphWidth - ResolveTextLayout_MultipleTabCharacters_EachAdvancesToItsOwnNextTabStop + + - id: CanvasNetPptx-PptxDocument-PictureSmoothResample + title: >- + The PptxDocument class shall resample a picture smoothly with the shared engine + when it is enlarged or shrunk, keeping rotated pictures on an inverse-mapped + bilinear fallback. + justification: | + Pictures are routinely shown at a size different from their pixel size and must not + appear blocky or lose thin details. + tests: + - PaintPicture_EnlargedPicture_IsSmooth diff --git a/docs/reqstream/canvas-net-svg.yaml b/docs/reqstream/canvas-net-svg.yaml index 20aade4dc..4fb4d656a 100644 --- a/docs/reqstream/canvas-net-svg.yaml +++ b/docs/reqstream/canvas-net-svg.yaml @@ -229,6 +229,7 @@ sections: rather than introducing an unbounded or security-sensitive capability. children: - CanvasNetSvg-SvgCodec-ImageRendering + - CanvasNetSvg-SvgCodec-ImageSmoothResample - CanvasNetSvg-SvgCodec-ImageExternalHrefScope - CanvasNetSvg-SvgCodec-ImageResourceSafety tests: diff --git a/docs/reqstream/canvas-net-svg/svg-codec.yaml b/docs/reqstream/canvas-net-svg/svg-codec.yaml index 1f79fae60..7b91dda57 100644 --- a/docs/reqstream/canvas-net-svg/svg-codec.yaml +++ b/docs/reqstream/canvas-net-svg/svg-codec.yaml @@ -1454,3 +1454,18 @@ sections: - SvgCodec_Load_CssMalformedRule_SkipsOnlyThatRuleAndStillLoads - SvgCodec_Load_CssMalformedDeclaration_SkipsOnlyThatDeclaration - SvgCodec_Load_CssSiblingCombinator_DropsOnlyThatSelectorFromList + + - id: CanvasNetSvg-SvgCodec-ImageSmoothResample + title: >- + The SvgCodec class shall resample an image element smoothly with the shared engine + and use nearest-neighbor sampling when image-rendering is pixelated, crisp-edges or + optimizeSpeed, whether given as an attribute, a style declaration or a stylesheet rule. + justification: | + Smooth resampling keeps thin features of shrunken images, while authors need + pixel-art images to stay sharp when enlarged. + tests: + - Image_Enlarged_IsSmooth + - Image_RenderingAttribute_IsNearest + - Image_RenderingStyle_IsNearest + - Image_RenderingStylesheet_IsNearest + - Image_Shrunk_KeepsOnePixelLine diff --git a/docs/reqstream/canvas-net.yaml b/docs/reqstream/canvas-net.yaml index 1f493da4a..c55171445 100644 --- a/docs/reqstream/canvas-net.yaml +++ b/docs/reqstream/canvas-net.yaml @@ -85,6 +85,51 @@ sections: tests: - CanvasNet_SystemIntegration_CanvasCrop_ReturnsIndependentSubRegion + - id: CanvasNet-Lib-ImageResize + title: The library shall resample a pixel buffer to a new size with a selectable reconstruction filter. + tags: [system] + justification: | + Callers need to enlarge or shrink decoded images (for example before saving a thumbnail) + without writing their own filter, and thin features such as one-pixel lines must survive + a reduction rather than being dropped by point sampling. + children: + - CanvasNet-Canvas-Resize + tests: + - Resize_BmpCodec_RoundTrip + - Resize_PngCodec_RoundTrip + + - id: CanvasNet-Lib-ImageResizeAlpha + title: The library shall resample images in premultiplied alpha so transparent pixels leave no color fringe. + tags: [system] + justification: | + Filtering straight-alpha color lets the color of fully transparent pixels bleed into + neighboring pixels and produces dark or tinted edges around transparent regions. + children: + - CanvasNet-Canvas-ResizeAlpha + tests: + - Resize_AlphaEdge_HasNoColorFringe + + - id: CanvasNet-Lib-ImageResizeValidation + title: The library shall reject invalid resize parameters with ArgumentOutOfRangeException. + tags: [system] + justification: | + Non-positive or oversized dimensions and undefined filter modes cannot describe a valid + result and must be rejected before any allocation is attempted. + children: + - CanvasNet-Canvas-ResizeValidation + tests: + - Resize_InvalidDimensions_Throws + + - id: CanvasNet-Lib-ImageResizeToFit + title: The library shall resize an image to fit a bounding box while preserving its aspect ratio. + tags: [system] + justification: | + Thumbnails and previews are almost always specified as a bounding box rather than exact + dimensions, and callers should not have to compute the aspect-preserving size themselves. + children: + - CanvasNet-Canvas-ResizeToFit + tests: + - ResizeToFit_KeepsAspectAndFitsBox - id: CanvasNet-Lib-CanvasPremultiply title: >- The library shall convert a pixel buffer, in place, between straight (unassociated) and diff --git a/docs/reqstream/canvas-net/canvas.yaml b/docs/reqstream/canvas-net/canvas.yaml index c52634967..9656fcd64 100644 --- a/docs/reqstream/canvas-net/canvas.yaml +++ b/docs/reqstream/canvas-net/canvas.yaml @@ -396,6 +396,49 @@ sections: - Rgba32_Parse_6HexUppercase_ReturnsExpectedRgbaWithAlpha255 - Rgba32_TryParse_ValidInput_ReturnsTrueAndSetsResult + - id: CanvasNet-Canvas-Resize + title: >- + The Canvas subsystem shall create a resampled copy of a surface at a requested size using a + selectable filter. + justification: | + Enlarging and shrinking images with a quality filter is a core imaging operation, and + the same engine serves the renderer packages that draw raster images. + children: + - CanvasNet-Canvas-Surface-Resize + - CanvasNet-Canvas-Surface-ResizeIdentity + - CanvasNet-Canvas-Surface-ResizeBoundedMemory + - CanvasNet-Canvas-Surface-DeviceResample + - CanvasNet-Canvas-Surface-WrappedBilinear + tests: + - Resize_AllModes_ProduceRequestedSize + + - id: CanvasNet-Canvas-ResizeAlpha + title: The Canvas subsystem shall resample in premultiplied alpha. + justification: | + Premultiplied filtering prevents color bleeding from transparent pixels. + children: + - CanvasNet-Canvas-Surface-ResizeAlphaPremultiplied + tests: + - Resize_AlphaEdge_HasNoColorFringe + + - id: CanvasNet-Canvas-ResizeValidation + title: The Canvas subsystem shall reject invalid resize arguments and disposed surfaces. + justification: | + Invalid arguments must fail fast and predictably before any buffer is allocated. + children: + - CanvasNet-Canvas-Surface-ResizeInvalid + tests: + - Resize_InvalidDimensions_Throws + + - id: CanvasNet-Canvas-ResizeToFit + title: The Canvas subsystem shall resize a surface to fit a bounding box while preserving its aspect ratio. + justification: | + Bounding-box sizing is the common way callers request thumbnails and previews. + children: + - CanvasNet-Canvas-Surface-ResizeToFit + - CanvasNet-Canvas-Surface-ResizeToFitInvalidBox + tests: + - ResizeToFit_KeepsAspectAndFitsBox - id: CanvasNet-Canvas-PixelCompositing title: >- The Canvas subsystem shall provide a single-pixel Porter-Duff "over" alpha- diff --git a/docs/reqstream/canvas-net/canvas/surface.yaml b/docs/reqstream/canvas-net/canvas/surface.yaml index 6349049aa..55649b907 100644 --- a/docs/reqstream/canvas-net/canvas/surface.yaml +++ b/docs/reqstream/canvas-net/canvas/surface.yaml @@ -416,3 +416,100 @@ sections: shrink that the integer block factor cannot, without reading outside the image. tests: - SampleBilinear_CentreAndMidpoint_InterpolatesAndClampsEdges + + - id: CanvasNet-Canvas-Surface-Resize + title: >- + The Surface class shall return a new surface resampled to the requested size using + the Nearest, Bilinear, Bicubic (Catmull-Rom), Lanczos3 or Area filter, with Auto + choosing Area when shrinking and Bicubic when enlarging per axis, widening the + filter support by the reduction ratio so thin features survive a shrink. + justification: | + A separable, weight-table based resampler with a reduction-scaled support gives + predictable quality at every ratio and never drops one-pixel lines. + tests: + - Resize_Nearest_Upscale_ReplicatesPixels + - Resize_Bilinear_Upscale_InterpolatesLinearly + - Resize_Area_IntegerReduction_AveragesBlocks + - Resize_SharpFilters_StepEdge_ClampsToByteRange + - Resize_ConstantImage_StaysConstant + - Resize_Downscale_PreservesOnePixelLine + - Resize_Upscale_IsSmooth + - Resize_Auto_ChoosesPerAxis + - Resize_AllModes_ProduceRequestedSize + + - id: CanvasNet-Canvas-Surface-ResizeIdentity + title: >- + The Surface class shall return an exact, independent copy when the requested size equals + the current size. + justification: | + A same-size resize must not alter pixel values for any filter and must not share storage. + tests: + - Resize_SameSize_IsExactIndependentCopy + + - id: CanvasNet-Canvas-Surface-ResizeAlphaPremultiplied + title: The Surface class shall filter in premultiplied alpha and clamp results to the byte range. + justification: | + Premultiplied filtering avoids fringes around transparent pixels; clamping contains + the overshoot of the sharpening filters. + tests: + - Resize_AlphaEdge_HasNoColorFringe + - Resize_SharpFilters_StepEdge_ClampsToByteRange + + - id: CanvasNet-Canvas-Surface-ResizeInvalid + title: >- + The Surface class shall reject a width or height outside 1 to MaxDimension, an + undefined mode, or a disposed surface when resizing. + justification: | + Invalid arguments cannot describe a valid result and must be rejected before allocation. + tests: + - Resize_InvalidDimensions_Throws + - Resize_UndefinedMode_Throws + - Resize_Disposed_Throws + + - id: CanvasNet-Canvas-Surface-ResizeBoundedMemory + title: >- + The Surface class shall resample with working memory bounded independently of the extreme + aspect ratio of the image. + justification: | + Resizing an 8192 by 1 image to 1 by 8192 must not allocate an unbounded intermediate buffer. + tests: + - Resize_LargeAndWide_ProducesExpectedShape + + - id: CanvasNet-Canvas-Surface-ResizeToFit + title: >- + The Surface class shall resize to the largest aspect-preserving size that fits a + box, enlarging or shrinking, never returning a dimension below one pixel. + justification: | + Bounding-box sizing must keep the aspect ratio and stay within the box. + tests: + - ResizeToFit_KeepsAspectAndFitsBox + - ResizeToFit_VeryElongated_ClampsToOnePixel + + - id: CanvasNet-Canvas-Surface-ResizeToFitInvalidBox + title: The Surface class shall reject a bounding box dimension outside 1 to MaxDimension. + justification: | + An empty or oversized box cannot produce a valid result. + tests: + - ResizeToFit_InvalidBox_Throws + + - id: CanvasNet-Canvas-Surface-DeviceResample + title: >- + The Surface unit shall provide an internal helper that resamples a source to the + device window of an axis-aligned image placement, and declines rotated or skewed placements. + justification: | + The PDF, PPTX and SVG renderers draw most images axis-aligned and benefit from a + single high-quality resample followed by a 1:1 composite. + tests: + - TryResampleToDevice_RotatedMatrix_ReturnsFalse + - TryResampleToDevice_AxisAligned_ReturnsWindowAtOrigin + - TryResampleToDevice_OffScreen_ReturnsTrueWithNullWindow + - BoxReduce_MatchesAreaResize + + - id: CanvasNet-Canvas-Surface-WrappedBilinear + title: >- + The Surface unit shall provide an internal bilinear sampler that wraps at the surface edges + for tiled paints. + justification: | + Magnified repeating tiles must blend across the tile seam rather than clamp. + tests: + - SampleBilinearWrapped_AtEdge_BlendsWithOppositeSide diff --git a/docs/reqstream/canvas-net/drawing.yaml b/docs/reqstream/canvas-net/drawing.yaml index 5b9688ba9..9833be5cf 100644 --- a/docs/reqstream/canvas-net/drawing.yaml +++ b/docs/reqstream/canvas-net/drawing.yaml @@ -218,6 +218,7 @@ sections: - CanvasNet-Drawing-TilePaint-Definition - CanvasNet-Drawing-TilePaint-WithTransform - CanvasNet-Drawing-TilePaint-Sampling + - CanvasNet-Drawing-TilePaint-Smoothing - CanvasNet-Drawing-TilePaint-DegenerateTransparent - CanvasNet-Drawing-TilePaint-Paint - CanvasNet-Drawing-PathFiller-TileFill diff --git a/docs/reqstream/canvas-net/drawing/tile-paint.yaml b/docs/reqstream/canvas-net/drawing/tile-paint.yaml index e5a3442ac..d55fe75d7 100644 --- a/docs/reqstream/canvas-net/drawing/tile-paint.yaml +++ b/docs/reqstream/canvas-net/drawing/tile-paint.yaml @@ -121,3 +121,15 @@ sections: - PathFiller_Fill_TilePaint_NullPath_ThrowsArgumentNullException - PathFiller_Fill_TilePaint_NullPaint_ThrowsArgumentNullException - ScanlineRasterizer_Fill_TilePaint_NullPaint_ThrowsArgumentNullException + + - id: CanvasNet-Drawing-TilePaint-Smoothing + title: >- + The TilePaintEvaluator shall sample a magnified tile bilinearly with wrap-around, + replace a minified tile by an area-averaged copy, and keep exact pixel sampling + for tiles drawn at one device pixel per tile pixel. + justification: | + Pattern tiles drawn at other than 1:1 scale otherwise look blocky or alias. + tests: + - EvaluateRow_MagnifiedTile_IsSmooth + - CreatePlan_OneToOneTile_IsNeitherMagnifiedNorMinified + - EvaluateRow_MinifiedTile_AveragesColors diff --git a/docs/user_guide/introduction.md b/docs/user_guide/introduction.md index 85949ad93..e88ecbe7b 100644 --- a/docs/user_guide/introduction.md +++ b/docs/user_guide/introduction.md @@ -208,6 +208,38 @@ A new `Surface` containing an independent copy of the requested pixels. - `ArgumentOutOfRangeException`: Thrown when any argument is invalid or the region exceeds the source surface's bounds. +##### Resize + +```csharp +public Surface Resize(int width, int height, ResamplingMode mode = ResamplingMode.Auto) +``` + +Creates a new, independent `Surface` resampled to the requested size. Resampling is done in +premultiplied alpha, so transparent pixels leave no color fringe, and thin features such as +one-pixel lines survive a reduction. A request for the current size returns an exact copy. + +**Parameters:** + +- `width` (int): The new width. Must be between 1 and `Surface.MaxDimension`. +- `height` (int): The new height. Must be between 1 and `Surface.MaxDimension`. +- `mode` (`ResamplingMode`): The reconstruction filter. `Auto` (default) uses `Area` on an axis that + shrinks and `Bicubic` on an axis that enlarges. The other values are `Nearest`, `Bilinear`, + `Bicubic` (Catmull-Rom), `Lanczos3` and `Area`. + +**Exceptions:** + +- `ArgumentOutOfRangeException`: Thrown when a dimension is out of range or `mode` is not defined. +- `ObjectDisposedException`: Thrown when the surface has been disposed. + +##### ResizeToFit + +```csharp +public Surface ResizeToFit(int maxWidth, int maxHeight, ResamplingMode mode = ResamplingMode.Auto) +``` + +Creates a new `Surface` with the aspect ratio preserved that fits inside the given box, enlarging or +shrinking as needed (each dimension is at least one pixel). + ##### PremultiplyAlpha ```csharp @@ -2332,6 +2364,18 @@ Console.WriteLine(cropped.Height); // Output: 2 Console.WriteLine(cropped[0, 0].G); // Output: 255 ``` +## Example 2b: Load, Crop, Resize and Save + +```csharp +using DemaConsulting.CanvasNet.Canvas; +using DemaConsulting.CanvasNet.Codecs; + +using var original = PngCodec.Load("photo.png"); +using var cropped = original.Crop(10, 10, 200, 100); +using var thumbnail = cropped.ResizeToFit(64, 64, ResamplingMode.Lanczos3); +PngCodec.Save(thumbnail, "thumbnail.png"); +``` + ## Example 3: BMP Load/Save ```csharp diff --git a/docs/verification/canvas-net-pdf/pdf-document.md b/docs/verification/canvas-net-pdf/pdf-document.md index 998763c8b..845ec3676 100644 --- a/docs/verification/canvas-net-pdf/pdf-document.md +++ b/docs/verification/canvas-net-pdf/pdf-document.md @@ -1079,14 +1079,25 @@ bits before each row, rather than the implementation coincidentally tolerating z **Tests**: `Render_ShrunkImageWithOnePixelLines_KeepsEveryLine`, `Render_ShrunkFlippedImage_KeepsEveryLine`, `Render_ShrunkRotatedImage_KeepsEveryLine`, -`Render_EnlargedImage_RemainsExactBlocks` +`Render_EnlargedImage_IsSmoothlyInterpolated` `PdfDocumentImageDownscaleTests.cs` builds a synthetic in-memory PDF with a 1940x4 raw gray image containing one-pixel black lines every 24 source pixels, drawn full-page and rendered at 765, 1020, 1108 and 1303 pixels wide (non-integer reduction ratios), mirrored, and rotated 90 degrees. Every line must leave at least 70% of its area-proportional darkness within two pixels of its -mapped column (point sampling leaves some lines at zero). A 4x1 image enlarged 100x must still -render exact nearest-neighbor blocks. No timing is asserted. +mapped column (point sampling leaves some lines at zero). A 4x1 image enlarged 100x must be +smoothly interpolated (centers keep the source values, boundaries blend, the ramp is monotone). +`PdfImageResamplingTests.cs` renders a 1940-pixel-wide synthetic grid at nine output sizes (765 to 3672 +pixels wide) and requires that no line goes missing and the ink per line tracks the scale. No timing is asserted. + +#### CanvasNetPdf-PdfDocument-ImageSmoothResample: Axis-Aligned Images Are Resampled Once Per Draw + +**Tests**: `Render_GridImage_NoLineMissingAtAnySize`, `Render_ShrunkRotatedImage_KeepsEveryLine` + +`PdfImageResamplingTests.cs` renders a synthetic one-pixel-line grid at nine output sizes and +asserts that no line is missing and that the ink per line stays within a band around the +area-proportional value; the rotated case exercises the inverse-mapped bilinear fallback. No timing is +asserted. #### CanvasNetPdf-PdfDocument-ImageXObjects: Do Composites Images, Fails Closed on Unsupported Features @@ -1146,7 +1157,7 @@ formula. `PdfDocumentJpxTests.cs` builds minimal PDFs at test-run time. A 1x1 raw gray image, an 8x8 `DCTDecode` image and a JPX image each carry an `/SMask`; the rendered pixel's alpha equals the -mask luminance (the JPX case uses a 2x1 mask over an 8x8 base to prove nearest-neighbor +mask luminance (the JPX case uses a 2x1 mask over an 8x8 base to prove smooth (bilinear) resampling of the mask). A 1-bit 2x1 mask yields alpha `0` and `255`, a 16-bit mask contributes its high byte (`0x8000` gives alpha `128`), and a 4-bit mask with `/Decode [1 0]` yields `204`, proving every bit depth flows through the shared sample path instead of failing the page. diff --git a/docs/verification/canvas-net-pptx/pptx-document.md b/docs/verification/canvas-net-pptx/pptx-document.md index 9e4fd20d8..1b7f7ab63 100644 --- a/docs/verification/canvas-net-pptx/pptx-document.md +++ b/docs/verification/canvas-net-pptx/pptx-document.md @@ -1048,6 +1048,12 @@ resolved content type is not a recognized raster format throws `PptxUnsupportedF carrying the `"pptx-image-format"` feature token, and proves null argument validation for both `picElement`/`document`. +#### CanvasNetPptx-PptxDocument-PictureSmoothResample: Pictures Are Resampled Smoothly + +**Tests**: `PaintPicture_EnlargedPicture_IsSmooth` + +A 2x1 black/white picture painted at 40x4 contains many distinct gray levels instead of two hard blocks. + #### CanvasNetPptx-PptxDocument-PicturePainting: Picture Compositing Without PDF's Y-Flip **Tests**: `PaintPicture_IdentityTransformNoCrop_PaintsImagePixelsUnflipped`, diff --git a/docs/verification/canvas-net-svg/svg-codec.md b/docs/verification/canvas-net-svg/svg-codec.md index f6e773ca1..3db4866c3 100644 --- a/docs/verification/canvas-net-svg/svg-codec.md +++ b/docs/verification/canvas-net-svg/svg-codec.md @@ -1467,6 +1467,16 @@ neither `width` nor `height` present at all (both default to `0`, per this codec "no auto-sizing from intrinsic raster dimensions" simplification), each tolerantly render nothing rather than throwing or dividing by zero. +#### CanvasNetSvg-SvgCodec-ImageSmoothResample: `image` Is Resampled Smoothly, `image-rendering` Selects Nearest + +**Tests**: `Image_Enlarged_IsSmooth`, `Image_RenderingAttribute_IsNearest`, `Image_RenderingStyle_IsNearest`, +`Image_RenderingStylesheet_IsNearest`, `Image_Shrunk_KeepsOnePixelLine` + +`SvgImageResamplingTests.cs` enlarges a 2x1 black/white image to 40x4: by default the row has many +gray levels; with `image-rendering` `pixelated` or `crisp-edges` (attribute, style declaration or +stylesheet rule) it has only the two source levels. A 100x1 image with a one-pixel line shrunk to 17 +pixels keeps its area-proportional ink. + #### CanvasNetSvg-SvgCodec-ImageExternalHrefScope: `image` External-Href and Nested-SVG Scope Boundaries **Tests**: `SvgCodec_Load_ImageExternalFileHref_RendersNothingWithoutFileAccess`, diff --git a/docs/verification/canvas-net/canvas/surface.md b/docs/verification/canvas-net/canvas/surface.md index 56273b3e7..b190c764b 100644 --- a/docs/verification/canvas-net/canvas/surface.md +++ b/docs/verification/canvas-net/canvas/surface.md @@ -416,6 +416,73 @@ pixel with the global average; and rotation uses column norms. No timing is asse The bilinear sampler returns pixel centres exactly, blends midpoints, and clamps at the edges. +##### CanvasNet-Canvas-Surface-Resize: Resize Filters Behave as Documented + +**Tests**: `Resize_Nearest_Upscale_ReplicatesPixels`, `Resize_Bilinear_Upscale_InterpolatesLinearly`, +`Resize_Area_IntegerReduction_AveragesBlocks`, `Resize_SharpFilters_StepEdge_ClampsToByteRange`, +`Resize_ConstantImage_StaysConstant`, `Resize_Downscale_PreservesOnePixelLine`, +`Resize_Upscale_IsSmooth`, `Resize_Auto_ChoosesPerAxis`, `Resize_AllModes_ProduceRequestedSize` + +`SurfaceResizeTests.cs` checks exact values on tiny inputs for `Nearest`, `Bilinear` and `Area`, +that `Bicubic`/`Lanczos3` stay inside the byte range on a step edge, that a constant image stays +constant at many ratios, that a one-pixel line survives downscaling at ratios from 1.001:1 to 100:1 +(with `Area` conserving its ink to within 10 percent), that enlargement has no jumps, and that `Auto` +averages on the shrinking axis. No timing is asserted. + +##### CanvasNet-Canvas-Surface-ResizeIdentity: Same-Size Resize Is an Exact Copy + +**Tests**: `Resize_SameSize_IsExactIndependentCopy` + +For every mode a same-size resize returns a different instance with identical pixels, and mutating +it leaves the source unchanged. + +##### CanvasNet-Canvas-Surface-ResizeAlphaPremultiplied: Premultiplied Filtering and Clamping + +**Tests**: `Resize_AlphaEdge_HasNoColorFringe`, `Resize_SharpFilters_StepEdge_ClampsToByteRange` + +A red region beside fully transparent black keeps its color wherever the result is not transparent. + +##### CanvasNet-Canvas-Surface-ResizeInvalid: Invalid Resize Arguments + +**Tests**: `Resize_InvalidDimensions_Throws`, `Resize_UndefinedMode_Throws`, `Resize_Disposed_Throws` + +Zero, negative and above-`MaxDimension` sizes report the offending parameter name; an undefined mode +reports `mode`; a disposed surface throws `ObjectDisposedException`. + +##### CanvasNet-Canvas-Surface-ResizeBoundedMemory: Extreme Aspect Ratios + +**Tests**: `Resize_LargeAndWide_ProducesExpectedShape` + +An 8192x1 surface resizes to 1x8192 with the expected content. + +##### CanvasNet-Canvas-Surface-ResizeToFit: Aspect-Preserving Fit + +**Tests**: `ResizeToFit_KeepsAspectAndFitsBox`, `ResizeToFit_VeryElongated_ClampsToOnePixel` + +Wide, tall, enlarging, shrinking and elongated cases produce the expected sizes, never below one pixel. +`SurfaceResizeCodecRoundTripTests.cs` additionally loads, crops, resizes, saves and reloads through +`BmpCodec` and `PngCodec`. + +##### CanvasNet-Canvas-Surface-ResizeToFitInvalidBox: Invalid Bounding Box + +**Tests**: `ResizeToFit_InvalidBox_Throws` + +A zero or oversized box dimension reports `maxWidth` or `maxHeight`. + +##### CanvasNet-Canvas-Surface-DeviceResample: Device Window Resampling + +**Tests**: `TryResampleToDevice_RotatedMatrix_ReturnsFalse`, `TryResampleToDevice_AxisAligned_ReturnsWindowAtOrigin`, +`TryResampleToDevice_OffScreen_ReturnsTrueWithNullWindow`, `BoxReduce_MatchesAreaResize` + +Rotation is declined, an axis-aligned placement yields a window of the expected size and origin, an +off-screen placement yields no window, and `BoxReduce` equals an `Area` resize. + +##### CanvasNet-Canvas-Surface-WrappedBilinear: Wrap-Around Bilinear Sampling + +**Tests**: `SampleBilinearWrapped_AtEdge_BlendsWithOppositeSide` + +Sampling on the tile seam blends the last and first pixels. + ##### Rgba32 Sanity Checks (no requirement link) **Tests**: `Rgba32_FieldAssignment_StoresChannelValues`, `Rgba32_Equals_SameChannelValues_ReturnsTrue` diff --git a/docs/verification/canvas-net/drawing/tile-paint.md b/docs/verification/canvas-net/drawing/tile-paint.md index 4518c8dad..15663b33c 100644 --- a/docs/verification/canvas-net/drawing/tile-paint.md +++ b/docs/verification/canvas-net/drawing/tile-paint.md @@ -97,6 +97,15 @@ checkerboard tile produces both of the tile's own colors in the filled result; t reject a null surface, path, or tile paint argument; and they honor the same empty-input/ no-polygons no-op behavior already established for the solid-color and gradient overloads. +##### TilePaintEvaluator: Magnified and Minified Tiles + +**Tests**: `EvaluateRow_MagnifiedTile_IsSmooth`, `CreatePlan_OneToOneTile_IsNeitherMagnifiedNorMinified`, +`EvaluateRow_MinifiedTile_AveragesColors` + +A tile enlarged 4x is sampled bilinearly (many distinct values), a 1:1 tile keeps exact lookup with no +owned minified copy, and a tile shrunk to a quarter is replaced by an area-averaged copy whose colors +average the checkerboard. + #### Complexity Verification Policy No algorithmic complexity properties are newly established by this unit beyond those already diff --git a/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs b/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs index 8889a795d..c36ad880d 100644 --- a/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs +++ b/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs @@ -130,6 +130,25 @@ private static Surface BuildTwoToneImage(int width, int height) return image; } + /// Proves an enlarged picture is smoothly interpolated rather than painted as hard blocks. + [Fact] + public void PaintPicture_EnlargedPicture_IsSmooth() + { + using var image = new Surface(2, 1); + image[0, 0] = new Rgba32(0, 0, 0, 255); + image[1, 0] = new Rgba32(255, 255, 255, 255); + using var surface = new Surface(40, 4); + + PptxDocument.PaintPicture(surface, image, srcRect: null, Matrix3x2.Identity, widthEmu: 40f, heightEmu: 4f); + + var distinct = new HashSet(); + for (var x = 0; x < 40; x++) + { + distinct.Add(surface[x, 2].R); + } + + Assert.True(distinct.Count > 8); + } /// Proves an identity-transformed, uncropped picture paints the source image's pixels at the expected destination location, left-to-right unflipped. [Fact] public void PaintPicture_IdentityTransformNoCrop_PaintsImagePixelsUnflipped() diff --git a/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs b/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs index 3c7c38775..54cdf060b 100644 --- a/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs +++ b/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs @@ -1,95 +1,96 @@ -using System.Text; -using DemaConsulting.CanvasNet.Canvas; -using DemaConsulting.CanvasNet.Codecs; - -namespace DemaConsulting.CanvasNet.Svg.Tests; - -/// -/// Tests that SVG <image> elements are smoothly resampled and that the -/// image-rendering property selects nearest-neighbor sampling. Timing is never asserted. -/// -public class SvgImageResamplingTests -{ - /// Builds a 2x1 black/white PNG data URI. - private static string TwoPixelPng() - { - using var source = new Surface(2, 1); - source[0, 0] = new Rgba32(0, 0, 0, 255); - source[1, 0] = new Rgba32(255, 255, 255, 255); - using var stream = new MemoryStream(); - PngCodec.Save(source, stream); - return "data:image/png;base64," + Convert.ToBase64String(stream.ToArray()); - } - - /// Renders a 2x1 image enlarged to 40x4 using the given extra markup. - private static Surface Render(string imageAttributes, string styleBlock = "") - { - var svg = $"{styleBlock}" + - $""; - using var stream = new MemoryStream(Encoding.UTF8.GetBytes(svg)); - return SvgCodec.Load(stream, 40, 4); - } - - /// Counts distinct gray levels in the middle row. - private static int DistinctLevels(Surface surface) => - Enumerable.Range(0, surface.Width).Select(x => (int)surface[x, 2].R).Distinct().Count(); - - /// By default an enlarged image is smoothly interpolated. - [Fact] - public void Image_Enlarged_IsSmooth() - { - using var surface = Render(string.Empty); - Assert.True(DistinctLevels(surface) > 8); - } - - /// image-rendering as an attribute selects nearest-neighbor. - [Theory] - [InlineData("pixelated")] - [InlineData("crisp-edges")] - public void Image_RenderingAttribute_IsNearest(string value) - { - using var surface = Render($"image-rendering='{value}'"); - Assert.True(DistinctLevels(surface) <= 2); - Assert.Equal(0, surface[5, 2].R); - Assert.Equal(255, surface[35, 2].R); - } - - /// image-rendering in a style attribute selects nearest-neighbor. - [Fact] - public void Image_RenderingStyle_IsNearest() - { - using var surface = Render("style='image-rendering:pixelated'"); - Assert.True(DistinctLevels(surface) <= 2); - } - - /// image-rendering from a stylesheet selects nearest-neighbor. - [Fact] - public void Image_RenderingStylesheet_IsNearest() - { - using var surface = Render("class='px'", ""); - Assert.True(DistinctLevels(surface) <= 2); - } - - /// A shrunken image keeps a one-pixel line instead of dropping it. - [Fact] - public void Image_Shrunk_KeepsOnePixelLine() - { - using var source = new Surface(100, 1); - source.Clear(new Rgba32(255, 255, 255, 255)); - source[37, 0] = new Rgba32(0, 0, 0, 255); - using var stream = new MemoryStream(); - PngCodec.Save(source, stream); - var uri = "data:image/png;base64," + Convert.ToBase64String(stream.ToArray()); - var svg = $""; - using var svgStream = new MemoryStream(Encoding.UTF8.GetBytes(svg)); - using var surface = SvgCodec.Load(svgStream, 17, 1); - - double ink = 0; - for (var x = 0; x < 17; x++) - { - ink += 255 - surface[x, 0].R; - } - - Assert.InRange(ink, 255 * 0.17 * 0.8, 255 * 0.17 * 1.2 + 1); - } -} +using System.Text; +using DemaConsulting.CanvasNet.Canvas; +using DemaConsulting.CanvasNet.Codecs; + +namespace DemaConsulting.CanvasNet.Svg.Tests; + +/// +/// Tests that SVG <image> elements are smoothly resampled and that the +/// image-rendering property selects nearest-neighbor sampling. Timing is never asserted. +/// +public class SvgImageResamplingTests +{ + /// Builds a 2x1 black/white PNG data URI. + private static string TwoPixelPng() + { + using var source = new Surface(2, 1); + source[0, 0] = new Rgba32(0, 0, 0, 255); + source[1, 0] = new Rgba32(255, 255, 255, 255); + using var stream = new MemoryStream(); + PngCodec.Save(source, stream); + return "data:image/png;base64," + Convert.ToBase64String(stream.ToArray()); + } + + /// Renders a 2x1 image enlarged to 40x4 using the given extra markup. + private static Surface Render(string imageAttributes, string styleBlock = "") + { + var svg = $"{styleBlock}" + + $""; + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(svg)); + return SvgCodec.Load(stream, 40, 4); + } + + /// Counts distinct gray levels in the middle row. + private static int DistinctLevels(Surface surface) => + Enumerable.Range(0, surface.Width).Select(x => (int)surface[x, 2].R).Distinct().Count(); + + /// By default an enlarged image is smoothly interpolated. + [Fact] + public void Image_Enlarged_IsSmooth() + { + using var surface = Render(string.Empty); + Assert.True(DistinctLevels(surface) > 8); + } + + /// image-rendering as an attribute selects nearest-neighbor. + [Theory] + [InlineData("pixelated")] + [InlineData("crisp-edges")] + public void Image_RenderingAttribute_IsNearest(string value) + { + using var surface = Render($"image-rendering='{value}'"); + Assert.True(DistinctLevels(surface) <= 2); + Assert.Equal(0, surface[5, 2].R); + Assert.Equal(255, surface[35, 2].R); + } + + /// image-rendering in a style attribute selects nearest-neighbor. + [Fact] + public void Image_RenderingStyle_IsNearest() + { + using var surface = Render("style='image-rendering:pixelated'"); + Assert.True(DistinctLevels(surface) <= 2); + } + + /// image-rendering from a stylesheet selects nearest-neighbor. + [Fact] + public void Image_RenderingStylesheet_IsNearest() + { + using var surface = Render("class='px'", ""); + Assert.True(DistinctLevels(surface) <= 2); + } + + /// A shrunken image keeps a one-pixel line instead of dropping it. + [Fact] + public void Image_Shrunk_KeepsOnePixelLine() + { + using var source = new Surface(100, 1); + source.Clear(new Rgba32(255, 255, 255, 255)); + source[37, 0] = new Rgba32(0, 0, 0, 255); + using var stream = new MemoryStream(); + PngCodec.Save(source, stream); + var uri = "data:image/png;base64," + Convert.ToBase64String(stream.ToArray()); + var svg = $""; + using var svgStream = new MemoryStream(Encoding.UTF8.GetBytes(svg)); + using var surface = SvgCodec.Load(svgStream, 17, 1); + + double ink = 0; + for (var x = 0; x < 17; x++) + { + ink += 255 - surface[x, 0].R; + } + + Assert.InRange(ink, 255 * 0.17 * 0.8, 255 * 0.17 * 1.2 + 1); + + } +} From cc1a455d3ee1ca098ff356d383b3af241b3cafb4 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 09:53:18 -0400 Subject: [PATCH 03/16] Isolate PPTX srcRect crop from resampling; test SVG pattern tile smoothing; doc fixes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .reviewmark.yaml | 1 + docs/design/canvas-net-pdf/pdf-document.md | 5 +- docs/design/canvas-net-pptx/pptx-document.md | 10 +- docs/design/canvas-net-svg/svg-codec.md | 3 +- .../canvas-net-pptx/pptx-document.yaml | 4 +- docs/reqstream/canvas-net-svg.yaml | 1 + docs/reqstream/canvas-net-svg/svg-codec.yaml | 13 +++ .../canvas-net-pdf/pdf-document.md | 6 ++ .../canvas-net-pptx/pptx-document.md | 7 +- docs/verification/canvas-net-svg/svg-codec.md | 13 +++ .../PptxDocument.Images.cs | 40 ++++++-- .../SvgCodec.Patterns.cs | 2 +- .../PdfDocumentJpxTests.cs | 6 ++ .../PptxImagesTests.cs | 65 +++++++++++++ .../SvgPatternTileSmoothingTests.cs | 92 +++++++++++++++++++ 15 files changed, 249 insertions(+), 19 deletions(-) create mode 100644 test/DemaConsulting.CanvasNet.Svg.Tests/SvgPatternTileSmoothingTests.cs diff --git a/.reviewmark.yaml b/.reviewmark.yaml index ca8758b0d..c064cc2c5 100644 --- a/.reviewmark.yaml +++ b/.reviewmark.yaml @@ -713,6 +713,7 @@ reviews: - "src/DemaConsulting.CanvasNet.Svg/NamespaceDoc.cs" # Svg namespace documentation - "test/DemaConsulting.CanvasNet.Svg.Tests/SvgCodecTests.cs" # unit tests - "test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs" # image resampling unit tests + - "test/DemaConsulting.CanvasNet.Svg.Tests/SvgPatternTileSmoothingTests.cs" # pattern tile sampling unit tests - "test/DemaConsulting.CanvasNet.Svg.Tests/SvgFixtureTests.cs" # fixture conformance tests # CanvasNetPdf-Architecture Review (one per system) diff --git a/docs/design/canvas-net-pdf/pdf-document.md b/docs/design/canvas-net-pdf/pdf-document.md index 5e048e812..a08f30f46 100644 --- a/docs/design/canvas-net-pdf/pdf-document.md +++ b/docs/design/canvas-net-pdf/pdf-document.md @@ -783,8 +783,9 @@ its own distinguishable `Feature` token. specification's image-space convention, the opposite of user-space's y-up convention). A rotated or skewed placement falls back to inverse-mapped bilinear sampling of an area-prefiltered source (`Prefilter` + `SampleBilinear`). Thin features such as one-pixel rules are therefore attenuated - rather than dropped, and enlarged images are interpolated rather than shown as blocks. Stencil - `/ImageMask` images are not implemented, so no `Nearest` special case exists yet. `/Interpolate` is not consulted. + rather than dropped, and enlarged images are interpolated rather than shown as blocks. `/ImageMask` + stencil images are not rendered by this package (there is no code path for them), so no `Nearest` special + case applies. `/Interpolate` is not consulted. Each sampled source pixel is alpha-blended "over" the existing destination pixel via the shared internal `Canvas.Rgba32.CompositeOver(Rgba32, Rgba32)` helper (standard Porter-Duff "over" alpha compositing — straight/unassociated alpha in and out, diff --git a/docs/design/canvas-net-pptx/pptx-document.md b/docs/design/canvas-net-pptx/pptx-document.md index a21bb1883..c47d411b1 100644 --- a/docs/design/canvas-net-pptx/pptx-document.md +++ b/docs/design/canvas-net-pptx/pptx-document.md @@ -850,10 +850,12 @@ resolves a `` shape's `/` into a decoded core `Surfac rectangle's own crop-to-unit-square mapping with `shapeTransform` into a single image-to-surface matrix, and for an axis-aligned placement resamples the cropped region once with `SurfaceResampler.TryResampleToDevice` (shared separable engine: `Area` when shrinking, `Bicubic` when - enlarging) and composites the resulting device window 1:1. The `srcRect` crop is folded into the - mapping, so kernel taps next to a crop edge may read a little from outside the crop (a documented - minor limitation). A rotated picture inverts the matrix once and bilinear-samples an area-prefiltered - source per destination pixel whose inverse-mapped coordinate falls within `[0,1]x[0,1]`. Each sampled source pixel is + enlarging) and composites the resulting device window 1:1. The `srcRect` crop is isolated first: the smallest + whole-pixel window of the source containing the crop is cut out (`Surface.Crop`), so kernel taps next to a + crop edge fold into the window's own edge pixels and pixels outside the crop never bleed into it; the + fractional crop offset is part of the mapping. A rotated picture inverts the matrix once and + bilinear-samples an area-prefiltered copy of the same cropped window per destination pixel whose + inverse-mapped coordinate falls within `[0,1]x[0,1]`. Each sampled source pixel is alpha-blended "over" the existing destination pixel via the shared internal `Canvas.Rgba32.CompositeOver(Rgba32, Rgba32)` helper (standard Porter-Duff "over" alpha compositing - straight/unassociated alpha in and out, `outA = fgA + diff --git a/docs/design/canvas-net-svg/svg-codec.md b/docs/design/canvas-net-svg/svg-codec.md index 7d2369d4b..79c8f76cb 100644 --- a/docs/design/canvas-net-svg/svg-codec.md +++ b/docs/design/canvas-net-svg/svg-codec.md @@ -1105,7 +1105,8 @@ pixel's own center is inverse-transformed back into grid space, wrapped (modulo) own `[0, width) x [0, height)` extent via `WrapCoordinate`, rescaled into the tile buffer's own pixel coordinates, and sampled according to the tile scale: exact nearest lookup when the tile is drawn at about one device pixel per tile pixel (within 5 percent), wrapped bilinear when magnified, and an `Area`-resized copy of the tile -(disposed after the fill) when minified - new, isolated, well-commented arithmetic with no existing +(disposed after the fill) when minified (the sampling step is internal so that unit tests can exercise +each scale regime directly) - new, isolated, well-commented arithmetic with no existing precedent to reuse, since this is a pure C# rasterizer with no native tiled/bitmap-shader primitive of any kind. That sample's own alpha is then multiplied by a freshly rasterized antialiased fill/stroke coverage buffer (`PathFiller.Fill` into a fresh `Surface`, the same diff --git a/docs/reqstream/canvas-net-pptx/pptx-document.yaml b/docs/reqstream/canvas-net-pptx/pptx-document.yaml index a19db4661..dea1d28c2 100644 --- a/docs/reqstream/canvas-net-pptx/pptx-document.yaml +++ b/docs/reqstream/canvas-net-pptx/pptx-document.yaml @@ -2238,9 +2238,11 @@ sections: title: >- The PptxDocument class shall resample a picture smoothly with the shared engine when it is enlarged or shrunk, keeping rotated pictures on an inverse-mapped - bilinear fallback. + bilinear fallback, without letting pixels outside a srcRect crop influence the crop edge. justification: | Pictures are routinely shown at a size different from their pixel size and must not appear blocky or lose thin details. tests: - PaintPicture_EnlargedPicture_IsSmooth + - PaintPicture_EnlargedCrop_DoesNotBleedPixelsOutsideCrop + - PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop diff --git a/docs/reqstream/canvas-net-svg.yaml b/docs/reqstream/canvas-net-svg.yaml index 4fb4d656a..7fe5343fe 100644 --- a/docs/reqstream/canvas-net-svg.yaml +++ b/docs/reqstream/canvas-net-svg.yaml @@ -183,6 +183,7 @@ sections: (gradient) and effect (clip-path/mask) support. children: - CanvasNetSvg-SvgCodec-PatternRendering + - CanvasNetSvg-SvgCodec-PatternTileSmoothing - CanvasNetSvg-SvgCodec-PatternHrefInheritance - CanvasNetSvg-SvgCodec-PatternResourceSafety tests: diff --git a/docs/reqstream/canvas-net-svg/svg-codec.yaml b/docs/reqstream/canvas-net-svg/svg-codec.yaml index 7b91dda57..104b58ea0 100644 --- a/docs/reqstream/canvas-net-svg/svg-codec.yaml +++ b/docs/reqstream/canvas-net-svg/svg-codec.yaml @@ -1469,3 +1469,16 @@ sections: - Image_RenderingStyle_IsNearest - Image_RenderingStylesheet_IsNearest - Image_Shrunk_KeepsOnePixelLine + + - id: CanvasNetSvg-SvgCodec-PatternTileSmoothing + title: >- + The SvgCodec class shall sample a rendered pattern tile smoothly when the tile is + magnified (interpolated), area-average it when minified, and copy it exactly when it + is drawn at about one device pixel per tile pixel. + justification: | + Point sampling a scaled pattern tile produces blocky or aliased fills, while the + common device-scale case must stay pixel-exact. + tests: + - SampleTileIntoRegion_MagnifiedTile_IsSmooth + - SampleTileIntoRegion_MinifiedTile_IsAreaAveraged + - SampleTileIntoRegion_OneToOneTile_IsExactCopy diff --git a/docs/verification/canvas-net-pdf/pdf-document.md b/docs/verification/canvas-net-pdf/pdf-document.md index 845ec3676..7a553b459 100644 --- a/docs/verification/canvas-net-pdf/pdf-document.md +++ b/docs/verification/canvas-net-pdf/pdf-document.md @@ -1090,6 +1090,12 @@ smoothly interpolated (centers keep the source values, boundaries blend, the ram `PdfImageResamplingTests.cs` renders a 1940-pixel-wide synthetic grid at nine output sizes (765 to 3672 pixels wide) and requires that no line goes missing and the ink per line tracks the scale. No timing is asserted. +> **Note on tolerances**: before smooth resampling, image tests compared sampled pixels exactly. Smooth +> resampling (Catmull-Rom when enlarged, area averaging when shrunk) only alters pixels at or beside a +> source-pixel boundary or the image edge, so those tests now assert interior samples with a small per-channel +> tolerance (2 to 4 levels, from sampling slightly off a source pixel center) and use a larger tolerance +> (16 levels) only for the one soft-mask edge-adjacent sample. The expected colors themselves are unchanged. + #### CanvasNetPdf-PdfDocument-ImageSmoothResample: Axis-Aligned Images Are Resampled Once Per Draw **Tests**: `Render_GridImage_NoLineMissingAtAnySize`, `Render_ShrunkRotatedImage_KeepsEveryLine` diff --git a/docs/verification/canvas-net-pptx/pptx-document.md b/docs/verification/canvas-net-pptx/pptx-document.md index 1b7f7ab63..69e76c8db 100644 --- a/docs/verification/canvas-net-pptx/pptx-document.md +++ b/docs/verification/canvas-net-pptx/pptx-document.md @@ -1050,9 +1050,14 @@ carrying the `"pptx-image-format"` feature token, and proves null argument valid #### CanvasNetPptx-PptxDocument-PictureSmoothResample: Pictures Are Resampled Smoothly -**Tests**: `PaintPicture_EnlargedPicture_IsSmooth` +**Tests**: `PaintPicture_EnlargedPicture_IsSmooth`, `PaintPicture_EnlargedCrop_DoesNotBleedPixelsOutsideCrop`, +`PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop` A 2x1 black/white picture painted at 40x4 contains many distinct gray levels instead of two hard blocks. +An 8x8 picture with two bright-red left columns and six blue columns, cropped with `srcRect` left = 25 percent +and enlarged (axis-aligned) or rotated 90 degrees, paints only pure blue everywhere (the red outside the crop +never reaches the crop edge); an exact-equality assertion is valid here because the crop window is isolated +before resampling. #### CanvasNetPptx-PptxDocument-PicturePainting: Picture Compositing Without PDF's Y-Flip diff --git a/docs/verification/canvas-net-svg/svg-codec.md b/docs/verification/canvas-net-svg/svg-codec.md index 3db4866c3..8d3b638e2 100644 --- a/docs/verification/canvas-net-svg/svg-codec.md +++ b/docs/verification/canvas-net-svg/svg-codec.md @@ -1386,6 +1386,16 @@ per SVG's own "a pattern with no positive tile area applies no paint" semantics; correctly via the ordinary recursive `RenderElement` walk (not a bespoke, feature-limited content renderer), proving tile content may freely use this codec's other rendering features. +#### CanvasNetSvg-SvgCodec-PatternTileSmoothing: Pattern Tile Sampling Is Scale-Aware + +**Tests**: `SampleTileIntoRegion_MagnifiedTile_IsSmooth`, `SampleTileIntoRegion_MinifiedTile_IsAreaAveraged`, +`SampleTileIntoRegion_OneToOneTile_IsExactCopy` + +`SvgPatternTileSmoothingTests.cs` calls the internal `SampleTileIntoRegion` directly with a one-row tile. +A 2x1 black/white tile drawn 20x larger (a scaled `patternTransform`) yields a many-level, non-decreasing ramp +whose tile-pixel boundary is mid-gray. An 8x1 alternating black/white tile drawn at half size is area-averaged to +uniform mid-gray instead of aliasing to stripes. A 4x1 tile drawn at exactly 1:1 repeats as an exact, bit-for-bit copy. + #### CanvasNetSvg-SvgCodec-PatternHrefInheritance: `pattern` Href Template Inheritance and Cycle Rejection **Tests**: `SvgCodec_Load_PatternHrefInheritance_InheritsContentFromTemplate`, @@ -1477,6 +1487,9 @@ gray levels; with `image-rendering` `pixelated` or `crisp-edges` (attribute, sty stylesheet rule) it has only the two source levels. A 100x1 image with a one-pixel line shrunk to 17 pixels keeps its area-proportional ink. +Where the image tests above compare against smoothed output they use a small tolerance, because smoothing +only changes pixels at or beside a source-pixel boundary; interior pixels are still asserted to their expected colors. + #### CanvasNetSvg-SvgCodec-ImageExternalHrefScope: `image` External-Href and Nested-SVG Scope Boundaries **Tests**: `SvgCodec_Load_ImageExternalFileHref_RendersNothingWithoutFileAccess`, diff --git a/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs b/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs index e5b7f969c..6d87d676f 100644 --- a/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs +++ b/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs @@ -706,12 +706,34 @@ internal static void PaintPicture( // the pixel-to-device mapping. var cropWidth = Math.Max(1e-6f, 1f - left - right); var cropHeight = Math.Max(1e-6f, 1f - top - bottom); + + // The srcRect crop must be isolated from the rest of the image. Otherwise the bicubic or + // area kernel reads adjacent pixels outside the crop and they bleed into its edge. + // So first cut the smallest whole-pixel window containing the crop, and the resampler + // folds taps beyond that window into the window's own edge pixels. + var cropLeftPx = (double)left * image.Width; + var cropTopPx = (double)top * image.Height; + var cropWidthPx = (double)cropWidth * image.Width; + var cropHeightPx = (double)cropHeight * image.Height; + var windowX0 = Math.Clamp((int)Math.Floor(cropLeftPx + 1e-6), 0, image.Width - 1); + var windowY0 = Math.Clamp((int)Math.Floor(cropTopPx + 1e-6), 0, image.Height - 1); + var windowX1 = Math.Clamp((int)Math.Ceiling(cropLeftPx + cropWidthPx - 1e-6) - 1, windowX0, image.Width - 1); + var windowY1 = Math.Clamp((int)Math.Ceiling(cropTopPx + cropHeightPx - 1e-6) - 1, windowY0, image.Height - 1); + var windowW = windowX1 - windowX0 + 1; + var windowH = windowY1 - windowY0 + 1; + var cropped = windowW == image.Width && windowH == image.Height + ? null + : image.Crop(windowX0, windowY0, windowW, windowH); + var source = cropped ?? image; + using var croppedOwner = cropped; + + // Maps a source-window pixel to the unit square: add the window origin, subtract the crop origin, divide by the crop size var pixelToUnit = new Matrix3x2( - 1f / (image.Width * cropWidth), 0f, - 0f, 1f / (image.Height * cropHeight), - -left / cropWidth, -top / cropHeight); + (float)(1.0 / cropWidthPx), 0f, + 0f, (float)(1.0 / cropHeightPx), + (float)((windowX0 - cropLeftPx) / cropWidthPx), (float)((windowY0 - cropTopPx) / cropHeightPx)); var pixelToSurface = pixelToUnit * unitToSurface; - if (SurfaceResampler.TryResampleToDevice(image, pixelToSurface, surface.Width, surface.Height, ResamplingMode.Auto, out var window, out var originX, out var originY)) + if (SurfaceResampler.TryResampleToDevice(source, pixelToSurface, surface.Width, surface.Height, ResamplingMode.Auto, out var window, out var originX, out var originY)) { using (window) { @@ -725,8 +747,8 @@ internal static void PaintPicture( } // Rotated or skewed pictures: inverse-map each destination pixel and sample the - // source (prefiltered when shrinking) bilinearly. - var prefiltered = SurfaceResampler.Prefilter(image, pixelToSurface, out _); + // source window (prefiltered when shrinking) bilinearly. + var prefiltered = SurfaceResampler.Prefilter(source, pixelToSurface, out _); try { for (var y = startY; y <= endY; y++) @@ -749,8 +771,8 @@ internal static void PaintPicture( } // Remap the unit-square sample point through the srcRect crop; no (1 - v) flip - var imageU = left + (u * (1f - left - right)); - var imageV = top + (v * (1f - top - bottom)); + var imageU = (float)((cropLeftPx - windowX0 + (u * cropWidthPx)) / windowW); + var imageV = (float)((cropTopPx - windowY0 + (v * cropHeightPx)) / windowH); var sourcePixel = SurfaceResampler.SampleBilinear(prefiltered, imageU, imageV); surface[x, y] = Rgba32.CompositeOver(surface[x, y], ScaleAlpha(sourcePixel, maskAlpha)); } @@ -758,7 +780,7 @@ internal static void PaintPicture( } finally { - if (!ReferenceEquals(prefiltered, image)) + if (!ReferenceEquals(prefiltered, source)) { prefiltered.Dispose(); } diff --git a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs index e91f89cb8..36a9305f9 100644 --- a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs +++ b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs @@ -527,7 +527,7 @@ private static bool TryComputeContentRenderTransform( /// The tile rectangle's own height, in grid space. Already validated positive. /// The inverse of the composed grid-space-to-pixel-space transform. /// A new region-sized buffer, ready for . - private static Surface SampleTileIntoRegion( + internal static Surface SampleTileIntoRegion( Surface tileBuffer, Surface coverage, int pixelX, diff --git a/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentJpxTests.cs b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentJpxTests.cs index ac341d124..92cece1c6 100644 --- a/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentJpxTests.cs +++ b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentJpxTests.cs @@ -90,6 +90,12 @@ private static Surface Render(params byte[][] extraObjects) private static void AssertChannelNear(int expected, int actual, int tolerance = 4) => Assert.True(Math.Abs(expected - actual) <= tolerance, $"expected {expected} actual {actual}"); + /// + /// Asserts every channel is within of . + /// Tolerance (rather than exactness) is needed because enlarged images are smoothly resampled, + /// which only alters pixels at or next to a source-pixel boundary; the samples asserted here + /// are interior pixels, so a small tolerance still pins the expected color. + /// private static void AssertNear(Rgba32 expected, Rgba32 actual, int tolerance = 2) { Assert.True(Math.Abs(expected.R - actual.R) <= tolerance, $"R expected {expected.R} actual {actual.R}"); diff --git a/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs b/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs index c36ad880d..b76a233e5 100644 --- a/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs +++ b/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs @@ -187,6 +187,71 @@ public void PaintPicture_TopBottomAsymmetricImage_PaintsWithoutVerticalFlip() Assert.Equal(new Rgba32(0, 255, 255, 255), surface[1, 3]); } + /// Builds an 8x8 image whose two left columns are bright red and whose other six columns are blue. + private static Surface BuildRedBorderBlueImage() + { + var image = new Surface(8, 8); + for (var y = 0; y < 8; y++) + { + for (var x = 0; x < 8; x++) + { + image[x, y] = x < 2 ? new Rgba32(255, 0, 0, 255) : new Rgba32(0, 0, 255, 255); + } + } + + return image; + } + + /// Proves pixels outside a crop do not bleed into the crop edge when an axis-aligned picture is enlarged (the smoothing kernel is confined to the cropped window). + [Fact] + public void PaintPicture_EnlargedCrop_DoesNotBleedPixelsOutsideCrop() + { + // Crop away the two bright-red columns (25 percent of the width) and enlarge the rest 6.67x + using var image = BuildRedBorderBlueImage(); + using var surface = new Surface(40, 40); + var srcRect = new PptxSrcRect(Left: 0.25f, Top: 0f, Right: 0f, Bottom: 0f); + + PptxDocument.PaintPicture(surface, image, srcRect, Matrix3x2.Identity, widthEmu: 40f, heightEmu: 40f); + + // Every pixel, including the left crop edge, is pure blue: no red leaks in from outside the crop + for (var y = 0; y < 40; y++) + { + for (var x = 0; x < 40; x++) + { + Assert.Equal(new Rgba32(0, 0, 255, 255), surface[x, y]); + } + } + } + + /// Proves the crop also does not bleed for a rotated picture (inverse-mapped bilinear path). + [Fact] + public void PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop() + { + using var image = BuildRedBorderBlueImage(); + using var surface = new Surface(40, 40); + var srcRect = new PptxSrcRect(Left: 0.25f, Top: 0f, Right: 0f, Bottom: 0f); + var transform = Matrix3x2.CreateRotation(MathF.PI / 2f) * Matrix3x2.CreateTranslation(40f, 0f); + + PptxDocument.PaintPicture(surface, image, srcRect, transform, widthEmu: 40f, heightEmu: 40f); + + var painted = 0; + for (var y = 0; y < 40; y++) + { + for (var x = 0; x < 40; x++) + { + if (surface[x, y].A == 0) + { + continue; + } + + painted++; + Assert.Equal(0, surface[x, y].R); + } + } + + Assert.True(painted > 1000, "the rotated picture should cover most of the surface"); + } + /// Proves a crop re-maps the sampled region: cropping away the left half of a two-tone image leaves only its right (blue) half visible. [Fact] public void PaintPicture_WithSrcRectCroppingLeftHalf_SamplesOnlyRightHalf() diff --git a/test/DemaConsulting.CanvasNet.Svg.Tests/SvgPatternTileSmoothingTests.cs b/test/DemaConsulting.CanvasNet.Svg.Tests/SvgPatternTileSmoothingTests.cs new file mode 100644 index 000000000..42aba2ac8 --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Svg.Tests/SvgPatternTileSmoothingTests.cs @@ -0,0 +1,92 @@ +using System.Numerics; +using DemaConsulting.CanvasNet.Canvas; + +namespace DemaConsulting.CanvasNet.Svg.Tests; + +/// +/// Tests the sampling of a rendered pattern tile buffer into the painted region +/// (SvgCodec.SampleTileIntoRegion): a magnified tile is smoothly interpolated, a +/// minified tile is area-averaged, and a tile drawn at about one device pixel per tile pixel +/// is copied exactly. Timing is never asserted. +/// +public class SvgPatternTileSmoothingTests +{ + /// Samples a one-row repeated across a -pixel-wide row. + /// The tile buffer. + /// Tile width in grid space. + /// Uniform grid-to-device scale. + /// Painted region width in device pixels. + private static Surface Sample(Surface tile, float tileWidth, float scale, int regionWidth) + { + using var coverage = new Surface(regionWidth, 1); + coverage.Clear(new Rgba32(255, 255, 255, 255)); + return SvgCodec.SampleTileIntoRegion( + tile, coverage, 0, 0, regionWidth, 1, 0f, 0f, tileWidth, 1f, Matrix3x2.CreateScale(1f / scale)); + } + + /// A tile drawn well above one device pixel per tile pixel (a scaled pattern) is smoothly interpolated, not blocky. + [Fact] + public void SampleTileIntoRegion_MagnifiedTile_IsSmooth() + { + // A 2x1 black/white tile drawn 20x larger (device scale 20) + using var tile = new Surface(2, 1); + tile[0, 0] = new Rgba32(0, 0, 0, 255); + tile[1, 0] = new Rgba32(255, 255, 255, 255); + + using var result = Sample(tile, tileWidth: 2f, scale: 20f, regionWidth: 40); + + // Nearest sampling would give exactly two levels; bilinear gives a ramp + var levels = Enumerable.Range(0, 40).Select(x => (int)result[x, 0].R).Distinct().Count(); + Assert.True(levels > 8, $"expected a smooth ramp, saw {levels} levels"); + + // The boundary between the two tile pixels (device x = 20) blends them about equally + Assert.InRange(result[19, 0].R, 110, 145); + Assert.InRange(result[20, 0].R, 110, 145); + + // The ramp never decreases between the two pixel centers (device x = 10 .. 30) + for (var x = 11; x <= 30; x++) + { + Assert.True(result[x, 0].R >= result[x - 1, 0].R, $"ramp decreased at x={x}"); + } + } + + /// A tile drawn smaller than one device pixel per tile pixel is area-averaged so alternating thin features do not alias. + [Fact] + public void SampleTileIntoRegion_MinifiedTile_IsAreaAveraged() + { + // An 8x1 tile of alternating black/white pixels drawn at half size: each device pixel covers one black and one white tile pixel + using var tile = new Surface(8, 1); + for (var x = 0; x < 8; x++) + { + var v = (byte)(x % 2 == 0 ? 0 : 255); + tile[x, 0] = new Rgba32(v, v, v, 255); + } + + using var result = Sample(tile, tileWidth: 8f, scale: 0.5f, regionWidth: 16); + + // Point sampling would alias to solid black or white stripes; averaging gives uniform mid-gray + for (var x = 0; x < 16; x++) + { + Assert.InRange(result[x, 0].R, 125, 130); + } + } + + /// A tile drawn at one device pixel per tile pixel is copied exactly (no smoothing), repeating with wrap-around. + [Fact] + public void SampleTileIntoRegion_OneToOneTile_IsExactCopy() + { + using var tile = new Surface(4, 1); + Rgba32[] colors = [new(255, 0, 0, 255), new(0, 255, 0, 255), new(0, 0, 255, 255), new(10, 20, 30, 255)]; + for (var x = 0; x < 4; x++) + { + tile[x, 0] = colors[x]; + } + + using var result = Sample(tile, tileWidth: 4f, scale: 1f, regionWidth: 8); + + for (var x = 0; x < 8; x++) + { + Assert.Equal(colors[x % 4], result[x, 0]); + } + } +} From 0a3c673e9390eca7d2b80c39e5a23f91895bc8a3 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 10:09:35 -0400 Subject: [PATCH 04/16] Address formal-review findings: Area edge renormalization, SVG image-rendering parsing, shared tile classification, tests and docs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .cspell.yaml | 1 + docs/design/canvas-net-pdf/pdf-document.md | 8 +-- docs/design/canvas-net-pptx/pptx-document.md | 4 +- docs/design/canvas-net-svg/svg-codec.md | 4 +- .../canvas-net-pptx/pptx-document.yaml | 1 + docs/reqstream/canvas-net-svg/svg-codec.yaml | 3 + docs/reqstream/canvas-net/canvas/surface.yaml | 9 ++- .../canvas-net/drawing/tile-paint.yaml | 2 + .../canvas-net-pptx/pptx-document.md | 8 ++- docs/verification/canvas-net-svg/svg-codec.md | 4 +- .../verification/canvas-net/canvas/surface.md | 6 +- .../SvgCodec.Elements.cs | 7 +- .../SvgCodec.Patterns.cs | 14 +--- .../Canvas/SurfaceResampler.Engine.cs | 66 ++++++++++++++++++ .../Drawing/TilePaintEvaluator.cs | 23 +------ .../PptxImagesTests.cs | 23 +++++++ .../SvgImageResamplingTests.cs | 36 ++++++++++ .../Canvas/SurfaceResamplerTests.cs | 67 +++++++++++++++++++ .../Canvas/SurfaceResizeTests.cs | 13 ++-- .../Drawing/TilePaintEvaluatorTests.cs | 44 ++++++++++++ 20 files changed, 289 insertions(+), 54 deletions(-) diff --git a/.cspell.yaml b/.cspell.yaml index 9a2e3b2e7..db367cb7d 100644 --- a/.cspell.yaml +++ b/.cspell.yaml @@ -23,6 +23,7 @@ words: - Catmull - Lanczos - optimizespeed + - optimizequality - sinc - Strikethru - Strikethrough diff --git a/docs/design/canvas-net-pdf/pdf-document.md b/docs/design/canvas-net-pdf/pdf-document.md index a08f30f46..55b95e7f6 100644 --- a/docs/design/canvas-net-pdf/pdf-document.md +++ b/docs/design/canvas-net-pdf/pdf-document.md @@ -93,7 +93,8 @@ supported (an unrecognized base encoding also fails closed); text-rendering mode glyph under a clip mode fails closed); and no additional stream filters were added for any of these phases. **Phase 3 limitations** (narrowed by Phase 7/13 and the `/Pattern` color-space phase, see below): there are no transparency groups, `/Mask` (stencil/color-key) image masks and `/Matte` are not -consulted, and the Phase 3 operator subset is otherwise limited as documented below. These remain +consulted, `/ImageMask` stencil images are not rendered (there is no code path for them, so no +`Nearest` special case applies), and the Phase 3 operator subset is otherwise limited as documented below. These remain out of scope and are silently skipped (any other undefined keyword) or explicitly rejected (unsupported color spaces/filters/fonts/encodings/render modes), per the operator/exception taxonomy documented below. Since then the following have been added: shading/tiling pattern fills @@ -783,9 +784,8 @@ its own distinguishable `Feature` token. specification's image-space convention, the opposite of user-space's y-up convention). A rotated or skewed placement falls back to inverse-mapped bilinear sampling of an area-prefiltered source (`Prefilter` + `SampleBilinear`). Thin features such as one-pixel rules are therefore attenuated - rather than dropped, and enlarged images are interpolated rather than shown as blocks. `/ImageMask` - stencil images are not rendered by this package (there is no code path for them), so no `Nearest` special - case applies. `/Interpolate` is not consulted. + rather than dropped, and enlarged images are interpolated rather than shown as blocks. + `/Interpolate` is not consulted. Each sampled source pixel is alpha-blended "over" the existing destination pixel via the shared internal `Canvas.Rgba32.CompositeOver(Rgba32, Rgba32)` helper (standard Porter-Duff "over" alpha compositing — straight/unassociated alpha in and out, diff --git a/docs/design/canvas-net-pptx/pptx-document.md b/docs/design/canvas-net-pptx/pptx-document.md index c47d411b1..734d71b95 100644 --- a/docs/design/canvas-net-pptx/pptx-document.md +++ b/docs/design/canvas-net-pptx/pptx-document.md @@ -852,7 +852,9 @@ resolves a `` shape's `/` into a decoded core `Surfac `SurfaceResampler.TryResampleToDevice` (shared separable engine: `Area` when shrinking, `Bicubic` when enlarging) and composites the resulting device window 1:1. The `srcRect` crop is isolated first: the smallest whole-pixel window of the source containing the crop is cut out (`Surface.Crop`), so kernel taps next to a - crop edge fold into the window's own edge pixels and pixels outside the crop never bleed into it; the + crop edge fold into the window's own edge pixels and pixels outside the window never bleed into it. The + window is a whole-pixel superset of the (possibly fractional) crop, so a partially covered border pixel + still contributes to the crop edge; the fractional crop offset is part of the mapping. A rotated picture inverts the matrix once and bilinear-samples an area-prefiltered copy of the same cropped window per destination pixel whose inverse-mapped coordinate falls within `[0,1]x[0,1]`. Each sampled source pixel is diff --git a/docs/design/canvas-net-svg/svg-codec.md b/docs/design/canvas-net-svg/svg-codec.md index 79c8f76cb..2149bf468 100644 --- a/docs/design/canvas-net-svg/svg-codec.md +++ b/docs/design/canvas-net-svg/svg-codec.md @@ -1180,7 +1180,9 @@ the decoded image's own pixel space and resampled through the shared engine (`Su `Bicubic` when enlarging) for axis-aligned placements, with an inverse-mapped bilinear fallback on a prefiltered source for rotated or skewed ones; the `image-rendering` property (attribute, style declaration or stylesheet, inherited) set to `pixelated`, `crisp-edges` or `optimizeSpeed` selects -`Nearest` instead (`feImage` always smooths) - a pixel whose inverse-transformed coordinate falls +`Nearest` instead, while `auto`, `optimizeQuality`, `smooth` and `high-quality` select smooth +resampling and any other (unrecognized) value is ignored, so the element inherits its parent's +setting (`feImage` always smooths) - a pixel whose inverse-transformed coordinate falls outside the decoded image's own `[0, width) x [0, height)` extent (possible under a `slice` fit, or simply near the fit rect's own edges) is left untouched rather than wrapped, unlike `pattern`'s own deliberate wrap-around tiling. The result is composited onto the real canvas via diff --git a/docs/reqstream/canvas-net-pptx/pptx-document.yaml b/docs/reqstream/canvas-net-pptx/pptx-document.yaml index dea1d28c2..85ec8710d 100644 --- a/docs/reqstream/canvas-net-pptx/pptx-document.yaml +++ b/docs/reqstream/canvas-net-pptx/pptx-document.yaml @@ -2246,3 +2246,4 @@ sections: - PaintPicture_EnlargedPicture_IsSmooth - PaintPicture_EnlargedCrop_DoesNotBleedPixelsOutsideCrop - PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop + - PaintPicture_FractionalCrop_PartiallyCoveredBorderPixelContributes diff --git a/docs/reqstream/canvas-net-svg/svg-codec.yaml b/docs/reqstream/canvas-net-svg/svg-codec.yaml index 104b58ea0..fa851e043 100644 --- a/docs/reqstream/canvas-net-svg/svg-codec.yaml +++ b/docs/reqstream/canvas-net-svg/svg-codec.yaml @@ -1469,6 +1469,9 @@ sections: - Image_RenderingStyle_IsNearest - Image_RenderingStylesheet_IsNearest - Image_Shrunk_KeepsOnePixelLine + - Image_RenderingInheritedFromGroup_IsNearest + - Image_RenderingBogus_InheritsPixelatedFromParent + - Image_RenderingSmoothKeyword_OverridesPixelatedParent - id: CanvasNetSvg-SvgCodec-PatternTileSmoothing title: >- diff --git a/docs/reqstream/canvas-net/canvas/surface.yaml b/docs/reqstream/canvas-net/canvas/surface.yaml index 55649b907..01f0ede00 100644 --- a/docs/reqstream/canvas-net/canvas/surface.yaml +++ b/docs/reqstream/canvas-net/canvas/surface.yaml @@ -471,9 +471,12 @@ sections: The Surface class shall resample with working memory bounded independently of the extreme aspect ratio of the image. justification: | - Resizing an 8192 by 1 image to 1 by 8192 must not allocate an unbounded intermediate buffer. + Resizing an 8192 by 1 image to 1 by 8192 must not allocate an unbounded intermediate buffer; + the engine processes the image in strips sized by an intermediate-buffer budget, and a tiny + budget must give output identical to the default. tests: - - Resize_LargeAndWide_ProducesExpectedShape + - Resize_ExtremeAspectChange_ProducesExpectedShape + - Resample_TinyIntermediateBudget_MatchesDefaultBudget - id: CanvasNet-Canvas-Surface-ResizeToFit title: >- @@ -504,6 +507,8 @@ sections: - TryResampleToDevice_AxisAligned_ReturnsWindowAtOrigin - TryResampleToDevice_OffScreen_ReturnsTrueWithNullWindow - BoxReduce_MatchesAreaResize + - BoxReduce_NonDivisibleSize_AveragesOnlyCoveredPixelsInPartialBlock + - BoxReduce_NonDivisibleSizeWithAlpha_PartialBlockUsesCoveredPixelsOnly - id: CanvasNet-Canvas-Surface-WrappedBilinear title: >- diff --git a/docs/reqstream/canvas-net/drawing/tile-paint.yaml b/docs/reqstream/canvas-net/drawing/tile-paint.yaml index d55fe75d7..47c92afbb 100644 --- a/docs/reqstream/canvas-net/drawing/tile-paint.yaml +++ b/docs/reqstream/canvas-net/drawing/tile-paint.yaml @@ -133,3 +133,5 @@ sections: - EvaluateRow_MagnifiedTile_IsSmooth - CreatePlan_OneToOneTile_IsNeitherMagnifiedNorMinified - EvaluateRow_MinifiedTile_AveragesColors + - ClassifyTileScale_MixedAndSingleAxisCases + - CreatePlan_MixedMagnifiedAndMinifiedTile_IsMagnifiedOnly diff --git a/docs/verification/canvas-net-pptx/pptx-document.md b/docs/verification/canvas-net-pptx/pptx-document.md index 69e76c8db..adf76778a 100644 --- a/docs/verification/canvas-net-pptx/pptx-document.md +++ b/docs/verification/canvas-net-pptx/pptx-document.md @@ -1051,13 +1051,15 @@ carrying the `"pptx-image-format"` feature token, and proves null argument valid #### CanvasNetPptx-PptxDocument-PictureSmoothResample: Pictures Are Resampled Smoothly **Tests**: `PaintPicture_EnlargedPicture_IsSmooth`, `PaintPicture_EnlargedCrop_DoesNotBleedPixelsOutsideCrop`, -`PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop` +`PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop`, `PaintPicture_FractionalCrop_PartiallyCoveredBorderPixelContributes` A 2x1 black/white picture painted at 40x4 contains many distinct gray levels instead of two hard blocks. An 8x8 picture with two bright-red left columns and six blue columns, cropped with `srcRect` left = 25 percent and enlarged (axis-aligned) or rotated 90 degrees, paints only pure blue everywhere (the red outside the crop -never reaches the crop edge); an exact-equality assertion is valid here because the crop window is isolated -before resampling. +never reaches the crop edge); an exact-equality assertion is valid here because the window is isolated +before resampling and, for whole-pixel crops, holds only pixels inside the crop. With a fractional crop the +whole-pixel superset window includes the partially covered border pixel, which therefore contributes to the +crop edge (a 4x4 picture with a black first column and a 12.5 percent left crop paints a dark leftmost pixel). #### CanvasNetPptx-PptxDocument-PicturePainting: Picture Compositing Without PDF's Y-Flip diff --git a/docs/verification/canvas-net-svg/svg-codec.md b/docs/verification/canvas-net-svg/svg-codec.md index 8d3b638e2..ccbf32f32 100644 --- a/docs/verification/canvas-net-svg/svg-codec.md +++ b/docs/verification/canvas-net-svg/svg-codec.md @@ -1480,7 +1480,9 @@ rather than throwing or dividing by zero. #### CanvasNetSvg-SvgCodec-ImageSmoothResample: `image` Is Resampled Smoothly, `image-rendering` Selects Nearest **Tests**: `Image_Enlarged_IsSmooth`, `Image_RenderingAttribute_IsNearest`, `Image_RenderingStyle_IsNearest`, -`Image_RenderingStylesheet_IsNearest`, `Image_Shrunk_KeepsOnePixelLine` +`Image_RenderingStylesheet_IsNearest`, `Image_Shrunk_KeepsOnePixelLine`, +`Image_RenderingInheritedFromGroup_IsNearest`, `Image_RenderingBogus_InheritsPixelatedFromParent`, +`Image_RenderingSmoothKeyword_OverridesPixelatedParent` `SvgImageResamplingTests.cs` enlarges a 2x1 black/white image to 40x4: by default the row has many gray levels; with `image-rendering` `pixelated` or `crisp-edges` (attribute, style declaration or diff --git a/docs/verification/canvas-net/canvas/surface.md b/docs/verification/canvas-net/canvas/surface.md index b190c764b..c6cd3c76f 100644 --- a/docs/verification/canvas-net/canvas/surface.md +++ b/docs/verification/canvas-net/canvas/surface.md @@ -451,9 +451,11 @@ reports `mode`; a disposed surface throws `ObjectDisposedException`. ##### CanvasNet-Canvas-Surface-ResizeBoundedMemory: Extreme Aspect Ratios -**Tests**: `Resize_LargeAndWide_ProducesExpectedShape` +**Tests**: `Resize_ExtremeAspectChange_ProducesExpectedShape`, `Resample_TinyIntermediateBudget_MatchesDefaultBudget` -An 8192x1 surface resizes to 1x8192 with the expected content. +An 8192x1 surface resizes to 1x8192 with the expected content. Resampling with intermediate budgets of 1 and +64 bytes (forcing the multi-strip path) produces output identical to the default budget for Bilinear, +Lanczos3 and Area. ##### CanvasNet-Canvas-Surface-ResizeToFit: Aspect-Preserving Fit diff --git a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Elements.cs b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Elements.cs index f88c8a03a..1d6a3243a 100644 --- a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Elements.cs +++ b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Elements.cs @@ -662,13 +662,14 @@ _ when string.Equals(dashArrayAttr.Trim(), "none", StringComparison.OrdinalIgnor /// The raw value, or if absent. /// /// for pixelated/crisp-edges/optimizeSpeed, - /// for any other recognized keyword, if absent (inherit). + /// for auto/optimizeQuality/smooth/high-quality, + /// if absent or unrecognized (ignored, inherit). /// private static bool? ParseImageRendering(string? raw) => raw?.Trim().ToLowerInvariant() switch { - null => null, "pixelated" or "crisp-edges" or "optimizespeed" => true, - _ => false + "auto" or "optimizequality" or "smooth" or "high-quality" => false, + _ => null }; /// Parses a fill-rule/clip-rule-style keyword. diff --git a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs index 36a9305f9..678f385bf 100644 --- a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs +++ b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs @@ -549,19 +549,9 @@ internal static Surface SampleTileIntoRegion( { var deviceX = Math.Sqrt(((double)gridToPixel.M11 * gridToPixel.M11) + ((double)gridToPixel.M12 * gridToPixel.M12)) * tileWidth / tileBuffer.Width; var deviceY = Math.Sqrt(((double)gridToPixel.M21 * gridToPixel.M21) + ((double)gridToPixel.M22 * gridToPixel.M22)) * tileHeight / tileBuffer.Height; - if (double.IsFinite(deviceX) && double.IsFinite(deviceY) && deviceX > 0 && deviceY > 0) + if (SurfaceResampler.ClassifyTileScale(deviceX, deviceY, tileBuffer.Width, tileBuffer.Height, out magnified, out var reducedWidth, out var reducedHeight)) { - if (deviceX > 1.05 || deviceY > 1.05) - { - magnified = true; - } - else if (deviceX < 0.95 || deviceY < 0.95) - { - minified = tileBuffer.Resize( - deviceX < 0.95 ? Math.Max(1, (int)Math.Round(tileBuffer.Width * deviceX)) : tileBuffer.Width, - deviceY < 0.95 ? Math.Max(1, (int)Math.Round(tileBuffer.Height * deviceY)) : tileBuffer.Height, - ResamplingMode.Area); - } + minified = tileBuffer.Resize(reducedWidth, reducedHeight, ResamplingMode.Area); } } diff --git a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs index 07414a1ec..7e490072c 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs @@ -277,6 +277,12 @@ private static AxisWeights BuildAxis(int sourceSize, double start, double extent w.Clear(); for (var i = los[o]; i <= his[o]; i++) { + // Area drops out-of-image taps (renormalized below); other filters fold them into the edge pixel + if (mode == ResamplingMode.Area && (i < 0 || i > last)) + { + continue; + } + var index = (int)Math.Clamp(i, 0, last); w[index - first] += Weight(mode, i + 0.5 - c, scale); } @@ -335,6 +341,66 @@ private static double Weight(ResamplingMode mode, double distance, double scale) }; } + /// Device pixels per tile pixel above which a tile is considered magnified (smoothed). + private const double TileMagnifiedThreshold = 1.05; + + /// Device pixels per tile pixel below which a tile is considered minified (prefiltered). + private const double TileMinifiedThreshold = 0.95; + + /// + /// Classifies the device scale of one tile pixel. Magnification on either axis wins + /// (the whole tile is then sampled bilinearly, no prefilter); otherwise, when either axis is + /// minified, only the minified axes are reduced (the other keeps its size). + /// + /// Device pixels per tile pixel along x. + /// Device pixels per tile pixel along y. + /// Tile buffer width in pixels. + /// Tile buffer height in pixels. + /// Receives when the tile should be sampled bilinearly. + /// Receives the prefiltered width when minified. + /// Receives the prefiltered height when minified. + /// when the tile should be prefiltered to the reduced size. + internal static bool ClassifyTileScale( + double deviceX, + double deviceY, + int tileWidth, + int tileHeight, + out bool magnified, + out int reducedWidth, + out int reducedHeight) + { + magnified = false; + reducedWidth = tileWidth; + reducedHeight = tileHeight; + if (!double.IsFinite(deviceX) || !double.IsFinite(deviceY) || deviceX <= 0 || deviceY <= 0) + { + return false; + } + + if (deviceX > TileMagnifiedThreshold || deviceY > TileMagnifiedThreshold) + { + magnified = true; + return false; + } + + if (deviceX >= TileMinifiedThreshold && deviceY >= TileMinifiedThreshold) + { + return false; + } + + if (deviceX < TileMinifiedThreshold) + { + reducedWidth = Math.Max(1, (int)Math.Round(tileWidth * deviceX)); + } + + if (deviceY < TileMinifiedThreshold) + { + reducedHeight = Math.Max(1, (int)Math.Round(tileHeight * deviceY)); + } + + return true; + } + /// The Catmull-Rom cubic kernel (support two) at non-negative distance . private static double CatmullRom(double x) { diff --git a/src/DemaConsulting.CanvasNet/Drawing/TilePaintEvaluator.cs b/src/DemaConsulting.CanvasNet/Drawing/TilePaintEvaluator.cs index 402a11f26..2098a876d 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/TilePaintEvaluator.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/TilePaintEvaluator.cs @@ -90,16 +90,6 @@ internal readonly record struct TilePaintPlan public void Release() => Minified?.Dispose(); } - /// - /// Device pixels per tile pixel above which the tile is considered magnified (smoothed). - /// - private const double MagnifiedThreshold = 1.05; - - /// - /// Device pixels per tile pixel below which the tile is considered minified (prefiltered). - /// - private const double MinifiedThreshold = 0.95; - /// /// Computes every per- (never per-point) quantity once, for reuse /// across an entire fill operation (every row of a tile @@ -130,18 +120,9 @@ internal static TilePaintPlan CreatePlan(TilePaint tile) var deviceY = Math.Sqrt(((double)m.M21 * m.M21) + ((double)m.M22 * m.M22)) / tilePixelsPerUnitY; Surface? minified = null; var magnified = false; - if (double.IsFinite(deviceX) && double.IsFinite(deviceY) && deviceX > 0 && deviceY > 0) + if (SurfaceResampler.ClassifyTileScale(deviceX, deviceY, surface.Width, surface.Height, out magnified, out var width, out var height)) { - if (deviceX > MagnifiedThreshold || deviceY > MagnifiedThreshold) - { - magnified = true; - } - else if (deviceX < MinifiedThreshold || deviceY < MinifiedThreshold) - { - var width = deviceX < MinifiedThreshold ? Math.Max(1, (int)Math.Round(surface.Width * deviceX)) : surface.Width; - var height = deviceY < MinifiedThreshold ? Math.Max(1, (int)Math.Round(surface.Height * deviceY)) : surface.Height; - minified = surface.Resize(width, height, ResamplingMode.Area); - } + minified = surface.Resize(width, height, ResamplingMode.Area); } return new TilePaintPlan diff --git a/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs b/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs index b76a233e5..71c68c10e 100644 --- a/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs +++ b/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs @@ -149,6 +149,7 @@ public void PaintPicture_EnlargedPicture_IsSmooth() Assert.True(distinct.Count > 8); } + /// Proves an identity-transformed, uncropped picture paints the source image's pixels at the expected destination location, left-to-right unflipped. [Fact] public void PaintPicture_IdentityTransformNoCrop_PaintsImagePixelsUnflipped() @@ -223,6 +224,28 @@ public void PaintPicture_EnlargedCrop_DoesNotBleedPixelsOutsideCrop() } } + /// Proves a fractional crop uses the whole-pixel superset window: a partially covered border pixel still contributes to the crop edge. + [Fact] + public void PaintPicture_FractionalCrop_PartiallyCoveredBorderPixelContributes() + { + // 4x4 image: column 0 black, the rest white; crop left = 12.5 percent (half of column 0 remains) + using var image = new Surface(4, 4); + image.Clear(new Rgba32(255, 255, 255, 255)); + for (var y = 0; y < 4; y++) + { + image[0, y] = new Rgba32(0, 0, 0, 255); + } + + using var surface = new Surface(40, 4); + var srcRect = new PptxSrcRect(Left: 0.125f, Top: 0f, Right: 0f, Bottom: 0f); + + PptxDocument.PaintPicture(surface, image, srcRect, Matrix3x2.Identity, widthEmu: 40f, heightEmu: 4f); + + // The leftmost painted pixel is dominated by the half-covered black column, the far right is white + Assert.InRange(surface[0, 2].R, 0, 127); + Assert.Equal(255, surface[39, 2].R); + } + /// Proves the crop also does not bleed for a rotated picture (inverse-mapped bilinear path). [Fact] public void PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop() diff --git a/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs b/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs index 54cdf060b..395eac4b4 100644 --- a/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs +++ b/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs @@ -91,6 +91,42 @@ public void Image_Shrunk_KeepsOnePixelLine() } Assert.InRange(ink, 255 * 0.17 * 0.8, 255 * 0.17 * 1.2 + 1); + } + + /// Renders the enlarged image inside a group with the given group attributes and image attributes. + private static Surface RenderInGroup(string groupAttributes, string imageAttributes) + { + var svg = $"" + + $""; + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(svg)); + return SvgCodec.Load(stream, 40, 4); + } + /// image-rendering is inherited from a parent group. + [Fact] + public void Image_RenderingInheritedFromGroup_IsNearest() + { + using var surface = RenderInGroup("image-rendering='pixelated'", string.Empty); + Assert.True(DistinctLevels(surface) <= 2); + } + + /// An unrecognized image-rendering value is ignored and the parent's pixelated value is inherited. + [Fact] + public void Image_RenderingBogus_InheritsPixelatedFromParent() + { + using var surface = RenderInGroup("image-rendering='pixelated'", "image-rendering='bogus'"); + Assert.True(DistinctLevels(surface) <= 2); + } + + /// An explicit smooth keyword overrides a pixelated parent. + [Theory] + [InlineData("auto")] + [InlineData("optimizeQuality")] + [InlineData("smooth")] + [InlineData("high-quality")] + public void Image_RenderingSmoothKeyword_OverridesPixelatedParent(string value) + { + using var surface = RenderInGroup("image-rendering='pixelated'", $"image-rendering='{value}'"); + Assert.True(DistinctLevels(surface) > 8); } } diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs index cb1be5cfc..5aaad864b 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs @@ -173,6 +173,7 @@ public void SampleBilinear_CentreAndMidpoint_InterpolatesAndClampsEdges() Assert.Equal(new Rgba32(0, 0, 0, 255), SurfaceResampler.SampleBilinear(image, 0f, 0f)); Assert.Equal(new Rgba32(200, 100, 50, 255), SurfaceResampler.SampleBilinear(image, 0.999f, 0.999f)); } + /// Rotation or skew is rejected so callers use the inverse-mapped fallback. [Fact] public void TryResampleToDevice_RotatedMatrix_ReturnsFalse() @@ -208,6 +209,72 @@ public void TryResampleToDevice_OffScreen_ReturnsTrueWithNullWindow() Assert.Null(window); } + /// BoxReduce renormalizes partial edge blocks: a 10x1 ramp reduced by 4 ends with the mean of the two covered pixels, not an edge-folded value. + [Fact] + public void BoxReduce_NonDivisibleSize_AveragesOnlyCoveredPixelsInPartialBlock() + { + using var source = new Surface(10, 1); + for (var x = 0; x < 10; x++) + { + var v = (byte)(x * 20); + source[x, 0] = new Rgba32(v, v, v, 255); + } + + using var reduced = SurfaceResampler.BoxReduce(source, 4, 1); + Assert.Equal(3, reduced.Width); + Assert.Equal(30, reduced[0, 0].R); + Assert.Equal(110, reduced[1, 0].R); + Assert.Equal(170, reduced[2, 0].R); // (160 + 180) / 2 + } + + /// BoxReduce of a non-divisible size with alpha averages premultiplied color over the covered pixels only. + [Fact] + public void BoxReduce_NonDivisibleSizeWithAlpha_PartialBlockUsesCoveredPixelsOnly() + { + using var source = new Surface(3, 1); + source[0, 0] = new Rgba32(0, 0, 0, 0); + source[1, 0] = new Rgba32(0, 0, 0, 0); + source[2, 0] = new Rgba32(200, 100, 50, 255); + + using var reduced = SurfaceResampler.BoxReduce(source, 2, 1); + Assert.Equal(2, reduced.Width); + Assert.Equal(new Rgba32(0, 0, 0, 0), reduced[0, 0]); + Assert.Equal(new Rgba32(200, 100, 50, 255), reduced[1, 0]); // the partial block covers only the opaque pixel + } + + /// A tiny intermediate budget (multi-strip path) gives output identical to the default budget. + [Theory] + [InlineData(ResamplingMode.Bilinear, 1)] + [InlineData(ResamplingMode.Bilinear, 64)] + [InlineData(ResamplingMode.Lanczos3, 1)] + [InlineData(ResamplingMode.Lanczos3, 64)] + [InlineData(ResamplingMode.Area, 1)] + [InlineData(ResamplingMode.Area, 64)] + public void Resample_TinyIntermediateBudget_MatchesDefaultBudget(ResamplingMode mode, int budget) + { + using var source = new Surface(23, 19); + for (var y = 0; y < 19; y++) + { + for (var x = 0; x < 23; x++) + { + source[x, y] = new Rgba32((byte)((x * 11) + y), (byte)(y * 13), (byte)((x * y) & 255), (byte)(255 - ((x + y) % 5 * 20))); + } + } + + foreach (var (w, h) in new[] { (9, 7), (40, 31) }) + { + using var expected = SurfaceResampler.Resample(source, 0, 23, 0, 19, w, h, mode); + using var actual = SurfaceResampler.Resample(source, 0, 23, 0, 19, w, h, mode, budget); + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + Assert.Equal(expected[x, y], actual[x, y]); + } + } + } + } + /// BoxReduce matches an explicit Area resize. [Fact] public void BoxReduce_MatchesAreaResize() diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs index f5e1ca32c..2723f5661 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs @@ -66,7 +66,7 @@ public void Resize_Area_IntegerReduction_AveragesBlocks() Assert.InRange(reds[1], 119, 121); } - /// Bicubic and Lanczos3 keep source values at the pixel centers of an exact 2x enlargement's constant regions and never leave the byte range. + /// Bicubic and Lanczos3 keep the flat regions of a step edge at their exact values and never leave the byte range (overshoot is clamped). [Theory] [InlineData(ResamplingMode.Bicubic)] [InlineData(ResamplingMode.Lanczos3)] @@ -216,7 +216,7 @@ public void Resize_Auto_ChoosesPerAxis() { for (var x = 0; x < 4; x++) { - source[x, y] = new Rgba32((byte)(x * 60), (byte)(x * 60), (byte)(x * 60), 255); + source[x, y] = new Rgba32((byte)(x * 60), (byte)(y * 100), (byte)(x * 60), 255); } } @@ -225,6 +225,11 @@ public void Resize_Auto_ChoosesPerAxis() Assert.Equal(2, auto.Width); Assert.Equal(4, auto.Height); + // The enlarged (y) axis interpolates the two source rows smoothly: strictly between them, increasing + Assert.True(auto[0, 0].G < auto[0, 1].G && auto[0, 1].G < auto[0, 2].G && auto[0, 2].G < auto[0, 3].G); + Assert.InRange(auto[0, 0].G, 0, 40); + Assert.InRange(auto[0, 3].G, 60, 120); + // The shrunken axis averages pairs: (0+60)/2 and (120+180)/2 Assert.InRange(auto[0, 1].R, 29, 31); Assert.InRange(auto[1, 1].R, 149, 151); @@ -232,9 +237,9 @@ public void Resize_Auto_ChoosesPerAxis() Assert.Equal(explicitArea[0, 0], autoSame[0, 0]); } - /// The extreme 8192x1 to 1x8192 resize works within bounded memory. + /// Resizing an extremely wide 8192x1 image to 1x8192 yields the expected shape and content. [Fact] - public void Resize_LargeAndWide_ProducesExpectedShape() + public void Resize_ExtremeAspectChange_ProducesExpectedShape() { using var wide = new Surface(8192, 1); wide.Clear(new Rgba32(10, 20, 30, 255)); diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/TilePaintEvaluatorTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/TilePaintEvaluatorTests.cs index c655b1836..14353cc33 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/TilePaintEvaluatorTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/TilePaintEvaluatorTests.cs @@ -53,6 +53,8 @@ public void EvaluateRow_NonInvertibleTransform_WritesFullyTransparentRow() { Assert.Equal(default, pixel); } + + plan.Release(); } /// @@ -71,6 +73,7 @@ public void EvaluateRow_IdentityTransform_SamplesExpectedTilePixels() Assert.Equal(new Rgba32(255, 0, 0, 255), destination[0]); Assert.Equal(new Rgba32(0, 0, 255, 255), destination[1]); + plan.Release(); } /// @@ -91,6 +94,7 @@ public void EvaluateRow_WrapAroundBeyondOneTile_MatchesFirstTileRepetition() Assert.Equal(destination[0], destination[2]); // Columns 1 and 3 both sample pattern-space x in [1,2) -> same wrapped tile pixel. Assert.Equal(destination[1], destination[3]); + plan.Release(); } /// @@ -114,7 +118,10 @@ public void EvaluateRow_NegativeSteps_SamplesUsingAbsoluteValueWraparound() Assert.Equal(positiveRow[0], negativeRow[0]); Assert.Equal(positiveRow[1], negativeRow[1]); + positivePlan.Release(); + negativePlan.Release(); } + /// A tile enlarged 4x is smoothly interpolated instead of showing hard blocks. [Fact] public void EvaluateRow_MagnifiedTile_IsSmooth() @@ -141,6 +148,43 @@ public void EvaluateRow_MagnifiedTile_IsSmooth() } } + /// Tile scale classification is shared: magnification on either axis wins (mixed case), otherwise only minified axes are reduced. + [Fact] + public void ClassifyTileScale_MixedAndSingleAxisCases() + { + // Mixed: one axis magnified, the other minified -> magnified, no prefilter + Assert.False(SurfaceResampler.ClassifyTileScale(2.0, 0.5, 8, 8, out var magnified, out _, out _)); + Assert.True(magnified); + + // Minified on one axis only: only that axis is reduced + Assert.True(SurfaceResampler.ClassifyTileScale(0.5, 1.0, 8, 8, out magnified, out var w, out var h)); + Assert.False(magnified); + Assert.Equal((4, 8), (w, h)); + + // Near 1:1 and non-finite/degenerate scales are left untouched + Assert.False(SurfaceResampler.ClassifyTileScale(1.04, 0.96, 8, 8, out magnified, out _, out _)); + Assert.False(magnified); + Assert.False(SurfaceResampler.ClassifyTileScale(double.NaN, 0.5, 8, 8, out magnified, out _, out _)); + Assert.False(magnified); + } + + /// A mixed magnified/minified tile is sampled bilinearly without a prefiltered copy. + [Fact] + public void CreatePlan_MixedMagnifiedAndMinifiedTile_IsMagnifiedOnly() + { + using var tileSurface = CreateCheckerboardTileSurface(); + var plan = TilePaintEvaluator.CreatePlan(new TilePaint(tileSurface, Matrix3x2.CreateScale(4f, 0.25f), 2f, 2f)); + try + { + Assert.True(plan.Magnified); + Assert.Null(plan.Minified); + } + finally + { + plan.Release(); + } + } + /// A tile at exactly one device pixel per tile pixel keeps exact pixel values. [Fact] public void CreatePlan_OneToOneTile_IsNeitherMagnifiedNorMinified() From 12716ad9a52c75a22a6f7e692ea74e35f0921209 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 11:17:47 -0400 Subject: [PATCH 05/16] Optimize rasterizer sweep, composite workspace reuse, glyph outline cache and resampler allocations Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .cspell.yaml | 1 + .reviewmark.yaml | 1 + docs/design/canvas-net-pdf/pdf-document.md | 3 + docs/design/canvas-net/canvas/surface.md | 26 +- docs/design/canvas-net/drawing/path-filler.md | 18 +- .../design/canvas-net/fonts/true-type-font.md | 9 + docs/design/canvas-net/geometry/path.md | 2 + docs/reqstream/canvas-net-pdf.yaml | 1 + .../canvas-net-pdf/pdf-document.yaml | 14 + docs/reqstream/canvas-net/canvas.yaml | 2 + docs/reqstream/canvas-net/canvas/surface.yaml | 28 ++ docs/reqstream/canvas-net/drawing.yaml | 1 + .../canvas-net/drawing/path-filler.yaml | 18 ++ docs/reqstream/canvas-net/fonts.yaml | 1 + .../canvas-net/fonts/true-type-font.yaml | 13 + docs/reqstream/canvas-net/geometry/path.yaml | 1 + .../canvas-net-pdf/pdf-document.md | 10 + .../verification/canvas-net/canvas/surface.md | 20 ++ .../canvas-net/drawing/path-filler.md | 18 ++ .../canvas-net/fonts/true-type-font.md | 9 + docs/verification/canvas-net/geometry/path.md | 7 +- .../PdfDocument.Color.cs | 18 +- .../PdfDocument.Images.cs | 6 +- .../Canvas/Surface.cs | 68 +++++ .../Canvas/SurfaceResampler.Engine.cs | 63 ++-- .../Drawing/ScanlineRasterizer.cs | 156 +++++++--- .../Fonts/TrueTypeFont.cs | 31 +- .../Geometry/PathBuilder.cs | 7 +- .../PdfDocumentImageColorConversionTests.cs | 119 ++++++++ .../Canvas/SurfaceResamplerTests.cs | 39 +++ .../Canvas/SurfaceTests.cs | 79 +++++ .../Drawing/ScanlineRasterizerTests.cs | 285 ++++++++++++++++++ .../Fonts/TrueTypeFontTests.cs | 60 ++++ .../Geometry/PathBuilderTests.cs | 42 +++ 34 files changed, 1096 insertions(+), 80 deletions(-) create mode 100644 test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageColorConversionTests.cs diff --git a/.cspell.yaml b/.cspell.yaml index db367cb7d..c2c4ace72 100644 --- a/.cspell.yaml +++ b/.cspell.yaml @@ -17,6 +17,7 @@ words: - Cmaps - subtables - bilinearly + - stackalloc - prefilter - prefiltered - resampler diff --git a/.reviewmark.yaml b/.reviewmark.yaml index c064cc2c5..eb2eb88cd 100644 --- a/.reviewmark.yaml +++ b/.reviewmark.yaml @@ -807,6 +807,7 @@ reviews: - "test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentJpxTests.cs" # JPXDecode/SMask unit tests - "test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentThinRuleInkTests.cs" # thin-rule ink unit tests - "test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageDownscaleTests.cs" # image downscale unit tests + - "test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageColorConversionTests.cs" # image color tests - "test/DemaConsulting.CanvasNet.Pdf.Tests/PdfImageResamplingTests.cs" # image resampling grid unit tests - "test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentHairlineStrokeTests.cs" # hairline stroke unit tests - "test/DemaConsulting.CanvasNet.Tests/Jpeg2000Fixtures/gray.jp2" # gray JPX fixture diff --git a/docs/design/canvas-net-pdf/pdf-document.md b/docs/design/canvas-net-pdf/pdf-document.md index 55b95e7f6..ccd49cdc3 100644 --- a/docs/design/canvas-net-pdf/pdf-document.md +++ b/docs/design/canvas-net-pdf/pdf-document.md @@ -673,6 +673,9 @@ its own distinguishable `Feature` token. number, resolves `lookup` (a PDF string's raw bytes, or a stream decoded via `GetStreamDecodedBytes`), and validates the resolved palette has at least `(Hival + 1) * ComponentCount(baseSpace)` bytes (else `InvalidDataException` in each case). + Image samples are converted without a per-pixel array: `SamplesToColor` and `IndexedToColor` + place the (at most four) components in a `stackalloc` span and call + `ColorFromComponentSpan`, which applies the same conversion as the `IReadOnlyList` overload. `ComponentCount` reports `1` for `Indexed` (the palette index itself); `ColorFromComponents` dispatches an `Indexed` color's single raw (not `[0, 1]`-normalized) index component to `IndexedToColor`, which rounds/clamps the index into `[0, Hival]` (an out-of-range index diff --git a/docs/design/canvas-net/canvas/surface.md b/docs/design/canvas-net/canvas/surface.md index d5fc2174b..0b1791b62 100644 --- a/docs/design/canvas-net/canvas/surface.md +++ b/docs/design/canvas-net/canvas/surface.md @@ -453,9 +453,11 @@ the same fixed width. To eliminate this, `Surface` exposes an `internal` nested `CompositeSpanWorkspace` type bundling one reusable set of these scratch buffers, sized once to a caller-chosen capacity, plus an `internal` `CompositeOverSpan(int, int, ReadOnlySpan, Rgba32, CompositeSpanWorkspace)` overload that reuses the supplied workspace's buffers instead of -renting its own. `ScanlineRasterizer.Fill` constructs one `CompositeSpanWorkspace` sized to its -row width before its row loop, reuses it for every row's `CompositeOverSpan` call, and disposes it -once after the loop - so the whole fill rents each scratch buffer exactly once, not once per row. +renting its own. `ScanlineRasterizer.Fill` obtains one `CompositeSpanWorkspace` sized to its +row width (via `CompositeSpanWorkspace.Rent`, see "Per-thread workspace cache" below) before its +row loop, reuses it for every row's `CompositeOverSpan` call, and disposes it exactly once after +the loop - so the whole fill acquires its scratch buffers once, not once per row, and the buffers +may persist in the per-thread cache for later fills. Both overloads share the same private blend body (`CompositeOverSpanCore`); the only difference between them is where their `RowChannelBuffers`/`CompositeWorkBuffers` come from, so the blend math itself is never duplicated. This overload is `internal`, not `public`: it exposes an @@ -474,6 +476,18 @@ versus supplied workspace) differs between the public and internal forms. A dedi (`Surface_CompositeOverSpan_PerPixelColors_MatchesConstantColorOverload_WhenAllColorsEqual`) proves the pre-existing constant-color overload's output is unchanged by this refactor. +**Per-thread workspace cache.** A glyph-heavy page performs thousands of tiny fills, and +renting and returning every scratch array from `ArrayPool` for each one was measurable +overhead. `ScanlineRasterizer.Fill` therefore obtains its workspace from +`CompositeSpanWorkspace.Rent(capacity)`, which hands out the calling thread's cached workspace +when it is large enough (taking it out of the `[ThreadStatic]` slot while in use, so a nested +rent gets a distinct instance) and otherwise creates one of at least 256 pixels. Disposing a +rented workspace whose capacity is at most 16384 pixels returns it to the thread's slot instead +of releasing its arrays; larger or surplus workspaces release their arrays as before. A +workspace created directly with its public constructor is never cached. Trade-off: a cached +workspace keeps the last scratch pixel data in memory (bounded at 16384 pixels per thread) +instead of clearing it on return. + #### Internal image-resampling engine (SurfaceResampler) `Canvas/SurfaceResampler.cs` and `Canvas/SurfaceResampler.Engine.cs` hold an `internal static @@ -490,7 +504,11 @@ axis with scale 1 and an integer start is an exact copy. Work is done in premult separable passes: a horizontal pass over strips of columns into a float intermediate sized by an 8 MiB budget, then a vertical pass using `TensorPrimitives` multiply-add. Results are clamped to `[0, 255]`, un-premultiplied and rounded; all index and size arithmetic uses `long`/checked math, so -the working memory is bounded regardless of aspect ratio (8192x1 to 1x8192 included). +the working memory is bounded regardless of aspect ratio (8192x1 to 1x8192 included). The float +intermediate and accumulator are rented from `ArrayPool.Shared` (returned in `finally`) +and deliberately not cleared: every element read is written first in the same call (the +horizontal pass fills the whole strip, and the first vertical tap overwrites the accumulator), so +output never depends on a buffer's previous contents. **Renderer entry points.** `TryResampleToDevice` resamples a source to the device window covered by an axis-aligned image placement (the window is clipped to the visible area) so the renderer can diff --git a/docs/design/canvas-net/drawing/path-filler.md b/docs/design/canvas-net/drawing/path-filler.md index 4f2fca21c..241e16cb3 100644 --- a/docs/design/canvas-net/drawing/path-filler.md +++ b/docs/design/canvas-net/drawing/path-filler.md @@ -222,12 +222,24 @@ approximation converging only as the sample count grows. per-pixel `float[]` coverage row for the row's clipped `[minX, maxX)` sub-range is composited directly via the internal, workspace-reusing `Surface.CompositeOverSpan(y, minX, coverage, color, workspace)` overload - a single - `Surface.CompositeSpanWorkspace` is constructed once, sized to the row width, before this - method's row loop begins, and reused for every row's composite call, so `CompositeOverSpan`'s - scratch buffers are rented from `ArrayPool.Shared` exactly once per `Fill` call rather than + `Surface.CompositeSpanWorkspace` is rented (`CompositeSpanWorkspace.Rent`) once, sized to the + row width, before this method's row loop begins, and reused for every row's composite call, so + `CompositeOverSpan`'s scratch buffers are acquired exactly once per `Fill` call rather than once per row (see _Surface Unit Design_, `../canvas/surface.md`, for the workspace type itself) - no full-row or full-surface coverage buffer is ever allocated; only the current row's `cover`/`area`/coverage arrays exist at any time. + - **Touched-window trimming (profile-driven optimization)**: `CoverageSweep.MoveNext` does not + yield the full clipped row. For each row, the single-pass path computes the smallest column + range `[lo, hi]` any `RowEdge` can touch (falling back to the full range when an edge + coordinate is non-finite or beyond `TouchedRangeLimit`), clears and sweeps only that range, + fills the constant tail to the right of `hi` with `ResolveCoverage(accumulatedCover)` (no edge + contributes there, so `area` is zero), and finally trims leading and trailing columns whose + resolved coverage is exactly zero. `MoveNext` yields `(y, x, rowCoverage)` for that trimmed + window and skips rows whose window is empty. Zero coverage means "pixel untouched" in + `Surface.CompositeOverSpan`, so the trimmed and skipped columns/rows would not have changed + any pixel; the result is pixel-identical to compositing the full row. The dense clip multiply + (`ApplyClip`) operates on the same window and uses `TensorPrimitives.Multiply`, which is + bit-identical to the scalar float multiply. - **Why this handles crossing/self-intersecting edges correctly, not merely assumed absent**: a prior revision of this algorithm split each row into sub-intervals at every edge's own start/end `y`, sorted the edges spanning each sub-interval by `x` once, and relied on that diff --git a/docs/design/canvas-net/fonts/true-type-font.md b/docs/design/canvas-net/fonts/true-type-font.md index f7af40697..61baa414e 100644 --- a/docs/design/canvas-net/fonts/true-type-font.md +++ b/docs/design/canvas-net/fonts/true-type-font.md @@ -648,6 +648,15 @@ charstring. outside the supported set, is truncated, exceeds the subroutine call depth/step bound, or references an out-of-range subroutine index +**Memoization.** Decoded outlines are cached per font in a `ConcurrentDictionary` (at +most 4096 entries; once full, further glyphs are decoded on demand but not stored). `Path` is +immutable, so every caller shares one instance. A decode that throws is never cached, so a +malformed glyph reports its error on every call. The cache is per `TrueTypeFont` instance and +the PDF renderer builds fonts per render, so it benefits repeated glyphs within one page; +the static fallback-font cache shares one font (hence the thread-safe dictionary). Profiling +showed outline decode and path building at roughly 20% of text-heavy page time; the measured +saving is smaller (about 2 to 6% time, 14 to 28% allocation). + ##### GetAdvanceWidth(int glyphIndex) Validates `glyphIndex`, then returns the glyph's horizontal advance width from `hmtx`, reusing diff --git a/docs/design/canvas-net/geometry/path.md b/docs/design/canvas-net/geometry/path.md index ea5197aa6..b3a82c8aa 100644 --- a/docs/design/canvas-net/geometry/path.md +++ b/docs/design/canvas-net/geometry/path.md @@ -94,6 +94,8 @@ Returns an immutable `Path` snapshot of every subpath recorded so far (including currently-open subpath, if any, uncommitted state included). The builder remains usable afterward: further commands (and further `Build()` calls) do not affect a previously returned `Path`. If no commands have ever been issued, returns a `Path` with zero `Subpaths`. +The builder reuses one scratch list for the current subpath's commands (cleared on each +`MoveTo`); the snapshot copies the commands, so reuse never alters a previously built `Path`. ##### PathBuilder.Clear() diff --git a/docs/reqstream/canvas-net-pdf.yaml b/docs/reqstream/canvas-net-pdf.yaml index 8d1babd8f..282bd07bd 100644 --- a/docs/reqstream/canvas-net-pdf.yaml +++ b/docs/reqstream/canvas-net-pdf.yaml @@ -248,6 +248,7 @@ sections: - CanvasNetPdf-PdfDocument-ImageDecodeArrayInvalid - CanvasNetPdf-PdfDocument-ImageDownscale - CanvasNetPdf-PdfDocument-ImageSmoothResample + - CanvasNetPdf-PdfDocument-ImageColorConversion - CanvasNetPdf-PdfDocument-JpxDecode - CanvasNetPdf-PdfDocument-JpxColorSpace - CanvasNetPdf-PdfDocument-JpxSMaskInData diff --git a/docs/reqstream/canvas-net-pdf/pdf-document.yaml b/docs/reqstream/canvas-net-pdf/pdf-document.yaml index 005adc2a4..86c2a3c07 100644 --- a/docs/reqstream/canvas-net-pdf/pdf-document.yaml +++ b/docs/reqstream/canvas-net-pdf/pdf-document.yaml @@ -2037,6 +2037,20 @@ sections: - Render_ShrunkRotatedImage_KeepsEveryLine - Render_EnlargedImage_IsSmoothlyInterpolated + - id: CanvasNetPdf-PdfDocument-ImageColorConversion + title: >- + The PdfDocument class shall convert decoded raster image samples to pixel colors for + DeviceGray, DeviceRGB, DeviceCMYK and Indexed color spaces exactly as the general + component-list conversion does, without a per-pixel array allocation. + justification: | + Large images convert millions of samples; the allocation-free path must give + pixel-identical output to the original conversion. + tests: + - PdfDocument_ImageColor_DeviceGray_ConvertsEachSampleExactly + - PdfDocument_ImageColor_DeviceRgb_ConvertsEachSampleExactly + - PdfDocument_ImageColor_DeviceCmyk_ConvertsEachSampleExactly + - PdfDocument_ImageColor_Indexed_LooksUpEachPaletteEntryExactly + - id: CanvasNetPdf-PdfDocument-ImageSmoothResample title: >- The PdfDocument class shall resample a raster image placed axis-aligned on the page diff --git a/docs/reqstream/canvas-net/canvas.yaml b/docs/reqstream/canvas-net/canvas.yaml index 9656fcd64..317f750bf 100644 --- a/docs/reqstream/canvas-net/canvas.yaml +++ b/docs/reqstream/canvas-net/canvas.yaml @@ -337,6 +337,7 @@ sections: full-row or full-surface buffer merely to hold mostly-untouched pixels. children: - CanvasNet-Canvas-Surface-CompositeOverSpan + - CanvasNet-Canvas-Surface-SpanWorkspaceCache tests: - Surface_CompositeOverSpan_FullCoverage_MatchesCompositeOverColor - Surface_CompositeOverSpan_ZeroCoverage_LeavesBackgroundUnchanged @@ -407,6 +408,7 @@ sections: - CanvasNet-Canvas-Surface-Resize - CanvasNet-Canvas-Surface-ResizeIdentity - CanvasNet-Canvas-Surface-ResizeBoundedMemory + - CanvasNet-Canvas-Surface-ResizePooledBuffers - CanvasNet-Canvas-Surface-DeviceResample - CanvasNet-Canvas-Surface-WrappedBilinear tests: diff --git a/docs/reqstream/canvas-net/canvas/surface.yaml b/docs/reqstream/canvas-net/canvas/surface.yaml index 01f0ede00..c195c393a 100644 --- a/docs/reqstream/canvas-net/canvas/surface.yaml +++ b/docs/reqstream/canvas-net/canvas/surface.yaml @@ -352,6 +352,23 @@ sections: - Surface_CompositeOverSpan_PerPixelColors_LengthMismatch_ThrowsArgumentException - Surface_CompositeOverSpanWithWorkspace_PerPixelColors_MatchesPublicOverload + - id: CanvasNet-Canvas-Surface-SpanWorkspaceCache + title: >- + The internal CompositeSpanWorkspace shall be obtainable through Rent, which + rejects a non-positive capacity, returns a workspace of at least the requested + capacity, reuses the calling thread's cached workspace after Dispose, never + hands the same instance to two concurrent users on one thread, and composites + identically to a directly constructed workspace. + justification: | + Tiny fills such as glyphs would otherwise pay the cost of renting and returning + every scratch array per fill; a per-thread cache removes that cost, but is only + safe if reuse, isolation, and output equivalence are verified. + tests: + - CompositeSpanWorkspace_Rent_NonPositiveCapacity_ThrowsArgumentOutOfRangeException + - CompositeSpanWorkspace_Rent_AfterDispose_ReusesCachedWorkspaceWithSufficientCapacity + - CompositeSpanWorkspace_Rent_WhileAnotherIsInUse_ReturnsDistinctWorkspace + - CompositeSpanWorkspace_Rent_LargerThanCached_GrowsAndCompositesIdenticallyToConstructedWorkspace + - id: CanvasNet-Canvas-Surface-Disposal title: >- The Surface class shall implement IDisposable, logically releasing its @@ -478,6 +495,17 @@ sections: - Resize_ExtremeAspectChange_ProducesExpectedShape - Resample_TinyIntermediateBudget_MatchesDefaultBudget + - id: CanvasNet-Canvas-Surface-ResizePooledBuffers + title: >- + The Surface resampling engine shall produce output that does not depend on the + prior contents of its recycled intermediate and accumulator buffers. + justification: | + The engine rents its large float scratch buffers from a shared pool without + clearing them to avoid per-call allocation; a call repeated after differently + sized calls must still give identical pixels. + tests: + - Resample_RepeatedAfterDifferentSizes_IsIdenticalDespiteRecycledBuffers + - id: CanvasNet-Canvas-Surface-ResizeToFit title: >- The Surface class shall resize to the largest aspect-preserving size that fits a diff --git a/docs/reqstream/canvas-net/drawing.yaml b/docs/reqstream/canvas-net/drawing.yaml index 9833be5cf..a3564ec67 100644 --- a/docs/reqstream/canvas-net/drawing.yaml +++ b/docs/reqstream/canvas-net/drawing.yaml @@ -38,6 +38,7 @@ sections: - CanvasNet-Drawing-PathFiller-ScanlineDegenerateInputNoOp - CanvasNet-Drawing-PathFiller-ScanlineCrossingEdges - CanvasNet-Drawing-PathFiller-ScanlineEvenOddMultiToggleRow + - CanvasNet-Drawing-PathFiller-ScanlineWindowedCoverage tests: - CanvasNet_SystemIntegration_BuildAndFillTrianglePath_ReturnsExpectedPixels diff --git a/docs/reqstream/canvas-net/drawing/path-filler.yaml b/docs/reqstream/canvas-net/drawing/path-filler.yaml index ecb3d7f5a..63018da46 100644 --- a/docs/reqstream/canvas-net/drawing/path-filler.yaml +++ b/docs/reqstream/canvas-net/drawing/path-filler.yaml @@ -275,6 +275,24 @@ sections: - ScanlineRasterizer_Fill_NoPolygons_NoOp - ScanlineRasterizer_Fill_DegeneratePolygon_ContributesZeroCoverage + - id: CanvasNet-Drawing-PathFiller-ScanlineWindowedCoverage + title: >- + The internal ScanlineRasterizer helper shall yield, for each swept row, only the + window of columns its edges can touch (skipping rows with no coverage), such that + the resulting fill is pixel-identical to compositing the full-width coverage row, + for solid color, gradient, tile, and dense-clip fills. + justification: | + Trimming each row to its touched window and skipping empty rows removes the + clearing, sweeping, and compositing of pixels that cannot change; because zero + coverage leaves a pixel untouched, the optimization is only valid if it is + provably output-neutral, which an exact-area geometric reference and a + full-width composite reference verify. + tests: + - ScanlineRasterizer_AccumulateCoverageMask_Shapes_MatchesExactPixelAreaReference + - ScanlineRasterizer_Fill_Shapes_PixelExactAgainstFullWidthCompositeReference + - ScanlineRasterizer_Fill_DenseClipMask_PixelExactAgainstCoverageTimesClipReference + - ScanlineRasterizer_Fill_ConstantGradientAndTile_PixelExactAgainstSolid + - id: CanvasNet-Drawing-PathFiller-GradientFill title: >- The PathFiller class shall fill a closed path onto a surface with a linear or diff --git a/docs/reqstream/canvas-net/fonts.yaml b/docs/reqstream/canvas-net/fonts.yaml index 5ab178a49..ba7f28d93 100644 --- a/docs/reqstream/canvas-net/fonts.yaml +++ b/docs/reqstream/canvas-net/fonts.yaml @@ -81,6 +81,7 @@ sections: - CanvasNet-Fonts-TrueTypeFont-GlyphOutlineRejectsExcessivePoints - CanvasNet-Fonts-TrueTypeFont-GlyphOutlineRejectsPointMatchedComponent - CanvasNet-Fonts-TrueTypeFont-GlyphOutlineRejectsMalformedGlyphData + - CanvasNet-Fonts-TrueTypeFont-GlyphOutlineMemoized - CanvasNet-Fonts-TrueTypeFont-GlyphIndexValidation tests: - CanvasNet_SystemIntegration_LoadFontAndFillGlyphOutline_ReturnsExpectedPixels diff --git a/docs/reqstream/canvas-net/fonts/true-type-font.yaml b/docs/reqstream/canvas-net/fonts/true-type-font.yaml index 012fc7474..9e0be6d66 100644 --- a/docs/reqstream/canvas-net/fonts/true-type-font.yaml +++ b/docs/reqstream/canvas-net/fonts/true-type-font.yaml @@ -329,6 +329,19 @@ sections: - GlyfLocaReader_Parse_NonMonotonicLocaEntries_ThrowsInvalidDataException - GlyfLocaReader_Parse_TruncatedLoca_ThrowsInvalidDataException + - id: CanvasNet-Fonts-TrueTypeFont-GlyphOutlineMemoized + title: >- + The TrueTypeFont class shall memoize decoded glyph outlines so a repeated request + for the same glyph index returns the same geometry as a fresh decode, and shall + not memoize a glyph that fails to decode. + justification: | + Text repeats glyphs heavily and decoding plus path building is a measurable share + of render time; caching is only safe if the cached outline equals a cold decode + and malformed glyphs keep reporting their error. + tests: + - TrueTypeFont_GetGlyphOutline_RepeatedCalls_ReturnMemoizedOutlineEqualToFreshDecode + - TrueTypeFont_GetGlyphOutline_MalformedGlyph_ThrowsOnEveryCall + - id: CanvasNet-Fonts-TrueTypeFont-GlyphIndexValidation title: >- The TrueTypeFont class shall reject an out-of-range glyph index argument to diff --git a/docs/reqstream/canvas-net/geometry/path.yaml b/docs/reqstream/canvas-net/geometry/path.yaml index 97094cfa7..aea346bd3 100644 --- a/docs/reqstream/canvas-net/geometry/path.yaml +++ b/docs/reqstream/canvas-net/geometry/path.yaml @@ -114,6 +114,7 @@ sections: to trust that the first Path they obtained never changes underneath them. tests: - PathBuilder_Build_ThenMutateBuilder_DoesNotAffectPreviouslyBuiltPath + - PathBuilder_Build_ThenReuseBuilder_EarlierPathsAreUnchanged - id: CanvasNet-Geometry-Path-BuildEmpty title: >- diff --git a/docs/verification/canvas-net-pdf/pdf-document.md b/docs/verification/canvas-net-pdf/pdf-document.md index 7a553b459..4ead51df5 100644 --- a/docs/verification/canvas-net-pdf/pdf-document.md +++ b/docs/verification/canvas-net-pdf/pdf-document.md @@ -1096,6 +1096,16 @@ pixels wide) and requires that no line goes missing and the ink per line tracks > tolerance (2 to 4 levels, from sampling slightly off a source pixel center) and use a larger tolerance > (16 levels) only for the one soft-mask edge-adjacent sample. The expected colors themselves are unchanged. +#### CanvasNetPdf-PdfDocument-ImageColorConversion: Samples Convert Without Per-Pixel Allocation + +**Tests**: `PdfDocument_ImageColor_DeviceGray_ConvertsEachSampleExactly`, +`PdfDocument_ImageColor_DeviceRgb_ConvertsEachSampleExactly`, +`PdfDocument_ImageColor_DeviceCmyk_ConvertsEachSampleExactly`, +`PdfDocument_ImageColor_Indexed_LooksUpEachPaletteEntryExactly` + +`PdfDocumentImageColorConversionTests.cs` draws a 4x1 image 1:1 for each color space and asserts +every output pixel against its hand-computed color. No timing is asserted. + #### CanvasNetPdf-PdfDocument-ImageSmoothResample: Axis-Aligned Images Are Resampled Once Per Draw **Tests**: `Render_GridImage_NoLineMissingAtAnySize`, `Render_ShrunkRotatedImage_KeepsEveryLine` diff --git a/docs/verification/canvas-net/canvas/surface.md b/docs/verification/canvas-net/canvas/surface.md index c6cd3c76f..3ee246ec9 100644 --- a/docs/verification/canvas-net/canvas/surface.md +++ b/docs/verification/canvas-net/canvas/surface.md @@ -389,6 +389,19 @@ through either the public or the internal fill entry point. `CompositeOver(Surface)` additionally rejects a disposed `foreground` argument, even when this surface itself has not been disposed. +##### CanvasNet-Canvas-Surface-SpanWorkspaceCache: Rented Workspaces Are Reused, Isolated, and Equivalent + +**Tests**: `CompositeSpanWorkspace_Rent_NonPositiveCapacity_ThrowsArgumentOutOfRangeException`, +`CompositeSpanWorkspace_Rent_AfterDispose_ReusesCachedWorkspaceWithSufficientCapacity`, +`CompositeSpanWorkspace_Rent_WhileAnotherIsInUse_ReturnsDistinctWorkspace`, +`CompositeSpanWorkspace_Rent_LargerThanCached_GrowsAndCompositesIdenticallyToConstructedWorkspace` + +Asserts `Rent` rejects zero and negative capacities; that renting, disposing, and renting again +on the same thread returns the same instance with sufficient capacity; that two workspaces held +at once are distinct; and that a workspace rented larger than the cached one (8000 pixels versus +the 256-pixel minimum) composites a coverage pattern byte-identically to a directly constructed +workspace. No test asserts timing. + ##### CanvasNet-Canvas-Surface-ImageResampling: Box Prefilter Behaves as Documented **Tests**: `Prefilter_UpscaleOrIdentity_ReturnsSourceUnchanged`, @@ -457,6 +470,13 @@ An 8192x1 surface resizes to 1x8192 with the expected content. Resampling with i 64 bytes (forcing the multi-strip path) produces output identical to the default budget for Bilinear, Lanczos3 and Area. +##### CanvasNet-Canvas-Surface-ResizePooledBuffers: Recycled Scratch Buffers Do Not Leak State + +**Tests**: `Resample_RepeatedAfterDifferentSizes_IsIdenticalDespiteRecycledBuffers` + +Resamples a 37x29 source to 11x8, then to a larger and a mid-sized target (leaving stale data in +pooled buffers), then to 11x8 again for Area, Bicubic and Lanczos3, and asserts the pixels are identical. + ##### CanvasNet-Canvas-Surface-ResizeToFit: Aspect-Preserving Fit **Tests**: `ResizeToFit_KeepsAspectAndFitsBox`, `ResizeToFit_VeryElongated_ClampsToOnePixel` diff --git a/docs/verification/canvas-net/drawing/path-filler.md b/docs/verification/canvas-net/drawing/path-filler.md index d9fd43541..4f1664787 100644 --- a/docs/verification/canvas-net/drawing/path-filler.md +++ b/docs/verification/canvas-net/drawing/path-filler.md @@ -280,6 +280,24 @@ Calls `ScanlineRasterizer.Fill` with an empty polygon list, and separately with reduced to two points (fewer than the edges needed to enclose any area), and asserts the surface remains completely unmodified in both cases, without throwing. +##### CanvasNet-Drawing-PathFiller-ScanlineWindowedCoverage: Windowed Row Coverage Is Pixel-Identical to Full-Width Coverage + +**Tests**: `ScanlineRasterizer_AccumulateCoverageMask_Shapes_MatchesExactPixelAreaReference`, +`ScanlineRasterizer_Fill_Shapes_PixelExactAgainstFullWidthCompositeReference`, +`ScanlineRasterizer_Fill_DenseClipMask_PixelExactAgainstCoverageTimesClipReference`, +`ScanlineRasterizer_Fill_ConstantGradientAndTile_PixelExactAgainstSolid` + +Each is a theory over seven shapes (rectangle, triangle, slanted parallelogram, shape with a +counter-wound hole, a tiny sparse shape in the far corner, a full-surface rectangle, and a shape +entirely outside the surface). The first checks the swept coverage against an independent exact +pixel-area reference (Sutherland-Hodgman clipping plus the shoelace formula) to a tolerance of +`1e-4`. The second fills a background mixing opaque, semi-transparent, and transparent pixels and +asserts byte equality against compositing the zero-padded full-width coverage rows with the +public span API. The third does the same through a dense clip mask, allowing one byte of +difference per channel for float rounding of the geometric versus multiplied clip. The fourth +asserts gradient and tile fills with a constant color source are byte-identical to the solid fill. +No test asserts timing. + ##### CanvasNet-Drawing-PathFiller-GradientFill: Gradient Fill Shares Flattening/Clipping/Fill-Rule Behavior **Tests**: `PathFiller_Fill_Gradient_HorizontalRectangleWithHorizontalLinearGradient_VariesLeftToRight`, diff --git a/docs/verification/canvas-net/fonts/true-type-font.md b/docs/verification/canvas-net/fonts/true-type-font.md index 6ac4b4504..dea17f2f9 100644 --- a/docs/verification/canvas-net/fonts/true-type-font.md +++ b/docs/verification/canvas-net/fonts/true-type-font.md @@ -256,6 +256,15 @@ fails with `InvalidDataException`. Covers out-of-range referenced glyphs, truncated glyph bytes, invalid contour counts, and invalid `loca` tables, asserting each fails with `InvalidDataException`. +##### CanvasNet-Fonts-TrueTypeFont-GlyphOutlineMemoized: Outlines Are Memoized Without Changing Results + +**Tests**: `TrueTypeFont_GetGlyphOutline_RepeatedCalls_ReturnMemoizedOutlineEqualToFreshDecode`, +`TrueTypeFont_GetGlyphOutline_MalformedGlyph_ThrowsOnEveryCall` + +Asserts two calls on one font return the same instance, that its subpaths, start points, closed +flags and every command equal those decoded by a second font that has cached nothing, and that a +glyph with an invalid contour count throws `InvalidDataException` on each call. No timing is asserted. + ##### CanvasNet-Fonts-TrueTypeFont-GlyphIndexValidation: `GetGlyphOutline` Rejects Out-of-Range Glyph Indices **Tests**: `TrueTypeFont_GetGlyphOutline_NegativeGlyphIndex_ThrowsArgumentOutOfRangeException`, diff --git a/docs/verification/canvas-net/geometry/path.md b/docs/verification/canvas-net/geometry/path.md index c2e03a061..1e756a3db 100644 --- a/docs/verification/canvas-net/geometry/path.md +++ b/docs/verification/canvas-net/geometry/path.md @@ -77,10 +77,13 @@ Calls `Close`, then `LineTo` without an intervening `MoveTo`, and asserts ##### CanvasNet-Geometry-Path-BuildSnapshotIndependence: Build Returns an Independent Snapshot -**Test**: `PathBuilder_Build_ThenMutateBuilder_DoesNotAffectPreviouslyBuiltPath` +**Tests**: `PathBuilder_Build_ThenMutateBuilder_DoesNotAffectPreviouslyBuiltPath`, +`PathBuilder_Build_ThenReuseBuilder_EarlierPathsAreUnchanged` Builds a `Path`, then issues further commands (including a new `MoveTo`/subpath) on the same -builder, and asserts the previously built `Path` instance's `Subpaths` are unchanged. +builder, and asserts the previously built `Path` instance's `Subpaths` are unchanged. The second +test also builds again, calls `Clear()`, and builds an unrelated path, proving the recycled +command list never leaks into earlier or later results. ##### CanvasNet-Geometry-Path-BuildEmpty: Build With No Commands Returns No Subpaths diff --git a/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Color.cs b/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Color.cs index 995a59d9c..2a15433a3 100644 --- a/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Color.cs +++ b/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Color.cs @@ -739,6 +739,20 @@ private static Rgba32 ColorFromComponents(PdfColorSpace colorSpace, IReadOnlyLis _ => throw new InvalidOperationException($"Unreachable: unrecognized color space {colorSpace.Kind}."), }; + /// + /// Allocation-free twin of + /// for per-pixel image conversion: identical conversion formulas over a span of components. + /// + private static Rgba32 ColorFromComponentSpan(PdfColorSpace colorSpace, ReadOnlySpan components) => + colorSpace.Kind switch + { + PdfColorSpace.Family.DeviceGray => GrayToColor(components[0]), + PdfColorSpace.Family.DeviceRGB => RgbToColor(components[0], components[1], components[2]), + PdfColorSpace.Family.DeviceCMYK => CmykToColor(components[0], components[1], components[2], components[3]), + PdfColorSpace.Family.Indexed => IndexedToColor(colorSpace, components[0]), + _ => throw new InvalidOperationException($"Unreachable: unrecognized color space {colorSpace.Kind}."), + }; + private static Rgba32 GrayToColor(double gray) { var value = ComponentToByte(gray); @@ -777,13 +791,13 @@ private static Rgba32 IndexedToColor(PdfColorSpace colorSpace, double rawIndex) var componentCount = ComponentCount(baseSpace); var offset = index * componentCount; - var components = new double[componentCount]; + Span components = componentCount <= 4 ? stackalloc double[componentCount] : new double[componentCount]; for (var i = 0; i < componentCount; i++) { components[i] = colorSpace.IndexedPalette[offset + i] / 255.0; } - return ColorFromComponents(baseSpace, components); + return ColorFromComponentSpan(baseSpace, components); } /// Converts a [0, 1] color component (clamped) into a [0, 255] byte value. diff --git a/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs b/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs index 7c3bccbdc..5dcf5191e 100644 --- a/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs +++ b/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs @@ -902,16 +902,16 @@ private static Rgba32 SamplesToColor(PdfColorSpace colorSpace, byte[] decoded, i { // An /Indexed sample is a raw palette index, not a [0, 1]-normalized component - do // not divide by 255.0 like every other color space below. - return ColorFromComponents(colorSpace, [(double)decoded[offset]]); + return IndexedToColor(colorSpace, decoded[offset]); } - var components = new double[count]; + Span components = count <= 4 ? stackalloc double[count] : new double[count]; for (var i = 0; i < count; i++) { components[i] = decoded[offset + i] / 255.0; } - return ColorFromComponents(colorSpace, components); + return ColorFromComponentSpan(colorSpace, components); } /// diff --git a/src/DemaConsulting.CanvasNet/Canvas/Surface.cs b/src/DemaConsulting.CanvasNet/Canvas/Surface.cs index 8386b1951..1335ba46c 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/Surface.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/Surface.cs @@ -1528,6 +1528,61 @@ public CompositeSpanWorkspace(int capacity) Work = new CompositeWorkBuffers(capacity); } + /// + /// The largest capacity a workspace may have and still be retained in the per-thread + /// cache by (bounds the memory a thread keeps after a large fill). + /// + private const int MaxCachedCapacity = 16384; + + /// + /// The smallest capacity creates, so the many small fills (for example + /// glyphs) can all reuse one cached workspace. + /// + private const int MinRentedCapacity = 256; + + /// + /// The per-thread cached workspace, available to (taken out of this + /// slot while in use, so a nested or concurrent use on the same thread never shares one). + /// + [ThreadStatic] + private static CompositeSpanWorkspace? _cached; + + private bool _pooled; + + private static void Cache(CompositeSpanWorkspace workspace) => _cached = workspace; + + /// + /// Gets a workspace able to serve spans of up to pixels, reusing + /// this thread's cached one when it is large enough. Disposing it hands it back to the + /// cache rather than returning its arrays to , which removes the + /// per-fill rent/return churn of every scratch array from tiny fills such as glyphs. + /// + /// The largest span length to serve. Must be greater than zero. + /// A workspace whose is at least . + public static CompositeSpanWorkspace Rent(int capacity) + { + if (capacity <= 0) + { + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "Capacity must be greater than zero."); + } + + var cached = _cached; + _cached = null; + if (cached != null) + { + if (cached.Capacity >= capacity) + { + return cached; + } + + cached._pooled = false; + cached.Dispose(); + } + + var rented = new CompositeSpanWorkspace(Math.Max(capacity, MinRentedCapacity)) { _pooled = capacity <= MaxCachedCapacity }; + return rented; + } + /// /// The largest coverage-span length this workspace's buffers can serve. /// @@ -1548,6 +1603,19 @@ public CompositeSpanWorkspace(int capacity) /// public void Dispose() { + if (ReferenceEquals(_cached, this)) + { + // Already handed back to the cache: a repeated Dispose must not free its arrays. + return; + } + + if (_pooled && _cached == null) + { + // Keep the arrays for the next fill on this thread instead of returning them. + Cache(this); + return; + } + Bg.Dispose(); Fg.Dispose(); Work.Dispose(); diff --git a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs index 7e490072c..48ab70a43 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Numerics; using System.Numerics.Tensors; @@ -82,42 +83,52 @@ internal static Surface Resample( var bytesPerColumn = (long)rows * Channels * sizeof(float); var strip = (int)Math.Clamp(intermediateBudgetBytes / bytesPerColumn, 1L, outWidth); var rowStride = checked(strip * Channels); - var intermediate = new float[checked(rows * rowStride)]; - var accumulator = new float[rowStride]; + var intermediate = ArrayPool.Shared.Rent(checked(rows * rowStride)); + var accumulator = ArrayPool.Shared.Rent(rowStride); - for (var column0 = 0; column0 < outWidth; column0 += strip) + // Pooled buffers are not cleared: every element read below (the strip's rows of the + // intermediate, and the accumulator's first Multiply tap) is written first. + try { - var columns = Math.Min(strip, outWidth - column0); - - // Horizontal pass: filter every needed source row into the intermediate strip - for (var r = 0; r < rows; r++) + for (var column0 = 0; column0 < outWidth; column0 += strip) { - HorizontalRow(source.GetRowSpan(ys.MinIndex + r), xs, column0, columns, intermediate.AsSpan(r * rowStride, columns * Channels)); - } + var columns = Math.Min(strip, outWidth - column0); - // Vertical pass: each output row is a weighted sum of intermediate rows - var acc = accumulator.AsSpan(0, columns * Channels); - for (var oy = 0; oy < outHeight; oy++) - { - var first = ys.First[oy]; - var count = ys.Count[oy]; - var offset = ys.Offset[oy]; - for (var t = 0; t < count; t++) + // Horizontal pass: filter every needed source row into the intermediate strip + for (var r = 0; r < rows; r++) { - var row = intermediate.AsSpan((first + t - ys.MinIndex) * rowStride, columns * Channels); - if (t == 0) - { - TensorPrimitives.Multiply(row, ys.Weights[offset], acc); - } - else + HorizontalRow(source.GetRowSpan(ys.MinIndex + r), xs, column0, columns, intermediate.AsSpan(r * rowStride, columns * Channels)); + } + + // Vertical pass: each output row is a weighted sum of intermediate rows + var acc = accumulator.AsSpan(0, columns * Channels); + for (var oy = 0; oy < outHeight; oy++) + { + var first = ys.First[oy]; + var count = ys.Count[oy]; + var offset = ys.Offset[oy]; + for (var t = 0; t < count; t++) { - TensorPrimitives.MultiplyAdd(row, ys.Weights[offset + t], acc, acc); + var row = intermediate.AsSpan((first + t - ys.MinIndex) * rowStride, columns * Channels); + if (t == 0) + { + TensorPrimitives.Multiply(row, ys.Weights[offset], acc); + } + else + { + TensorPrimitives.MultiplyAdd(row, ys.Weights[offset + t], acc, acc); + } } - } - StoreRow(acc, result.GetRowSpan(oy).Slice(column0, columns)); + StoreRow(acc, result.GetRowSpan(oy).Slice(column0, columns)); + } } } + finally + { + ArrayPool.Shared.Return(intermediate); + ArrayPool.Shared.Return(accumulator); + } return result; } diff --git a/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs b/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs index 4f386c84a..87c732f20 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs @@ -1,5 +1,6 @@ // cspell:ignore precomputation using System.Numerics; +using System.Numerics.Tensors; using DemaConsulting.CanvasNet.Canvas; using DemaConsulting.CanvasNet.Geometry; @@ -174,6 +175,12 @@ internal static class ScanlineRasterizer /// private const float NearZeroDisplacement = 1e-6f; + /// + /// Coordinate magnitude beyond which a row's touched-column range is not trusted and the + /// full clip width is swept instead (also catches non-finite coordinates). + /// + private const float TouchedRangeLimit = 1e8f; + /// /// Rasterizes onto , compositing /// at each pixel scaled by its analytically computed fill @@ -217,11 +224,11 @@ internal static void Fill(Surface surface, IReadOnlyList> polygons // CompositeOverSpan call - amortizing the per-row ArrayPool rent/return of // Surface.CompositeOverSpan's scratch buffers across the whole fill instead of paying it // once per rasterized row. - using var compositeWorkspace = new Surface.CompositeSpanWorkspace(sweep.Width); + using var compositeWorkspace = Surface.CompositeSpanWorkspace.Rent(sweep.Width); - while (sweep.MoveNext(out var y, out var rowCoverage)) + while (sweep.MoveNext(out var y, out var x, out var rowCoverage)) { - surface.CompositeOverSpan(y, sweep.ClipMinX, rowCoverage, color, compositeWorkspace); + surface.CompositeOverSpan(y, x, rowCoverage, color, compositeWorkspace); } } @@ -270,7 +277,7 @@ internal static void Fill(Surface surface, IReadOnlyList> polygons return; } - using var compositeWorkspace = new Surface.CompositeSpanWorkspace(sweep.Width); + using var compositeWorkspace = Surface.CompositeSpanWorkspace.Rent(sweep.Width); var rowColors = new Rgba32[sweep.Width]; // Built once per fill operation, not once per row - the transform inverse and radial @@ -278,10 +285,11 @@ internal static void Fill(Surface surface, IReadOnlyList> polygons // GradientEvaluator's "Per-fill precomputation" remarks). var plan = GradientEvaluator.CreatePlan(paint); - while (sweep.MoveNext(out var y, out var rowCoverage)) + while (sweep.MoveNext(out var y, out var x, out var rowCoverage)) { - GradientEvaluator.EvaluateRow(in plan, y, sweep.ClipMinX, sweep.Width, rowColors); - surface.CompositeOverSpan(y, sweep.ClipMinX, rowCoverage, rowColors, compositeWorkspace); + var colors = rowColors.AsSpan(0, rowCoverage.Length); + GradientEvaluator.EvaluateRow(in plan, y, x, rowCoverage.Length, rowColors); + surface.CompositeOverSpan(y, x, rowCoverage, colors, compositeWorkspace); } } @@ -329,7 +337,7 @@ internal static void Fill(Surface surface, IReadOnlyList> polygons return; } - using var compositeWorkspace = new Surface.CompositeSpanWorkspace(sweep.Width); + using var compositeWorkspace = Surface.CompositeSpanWorkspace.Rent(sweep.Width); var rowColors = new Rgba32[sweep.Width]; // Built once per fill operation, not once per row - see TilePaintEvaluator's "Per-fill @@ -338,10 +346,11 @@ internal static void Fill(Surface surface, IReadOnlyList> polygons try { - while (sweep.MoveNext(out var y, out var rowCoverage)) + while (sweep.MoveNext(out var y, out var x, out var rowCoverage)) { - TilePaintEvaluator.EvaluateRow(in plan, y, sweep.ClipMinX, sweep.Width, rowColors); - surface.CompositeOverSpan(y, sweep.ClipMinX, rowCoverage, rowColors, compositeWorkspace); + var colors = rowColors.AsSpan(0, rowCoverage.Length); + TilePaintEvaluator.EvaluateRow(in plan, y, x, rowCoverage.Length, rowColors); + surface.CompositeOverSpan(y, x, rowCoverage, colors, compositeWorkspace); } } finally @@ -428,9 +437,9 @@ internal static void AccumulateCoverageMask( return; } - while (sweep.MoveNext(out var y, out var rowCoverage)) + while (sweep.MoveNext(out var y, out var x, out var rowCoverage)) { - var rowOffset = ((y - originY) * maskWidth) + (sweep.ClipMinX - originX); + var rowOffset = ((y - originY) * maskWidth) + (x - originX); rowCoverage.CopyTo(mask.AsSpan(rowOffset, rowCoverage.Length)); } } @@ -478,6 +487,8 @@ private sealed class CoverageSweep private readonly List _subRowEdges = []; private int _nextEdgeIndex; private int _currentY; + private int _spanStart; + private int _spanLength; public CoverageSweep(IReadOnlyList> polygons, FillRule fillRule, Rect clipBounds, ClipMask? clip = null) { @@ -549,18 +560,11 @@ public CoverageSweep(IReadOnlyList> polygons, FillRule fillRule, R } /// - /// The clipped row width, in pixel columns; also the length of every + /// The clipped row width, in pixel columns; the upper bound on the length of every /// rowCoverage span yielded by . /// public int Width { get; } - /// - /// The clipped leftmost pixel column; the x argument every caller should pass - /// to - /// alongside a yielded row. - /// - public int ClipMinX => _clipMinX; - /// /// when this fill operation has no visible rows or edges at /// all (an empty clip region, or geometry with no non-horizontal edges), meaning @@ -574,8 +578,14 @@ public CoverageSweep(IReadOnlyList> polygons, FillRule fillRule, R /// [0, 1] coverage span. /// /// The zero-based row just computed. + /// + /// The zero-based surface column of 's first element + /// (at least the clip's leftmost column). + /// /// - /// The row's coverage span, one value per column starting at . + /// The row's coverage span, one value per column starting at . Every + /// column outside it (left of or right of the span) has zero + /// coverage, and rows whose coverage is entirely zero are never yielded. /// This span is reused (overwritten) by every call - a caller must fully consume it /// (for example, by compositing it) before calling again. /// @@ -583,7 +593,7 @@ public CoverageSweep(IReadOnlyList> polygons, FillRule fillRule, R /// if a row was produced; once every /// row in the clip range has been swept. /// - public bool MoveNext(out int y, out ReadOnlySpan rowCoverage) + public bool MoveNext(out int y, out int x, out ReadOnlySpan rowCoverage) { while (_currentY < _clipMaxY) { @@ -609,11 +619,20 @@ public bool MoveNext(out int y, out ReadOnlySpan rowCoverage) AccumulateRowCoverage(y, rowTop, rowBottom); - rowCoverage = _rowCoverage; + if (_spanLength == 0) + { + // Every column of this row has zero coverage, which the compositing contract + // defines as "untouched" - nothing to yield. + continue; + } + + x = _clipMinX + _spanStart; + rowCoverage = new ReadOnlySpan(_rowCoverage, _spanStart, _spanLength); return true; } y = 0; + x = 0; rowCoverage = default; return false; } @@ -762,11 +781,49 @@ private void AccumulateRowCoverage(int y, float rowTop, float rowBottom) /// private void AccumulateRowCoverageSinglePass(int y) { + // Bound the columns this row's edges can possibly touch: every column left of "lo" + // has a zero running total (nothing has been accumulated yet) and every column right + // of "hi" has a constant running total (no edge contributes there), so only [lo, hi] + // needs clearing, accumulating, and per-column resolving - a thin shape on a wide + // clip region costs O(shape width), not O(clip width). + var minX = float.PositiveInfinity; + var maxX = float.NegativeInfinity; + foreach (var edge in _rowEdges) + { + minX = Math.Min(minX, Math.Min(edge.XAtY0, edge.XAtY1)); + maxX = Math.Max(maxX, Math.Max(edge.XAtY0, edge.XAtY1)); + } + + int lo; + int hi; + if (minX > -TouchedRangeLimit && maxX < TouchedRangeLimit) + { + // "cover" indexes up to floor(x) + 1 (the bank column to the right of an edge's + // column), clamped into the Width + 1 slots; the overflow slot is never read. + lo = Math.Clamp((int)MathF.Floor(minX) - _clipMinX, 0, Width); + hi = Math.Clamp((int)MathF.Floor(maxX) - _clipMinX + 1, 0, Width - 1); + } + else + { + // Non-finite or absurdly large coordinates: take the full, always-correct range. + lo = 0; + hi = Width - 1; + } + + if (lo > hi) + { + // Every edge lies right of the visible range: nothing is visible on this row. + _spanStart = 0; + _spanLength = 0; + return; + } + // Accumulate every active edge's row-restricted slice into the shared cell // arrays - a single O(edges) pass, with no sorting and no pairing of edges into - // "inside gaps". - Array.Clear(_cover); - Array.Clear(_area); + // "inside gaps". Only [lo, hi] is cleared: no edge writes outside it (apart from the + // never-read overflow slot), and nothing outside it is read below. + Array.Clear(_cover, lo, hi - lo + 1); + Array.Clear(_area, lo, hi - lo + 1); foreach (var edge in _rowEdges) { AccumulateRowEdge(edge, _clipMinX, _clipMaxX, _cover, _area); @@ -781,18 +838,45 @@ private void AccumulateRowCoverageSinglePass(int y) // was already applied geometrically to the polygons (ApplyRectClip), so it is not // multiplied here - that would square coverage where fill and clip edges coincide. var accumulatedCover = 0f; - for (var i = 0; i < Width; i++) + for (var i = lo; i <= hi; i++) { accumulatedCover += _cover[i]; var total = accumulatedCover + _area[i]; _rowCoverage[i] = ResolveCoverage(total, _fillRule); } + // Right of "hi" no edge contributes, so the coverage is the constant resolution of + // the final running total (zero for any closed, fully visible shape). + var end = hi + 1; + if (end < Width) + { + var tail = ResolveCoverage(accumulatedCover, _fillRule); + if (tail > 0f) + { + _rowCoverage.AsSpan(end, Width - end).Fill(tail); + end = Width; + } + } + + // Zero coverage means "untouched" to the compositor, so zero columns at either end of + // the window are simply left out of the yielded span. + while (lo < end && !(_rowCoverage[lo] > 0f)) + { + lo++; + } + + while (end > lo && !(_rowCoverage[end - 1] > 0f)) + { + end--; + } + + _spanStart = lo; + _spanLength = end - lo; ApplyClip(y); } /// - /// Multiplies the just-resolved by the active clip's + /// Multiplies the just-resolved window by the active clip's /// dense coverage for row , if any. The clip's analytic rectangle /// was already applied geometrically to the polygons (see ), /// so it contributes no per-pixel factor here: a fill edge coincident with a clip edge @@ -800,22 +884,20 @@ private void AccumulateRowCoverageSinglePass(int y) /// private void ApplyClip(int y) { - if (_clip == null) + if (_clip == null || _spanLength == 0) { return; } - var dense = _clip.GetDenseRow(y, _clipMinX, Width); + var dense = _clip.GetDenseRow(y, _clipMinX + _spanStart, _spanLength); if (dense.IsEmpty) { return; } - var row = _rowCoverage.AsSpan(0, Width); - for (var i = 0; i < row.Length; i++) - { - row[i] *= dense[i]; - } + // IEEE single-precision multiply, element-wise: bit-identical to the scalar loop. + var row = _rowCoverage.AsSpan(_spanStart, _spanLength); + TensorPrimitives.Multiply(row, dense, row); } /// @@ -964,6 +1046,8 @@ private void AccumulateRowCoverageWithSubRowSplitting(int y, float rowTop, float _rowCoverage[i] = _subRowCoverage[i]; } + _spanStart = 0; + _spanLength = Width; ApplyClip(y); } diff --git a/src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs b/src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs index 47cd58032..79802479e 100644 --- a/src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs +++ b/src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs @@ -2,6 +2,7 @@ // cspell:ignore maxp Maxp notdef codepoint codepoints subtable subtables subsetted // cspell:ignore subsetting PPEM OTTO ttcf // cspell:ignore macStyle fsSelection usWeightClass isFixedPitch italicAngle nameID +using System.Collections.Concurrent; using DemaConsulting.CanvasNet.Geometry; using Path = DemaConsulting.CanvasNet.Geometry.Path; @@ -124,6 +125,19 @@ public sealed class TrueTypeFont private readonly KernTable _kern; private readonly NameTable _name; + /// + /// The most outlines retains per font. The cache is a pure + /// memoization of , so exceeding the limit only means later + /// glyphs are decoded on every call instead of once. + /// + private const int MaxCachedOutlines = 4096; + + /// + /// Decoded outlines by glyph index. A is immutable, so a cached instance + /// is safely shared by every caller; only successful decodes are stored. + /// + private readonly ConcurrentDictionary _outlineCache = new(); + /// /// The number of font design units per em, from head.unitsPerEm. /// @@ -465,7 +479,8 @@ public int GetGlyphIndex(int codepoint) } /// - /// Decodes a single glyph's outline. + /// Decodes a single glyph's outline. The result is memoized per glyph index (up to a fixed + /// per-font limit): repeated calls return the same immutable instance. /// /// The glyph index to decode, as returned by . /// @@ -486,7 +501,19 @@ public int GetGlyphIndex(int codepoint) public Path GetGlyphOutline(int glyphIndex) { ValidateGlyphIndex(glyphIndex); - return _glyphs.GetGlyphOutline(glyphIndex); + if (_outlineCache.TryGetValue(glyphIndex, out var cached)) + { + return cached; + } + + // A malformed glyph throws here and is therefore never cached: every call reports it again. + var outline = _glyphs.GetGlyphOutline(glyphIndex); + if (_outlineCache.Count < MaxCachedOutlines) + { + outline = _outlineCache.GetOrAdd(glyphIndex, outline); + } + + return outline; } /// diff --git a/src/DemaConsulting.CanvasNet/Geometry/PathBuilder.cs b/src/DemaConsulting.CanvasNet/Geometry/PathBuilder.cs index de5c67fdc..8c50cc7a9 100644 --- a/src/DemaConsulting.CanvasNet/Geometry/PathBuilder.cs +++ b/src/DemaConsulting.CanvasNet/Geometry/PathBuilder.cs @@ -26,7 +26,7 @@ public sealed class PathBuilder /// Commands accumulated for the subpath currently being built, since the most recent /// . /// - private List _currentCommands = []; + private readonly List _currentCommands = []; /// /// The point the current subpath started at, from the most recent . @@ -56,7 +56,10 @@ public PathBuilder MoveTo(Vector2 point) CommitCurrentSubpath(isClosed: false); _currentStart = point; - _currentCommands = []; + + // CommitCurrentSubpath already copied the commands into the committed subpath, so the + // scratch list is reused rather than reallocated (and regrown) for every subpath. + _currentCommands.Clear(); _hasCurrentSubpath = true; return this; } diff --git a/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageColorConversionTests.cs b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageColorConversionTests.cs new file mode 100644 index 000000000..ed81f9939 --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageColorConversionTests.cs @@ -0,0 +1,119 @@ +using System.Text; + +namespace DemaConsulting.CanvasNet.Pdf.Tests; + +/// +/// End-to-end, pixel-exact tests of the per-pixel image color conversion (DeviceGray, +/// DeviceRGB, DeviceCMYK and /Indexed samples): a raster image drawn 1:1 is an +/// exact copy of its converted samples, so every expected pixel below is checked exactly. +/// +public class PdfDocumentImageColorConversionTests +{ + private const int ImageWidth = 4; + + private static readonly PdfRenderOptions Opaque = new() { BackgroundColor = new(1, 2, 3, 255) }; + + /// Builds a one-page PDF (4 x 1 points) drawing a 4 x 1 8-bit image 1:1. + private static byte[] BuildPdf(string colorSpace, byte[] samples) + { + var content = Encoding.ASCII.GetBytes("4 0 0 1 0 0 cm /Im0 Do"); + var bodies = new List + { + "<< /Type /Catalog /Pages 2 0 R >>"u8.ToArray(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"u8.ToArray(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 4 1] /Contents 4 0 R /Resources << /XObject << /Im0 5 0 R >> >> >>"u8.ToArray(), + PdfDocumentImageDownscaleTests.Stream("<< /Length " + content.Length + " >>", content), + PdfDocumentImageDownscaleTests.Stream( + $"<< /Type /XObject /Subtype /Image /Width {ImageWidth} /Height 1 /ColorSpace {colorSpace} /BitsPerComponent 8 /Length {samples.Length} >>", + samples), + }; + + var buffer = new List(); + buffer.AddRange("%PDF-1.7\n"u8.ToArray()); + var offsets = new List(); + for (var i = 0; i < bodies.Count; i++) + { + offsets.Add(buffer.Count); + buffer.AddRange(Encoding.ASCII.GetBytes($"{i + 1} 0 obj\n")); + buffer.AddRange(bodies[i]); + buffer.AddRange("\nendobj\n"u8.ToArray()); + } + + var xrefOffset = buffer.Count; + buffer.AddRange(Encoding.ASCII.GetBytes($"xref\n0 {bodies.Count + 1}\n0000000000 65535 f \n")); + foreach (var offset in offsets) + { + buffer.AddRange(Encoding.ASCII.GetBytes($"{offset:D10} 00000 n \n")); + } + + buffer.AddRange(Encoding.ASCII.GetBytes( + $"trailer\n<< /Size {bodies.Count + 1} /Root 1 0 R >>\nstartxref\n{xrefOffset}\n%%EOF\n")); + return [.. buffer]; + } + + /// Renders the image and returns its four pixels as (R, G, B) triples. + private static (int R, int G, int B)[] RenderPixels(string colorSpace, byte[] samples) + { + using var document = PdfDocument.Open(new MemoryStream(BuildPdf(colorSpace, samples))); + using var surface = document.Render(0, ImageWidth, 1, Opaque); + var pixels = new (int, int, int)[ImageWidth]; + for (var x = 0; x < ImageWidth; x++) + { + var p = surface[x, 0]; + Assert.Equal(255, p.A); + pixels[x] = (p.R, p.G, p.B); + } + + return pixels; + } + + /// Proves that 8-bit DeviceGray samples become opaque gray pixels. + [Fact] + public void PdfDocument_ImageColor_DeviceGray_ConvertsEachSampleExactly() + { + // Arrange / Act: four gray samples drawn 1:1 + var pixels = RenderPixels("/DeviceGray", [0, 64, 128, 255]); + + // Assert: each pixel is the sample replicated into R, G and B + (int, int, int)[] expected = [(0, 0, 0), (64, 64, 64), (128, 128, 128), (255, 255, 255)]; + Assert.Equal(expected, pixels); + } + + /// Proves that 8-bit DeviceRGB samples are copied unchanged. + [Fact] + public void PdfDocument_ImageColor_DeviceRgb_ConvertsEachSampleExactly() + { + // Arrange / Act + var pixels = RenderPixels("/DeviceRGB", [255, 0, 0, 10, 20, 30, 0, 255, 128, 7, 8, 9]); + + // Assert + (int, int, int)[] expected = [(255, 0, 0), (10, 20, 30), (0, 255, 128), (7, 8, 9)]; + Assert.Equal(expected, pixels); + } + + /// Proves that 8-bit DeviceCMYK samples use the naive 255 * (1 - c) * (1 - k) conversion. + [Fact] + public void PdfDocument_ImageColor_DeviceCmyk_ConvertsEachSampleExactly() + { + // Arrange / Act: white, pure cyan, pure black key, and pure magenta + var pixels = RenderPixels("/DeviceCMYK", [0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 255, 0, 255, 0, 0]); + + // Assert + (int, int, int)[] expected = [(255, 255, 255), (0, 255, 255), (0, 0, 0), (255, 0, 255)]; + Assert.Equal(expected, pixels); + } + + /// Proves that /Indexed samples look up their palette entries exactly. + [Fact] + public void PdfDocument_ImageColor_Indexed_LooksUpEachPaletteEntryExactly() + { + // Arrange / Act: a four-entry RGB palette, sampled out of order + var pixels = RenderPixels( + "[/Indexed /DeviceRGB 3 ]", + [3, 0, 2, 1]); + + // Assert + (int, int, int)[] expected = [(16, 32, 48), (255, 0, 0), (0, 0, 255), (0, 255, 0)]; + Assert.Equal(expected, pixels); + } +} diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs index 5aaad864b..4ce719979 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs @@ -299,6 +299,45 @@ public void BoxReduce_MatchesAreaResize() } } + /// + /// Resampling is deterministic across the pooled scratch buffers: a call repeated after + /// differently sized calls (which leave stale data in recycled buffers) is identical to the first. + /// + [Theory] + [InlineData(ResamplingMode.Area)] + [InlineData(ResamplingMode.Bicubic)] + [InlineData(ResamplingMode.Lanczos3)] + public void Resample_RepeatedAfterDifferentSizes_IsIdenticalDespiteRecycledBuffers(ResamplingMode mode) + { + using var source = new Surface(37, 29); + for (var y = 0; y < 29; y++) + { + for (var x = 0; x < 37; x++) + { + source[x, y] = new Rgba32((byte)((x * 7) + y), (byte)(y * 9), (byte)((x * y) & 255), (byte)(255 - ((x + y) % 6 * 15))); + } + } + + using var baseline = SurfaceResampler.Resample(source, 0, 37, 0, 29, 11, 8, mode); + + // Churn the pool: a much larger intermediate, then a mid-sized one + using (var large = SurfaceResampler.Resample(source, 0, 37, 0, 29, 150, 120, mode)) + using (var mid = SurfaceResampler.Resample(source, 0, 37, 0, 29, 25, 40, mode)) + { + Assert.Equal(150, large.Width); + Assert.Equal(25, mid.Width); + } + + using var repeated = SurfaceResampler.Resample(source, 0, 37, 0, 29, 11, 8, mode); + for (var y = 0; y < 8; y++) + { + for (var x = 0; x < 11; x++) + { + Assert.Equal(baseline[x, y], repeated[x, y]); + } + } + } + /// Wrapped bilinear sampling wraps across the tile edge. [Fact] public void SampleBilinearWrapped_AtEdge_BlendsWithOppositeSide() diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceTests.cs index 4c8ba95d4..6cda2bb25 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceTests.cs @@ -1432,6 +1432,85 @@ public void CompositeSpanWorkspace_Constructor_NonPositiveCapacity_ThrowsArgumen Assert.Throws(() => new Surface.CompositeSpanWorkspace(capacity)); } + /// + /// Proves CompositeSpanWorkspace.Rent rejects a non-positive capacity. + /// + [Theory] + [InlineData(0)] + [InlineData(-5)] + public void CompositeSpanWorkspace_Rent_NonPositiveCapacity_ThrowsArgumentOutOfRangeException(int capacity) + { + // Act & Assert + Assert.Throws(() => Surface.CompositeSpanWorkspace.Rent(capacity)); + } + + /// + /// Proves a rented workspace is large enough for the request and that disposing it and + /// renting again on the same thread reuses the same instance (the per-thread cache). + /// + [Fact] + public void CompositeSpanWorkspace_Rent_AfterDispose_ReusesCachedWorkspaceWithSufficientCapacity() + { + // Arrange / Act + var first = Surface.CompositeSpanWorkspace.Rent(10); + var firstCapacity = first.Capacity; + first.Dispose(); + using var second = Surface.CompositeSpanWorkspace.Rent(10); + + // Assert + Assert.True(firstCapacity >= 10); + Assert.Same(first, second); + } + + /// + /// Proves two workspaces rented at the same time on one thread are distinct instances, + /// so nested use never shares scratch buffers. + /// + [Fact] + public void CompositeSpanWorkspace_Rent_WhileAnotherIsInUse_ReturnsDistinctWorkspace() + { + // Arrange / Act + using var outer = Surface.CompositeSpanWorkspace.Rent(10); + using var inner = Surface.CompositeSpanWorkspace.Rent(10); + + // Assert + Assert.NotSame(outer, inner); + } + + /// + /// Proves a request larger than the cached workspace gets a workspace large enough for it, + /// and that a rented workspace produces the same pixels as a directly constructed one. + /// + [Fact] + public void CompositeSpanWorkspace_Rent_LargerThanCached_GrowsAndCompositesIdenticallyToConstructedWorkspace() + { + // Arrange + Surface.CompositeSpanWorkspace.Rent(4).Dispose(); + const int width = 8000; + float[] coverage = [.. Enumerable.Range(0, width).Select(i => (i % 5) / 4f)]; + using var expected = new Surface(width, 1); + using var actual = new Surface(width, 1); + var color = new Rgba32(10, 120, 240, 180); + + // Act + using (var constructed = new Surface.CompositeSpanWorkspace(width)) + { + expected.CompositeOverSpan(0, 0, coverage, color, constructed); + } + + using (var rented = Surface.CompositeSpanWorkspace.Rent(width)) + { + Assert.True(rented.Capacity >= width); + actual.CompositeOverSpan(0, 0, coverage, color, rented); + } + + // Assert + for (var x = 0; x < width; x++) + { + Assert.Equal(expected[x, 0], actual[x, 0]); + } + } + /// /// Proves that the per-pixel-color CompositeOverSpan overload applies each pixel's /// own color, matching the constant-color overload's result at each pixel when every diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs index f09d84d30..5393b3800 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs @@ -946,5 +946,290 @@ public void ScanlineRasterizer_Fill_CoincidentRectangleClip_EqualsUnclippedFill( } } } + + /// + /// The shapes used by the reference-equivalence tests: each is a list of convex polygons + /// (a hole is a separate counter-wound polygon, subtracted by the geometric reference), + /// chosen to exercise sparse rows, fully covered rows, slanted edges, and holes. + /// + public static TheoryData ShapeNames => + [ + "rect", + "triangle", + "slanted", + "hole", + "sparse", + "full", + "outside" + ]; + + private const int RefWidth = 70; + private const int RefHeight = 40; + + private static (List> Polygons, List Signs) BuildShape(string name) + { + List Rect(float l, float t, float r, float b, bool reverse = false) + { + List p = [new(l, t), new(r, t), new(r, b), new(l, b), new(l, t)]; + if (reverse) + { + p.Reverse(); + } + + return p; + } + + return name switch + { + "rect" => ([Rect(3.3f, 4.6f, 61.7f, 30.2f)], [1]), + "triangle" => ([[new(5.2f, 3.1f), new(64.7f, 20.4f), new(10.9f, 36.8f), new(5.2f, 3.1f)]], [1]), + "slanted" => ([[new(2.5f, 2.5f), new(9.5f, 2.5f), new(66.5f, 37.5f), new(59.5f, 37.5f), new(2.5f, 2.5f)]], [1]), + "hole" => ([Rect(4f, 4f, 66f, 36f), Rect(20.4f, 12.2f, 50.6f, 27.9f, reverse: true)], [1, -1]), + "sparse" => ([Rect(66.25f, 36.5f, 68.75f, 38.25f)], [1]), + "full" => ([Rect(0f, 0f, RefWidth, RefHeight)], [1]), + "outside" => ([Rect(-20f, -9f, 12.5f, 6.5f)], [1]), + _ => throw new ArgumentOutOfRangeException(nameof(name)) + }; + } + + /// + /// Exact area of a convex polygon clipped to the unit pixel at (, + /// ), by Sutherland-Hodgman clipping and the shoelace formula - an + /// independent reference that shares no code with the scanline accumulation. + /// + private static double PixelArea(List polygon, int px, int py) + { + var pts = polygon.Select(p => ((double)p.X, (double)p.Y)).ToList(); + if (pts.Count > 1 && pts[0] == pts[^1]) + { + pts.RemoveAt(pts.Count - 1); + } + + // Clip against x >= px, x <= px+1, y >= py, y <= py+1 + pts = ClipHalfPlane(pts, p => p.Item1 - px); + pts = ClipHalfPlane(pts, p => px + 1 - p.Item1); + pts = ClipHalfPlane(pts, p => p.Item2 - py); + pts = ClipHalfPlane(pts, p => py + 1 - p.Item2); + var area = 0.0; + for (var i = 0; i < pts.Count; i++) + { + var a = pts[i]; + var b = pts[(i + 1) % pts.Count]; + area += (a.Item1 * b.Item2) - (b.Item1 * a.Item2); + } + + return Math.Abs(area) / 2; + } + + private static List<(double, double)> ClipHalfPlane(List<(double, double)> input, Func<(double, double), double> inside) + { + var output = new List<(double, double)>(); + for (var i = 0; i < input.Count; i++) + { + var cur = input[i]; + var prev = input[(i + input.Count - 1) % input.Count]; + var dc = inside(cur); + var dp = inside(prev); + if ((dc >= 0) != (dp >= 0)) + { + var t = dp / (dp - dc); + output.Add((prev.Item1 + (t * (cur.Item1 - prev.Item1)), prev.Item2 + (t * (cur.Item2 - prev.Item2)))); + } + + if (dc >= 0) + { + output.Add(cur); + } + } + + return output; + } + + private static float[] ReferenceCoverage(List> polygons, List signs) + { + var cover = new float[RefWidth * RefHeight]; + for (var y = 0; y < RefHeight; y++) + { + for (var x = 0; x < RefWidth; x++) + { + var a = 0.0; + for (var i = 0; i < polygons.Count; i++) + { + a += signs[i] * PixelArea(polygons[i], x, y); + } + + cover[(y * RefWidth) + x] = (float)Math.Clamp(a, 0.0, 1.0); + } + } + + return cover; + } + + private static Surface PatternBackground() + { + // Opaque, semi-transparent and fully transparent background pixels, so the composite + // takes every alpha branch. + var surface = new Surface(RefWidth, RefHeight); + for (var y = 0; y < RefHeight; y++) + { + for (var x = 0; x < RefWidth; x++) + { + surface[x, y] = (((x / 7) + y) % 3) switch + { + 0 => new Rgba32((byte)(x * 3), (byte)(y * 5), 77, 255), + 1 => new Rgba32(200, (byte)(x * 2), (byte)(y * 4), 90), + _ => new Rgba32(0, 0, 0, 0) + }; + } + } + + return surface; + } + + private static void AssertSurfacesEqual(Surface expected, Surface actual) + { + for (var y = 0; y < RefHeight; y++) + { + for (var x = 0; x < RefWidth; x++) + { + Assert.True(expected[x, y] == actual[x, y], $"pixel ({x},{y}): expected {expected[x, y]}, actual {actual[x, y]}"); + } + } + } + + /// + /// Proves the rasterized coverage matches an independent exact pixel-area reference to a + /// tight tolerance for every shape, including shapes whose rows are sparse, fully covered, + /// or entirely outside the surface (the rows and columns the sweep skips or trims). + /// + [Theory] + [MemberData(nameof(ShapeNames))] + public void ScanlineRasterizer_AccumulateCoverageMask_Shapes_MatchesExactPixelAreaReference(string shape) + { + // Arrange + var (polygons, signs) = BuildShape(shape); + var expected = ReferenceCoverage(polygons, signs); + var mask = new float[RefWidth * RefHeight]; + + // Act + ScanlineRasterizer.AccumulateCoverageMask(polygons, FillRule.NonZero, new Rect(0, 0, RefWidth, RefHeight), mask, RefWidth, 0, 0); + + // Assert + for (var i = 0; i < mask.Length; i++) + { + Assert.True(Math.Abs(expected[i] - mask[i]) <= 1e-4f, $"index {i}: expected {expected[i]}, actual {mask[i]}"); + } + } + + /// + /// Proves a solid-color fill is pixel-exact against compositing the full-width, + /// zero-padded coverage rows with the public span API - i.e. trimming each row to its + /// touched window and skipping empty rows changes no pixel, over opaque, semi-transparent + /// and transparent backgrounds. + /// + [Theory] + [MemberData(nameof(ShapeNames))] + public void ScanlineRasterizer_Fill_Shapes_PixelExactAgainstFullWidthCompositeReference(string shape) + { + // Arrange + var (polygons, _) = BuildShape(shape); + var color = new Rgba32(210, 40, 130, 200); + var bounds = new Rect(0, 0, RefWidth, RefHeight); + var mask = new float[RefWidth * RefHeight]; + ScanlineRasterizer.AccumulateCoverageMask(polygons, FillRule.NonZero, bounds, mask, RefWidth, 0, 0); + using var expected = PatternBackground(); + using var actual = PatternBackground(); + for (var y = 0; y < RefHeight; y++) + { + expected.CompositeOverSpan(y, 0, mask.AsSpan(y * RefWidth, RefWidth), color); + } + + // Act + ScanlineRasterizer.Fill(actual, polygons, color, FillRule.NonZero, bounds); + + // Assert + AssertSurfacesEqual(expected, actual); + } + + /// + /// Proves a fill with a dense (non-rectangular) clip mask is pixel-exact against the + /// product of the unclipped coverage and the clip's own per-pixel coverage. + /// + [Theory] + [MemberData(nameof(ShapeNames))] + public void ScanlineRasterizer_Fill_DenseClipMask_PixelExactAgainstCoverageTimesClipReference(string shape) + { + // Arrange + var (polygons, _) = BuildShape(shape); + var color = new Rgba32(20, 160, 230, 255); + var bounds = new Rect(0, 0, RefWidth, RefHeight); + var clip = ClipMask.FromPathDense( + new PathBuilder() + .MoveTo(new Vector2(6.3f, 2.2f)).LineTo(new Vector2(60.8f, 9.4f)) + .LineTo(new Vector2(33.1f, 38.6f)).Close().Build(), + FillRule.NonZero, + RefWidth, + RefHeight); + var mask = new float[RefWidth * RefHeight]; + ScanlineRasterizer.AccumulateCoverageMask(polygons, FillRule.NonZero, bounds, mask, RefWidth, 0, 0); + using var expected = PatternBackground(); + using var actual = PatternBackground(); + var row = new float[RefWidth]; + for (var y = 0; y < RefHeight; y++) + { + for (var x = 0; x < RefWidth; x++) + { + row[x] = mask[(y * RefWidth) + x] * clip.GetCoverage(x, y); + } + + expected.CompositeOverSpan(y, 0, row, color); + } + + // Act + ScanlineRasterizer.Fill(actual, polygons, color, FillRule.NonZero, bounds, clip); + + // Assert: coverage*clip may differ from the geometric clip by float rounding only + for (var y = 0; y < RefHeight; y++) + { + for (var x = 0; x < RefWidth; x++) + { + var e = expected[x, y]; + var a = actual[x, y]; + Assert.True( + Math.Abs(e.R - a.R) <= 1 && Math.Abs(e.G - a.G) <= 1 && Math.Abs(e.B - a.B) <= 1 && Math.Abs(e.A - a.A) <= 1, + $"pixel ({x},{y}): expected {e}, actual {a}"); + } + } + } + + /// + /// Proves the gradient and tile overloads, filled with a constant-color source, are + /// pixel-exact against the solid-color overload for each shape (the trimmed window's + /// per-pixel color evaluation lines up with its coverage). + /// + [Theory] + [MemberData(nameof(ShapeNames))] + public void ScanlineRasterizer_Fill_ConstantGradientAndTile_PixelExactAgainstSolid(string shape) + { + // Arrange + var (polygons, _) = BuildShape(shape); + var color = new Rgba32(90, 200, 60, 210); + var bounds = new Rect(0, 0, RefWidth, RefHeight); + using var solid = PatternBackground(); + using var gradient = PatternBackground(); + using var tile = PatternBackground(); + using var tileSurface = new Surface(1, 1); + tileSurface[0, 0] = color; + + // Act + ScanlineRasterizer.Fill(solid, polygons, color, FillRule.NonZero, bounds); + ScanlineRasterizer.Fill( + gradient, polygons, new LinearGradient(Vector2.Zero, new Vector2(RefWidth, 0), [new GradientStop(0f, color)]), FillRule.NonZero, bounds); + ScanlineRasterizer.Fill(tile, polygons, new TilePaint(tileSurface, Matrix3x2.Identity, 1f, 1f), FillRule.NonZero, bounds); + + // Assert + AssertSurfacesEqual(solid, gradient); + AssertSurfacesEqual(solid, tile); + } } diff --git a/test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs b/test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs index 228234b1e..c80466256 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs @@ -320,6 +320,66 @@ public void TrueTypeFont_GetGlyphOutline_GlyphIndexTooLarge_ThrowsArgumentOutOfR Assert.Throws(() => font.GetGlyphOutline(font.GlyphCount)); } + /// + /// Proves that repeated GetGlyphOutline calls return the same memoized instance, and that the + /// memoized outline equals the outline decoded by a font that has not cached anything. + /// + [Fact] + public void TrueTypeFont_GetGlyphOutline_RepeatedCalls_ReturnMemoizedOutlineEqualToFreshDecode() + { + // Arrange: two independent fonts loaded from the same bytes + var data = BuildWellFormedFont(); + using var cachedStream = new MemoryStream(data); + using var freshStream = new MemoryStream(data); + var cachedFont = TrueTypeFont.Load(cachedStream); + var freshFont = TrueTypeFont.Load(freshStream); + + // Act + var first = cachedFont.GetGlyphOutline(1); + var second = cachedFont.GetGlyphOutline(1); + var fresh = freshFont.GetGlyphOutline(1); + + // Assert: one shared instance, with exactly the geometry a cold decode produces + Assert.Same(first, second); + Assert.Equal(fresh.Subpaths.Count, first.Subpaths.Count); + for (var s = 0; s < fresh.Subpaths.Count; s++) + { + Assert.Equal(fresh.Subpaths[s].Start, first.Subpaths[s].Start); + Assert.Equal(fresh.Subpaths[s].IsClosed, first.Subpaths[s].IsClosed); + Assert.Equal(fresh.Subpaths[s].Commands.Count, first.Subpaths[s].Commands.Count); + for (var c = 0; c < fresh.Subpaths[s].Commands.Count; c++) + { + Assert.Equal(fresh.Subpaths[s].Commands[c], first.Subpaths[s].Commands[c]); + } + } + } + + /// + /// Proves that a malformed glyph is never memoized: every call reports it again. + /// + [Fact] + public void TrueTypeFont_GetGlyphOutline_MalformedGlyph_ThrowsOnEveryCall() + { + // Arrange: glyph 1 declares an invalid (below -1) contour count + var glyph = new byte[12]; + glyph[0] = 0xFF; + glyph[1] = 0xFE; + var data = new SyntheticFontBuilder() + .AddTable("head", SyntheticFontBuilder.Head(1000, 0)) + .AddTable("maxp", SyntheticFontBuilder.Maxp(2)) + .AddTable("hhea", SyntheticFontBuilder.Hhea(800, -200, 50, 2)) + .AddTable("hmtx", SyntheticFontBuilder.Hmtx([0, 500])) + .AddTable("loca", SyntheticFontBuilder.Loca([0, glyph.Length], longFormat: false)) + .AddTable("glyf", glyph) + .Build(); + using var stream = new MemoryStream(data); + var font = TrueTypeFont.Load(stream); + + // Act/Assert: the failure is repeatable + Assert.Throws(() => font.GetGlyphOutline(1)); + Assert.Throws(() => font.GetGlyphOutline(1)); + } + /// /// Proves that TrueTypeFont GetAdvanceWidth GlyphIndexTooLarge ThrowsArgumentOutOfRangeException. /// diff --git a/test/DemaConsulting.CanvasNet.Tests/Geometry/PathBuilderTests.cs b/test/DemaConsulting.CanvasNet.Tests/Geometry/PathBuilderTests.cs index d56f0bb1f..e77fc2ad4 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Geometry/PathBuilderTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Geometry/PathBuilderTests.cs @@ -434,4 +434,46 @@ public void PathBuilder_TangentArcTo_NoCurrentPoint_ThrowsInvalidOperationExcept var builder = new PathBuilder(); Assert.Throws(() => builder.TangentArcTo(new Vector2(10, 0), new Vector2(10, 10), 1f)); } + + /// + /// Proves that a built Path is a stable snapshot: later MoveTo/draw/Clear/reuse of the same + /// builder (which recycles its scratch command list) never alters it, and each subpath keeps + /// only its own commands. + /// + [Fact] + public void PathBuilder_Build_ThenReuseBuilder_EarlierPathsAreUnchanged() + { + // Arrange: a first path with two subpaths, the second still open when built + var builder = new PathBuilder(); + builder.MoveTo(new Vector2(0, 0)).LineTo(new Vector2(1, 0)).LineTo(new Vector2(1, 1)).Close(); + builder.MoveTo(new Vector2(5, 5)).LineTo(new Vector2(6, 5)); + var first = builder.Build(); + + // Act: keep drawing on the same builder, then clear it and build something unrelated + builder.LineTo(new Vector2(7, 7)).MoveTo(new Vector2(9, 9)).QuadraticBezierTo(new Vector2(10, 9), new Vector2(10, 10)); + var second = builder.Build(); + builder.Clear(); + builder.MoveTo(new Vector2(-1, -1)).LineTo(new Vector2(-2, -2)); + var third = builder.Build(); + + // Assert: the first path still holds exactly what it held when built + Assert.Equal(2, first.Subpaths.Count); + Assert.Equal( + [PathCommandType.LineTo, PathCommandType.LineTo, PathCommandType.Close], + first.Subpaths[0].Commands.Select(c => c.Type)); + Assert.Equal(new Vector2(5, 5), first.Subpaths[1].Start); + var open = Assert.Single(first.Subpaths[1].Commands); + Assert.Equal(new Vector2(6, 5), open.EndPoint); + + // Assert: the second path has the extended second subpath and the new third subpath + Assert.Equal(3, second.Subpaths.Count); + Assert.Equal(2, second.Subpaths[1].Commands.Count); + Assert.Equal(new Vector2(7, 7), second.Subpaths[1].Commands[1].EndPoint); + Assert.Equal(PathCommandType.QuadraticBezierTo, Assert.Single(second.Subpaths[2].Commands).Type); + + // Assert: the reused builder starts from scratch + var subpath = Assert.Single(third.Subpaths); + Assert.Equal(new Vector2(-1, -1), subpath.Start); + Assert.Equal(new Vector2(-2, -2), Assert.Single(subpath.Commands).EndPoint); + } } From 97b3c40200dd351338809f47cbe327edb4bb681f Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 12:49:39 -0400 Subject: [PATCH 06/16] Fix review findings: resampling docs, requirements, system resize tests Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/canvas-net-pdf/pdf-document.md | 6 +- docs/design/canvas-net.md | 5 + docs/design/canvas-net/canvas.md | 5 +- docs/design/canvas-net/canvas/surface.md | 4 +- docs/design/introduction.md | 4 + .../canvas-net-pdf/pdf-document.yaml | 10 +- .../canvas-net-pptx/pptx-document.yaml | 6 +- docs/reqstream/canvas-net.yaml | 5 + docs/reqstream/canvas-net/canvas.yaml | 1 + .../canvas-net/drawing/tile-paint.yaml | 3 +- docs/user_guide/introduction.md | 64 +++++++++---- docs/verification/canvas-net-svg/svg-codec.md | 5 + docs/verification/canvas-net.md | 28 ++++++ docs/verification/canvas-net/canvas.md | 8 +- .../verification/canvas-net/canvas/surface.md | 9 +- .../canvas-net/drawing/tile-paint.md | 10 +- .../PdfDocument.Images.cs | 4 +- .../Canvas/ResamplingMode.cs | 7 +- .../Canvas/SurfaceResampler.cs | 11 ++- .../CanvasNetTests.cs | 93 +++++++++++++++++++ 20 files changed, 244 insertions(+), 44 deletions(-) diff --git a/docs/design/canvas-net-pdf/pdf-document.md b/docs/design/canvas-net-pdf/pdf-document.md index ccd49cdc3..eb33e79eb 100644 --- a/docs/design/canvas-net-pdf/pdf-document.md +++ b/docs/design/canvas-net-pdf/pdf-document.md @@ -93,9 +93,9 @@ supported (an unrecognized base encoding also fails closed); text-rendering mode glyph under a clip mode fails closed); and no additional stream filters were added for any of these phases. **Phase 3 limitations** (narrowed by Phase 7/13 and the `/Pattern` color-space phase, see below): there are no transparency groups, `/Mask` (stencil/color-key) image masks and `/Matte` are not -consulted, `/ImageMask` stencil images are not rendered (there is no code path for them, so no -`Nearest` special case applies), and the Phase 3 operator subset is otherwise limited as documented below. These remain -out of scope and are silently skipped (any other undefined keyword) or explicitly rejected +consulted, and the Phase 3 operator subset is otherwise limited as documented below. These remain +out of scope (along with `/ImageMask` stencil images, which are not rendered) and are silently +skipped (any other undefined keyword) or explicitly rejected (unsupported color spaces/filters/fonts/encodings/render modes), per the operator/exception taxonomy documented below. Since then the following have been added: shading/tiling pattern fills (`/ShadingType 2`/`3`, `/PatternType 1`/`2` — see _`/Pattern` Color Space (Shading and Tiling diff --git a/docs/design/canvas-net.md b/docs/design/canvas-net.md index bbf0259cd..53e5effd9 100644 --- a/docs/design/canvas-net.md +++ b/docs/design/canvas-net.md @@ -179,6 +179,10 @@ The system exposes the following public API to external consumers: - **Surface.Resize(int width, int height, ResamplingMode mode = Auto)** / **Surface.ResizeToFit(int maxWidth, int maxHeight, ResamplingMode mode = Auto)**: Return a new, independent, resampled Surface. Throw `ArgumentOutOfRangeException` for dimensions outside 1 to `MaxDimension` or an undefined mode. +- **ResamplingMode**: Public enum selecting the reconstruction filter, with six values: `Auto` (Area + when an axis shrinks, Bicubic when it grows), `Nearest`, `Bilinear`, `Bicubic`, `Lanczos3` and `Area`. + The internal `SurfaceResampler` engine is shared with the `Pdf`, `Pptx` and `Svg` packages through + `InternalsVisibleTo` (the `DemaConsulting.CanvasNet.Svg` grant is new). - **Surface.PremultiplyAlpha()**: Converts the surface's pixels from straight (unassociated) alpha to premultiplied alpha in place. - **Surface.UnpremultiplyAlpha()**: Converts the surface's pixels from premultiplied alpha back to @@ -360,6 +364,7 @@ The system exposes the following public API to external consumers: | `Surface.Crop(int,int,int,int)` | Inbound/Outbound | Method call / `Surface` return | Region within source bounds | | `Surface.Resize(int,int,ResamplingMode)` | Inbound/Outbound | Method call / `Surface` return | 1..MaxDimension, defined mode | | `Surface.ResizeToFit(int,int,ResamplingMode)`| Inbound/Outbound | Method call / `Surface` return | 1..MaxDimension, defined mode | +| `ResamplingMode` | Inbound | Enum argument | Six defined values | | `Surface.PremultiplyAlpha()` | Inbound | Method call | None | | `Surface.UnpremultiplyAlpha()` | Inbound | Method call | None | | `Surface.CompositeOver(Surface)` | Inbound | Method call | Equal dimensions, non-null | diff --git a/docs/design/canvas-net/canvas.md b/docs/design/canvas-net/canvas.md index 4e39164ec..c490f2d1a 100644 --- a/docs/design/canvas-net/canvas.md +++ b/docs/design/canvas-net/canvas.md @@ -14,8 +14,9 @@ other subsystem: the `Codecs` subsystem depends on `Canvas`, not the other way a ### Units -- **Surface** — mutable, in-memory 32-bit RGBA pixel buffer with allocation-free row access and - independent-copy cropping; see _Surface Unit Design_ (`canvas/surface.md`) +- **Surface** — mutable, in-memory 32-bit RGBA pixel buffer with allocation-free row access, + independent-copy cropping and resampling (`Resize`/`ResizeToFit` with the `ResamplingMode` + filters, backed by the internal separable `SurfaceResampler` engine); see _Surface Unit Design_ (`canvas/surface.md`) - **Rgba32** — a blittable four-byte value type representing a single RGBA pixel; its channel layout is documented inline within the `Surface` unit design and its hex-literal `Parse`/`TryParse` methods are covered in _Rgba32 Unit Design_ (`canvas/rgba32.md`) diff --git a/docs/design/canvas-net/canvas/surface.md b/docs/design/canvas-net/canvas/surface.md index 0b1791b62..539fd77a4 100644 --- a/docs/design/canvas-net/canvas/surface.md +++ b/docs/design/canvas-net/canvas/surface.md @@ -512,7 +512,9 @@ output never depends on a buffer's previous contents. **Renderer entry points.** `TryResampleToDevice` resamples a source to the device window covered by an axis-aligned image placement (the window is clipped to the visible area) so the renderer can -composite it 1:1; it returns `false` for rotation, skew or non-finite/degenerate matrices, and `true` +composite it 1:1; it returns `false` for rotation, skew or non-finite/degenerate matrices (a +rotation/skew component is tolerated only while it moves no pixel by more than 0.01 device pixel, +i.e. `|M12|*height` and `|M21|*width` are each at most 0.01), and `true` with no window when nothing is visible. Rotated or skewed placements use `Prefilter` (area-reduce by an integer factor) plus `SampleBilinear` (inverse mapped, premultiplied, edge-clamped). `SampleBilinearWrapped` is the wrap-around bilinear sampler used for magnified pattern tiles. diff --git a/docs/design/introduction.md b/docs/design/introduction.md index a5761343c..e7cc029d2 100644 --- a/docs/design/introduction.md +++ b/docs/design/introduction.md @@ -270,6 +270,10 @@ and descriptions as follows: src/DemaConsulting.CanvasNet/ ├── Canvas/ │ ├── Surface.cs — Mutable, in-memory 32-bit RGBA pixel buffer +│ ├── ResamplingMode.cs — Public enum of resampling filters for Resize/ResizeToFit +│ ├── SurfaceResampler.cs — Internal box-reduction prefilter and bilinear samplers +│ ├── SurfaceResampler.Engine.cs — Internal separable resampling engine, device-window and +│ │ tile helpers │ ├── Rgba32.cs — Single 32-bit RGBA pixel value type │ └── NamespaceDoc.cs — Namespace-level XML documentation ├── Codecs/ diff --git a/docs/reqstream/canvas-net-pdf/pdf-document.yaml b/docs/reqstream/canvas-net-pdf/pdf-document.yaml index 86c2a3c07..239af0bce 100644 --- a/docs/reqstream/canvas-net-pdf/pdf-document.yaml +++ b/docs/reqstream/canvas-net-pdf/pdf-document.yaml @@ -856,7 +856,8 @@ sections: raw DeviceGray/DeviceRGB/DeviceCMYK/Indexed samples of 1, 2, 4, 8 or 16 bits per component, and compositing the decoded image onto the destination surface through the current transformation - matrix (nearest-neighbor sampling, treating every image as fully opaque unless it + matrix (resampled once per draw: area averaging when shrinking, bicubic when enlarging, + and a bilinear fallback for rotated or skewed placements; treating every image as fully opaque unless it carries alpha via /SMask, and alpha-blending each sampled source pixel over the existing destination pixel via standard Porter-Duff "over" compositing rather than overwriting it outright); an @@ -897,8 +898,8 @@ sections: The PdfDocument class shall apply an explicit /SMask image of an image XObject (whatever the base image's encoding: raw samples, DCTDecode or JPXDecode) as the base image's alpha channel, multiplying the mask's single-component luminance - into the base alpha (resampling the mask to the base image with nearest-neighbor - sampling; the mask may use any supported bit depth - 1, 2, 4, 8 or 16 bits per + into the base alpha (resampling the mask to the base image bilinearly when + the sizes differ; the mask may use any supported bit depth - 1, 2, 4, 8 or 16 bits per component) and ignoring the mask's own /SMask. justification: | Soft-masked images are the common way PDF producers store transparent raster @@ -2000,7 +2001,8 @@ sections: The PdfDocument class shall fill or stroke a path using a /PatternType 1 (tiling) pattern, rendering the pattern's own content stream once into an offscreen tile surface (sized from /XStep/YStep scaled by the pattern-to-device transform) and - repeating that tile across the painted region, nearest-neighbor sampled. A + repeating that tile across the painted region (exact at about one device pixel per tile pixel, smoothed + otherwise). A /PaintType 1 (colored) pattern paints its own content stream's colors unmodified; a /PaintType 2 (uncolored) pattern recolors every painted pixel to the scn/SCN-supplied tint while preserving each pixel's own painted alpha. A zero or non-finite diff --git a/docs/reqstream/canvas-net-pptx/pptx-document.yaml b/docs/reqstream/canvas-net-pptx/pptx-document.yaml index 85ec8710d..775e937eb 100644 --- a/docs/reqstream/canvas-net-pptx/pptx-document.yaml +++ b/docs/reqstream/canvas-net-pptx/pptx-document.yaml @@ -1238,8 +1238,8 @@ sections: The PptxDocument class shall paint a decoded picture Surface onto a destination Surface by composing the picture's own crop-rectangle-to-unit-square mapping with the shape's resolved frame transform into a single image-to-surface matrix, sampling - the source image with nearest-neighbor filtering for each destination pixel whose - inverse-mapped source coordinate falls within the image bounds, alpha-blending each + the source image through that single matrix (the filtering is specified by + PictureSmoothResample), alpha-blending each sampled source pixel over the existing destination pixel via standard Porter-Duff "over" compositing (rather than overwriting it outright), and painting no pixels at all when the composed transform is singular (non-invertible), without applying any @@ -1247,7 +1247,7 @@ sections: package's surface space is already y-down, matching the image's own top-down pixel row order). justification: | - Nearest-neighbor sampling composed through a single matrix keeps picture painting + Composing the mapping through a single matrix keeps picture painting consistent with this package's existing shape-transform/geometry conventions (see Phase 1c's ResolveShapeFrame) without introducing a second coordinate-mapping scheme just for images. A singular transform (for example a zero-area shape frame) has no diff --git a/docs/reqstream/canvas-net.yaml b/docs/reqstream/canvas-net.yaml index c55171445..5a4cc6651 100644 --- a/docs/reqstream/canvas-net.yaml +++ b/docs/reqstream/canvas-net.yaml @@ -97,6 +97,7 @@ sections: tests: - Resize_BmpCodec_RoundTrip - Resize_PngCodec_RoundTrip + - CanvasNet_SystemIntegration_Resize_ProducesRequestedSizeAndPreservesColor - id: CanvasNet-Lib-ImageResizeAlpha title: The library shall resample images in premultiplied alpha so transparent pixels leave no color fringe. @@ -108,6 +109,7 @@ sections: - CanvasNet-Canvas-ResizeAlpha tests: - Resize_AlphaEdge_HasNoColorFringe + - CanvasNet_SystemIntegration_ResizeAlphaEdge_HasNoColorFringe - id: CanvasNet-Lib-ImageResizeValidation title: The library shall reject invalid resize parameters with ArgumentOutOfRangeException. @@ -119,6 +121,7 @@ sections: - CanvasNet-Canvas-ResizeValidation tests: - Resize_InvalidDimensions_Throws + - CanvasNet_SystemIntegration_ResizeInvalidArguments_ThrowsArgumentOutOfRangeException - id: CanvasNet-Lib-ImageResizeToFit title: The library shall resize an image to fit a bounding box while preserving its aspect ratio. @@ -130,6 +133,8 @@ sections: - CanvasNet-Canvas-ResizeToFit tests: - ResizeToFit_KeepsAspectAndFitsBox + - CanvasNet_SystemIntegration_ResizeToFit_PreservesAspectRatio + - id: CanvasNet-Lib-CanvasPremultiply title: >- The library shall convert a pixel buffer, in place, between straight (unassociated) and diff --git a/docs/reqstream/canvas-net/canvas.yaml b/docs/reqstream/canvas-net/canvas.yaml index 317f750bf..36f18bb58 100644 --- a/docs/reqstream/canvas-net/canvas.yaml +++ b/docs/reqstream/canvas-net/canvas.yaml @@ -441,6 +441,7 @@ sections: - CanvasNet-Canvas-Surface-ResizeToFitInvalidBox tests: - ResizeToFit_KeepsAspectAndFitsBox + - id: CanvasNet-Canvas-PixelCompositing title: >- The Canvas subsystem shall provide a single-pixel Porter-Duff "over" alpha- diff --git a/docs/reqstream/canvas-net/drawing/tile-paint.yaml b/docs/reqstream/canvas-net/drawing/tile-paint.yaml index 47c92afbb..2d49b04e2 100644 --- a/docs/reqstream/canvas-net/drawing/tile-paint.yaml +++ b/docs/reqstream/canvas-net/drawing/tile-paint.yaml @@ -62,7 +62,8 @@ sections: TilePaintEvaluator shall map a device-space point back into pattern space via the tile paint's transform, wrap the result modulo the absolute value of the horizontal/vertical repeat pitch, and sample the tile surface by - nearest-neighbor at the corresponding wrapped tile-pixel coordinate, repeating + nearest-neighbor at the corresponding wrapped tile-pixel coordinate at about one + device pixel per tile pixel (see TilePaint-Smoothing otherwise), repeating identically for every subsequent tile repetition regardless of the sign of the repeat pitch. justification: | diff --git a/docs/user_guide/introduction.md b/docs/user_guide/introduction.md index e88ecbe7b..5fa771c37 100644 --- a/docs/user_guide/introduction.md +++ b/docs/user_guide/introduction.md @@ -240,6 +240,33 @@ public Surface ResizeToFit(int maxWidth, int maxHeight, ResamplingMode mode = Re Creates a new `Surface` with the aspect ratio preserved that fits inside the given box, enlarging or shrinking as needed (each dimension is at least one pixel). +**Parameters:** + +- `maxWidth` (int): The width of the bounding box. Must be between 1 and `Surface.MaxDimension`. +- `maxHeight` (int): The height of the bounding box. Must be between 1 and `Surface.MaxDimension`. +- `mode` (`ResamplingMode`): The reconstruction filter; see `ResamplingMode` below. Defaults to `Auto`. + +**Returns:** + +A new `Surface` whose aspect ratio matches the source and that fits inside the box. + +**Exceptions:** + +- `ArgumentOutOfRangeException`: Thrown when `maxWidth` or `maxHeight` is out of range or `mode` is + not defined. +- `ObjectDisposedException`: Thrown when the surface has been disposed. + +##### ResamplingMode + +The `ResamplingMode` enum selects the reconstruction filter for `Resize` and `ResizeToFit`: + +- `Auto`: `Area` on an axis that shrinks, `Bicubic` on an axis that enlarges, exact copy when unchanged. +- `Nearest`: point sampling; hard edges, but aliases and can drop thin features when shrinking. +- `Bilinear`: triangle filter; smooth, no overshoot. +- `Bicubic`: Catmull-Rom cubic; sharper, with clamped overshoot. +- `Lanczos3`: three-lobe windowed sinc; the sharpest smooth filter, with mild ringing. +- `Area`: exact area averaging; best for large reductions. + ##### PremultiplyAlpha ```csharp @@ -1047,7 +1074,10 @@ paint server, honoring `patternUnits`/`patternContentUnits`, `patternTransform`, `viewBox`/`preserveAspectRatio`, and `href`/`xlink:href` tile-content inheritance) - `image` elements (a base64-encoded `data:` URI in a supported raster format, decoded through that format's own existing codec and drawn into the element's own `x`/`y`/`width`/`height` placement -rect) - and best-effort, +rect) - `image-rendering` on an `image` (attribute, `style` declaration or stylesheet rule, inherited +from ancestors) selects the resampling filter: `pixelated`, `crisp-edges` and `optimizeSpeed` draw with +hard nearest-pixel edges, any other recognized value (for example `auto` or `optimizeQuality`) smooths, +and an unrecognized value is ignored so the inherited value applies - and best-effort, weight/style-aware `text` rendering against a caller-supplied dictionary of per-family font faces: either a single `TrueTypeFont` per family (the legacy shape), or a list of `SvgFontFace` values - each pairing a `TrueTypeFont` with the `font-weight`/`font-style` it represents - letting a caller @@ -1617,7 +1647,7 @@ upward, per the TrueType convention. Callers typically scale that path by the de and flip Y before rendering it through `PathFiller` or `PathStroker`. A glyf-flavored font's outline uses `LineTo`/`QuadraticBezierTo` segments; a CFF/OpenType font's outline uses `LineTo`/`CubicBezierTo` segments instead - callers that support both must handle both command -kinds (see Example 12 below). +kinds (see Example 13 below). ```csharp var font = TrueTypeFont.Load("font.ttf"); // also accepts a CFF/OpenType .otf file @@ -2364,7 +2394,7 @@ Console.WriteLine(cropped.Height); // Output: 2 Console.WriteLine(cropped[0, 0].G); // Output: 255 ``` -## Example 2b: Load, Crop, Resize and Save +## Example 3: Load, Crop, Resize and Save ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2376,7 +2406,7 @@ using var thumbnail = cropped.ResizeToFit(64, 64, ResamplingMode.Lanczos3); PngCodec.Save(thumbnail, "thumbnail.png"); ``` -## Example 3: BMP Load/Save +## Example 4: BMP Load/Save ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2396,7 +2426,7 @@ using var loaded24 = BmpCodec.Load("surface24.bmp"); Console.WriteLine(loaded24[0, 0].A); // Output: 255 ``` -## Example 4: PNG Load/Save +## Example 5: PNG Load/Save ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2416,7 +2446,7 @@ using var loadedRgb = PngCodec.Load("surface-rgb.png"); Console.WriteLine(loadedRgb[0, 0].A); // Output: 255 ``` -## Example 5: TIFF Load/Save +## Example 6: TIFF Load/Save ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2436,7 +2466,7 @@ using var loadedLzw = TiffCodec.Load("surface-lzw.tiff"); Console.WriteLine(loadedLzw[0, 0].B); // Output: 255 ``` -## Example 6: JPEG Load/Save +## Example 7: JPEG Load/Save ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2454,7 +2484,7 @@ Console.WriteLine(loaded[0, 0].A); // Output: 255 Console.WriteLine(Math.Abs(loaded[0, 0].R - surface[0, 0].R) <= 15); // Output: True ``` -## Example 7: Compositing a Semi-Transparent Color Over a Background +## Example 8: Compositing a Semi-Transparent Color Over a Background ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2472,7 +2502,7 @@ Console.WriteLine($"{result.R} {result.G} {result.B} {result.A}"); // Output: 12 // surface rather than a single constant color. ``` -## Example 8: Header-Only Probing Before Load (Decompression-Bomb Triage) +## Example 9: Header-Only Probing Before Load (Decompression-Bomb Triage) ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2544,7 +2574,7 @@ catch (InvalidDataException ex) } ``` -## Example 9: Filling a Vector Path +## Example 10: Filling a Vector Path ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2565,7 +2595,7 @@ PathFiller.Fill(canvas, triangle, new Rgba32(0, 128, 255, 255)); Console.WriteLine(canvas[32, 40].A); // Output: 255 (well inside the triangle) ``` -## Example 10: Stroking a Vector Path +## Example 11: Stroking a Vector Path ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2591,7 +2621,7 @@ PathFiller.Fill(canvas, strokedOutline, new Rgba32(255, 128, 0, 255)); Console.WriteLine(canvas[20, 32].A); // Output: 255 (on the centerline, inside one visible dash run) ``` -## Example 11: Filling a Vector Path with a Radial Gradient +## Example 12: Filling a Vector Path with a Radial Gradient ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2624,7 +2654,7 @@ PathFiller.Fill(canvas, square, gradient); Console.WriteLine(canvas[32, 32].A); // Output: 255 (at the gradient's center) ``` -## Example 12: Loading a TrueType Font and Filling a Glyph Outline +## Example 13: Loading a TrueType Font and Filling a Glyph Outline ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2684,7 +2714,7 @@ PathFiller.Fill(surface, canvasOutline, new Rgba32(20, 120, 255, 255)); Console.WriteLine(font.GetAdvanceWidth(glyphIndex)); ``` -## Example 13: Decoding and Rasterizing an SVG Document +## Example 14: Decoding and Rasterizing an SVG Document ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2710,7 +2740,7 @@ using var surfaceSvg = SvgCodec.Load(loadStream, 64, 64); Console.WriteLine(surfaceSvg[32, 32].A); // Output: 255 (well inside the filled rectangle) ``` -## Example 14: Building and Rendering a Chart +## Example 15: Building and Rendering a Chart ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2731,7 +2761,7 @@ using var chartSurface = ChartRenderer.Render(chart, 400, 300); Console.WriteLine($"{chartSurface.Width}x{chartSurface.Height}"); // Output: 400x300 ``` -## Example 15: Parsing and Rendering an OOXML Chart +## Example 16: Parsing and Rendering an OOXML Chart ```csharp using DemaConsulting.CanvasNet.Canvas; @@ -2785,7 +2815,7 @@ using var parsedChartSurface = ChartRenderer.Render(parsedChart, 400, 300); Console.WriteLine($"{parsedChartSurface.Width}x{parsedChartSurface.Height}"); // Output: 400x300 ``` -## Example 16: Opening and Rendering a Visio (.vsdx) Diagram +## Example 17: Opening and Rendering a Visio (.vsdx) Diagram ```csharp using DemaConsulting.CanvasNet.Canvas; diff --git a/docs/verification/canvas-net-svg/svg-codec.md b/docs/verification/canvas-net-svg/svg-codec.md index ccbf32f32..1cbcce90c 100644 --- a/docs/verification/canvas-net-svg/svg-codec.md +++ b/docs/verification/canvas-net-svg/svg-codec.md @@ -1489,6 +1489,11 @@ gray levels; with `image-rendering` `pixelated` or `crisp-edges` (attribute, sty stylesheet rule) it has only the two source levels. A 100x1 image with a one-pixel line shrunk to 17 pixels keeps its area-proportional ink. +`image-rendering` is inherited from an ancestor `g` (`Image_RenderingInheritedFromGroup_IsNearest`). +An unrecognized value (for example `bogus`) is ignored, so the element keeps inheriting the parent's +value (`Image_RenderingBogus_InheritsPixelatedFromParent`), while a recognized smooth keyword on the +element overrides a `pixelated` parent (`Image_RenderingSmoothKeyword_OverridesPixelatedParent`). +An `feImage` filter primitive always resamples smoothly and ignores `image-rendering`. Where the image tests above compare against smoothed output they use a small tolerance, because smoothing only changes pixels at or beside a source-pixel boundary; interior pixels are still asserted to their expected colors. diff --git a/docs/verification/canvas-net.md b/docs/verification/canvas-net.md index d5ff7e63f..9e8d0c4ce 100644 --- a/docs/verification/canvas-net.md +++ b/docs/verification/canvas-net.md @@ -46,6 +46,34 @@ Constructs a `Surface`, sets a distinct pixel within a region, crops that region source surface. Asserts the cropped result retains the pixel value captured at crop time, confirming that `Crop` produces an independent copy at the system level. +### Integration: Resize Produces Requested Size and Preserves Color + +**Test**: `CanvasNet_SystemIntegration_Resize_ProducesRequestedSizeAndPreservesColor` + +Resizes a solid-color `Surface` (shrinking one axis, enlarging the other) with every +`ResamplingMode`. Asserts the requested dimensions and that the solid color and alpha are preserved, +confirming the public resampling API at the system level. + +### Integration: ResizeToFit Preserves Aspect Ratio + +**Test**: `CanvasNet_SystemIntegration_ResizeToFit_PreservesAspectRatio` + +Fits a 100x50 `Surface` into a 20x20 box. Asserts a 20x10 result (width-limited, aspect preserved). + +### Integration: Resize Alpha Edge Has No Color Fringe + +**Test**: `CanvasNet_SystemIntegration_ResizeAlphaEdge_HasNoColorFringe` + +Enlarges a row of opaque red beside transparent black with the bicubic filter. Asserts every pixel +with nonzero alpha is still red, confirming resampling in premultiplied alpha. + +### Integration: Resize Invalid Arguments Throw ArgumentOutOfRangeException + +**Test**: `CanvasNet_SystemIntegration_ResizeInvalidArguments_ThrowsArgumentOutOfRangeException` + +Calls `Resize` and `ResizeToFit` with a non-positive width/height, an oversized height, an undefined +mode and an invalid box. Asserts `ArgumentOutOfRangeException` carrying the offending parameter name. + ### Integration: BMP Save Then Load Returns Expected Pixel **Test**: `CanvasNet_SystemIntegration_BmpSaveThenLoad_ReturnsExpectedPixel` diff --git a/docs/verification/canvas-net/canvas.md b/docs/verification/canvas-net/canvas.md index 8428d4d5a..9bf151efa 100644 --- a/docs/verification/canvas-net/canvas.md +++ b/docs/verification/canvas-net/canvas.md @@ -7,7 +7,9 @@ This document describes the subsystem-level verification strategy for the `Canva The `Canvas` subsystem is verified entirely through its constituent unit's tests: the `Surface` unit's tests (see _Surface Unit Verification Design_, `canvas/surface.md`) exercise every public -constructor, property, indexer, span accessor, and the `Crop` method in isolation. No separate +constructor, property, indexer, span accessor, the `Crop` method, and the `Resize`/`ResizeToFit` +resampling API (requirements `CanvasNet-Canvas-Resize`, `-ResizeAlpha`, `-ResizeValidation` and +`-ResizeToFit`) in isolation. No separate subsystem-level tests exist; the subsystem-level requirements reuse the same `Surface` unit tests as verification evidence, since the `Canvas` subsystem currently contains exactly one unit with externally observable behavior. @@ -29,6 +31,8 @@ exception. The `Canvas` subsystem currently contains exactly one unit with externally observable behavior, so its test scenarios are exactly those named in _Surface Unit Verification Design_ (`canvas/surface.md`): construction and invariants, indexer and span-accessor boundary conditions, -`Crop` normal/boundary/error paths, `PremultiplyAlpha`/`UnpremultiplyAlpha`/`CompositeOver` +`Crop` normal/boundary/error paths, `Resize`/`ResizeToFit` size, filter, premultiplied-alpha (no color +fringe) and argument-validation behavior (`CanvasNet-Canvas-Resize*`), +`PremultiplyAlpha`/`UnpremultiplyAlpha`/`CompositeOver` compositing correctness, and `Dispose` idempotency. No subsystem-level test exists beyond this unit's own coverage. diff --git a/docs/verification/canvas-net/canvas/surface.md b/docs/verification/canvas-net/canvas/surface.md index 3ee246ec9..3a7f2b1ec 100644 --- a/docs/verification/canvas-net/canvas/surface.md +++ b/docs/verification/canvas-net/canvas/surface.md @@ -494,10 +494,15 @@ A zero or oversized box dimension reports `maxWidth` or `maxHeight`. ##### CanvasNet-Canvas-Surface-DeviceResample: Device Window Resampling **Tests**: `TryResampleToDevice_RotatedMatrix_ReturnsFalse`, `TryResampleToDevice_AxisAligned_ReturnsWindowAtOrigin`, -`TryResampleToDevice_OffScreen_ReturnsTrueWithNullWindow`, `BoxReduce_MatchesAreaResize` +`TryResampleToDevice_OffScreen_ReturnsTrueWithNullWindow`, `BoxReduce_MatchesAreaResize`, +`BoxReduce_NonDivisibleSize_AveragesOnlyCoveredPixelsInPartialBlock`, +`BoxReduce_NonDivisibleSizeWithAlpha_PartialBlockUsesCoveredPixelsOnly` Rotation is declined, an axis-aligned placement yields a window of the expected size and origin, an -off-screen placement yields no window, and `BoxReduce` equals an `Area` resize. +off-screen placement yields no window, and `BoxReduce` equals an `Area` resize. When the source size +is not divisible by the block size, the trailing partial block is averaged over only the source +pixels it actually covers (including, with alpha, in premultiplied space), so edge pixels are not +darkened or made transparent by phantom pixels. ##### CanvasNet-Canvas-Surface-WrappedBilinear: Wrap-Around Bilinear Sampling diff --git a/docs/verification/canvas-net/drawing/tile-paint.md b/docs/verification/canvas-net/drawing/tile-paint.md index 15663b33c..abedcf291 100644 --- a/docs/verification/canvas-net/drawing/tile-paint.md +++ b/docs/verification/canvas-net/drawing/tile-paint.md @@ -97,14 +97,18 @@ checkerboard tile produces both of the tile's own colors in the filled result; t reject a null surface, path, or tile paint argument; and they honor the same empty-input/ no-polygons no-op behavior already established for the solid-color and gradient overloads. -##### TilePaintEvaluator: Magnified and Minified Tiles +##### CanvasNet-Drawing-TilePaint-Smoothing: Magnified and Minified Tiles **Tests**: `EvaluateRow_MagnifiedTile_IsSmooth`, `CreatePlan_OneToOneTile_IsNeitherMagnifiedNorMinified`, -`EvaluateRow_MinifiedTile_AveragesColors` +`EvaluateRow_MinifiedTile_AveragesColors`, `ClassifyTileScale_MixedAndSingleAxisCases`, +`CreatePlan_MixedMagnifiedAndMinifiedTile_IsMagnifiedOnly` A tile enlarged 4x is sampled bilinearly (many distinct values), a 1:1 tile keeps exact lookup with no owned minified copy, and a tile shrunk to a quarter is replaced by an area-averaged copy whose colors -average the checkerboard. +average the checkerboard. The shared classification handles mixed and single-axis cases: a tile +magnified on one axis and minified on the other is classified as magnified only (bilinear, no +minified copy), and a tile scaled on a single axis while the other stays at about 1:1 is classified +by the scaled axis alone. #### Complexity Verification Policy diff --git a/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs b/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs index 5dcf5191e..5d5f053df 100644 --- a/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs +++ b/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs @@ -929,7 +929,9 @@ private static Rgba32 SamplesToColor(PdfColorSpace colorSpace, byte[] decoded, i /// inverse-mapped with bilinear sampling. A non-invertible (degenerate) silently paints /// nothing, rather than throwing. Per the PDF specification's image-space convention, /// image sample row 0 is the top of the unit square (the opposite of - /// user-space's y-up convention): row = floor((1 - v) * image.Height). Each sampled + /// user-space's y-up convention). The flip is folded into the pixel-to-device matrix handed + /// to TryResampleToDevice; the explicit row = floor((1 - v) * image.Height) + /// formula applies only to the rotated/skewed fallback. Each sampled /// source pixel is alpha-blended "over" the existing destination pixel via /// (standard Porter-Duff "over" compositing) rather /// than overwriting it outright, so a source pixel with a non-opaque (including fully diff --git a/src/DemaConsulting.CanvasNet/Canvas/ResamplingMode.cs b/src/DemaConsulting.CanvasNet/Canvas/ResamplingMode.cs index 1415626ff..87dce952d 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/ResamplingMode.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/ResamplingMode.cs @@ -5,8 +5,11 @@ namespace DemaConsulting.CanvasNet.Canvas; /// . /// /// -/// Every mode other than works in premultiplied alpha, clamps its -/// result to the valid byte range, and clamps at the image edges. The smooth modes +/// Every mode other than works in premultiplied alpha and clamps its +/// result to the valid byte range. The smooth filters (, +/// , ) clamp at the image edges (edge pixels are +/// replicated), whereas renormalizes its weights over the source pixels +/// actually covered. The smooth modes /// (, , ) widen their /// kernel by the reduction ratio when an axis is shrunk, so they act as a true prefilter /// and do not drop thin features the way point sampling does. diff --git a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs index c88bfa36a..4d375e2ab 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs @@ -3,11 +3,16 @@ namespace DemaConsulting.CanvasNet.Canvas; /// -/// Internal image-resampling helpers owned by the unit: an area-average -/// (box) prefilter used when an image is shrunk on screen, and a bilinear sampler used to -/// read the prefiltered result. +/// Internal image-resampling helpers owned by the unit. The full +/// separable resampling engine (filter weights, per-axis passes) lives in +/// SurfaceResampler.Engine.cs and backs and +/// ; this file holds the box-reduction prefilter and the +/// bilinear sampler used for rotated or skewed placements. /// /// +/// The engine also provides TryResampleToDevice (single-pass resample of an image +/// directly into its axis-aligned device rectangle) and the tile-pattern helpers +/// (ClassifyTileScale, SampleBilinearWrapped). /// Point sampling a source image while shrinking it drops thin features (a one-pixel line in /// a 2.6:1 reduction is hit by roughly one destination sample in 2.6). The prefilter averages /// integer-sized blocks of source pixels (the rounded reduction ratio) once per draw (a single diff --git a/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs b/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs index e7d968393..cf690cc23 100644 --- a/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs @@ -55,6 +55,99 @@ public void CanvasNet_SystemIntegration_CanvasCrop_ReturnsIndependentSubRegion() Assert.Equal(new Rgba32(1, 2, 3, 4), cropped[0, 0]); } + /// + /// Proves that the system can resample a Surface to a new size through the public API + /// with each reconstruction filter, producing the requested dimensions and preserving a + /// solid color. + /// + [Fact] + public void CanvasNet_SystemIntegration_Resize_ProducesRequestedSizeAndPreservesColor() + { + // Arrange: a solid-color surface + using var source = new Surface(6, 4); + source.Clear(new Rgba32(40, 80, 120, 255)); + + foreach (var mode in new[] { ResamplingMode.Auto, ResamplingMode.Nearest, ResamplingMode.Bilinear, ResamplingMode.Bicubic, ResamplingMode.Area }) + { + // Act: shrink one axis and enlarge the other + using var result = source.Resize(3, 8, mode); + + // Assert: requested size, solid color preserved + Assert.Equal(3, result.Width); + Assert.Equal(8, result.Height); + Assert.InRange(result[1, 4].R, 39, 41); + Assert.InRange(result[1, 4].G, 79, 81); + Assert.InRange(result[1, 4].B, 119, 121); + Assert.Equal(255, result[1, 4].A); + } + } + + /// + /// Proves that the system can resize a Surface to fit a bounding box while preserving + /// the aspect ratio. + /// + [Fact] + public void CanvasNet_SystemIntegration_ResizeToFit_PreservesAspectRatio() + { + // Arrange: a 100x50 surface and a 20x20 bounding box + using var source = new Surface(100, 50); + + // Act + using var result = source.ResizeToFit(20, 20); + + // Assert: width-limited, 2:1 aspect preserved + Assert.Equal(20, result.Width); + Assert.Equal(10, result.Height); + } + + /// + /// Proves that the system resamples in premultiplied alpha so that opaque pixels next to + /// transparent pixels leave no color fringe. + /// + [Fact] + public void CanvasNet_SystemIntegration_ResizeAlphaEdge_HasNoColorFringe() + { + // Arrange: opaque red on the left, transparent black on the right + using var source = new Surface(4, 1); + source[0, 0] = new Rgba32(255, 0, 0, 255); + source[1, 0] = new Rgba32(255, 0, 0, 255); + source[2, 0] = new Rgba32(0, 0, 0, 0); + source[3, 0] = new Rgba32(0, 0, 0, 0); + + // Act + using var result = source.Resize(9, 1, ResamplingMode.Bicubic); + + // Assert: every visible pixel is still red + for (var x = 0; x < 9; x++) + { + var p = result[x, 0]; + if (p.A > 0) + { + Assert.InRange(p.R, 250, 255); + Assert.InRange(p.G, 0, 5); + Assert.InRange(p.B, 0, 5); + } + } + } + + /// + /// Proves that the system rejects invalid resize parameters (non-positive or oversized + /// dimensions, undefined mode, invalid fit box) with ArgumentOutOfRangeException. + /// + [Fact] + public void CanvasNet_SystemIntegration_ResizeInvalidArguments_ThrowsArgumentOutOfRangeException() + { + // Arrange + using var source = new Surface(4, 4); + + // Act and Assert + Assert.Equal("width", Assert.Throws(() => source.Resize(0, 2)).ParamName); + Assert.Equal("height", Assert.Throws(() => source.Resize(2, Surface.MaxDimension + 1)).ParamName); + Assert.Equal("mode", Assert.Throws(() => source.Resize(2, 2, (ResamplingMode)99)).ParamName); + Assert.Equal("maxWidth", Assert.Throws(() => source.ResizeToFit(0, 5)).ParamName); + Assert.Equal("maxHeight", Assert.Throws(() => source.ResizeToFit(5, 0)).ParamName); + } + /// /// Proves that the system can fill an entire Surface with a constant color through the /// public API (Surface.Clear), overwriting pre-existing pixel data, and that the From 3ad0dbdc527d048f1052443ac356b128e693e0a3 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 13:35:35 -0400 Subject: [PATCH 07/16] Bound resampler tap work, trim clipped scanline windows, make glyph cache cap atomic Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/canvas-net/canvas/surface.md | 5 +- docs/design/canvas-net/drawing/path-filler.md | 4 +- .../design/canvas-net/fonts/true-type-font.md | 3 +- docs/reqstream/canvas-net/canvas/surface.yaml | 3 + .../canvas-net/drawing/path-filler.yaml | 1 + .../canvas-net/fonts/true-type-font.yaml | 1 + .../verification/canvas-net/canvas/surface.md | 8 +- .../canvas-net/drawing/path-filler.md | 1 + .../canvas-net/fonts/true-type-font.md | 6 +- .../Canvas/SurfaceResampler.Engine.cs | 64 +++++++++++++-- .../Drawing/ScanlineRasterizer.cs | 25 ++++-- .../Fonts/TrueTypeFont.cs | 16 +++- .../Canvas/SurfaceResamplerTests.cs | 78 +++++++++++++++++++ .../Drawing/ScanlineRasterizerTests.cs | 56 +++++++++++++ .../Fonts/TrueTypeFontTests.cs | 33 ++++++++ 15 files changed, 284 insertions(+), 20 deletions(-) diff --git a/docs/design/canvas-net/canvas/surface.md b/docs/design/canvas-net/canvas/surface.md index 539fd77a4..76f198e9f 100644 --- a/docs/design/canvas-net/canvas/surface.md +++ b/docs/design/canvas-net/canvas/surface.md @@ -499,7 +499,10 @@ images smoothly. `start + (o + 0.5) * extent / outDim` (a negative extent flips the axis) and builds, per axis, a table of tap indices and normalized weights for the chosen filter. When shrinking, the kernel support is multiplied by the reduction ratio so every source pixel contributes (thin lines cannot be skipped). -Taps outside the image fold into the edge pixel, except `Area`, which drops them and renormalizes. An +Taps outside the image fold into the edge pixel, except `Area`, which drops them and renormalizes. Weight +work is bounded by the source size, not the filter footprint (an extreme scale from a crafted placement can +imply about 1e9 taps): only the in-image intersection is iterated tap by tap, and each folded out-of-image +tail is summed exactly up to 1024 taps and otherwise by a 1024-bucket midpoint rule. An axis with scale 1 and an integer start is an exact copy. Work is done in premultiplied alpha as two separable passes: a horizontal pass over strips of columns into a float intermediate sized by an 8 MiB budget, then a vertical pass using `TensorPrimitives` multiply-add. Results are clamped to diff --git a/docs/design/canvas-net/drawing/path-filler.md b/docs/design/canvas-net/drawing/path-filler.md index 241e16cb3..4b4e3b9f0 100644 --- a/docs/design/canvas-net/drawing/path-filler.md +++ b/docs/design/canvas-net/drawing/path-filler.md @@ -239,7 +239,9 @@ approximation converging only as the sample count grows. `Surface.CompositeOverSpan`, so the trimmed and skipped columns/rows would not have changed any pixel; the result is pixel-identical to compositing the full row. The dense clip multiply (`ApplyClip`) operates on the same window and uses `TensorPrimitives.Multiply`, which is - bit-identical to the scalar float multiply. + bit-identical to the scalar float multiply. After the clip multiply (and on the multi-breakpoint + `EvenOdd` path, which starts from a full-row window) `ApplyClip` trims again, so zero coverage + produced by the clip never reaches the compositor; the window length becomes 0 for an empty row. - **Why this handles crossing/self-intersecting edges correctly, not merely assumed absent**: a prior revision of this algorithm split each row into sub-intervals at every edge's own start/end `y`, sorted the edges spanning each sub-interval by `x` once, and relied on that diff --git a/docs/design/canvas-net/fonts/true-type-font.md b/docs/design/canvas-net/fonts/true-type-font.md index 61baa414e..4383af35d 100644 --- a/docs/design/canvas-net/fonts/true-type-font.md +++ b/docs/design/canvas-net/fonts/true-type-font.md @@ -649,7 +649,8 @@ charstring. references an out-of-range subroutine index **Memoization.** Decoded outlines are cached per font in a `ConcurrentDictionary` (at -most 4096 entries; once full, further glyphs are decoded on demand but not stored). `Path` is +most 4096 entries; once full, further glyphs are decoded on demand but not stored; admission is +checked and inserted under a lock so the cap is strict under concurrency). `Path` is immutable, so every caller shares one instance. A decode that throws is never cached, so a malformed glyph reports its error on every call. The cache is per `TrueTypeFont` instance and the PDF renderer builds fonts per render, so it benefits repeated glyphs within one page; diff --git a/docs/reqstream/canvas-net/canvas/surface.yaml b/docs/reqstream/canvas-net/canvas/surface.yaml index c195c393a..aa0f00129 100644 --- a/docs/reqstream/canvas-net/canvas/surface.yaml +++ b/docs/reqstream/canvas-net/canvas/surface.yaml @@ -494,6 +494,9 @@ sections: tests: - Resize_ExtremeAspectChange_ProducesExpectedShape - Resample_TinyIntermediateBudget_MatchesDefaultBudget + - Resample_ExtremeReduction_CompletesWithSaneResult + - TryResampleToDevice_TinyScale_CompletesWithSaneWindow + - Resample_NormalScaleEdgeFolding_KeepsConstantImageConstant - id: CanvasNet-Canvas-Surface-ResizePooledBuffers title: >- diff --git a/docs/reqstream/canvas-net/drawing/path-filler.yaml b/docs/reqstream/canvas-net/drawing/path-filler.yaml index 63018da46..2d54cc06f 100644 --- a/docs/reqstream/canvas-net/drawing/path-filler.yaml +++ b/docs/reqstream/canvas-net/drawing/path-filler.yaml @@ -291,6 +291,7 @@ sections: - ScanlineRasterizer_AccumulateCoverageMask_Shapes_MatchesExactPixelAreaReference - ScanlineRasterizer_Fill_Shapes_PixelExactAgainstFullWidthCompositeReference - ScanlineRasterizer_Fill_DenseClipMask_PixelExactAgainstCoverageTimesClipReference + - ScanlineRasterizer_Fill_DenseClipZeroingWindow_MatchesCoverageTimesClipForAllShapes - ScanlineRasterizer_Fill_ConstantGradientAndTile_PixelExactAgainstSolid - id: CanvasNet-Drawing-PathFiller-GradientFill diff --git a/docs/reqstream/canvas-net/fonts/true-type-font.yaml b/docs/reqstream/canvas-net/fonts/true-type-font.yaml index 9e0be6d66..9040f5f0d 100644 --- a/docs/reqstream/canvas-net/fonts/true-type-font.yaml +++ b/docs/reqstream/canvas-net/fonts/true-type-font.yaml @@ -341,6 +341,7 @@ sections: tests: - TrueTypeFont_GetGlyphOutline_RepeatedCalls_ReturnMemoizedOutlineEqualToFreshDecode - TrueTypeFont_GetGlyphOutline_MalformedGlyph_ThrowsOnEveryCall + - TrueTypeFont_GetGlyphOutline_ConcurrentDistinctGlyphs_NeverExceedsCacheCap - id: CanvasNet-Fonts-TrueTypeFont-GlyphIndexValidation title: >- diff --git a/docs/verification/canvas-net/canvas/surface.md b/docs/verification/canvas-net/canvas/surface.md index 3a7f2b1ec..ef06fcafc 100644 --- a/docs/verification/canvas-net/canvas/surface.md +++ b/docs/verification/canvas-net/canvas/surface.md @@ -464,11 +464,15 @@ reports `mode`; a disposed surface throws `ObjectDisposedException`. ##### CanvasNet-Canvas-Surface-ResizeBoundedMemory: Extreme Aspect Ratios -**Tests**: `Resize_ExtremeAspectChange_ProducesExpectedShape`, `Resample_TinyIntermediateBudget_MatchesDefaultBudget` +**Tests**: `Resize_ExtremeAspectChange_ProducesExpectedShape`, `Resample_TinyIntermediateBudget_MatchesDefaultBudget`, +`Resample_ExtremeReduction_CompletesWithSaneResult`, `TryResampleToDevice_TinyScale_CompletesWithSaneWindow`, +`Resample_NormalScaleEdgeFolding_KeepsConstantImageConstant` An 8192x1 surface resizes to 1x8192 with the expected content. Resampling with intermediate budgets of 1 and 64 bytes (forcing the multi-strip path) produces output identical to the default budget for Bilinear, -Lanczos3 and Area. +Lanczos3 and Area. A source mapped at an extreme scale (one source pixel covering about 1e-9 device +pixels, i.e. a filter footprint of about 1e9 taps) resamples with work bounded by the source size and yields the +uniform source color for every filter; a constant image magnified past its edges stays exactly constant. ##### CanvasNet-Canvas-Surface-ResizePooledBuffers: Recycled Scratch Buffers Do Not Leak State diff --git a/docs/verification/canvas-net/drawing/path-filler.md b/docs/verification/canvas-net/drawing/path-filler.md index 4f1664787..e345b0f5c 100644 --- a/docs/verification/canvas-net/drawing/path-filler.md +++ b/docs/verification/canvas-net/drawing/path-filler.md @@ -285,6 +285,7 @@ remains completely unmodified in both cases, without throwing. **Tests**: `ScanlineRasterizer_AccumulateCoverageMask_Shapes_MatchesExactPixelAreaReference`, `ScanlineRasterizer_Fill_Shapes_PixelExactAgainstFullWidthCompositeReference`, `ScanlineRasterizer_Fill_DenseClipMask_PixelExactAgainstCoverageTimesClipReference`, +`ScanlineRasterizer_Fill_DenseClipZeroingWindow_MatchesCoverageTimesClipForAllShapes`, `ScanlineRasterizer_Fill_ConstantGradientAndTile_PixelExactAgainstSolid` Each is a theory over seven shapes (rectangle, triangle, slanted parallelogram, shape with a diff --git a/docs/verification/canvas-net/fonts/true-type-font.md b/docs/verification/canvas-net/fonts/true-type-font.md index dea17f2f9..c2e57f242 100644 --- a/docs/verification/canvas-net/fonts/true-type-font.md +++ b/docs/verification/canvas-net/fonts/true-type-font.md @@ -259,11 +259,13 @@ Covers out-of-range referenced glyphs, truncated glyph bytes, invalid contour co ##### CanvasNet-Fonts-TrueTypeFont-GlyphOutlineMemoized: Outlines Are Memoized Without Changing Results **Tests**: `TrueTypeFont_GetGlyphOutline_RepeatedCalls_ReturnMemoizedOutlineEqualToFreshDecode`, -`TrueTypeFont_GetGlyphOutline_MalformedGlyph_ThrowsOnEveryCall` +`TrueTypeFont_GetGlyphOutline_MalformedGlyph_ThrowsOnEveryCall`, +`TrueTypeFont_GetGlyphOutline_ConcurrentDistinctGlyphs_NeverExceedsCacheCap` Asserts two calls on one font return the same instance, that its subpaths, start points, closed flags and every command equal those decoded by a second font that has cached nothing, and that a -glyph with an invalid contour count throws `InvalidDataException` on each call. No timing is asserted. +glyph with an invalid contour count throws `InvalidDataException` on each call. A 6000-glyph font +requested concurrently from eight threads never holds more than 4096 cached outlines. No timing is asserted. ##### CanvasNet-Fonts-TrueTypeFont-GlyphIndexValidation: `GetGlyphOutline` Rejects Out-of-Range Glyph Indices diff --git a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs index 48ab70a43..dff9c1dac 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs @@ -40,6 +40,9 @@ internal static partial class SurfaceResampler /// Floats stored per intermediate pixel (premultiplied R, G, B and alpha). private const int Channels = 4; + /// The most out-of-image taps summed exactly per folded edge tail; longer tails are sampled. + private const int MaxExactTailTaps = 1024; + /// Per-axis weight table: for each output index a first source index, a tap count and the weights. /// First source index of each output pixel's taps. /// Number of consecutive taps of each output pixel. @@ -286,16 +289,26 @@ private static AxisWeights BuildAxis(int sourceSize, double start, double extent var first = firsts[o]; var w = buffer.AsSpan(0, count); w.Clear(); - for (var i = los[o]; i <= his[o]; i++) + var inLo = Math.Max(los[o], 0); + var inHi = Math.Min(his[o], last); + for (var i = inLo; i <= inHi; i++) + { + w[(int)i - first] += Weight(mode, i + 0.5 - c, scale); + } + + // Area drops out-of-image taps (renormalized); other filters fold them into the edge pixel. + // The folded tails can be enormous for extreme scales, so their work is bounded. + if (mode != ResamplingMode.Area) { - // Area drops out-of-image taps (renormalized below); other filters fold them into the edge pixel - if (mode == ResamplingMode.Area && (i < 0 || i > last)) + if (los[o] < 0) { - continue; + w[0 - first] += TailWeight(mode, los[o], Math.Min(his[o], -1L), c, scale); } - var index = (int)Math.Clamp(i, 0, last); - w[index - first] += Weight(mode, i + 0.5 - c, scale); + if (his[o] > last) + { + w[last - first] += TailWeight(mode, Math.Max(los[o], (long)last + 1), his[o], c, scale); + } } var sum = 0.0; @@ -322,6 +335,45 @@ private static AxisWeights BuildAxis(int sourceSize, double start, double extent return new AxisWeights(firsts, counts, offsets, weights, minIndex, maxIndex); } + /// + /// Sums the filter weights of the taps .. (all outside + /// the image). Short tails are summed exactly; longer ones are sampled at a bounded number of + /// evenly spaced taps so the work never depends on the footprint size. + /// + private static double TailWeight(ResamplingMode mode, long from, long to, double c, double scale) + { + if (to < from) + { + return 0.0; + } + + var n = to - from + 1; + if (n <= MaxExactTailTaps) + { + var exact = 0.0; + for (var i = from; i <= to; i++) + { + exact += Weight(mode, i + 0.5 - c, scale); + } + + return exact; + } + + // Midpoint rule over MaxExactTailTaps equal buckets, each bucket weighted by its tap count + var sum = 0.0; + for (var b = 0; b < MaxExactTailTaps; b++) + { + var b0 = from + (n * b / MaxExactTailTaps); + var b1 = from + (n * (b + 1) / MaxExactTailTaps); + if (b1 > b0) + { + sum += (b1 - b0) * Weight(mode, ((b0 + b1 - 1) / 2.0) + 0.5 - c, scale); + } + } + + return sum; + } + /// /// Evaluates the filter weight of one source pixel. /// diff --git a/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs b/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs index 87c732f20..23e9b26cd 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs @@ -890,14 +890,29 @@ private void ApplyClip(int y) } var dense = _clip.GetDenseRow(y, _clipMinX + _spanStart, _spanLength); - if (dense.IsEmpty) + if (!dense.IsEmpty) { - return; + // IEEE single-precision multiply, element-wise: bit-identical to the scalar loop. + var row = _rowCoverage.AsSpan(_spanStart, _spanLength); + TensorPrimitives.Multiply(row, dense, row); } - // IEEE single-precision multiply, element-wise: bit-identical to the scalar loop. - var row = _rowCoverage.AsSpan(_spanStart, _spanLength); - TensorPrimitives.Multiply(row, dense, row); + // The clip (or, on the multi-breakpoint path, the full-row window) may have zeroed either end (or all) of the window; zero coverage means + // "untouched" to the compositor, so trim it out (length 0 when the row is empty). + var lo = _spanStart; + var end = _spanStart + _spanLength; + while (lo < end && !(_rowCoverage[lo] > 0f)) + { + lo++; + } + + while (end > lo && !(_rowCoverage[end - 1] > 0f)) + { + end--; + } + + _spanStart = lo; + _spanLength = end - lo; } /// diff --git a/src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs b/src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs index 79802479e..58be2c125 100644 --- a/src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs +++ b/src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs @@ -138,6 +138,9 @@ public sealed class TrueTypeFont /// private readonly ConcurrentDictionary _outlineCache = new(); + /// Serializes cache admission so is a strict cap. + private readonly object _outlineCacheLock = new(); + /// /// The number of font design units per em, from head.unitsPerEm. /// @@ -508,9 +511,18 @@ public Path GetGlyphOutline(int glyphIndex) // A malformed glyph throws here and is therefore never cached: every call reports it again. var outline = _glyphs.GetGlyphOutline(glyphIndex); - if (_outlineCache.Count < MaxCachedOutlines) + // Admission is atomic (check + insert under a lock) so concurrent threads can never exceed the cap + lock (_outlineCacheLock) { - outline = _outlineCache.GetOrAdd(glyphIndex, outline); + if (_outlineCache.TryGetValue(glyphIndex, out cached)) + { + return cached; + } + + if (_outlineCache.Count < MaxCachedOutlines) + { + _outlineCache[glyphIndex] = outline; + } } return outline; diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs index 4ce719979..81fa2f553 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs @@ -338,6 +338,84 @@ public void Resample_RepeatedAfterDifferentSizes_IsIdenticalDespiteRecycledBuffe } } + /// + /// An extreme pixel scale (a crafted placement where one source pixel covers ~1e-9 device + /// pixels) must complete with work bounded by the source size and give a sane result: + /// the output is the (uniform) source color for every filter. + /// + [Theory] + [InlineData(ResamplingMode.Area)] + [InlineData(ResamplingMode.Bilinear)] + [InlineData(ResamplingMode.Bicubic)] + [InlineData(ResamplingMode.Lanczos3)] + public void Resample_ExtremeReduction_CompletesWithSaneResult(ResamplingMode mode) + { + using var source = new Surface(5, 4); + for (var y = 0; y < 4; y++) + { + for (var x = 0; x < 5; x++) + { + source[x, y] = new Rgba32(90, 150, 210, 255); + } + } + + using var result = SurfaceResampler.Resample(source, 0, 1e9, 0, 1e9, 2, 2, mode); + + Assert.Equal(2, result.Width); + for (var y = 0; y < 2; y++) + { + for (var x = 0; x < 2; x++) + { + var p = result[x, y]; + Assert.InRange(p.R, 89, 91); + Assert.InRange(p.G, 149, 151); + Assert.InRange(p.B, 209, 211); + } + } + } + + /// A tiny image placement via TryResampleToDevice completes with a sane window. + [Fact] + public void TryResampleToDevice_TinyScale_CompletesWithSaneWindow() + { + using var source = new Surface(8, 8); + for (var y = 0; y < 8; y++) + { + for (var x = 0; x < 8; x++) + { + source[x, y] = new Rgba32(200, 100, 50, 255); + } + } + + var m = new Matrix3x2(1e-9f, 0, 0, 1e-9f, 0.2f, 0.2f); + Assert.True(SurfaceResampler.TryResampleToDevice(source, m, 10, 10, ResamplingMode.Lanczos3, out var window, out _, out _)); + window?.Dispose(); + } + + /// Folding long out-of-image tails keeps results identical to a direct sum for normal scales. + [Fact] + public void Resample_NormalScaleEdgeFolding_KeepsConstantImageConstant() + { + using var source = new Surface(6, 6); + for (var y = 0; y < 6; y++) + { + for (var x = 0; x < 6; x++) + { + source[x, y] = new Rgba32(40, 80, 120, 255); + } + } + + // Magnified view whose Lanczos support extends beyond both edges + using var result = SurfaceResampler.Resample(source, -3, 12, -3, 12, 30, 30, ResamplingMode.Lanczos3); + for (var y = 0; y < 30; y++) + { + for (var x = 0; x < 30; x++) + { + Assert.Equal(new Rgba32(40, 80, 120, 255), result[x, y]); + } + } + } + /// Wrapped bilinear sampling wraps across the tile edge. [Fact] public void SampleBilinearWrapped_AtEdge_BlendsWithOppositeSide() diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs index 5393b3800..dc62a928c 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs @@ -1151,6 +1151,62 @@ public void ScanlineRasterizer_Fill_Shapes_PixelExactAgainstFullWidthCompositeRe AssertSurfacesEqual(expected, actual); } + /// + /// Proves that a dense clip that zeroes part or all of a row's coverage window (so the + /// window is trimmed after the clip multiply) leaves pixel output identical to + /// coverage times clip, for both fill rules (EvenOdd includes the multi-breakpoint path). + /// + [Theory] + [InlineData("small", true)] + [InlineData("small", false)] + [InlineData("outside", true)] + [InlineData("outside", false)] + public void ScanlineRasterizer_Fill_DenseClipZeroingWindow_MatchesCoverageTimesClipForAllShapes(string clipKind, bool evenOdd) + { + var rule = evenOdd ? FillRule.EvenOdd : FillRule.NonZero; + var color = new Rgba32(20, 160, 230, 255); + var bounds = new Rect(0, 0, RefWidth, RefHeight); + var clipPath = clipKind == "small" + ? new PathBuilder().MoveTo(new Vector2(20.4f, 10.2f)).LineTo(new Vector2(30.8f, 12.4f)) + .LineTo(new Vector2(24.1f, 20.6f)).Close().Build() + : new PathBuilder().MoveTo(new Vector2(RefWidth - 3.5f, RefHeight - 3.5f)).LineTo(new Vector2(RefWidth - 1.5f, RefHeight - 3.5f)) + .LineTo(new Vector2(RefWidth - 2.5f, RefHeight - 1.5f)).Close().Build(); + var clip = ClipMask.FromPathDense(clipPath, FillRule.NonZero, RefWidth, RefHeight); + + foreach (var shape in ShapeNames.Select(d => d.Data)) + { + var (polygons, _) = BuildShape(shape); + var mask = new float[RefWidth * RefHeight]; + ScanlineRasterizer.AccumulateCoverageMask(polygons, rule, bounds, mask, RefWidth, 0, 0); + using var expected = PatternBackground(); + using var actual = PatternBackground(); + var row = new float[RefWidth]; + for (var y = 0; y < RefHeight; y++) + { + for (var x = 0; x < RefWidth; x++) + { + row[x] = mask[(y * RefWidth) + x] * clip.GetCoverage(x, y); + } + + expected.CompositeOverSpan(y, 0, row, color); + } + + ScanlineRasterizer.Fill(actual, polygons, color, rule, bounds, clip); + + for (var y = 0; y < RefHeight; y++) + { + for (var x = 0; x < RefWidth; x++) + { + var e = expected[x, y]; + var a = actual[x, y]; + Assert.True( + Math.Abs(e.R - a.R) <= 1 && Math.Abs(e.G - a.G) <= 1 && Math.Abs(e.B - a.B) <= 1 && Math.Abs(e.A - a.A) <= 1, + $"{shape} pixel ({x},{y}): expected {e}, actual {a}"); + } + } + } + } + /// /// Proves a fill with a dense (non-rectangular) clip mask is pixel-exact against the /// product of the unclipped coverage and the clip's own per-pixel coverage. diff --git a/test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs b/test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs index c80466256..429c862b9 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs @@ -354,6 +354,39 @@ public void TrueTypeFont_GetGlyphOutline_RepeatedCalls_ReturnMemoizedOutlineEqua } } + /// + /// Proves that the glyph outline cache never exceeds its 4096-entry cap, even when many + /// threads request distinct glyphs concurrently, and that every request still succeeds. + /// + [Fact] + public void TrueTypeFont_GetGlyphOutline_ConcurrentDistinctGlyphs_NeverExceedsCacheCap() + { + // Arrange: a font with more glyphs than the cap, all empty (equal consecutive loca offsets) + const int glyphCount = 6000; + var data = new SyntheticFontBuilder() + .AddTable("head", SyntheticFontBuilder.Head(1000, 0)) + .AddTable("maxp", SyntheticFontBuilder.Maxp(glyphCount)) + .AddTable("hhea", SyntheticFontBuilder.Hhea(800, -200, 50, 1)) + .AddTable("hmtx", SyntheticFontBuilder.Hmtx([500], glyphCount - 1)) + .AddTable("loca", SyntheticFontBuilder.Loca(new int[glyphCount], longFormat: false)) + .AddTable("glyf", new byte[4]) + .Build(); + using var stream = new MemoryStream(data); + var font = TrueTypeFont.Load(stream); + + // Act: hammer the cache from many threads + var options = new ParallelOptions { MaxDegreeOfParallelism = 8 }; + Parallel.For(0, glyphCount * 4, options, i => Assert.NotNull(font.GetGlyphOutline(i % glyphCount))); + + // Assert: the private cache is capped exactly + var field = typeof(TrueTypeFont).GetField( + "_outlineCache", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + Assert.NotNull(field); + var cache = (System.Collections.ICollection)field.GetValue(font)!; + Assert.InRange(cache.Count, 1, 4096); + } + /// /// Proves that a malformed glyph is never memoized: every call reports it again. /// From 13133274fb1bb63beb0ac5ea4fd658af742c176d Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 13:52:04 -0400 Subject: [PATCH 08/16] Trim multi-breakpoint EvenOdd rows without clip; strengthen resize alpha-edge tests Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Drawing/ScanlineRasterizer.cs | 6 ++- .../Canvas/SurfaceResizeTests.cs | 1 + .../CanvasNetTests.cs | 3 +- .../Drawing/ScanlineRasterizerTests.cs | 52 +++++++++++++++++++ 4 files changed, 59 insertions(+), 3 deletions(-) diff --git a/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs b/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs index 23e9b26cd..acaf928a2 100644 --- a/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs +++ b/src/DemaConsulting.CanvasNet/Drawing/ScanlineRasterizer.cs @@ -884,12 +884,14 @@ private void AccumulateRowCoverageSinglePass(int y) /// private void ApplyClip(int y) { - if (_clip == null || _spanLength == 0) + if (_spanLength == 0) { return; } - var dense = _clip.GetDenseRow(y, _clipMinX + _spanStart, _spanLength); + var dense = _clip == null + ? default + : _clip.GetDenseRow(y, _clipMinX + _spanStart, _spanLength); if (!dense.IsEmpty) { // IEEE single-precision multiply, element-wise: bit-identical to the scalar loop. diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs index 2723f5661..6f2348894 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs @@ -195,6 +195,7 @@ public void Resize_AlphaEdge_HasNoColorFringe(ResamplingMode mode) source[2, 0] = new Rgba32(0, 0, 0, 0); source[3, 0] = new Rgba32(0, 0, 0, 0); using var result = source.Resize(9, 1, mode); + Assert.InRange(result[0, 0].A, 250, 255); for (var x = 0; x < 9; x++) { var p = result[x, 0]; diff --git a/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs b/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs index cf690cc23..b911b2cf2 100644 --- a/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs @@ -117,7 +117,8 @@ public void CanvasNet_SystemIntegration_ResizeAlphaEdge_HasNoColorFringe() // Act using var result = source.Resize(9, 1, ResamplingMode.Bicubic); - // Assert: every visible pixel is still red + // Assert: the left edge is clearly visible, and every visible pixel is still red + Assert.InRange(result[0, 0].A, 250, 255); for (var x = 0; x < 9; x++) { var p = result[x, 0]; diff --git a/test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs index dc62a928c..253b2bbb3 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Drawing/ScanlineRasterizerTests.cs @@ -670,6 +670,58 @@ static List Rectangle(float top, float bottom) => Assert.Equal((byte)85, evenOddSurface[0, 6].A); } + /// + /// Proves that a narrow EvenOdd shape whose rows have several mid-row breakpoints, filled + /// with no clip on a wide surface, changes only the pixels it covers: every column outside the + /// shape and every row it does not reach keeps its original pixel exactly. + /// + [Fact] + public void ScanlineRasterizer_Fill_EvenOddMultipleBreakpointsNoClip_LeavesUncoveredPixelsUntouched() + { + // Arrange: the nested rectangles span only column 0 of a 12-wide opaque blue surface + static List Rectangle(float top, float bottom) => + [ + new Vector2(0, top), + new Vector2(1, top), + new Vector2(1, bottom), + new Vector2(0, bottom), + new Vector2(0, top) + ]; + + var background = new Rgba32(0, 0, 255, 255); + using var surface = new Surface(12, 26); + for (var y = 0; y < 26; y++) + { + for (var x = 0; x < 12; x++) + { + surface[x, y] = background; + } + } + + var polygons = new List> + { + Rectangle(6.0f, 20f), Rectangle(6.167f, 19.833f), Rectangle(6.333f, 19.667f), Rectangle(6.5f, 19.5f) + }; + + // Act + ScanlineRasterizer.Fill(surface, polygons, new Rgba32(255, 255, 255, 255), FillRule.EvenOdd, new Rect(0, 0, 12, 26)); + + // Assert: the covered pixel changed, and everything else is exactly the background + Assert.NotEqual(background, surface[0, 6]); + for (var y = 0; y < 26; y++) + { + for (var x = 0; x < 12; x++) + { + if (x == 0 && y >= 6 && y <= 19) + { + continue; + } + + Assert.Equal(background, surface[x, y]); + } + } + } + /// /// Proves that NonZero's resolution of the very same multi-mid-row-breakpoint /// geometry used by From b299112ec3767c4889d68df1cea014bf900724dd Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 14:23:07 -0400 Subject: [PATCH 09/16] Bound resampler footprints and font outline cache; refresh SysML2 model Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../design/canvas-net/fonts/true-type-font.md | 5 +- .../model/canvas-net-pdf/pdf-document.sysml | 2 +- .../model/canvas-net-pptx/pptx-document.sysml | 2 +- .../model/canvas-net-svg/svg-codec.sysml | 2 +- .../model/canvas-net/canvas/surface.sysml | 6 +- .../model/canvas-net/drawing/tile-paint.sysml | 2 +- .../canvas-net/fonts/true-type-font.sysml | 2 +- .../canvas-net/fonts/true-type-font.md | 7 +- .../Canvas/SurfaceResampler.Engine.cs | 34 ++++++--- .../Fonts/TrueTypeFont.cs | 34 ++++++++- .../Canvas/SurfaceResamplerTests.cs | 72 +++++++++++++++++++ .../Fonts/TrueTypeFontTests.cs | 29 ++++++++ 12 files changed, 175 insertions(+), 22 deletions(-) diff --git a/docs/design/canvas-net/fonts/true-type-font.md b/docs/design/canvas-net/fonts/true-type-font.md index 4383af35d..69a492289 100644 --- a/docs/design/canvas-net/fonts/true-type-font.md +++ b/docs/design/canvas-net/fonts/true-type-font.md @@ -649,8 +649,9 @@ charstring. references an out-of-range subroutine index **Memoization.** Decoded outlines are cached per font in a `ConcurrentDictionary` (at -most 4096 entries; once full, further glyphs are decoded on demand but not stored; admission is -checked and inserted under a lock so the cap is strict under concurrency). `Path` is +most 4096 entries and at most 1,500,000 units of retained geometry, where an outline costs one unit +per subpath plus one per command; an outline that would exceed either bound is decoded on demand but +not stored; admission is checked and inserted under a lock so both caps are strict under concurrency). `Path` is immutable, so every caller shares one instance. A decode that throws is never cached, so a malformed glyph reports its error on every call. The cache is per `TrueTypeFont` instance and the PDF renderer builds fonts per render, so it benefits repeated glyphs within one page; diff --git a/docs/sysml2/model/canvas-net-pdf/pdf-document.sysml b/docs/sysml2/model/canvas-net-pdf/pdf-document.sysml index c0f31098b..4ae4ce294 100644 --- a/docs/sysml2/model/canvas-net-pdf/pdf-document.sysml +++ b/docs/sysml2/model/canvas-net-pdf/pdf-document.sysml @@ -3,7 +3,7 @@ package CanvasNet { doc /* PDF document parser and page-rendering codec: parses cross-references, trailer, and page tree, reports page count/size/rotation, and interprets each page's content stream (path construction/painting/clipping/shading, graphics-state stack, device color operators, generalized stream filter pipeline, image XObjects (raw, DCTDecode, CCITTFaxDecode and JPXDecode samples, /Decode, /SMask soft masks and JPX /SMaskInData), and (Phase 4) simple TrueType font resolution/encoding and text-object/positioning/showing operators, with (Phase 6) automatic system/bundled-Liberation font-fallback substitution for a non-embedded font) to render real path geometry, images, and glyph outlines onto the returned Surface in real device color. */ comment sourceRef /* Source: src/DemaConsulting.CanvasNet.Pdf/PdfDocument.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Tokenizer.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.ObjectModel.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Xref.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.PageTree.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.ContentStream.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.GraphicsState.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.PathOps.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Color.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Filters.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Filters.Lzw.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Filters.Ascii.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Filters.RunLength.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Fonts.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Fonts.ToUnicode.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Fonts.Type0.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Fonts.Type1.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Fonts.Type3.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.FontFallback.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Text.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.CcittFax.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Encryption.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Functions.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Patterns.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Patterns.Shading.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Patterns.Shading.Mesh.cs, src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Patterns.Tiling.cs, src/DemaConsulting.CanvasNet.Pdf/PdfPageInfo.cs, src/DemaConsulting.CanvasNet.Pdf/PdfRenderOptions.cs, src/DemaConsulting.CanvasNet.Pdf/NamespaceDoc.cs */ - comment testRef /* Test: test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfSystemIntegrationTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfFixtureTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentEncryptionTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentMeshShadingTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentSymbolicEncodingTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentJpxTests.cs */ + comment testRef /* Test: test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfSystemIntegrationTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfFixtureTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentEncryptionTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentMeshShadingTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentSymbolicEncodingTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentJpxTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfImageResamplingTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageColorConversionTests.cs, test/DemaConsulting.CanvasNet.Pdf.Tests/PdfDocumentImageDownscaleTests.cs */ comment designRef /* Design: docs/design/canvas-net-pdf/pdf-document.md */ comment verificationRef /* Verification: docs/verification/canvas-net-pdf/pdf-document.md */ comment reqRef /* Requirements: docs/reqstream/canvas-net-pdf/pdf-document.yaml */ diff --git a/docs/sysml2/model/canvas-net-pptx/pptx-document.sysml b/docs/sysml2/model/canvas-net-pptx/pptx-document.sysml index 82f82f2be..53d6d330e 100644 --- a/docs/sysml2/model/canvas-net-pptx/pptx-document.sysml +++ b/docs/sysml2/model/canvas-net-pptx/pptx-document.sysml @@ -3,7 +3,7 @@ package CanvasNet { /* cspell:ignore srcRect blipFill tblGrid gridCol tcPr hMerge vMerge gridSpan rowSpan grpSp grpSpPr cxnSp graphicFrame pattFill spTree */ /* cspell:ignore tblStyle wholeTbl tcStyle tcBdr insideH insideV bandRow firstRow band1H band2H */ part def PptxDocument { - doc /* OOXML (Office Open XML) package parser and presentation-rendering codec, delivered incrementally across Phases 1a-1f, each additive to the last. Phase 1a implements the package layer: opens a .pptx file as a read-only ZipArchive, resolves [Content_Types].xml's default extension mappings and part-specific overrides, and resolves package-level (_rels/.rels) and per-part relationships (including relative-target resolution with ".." traversal). Phase 1b adds the presentation/theme/master/layout/slide model: parses ppt/presentation.xml's declared slide size and ordered slide list, resolves each slide master's theme (color/font scheme), structurally parses each master/layout/slide's placeholder shapes, and implements the verified ECMA-376 placeholder property-inheritance resolver (slide -> layout matched by idx alone, layout -> master matched by type alone via a fixed remapping table). Phase 1c adds DrawingML shape geometry and paint resolution: a shape's position/rotation/flip transform, a group's chOff/chExt child-coordinate-space transform composition, preset geometry (28 supported names, including a later-hardening-pass-added curved-arrow family) and custom path-command parsing resolved into the core Path type, and // fill plus stroke resolution into core paint types - including scheme-color lookup through the resolved theme, the lumMod/lumOff/shade/tint/alpha color-transform pipeline, and a stroked outline realized via the core PathStroker. Phase 1d adds DrawingML text body parsing (//////), attribute-level run/paragraph property inheritance through the placeholder/layout/master (including the master's own titleStyle/bodyStyle/otherStyle buckets)/theme chain, word-wrap/alignment/vertical-anchor/autofit text layout, and glyph-ink rendering onto a core Surface via the core Fonts.TrueTypeFont/SystemFontCatalog and Drawing.PathFiller, mirroring the PDF renderer's own glyph-painting pattern. Phase 1e adds dedicated picture-shape support (content-type dispatch mirroring CanvasNetSvg's SvgCodec.ResolveRasterDecoder, crop-rectangle resolution, and y-down nearest-neighbor compositing that deliberately omits the PDF renderer's own y-up vertical flip), table support (structure/cell parsing reusing the Phase 1c/1d fill/border/text-body resolvers verbatim, merge-aware cell-rect resolution, and cell fill/border/text painting), and recursive, full shape-tree parsing across a slide's own /// elements (including nested child-transform composition) with lazy, invoke-on-demand theme resolution so a shape tree with no never resolves a theme at all. Phase 1f adds the public, slide-level rendering API: PptxDocument.Render(int slideIndex, int width, int height, PptxRenderOptions? options) and a DPI convenience overload, which walk a slide's full PptxSlide.ShapeTree recursively in document order with an accumulating transform, dispatching each node kind to the already-verified Phase 1c/1d/1e resolvers/painters verbatim - composing a group's own already-resolved child transform, resolving an ordinary/placeholder shape's geometry/fill/stroke/text (a placeholder's own text is always read from the slide-level shape's own txBody, never from its matched layout placeholder), compositing a picture's embedded image, and painting a graphic frame's own table - clearing the destination Surface to PptxRenderOptions.BackgroundColor (default opaque white) before painting, and silently skipping a shape/picture/graphic-frame with no resolvable xfrm or a picture with no blipFill, mirroring ParseShapeTree's own tolerant-tree-walk precedent. With Phase 1f, the planned PPTX 1.0 feature set was complete. A Phase 2 Follow-Up pass then closed the single highest-visual-impact gap left by Phase 1f: a slide's own / background fill is now resolved - falling back to its layout's, then its master's, own when the slide declares none, then to PptxRenderOptions.BackgroundColor only when none of the three declare one at all - and painted across the full slide before the shape-tree walk, reusing the existing Phase 1c ResolveFill/ResolveColor pipeline verbatim (including a new, optional phClr-override parameter threaded through it for theme-indexed resolution against a new PptxTheme.BgFillStyleList, parsed from /). Solid-color fills and theme-indexed fills are fully supported; a linear gradient background fill is best-effort (inheriting Phase 1c's own linear-only boundary unchanged); a pattern or picture background fill remains explicitly deferred (inheriting ResolveFill's own pre-existing PptxUnsupportedFeatureException boundary unchanged). A non-placeholder shape's own background fill via / inside (picture/pattern fill remains scoped to a dedicated shape's own ), picture effects/shadows, nested tables, table auto-sizing to fit overflowing cell content (each row's resolved height is taken verbatim from its declared value, with no growth to accommodate overflowing cell content), table style/banding (), connector shapes, group-level style cascading beyond transform composition, radial/path gradients, adjustment-value parsing, bullets/numbering, full text justification, shape-resize autofit, kerning, and text clipping on overflow remain out of scope; none of these is a currently planned phase, and any of them remaining important is a candidate for a future, corpus-driven hardening pass (pptx-phase-2), not a scheduled increment. A further Phase 2 Follow-Up pass then closed the master/layout decorative-shape gap: a slide's own master and layout each contribute their own full shape tree - rendered beneath the slide's own shape tree, in master-then-layout-then-slide order, with each matched placeholder shape skipped (a placeholder's own geometry/fill/stroke/text is painted exactly once, from the slide-level shape, via the existing placeholder-inheritance resolver) so only genuine, non-placeholder decorative shapes contributed by the master/layout are painted - reusing the existing Phase 1c-1e geometry/paint/text/picture/table resolvers verbatim. A further Phase 2 Follow-Up pass closed the bullets/numbering gap: a paragraph's character, auto-number marker, or explicit absence is now parsed and resolved through the same four-tier placeholder/layout/master inheritance chain established for other paragraph properties, formatted into its rendered string for the eleven most common Latin-numeral auto-number schemes, and measured and painted at the paragraph's own gutter without ever overlapping its text. A further Phase 2 Follow-Up pass closed the connector-shapes gap: a is now parsed into its own shape-tree node alongside every other shape kind, and the public rendering API paints its resolved straight/elbow/curved line - merging its own line style with its style-reference fallback - and orients an optional stroked or filled arrowhead at either end; an unrecognized connector preset degrades to that one connector being invisible rather than aborting the slide. A subsequent regression fix corrected two real-file rendering failures this pass introduced: a master/layout decorative shape (including one nested inside a group) that itself throws PptxUnsupportedFeatureException while painting is now caught and only that single shape is skipped, so one already-deferred feature (for example an EMF picture) no longer aborts rendering for the rest of the slide - a slide's own shape still hard-fails unchanged; and a declaring only a Microsoft SVG extension fallback (/, the "Insert Icon" SVG-with-no-raster-fallback pattern) is now correctly classified as PptxUnsupportedFeatureException (feature token "pptx-image-svg-only") rather than misclassified as a malformed-data InvalidDataException. A further Phase 2 Follow-Up pass replaced that same "pptx-image-svg-only" PptxUnsupportedFeatureException with a successful decode: the Microsoft SVG extension's own relationship is now resolved (scoped to the owning part, exactly like a normal raster r:embed) and its referenced .svg media part is rasterized via the sibling CanvasNetSvg package's SvgCodec - using SvgCodec.GetInfo to measure the SVG's own intrinsic viewBox/width/height (clamped to [1, Surface.MaxDimension] on each axis) and SvgCodec.Load to rasterize at that resolution - returning the decoded Surface from ResolvePictureSurface exactly like any other raster image, so every downstream consumer (crop/srcRect, stretch/tile, shape transform, master/layout painting, disposal/ownership tracking) is unchanged; only the same extension present but with no r:embed of its own still throws InvalidDataException, and a malformed/unparsable referenced SVG still propagates SvgCodec's own InvalidDataException unchanged. A further bug fix corrected a real-world-verified compositing defect confirmed against a user-supplied deck: Phase 1e's own picture compositing loop previously overwrote each destination pixel outright with the raw sampled source pixel, ignoring the source image's own alpha channel entirely, so a PNG logo with genuine RGBA transparency rendered with a solid, incorrect matte rectangle instead of showing the slide background through its transparent area; the loop now alpha-blends each sampled source pixel over the existing destination pixel using the standard Porter-Duff "over" formula, via a new internal, single-pixel Rgba32.CompositeOver(Rgba32, Rgba32) helper shared cross-assembly with (and formula-identical to) CanvasNetPdf's own CompositeImageOntoSurface fix for the same defect. A further Phase 2 Follow-Up pass fixed a color-map-indirection defect: bg1/tx1/bg2/tx2 scheme-color resolution previously hard-coded a fixed bg1->Light1/tx1->Dark1/bg2->Light2/tx2->Dark2 mapping, ignoring the slide master's own required and any layout/slide override; these four aliases now correctly indirect through the effective, per-slide color map (slide overriding layout overriding the master's own , with an marker at any tier falling through to the next) before the existing theme-slot lookup, closing the gap for any non-identity (for example dark/inverted) master or layout. A further bug fix corrected ResolveLineStyle's own stroke-width resolution: a genuinely-absent w attribute previously collapsed to the same "no stroke" outcome as an explicit w="0", so a real-world that declares only a color (relying on PowerPoint's own default stroke weight) rendered with no visible outline at all; a genuinely-absent w now resolves to PowerPoint's own observed default stroke width (9525 EMU / 0.75pt, an application-level convention rather than a formal XSD schema default), while an explicitly-present w="0" or negative w still resolves to no stroke exactly as before - scoped narrowly to ResolveLineStyle itself, leaving ResolveShapeLineStyle's and ResolveConnectorLineStyle's own separate width-merge logic unchanged. A further bug fix corrected a bullet-gutter/text-start-X collision confirmed against a real-world buAutoNum paragraph (marL="320040", lvl="1", no indent attribute, no placeholder/master tier contributing one): PositionLines now clamps a bulleted first line's own text-start-X to never fall short of the bullet glyph's own gutter position plus its own measured width, so the bullet and the paragraph's own text never paint at an overlapping X coordinate, regardless of the paragraph's resolved indent. A further bug fix corrected an underline-rendering defect confirmed against a real-world corpus fixture: a text run's resolved (and every other ECMA-376 underline-style value) was parsed into an effective property that nothing downstream ever consumed, so an explicitly-authored underline rendered with no underline at all; underline style/color now resolve through the same four-tier inheritance chain as every other text property, and PositionLines/PaintTextLayout now emit and paint a per-run underline span - continuous across a run's own interior whitespace but never bridging a run boundary, with thickness/offset approximated proportional to the run's own font size - closing the gap. A further Phase 2 Follow-Up pass closed the table-style/banding gap: a new PptxDocument.TableStyles.cs resolves a /'s against the presentation package's own ppt/tableStyles.xml part (tolerating every "not found" cause by falling back to today's plain, style-less cell rendering without throwing) and applies the matched 's base tier to every cell, its / tiers alternating by non-header row parity when (a tier missing its own fill falling through to the next lower tier rather than to "no fill"), and its tier overriding both for the header row when , with a cell's own explicit fill/border always taking final precedence over every style tier - mirroring ResolveShapeLineStyle's own established "explicit always wins" precedence pattern and reusing the existing ResolveFill/ResolveLineStyle resolvers verbatim for every style-tier color, including schemeClr. firstCol/lastCol/lastRow/corner-cell style parts, column banding (band1V/band2V), and table-style-driven font color remain explicitly deferred. A further Phase 2 Follow-Up pass closed the default-tab-stop-expansion gap confirmed against a real-world corpus slide (literal digit-plus-tab-plus-sentence "numbered list" paragraphs, not buAutoNum bullets): a literal U+0009 TAB run character previously measured via the shared ResolveGlyph font-glyph lookup (resolving to a near-zero .notdef advance for most fonts' own missing cmap entry) now expands to the next default 914400-EMU (1 inch) tab stop instead, isolated as its own single-character token and computed dynamically from the running cursor position for both the word-wrap fit decision and the rendered cursor expansion; explicit tab-stop support remains out of scope, since no corpus slide declares one. A further Phase 2 Follow-Up pass closed the table-row-height-growth gap: ResolveCellRects now optionally grows a row's own effective height past its stored value to fit its tallest single-row cell's own wrapped text, computed via a new MeasureRequiredTextHeightEmu entry point built atop a verbatim extraction (ResolveWrappedLines) of ResolveTextLayout's own pre-existing word-wrap/autofit steps, measured against an unbounded height sentinel so the measurement can never itself trigger autofit shrinkage; a row-spanning cell's own shortfall against its spanned rows' stored height sum is added entirely onto its last spanned row; omitting the new optional theme/fontResolver parameters preserves today's stored-height-only behavior unconditionally, so every pre-existing caller is unaffected and only PaintTable's own production call site opts in. A further Phase 2 Follow-Up pass closed the slide-number-field gap: an field is now parsed alongside plain runs (its cached text captured but not trusted, since PowerPoint caches a stale value at authoring time), and PptxDocument.Render's slide-level entry point substitutes every such field's text with the shape's own actual one-based slide index immediately before painting (SubstituteSlideNumberField), per slide, so a rendered deck always shows the slide's true current number rather than whatever number PowerPoint happened to cache; every other type (for example "datetime1") is left at its cached text unchanged. */ + doc /* OOXML (Office Open XML) package parser and presentation-rendering codec, delivered incrementally across Phases 1a-1f, each additive to the last. Phase 1a implements the package layer: opens a .pptx file as a read-only ZipArchive, resolves [Content_Types].xml's default extension mappings and part-specific overrides, and resolves package-level (_rels/.rels) and per-part relationships (including relative-target resolution with ".." traversal). Phase 1b adds the presentation/theme/master/layout/slide model: parses ppt/presentation.xml's declared slide size and ordered slide list, resolves each slide master's theme (color/font scheme), structurally parses each master/layout/slide's placeholder shapes, and implements the verified ECMA-376 placeholder property-inheritance resolver (slide -> layout matched by idx alone, layout -> master matched by type alone via a fixed remapping table). Phase 1c adds DrawingML shape geometry and paint resolution: a shape's position/rotation/flip transform, a group's chOff/chExt child-coordinate-space transform composition, preset geometry (28 supported names, including a later-hardening-pass-added curved-arrow family) and custom path-command parsing resolved into the core Path type, and // fill plus stroke resolution into core paint types - including scheme-color lookup through the resolved theme, the lumMod/lumOff/shade/tint/alpha color-transform pipeline, and a stroked outline realized via the core PathStroker. Phase 1d adds DrawingML text body parsing (//////), attribute-level run/paragraph property inheritance through the placeholder/layout/master (including the master's own titleStyle/bodyStyle/otherStyle buckets)/theme chain, word-wrap/alignment/vertical-anchor/autofit text layout, and glyph-ink rendering onto a core Surface via the core Fonts.TrueTypeFont/SystemFontCatalog and Drawing.PathFiller, mirroring the PDF renderer's own glyph-painting pattern. Phase 1e adds dedicated picture-shape support (content-type dispatch mirroring CanvasNetSvg's SvgCodec.ResolveRasterDecoder, crop-rectangle resolution, and y-down resampled compositing (SurfaceResampler single-pass device resampling, area averaging when shrunk and Catmull-Rom bicubic otherwise, with an inverse-mapped fallback for rotated placements) that deliberately omits the PDF renderer's own y-up vertical flip), table support (structure/cell parsing reusing the Phase 1c/1d fill/border/text-body resolvers verbatim, merge-aware cell-rect resolution, and cell fill/border/text painting), and recursive, full shape-tree parsing across a slide's own /// elements (including nested child-transform composition) with lazy, invoke-on-demand theme resolution so a shape tree with no never resolves a theme at all. Phase 1f adds the public, slide-level rendering API: PptxDocument.Render(int slideIndex, int width, int height, PptxRenderOptions? options) and a DPI convenience overload, which walk a slide's full PptxSlide.ShapeTree recursively in document order with an accumulating transform, dispatching each node kind to the already-verified Phase 1c/1d/1e resolvers/painters verbatim - composing a group's own already-resolved child transform, resolving an ordinary/placeholder shape's geometry/fill/stroke/text (a placeholder's own text is always read from the slide-level shape's own txBody, never from its matched layout placeholder), compositing a picture's embedded image, and painting a graphic frame's own table - clearing the destination Surface to PptxRenderOptions.BackgroundColor (default opaque white) before painting, and silently skipping a shape/picture/graphic-frame with no resolvable xfrm or a picture with no blipFill, mirroring ParseShapeTree's own tolerant-tree-walk precedent. With Phase 1f, the planned PPTX 1.0 feature set was complete. A Phase 2 Follow-Up pass then closed the single highest-visual-impact gap left by Phase 1f: a slide's own / background fill is now resolved - falling back to its layout's, then its master's, own when the slide declares none, then to PptxRenderOptions.BackgroundColor only when none of the three declare one at all - and painted across the full slide before the shape-tree walk, reusing the existing Phase 1c ResolveFill/ResolveColor pipeline verbatim (including a new, optional phClr-override parameter threaded through it for theme-indexed resolution against a new PptxTheme.BgFillStyleList, parsed from /). Solid-color fills and theme-indexed fills are fully supported; a linear gradient background fill is best-effort (inheriting Phase 1c's own linear-only boundary unchanged); a pattern or picture background fill remains explicitly deferred (inheriting ResolveFill's own pre-existing PptxUnsupportedFeatureException boundary unchanged). A non-placeholder shape's own background fill via / inside (picture/pattern fill remains scoped to a dedicated shape's own ), picture effects/shadows, nested tables, table auto-sizing to fit overflowing cell content (each row's resolved height is taken verbatim from its declared value, with no growth to accommodate overflowing cell content), table style/banding (), connector shapes, group-level style cascading beyond transform composition, radial/path gradients, adjustment-value parsing, bullets/numbering, full text justification, shape-resize autofit, kerning, and text clipping on overflow remain out of scope; none of these is a currently planned phase, and any of them remaining important is a candidate for a future, corpus-driven hardening pass (pptx-phase-2), not a scheduled increment. A further Phase 2 Follow-Up pass then closed the master/layout decorative-shape gap: a slide's own master and layout each contribute their own full shape tree - rendered beneath the slide's own shape tree, in master-then-layout-then-slide order, with each matched placeholder shape skipped (a placeholder's own geometry/fill/stroke/text is painted exactly once, from the slide-level shape, via the existing placeholder-inheritance resolver) so only genuine, non-placeholder decorative shapes contributed by the master/layout are painted - reusing the existing Phase 1c-1e geometry/paint/text/picture/table resolvers verbatim. A further Phase 2 Follow-Up pass closed the bullets/numbering gap: a paragraph's character, auto-number marker, or explicit absence is now parsed and resolved through the same four-tier placeholder/layout/master inheritance chain established for other paragraph properties, formatted into its rendered string for the eleven most common Latin-numeral auto-number schemes, and measured and painted at the paragraph's own gutter without ever overlapping its text. A further Phase 2 Follow-Up pass closed the connector-shapes gap: a is now parsed into its own shape-tree node alongside every other shape kind, and the public rendering API paints its resolved straight/elbow/curved line - merging its own line style with its style-reference fallback - and orients an optional stroked or filled arrowhead at either end; an unrecognized connector preset degrades to that one connector being invisible rather than aborting the slide. A subsequent regression fix corrected two real-file rendering failures this pass introduced: a master/layout decorative shape (including one nested inside a group) that itself throws PptxUnsupportedFeatureException while painting is now caught and only that single shape is skipped, so one already-deferred feature (for example an EMF picture) no longer aborts rendering for the rest of the slide - a slide's own shape still hard-fails unchanged; and a declaring only a Microsoft SVG extension fallback (/, the "Insert Icon" SVG-with-no-raster-fallback pattern) is now correctly classified as PptxUnsupportedFeatureException (feature token "pptx-image-svg-only") rather than misclassified as a malformed-data InvalidDataException. A further Phase 2 Follow-Up pass replaced that same "pptx-image-svg-only" PptxUnsupportedFeatureException with a successful decode: the Microsoft SVG extension's own relationship is now resolved (scoped to the owning part, exactly like a normal raster r:embed) and its referenced .svg media part is rasterized via the sibling CanvasNetSvg package's SvgCodec - using SvgCodec.GetInfo to measure the SVG's own intrinsic viewBox/width/height (clamped to [1, Surface.MaxDimension] on each axis) and SvgCodec.Load to rasterize at that resolution - returning the decoded Surface from ResolvePictureSurface exactly like any other raster image, so every downstream consumer (crop/srcRect, stretch/tile, shape transform, master/layout painting, disposal/ownership tracking) is unchanged; only the same extension present but with no r:embed of its own still throws InvalidDataException, and a malformed/unparsable referenced SVG still propagates SvgCodec's own InvalidDataException unchanged. A further bug fix corrected a real-world-verified compositing defect confirmed against a user-supplied deck: Phase 1e's own picture compositing loop previously overwrote each destination pixel outright with the raw sampled source pixel, ignoring the source image's own alpha channel entirely, so a PNG logo with genuine RGBA transparency rendered with a solid, incorrect matte rectangle instead of showing the slide background through its transparent area; the loop now alpha-blends each sampled source pixel over the existing destination pixel using the standard Porter-Duff "over" formula, via a new internal, single-pixel Rgba32.CompositeOver(Rgba32, Rgba32) helper shared cross-assembly with (and formula-identical to) CanvasNetPdf's own CompositeImageOntoSurface fix for the same defect. A further Phase 2 Follow-Up pass fixed a color-map-indirection defect: bg1/tx1/bg2/tx2 scheme-color resolution previously hard-coded a fixed bg1->Light1/tx1->Dark1/bg2->Light2/tx2->Dark2 mapping, ignoring the slide master's own required and any layout/slide override; these four aliases now correctly indirect through the effective, per-slide color map (slide overriding layout overriding the master's own , with an marker at any tier falling through to the next) before the existing theme-slot lookup, closing the gap for any non-identity (for example dark/inverted) master or layout. A further bug fix corrected ResolveLineStyle's own stroke-width resolution: a genuinely-absent w attribute previously collapsed to the same "no stroke" outcome as an explicit w="0", so a real-world that declares only a color (relying on PowerPoint's own default stroke weight) rendered with no visible outline at all; a genuinely-absent w now resolves to PowerPoint's own observed default stroke width (9525 EMU / 0.75pt, an application-level convention rather than a formal XSD schema default), while an explicitly-present w="0" or negative w still resolves to no stroke exactly as before - scoped narrowly to ResolveLineStyle itself, leaving ResolveShapeLineStyle's and ResolveConnectorLineStyle's own separate width-merge logic unchanged. A further bug fix corrected a bullet-gutter/text-start-X collision confirmed against a real-world buAutoNum paragraph (marL="320040", lvl="1", no indent attribute, no placeholder/master tier contributing one): PositionLines now clamps a bulleted first line's own text-start-X to never fall short of the bullet glyph's own gutter position plus its own measured width, so the bullet and the paragraph's own text never paint at an overlapping X coordinate, regardless of the paragraph's resolved indent. A further bug fix corrected an underline-rendering defect confirmed against a real-world corpus fixture: a text run's resolved (and every other ECMA-376 underline-style value) was parsed into an effective property that nothing downstream ever consumed, so an explicitly-authored underline rendered with no underline at all; underline style/color now resolve through the same four-tier inheritance chain as every other text property, and PositionLines/PaintTextLayout now emit and paint a per-run underline span - continuous across a run's own interior whitespace but never bridging a run boundary, with thickness/offset approximated proportional to the run's own font size - closing the gap. A further Phase 2 Follow-Up pass closed the table-style/banding gap: a new PptxDocument.TableStyles.cs resolves a /'s against the presentation package's own ppt/tableStyles.xml part (tolerating every "not found" cause by falling back to today's plain, style-less cell rendering without throwing) and applies the matched 's base tier to every cell, its / tiers alternating by non-header row parity when (a tier missing its own fill falling through to the next lower tier rather than to "no fill"), and its tier overriding both for the header row when , with a cell's own explicit fill/border always taking final precedence over every style tier - mirroring ResolveShapeLineStyle's own established "explicit always wins" precedence pattern and reusing the existing ResolveFill/ResolveLineStyle resolvers verbatim for every style-tier color, including schemeClr. firstCol/lastCol/lastRow/corner-cell style parts, column banding (band1V/band2V), and table-style-driven font color remain explicitly deferred. A further Phase 2 Follow-Up pass closed the default-tab-stop-expansion gap confirmed against a real-world corpus slide (literal digit-plus-tab-plus-sentence "numbered list" paragraphs, not buAutoNum bullets): a literal U+0009 TAB run character previously measured via the shared ResolveGlyph font-glyph lookup (resolving to a near-zero .notdef advance for most fonts' own missing cmap entry) now expands to the next default 914400-EMU (1 inch) tab stop instead, isolated as its own single-character token and computed dynamically from the running cursor position for both the word-wrap fit decision and the rendered cursor expansion; explicit tab-stop support remains out of scope, since no corpus slide declares one. A further Phase 2 Follow-Up pass closed the table-row-height-growth gap: ResolveCellRects now optionally grows a row's own effective height past its stored value to fit its tallest single-row cell's own wrapped text, computed via a new MeasureRequiredTextHeightEmu entry point built atop a verbatim extraction (ResolveWrappedLines) of ResolveTextLayout's own pre-existing word-wrap/autofit steps, measured against an unbounded height sentinel so the measurement can never itself trigger autofit shrinkage; a row-spanning cell's own shortfall against its spanned rows' stored height sum is added entirely onto its last spanned row; omitting the new optional theme/fontResolver parameters preserves today's stored-height-only behavior unconditionally, so every pre-existing caller is unaffected and only PaintTable's own production call site opts in. A further Phase 2 Follow-Up pass closed the slide-number-field gap: an field is now parsed alongside plain runs (its cached text captured but not trusted, since PowerPoint caches a stale value at authoring time), and PptxDocument.Render's slide-level entry point substitutes every such field's text with the shape's own actual one-based slide index immediately before painting (SubstituteSlideNumberField), per slide, so a rendered deck always shows the slide's true current number rather than whatever number PowerPoint happened to cache; every other type (for example "datetime1") is left at its cached text unchanged. */ comment sourceRef /* Source: src/DemaConsulting.CanvasNet.Pptx/PptxDocument.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Package.cs, src/DemaConsulting.CanvasNet.Pptx/NamespaceDoc.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Presentation.cs, src/DemaConsulting.CanvasNet.Pptx/PptxSlideSize.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Theme.cs, src/DemaConsulting.CanvasNet.Pptx/PptxTheme.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Masters.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Layouts.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Slides.cs, src/DemaConsulting.CanvasNet.Pptx/PptxPlaceholder.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Inheritance.cs, src/DemaConsulting.CanvasNet.Pptx/PptxPlaceholderProperties.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Geometry.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Paint.cs, src/DemaConsulting.CanvasNet.Pptx/PptxPresetGeometry.cs, src/DemaConsulting.CanvasNet.Pptx/PptxShapeFrame.cs, src/DemaConsulting.CanvasNet.Pptx/PptxPaint.cs, src/DemaConsulting.CanvasNet.Pptx/PptxLineStyle.cs, src/DemaConsulting.CanvasNet.Pptx/PptxUnsupportedFeatureException.cs, src/DemaConsulting.CanvasNet.Pptx/PptxTextBody.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Text.cs, src/DemaConsulting.CanvasNet.Pptx/PptxEffectiveTextProperties.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.TextInheritance.cs, src/DemaConsulting.CanvasNet.Pptx/PptxTextLayout.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.TextLayout.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.TextRender.cs, src/DemaConsulting.CanvasNet.Pptx/PptxPicture.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs, src/DemaConsulting.CanvasNet.Pptx/PptxTable.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Tables.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.TableStyles.cs, src/DemaConsulting.CanvasNet.Pptx/PptxShapeTree.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.ShapeTree.cs, src/DemaConsulting.CanvasNet.Pptx/PptxRenderOptions.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Render.cs, src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Background.cs */ comment testRef /* Test: test/DemaConsulting.CanvasNet.Pptx.Tests/PptxDocumentTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxSystemIntegrationTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxGeometryTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxPaintTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxTextTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxTextLayoutTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxTextRenderTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxTablesTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxGroupsTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxRenderTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxBackgroundTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxFixturesCorpusTests.cs, test/DemaConsulting.CanvasNet.Pptx.Tests/PptxColorMapTests.cs */ diff --git a/docs/sysml2/model/canvas-net-svg/svg-codec.sysml b/docs/sysml2/model/canvas-net-svg/svg-codec.sysml index d1a500db0..20197296c 100644 --- a/docs/sysml2/model/canvas-net-svg/svg-codec.sysml +++ b/docs/sysml2/model/canvas-net-svg/svg-codec.sysml @@ -3,7 +3,7 @@ package CanvasNet { doc /* Decode/rasterize-only loader for a common real-world subset of SVG documents, rasterizing them into Surface pixel buffers. */ comment sourceRef /* Source: src/DemaConsulting.CanvasNet.Svg/SvgCodec.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Core.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Parsing.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Elements.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Shapes.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.PathData.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.PathRender.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.ColorMatrix.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.ComponentTransfer.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Morphology.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Convolution.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.DisplacementMap.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Tile.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.DropShadow.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.FeImage.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Paint.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Gradients.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Markers.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Text.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Attributes.cs, src/DemaConsulting.CanvasNet.Svg/SvgFontFace.cs, src/DemaConsulting.CanvasNet.Svg/SvgFontStyle.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.ClippingAndMasking.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Patterns.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.PreserveAspectRatio.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Lighting.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Turbulence.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Blend.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Css.Parser.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Css.Selectors.cs, src/DemaConsulting.CanvasNet.Svg/SvgCodec.Css.Cascade.cs, src/DemaConsulting.CanvasNet/Codecs/ImageInfo.cs (cross-package: shared header-only probe result type in the core DemaConsulting.CanvasNet package) */ - comment testRef /* Test: test/DemaConsulting.CanvasNet.Svg.Tests/SvgCodecTests.cs, test/DemaConsulting.CanvasNet.Svg.Tests/SvgFixtureTests.cs, test/DemaConsulting.CanvasNet.Svg.Tests/SvgSystemIntegrationTests.cs */ + comment testRef /* Test: test/DemaConsulting.CanvasNet.Svg.Tests/SvgCodecTests.cs, test/DemaConsulting.CanvasNet.Svg.Tests/SvgFixtureTests.cs, test/DemaConsulting.CanvasNet.Svg.Tests/SvgSystemIntegrationTests.cs, test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs, test/DemaConsulting.CanvasNet.Svg.Tests/SvgPatternTileSmoothingTests.cs */ comment designRef /* Design: docs/design/canvas-net-svg/svg-codec.md */ comment verificationRef /* Verification: docs/verification/canvas-net-svg/svg-codec.md */ comment reqRef /* Requirements: docs/reqstream/canvas-net-svg/svg-codec.yaml */ diff --git a/docs/sysml2/model/canvas-net/canvas/surface.sysml b/docs/sysml2/model/canvas-net/canvas/surface.sysml index 7f3f8b8e6..1ec59915d 100644 --- a/docs/sysml2/model/canvas-net/canvas/surface.sysml +++ b/docs/sysml2/model/canvas-net/canvas/surface.sysml @@ -1,9 +1,9 @@ package CanvasNet { part def Surface { - doc /* Mutable, in-memory 32-bit RGBA pixel buffer providing span-based row access, independent-copy cropping, and vectorized bulk pixel operations (alpha premultiplication and Porter-Duff "over" compositing). Implements IDisposable to establish the disposal contract for its pixel buffer ahead of a future ArrayPool-backed storage change. */ + doc /* Mutable, in-memory 32-bit RGBA pixel buffer providing span-based row access, independent-copy cropping, vectorized bulk pixel operations (alpha premultiplication and Porter-Duff "over" compositing), and high-quality resizing (Surface.Resize) through the internal two-pass separable resampling engine (nearest, area, bilinear, Catmull-Rom bicubic and Lanczos3 filters selected by ResamplingMode, premultiplied-alpha filtering, edge clamping, bounded-memory strips, and overflow-safe handling of extreme footprints). Implements IDisposable to establish the disposal contract for its pixel buffer ahead of a future ArrayPool-backed storage change. */ - comment sourceRef /* Source: src/DemaConsulting.CanvasNet/Canvas/Surface.cs, src/DemaConsulting.CanvasNet/Canvas/Rgba32.cs */ - comment testRef /* Test: test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceTests.cs */ + comment sourceRef /* Source: src/DemaConsulting.CanvasNet/Canvas/Surface.cs, src/DemaConsulting.CanvasNet/Canvas/Rgba32.cs, src/DemaConsulting.CanvasNet/Canvas/ResamplingMode.cs, src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs, src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs */ + comment testRef /* Test: test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceTests.cs, test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeTests.cs, test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs, test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResizeCodecRoundTripTests.cs */ comment designRef /* Design: docs/design/canvas-net/canvas/surface.md */ comment verificationRef /* Verification: docs/verification/canvas-net/canvas/surface.md */ comment reqRef /* Requirements: docs/reqstream/canvas-net/canvas/surface.yaml */ diff --git a/docs/sysml2/model/canvas-net/drawing/tile-paint.sysml b/docs/sysml2/model/canvas-net/drawing/tile-paint.sysml index 94f13f482..808d4c0c2 100644 --- a/docs/sysml2/model/canvas-net/drawing/tile-paint.sysml +++ b/docs/sysml2/model/canvas-net/drawing/tile-paint.sysml @@ -1,6 +1,6 @@ package CanvasNet { part def TilePaint { - doc /* Public TilePaint type (a pre-rendered one-cell tile Surface plus a device-space Transform and pattern-space XStep/YStep pitch) and the internal TilePaintEvaluator helper that resolves a tiled pattern's color per pixel by nearest-neighbor sampling the wrapped-around tile; consumed by PathFiller's tile-paint Fill overload. Mirrors GradientPaint's own public-type-plus-internal-evaluator shape; added alongside CanvasNetPdf's /Pattern color-space tiling-pattern support. */ + doc /* Public TilePaint type (a pre-rendered one-cell tile Surface plus a device-space Transform and pattern-space XStep/YStep pitch) and the internal TilePaintEvaluator helper that resolves a tiled pattern's color per pixel from the wrapped-around tile (exact pixel lookup at 1:1 scale, wrapped bilinear sampling when the tile is magnified, and an area-averaged prefiltered copy when it is minified, via SurfaceResampler); consumed by PathFiller's tile-paint Fill overload. Mirrors GradientPaint's own public-type-plus-internal-evaluator shape; added alongside CanvasNetPdf's /Pattern color-space tiling-pattern support. */ comment sourceRef /* Source: src/DemaConsulting.CanvasNet/Drawing/TilePaint.cs, src/DemaConsulting.CanvasNet/Drawing/TilePaintEvaluator.cs */ comment testRef /* Test: test/DemaConsulting.CanvasNet.Tests/Drawing/TilePaintTests.cs, test/DemaConsulting.CanvasNet.Tests/Drawing/TilePaintEvaluatorTests.cs */ diff --git a/docs/sysml2/model/canvas-net/fonts/true-type-font.sysml b/docs/sysml2/model/canvas-net/fonts/true-type-font.sysml index bcc32dee5..7fc72c1ae 100644 --- a/docs/sysml2/model/canvas-net/fonts/true-type-font.sysml +++ b/docs/sysml2/model/canvas-net/fonts/true-type-font.sysml @@ -1,6 +1,6 @@ package CanvasNet { part def TrueTypeFont { - doc /* Public TrueType/CFF/Type 1 font loader/query unit fronting SFNT container parsing (including ttcf collection face selection), cmap lookup, glyf/loca outline decoding, CFF/Type 2 charstring outline decoding, standalone Type 1/PostScript font parsing (PFA/PFB container reading, eexec/charstring decryption, and Type 1 charstring outline decoding with standard glyph name resolution), hhea/hmtx metrics, tolerant format-0 kern lookup, and name/style metadata (family/subfamily/full/PostScript name, bold/italic/fixed-pitch). */ + doc /* Public TrueType/CFF/Type 1 font loader/query unit fronting SFNT container parsing (including ttcf collection face selection), cmap lookup, glyf/loca outline decoding, CFF/Type 2 charstring outline decoding, standalone Type 1/PostScript font parsing (PFA/PFB container reading, eexec/charstring decryption, and Type 1 charstring outline decoding with standard glyph name resolution), hhea/hmtx metrics, tolerant format-0 kern lookup, and name/style metadata (family/subfamily/full/PostScript name, bold/italic/fixed-pitch), with a per-font decoded-outline cache bounded by both entry count and total retained geometry cost. */ comment sourceRef /* Source: src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs, src/DemaConsulting.CanvasNet/Fonts/SfntContainer.cs, src/DemaConsulting.CanvasNet/Fonts/CmapTable.cs, src/DemaConsulting.CanvasNet/Fonts/GlyfLocaReader.cs, src/DemaConsulting.CanvasNet/Fonts/IGlyphOutlineSource.cs, src/DemaConsulting.CanvasNet/Fonts/CffTable.cs, src/DemaConsulting.CanvasNet/Fonts/CffCharstringInterpreter.cs, src/DemaConsulting.CanvasNet/Fonts/CffStandardEncoding.cs, src/DemaConsulting.CanvasNet/Fonts/Type1Table.cs, src/DemaConsulting.CanvasNet/Fonts/Type1CharstringInterpreter.cs, src/DemaConsulting.CanvasNet/Fonts/Type1CharstringDecryption.cs, src/DemaConsulting.CanvasNet/Fonts/Type1PfbReader.cs, src/DemaConsulting.CanvasNet/Fonts/Type1PfaReader.cs, src/DemaConsulting.CanvasNet/Fonts/Type1StandardGlyphNames.cs, src/DemaConsulting.CanvasNet/Fonts/HmtxHheaReader.cs, src/DemaConsulting.CanvasNet/Fonts/KernTable.cs, src/DemaConsulting.CanvasNet/Fonts/NameTable.cs, src/DemaConsulting.CanvasNet/Fonts/StyleTable.cs, src/DemaConsulting.CanvasNet/Fonts/NamespaceDoc.cs */ comment testRef /* Test: test/DemaConsulting.CanvasNet.Tests/Fonts/SfntContainerTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/CmapTableTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/GlyfLocaReaderTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/CffTableTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/CffCharstringInterpreterTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/CffStandardEncodingTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/Type1TableTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/Type1CharstringInterpreterTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/Type1PfbReaderTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/Type1PfaReaderTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/HmtxHheaReaderTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/KernTableTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/NameTableTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/StyleTableTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs, test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontRealFontIntegrationTests.cs, test/DemaConsulting.CanvasNet.Tests/TestSupport/SyntheticFontBuilder.cs */ diff --git a/docs/verification/canvas-net/fonts/true-type-font.md b/docs/verification/canvas-net/fonts/true-type-font.md index c2e57f242..b8bee92db 100644 --- a/docs/verification/canvas-net/fonts/true-type-font.md +++ b/docs/verification/canvas-net/fonts/true-type-font.md @@ -260,12 +260,15 @@ Covers out-of-range referenced glyphs, truncated glyph bytes, invalid contour co **Tests**: `TrueTypeFont_GetGlyphOutline_RepeatedCalls_ReturnMemoizedOutlineEqualToFreshDecode`, `TrueTypeFont_GetGlyphOutline_MalformedGlyph_ThrowsOnEveryCall`, -`TrueTypeFont_GetGlyphOutline_ConcurrentDistinctGlyphs_NeverExceedsCacheCap` +`TrueTypeFont_GetGlyphOutline_ConcurrentDistinctGlyphs_NeverExceedsCacheCap`, +`TrueTypeFont_GetGlyphOutline_OutlineExceedingCostBudget_IsNotCached` Asserts two calls on one font return the same instance, that its subpaths, start points, closed flags and every command equal those decoded by a second font that has cached nothing, and that a glyph with an invalid contour count throws `InvalidDataException` on each call. A 6000-glyph font -requested concurrently from eight threads never holds more than 4096 cached outlines. No timing is asserted. +requested concurrently from eight threads never holds more than 4096 cached outlines. With the +geometry-cost budget lowered below one glyph's cost the outline is not cached (each call returns a +fresh instance), and with the default budget it is cached. No timing is asserted. ##### CanvasNet-Fonts-TrueTypeFont-GlyphIndexValidation: `GetGlyphOutline` Rejects Out-of-Range Glyph Indices diff --git a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs index dff9c1dac..03f44cfe5 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs @@ -225,6 +225,14 @@ private static AxisWeights BuildAxis(int sourceSize, double start, double extent mode = ResamplingMode.Nearest; } + // A footprint far larger than the whole image is a global average on every kernel; Area + // (which drops out-of-image taps) gives that without folding an astronomically long tail + // into an edge pixel + if (mode is not (ResamplingMode.Nearest or ResamplingMode.Area) && scale > (16.0 * sourceSize) + 1024.0) + { + mode = ResamplingMode.Area; + } + var radius = mode switch { ResamplingMode.Bilinear => 1.0, @@ -249,22 +257,22 @@ private static AxisWeights BuildAxis(int sourceSize, double start, double extent switch (mode) { case ResamplingMode.Nearest: - lo = hi = (long)Math.Floor(c); + lo = hi = ToSafeLong(Math.Floor(c)); break; case ResamplingMode.Area: - lo = (long)Math.Floor(c - (scale / 2)); - hi = (long)Math.Ceiling(c + (scale / 2)) - 1; + lo = ToSafeLong(Math.Floor(c - (scale / 2))); + hi = ToSafeLong(Math.Ceiling(c + (scale / 2))) - 1; break; default: var support = radius * Math.Max(1.0, scale); - lo = (long)Math.Ceiling(c - support - 0.5); - hi = (long)Math.Floor(c + support - 0.5); + lo = ToSafeLong(Math.Ceiling(c - support - 0.5)); + hi = ToSafeLong(Math.Floor(c + support - 0.5)); break; } if (hi < lo) { - lo = hi = (long)Math.Floor(c); + lo = hi = ToSafeLong(Math.Floor(c)); } los[o] = lo; @@ -360,20 +368,28 @@ private static double TailWeight(ResamplingMode mode, long from, long to, double } // Midpoint rule over MaxExactTailTaps equal buckets, each bucket weighted by its tap count + // (bucket bounds are computed in double so a huge tail cannot overflow long) var sum = 0.0; for (var b = 0; b < MaxExactTailTaps; b++) { - var b0 = from + (n * b / MaxExactTailTaps); - var b1 = from + (n * (b + 1) / MaxExactTailTaps); + var b0 = from + (long)Math.Floor((double)n * b / MaxExactTailTaps); + var b1 = from + (long)Math.Floor((double)n * (b + 1) / MaxExactTailTaps); if (b1 > b0) { - sum += (b1 - b0) * Weight(mode, ((b0 + b1 - 1) / 2.0) + 0.5 - c, scale); + sum += (b1 - b0) * Weight(mode, (((double)b0 + b1 - 1) / 2.0) + 0.5 - c, scale); } } return sum; } + /// The largest tap coordinate magnitude used; keeps every cast and sum well inside long. + private const double MaxTapCoordinate = 4503599627370496.0; // 2^52 + + /// Clamps a finite or infinite double to +-2^52 and converts it to long (NaN becomes zero). + private static long ToSafeLong(double value) => + double.IsNaN(value) ? 0L : (long)Math.Clamp(value, -MaxTapCoordinate, MaxTapCoordinate); + /// /// Evaluates the filter weight of one source pixel. /// diff --git a/src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs b/src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs index 58be2c125..a3ea3b674 100644 --- a/src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs +++ b/src/DemaConsulting.CanvasNet/Fonts/TrueTypeFont.cs @@ -132,6 +132,19 @@ public sealed class TrueTypeFont /// private const int MaxCachedOutlines = 4096; + /// + /// The default total geometry cost (one unit per subpath plus one per command) the outline + /// cache retains per font, so retained memory is bounded even when individual glyphs are + /// large (the decoder permits up to 200,000 points/commands per glyph). + /// + private const long MaxCachedOutlineCost = 1_500_000; + + /// The cost budget in effect; guarded by when admitting. + private readonly long _outlineCostBudget = MaxCachedOutlineCost; + + /// The summed cost of the cached outlines; guarded by . + private long _cachedOutlineCost; + /// /// Decoded outlines by glyph index. A is immutable, so a cached instance /// is safely shared by every caller; only successful decodes are stored. @@ -519,15 +532,34 @@ public Path GetGlyphOutline(int glyphIndex) return cached; } + // Admit only while both the entry cap and the geometry budget hold; oversized outlines are + // simply decoded again on demand if (_outlineCache.Count < MaxCachedOutlines) { - _outlineCache[glyphIndex] = outline; + var cost = OutlineCost(outline); + if (cost <= _outlineCostBudget - _cachedOutlineCost) + { + _outlineCache[glyphIndex] = outline; + _cachedOutlineCost += cost; + } } } return outline; } + /// Measures an outline's retained geometry: one unit per subpath plus one per command. + private static long OutlineCost(Path outline) + { + long cost = 0; + foreach (var subpath in outline.Subpaths) + { + cost += 1 + subpath.Commands.Count; + } + + return cost; + } + /// /// Looks up a glyph's advance width. /// diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs index 81fa2f553..58cd1071c 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs @@ -392,6 +392,78 @@ public void TryResampleToDevice_TinyScale_CompletesWithSaneWindow() window?.Dispose(); } + /// + /// A huge source footprint (tiny placement) averages the whole image for every filter, + /// never selecting an edge pixel or overflowing tap arithmetic. + /// + [Theory] + [InlineData(ResamplingMode.Auto, 1e-19f)] + [InlineData(ResamplingMode.Area, 1e-19f)] + [InlineData(ResamplingMode.Bilinear, 1e-19f)] + [InlineData(ResamplingMode.Bicubic, 1e-19f)] + [InlineData(ResamplingMode.Lanczos3, 1e-19f)] + [InlineData(ResamplingMode.Bilinear, 1e-12f)] + [InlineData(ResamplingMode.Bicubic, 1e-12f)] + [InlineData(ResamplingMode.Lanczos3, 1e-12f)] + [InlineData(ResamplingMode.Bilinear, 1e-6f)] + [InlineData(ResamplingMode.Bicubic, 1e-6f)] + [InlineData(ResamplingMode.Lanczos3, 1e-6f)] + public void TryResampleToDevice_HugeFootprintTwoTone_YieldsMean(ResamplingMode mode, float scale) + { + // Left half black, right half R=200 (mean 100), 8192 wide + using var source = new Surface(8192, 2); + for (var y = 0; y < 2; y++) + { + for (var x = 0; x < 8192; x++) + { + source[x, y] = new Rgba32((byte)(x < 4096 ? 0 : 200), 0, 0, 255); + } + } + + // Only x is tiny (y stays 1:1) so the 2-row image still covers device pixel centers in y + var m = new Matrix3x2(scale, 0, 0, 1f, 0.5f, 0f); + Assert.True(SurfaceResampler.TryResampleToDevice(source, m, 4, 4, mode, out var window, out var ox, out var oy)); + Assert.NotNull(window); + using (window) + { + Assert.Equal(0, ox); + Assert.Equal(0, oy); + Assert.Equal(1, window.Width); + Assert.Equal(2, window.Height); + Assert.InRange(window[0, 0].R, 98, 102); + Assert.Equal(255, window[0, 0].A); + } + } + + /// Less extreme tiny scales on a constant image keep the constant color for every filter. + [Theory] + [InlineData(ResamplingMode.Bilinear, 1e-4f)] + [InlineData(ResamplingMode.Bicubic, 1e-4f)] + [InlineData(ResamplingMode.Lanczos3, 1e-4f)] + [InlineData(ResamplingMode.Bilinear, 1e-5f)] + [InlineData(ResamplingMode.Bicubic, 1e-5f)] + [InlineData(ResamplingMode.Lanczos3, 1e-5f)] + [InlineData(ResamplingMode.Area, 1e-5f)] + public void TryResampleToDevice_LargeFootprintConstantImage_StaysConstant(ResamplingMode mode, float scale) + { + using var source = new Surface(8192, 2); + for (var y = 0; y < 2; y++) + { + for (var x = 0; x < 8192; x++) + { + source[x, y] = new Rgba32(40, 80, 120, 255); + } + } + + var m = new Matrix3x2(scale, 0, 0, scale, 0.5f, 0.5f); + Assert.True(SurfaceResampler.TryResampleToDevice(source, m, 4, 4, mode, out var window, out _, out _)); + Assert.NotNull(window); + using (window) + { + Assert.Equal(new Rgba32(40, 80, 120, 255), window[0, 0]); + } + } + /// Folding long out-of-image tails keeps results identical to a direct sum for normal scales. [Fact] public void Resample_NormalScaleEdgeFolding_KeepsConstantImageConstant() diff --git a/test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs b/test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs index 429c862b9..e0f5a7c22 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Fonts/TrueTypeFontTests.cs @@ -387,6 +387,35 @@ public void TrueTypeFont_GetGlyphOutline_ConcurrentDistinctGlyphs_NeverExceedsCa Assert.InRange(cache.Count, 1, 4096); } + /// + /// Proves that an outline whose geometry cost exceeds the cache's cost budget is not + /// retained, while the same outline is retained under the default budget. + /// + [Fact] + public void TrueTypeFont_GetGlyphOutline_OutlineExceedingCostBudget_IsNotCached() + { + // Arrange: one font with a budget below the glyph's cost, one with the default budget + var data = BuildWellFormedFont(); + using var smallStream = new MemoryStream(data); + using var defaultStream = new MemoryStream(data); + var limited = TrueTypeFont.Load(smallStream); + var normal = TrueTypeFont.Load(defaultStream); + var budget = typeof(TrueTypeFont).GetField( + "_outlineCostBudget", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + Assert.NotNull(budget); + budget.SetValue(limited, 2L); + + // Act + var first = limited.GetGlyphOutline(1); + var second = limited.GetGlyphOutline(1); + + // Assert: equal geometry, but not retained; the default budget retains it + Assert.NotSame(first, second); + Assert.Equal(first.Subpaths.Count, second.Subpaths.Count); + Assert.Same(normal.GetGlyphOutline(1), normal.GetGlyphOutline(1)); + } + /// /// Proves that a malformed glyph is never memoized: every call reports it again. /// From ec3b47c11898b610dcd1dd3138d2939795ad3c19 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 15:11:43 -0400 Subject: [PATCH 10/16] Fix reduced-source sampling in rotated image fallback; qualify thin-feature guarantee Map fallback sample coordinates by block factor (x / factor) instead of uniform normalization so a partial last block no longer shifts samples. Applies to PPTX, SVG and PDF. Qualify the thin-feature guarantee to filtering modes other than Nearest. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/reqstream/canvas-net.yaml | 5 +- docs/reqstream/canvas-net/canvas/surface.yaml | 5 +- docs/user_guide/introduction.md | 5 +- .../PdfDocument.Images.cs | 10 ++-- .../PptxDocument.Images.cs | 8 +-- .../SvgCodec.Image.cs | 10 +++- .../Canvas/Surface.cs | 6 ++- .../Canvas/SurfaceResampler.cs | 35 ++++++++++++- .../Canvas/SurfaceResamplerTests.cs | 52 +++++++++++++++++++ 9 files changed, 115 insertions(+), 21 deletions(-) diff --git a/docs/reqstream/canvas-net.yaml b/docs/reqstream/canvas-net.yaml index 5a4cc6651..855734eb5 100644 --- a/docs/reqstream/canvas-net.yaml +++ b/docs/reqstream/canvas-net.yaml @@ -90,8 +90,9 @@ sections: tags: [system] justification: | Callers need to enlarge or shrink decoded images (for example before saving a thumbnail) - without writing their own filter, and thin features such as one-pixel lines must survive - a reduction rather than being dropped by point sampling. + without writing their own filter, and with the filtering modes (all but Nearest) thin + features such as one-pixel lines must survive a reduction rather than being dropped by + point sampling. children: - CanvasNet-Canvas-Resize tests: diff --git a/docs/reqstream/canvas-net/canvas/surface.yaml b/docs/reqstream/canvas-net/canvas/surface.yaml index aa0f00129..f5fccd9d0 100644 --- a/docs/reqstream/canvas-net/canvas/surface.yaml +++ b/docs/reqstream/canvas-net/canvas/surface.yaml @@ -439,10 +439,11 @@ sections: The Surface class shall return a new surface resampled to the requested size using the Nearest, Bilinear, Bicubic (Catmull-Rom), Lanczos3 or Area filter, with Auto choosing Area when shrinking and Bicubic when enlarging per axis, widening the - filter support by the reduction ratio so thin features survive a shrink. + filter support by the reduction ratio so thin features survive a shrink in every + filtering mode other than Nearest. justification: | A separable, weight-table based resampler with a reduction-scaled support gives - predictable quality at every ratio and never drops one-pixel lines. + predictable quality at every ratio and, outside Nearest, never drops one-pixel lines. tests: - Resize_Nearest_Upscale_ReplicatesPixels - Resize_Bilinear_Upscale_InterpolatesLinearly diff --git a/docs/user_guide/introduction.md b/docs/user_guide/introduction.md index 5fa771c37..6b77d4bf1 100644 --- a/docs/user_guide/introduction.md +++ b/docs/user_guide/introduction.md @@ -215,8 +215,9 @@ public Surface Resize(int width, int height, ResamplingMode mode = ResamplingMod ``` Creates a new, independent `Surface` resampled to the requested size. Resampling is done in -premultiplied alpha, so transparent pixels leave no color fringe, and thin features such as -one-pixel lines survive a reduction. A request for the current size returns an exact copy. +premultiplied alpha, so transparent pixels leave no color fringe, and with any filtering mode other +than `Nearest` thin features such as one-pixel lines survive a reduction (`Nearest` uses point +sampling and can drop them). A request for the current size returns an exact copy. **Parameters:** diff --git a/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs b/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs index 5d5f053df..22646d75c 100644 --- a/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs +++ b/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs @@ -976,11 +976,11 @@ private void CompositeImageOntoSurface(Surface image, Matrix3x2 ctm) // Rotated or skewed placement: inverse-map each destination pixel and sample a // prefiltered source bilinearly - var sampled = SurfaceResampler.Prefilter(image, pixelToDevice, out _); + var sampled = SurfaceResampler.Prefilter(image, pixelToDevice, out _, out var factorX, out var factorY); var reduced = !ReferenceEquals(sampled, image); try { - CompositeSampledImage(sampled, ctm, inverse); + CompositeSampledImage(sampled, image.Width, image.Height, factorX, factorY, ctm, inverse); } finally { @@ -1024,8 +1024,8 @@ private void CompositeWindow(Surface window, int originX, int originY) } } - /// Paints (the original or its prefiltered reduction) through with bilinear sampling (the rotated/skewed fallback). - private void CompositeSampledImage(Surface sampled, Matrix3x2 ctm, Matrix3x2 inverse) + /// Paints (the original or its prefiltered reduction by by blocks of the by original) through with bilinear sampling (the rotated/skewed fallback). + private void CompositeSampledImage(Surface sampled, int imageWidth, int imageHeight, int factorX, int factorY, Matrix3x2 ctm, Matrix3x2 inverse) { var clip = _gs?.Clip; var corner00 = Vector2.Transform(new Vector2(0, 0), ctm); @@ -1062,7 +1062,7 @@ private void CompositeSampledImage(Surface sampled, Matrix3x2 ctm, Matrix3x2 inv continue; } - var sourcePixel = SurfaceResampler.SampleBilinear(sampled, u, 1 - v); + var sourcePixel = SurfaceResampler.SampleBilinearReduced(sampled, u * imageWidth, (1 - v) * imageHeight, factorX, factorY); if (clipCoverage < 1f) { diff --git a/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs b/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs index 6d87d676f..dfc293b1c 100644 --- a/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs +++ b/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs @@ -748,7 +748,7 @@ internal static void PaintPicture( // Rotated or skewed pictures: inverse-map each destination pixel and sample the // source window (prefiltered when shrinking) bilinearly. - var prefiltered = SurfaceResampler.Prefilter(source, pixelToSurface, out _); + var prefiltered = SurfaceResampler.Prefilter(source, pixelToSurface, out _, out var factorX, out var factorY); try { for (var y = startY; y <= endY; y++) @@ -771,9 +771,9 @@ internal static void PaintPicture( } // Remap the unit-square sample point through the srcRect crop; no (1 - v) flip - var imageU = (float)((cropLeftPx - windowX0 + (u * cropWidthPx)) / windowW); - var imageV = (float)((cropTopPx - windowY0 + (v * cropHeightPx)) / windowH); - var sourcePixel = SurfaceResampler.SampleBilinear(prefiltered, imageU, imageV); + var imageX = (float)(cropLeftPx - windowX0 + (u * cropWidthPx)); + var imageY = (float)(cropTopPx - windowY0 + (v * cropHeightPx)); + var sourcePixel = SurfaceResampler.SampleBilinearReduced(prefiltered, imageX, imageY, factorX, factorY); surface[x, y] = Rgba32.CompositeOver(surface[x, y], ScaleAlpha(sourcePixel, maskAlpha)); } } diff --git a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs index 8e698dbec..0b31726cf 100644 --- a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs +++ b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs @@ -431,7 +431,13 @@ private static Surface SampleImageIntoRegion( } // Rotated or skewed: inverse-map each pixel; smooth mode samples a prefiltered source bilinearly - var smooth = nearest ? decodedSurface : SurfaceResampler.Prefilter(decodedSurface, imageToRegion, out _); + var smooth = decodedSurface; + var factorX = 1; + var factorY = 1; + if (!nearest) + { + smooth = SurfaceResampler.Prefilter(decodedSurface, imageToRegion, out _, out factorX, out factorY); + } for (var row = 0; row < pixelHeight; row++) { @@ -463,7 +469,7 @@ private static Surface SampleImageIntoRegion( } else { - resultRow[col] = SurfaceResampler.SampleBilinear(smooth, imagePoint.X / decodedWidth, imagePoint.Y / decodedHeight); + resultRow[col] = SurfaceResampler.SampleBilinearReduced(smooth, imagePoint.X, imagePoint.Y, factorX, factorY); } } } diff --git a/src/DemaConsulting.CanvasNet/Canvas/Surface.cs b/src/DemaConsulting.CanvasNet/Canvas/Surface.cs index 1335ba46c..ae1a3cf75 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/Surface.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/Surface.cs @@ -459,8 +459,10 @@ public Surface Crop(int x, int y, int width, int height) /// /// Resizing never changes this surface. Filtering is performed in premultiplied alpha, /// results are clamped to the valid range, and the image edges are clamped (not wrapped). - /// When an axis is reduced the filter support is widened by the reduction ratio, so thin - /// features are attenuated rather than dropped. Working memory is bounded independently + /// When an axis is reduced with a filtering mode (any mode other than + /// ) the filter support is widened by the reduction + /// ratio, so thin features are attenuated rather than dropped; Nearest uses point + /// sampling and can drop them. Working memory is bounded independently /// of the image size. The aspect ratio is not preserved; use for that. /// /// diff --git a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs index 4d375e2ab..81adf834e 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs @@ -60,8 +60,19 @@ internal static (int Fx, int Fy) ComputeFactors(int width, int height, Matrix3x2 /// caller must not dispose it as a temporary. Otherwise a new surface the caller owns and /// must dispose. /// - internal static Surface Prefilter(Surface source, Matrix3x2 pixelToDevice, out bool useBilinear) + internal static Surface Prefilter(Surface source, Matrix3x2 pixelToDevice, out bool useBilinear) => + Prefilter(source, pixelToDevice, out useBilinear, out _, out _); + + /// + /// As , additionally reporting the block + /// factors used, so callers can map source-pixel coordinates onto the reduced surface with + /// (the last block may be partial, so the reduced size + /// does not scale the source size uniformly). + /// + internal static Surface Prefilter(Surface source, Matrix3x2 pixelToDevice, out bool useBilinear, out int factorX, out int factorY) { + factorX = 1; + factorY = 1; var sx = Math.Sqrt(((double)pixelToDevice.M11 * pixelToDevice.M11) + ((double)pixelToDevice.M12 * pixelToDevice.M12)); var sy = Math.Sqrt(((double)pixelToDevice.M21 * pixelToDevice.M21) + ((double)pixelToDevice.M22 * pixelToDevice.M22)); useBilinear = IsShrink(sx) || IsShrink(sy); @@ -71,7 +82,27 @@ internal static Surface Prefilter(Surface source, Matrix3x2 pixelToDevice, out b } var (fx, fy) = ComputeFactors(source.Width, source.Height, pixelToDevice); - return fx == 1 && fy == 1 ? source : BoxReduce(source, fx, fy); + if (fx == 1 && fy == 1) + { + return source; + } + + factorX = fx; + factorY = fy; + return BoxReduce(source, fx, fy); + } + + /// + /// Samples a result bilinearly at a position given in the ORIGINAL + /// (unreduced) pixel coordinates. Reduced pixel i covers original pixels + /// [i * factorX, (i + 1) * factorX), so the position maps to x / factorX in + /// reduced pixels regardless of a partial last block. + /// + internal static Rgba32 SampleBilinearReduced(Surface reduced, float x, float y, int factorX, int factorY) + { + var u = x / factorX / reduced.Width; + var v = y / factorY / reduced.Height; + return SampleBilinear(reduced, u, v); } /// diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs index 58cd1071c..cdfdf5a09 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs @@ -74,6 +74,58 @@ public void Prefilter_FractionalAnisotropic_UsesRoundedFactorsAndPartialEdgeBloc Assert.Equal(200, reduced[2, 0].R); // last block covers only the final pixel } + /// + /// A reduced surface with a partial last block is sampled by physical position: the boundary + /// between original pixels 2 and 3 (x = 3) lands exactly on the center of reduced pixel 1. + /// + [Fact] + public void SampleBilinearReduced_PartialLastBlock_MapsByFactorNotByUniformScale() + { + using var source = new Surface(5, 1); + for (var x = 0; x < 5; x++) + { + source[x, 0] = x < 3 ? new Rgba32(0, 0, 0, 255) : new Rgba32(255, 255, 255, 255); + } + + using var reduced = SurfaceResampler.Prefilter(source, Matrix3x2.CreateScale(0.45f, 1f), out _, out var fx, out var fy); + + Assert.Equal(3, reduced.Width); + Assert.Equal(2, fx); + Assert.Equal(1, fy); + Assert.Equal(0, reduced[0, 0].R); + Assert.Equal(128, reduced[1, 0].R); // (0 + 255) / 2 + Assert.Equal(255, reduced[2, 0].R); + + // x = 3 is the center of reduced pixel 1 (covering 2..4): exactly that block's value + Assert.Equal(128, SurfaceResampler.SampleBilinearReduced(reduced, 3f, 0.5f, fx, fy).R); + + // x = 1 is the center of reduced pixel 0 + Assert.Equal(0, SurfaceResampler.SampleBilinearReduced(reduced, 1f, 0.5f, fx, fy).R); + + // Halfway between those centers (x = 2) blends them equally + Assert.InRange(SurfaceResampler.SampleBilinearReduced(reduced, 2f, 0.5f, fx, fy).R, 63, 65); + + // Uniform normalization (x / 5) would have returned about 166 at x = 3 + Assert.NotInRange(SurfaceResampler.SampleBilinear(reduced, 3f / 5f, 0.5f).R, 120, 136); + } + + /// The vertical axis is mapped by its own factor when the last block is partial. + [Fact] + public void SampleBilinearReduced_PartialLastBlockVertical_MapsByFactor() + { + using var source = new Surface(1, 5); + for (var y = 0; y < 5; y++) + { + source[0, y] = y < 3 ? new Rgba32(0, 0, 0, 255) : new Rgba32(255, 255, 255, 255); + } + + using var reduced = SurfaceResampler.Prefilter(source, Matrix3x2.CreateScale(1f, 0.45f), out _, out var fx, out var fy); + + Assert.Equal(1, fx); + Assert.Equal(2, fy); + Assert.Equal(128, SurfaceResampler.SampleBilinearReduced(reduced, 0.5f, 3f, fx, fy).R); + } + /// Averaging is premultiplied: a transparent pixel contributes no color. [Fact] public void Prefilter_PremultipliedAlpha_TransparentPixelsDoNotBleedColor() From 09e0768585fe512db94f1aea15e78d9e3266dc19 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 15:43:19 -0400 Subject: [PATCH 11/16] Make CompositeSpanWorkspace dispose idempotent; add feImage resampling tests; qualify Nearest thin-feature docs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/canvas-net/canvas/surface.md | 3 +- docs/reqstream/canvas-net-svg/svg-codec.yaml | 2 + docs/verification/canvas-net-svg/svg-codec.md | 7 ++- .../verification/canvas-net/canvas/surface.md | 3 +- .../Canvas/Surface.cs | 15 ++++++- .../SvgImageResamplingTests.cs | 44 +++++++++++++++++++ .../Canvas/SurfaceTests.cs | 29 ++++++++++++ 7 files changed, 97 insertions(+), 6 deletions(-) diff --git a/docs/design/canvas-net/canvas/surface.md b/docs/design/canvas-net/canvas/surface.md index 76f198e9f..ec4b128e9 100644 --- a/docs/design/canvas-net/canvas/surface.md +++ b/docs/design/canvas-net/canvas/surface.md @@ -498,7 +498,8 @@ images smoothly. **Engine.** `Resample` maps the center of output pixel `o` to source coordinate `start + (o + 0.5) * extent / outDim` (a negative extent flips the axis) and builds, per axis, a table of tap indices and normalized weights for the chosen filter. When shrinking, the kernel support is -multiplied by the reduction ratio so every source pixel contributes (thin lines cannot be skipped). +multiplied by the reduction ratio so every source pixel contributes (thin lines cannot be skipped by +the filtering modes; `Nearest` point-samples and can skip them). Taps outside the image fold into the edge pixel, except `Area`, which drops them and renormalizes. Weight work is bounded by the source size, not the filter footprint (an extreme scale from a crafted placement can imply about 1e9 taps): only the in-image intersection is iterated tap by tap, and each folded out-of-image diff --git a/docs/reqstream/canvas-net-svg/svg-codec.yaml b/docs/reqstream/canvas-net-svg/svg-codec.yaml index fa851e043..641ef68aa 100644 --- a/docs/reqstream/canvas-net-svg/svg-codec.yaml +++ b/docs/reqstream/canvas-net-svg/svg-codec.yaml @@ -1472,6 +1472,8 @@ sections: - Image_RenderingInheritedFromGroup_IsNearest - Image_RenderingBogus_InheritsPixelatedFromParent - Image_RenderingSmoothKeyword_OverridesPixelatedParent + - FeImage_Enlarged_IsSmooth + - FeImage_Shrunk_KeepsOnePixelLine - id: CanvasNetSvg-SvgCodec-PatternTileSmoothing title: >- diff --git a/docs/verification/canvas-net-svg/svg-codec.md b/docs/verification/canvas-net-svg/svg-codec.md index 1cbcce90c..7c5e7e60c 100644 --- a/docs/verification/canvas-net-svg/svg-codec.md +++ b/docs/verification/canvas-net-svg/svg-codec.md @@ -1482,12 +1482,15 @@ rather than throwing or dividing by zero. **Tests**: `Image_Enlarged_IsSmooth`, `Image_RenderingAttribute_IsNearest`, `Image_RenderingStyle_IsNearest`, `Image_RenderingStylesheet_IsNearest`, `Image_Shrunk_KeepsOnePixelLine`, `Image_RenderingInheritedFromGroup_IsNearest`, `Image_RenderingBogus_InheritsPixelatedFromParent`, -`Image_RenderingSmoothKeyword_OverridesPixelatedParent` +`Image_RenderingSmoothKeyword_OverridesPixelatedParent`, `FeImage_Enlarged_IsSmooth`, +`FeImage_Shrunk_KeepsOnePixelLine` `SvgImageResamplingTests.cs` enlarges a 2x1 black/white image to 40x4: by default the row has many gray levels; with `image-rendering` `pixelated` or `crisp-edges` (attribute, style declaration or stylesheet rule) it has only the two source levels. A 100x1 image with a one-pixel line shrunk to 17 -pixels keeps its area-proportional ink. +pixels keeps its area-proportional ink. The same enlarged and shrunk rasters are also rendered through +an `feImage` primitive (`FeImage_Enlarged_IsSmooth`, `FeImage_Shrunk_KeepsOnePixelLine`) so a regression +to nearest-neighbor there is detected. `image-rendering` is inherited from an ancestor `g` (`Image_RenderingInheritedFromGroup_IsNearest`). An unrecognized value (for example `bogus`) is ignored, so the element keeps inheriting the parent's diff --git a/docs/verification/canvas-net/canvas/surface.md b/docs/verification/canvas-net/canvas/surface.md index ef06fcafc..4102235c3 100644 --- a/docs/verification/canvas-net/canvas/surface.md +++ b/docs/verification/canvas-net/canvas/surface.md @@ -438,7 +438,8 @@ The bilinear sampler returns pixel centres exactly, blends midpoints, and clamps `SurfaceResizeTests.cs` checks exact values on tiny inputs for `Nearest`, `Bilinear` and `Area`, that `Bicubic`/`Lanczos3` stay inside the byte range on a step edge, that a constant image stays -constant at many ratios, that a one-pixel line survives downscaling at ratios from 1.001:1 to 100:1 +constant at many ratios, that a one-pixel line survives downscaling in every mode except `Nearest` +at ratios from 1.001:1 to 100:1 (with `Area` conserving its ink to within 10 percent), that enlargement has no jumps, and that `Auto` averages on the shrinking axis. No timing is asserted. diff --git a/src/DemaConsulting.CanvasNet/Canvas/Surface.cs b/src/DemaConsulting.CanvasNet/Canvas/Surface.cs index ae1a3cf75..6cd7a04a8 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/Surface.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/Surface.cs @@ -1551,6 +1551,12 @@ public CompositeSpanWorkspace(int capacity) private bool _pooled; + /// + /// True while a caller owns the workspace (from construction or until + /// ); false while cached or after its arrays were released. + /// + private bool _inUse = true; + private static void Cache(CompositeSpanWorkspace workspace) => _cached = workspace; /// @@ -1574,10 +1580,13 @@ public static CompositeSpanWorkspace Rent(int capacity) { if (cached.Capacity >= capacity) { + cached._inUse = true; return cached; } + // Evict: release its arrays exactly once; a later Dispose by a stale holder is a no-op. cached._pooled = false; + cached._inUse = true; cached.Dispose(); } @@ -1605,12 +1614,14 @@ public static CompositeSpanWorkspace Rent(int capacity) /// public void Dispose() { - if (ReferenceEquals(_cached, this)) + if (!_inUse) { - // Already handed back to the cache: a repeated Dispose must not free its arrays. + // Already cached or released (for example a repeated Dispose, or a Dispose after + // eviction from the cache): the arrays must be returned to the pool at most once. return; } + _inUse = false; if (_pooled && _cached == null) { // Keep the arrays for the next fill on this thread instead of returning them. diff --git a/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs b/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs index 395eac4b4..2311eb5df 100644 --- a/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs +++ b/test/DemaConsulting.CanvasNet.Svg.Tests/SvgImageResamplingTests.cs @@ -93,6 +93,50 @@ public void Image_Shrunk_KeepsOnePixelLine() Assert.InRange(ink, 255 * 0.17 * 0.8, 255 * 0.17 * 1.2 + 1); } + /// Renders a data-URI raster through an feImage primitive filling the whole canvas. + private static Surface RenderFeImage(string uri, int width, int height) + { + var svg = $"" + + "" + + $"" + + $""; + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(svg)); + return SvgCodec.Load(stream, width, height); + } + + /// An enlarged raster feImage is smoothly interpolated, not nearest-neighbor. + [Fact] + public void FeImage_Enlarged_IsSmooth() + { + using var surface = RenderFeImage(TwoPixelPng(), 40, 4); + + Assert.True(DistinctLevels(surface) > 8); + Assert.InRange(surface[20, 2].R, 1, 254); + Assert.Equal(0, surface[2, 2].R); + Assert.Equal(255, surface[37, 2].R); + } + + /// A shrunken raster feImage keeps a one-pixel line by area averaging. + [Fact] + public void FeImage_Shrunk_KeepsOnePixelLine() + { + using var source = new Surface(100, 1); + source.Clear(new Rgba32(255, 255, 255, 255)); + source[37, 0] = new Rgba32(0, 0, 0, 255); + using var stream = new MemoryStream(); + PngCodec.Save(source, stream); + var uri = "data:image/png;base64," + Convert.ToBase64String(stream.ToArray()); + using var surface = RenderFeImage(uri, 17, 1); + + double ink = 0; + for (var x = 0; x < 17; x++) + { + ink += 255 - surface[x, 0].R; + } + + Assert.InRange(ink, 255 * 0.17 * 0.8, 255 * 0.17 * 1.2 + 1); + } + /// Renders the enlarged image inside a group with the given group attributes and image attributes. private static Surface RenderInGroup(string groupAttributes, string imageAttributes) { diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceTests.cs index 6cda2bb25..07e358377 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceTests.cs @@ -1462,6 +1462,35 @@ public void CompositeSpanWorkspace_Rent_AfterDispose_ReusesCachedWorkspaceWithSu Assert.Same(first, second); } + /// + /// Proves that disposing a workspace, having it evicted from the thread cache by a larger + /// rent, and disposing it again (plus a double Dispose) returns its arrays to the pool at + /// most once, so later concurrent rents never lease the same scratch array. + /// + [Fact] + public void CompositeSpanWorkspace_DisposeEvictDispose_ReturnsArraysAtMostOnce() + { + // Arrange + var held = Surface.CompositeSpanWorkspace.Rent(10); + held.Dispose(); + held.Dispose(); + + // Act - a larger rent evicts the cached instance; the stale holder disposes again + var large = Surface.CompositeSpanWorkspace.Rent(100000); + held.Dispose(); + held.Dispose(); + large.Dispose(); + using var first = Surface.CompositeSpanWorkspace.Rent(10); + using var second = Surface.CompositeSpanWorkspace.Rent(10); + + // Assert + Assert.NotSame(first, second); + Assert.NotSame(first.Bg.RFloat, second.Bg.RFloat); + Assert.NotSame(first.Fg.RFloat, second.Fg.RFloat); + Assert.NotSame(first.Work.OutR, second.Work.OutR); + Assert.NotSame(first.Bg.RBytes, second.Bg.RBytes); + } + /// /// Proves two workspaces rented at the same time on one thread are distinct instances, /// so nested use never shares scratch buffers. From a24eba2755058e43b4f50ff2ce02bfe04ba553fb Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 16:14:58 -0400 Subject: [PATCH 12/16] Fix negative srcRect overhang and partial-block reduced sampling Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/canvas-net-pptx/pptx-document.md | 4 +- docs/design/canvas-net/canvas/surface.md | 4 +- .../PdfDocument.Images.cs | 2 +- .../PptxDocument.Images.cs | 11 +++- .../SvgCodec.Image.cs | 2 +- .../Canvas/SurfaceResampler.cs | 44 ++++++++++++-- .../PptxImagesTests.cs | 29 ++++++++++ .../Canvas/SurfaceResamplerTests.cs | 58 +++++++++++++++++-- 8 files changed, 139 insertions(+), 15 deletions(-) diff --git a/docs/design/canvas-net-pptx/pptx-document.md b/docs/design/canvas-net-pptx/pptx-document.md index 734d71b95..c564f0ae3 100644 --- a/docs/design/canvas-net-pptx/pptx-document.md +++ b/docs/design/canvas-net-pptx/pptx-document.md @@ -855,7 +855,9 @@ resolves a `` shape's `/` into a decoded core `Surfac crop edge fold into the window's own edge pixels and pixels outside the window never bleed into it. The window is a whole-pixel superset of the (possibly fractional) crop, so a partially covered border pixel still contributes to the crop edge; the - fractional crop offset is part of the mapping. A rotated picture inverts the matrix once and + fractional crop offset is part of the mapping. A crop that overhangs the image (negative `srcRect` + edges) takes the inverse-mapped path below instead, whose edge-clamped sampling replicates the source + edge pixels across the overhang. A rotated picture inverts the matrix once and bilinear-samples an area-prefiltered copy of the same cropped window per destination pixel whose inverse-mapped coordinate falls within `[0,1]x[0,1]`. Each sampled source pixel is alpha-blended "over" the existing destination diff --git a/docs/design/canvas-net/canvas/surface.md b/docs/design/canvas-net/canvas/surface.md index ec4b128e9..f37967ce4 100644 --- a/docs/design/canvas-net/canvas/surface.md +++ b/docs/design/canvas-net/canvas/surface.md @@ -520,6 +520,8 @@ composite it 1:1; it returns `false` for rotation, skew or non-finite/degenerate rotation/skew component is tolerated only while it moves no pixel by more than 0.01 device pixel, i.e. `|M12|*height` and `|M21|*width` are each at most 0.01), and `true` with no window when nothing is visible. Rotated or skewed placements use `Prefilter` (area-reduce -by an integer factor) plus `SampleBilinear` (inverse mapped, premultiplied, edge-clamped). +by an integer factor) plus `SampleBilinear` (inverse mapped, premultiplied, edge-clamped); +`SampleBilinearReduced` maps original-pixel positions onto the reduced surface through the actual block +centers, so a partial last block is sampled at its own center rather than blended with its neighbor. `SampleBilinearWrapped` is the wrap-around bilinear sampler used for magnified pattern tiles. `BoxReduce` is the `Area` mode with integer factors. diff --git a/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs b/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs index 22646d75c..e8b5989ad 100644 --- a/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs +++ b/src/DemaConsulting.CanvasNet.Pdf/PdfDocument.Images.cs @@ -1062,7 +1062,7 @@ private void CompositeSampledImage(Surface sampled, int imageWidth, int imageHei continue; } - var sourcePixel = SurfaceResampler.SampleBilinearReduced(sampled, u * imageWidth, (1 - v) * imageHeight, factorX, factorY); + var sourcePixel = SurfaceResampler.SampleBilinearReduced(sampled, u * imageWidth, (1 - v) * imageHeight, factorX, factorY, imageWidth, imageHeight); if (clipCoverage < 1f) { diff --git a/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs b/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs index dfc293b1c..baf6f4e7b 100644 --- a/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs +++ b/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs @@ -733,7 +733,14 @@ internal static void PaintPicture( 0f, (float)(1.0 / cropHeightPx), (float)((windowX0 - cropLeftPx) / cropWidthPx), (float)((windowY0 - cropTopPx) / cropHeightPx)); var pixelToSurface = pixelToUnit * unitToSurface; - if (SurfaceResampler.TryResampleToDevice(source, pixelToSurface, surface.Width, surface.Height, ResamplingMode.Auto, out var window, out var originX, out var originY)) + // A crop reaching beyond the image (negative srcRect edges) must replicate the edge pixels + // across the overhang, which the edge-clamped inverse-mapped path below does and the + // window-only resample would not (it would leave the overhang transparent). + var cropOverhangs = cropLeftPx < 0 || cropTopPx < 0 + || cropLeftPx + cropWidthPx > image.Width + 1e-6 + || cropTopPx + cropHeightPx > image.Height + 1e-6; + if (!cropOverhangs + && SurfaceResampler.TryResampleToDevice(source, pixelToSurface, surface.Width, surface.Height, ResamplingMode.Auto, out var window, out var originX, out var originY)) { using (window) { @@ -773,7 +780,7 @@ internal static void PaintPicture( // Remap the unit-square sample point through the srcRect crop; no (1 - v) flip var imageX = (float)(cropLeftPx - windowX0 + (u * cropWidthPx)); var imageY = (float)(cropTopPx - windowY0 + (v * cropHeightPx)); - var sourcePixel = SurfaceResampler.SampleBilinearReduced(prefiltered, imageX, imageY, factorX, factorY); + var sourcePixel = SurfaceResampler.SampleBilinearReduced(prefiltered, imageX, imageY, factorX, factorY, source.Width, source.Height); surface[x, y] = Rgba32.CompositeOver(surface[x, y], ScaleAlpha(sourcePixel, maskAlpha)); } } diff --git a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs index 0b31726cf..de8b4f0b1 100644 --- a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs +++ b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Image.cs @@ -469,7 +469,7 @@ private static Surface SampleImageIntoRegion( } else { - resultRow[col] = SurfaceResampler.SampleBilinearReduced(smooth, imagePoint.X, imagePoint.Y, factorX, factorY); + resultRow[col] = SurfaceResampler.SampleBilinearReduced(smooth, imagePoint.X, imagePoint.Y, factorX, factorY, decodedWidth, decodedHeight); } } } diff --git a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs index 81adf834e..902af6e5c 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.cs @@ -95,16 +95,50 @@ internal static Surface Prefilter(Surface source, Matrix3x2 pixelToDevice, out b /// /// Samples a result bilinearly at a position given in the ORIGINAL /// (unreduced) pixel coordinates. Reduced pixel i covers original pixels - /// [i * factorX, (i + 1) * factorX), so the position maps to x / factorX in - /// reduced pixels regardless of a partial last block. + /// [i * factorX, (i + 1) * factorX) (the last block may be partial). Positions map + /// piecewise through the actual block centers: full blocks map as x / factorX, and + /// the span between the last two block centers is interpolated so the center of a partial + /// last block maps exactly onto that reduced pixel's center. /// - internal static Rgba32 SampleBilinearReduced(Surface reduced, float x, float y, int factorX, int factorY) + /// The box-reduced surface. + /// Horizontal position in original pixels. + /// Vertical position in original pixels. + /// Horizontal block size. + /// Vertical block size. + /// Width of the original (unreduced) image in pixels. + /// Height of the original (unreduced) image in pixels. + internal static Rgba32 SampleBilinearReduced(Surface reduced, float x, float y, int factorX, int factorY, int sourceWidth, int sourceHeight) { - var u = x / factorX / reduced.Width; - var v = y / factorY / reduced.Height; + var u = ReducedCoordinate(x, factorX, reduced.Width, sourceWidth) / reduced.Width; + var v = ReducedCoordinate(y, factorY, reduced.Height, sourceHeight) / reduced.Height; return SampleBilinear(reduced, u, v); } + /// Maps an original-pixel position to reduced-pixel coordinates using actual block centers. + private static float ReducedCoordinate(float position, int factor, int reducedSize, int sourceSize) + { + if (reducedSize < 2) + { + return position / factor; + } + + // Center of the last full-or-partial block and of the one before it (always a full block) + var lastCenter = ((reducedSize - 1) * (double)factor) + ((sourceSize - ((reducedSize - 1) * (double)factor)) / 2.0); + var prevCenter = ((reducedSize - 2) * (double)factor) + (factor / 2.0); + if (position <= prevCenter) + { + return position / factor; + } + + if (position >= lastCenter) + { + return reducedSize - 0.5f; + } + + var t = (position - prevCenter) / (lastCenter - prevCenter); + return (float)(reducedSize - 1.5 + t); + } + /// /// Reduces by averaging by /// blocks in premultiplied alpha; edge blocks average only the diff --git a/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs b/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs index 71c68c10e..8d11447c5 100644 --- a/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs +++ b/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs @@ -290,6 +290,35 @@ public void PaintPicture_WithSrcRectCroppingLeftHalf_SamplesOnlyRightHalf() Assert.Equal(new Rgba32(0, 0, 255, 255), surface[8, 5]); } + /// Proves negative (overhanging) srcRect edges replicate the source edge pixels across the overhang instead of leaving a transparent band, for an axis-aligned picture. + [Fact] + public void PaintPicture_WithNegativeSrcRectEdges_ReplicatesEdgePixelsIntoOverhang() + { + using var image = BuildTwoToneImage(10, 10); + using var surface = new Surface(30, 30); + + // Left/top overhang by half an image, right/bottom by a quarter: the footprint is 1.75x + // the image, so the left overhang spans 0.5/1.75 of the surface width. + var srcRect = new PptxSrcRect(Left: -0.5f, Top: -0.5f, Right: -0.25f, Bottom: -0.25f); + + PptxDocument.PaintPicture(surface, image, srcRect, Matrix3x2.Identity, widthEmu: 30f, heightEmu: 30f); + + // Left overhang (x < ~8.6) replicates the red left edge; the right overhang (x > ~25.7) the blue right edge + Assert.Equal(new Rgba32(255, 0, 0, 255), surface[2, 15]); + Assert.Equal(new Rgba32(255, 0, 0, 255), surface[2, 2]); + Assert.Equal(new Rgba32(0, 0, 255, 255), surface[28, 15]); + Assert.Equal(new Rgba32(0, 0, 255, 255), surface[28, 28]); + + // No pixel anywhere is left transparent + for (var y = 0; y < 30; y++) + { + for (var x = 0; x < 30; x++) + { + Assert.Equal(255, surface[x, y].A); + } + } + } + /// Proves a translated shape-to-surface transform shifts the painted footprint accordingly. [Fact] public void PaintPicture_TranslatedTransform_ShiftsPaintedFootprint() diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs index cdfdf5a09..2ef288aaf 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs @@ -97,13 +97,19 @@ public void SampleBilinearReduced_PartialLastBlock_MapsByFactorNotByUniformScale Assert.Equal(255, reduced[2, 0].R); // x = 3 is the center of reduced pixel 1 (covering 2..4): exactly that block's value - Assert.Equal(128, SurfaceResampler.SampleBilinearReduced(reduced, 3f, 0.5f, fx, fy).R); + Assert.Equal(128, SurfaceResampler.SampleBilinearReduced(reduced, 3f, 0.5f, fx, fy, 5, 1).R); // x = 1 is the center of reduced pixel 0 - Assert.Equal(0, SurfaceResampler.SampleBilinearReduced(reduced, 1f, 0.5f, fx, fy).R); + Assert.Equal(0, SurfaceResampler.SampleBilinearReduced(reduced, 1f, 0.5f, fx, fy, 5, 1).R); // Halfway between those centers (x = 2) blends them equally - Assert.InRange(SurfaceResampler.SampleBilinearReduced(reduced, 2f, 0.5f, fx, fy).R, 63, 65); + Assert.InRange(SurfaceResampler.SampleBilinearReduced(reduced, 2f, 0.5f, fx, fy, 5, 1).R, 63, 65); + + // The last (partial, one-pixel) block's center x = 4.5 is exactly that reduced pixel + Assert.Equal(255, SurfaceResampler.SampleBilinearReduced(reduced, 4.5f, 0.5f, fx, fy, 5, 1).R); + + // Halfway between block 1's center (3) and the last block's center (4.5) blends them equally + Assert.InRange(SurfaceResampler.SampleBilinearReduced(reduced, 3.75f, 0.5f, fx, fy, 5, 1).R, 190, 192); // Uniform normalization (x / 5) would have returned about 166 at x = 3 Assert.NotInRange(SurfaceResampler.SampleBilinear(reduced, 3f / 5f, 0.5f).R, 120, 136); @@ -123,7 +129,51 @@ public void SampleBilinearReduced_PartialLastBlockVertical_MapsByFactor() Assert.Equal(1, fx); Assert.Equal(2, fy); - Assert.Equal(128, SurfaceResampler.SampleBilinearReduced(reduced, 0.5f, 3f, fx, fy).R); + Assert.Equal(128, SurfaceResampler.SampleBilinearReduced(reduced, 0.5f, 3f, fx, fy, 1, 5).R); + Assert.Equal(255, SurfaceResampler.SampleBilinearReduced(reduced, 0.5f, 4.5f, fx, fy, 1, 5).R); + } + + /// Factor 3 over width 7 (blocks 3, 3, 1): the one-pixel last block's center and the transition map by actual block centers. + [Fact] + public void SampleBilinearReduced_Factor3Width7_LastBlockCenterExact() + { + using var source = new Surface(7, 1); + for (var x = 0; x < 7; x++) + { + source[x, 0] = x < 6 ? new Rgba32(0, 0, 0, 255) : new Rgba32(255, 255, 255, 255); + } + + using var reduced = SurfaceResampler.Prefilter(source, Matrix3x2.CreateScale(0.33f, 1f), out _, out var fx, out var fy); + + Assert.Equal(3, fx); + Assert.Equal(3, reduced.Width); + Assert.Equal(255, SurfaceResampler.SampleBilinearReduced(reduced, 6.5f, 0.5f, fx, fy, 7, 1).R); + Assert.Equal(0, SurfaceResampler.SampleBilinearReduced(reduced, 4.5f, 0.5f, fx, fy, 7, 1).R); + + // Halfway between centers 4.5 and 6.5 (x = 5.5) blends equally + Assert.InRange(SurfaceResampler.SampleBilinearReduced(reduced, 5.5f, 0.5f, fx, fy, 7, 1).R, 127, 129); + } + + /// The rotated/skewed fallback path samples a partial last block at its own center rather than blending in the previous block. + [Fact] + public void SampleBilinearReduced_FallbackPathScenario_LastPixelDoesNotBleedPreviousBlock() + { + using var source = new Surface(5, 5); + for (var y = 0; y < 5; y++) + { + for (var x = 0; x < 5; x++) + { + source[x, y] = x == 4 ? new Rgba32(255, 255, 255, 255) : new Rgba32(0, 0, 0, 255); + } + } + + // Rotated and shrunk: no axis-aligned fast path applies, so callers use the prefilter + sampler + var transform = Matrix3x2.CreateScale(0.45f) * Matrix3x2.CreateRotation(0.3f); + using var reduced = SurfaceResampler.Prefilter(source, transform, out _, out var fx, out var fy); + + Assert.Equal(2, fx); + Assert.Equal(2, fy); + Assert.Equal(255, SurfaceResampler.SampleBilinearReduced(reduced, 4.5f, 2.5f, fx, fy, 5, 5).R); } /// Averaging is premultiplied: a transparent pixel contributes no color. From 3bb396f1c10e32651797187680a81d6fd487c7e6 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 17:16:49 -0400 Subject: [PATCH 13/16] Fix PPTX crop window including excluded boundary column Compute crop fractions in double and snap near-integer pixel boundaries before Floor/Ceiling. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../PptxDocument.Images.cs | 27 +++++++++----- .../PptxImagesTests.cs | 36 +++++++++++++++++++ 2 files changed, 55 insertions(+), 8 deletions(-) diff --git a/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs b/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs index baf6f4e7b..b8345c78c 100644 --- a/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs +++ b/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs @@ -704,8 +704,10 @@ internal static void PaintPicture( // Axis-aligned pictures (the overwhelmingly common case) are resampled once to the exact // device-pixel rectangle they cover and composited 1:1; the srcRect crop becomes part of // the pixel-to-device mapping. - var cropWidth = Math.Max(1e-6f, 1f - left - right); - var cropHeight = Math.Max(1e-6f, 1f - top - bottom); + // The fraction math is done in double: float rounding (e.g. 0.6f) can push an exact + // integer pixel boundary a hair past the integer and pull in a whole excluded column. + var cropWidth = Math.Max(1e-6, 1.0 - left - right); + var cropHeight = Math.Max(1e-6, 1.0 - top - bottom); // The srcRect crop must be isolated from the rest of the image. Otherwise the bicubic or // area kernel reads adjacent pixels outside the crop and they bleed into its edge. @@ -713,12 +715,21 @@ internal static void PaintPicture( // folds taps beyond that window into the window's own edge pixels. var cropLeftPx = (double)left * image.Width; var cropTopPx = (double)top * image.Height; - var cropWidthPx = (double)cropWidth * image.Width; - var cropHeightPx = (double)cropHeight * image.Height; - var windowX0 = Math.Clamp((int)Math.Floor(cropLeftPx + 1e-6), 0, image.Width - 1); - var windowY0 = Math.Clamp((int)Math.Floor(cropTopPx + 1e-6), 0, image.Height - 1); - var windowX1 = Math.Clamp((int)Math.Ceiling(cropLeftPx + cropWidthPx - 1e-6) - 1, windowX0, image.Width - 1); - var windowY1 = Math.Clamp((int)Math.Ceiling(cropTopPx + cropHeightPx - 1e-6) - 1, windowY0, image.Height - 1); + var cropWidthPx = cropWidth * image.Width; + var cropHeightPx = cropHeight * image.Height; + + // Values within 1e-4 px of an integer are snapped to it so a boundary that is integral + // up to float parse error never includes a source column/row that is entirely outside. + static double Snap(double v) + { + var nearest = Math.Round(v); + return Math.Abs(v - nearest) < 1e-4 ? nearest : v; + } + + var windowX0 = Math.Clamp((int)Math.Floor(Snap(cropLeftPx)), 0, image.Width - 1); + var windowY0 = Math.Clamp((int)Math.Floor(Snap(cropTopPx)), 0, image.Height - 1); + var windowX1 = Math.Clamp((int)Math.Ceiling(Snap(cropLeftPx + cropWidthPx)) - 1, windowX0, image.Width - 1); + var windowY1 = Math.Clamp((int)Math.Ceiling(Snap(cropTopPx + cropHeightPx)) - 1, windowY0, image.Height - 1); var windowW = windowX1 - windowX0 + 1; var windowH = windowY1 - windowY0 + 1; var cropped = windowW == image.Width && windowH == image.Height diff --git a/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs b/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs index 8d11447c5..a4c4b2561 100644 --- a/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs +++ b/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs @@ -224,6 +224,42 @@ public void PaintPicture_EnlargedCrop_DoesNotBleedPixelsOutsideCrop() } } + /// Proves a non-binary fractional crop landing exactly on an integer pixel boundary excludes the neighboring column (right and left edges). + [Theory] + [InlineData(true)] + [InlineData(false)] + public void PaintPicture_FractionalCropOnIntegerBoundary_NoContaminationFromExcludedColumn(bool cropRight) + { + // The image is 45 px wide and 40 percent is exactly 18 px. A right crop keeps the first 27 columns + // and a left crop keeps the last 27, so the other columns are red and must never leak in. + using var image = new Surface(45, 4); + var blue = new Rgba32(0, 0, 255, 255); + var red = new Rgba32(255, 0, 0, 255); + for (var y = 0; y < 4; y++) + { + for (var x = 0; x < 45; x++) + { + var excluded = cropRight ? x >= 27 : x < 18; + image[x, y] = excluded ? red : blue; + } + } + + using var surface = new Surface(54, 4); + var srcRect = cropRight + ? new PptxSrcRect(Left: 0f, Top: 0f, Right: 0.4f, Bottom: 0f) + : new PptxSrcRect(Left: 0.4f, Top: 0f, Right: 0f, Bottom: 0f); + + PptxDocument.PaintPicture(surface, image, srcRect, Matrix3x2.Identity, widthEmu: 54f, heightEmu: 4f); + + for (var y = 0; y < 4; y++) + { + for (var x = 0; x < 54; x++) + { + Assert.Equal(blue, surface[x, y]); + } + } + } + /// Proves a fractional crop uses the whole-pixel superset window: a partially covered border pixel still contributes to the crop edge. [Fact] public void PaintPicture_FractionalCrop_PartiallyCoveredBorderPixelContributes() From 8520ba3e2af8f0f421da798b75949cf97278ef8a Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 17:26:01 -0400 Subject: [PATCH 14/16] Document supported smooth image-rendering keywords in SVG design Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/canvas-net-svg/svg-codec.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/design/canvas-net-svg/svg-codec.md b/docs/design/canvas-net-svg/svg-codec.md index 2149bf468..4b1f4fd6a 100644 --- a/docs/design/canvas-net-svg/svg-codec.md +++ b/docs/design/canvas-net-svg/svg-codec.md @@ -166,8 +166,9 @@ nested SVG document, whether base64-encoded or not) - tolerantly rendered as not same recursive-parsing-complexity reasoning that already excludes `feImage`'s own referenced-element case; auto-sizing from the decoded raster's own intrinsic dimensions when `width`/`height` are absent (both default to `0`, rendering nothing, rather than inferring a size -from the decoded content); and `image-rendering` values other than the automatic, `pixelated`, -`crisp-edges` and `optimizeSpeed` keywords. +from the decoded content); and `image-rendering` values other than the recognized keywords +(`auto`, `optimizeQuality`, `smooth` and `high-quality` select smooth sampling; `pixelated`, +`crisp-edges` and `optimizeSpeed` select nearest-neighbor sampling), which are ignored. A percentage value on a shape/text geometry attribute (`x`, `y`, `width`, `height`, `rx`, `ry`, `cx`, `cy`, `r`, `x1`/`y1`/`x2`/`y2`, `font-size`, `stroke-width`, `stroke-dasharray`, From 39dbd50ba2665db9b63aefb91078f36c5d9ea93f Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 17:35:10 -0400 Subject: [PATCH 15/16] List PPTX crop tests in requirement trace and verification Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/reqstream/canvas-net-pptx/pptx-document.yaml | 2 ++ docs/verification/canvas-net-pptx/pptx-document.md | 8 +++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/reqstream/canvas-net-pptx/pptx-document.yaml b/docs/reqstream/canvas-net-pptx/pptx-document.yaml index 775e937eb..55d7c2c08 100644 --- a/docs/reqstream/canvas-net-pptx/pptx-document.yaml +++ b/docs/reqstream/canvas-net-pptx/pptx-document.yaml @@ -2247,3 +2247,5 @@ sections: - PaintPicture_EnlargedCrop_DoesNotBleedPixelsOutsideCrop - PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop - PaintPicture_FractionalCrop_PartiallyCoveredBorderPixelContributes + - PaintPicture_FractionalCropOnIntegerBoundary_NoContaminationFromExcludedColumn + - PaintPicture_WithNegativeSrcRectEdges_ReplicatesEdgePixelsIntoOverhang diff --git a/docs/verification/canvas-net-pptx/pptx-document.md b/docs/verification/canvas-net-pptx/pptx-document.md index adf76778a..ef05a266f 100644 --- a/docs/verification/canvas-net-pptx/pptx-document.md +++ b/docs/verification/canvas-net-pptx/pptx-document.md @@ -1051,7 +1051,13 @@ carrying the `"pptx-image-format"` feature token, and proves null argument valid #### CanvasNetPptx-PptxDocument-PictureSmoothResample: Pictures Are Resampled Smoothly **Tests**: `PaintPicture_EnlargedPicture_IsSmooth`, `PaintPicture_EnlargedCrop_DoesNotBleedPixelsOutsideCrop`, -`PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop`, `PaintPicture_FractionalCrop_PartiallyCoveredBorderPixelContributes` +`PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop`, `PaintPicture_FractionalCrop_PartiallyCoveredBorderPixelContributes`, +`PaintPicture_FractionalCropOnIntegerBoundary_NoContaminationFromExcludedColumn`, +`PaintPicture_WithNegativeSrcRectEdges_ReplicatesEdgePixelsIntoOverhang` + +A 45-pixel-wide picture with a 40 percent right or left crop (exactly 18 pixels) excludes the neighboring +column entirely, so the output stays pure blue. A crop with negative edges on all four sides replicates the +edge pixels into the overhang strips with no transparent band. A 2x1 black/white picture painted at 40x4 contains many distinct gray levels instead of two hard blocks. An 8x8 picture with two bright-red left columns and six blue columns, cropped with `srcRect` left = 25 percent From deb731e8eeb80ac3528f33a44a313857644b33d0 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Sun, 11 Oct 2026 17:53:29 -0400 Subject: [PATCH 16/16] Fix PPTX fractional-crop footprint clipping and resampler skew tolerance axes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/canvas-net/canvas/surface.md | 2 +- .../canvas-net-pptx/pptx-document.yaml | 1 + docs/reqstream/canvas-net/canvas/surface.yaml | 2 ++ .../canvas-net-pptx/pptx-document.md | 1 + .../verification/canvas-net/canvas/surface.md | 4 +++- .../PptxDocument.Images.cs | 12 ++++++++-- .../Canvas/SurfaceResampler.Engine.cs | 5 ++-- .../PptxImagesTests.cs | 21 ++++++++++++++++ .../Canvas/SurfaceResamplerTests.cs | 24 +++++++++++++++++++ 9 files changed, 66 insertions(+), 6 deletions(-) diff --git a/docs/design/canvas-net/canvas/surface.md b/docs/design/canvas-net/canvas/surface.md index f37967ce4..a44cfa329 100644 --- a/docs/design/canvas-net/canvas/surface.md +++ b/docs/design/canvas-net/canvas/surface.md @@ -518,7 +518,7 @@ output never depends on a buffer's previous contents. an axis-aligned image placement (the window is clipped to the visible area) so the renderer can composite it 1:1; it returns `false` for rotation, skew or non-finite/degenerate matrices (a rotation/skew component is tolerated only while it moves no pixel by more than 0.01 device pixel, -i.e. `|M12|*height` and `|M21|*width` are each at most 0.01), and `true` +i.e. `|M12|*width` and `|M21|*height` are each at most 0.01), and `true` with no window when nothing is visible. Rotated or skewed placements use `Prefilter` (area-reduce by an integer factor) plus `SampleBilinear` (inverse mapped, premultiplied, edge-clamped); `SampleBilinearReduced` maps original-pixel positions onto the reduced surface through the actual block diff --git a/docs/reqstream/canvas-net-pptx/pptx-document.yaml b/docs/reqstream/canvas-net-pptx/pptx-document.yaml index 55d7c2c08..ecf93b0d4 100644 --- a/docs/reqstream/canvas-net-pptx/pptx-document.yaml +++ b/docs/reqstream/canvas-net-pptx/pptx-document.yaml @@ -2247,5 +2247,6 @@ sections: - PaintPicture_EnlargedCrop_DoesNotBleedPixelsOutsideCrop - PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop - PaintPicture_FractionalCrop_PartiallyCoveredBorderPixelContributes + - PaintPicture_FractionalCropAtOffset_PaintsOnlyInsideFootprint - PaintPicture_FractionalCropOnIntegerBoundary_NoContaminationFromExcludedColumn - PaintPicture_WithNegativeSrcRectEdges_ReplicatesEdgePixelsIntoOverhang diff --git a/docs/reqstream/canvas-net/canvas/surface.yaml b/docs/reqstream/canvas-net/canvas/surface.yaml index f5fccd9d0..402e75b9a 100644 --- a/docs/reqstream/canvas-net/canvas/surface.yaml +++ b/docs/reqstream/canvas-net/canvas/surface.yaml @@ -536,6 +536,8 @@ sections: single high-quality resample followed by a 1:1 composite. tests: - TryResampleToDevice_RotatedMatrix_ReturnsFalse + - TryResampleToDevice_WideImageSmallM12_DeclinedOnlyWhenDriftMatters + - TryResampleToDevice_TallImageSmallM21_DeclinedOnlyWhenDriftMatters - TryResampleToDevice_AxisAligned_ReturnsWindowAtOrigin - TryResampleToDevice_OffScreen_ReturnsTrueWithNullWindow - BoxReduce_MatchesAreaResize diff --git a/docs/verification/canvas-net-pptx/pptx-document.md b/docs/verification/canvas-net-pptx/pptx-document.md index ef05a266f..304c83848 100644 --- a/docs/verification/canvas-net-pptx/pptx-document.md +++ b/docs/verification/canvas-net-pptx/pptx-document.md @@ -1053,6 +1053,7 @@ carrying the `"pptx-image-format"` feature token, and proves null argument valid **Tests**: `PaintPicture_EnlargedPicture_IsSmooth`, `PaintPicture_EnlargedCrop_DoesNotBleedPixelsOutsideCrop`, `PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop`, `PaintPicture_FractionalCrop_PartiallyCoveredBorderPixelContributes`, `PaintPicture_FractionalCropOnIntegerBoundary_NoContaminationFromExcludedColumn`, +`PaintPicture_FractionalCropAtOffset_PaintsOnlyInsideFootprint`, `PaintPicture_WithNegativeSrcRectEdges_ReplicatesEdgePixelsIntoOverhang` A 45-pixel-wide picture with a 40 percent right or left crop (exactly 18 pixels) excludes the neighboring diff --git a/docs/verification/canvas-net/canvas/surface.md b/docs/verification/canvas-net/canvas/surface.md index 4102235c3..b48e8d7b8 100644 --- a/docs/verification/canvas-net/canvas/surface.md +++ b/docs/verification/canvas-net/canvas/surface.md @@ -498,7 +498,9 @@ A zero or oversized box dimension reports `maxWidth` or `maxHeight`. ##### CanvasNet-Canvas-Surface-DeviceResample: Device Window Resampling -**Tests**: `TryResampleToDevice_RotatedMatrix_ReturnsFalse`, `TryResampleToDevice_AxisAligned_ReturnsWindowAtOrigin`, +**Tests**: `TryResampleToDevice_RotatedMatrix_ReturnsFalse`, +`TryResampleToDevice_WideImageSmallM12_DeclinedOnlyWhenDriftMatters`, +`TryResampleToDevice_TallImageSmallM21_DeclinedOnlyWhenDriftMatters`, `TryResampleToDevice_AxisAligned_ReturnsWindowAtOrigin`, `TryResampleToDevice_OffScreen_ReturnsTrueWithNullWindow`, `BoxReduce_MatchesAreaResize`, `BoxReduce_NonDivisibleSize_AveragesOnlyCoveredPixelsInPartialBlock`, `BoxReduce_NonDivisibleSizeWithAlpha_PartialBlockUsesCoveredPixelsOnly` diff --git a/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs b/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs index b8345c78c..403d771cb 100644 --- a/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs +++ b/src/DemaConsulting.CanvasNet.Pptx/PptxDocument.Images.cs @@ -757,7 +757,7 @@ static double Snap(double v) { if (window is not null) { - CompositeWindow(surface, window, originX, originY, clipMask); + CompositeWindow(surface, window, originX, originY, clipMask, surfaceToUnit); } } @@ -808,8 +808,10 @@ static double Snap(double v) /// /// Composites a device-aligned resampled picture window onto /// one pixel at a time (Porter-Duff "over"), scaling alpha by the optional clip mask. + /// Pixels whose centers fall outside the picture's unit-square footprint (the window may + /// include whole border source pixels beyond a fractional crop) are skipped. /// - private static void CompositeWindow(Surface surface, Surface window, int originX, int originY, Surface? clipMask) + private static void CompositeWindow(Surface surface, Surface window, int originX, int originY, Surface? clipMask, Matrix3x2 surfaceToUnit) { for (var y = 0; y < window.Height; y++) { @@ -817,6 +819,12 @@ private static void CompositeWindow(Surface surface, Surface window, int originX { var dx = originX + x; var dy = originY + y; + var unitPoint = Vector2.Transform(new Vector2(dx + 0.5f, dy + 0.5f), surfaceToUnit); + if (unitPoint.X < 0 || unitPoint.X >= 1 || unitPoint.Y < 0 || unitPoint.Y >= 1) + { + continue; + } + var maskAlpha = clipMask is null ? (byte)255 : clipMask[dx, dy].A; if (maskAlpha == 0) { diff --git a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs index 03f44cfe5..ae4ad80ad 100644 --- a/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs +++ b/src/DemaConsulting.CanvasNet/Canvas/SurfaceResampler.Engine.cs @@ -544,8 +544,9 @@ internal static bool TryResampleToDevice( return false; } - // Rotation/skew is tolerated only while it moves no pixel by more than a hundredth of a device pixel - if (Math.Abs(m12) * source.Height > 0.01 || Math.Abs(m21) * source.Width > 0.01) + // Rotation/skew is tolerated only while it moves no pixel by more than a hundredth of a device pixel. + // Row-vector convention: device y gets M12 * (source x) and device x gets M21 * (source y). + if (Math.Abs(m12) * source.Width > 0.01 || Math.Abs(m21) * source.Height > 0.01) { return false; } diff --git a/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs b/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs index a4c4b2561..e5e8b8e12 100644 --- a/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs +++ b/test/DemaConsulting.CanvasNet.Pptx.Tests/PptxImagesTests.cs @@ -282,6 +282,27 @@ public void PaintPicture_FractionalCrop_PartiallyCoveredBorderPixelContributes() Assert.Equal(255, surface[39, 2].R); } + /// Proves a fractional crop's extra border source pixels (kept for filter taps) never paint outside the picture's own footprint. + [Fact] + public void PaintPicture_FractionalCropAtOffset_PaintsOnlyInsideFootprint() + { + using var image = new Surface(4, 4); + image.Clear(new Rgba32(255, 0, 0, 255)); + using var surface = new Surface(60, 20); + var srcRect = new PptxSrcRect(Left: 0.125f, Top: 0.125f, Right: 0.125f, Bottom: 0.125f); + + PptxDocument.PaintPicture(surface, image, srcRect, Matrix3x2.CreateTranslation(10f, 5f), widthEmu: 40f, heightEmu: 8f); + + for (var y = 0; y < 20; y++) + { + for (var x = 0; x < 60; x++) + { + var inside = x is >= 10 and < 50 && y is >= 5 and < 13; + Assert.Equal(inside, surface[x, y].A != 0); + } + } + } + /// Proves the crop also does not bleed for a rotated picture (inverse-mapped bilinear path). [Fact] public void PaintPicture_RotatedCrop_DoesNotBleedPixelsOutsideCrop() diff --git a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs index 2ef288aaf..11f71303e 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Canvas/SurfaceResamplerTests.cs @@ -285,6 +285,30 @@ public void TryResampleToDevice_RotatedMatrix_ReturnsFalse() Assert.Null(window); } + /// A wide image whose M12 shifts its far edge a full device pixel vertically is declined; negligible drift is accepted. + [Fact] + public void TryResampleToDevice_WideImageSmallM12_DeclinedOnlyWhenDriftMatters() + { + using var source = new Surface(1000, 1); + Assert.False(SurfaceResampler.TryResampleToDevice(source, new Matrix3x2(1f, 0.001f, 0f, 1f, 0f, 0f), 2000, 20, ResamplingMode.Auto, out var window, out _, out _)); + Assert.Null(window); + + Assert.True(SurfaceResampler.TryResampleToDevice(source, new Matrix3x2(1f, 0.000001f, 0f, 1f, 0f, 0f), 2000, 20, ResamplingMode.Auto, out var okWindow, out _, out _)); + okWindow?.Dispose(); + } + + /// A tall image whose M21 shifts its far edge a full device pixel horizontally is declined; negligible drift is accepted. + [Fact] + public void TryResampleToDevice_TallImageSmallM21_DeclinedOnlyWhenDriftMatters() + { + using var source = new Surface(1, 1000); + Assert.False(SurfaceResampler.TryResampleToDevice(source, new Matrix3x2(1f, 0f, 0.001f, 1f, 0f, 0f), 20, 2000, ResamplingMode.Auto, out var window, out _, out _)); + Assert.Null(window); + + Assert.True(SurfaceResampler.TryResampleToDevice(source, new Matrix3x2(1f, 0f, 0.000001f, 1f, 0f, 0f), 20, 2000, ResamplingMode.Auto, out var okWindow, out _, out _)); + okWindow?.Dispose(); + } + /// An axis-aligned enlargement yields a window covering exactly the image rectangle. [Fact] public void TryResampleToDevice_AxisAligned_ReturnsWindowAtOrigin()