From ca775028d1791ae2afe5385f84f36cea77a09411 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 28 Sep 2026 20:18:11 -0400 Subject: [PATCH 01/10] Split SVG codec into DemaConsulting.CanvasNet.Svg package Extracts the SVG rasterization codec into its own NuGet package and software system (CanvasNetSvg), separate from the core CanvasNet package/system, per software-items.md. Moves source, tests, and fixtures into new src/DemaConsulting.CanvasNet.Svg and test/DemaConsulting.CanvasNet.Svg.Tests projects, renames the SVG codec namespace to DemaConsulting.CanvasNet.Svg, and promotes SVG's requirements/design/verification/SysML2 model to top-level canvas-net-svg artifacts parallel to canvas-net. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/build.yaml | 2 + .reviewmark.yaml | 109 +- CanvasNet.slnx | 2 + README.md | 16 +- docs/design/canvas-net-svg.md | 189 +++ .../codecs => canvas-net-svg}/svg-codec.md | 219 +-- docs/design/canvas-net/codecs.md | 66 +- docs/design/introduction.md | 51 +- docs/reqstream/canvas-net-svg.yaml | 480 ++++++ docs/reqstream/canvas-net-svg/svg-codec.yaml | 1457 +++++++++++++++++ docs/reqstream/canvas-net.yaml | 417 +---- docs/reqstream/canvas-net/codecs.yaml | 471 +----- .../canvas-net/codecs/svg-codec.yaml | 1455 ---------------- docs/sysml2/model/canvas-net-svg.sysml | 18 + .../model/canvas-net-svg/svg-codec.sysml | 11 + docs/sysml2/model/canvas-net.sysml | 1 + docs/sysml2/model/canvas-net/codecs.sysml | 3 +- .../model/canvas-net/codecs/svg-codec.sysml | 11 - docs/sysml2/views/design-views.sysml | 4 + docs/user_guide/introduction.md | 5 + docs/verification/canvas-net-svg.md | 62 + .../codecs => canvas-net-svg}/svg-codec.md | 178 +- docs/verification/canvas-net/codecs.md | 22 +- requirements.yaml | 3 +- .../DemaConsulting.CanvasNet.Svg.csproj | 82 + .../NamespaceDoc.cs | 22 + .../SvgCodec.Attributes.cs | 2 +- .../SvgCodec.ClippingAndMasking.cs | 2 +- .../SvgCodec.Core.cs | 2 +- .../SvgCodec.Css.Cascade.cs | 2 +- .../SvgCodec.Css.Parser.cs | 2 +- .../SvgCodec.Css.Selectors.cs | 2 +- .../SvgCodec.Elements.cs | 2 +- .../SvgCodec.Filters.Blend.cs | 2 +- .../SvgCodec.Filters.ColorMatrix.cs | 2 +- .../SvgCodec.Filters.ComponentTransfer.cs | 2 +- .../SvgCodec.Filters.Convolution.cs | 2 +- .../SvgCodec.Filters.DisplacementMap.cs | 2 +- .../SvgCodec.Filters.DropShadow.cs | 2 +- .../SvgCodec.Filters.FeImage.cs | 2 +- .../SvgCodec.Filters.Lighting.cs | 2 +- .../SvgCodec.Filters.Morphology.cs | 2 +- .../SvgCodec.Filters.Tile.cs | 2 +- .../SvgCodec.Filters.Turbulence.cs | 2 +- .../SvgCodec.Filters.cs | 2 +- .../SvgCodec.Gradients.cs | 2 +- .../SvgCodec.Image.cs | 3 +- .../SvgCodec.Markers.cs | 2 +- .../SvgCodec.Paint.cs | 2 +- .../SvgCodec.Parsing.cs | 2 +- .../SvgCodec.PathData.cs | 2 +- .../SvgCodec.PathRender.cs | 2 +- .../SvgCodec.Patterns.cs | 2 +- .../SvgCodec.PreserveAspectRatio.cs | 2 +- .../SvgCodec.Shapes.cs | 2 +- .../SvgCodec.Text.cs | 2 +- .../SvgCodec.cs | 3 +- .../SvgFontFace.cs | 3 +- .../SvgFontStyle.cs | 2 +- .../Codecs/NamespaceDoc.cs | 22 +- .../DemaConsulting.CanvasNet.csproj | 1 + .../DemaConsulting.CanvasNet.Svg.Tests.csproj | 105 ++ .../SvgCodecTests.cs | 11 +- .../SvgFixtureTests.cs | 3 +- .../SvgFixtures/InkscapeFilters.svg | 0 .../SvgFixtures/README.md | 0 .../SvgFixtures/SvgGradient.svg | 0 .../SvgFixtures/WikimediaCommons.LICENSE | 0 .../SvgFixtures/arrow-markers.svg | 0 .../SvgFixtures/css-styling.svg | 0 .../SvgFixtures/gradient.svg | 0 .../SvgFixtures/groups-and-transforms.svg | 0 .../SvgFixtures/label-halo.svg | 0 .../SvgFixtures/shapes.svg | 0 .../SvgFixtures/text.svg | 0 .../SvgFixtures/tolerant-unsupported.svg | 0 .../SvgFixtures/use-reference.svg | 0 .../SvgSystemIntegrationTests.cs | 56 + .../CanvasNetTests.cs | 46 - .../DemaConsulting.CanvasNet.Tests.csproj | 7 - 80 files changed, 2937 insertions(+), 2739 deletions(-) create mode 100644 docs/design/canvas-net-svg.md rename docs/design/{canvas-net/codecs => canvas-net-svg}/svg-codec.md (94%) create mode 100644 docs/reqstream/canvas-net-svg.yaml create mode 100644 docs/reqstream/canvas-net-svg/svg-codec.yaml delete mode 100644 docs/reqstream/canvas-net/codecs/svg-codec.yaml create mode 100644 docs/sysml2/model/canvas-net-svg.sysml create mode 100644 docs/sysml2/model/canvas-net-svg/svg-codec.sysml delete mode 100644 docs/sysml2/model/canvas-net/codecs/svg-codec.sysml create mode 100644 docs/verification/canvas-net-svg.md rename docs/verification/{canvas-net/codecs => canvas-net-svg}/svg-codec.md (94%) create mode 100644 src/DemaConsulting.CanvasNet.Svg/DemaConsulting.CanvasNet.Svg.csproj create mode 100644 src/DemaConsulting.CanvasNet.Svg/NamespaceDoc.cs rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Attributes.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.ClippingAndMasking.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Core.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Css.Cascade.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Css.Parser.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Css.Selectors.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Elements.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Filters.Blend.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Filters.ColorMatrix.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Filters.ComponentTransfer.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Filters.Convolution.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Filters.DisplacementMap.cs (98%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Filters.DropShadow.cs (97%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Filters.FeImage.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Filters.Lighting.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Filters.Morphology.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Filters.Tile.cs (97%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Filters.Turbulence.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Filters.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Gradients.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Image.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Markers.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Paint.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Parsing.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.PathData.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.PathRender.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Patterns.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.PreserveAspectRatio.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Shapes.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgCodec.Text.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs => DemaConsulting.CanvasNet.Svg}/SvgCodec.cs (99%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgFontFace.cs (96%) rename src/{DemaConsulting.CanvasNet/Codecs/Svg => DemaConsulting.CanvasNet.Svg}/SvgFontStyle.cs (97%) create mode 100644 test/DemaConsulting.CanvasNet.Svg.Tests/DemaConsulting.CanvasNet.Svg.Tests.csproj rename test/{DemaConsulting.CanvasNet.Tests/Codecs => DemaConsulting.CanvasNet.Svg.Tests}/SvgCodecTests.cs (99%) rename test/{DemaConsulting.CanvasNet.Tests/Codecs => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtureTests.cs (99%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/InkscapeFilters.svg (100%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/README.md (100%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/SvgGradient.svg (100%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/WikimediaCommons.LICENSE (100%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/arrow-markers.svg (100%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/css-styling.svg (100%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/gradient.svg (100%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/groups-and-transforms.svg (100%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/label-halo.svg (100%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/shapes.svg (100%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/text.svg (100%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/tolerant-unsupported.svg (100%) rename test/{DemaConsulting.CanvasNet.Tests => DemaConsulting.CanvasNet.Svg.Tests}/SvgFixtures/use-reference.svg (100%) create mode 100644 test/DemaConsulting.CanvasNet.Svg.Tests/SvgSystemIntegrationTests.cs diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index a87105fec..5d71e2069 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -227,6 +227,8 @@ jobs: path: | src/DemaConsulting.CanvasNet/bin/Release/*.nupkg src/DemaConsulting.CanvasNet/bin/Release/*.snupkg + src/DemaConsulting.CanvasNet.Svg/bin/Release/*.nupkg + src/DemaConsulting.CanvasNet.Svg/bin/Release/*.snupkg # Runs CodeQL security and quality analysis, gathering results to include # in the code quality report. diff --git a/.reviewmark.yaml b/.reviewmark.yaml index 6d415eb33..84f5f56ea 100644 --- a/.reviewmark.yaml +++ b/.reviewmark.yaml @@ -99,7 +99,7 @@ reviews: - "docs/reqstream/canvas-net.yaml" paths: - "requirements.yaml" # root requirements file - - "docs/reqstream/**/*.yaml" # all requirements files + - "docs/reqstream/canvas-net/**/*.yaml" # all requirements files # CanvasNet-Canvas Review (one per subsystem) - id: CanvasNet-Canvas @@ -252,39 +252,6 @@ reviews: - "test/DemaConsulting.CanvasNet.Tests/Codecs/GifCodecTests.cs" # unit tests - "test/DemaConsulting.CanvasNet.Tests/Codecs/GifFixtureTests.cs" # fixture conformance tests - # CanvasNet-Codecs-SvgCodec Review (one per unit) - - id: CanvasNet-Codecs-SvgCodec - title: Review that CanvasNet Codecs SvgCodec Implementation is Correct - context: - - "docs/design/canvas-net.md" - - "docs/reqstream/canvas-net.yaml" - - "docs/design/canvas-net/codecs.md" - - "docs/reqstream/canvas-net/codecs.yaml" - paths: - - "docs/reqstream/canvas-net/codecs/svg-codec.yaml" # unit requirements - - "docs/design/canvas-net/codecs/svg-codec.md" # unit design - - "docs/verification/canvas-net/codecs/svg-codec.md" # unit verification - - "docs/sysml2/model/canvas-net/codecs/svg-codec.sysml" # unit SysML2 model - - "src/DemaConsulting.CanvasNet/Codecs/SvgCodec.cs" # unit source (public API entry point) - - "src/DemaConsulting.CanvasNet/Codecs/Svg/**/*.cs" # unit source (partial-class implementation files) - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.ColorMatrix.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.ComponentTransfer.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.Morphology.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.Convolution.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.DisplacementMap.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.Tile.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.DropShadow.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.FeImage.cs" # phase 5 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.Lighting.cs" # phase 6 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.Turbulence.cs" # phase 6 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Css.Parser.cs" # phase 7 CSS styling partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Css.Selectors.cs" # phase 7 CSS styling partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Css.Cascade.cs" # phase 7 CSS styling partial - - "src/DemaConsulting.CanvasNet/Codecs/Svg/SvgCodec.Filters.Blend.cs" # phase 8 filter partial - - "src/DemaConsulting.CanvasNet/Codecs/NamespaceDoc.cs" # Codecs namespace documentation - - "test/DemaConsulting.CanvasNet.Tests/Codecs/SvgCodecTests.cs" # unit tests - - "test/DemaConsulting.CanvasNet.Tests/Codecs/SvgFixtureTests.cs" # fixture conformance tests - # CanvasNet-Geometry Review (one per subsystem) - id: CanvasNet-Geometry title: Review that CanvasNet Geometry Subsystem Implementation is Correct @@ -568,6 +535,80 @@ reviews: - "src/DemaConsulting.CanvasNet/Rendering/Shapes.cs" # unit source - "test/DemaConsulting.CanvasNet.Tests/Rendering/ShapesTests.cs" # unit tests + # CanvasNetSvg-Architecture Review (one per system) + - id: CanvasNetSvg-Architecture + title: Review that CanvasNetSvg Architecture Satisfies Requirements + context: + - "README.md" + - "docs/user_guide/**/*.md" + paths: + - "docs/reqstream/canvas-net-svg.yaml" # system requirements + - "docs/design/introduction.md" # design introduction + - "docs/design/canvas-net-svg.md" # system design + - "docs/verification/introduction.md" # verification introduction + - "docs/verification/canvas-net-svg.md" # system verification + - "test/DemaConsulting.CanvasNet.Svg.Tests/SvgSystemIntegrationTests.cs" # integration tests + + # CanvasNetSvg-Design Review (one per system) + - id: CanvasNetSvg-Design + title: Review that CanvasNetSvg Design is Consistent and Complete + context: + - "docs/reqstream/canvas-net-svg.yaml" + paths: + - "docs/design/introduction.md" # design introduction + - "docs/design/canvas-net-svg.md" # system design + - "docs/design/canvas-net-svg/**/*.md" # all system design documents + + # CanvasNetSvg-Verification Review (one per system) + - id: CanvasNetSvg-Verification + title: Review that CanvasNetSvg Verification is Consistent and Complete + context: + - "docs/reqstream/canvas-net-svg.yaml" + paths: + - "docs/verification/introduction.md" # verification introduction + - "docs/verification/canvas-net-svg.md" # system verification + - "docs/verification/canvas-net-svg/**/*.md" # all verification documents + + # CanvasNetSvg-AllRequirements Review (one per system) + - id: CanvasNetSvg-AllRequirements + title: Review that All CanvasNetSvg Requirements are Complete + context: + - "docs/design/canvas-net-svg.md" + - "docs/reqstream/canvas-net-svg.yaml" + paths: + - "docs/reqstream/canvas-net-svg/**/*.yaml" # all requirements files + + # CanvasNetSvg-SvgCodec Review (one per direct unit) + - id: CanvasNetSvg-SvgCodec + title: Review that CanvasNetSvg SvgCodec Implementation is Correct + context: + - "docs/design/canvas-net-svg.md" + - "docs/reqstream/canvas-net-svg.yaml" + paths: + - "docs/reqstream/canvas-net-svg/svg-codec.yaml" # unit requirements + - "docs/design/canvas-net-svg/svg-codec.md" # unit design + - "docs/verification/canvas-net-svg/svg-codec.md" # unit verification + - "docs/sysml2/model/canvas-net-svg/svg-codec.sysml" # unit SysML2 model + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.cs" # unit source (public API entry point) + - "src/DemaConsulting.CanvasNet.Svg/*.cs" # unit source (partial-class implementation files) + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.ColorMatrix.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.ComponentTransfer.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Morphology.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Convolution.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.DisplacementMap.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Tile.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.DropShadow.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.FeImage.cs" # phase 5 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Lighting.cs" # phase 6 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Filters.Turbulence.cs" # phase 6 filter partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Css.Parser.cs" # phase 7 CSS styling partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Css.Selectors.cs" # phase 7 CSS styling partial + - "src/DemaConsulting.CanvasNet.Svg/SvgCodec.Css.Cascade.cs" # phase 7 CSS styling partial + - "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/SvgFixtureTests.cs" # fixture conformance tests + # OTS-BuildMark Review (one per OTS item) - id: OTS-BuildMark title: Review that BuildMark Provides Required Functionality diff --git a/CanvasNet.slnx b/CanvasNet.slnx index 194e23d3a..166d1c794 100644 --- a/CanvasNet.slnx +++ b/CanvasNet.slnx @@ -1,8 +1,10 @@ + + diff --git a/README.md b/README.md index e39b8345b..cc23a8aa4 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,8 @@ image operations using `Span`, and supports independent-copy cropping for loa - πŸ—œοΈ **JPEG Codec** - Load baseline/progressive; save baseline JPEG - 🎞️ **GIF Codec** - Decode-only load of first GIF frame; `GetInfo` reports the true frame count - πŸ“ **SVG Codec** - Rasterize a common SVG subset, including markers/filters/clip-paths/masks and - weight/style-aware font matching, to a surface + weight/style-aware font matching, to a surface (ships as the separate + `DemaConsulting.CanvasNet.Svg` package) - πŸ” **Header-Only Probing** - `GetInfo` reads headers without decoding pixels (GIF excepted) - πŸ–ŒοΈ **Path Filling** - Antialiased nonzero/even-odd fill of vector paths - πŸ–ŠοΈ **Stroke-to-Fill** - Convert stroked paths into fillable outlines @@ -55,11 +56,24 @@ Or via Package Manager Console: Install-Package DemaConsulting.CanvasNet ``` +SVG rasterization requires the separate `DemaConsulting.CanvasNet.Svg` package: + +```bash +dotnet add package DemaConsulting.CanvasNet.Svg +``` + +Or via Package Manager Console: + +```powershell +Install-Package DemaConsulting.CanvasNet.Svg +``` + ## Usage ```csharp using DemaConsulting.CanvasNet.Canvas; using DemaConsulting.CanvasNet.Codecs; +using DemaConsulting.CanvasNet.Svg; using System.IO; // Create a surface, set a pixel, and crop an independent copy diff --git a/docs/design/canvas-net-svg.md b/docs/design/canvas-net-svg.md new file mode 100644 index 000000000..80e800f47 --- /dev/null +++ b/docs/design/canvas-net-svg.md @@ -0,0 +1,189 @@ +# System Design + + + +This document provides the system-level design for CanvasNetSvg. + +![CanvasNetSvg Structure](CanvasNetSvgView.svg) + + + +## Architecture + +CanvasNetSvg is a .NET library providing SVG (Scalable Vector Graphics) rasterization, +distributed as its own NuGet package (`DemaConsulting.CanvasNet.Svg`, namespace +`DemaConsulting.CanvasNet.Svg`), independent of, but depending on, the core `CanvasNet` system +(its own separate package, `DemaConsulting.CanvasNet`) β€” see the Dependencies section below. The +system consists of a single implemented unit: + +- **SvgCodec** (namespace `DemaConsulting.CanvasNet.Svg`, folder + `src/DemaConsulting.CanvasNet.Svg/`, flat β€” no further nesting): a hand-rolled, + decode/rasterize-only codec for a common real-world subset of SVG documents, rasterizing them + directly into a `DemaConsulting.CanvasNet.Canvas.Surface` pixel buffer. Unlike the `CanvasNet` + system's own raster codecs (`BmpCodec`, `PngCodec`, `TiffCodec`, `JpegCodec`), `SvgCodec` has no + `Save` method: an SVG document is XML markup, not pixel data, so there is no meaningful inverse + operation that would turn an arbitrary `Surface` back into equivalent vector markup. See + _SvgCodec Unit Design_ (`canvas-net-svg/svg-codec.md`). + +`CanvasNetSvg` is modeled as its own top-level software system (rather than as a further unit of +the `CanvasNet` system's `Codecs` subsystem, as it was in an earlier revision of this design) +because it is distributed as its own independently-versioned NuGet package β€” per +`software-items.md`'s rule that a software package contains exactly one software system, a system +whose entire content ships in a distinct package must itself be modeled as a distinct system, not +folded into the package it depends on. `CanvasNetSvg` contains exactly one unit, so no Subsystem +tier is interposed between the system and `SvgCodec`: inserting one here would not separate +anything (there is nothing else in the system to separate it from), unlike `CanvasNet`'s own +`Fonts` subsystem, whose single-unit shape exists to keep a consistent finer-grained +decomposition within a System that already contains several other subsystems. + +## External Interfaces + +The system exposes the following public API to external consumers, all on the static `SvgCodec` +class: + +- **SvgCodec.Load(Stream stream, int width, int height, fonts)** / + **SvgCodec.Load(string path, int width, int height, fonts)**: Loads a `Surface` by rasterizing + a supported SVG document from a stream or file path into a caller-requested `width`x`height` + raster, with an optional single-font-per-family `fonts` dictionary. Throws + `ArgumentNullException` for a null `stream`/`path`, `ArgumentException` for an empty/whitespace + `path`, `InvalidDataException` for malformed or unsupported SVG data, and + `ArgumentOutOfRangeException` (propagated, unwrapped, from `Surface`'s own constructor) for a + non-positive `width`/`height`. +- **SvgCodec.LoadWithFontFaces(Stream stream, int width, int height, fontFaces)** / + **SvgCodec.LoadWithFontFaces(string path, int width, int height, fontFaces)**: The richer + loading entry point, accepting more than one registered `SvgFontFace` (weight/style variant) + per font-family, matching each text element's own cascaded font-weight/font-style to the + closest registered face. Same exception contract as `Load` above. +- **SvgCodec.GetInfo(Stream stream)** / **SvgCodec.GetInfo(string path)**: Reports an SVG + document's resolved intrinsic width, height, channel count (always 4), and alpha presence + (always true) via the shared `Codecs.ImageInfo` record struct, given a stream or a file path, + without rasterizing the document, falling back from `viewBox` to `width`/`height` to a + 300x150 CSS default. Throws `ArgumentNullException` for a null `stream`/`path`, + `ArgumentException` for an empty/whitespace `path`, and `InvalidDataException` for malformed + SVG data. + + +| Interface | Direction | Format | Constraints | +| -------------------------------------- | ---------------- | ------------------------------ | ------------------------------- | +| `SvgCodec.Load(...)` | Inbound/Outbound | Method call / `Surface` return | Valid SVG stream or path; `width`/`height` > 0 | +| `SvgCodec.LoadWithFontFaces(...)` | Inbound/Outbound | Method call / `Surface` return | Valid SVG stream or path; `width`/`height` > 0 | +| `SvgCodec.GetInfo(...)` | Inbound/Outbound | Method call / `ImageInfo` return | Valid SVG stream or path | + + +See _SvgCodec Unit Design_ (`canvas-net-svg/svg-codec.md`) for the complete in-scope SVG feature +subset (shapes, path data, transforms, gradients, patterns, filters, clip-path/mask, markers, +image, text, and CSS styling) and every method's full parameter and exception detail. + +## Dependencies + +`CanvasNetSvg` depends on the separate `CanvasNet` system (its own package, +`DemaConsulting.CanvasNet`, referenced via a project reference from +`src/DemaConsulting.CanvasNet.Svg/DemaConsulting.CanvasNet.Svg.csproj`), specifically: + +- The `Canvas` subsystem's `Surface` unit β€” constructing the destination raster and compositing + filled/stroked pixels into it +- The `Geometry` subsystem's `Path`/`PathBuilder` (assembling transformed shape/glyph outlines) + and `SvgArcConverter` (converting elliptical arc path commands to Bezier curves) +- The `Drawing` subsystem's `PathFiller`/`PathStroker` (rasterizing the already-transformed, + pixel-space paths `SvgCodec` builds) and `Gradient`/`LinearGradient`/`RadialGradient`/ + `GradientStop`/`GradientSpread` (representing resolved gradient paint) +- The `Fonts` subsystem's `TrueTypeFont` (glyph outline/metrics/kerning lookup for text + rendering) +- The `Codecs` subsystem's shared `ImageInfo` record struct (the return type of `GetInfo`) β€” see + _Codecs Subsystem Design_ (`docs/design/canvas-net/codecs.md`) + +This is an ordinary, same-repository, system-to-system dependency: both `CanvasNet` and +`CanvasNetSvg` are produced by this repository, so it is neither an OTS Software Item (not a +third-party/external-program dependency) nor a Shared Package (that category is scoped to a +package produced by a _different_ repository within the same program). Beyond `CanvasNet`, +`SvgCodec` uses only the .NET base class library's `System.Xml.Linq` (`XDocument`/`XElement`) and +`System.Numerics` (`Matrix3x2`/`Vector2`) namespaces, available on every one of CanvasNetSvg's +target frameworks with no new runtime NuGet dependency. `CanvasNetSvg` introduces no new OTS +Software Item beyond those already used to build and verify the `CanvasNet` system (BuildMark, +FileAssert, Pandoc, ReqStream, ReviewMark, SarifMark, SonarMark, VersionMark, WeasyPrint, xUnit) +β€” see _OTS Integration Design_ (`docs/design/ots.md`). + +## Risk Control Measures + +`SvgCodec`'s `Load`/`LoadWithFontFaces` operations parse externally-supplied, potentially +untrusted SVG documents (XML markup that may embed references, gradients, filters, and +base64-encoded raster images). Risk control for this untrusted-input parsing is segregated +entirely within the single `SvgCodec` unit β€” explicit DTD/external-entity hardening (rejecting +any document containing a DOCTYPE declaration), bounded element-nesting depth, total-element, +geometry-work, and number-list-length budgets, and tolerant-fallback (rather than +whole-document-rejecting) handling of dangling references, reference cycles, and +resource-disproportionate constructs β€” see _SvgCodec Unit Design_ (`canvas-net-svg/svg-codec.md`) +for the complete set of budgets and fallback behaviors. No other segregation is required at the +system level: `CanvasNetSvg` contains exactly one unit, so this risk control is inherently +contained within it (IEC 62304 Β§5.3.3). + +## Data Flow + +**SVG load/rasterize path:** + +1. **Input**: An SVG document (stream or file path), the caller-requested output raster + `width`/`height`, and an optional font dictionary +2. **Validation**: `Load`/`LoadWithFontFaces` reject a null `stream`/`path` with + `ArgumentNullException`, an empty/whitespace `path` with `ArgumentException`, and malformed or + resource-disproportionate SVG data (non-well-formed XML, a DOCTYPE declaration, a malformed + `viewBox`/`transform`/path `d` attribute, or a budget exceeded) with `InvalidDataException`; + a non-positive `width`/`height` propagates, unwrapped, as `Surface`'s own + `ArgumentOutOfRangeException` +3. **Processing**: Parses the document with `System.Xml.Linq`, builds an idβ†’element index, + resolves the root `viewBox`/`width`/`height` into an intrinsic size and computes the + `preserveAspectRatio`-driven fit transform into the requested raster, then recursively walks + the element tree β€” baking every composed transform directly into `Geometry.Path` points, + resolving presentation attributes/CSS cascade, gradients, patterns, clip-path/mask, and + filters, and rasterizing each renderable element via `Drawing.PathFiller`/`Drawing.PathStroker` + onto a new `Canvas.Surface`, with text elements shaped through `Fonts.TrueTypeFont` glyph + outlines +4. **Output**: A new `Canvas.Surface` containing the rasterized pixels + +**SVG GetInfo path:** + +1. **Input**: An SVG document (stream or file path) +2. **Validation**: Rejects a null `stream`/`path` with `ArgumentNullException`, an empty/ + whitespace `path` with `ArgumentException`, and malformed SVG data (up to and including the + root `svg` start-tag) with `InvalidDataException` +3. **Processing**: Reads only the root `svg` start-tag's own attributes via a forward-only, + character-budget-capped `XmlReader`, resolving intrinsic size by falling back from `viewBox` + to `width`/`height` to a 300x150 CSS default +4. **Output**: A `Codecs.ImageInfo` record struct reporting the resolved width, height, + `Channels = 4`, and `HasAlpha = true` + +## Design Constraints + +- **Simplicity**: Minimal functionality kept easy to understand and extend +- **Compliance**: All functionality must be traceable to requirements +- **Quality**: Zero warnings, full test coverage, complete documentation +- **Portability**: Compatible across supported .NET platforms +- **Decode-only**: `SvgCodec` provides no `Save`/encode direction (see Architecture above) + +### Platform Support + +The library targets the following frameworks, identical to the `CanvasNet` system it depends on, +enabling compatibility across modern, currently supported .NET runtimes: + +| Target Framework | Runtime / Environment | +| ---------------- | --------------------- | +| `net8.0` | .NET 8 LTS | +| `net9.0` | .NET 9 | +| `net10.0` | .NET 10 | + +The library is supported on the following operating systems: + +- **Windows** β€” primary developer and CI platform +- **Linux** β€” CI/CD and containerized environments +- **macOS** β€” developer workstations using Apple platforms + +Portability is achieved by restricting the implementation exclusively to Base Class Library (BCL) +APIs and the `CanvasNet` system's own public API, available across all target frameworks. No +platform-specific native interop, OS-specific APIs, or framework-version-specific features are +used. + +### Integration Patterns + +- **NuGet Packaging**: Standard .NET library packaging and distribution, referencing the + `CanvasNet` package as an ordinary NuGet dependency +- **CI/CD Integration**: Automated build, test, and quality validation +- **Requirements Traceability**: All features linked to passing tests diff --git a/docs/design/canvas-net/codecs/svg-codec.md b/docs/design/canvas-net-svg/svg-codec.md similarity index 94% rename from docs/design/canvas-net/codecs/svg-codec.md rename to docs/design/canvas-net-svg/svg-codec.md index afa50aa12..575143d07 100644 --- a/docs/design/canvas-net/codecs/svg-codec.md +++ b/docs/design/canvas-net-svg/svg-codec.md @@ -1,12 +1,18 @@ ## SvgCodec -![Codecs Structure](CodecsView.svg) +![CanvasNetSvg Structure](CanvasNetSvgView.svg) -The `SvgCodec` class is the fifth software unit in the `Codecs` subsystem, and the first codec -unit whose dependencies extend beyond `Canvas.Surface`. It provides hand-rolled, decode/ +`SvgCodec` is distributed as the separate `DemaConsulting.CanvasNet.Svg` NuGet package (namespace +`DemaConsulting.CanvasNet.Svg`), which references the core `DemaConsulting.CanvasNet` package. + +The `SvgCodec` class is the sole software unit of the `CanvasNetSvg` system - unlike the five +units of the `CanvasNet` system's `Codecs` subsystem, whose dependencies are limited to +`Canvas.Surface`, `SvgCodec`'s dependencies extend to `CanvasNet`'s `Geometry`, `Drawing`, and +`Fonts` subsystems as well (see the Dependencies section of _CanvasNetSvg System Design_, +`../canvas-net-svg.md`). It provides hand-rolled, decode/ rasterize-only support for a common real-world subset of SVG (Scalable Vector Graphics) documents, rendering them directly into a `Surface` pixel buffer. Unlike `BmpCodec`, `PngCodec`, `TiffCodec`, and `JpegCodec`, `SvgCodec` has no `Save` method: an SVG document is XML markup, not @@ -27,11 +33,11 @@ same reason as the other codecs: rasterizing an SVG document has no instance sta - Root `svg` sizing: `viewBox`/`width`/`height` resolve the document's intrinsic user-space origin/size, fit into the caller-requested raster via an optional `preserveAspectRatio` (`[defer] []` - all 10 aligns and both `meet`/`slice`; `defer` is parsed -and ignored - it only ever has an observable effect for a browser negotiating a *separately -fetched, cacheable* external image resource's own `preserveAspectRatio` against an embedding +and ignored - it only ever has an observable effect for a browser negotiating a _separately +fetched, cacheable_ external image resource's own `preserveAspectRatio` against an embedding ``/CSS reference, a negotiation this codec has no equivalent for even now that `` is partially supported, since its own supported `data:` URI case is neither separately fetched -nor cacheable) - see *ViewBox Fitting Policy* below +nor cacheable) - see _ViewBox Fitting Policy_ below - Shapes: `rect` (including `rx`/`ry` rounded corners), `circle`, `ellipse`, `line`, `polyline`, `polygon`, and `path` (the full `d` mini-language: `M`/`m`, `L`/`l`, `H`/`h`, `V`/`v`, `C`/`c`, `S`/`s`, `Q`/`q`, `T`/`t`, `A`/`a`, `Z`/`z`, in both absolute and relative forms) @@ -49,15 +55,15 @@ nor cacheable) - see *ViewBox Fitting Policy* below (`pad`/`reflect`/`repeat`), and a bounded, cycle-checked `href`/`xlink:href` template inheritance chain for color stops - `use`, referencing any element by id via `href`/`xlink:href`, with `x`/`y` translation (each - accepting a trailing `%`, resolved against the current viewport - see *Percentage-Based - Geometry Resolution* below), and, when the referenced element is a `symbol` with its own + accepting a trailing `%`, resolved against the current viewport - see _Percentage-Based + Geometry Resolution_ below), and, when the referenced element is a `symbol` with its own `viewBox`, a `preserveAspectRatio`-driven fit of that `viewBox` into the `use`/`symbol` - element's resolved `width`/`height` (see *ViewBox Fitting Policy* below) + element's resolved `width`/`height` (see _ViewBox Fitting Policy_ below) - `marker`, referenced from `line`/`polyline`/`polygon`/`path` via the `marker-start`/ `marker-mid`/`marker-end` presentation attributes (`url(#id)`), with `markerWidth`/ `markerHeight`, `refX`/`refY`, `markerUnits` (`strokeWidth`/`userSpaceOnUse`), `orient` (`auto`/`auto-start-reverse`/a fixed angle in degrees), an optional `viewBox`, and an optional - explicit `preserveAspectRatio` (see *ViewBox Fitting Policy* below) + explicit `preserveAspectRatio` (see _ViewBox Fitting Policy_ below) - `filter`, referenced from any renderable shape or `text` element, or from a `g`/`symbol` reference/`use` element (applied to the whole referenced subtree as a single unit), via the `filter` presentation attribute (`url(#id)`), with `x`/`y`/`width`/`height` filter-region @@ -70,26 +76,26 @@ nor cacheable) - see *ViewBox Fitting Policy* below `clip-path` presentation attribute (`url(#id)`), hard-clipping that element's own content to the union of the `clipPath` element's own direct `rect`/`circle`/`ellipse`/`polyline`/ `polygon`/`path`/`text` children, honoring `clipPathUnits` - (`userSpaceOnUse`/`objectBoundingBox`) and each child's own `clip-rule` - see *Clipping and - Masking* below + (`userSpaceOnUse`/`objectBoundingBox`) and each child's own `clip-rule` - see _Clipping and + Masking_ below - `mask`, referenced from any renderable shape/text/`g`/`symbol`/`use` element via the `mask` presentation attribute (`url(#id)`), attenuating that element's own alpha by the referenced `mask` element's own rendered content, evaluated as a luminance mask (the SVG-specification default), honoring `maskUnits`/`x`/`y`/`width`/`height` (the mask's own region box) and `maskContentUnits` (the mask content's own coordinate system) as independent attributes - see - *Clipping and Masking* below + _Clipping and Masking_ below - `pattern`, referenced from any renderable shape/text element's own `fill`/`stroke` presentation attribute (`url(#id)`) as a tiled paint server, honoring `patternUnits`/ `patternContentUnits` (`objectBoundingBox`/`userSpaceOnUse`, resolved as two independent attributes exactly as `clipPathUnits`/`maskContentUnits` already are), `patternTransform`, an optional `viewBox`/`preserveAspectRatio` pair, and a bounded, cycle-checked `href`/ - `xlink:href` template-inheritance chain for tile content - see *Pattern Paint-Server* below + `xlink:href` template-inheritance chain for tile content - see _Pattern Paint-Server_ below - `image`, whose `href`/`xlink:href` is a base64-encoded `data:` URI with a supported raster MIME type (`image/png`, `image/jpeg`, `image/bmp`, `image/tiff`, or `image/gif`), decoded through that format's own existing codec and drawn into the element's own `x`/`y`/`width`/`height` - placement rect, fitted per an optional `preserveAspectRatio` (see *ViewBox Fitting Policy* + placement rect, fitted per an optional `preserveAspectRatio` (see _ViewBox Fitting Policy_ below) - integrated with the same `clip-path`/`mask`/`filter`/opacity effects pipeline every - other renderable element already uses - see *Image* below + other renderable element already uses - see _Image_ below - `text`, with `x`/`y`, `font-family`, `font-size`, `fill`, `text-anchor` (`start`/`middle`/`end`), and `font-weight`/`font-style`, rendered through a caller-supplied dictionary of per-family `SvgFontFace` lists (or, via the legacy single-font-per-family @@ -103,9 +109,9 @@ constructs this codec does not implement. Encountering one of these does not fai document: `SvgCodec` silently skips just that element (and, for a container element, everything nested inside it) and continues walking the rest of the tree. This is a deliberate, tolerant-parsing policy distinct from the codec's malformed-input rejection policy (see -*Error Handling* below) β€” a document using an out-of-scope construct is not itself invalid SVG, +_Error Handling_ below) β€” a document using an out-of-scope construct is not itself invalid SVG, only partially outside this codec's supported feature set. Within a `style` element's own CSS -engine (see *CSS `" + + ""; + using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(svg)); + + // Act: rasterize the document onto a new Surface through the public API + var surface = SvgCodec.Load(stream, 10, 10); + + // Assert: the system produces the expected integrated rasterized pixel value + Assert.Equal(new Rgba32(11, 22, 33, 255), surface[5, 5]); + } +} diff --git a/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs b/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs index 3a3ef9e84..24f72527c 100644 --- a/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs @@ -372,52 +372,6 @@ public void CanvasNet_SystemIntegration_GifLoad_ReturnsExpectedPixel() Assert.Equal(new Rgba32(11, 22, 33, 255), surface[0, 0]); } - /// - /// Proves that the system can rasterize an SVG document into a Surface through the public - /// API, producing the expected integrated pixel result for a shape filled with a solid - /// color. Unlike the BMP/PNG/TIFF/JPEG system-integration tests above, there is no "Save" - /// half to this round-trip: SvgCodec is decode/rasterize-only (see SvgCodecTests/ - /// SvgFixtureTests for the full unit test coverage). - /// - [Fact] - public void CanvasNet_SystemIntegration_SvgLoad_ReturnsExpectedPixel() - { - // Arrange: a minimal SVG document with a viewBox matching the requested raster exactly, - // containing one rectangle filled with a distinct, fully opaque color - const string svg = ""; - using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(svg)); - - // Act: rasterize the document onto a new Surface through the public API - var surface = SvgCodec.Load(stream, 10, 10); - - // Assert: the system produces the expected integrated rasterized pixel value - Assert.Equal(new Rgba32(11, 22, 33, 255), surface[5, 5]); - } - - /// - /// Proves that the system can rasterize an SVG document whose color comes entirely from a - /// <style> element's CSS class selector - rather than a plain presentation - /// attribute - through the public API, integrating the whole CSS engine (style-element - /// parsing, selector matching, and the cascade chokepoint) with the rest of the rendering - /// pipeline. See SvgCodecTests/SvgFixtureTests for the full unit test - /// coverage of individual selectors/combinators/precedence tiers. - /// - [Fact] - public void CanvasNet_SystemIntegration_SvgLoadWithCssStyleElement_ReturnsExpectedPixel() - { - // Arrange: a minimal SVG document whose only source of color is a stylesheet class rule - - // the rect itself carries no fill attribute at all - const string svg = "" + - ""; - using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(svg)); - - // Act: rasterize the document onto a new Surface through the public API - var surface = SvgCodec.Load(stream, 10, 10); - - // Assert: the system produces the expected integrated rasterized pixel value - Assert.Equal(new Rgba32(11, 22, 33, 255), surface[5, 5]); - } - /// /// Proves that the system can composite a semi-transparent constant color over a Surface /// through the public API, producing the expected Porter-Duff "over" result. diff --git a/test/DemaConsulting.CanvasNet.Tests/DemaConsulting.CanvasNet.Tests.csproj b/test/DemaConsulting.CanvasNet.Tests/DemaConsulting.CanvasNet.Tests.csproj index 2be212ee9..f1dd78df7 100644 --- a/test/DemaConsulting.CanvasNet.Tests/DemaConsulting.CanvasNet.Tests.csproj +++ b/test/DemaConsulting.CanvasNet.Tests/DemaConsulting.CanvasNet.Tests.csproj @@ -93,13 +93,6 @@ - - - - PreserveNewest - - - From ef333b2586ab31b7909166184e267b08567bbeac Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 28 Sep 2026 20:30:32 -0400 Subject: [PATCH 02/10] Remove unsafe git-stash workaround from lint.ps1 dotnet format check Replace the stash-push/format/diff/checkout/stash-pop dance (added in 739b55d7 to work around dotnet/sdk#41422) with a simple non-mutating dry-run check. The stash-based approach snapshots the full worktree but only reverts a pathspec-scoped subset, which corrupts the repo when combined with bulk git-mv renames (as encountered while splitting the SVG codec into its own package). dotnet/sdk#41422 is confirmed still open and macOS-specific; its diagnostic text ("failed to verify formatting") is printed reliably regardless of the exit-code bug, so checking exit code OR that text is a safe fallback that never touches git state. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lint.ps1 | 71 +++++++++++++------------------------------------------- 1 file changed, 16 insertions(+), 55 deletions(-) diff --git a/lint.ps1 b/lint.ps1 index a2bf27039..876b9f871 100644 --- a/lint.ps1 +++ b/lint.ps1 @@ -136,62 +136,23 @@ dotnet restore > $null if ($LASTEXITCODE -ne 0) { $lintError = $true; $skipDotnetFormat = $true } if (-not $skipDotnetFormat) { - # NOTE: `dotnet format --verify-no-changes` has a known cross-platform exit-code - # bug (e.g. dotnet/sdk#41422) where it can report a non-zero exit code even when - # zero files require formatting, inconsistently between operating systems. To get - # a reliable check, format in place and use `git diff` as the source of truth. - # - # A plain `git diff` after formatting would also include any pre-existing - # uncommitted *.cs changes unrelated to formatting (e.g. a developer's - # in-progress edits), causing false failures. Stash those away first so the - # formatter runs against a clean tree and the diff reflects only its own - # changes, then restore the original working tree afterward regardless of - # outcome, leaving no side effects from running this check. - # - # `git status --porcelain` (rather than `git diff`) is used to detect - # pre-existing changes so that untracked *.cs files are also caught and - # stashed - otherwise an untracked file reformatted by `dotnet format` - # would be left modified with no diff ever having been checked against it. - # `--index` on the pop restores the original staged/unstaged split rather - # than flattening everything into the working tree. - $statusBeforeFormat = git status --porcelain -- '*.cs' - $hasPreexistingCsChanges = [bool]$statusBeforeFormat - if ($hasPreexistingCsChanges) { - git stash push --include-untracked --quiet --message "lint.ps1: pre-existing *.cs changes" -- '*.cs' - if ($LASTEXITCODE -ne 0) { - $lintError = $true - $skipDotnetFormat = $true - Write-Host "Failed to stash pre-existing *.cs changes; skipping dotnet format check." - $hasPreexistingCsChanges = $false - } - } -} - -if (-not $skipDotnetFormat) { - dotnet format --no-restore - if ($LASTEXITCODE -ne 0) { + # NOTE: `dotnet format --verify-no-changes` has a known, still-open, + # platform-specific exit-code bug (dotnet/sdk#41422) where the exit code + # can stay 0 on macOS even when files require formatting. It is NOT a + # reason to reformat in place and diff against git - doing so previously + # required stashing the working tree around the format run, which is + # unsafe (and was proven unsafe in practice) around uncommitted renames, + # moves, or any other change that git's stash/pop cannot losslessly + # round-trip. Instead, run in dry-run mode and treat BOTH the exit code + # AND the tool's own diagnostic text as signals - `--verify-no-changes` + # always prints a "failed to verify formatting" line per affected file + # regardless of which platform's exit-code bug is in play, so the text + # check is a reliable fallback. This never mutates the working tree. + $formatOutput = dotnet format --verify-no-changes --no-restore 2>&1 + $formatOutput | ForEach-Object { Write-Host $_ } + if ($LASTEXITCODE -ne 0 -or ($formatOutput -join "`n") -match 'failed to verify formatting') { $lintError = $true - } - else { - git diff --exit-code -- '*.cs' - if ($LASTEXITCODE -ne 0) { - $lintError = $true - Write-Host "dotnet format made changes; run fix.ps1 locally and commit the results." - } - } - - # Restore the working tree to its original state: discard any in-place - # formatting changes made purely for this check, then reapply the - # developer's original uncommitted *.cs changes (if any were stashed). - # `--index` restores the original staged/unstaged split rather than - # dropping everything into the working tree unstaged. - git checkout -- '*.cs' 2>$null - if ($hasPreexistingCsChanges) { - git stash pop --index --quiet - if ($LASTEXITCODE -ne 0) { - $lintError = $true - Write-Host "Failed to restore stashed *.cs changes; check 'git stash list' and resolve manually." - } + Write-Host "dotnet format found formatting issues; run fix.ps1 locally and commit the results." } } From f14359f8eb9a6e2ec7203ee27f1cbc14fa5fdda2 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 28 Sep 2026 21:01:05 -0400 Subject: [PATCH 03/10] Fix 9 Copilot PR review findings on PR #30 (SVG package split) 1. Remove cross-package InternalsVisibleTo from CanvasNet to CanvasNet.Svg; SvgCodec.Markers.cs now computes the closing-edge tangent directly via NormalizeOrNull instead of calling internal PathCommand.LineTo. 2. Add canvas-net-svg.md and canvas-net-svg/svg-codec.md to docs/design/definition.yaml's input-files. 3. Add docs/reqstream/canvas-net-svg/platform-requirements.yaml (mirrors canvas-net/platform-requirements.yaml), wire it into requirements.yaml and the CanvasNetSvg-Design review-set in .reviewmark.yaml. 4. Add 16 new CanvasNetSvg_SystemIntegration_* system-level tests to SvgSystemIntegrationTests.cs covering every top-level CanvasNetSvg requirement that previously had only unit-test (SvgCodec_*) evidence, and link them in docs/reqstream/canvas-net-svg.yaml. 5. Add canvas-net-svg.md and canvas-net-svg/svg-codec.md to docs/verification/definition.yaml's input-files, and mention CanvasNetSvg coverage in docs/verification/introduction.md's scope. 6. Rewrite the design doc's Risk Control Measures section to separate tolerantly-skipped no-effect constructs from reference cycles and resource-disproportionate constructs, both of which are rejected via a thrown InvalidDataException. 7. Correct docs/sysml2/model/canvas-net-svg.sysml wording: CanvasNet and CanvasNetSvg share a git repository but are separate NuGet packages. 8. Reword the "no I/O" claim in docs/verification/canvas-net-svg.md to distinguish no network/service I/O from supported local file-path I/O via Load(string)/GetInfo(string), and add/rename verification test-scenario descriptions to match the current public test suite. 9. Rename the two CanvasNet_SystemIntegration_* tests in SvgSystemIntegrationTests.cs to the CanvasNetSvg_ prefix, and update every reqstream/verification cross-reference to the old names. --- .reviewmark.yaml | 1 + docs/design/canvas-net-svg.md | 29 +- docs/design/definition.yaml | 2 + docs/reqstream/canvas-net-svg.yaml | 20 +- .../canvas-net-svg/platform-requirements.yaml | 72 +++ docs/reqstream/canvas-net-svg/svg-codec.yaml | 2 +- docs/sysml2/model/canvas-net-svg.sysml | 2 +- docs/verification/canvas-net-svg.md | 154 +++++- docs/verification/canvas-net-svg/svg-codec.md | 2 +- docs/verification/definition.yaml | 2 + docs/verification/introduction.md | 3 + requirements.yaml | 1 + .../SvgCodec.Markers.cs | 13 +- .../DemaConsulting.CanvasNet.csproj | 1 - .../SvgSystemIntegrationTests.cs | 490 +++++++++++++++++- 15 files changed, 766 insertions(+), 28 deletions(-) create mode 100644 docs/reqstream/canvas-net-svg/platform-requirements.yaml diff --git a/.reviewmark.yaml b/.reviewmark.yaml index 84f5f56ea..3dcc4026e 100644 --- a/.reviewmark.yaml +++ b/.reviewmark.yaml @@ -555,6 +555,7 @@ reviews: context: - "docs/reqstream/canvas-net-svg.yaml" paths: + - "docs/reqstream/canvas-net-svg/platform-requirements.yaml" # platform requirements - "docs/design/introduction.md" # design introduction - "docs/design/canvas-net-svg.md" # system design - "docs/design/canvas-net-svg/**/*.md" # all system design documents diff --git a/docs/design/canvas-net-svg.md b/docs/design/canvas-net-svg.md index 80e800f47..cdc530c91 100644 --- a/docs/design/canvas-net-svg.md +++ b/docs/design/canvas-net-svg.md @@ -108,14 +108,27 @@ FileAssert, Pandoc, ReqStream, ReviewMark, SarifMark, SonarMark, VersionMark, We `SvgCodec`'s `Load`/`LoadWithFontFaces` operations parse externally-supplied, potentially untrusted SVG documents (XML markup that may embed references, gradients, filters, and base64-encoded raster images). Risk control for this untrusted-input parsing is segregated -entirely within the single `SvgCodec` unit β€” explicit DTD/external-entity hardening (rejecting -any document containing a DOCTYPE declaration), bounded element-nesting depth, total-element, -geometry-work, and number-list-length budgets, and tolerant-fallback (rather than -whole-document-rejecting) handling of dangling references, reference cycles, and -resource-disproportionate constructs β€” see _SvgCodec Unit Design_ (`canvas-net-svg/svg-codec.md`) -for the complete set of budgets and fallback behaviors. No other segregation is required at the -system level: `CanvasNetSvg` contains exactly one unit, so this risk control is inherently -contained within it (IEC 62304 Β§5.3.3). +entirely within the single `SvgCodec` unit and falls into two distinct categories, each with its +own consistently-applied behavior: + +- **Tolerantly skipped, no-effect constructs** β€” a document containing one of these continues to + render the rest of its content rather than failing outright: a dangling `url(#id)` reference + (gradient, pattern, filter, clip-path, or mask) that resolves to no element, a well-formed but + out-of-scope/unrecognized element or filter primitive, an external (non-`data:`) `image` `href`, + and a nested `data:image/svg+xml` document. +- **Rejected reference cycles** β€” an unbounded self- or mutually-referencing chain (a `use` + element referencing itself directly or indirectly, a `marker` referencing a marker that + eventually references it again, a `mask`/`pattern` whose own content resolves back to itself) + is explicitly detected and rejected with a thrown `InvalidDataException`, rather than being + tolerated or silently skipped: recursing into a genuine cycle would otherwise never terminate. + +Beyond these two categories, explicit DTD/external-entity hardening (rejecting any document +containing a DOCTYPE declaration) and bounded element-nesting depth, total-element, +geometry-work, and number-list-length budgets likewise reject the offending document with a +thrown `InvalidDataException` once exceeded, rather than tolerating it β€” see _SvgCodec Unit +Design_ (`canvas-net-svg/svg-codec.md`) for the complete set of budgets and fallback behaviors. +No other segregation is required at the system level: `CanvasNetSvg` contains exactly one unit, +so this risk control is inherently contained within it (IEC 62304 Β§5.3.3). ## Data Flow diff --git a/docs/design/definition.yaml b/docs/design/definition.yaml index 4229ea34a..cec176d34 100644 --- a/docs/design/definition.yaml +++ b/docs/design/definition.yaml @@ -6,6 +6,8 @@ input-files: - docs/design/title.txt - docs/design/introduction.md - docs/design/canvas-net.md + - docs/design/canvas-net-svg.md + - docs/design/canvas-net-svg/svg-codec.md - docs/design/ots.md - docs/design/ots/buildmark.md - docs/design/ots/fileassert.md diff --git a/docs/reqstream/canvas-net-svg.yaml b/docs/reqstream/canvas-net-svg.yaml index a5a477f0e..1b2945aac 100644 --- a/docs/reqstream/canvas-net-svg.yaml +++ b/docs/reqstream/canvas-net-svg.yaml @@ -44,7 +44,7 @@ sections: - CanvasNetSvg-SvgCodec-TotalDocumentElementBudget - CanvasNetSvg-SvgCodec-ValidationOutputDimensions tests: - - CanvasNet_SystemIntegration_SvgLoad_ReturnsExpectedPixel + - CanvasNetSvg_SystemIntegration_SvgLoad_ReturnsExpectedPixel - id: CanvasNetSvg-Lib-SvgMarkerRendering title: >- @@ -65,6 +65,7 @@ sections: - CanvasNetSvg-SvgCodec-MarkerReferenceCycle - CanvasNetSvg-SvgCodec-MarkerPreserveAspectRatio tests: + - CanvasNetSvg_SystemIntegration_SvgMarkerRendering_RendersMarkerAtLineEnd - SvgCodec_Load_MarkerEndOnLine_RendersArrowheadPastLineEnd - SvgCodec_Load_MarkerStartMidEndOnPolyline_RendersDistinctMarkersAtEachVertex - SvgCodec_Load_ArrowMarkersFixture_RendersArrowheadPastLineEnd @@ -111,6 +112,7 @@ sections: - CanvasNetSvg-SvgCodec-FeBlend - CanvasNetSvg-SvgCodec-FilterPrimitiveResourceSafety tests: + - CanvasNetSvg_SystemIntegration_SvgFilterRendering_AppliesFilterChainToShape - SvgCodec_Load_FeFloodFeGaussianBlurFeCompositeFilter_RendersBlurredHaloBehindContent - SvgCodec_Load_FeColorMatrixTypeHueRotate_RotatesHueByAngle - SvgCodec_Load_FeFuncATypeGamma_AppliesGammaCurveToAlpha @@ -151,6 +153,7 @@ sections: - CanvasNetSvg-SvgCodec-EffectOrdering - CanvasNetSvg-SvgCodec-EffectResourceSafety tests: + - CanvasNetSvg_SystemIntegration_SvgClipPathRendering_ClipsContentToReferencedShape - SvgCodec_Load_ClipPathUserSpaceOnUse_ClipsToAbsoluteCircle - SvgCodec_Load_ClipPathObjectBoundingBox_ScalesClipContentToReferenceBounds - SvgCodec_Load_MaskDefaultLuminance_WhiteRevealsBlackHides @@ -181,6 +184,7 @@ sections: - CanvasNetSvg-SvgCodec-PatternHrefInheritance - CanvasNetSvg-SvgCodec-PatternResourceSafety tests: + - CanvasNetSvg_SystemIntegration_SvgPatternRendering_TilesPatternAcrossShape - SvgCodec_Load_PatternDefaultUnits_TilesOnceAcrossShapeBoundingBox - SvgCodec_Load_PatternUserSpaceOnUseUnits_TilesRepeatedlyAcrossUserSpace - SvgCodec_Load_PatternContentUnitsObjectBoundingBox_MapsContentThroughShapeBoundingBox @@ -226,6 +230,7 @@ sections: - CanvasNetSvg-SvgCodec-ImageExternalHrefScope - CanvasNetSvg-SvgCodec-ImageResourceSafety tests: + - CanvasNetSvg_SystemIntegration_SvgImageRendering_RendersEmbeddedRasterImage - SvgCodec_Load_ImageDataUriPng_RendersDecodedPixelsAtPlacementRect - SvgCodec_Load_ImageDataUriJpeg_RendersDecodedPixelsAtPlacementRect - SvgCodec_Load_ImagePreserveAspectRatioMeet_LettersOrPillarboxesNonMatchingAspect @@ -258,6 +263,7 @@ sections: - CanvasNetSvg-SvgCodec-ViewBoxFitting - CanvasNetSvg-SvgCodec-SymbolViewBoxFitting tests: + - CanvasNetSvg_SystemIntegration_SvgViewBoxFitting_LetterboxesWideViewBox - SvgCodec_Load_WideViewBoxIntoSquareRaster_LetterboxesTopAndBottom - SvgCodec_Load_TallViewBoxIntoSquareRaster_LetterboxesLeftAndRight - SvgCodec_Load_RootPreserveAspectRatio_AppliesAlignAndMeetOrSlice @@ -279,6 +285,7 @@ sections: children: - CanvasNetSvg-SvgCodec-PercentageGeometryResolved tests: + - CanvasNetSvg_SystemIntegration_SvgPercentageGeometryResolution_ResolvesWidthPercentage - SvgCodec_Load_RectXPercentage_ResolvesAgainstViewportWidth - SvgCodec_Load_RectWidthPercentage_ResolvesAgainstViewportWidth - SvgCodec_Load_RectYHeightPercentage_ResolvesAgainstViewportHeight @@ -302,6 +309,7 @@ sections: - CanvasNetSvg-SvgCodec-GetInfo - CanvasNetSvg-SvgCodec-GetInfoFallback tests: + - CanvasNetSvg_SystemIntegration_SvgGetInfo_ReturnsViewBoxDimensions - SvgCodec_GetInfo_ViewBoxPresent_ReturnsViewBoxDimensions - SvgCodec_GetInfo_FromFilePath_ReturnsExpectedInfo - SvgCodec_GetInfo_NoViewBoxWidthHeightPresent_ReturnsWidthHeight @@ -322,6 +330,7 @@ sections: - CanvasNetSvg-SvgCodec-TextFontFallbackSkipsSilently - CanvasNetSvg-SvgCodec-TextAnchor tests: + - CanvasNetSvg_SystemIntegration_SvgTextRendering_RendersGlyphAtExpectedPosition - SvgCodec_Load_TextWithMatchingFont_RendersGlyphAtExpectedPosition - SvgCodec_Load_TextWithKerningPair_AppliesKerningBetweenGlyphs - SvgCodec_Load_TextFixtureWithRealFont_RendersVisibleGlyphInk @@ -348,6 +357,7 @@ sections: - CanvasNetSvg-SvgCodec-FontFaceMatching - CanvasNetSvg-SvgCodec-LegacySingleFontCompatibility tests: + - CanvasNetSvg_SystemIntegration_SvgFontWeightStyleMatching_SelectsBoldFaceOverNormalFace - SvgCodec_Load_TextFontWeightBold_SelectsBoldFaceOverNormalFace - SvgCodec_Load_TextFontStyleItalic_SelectsItalicFaceOverNormalFace - SvgCodec_Load_TextFontWeightAndStyleCombined_SelectsExactMatchAmongThreeFaces @@ -367,6 +377,7 @@ sections: children: - CanvasNetSvg-SvgCodec-ValidationNull tests: + - CanvasNetSvg_SystemIntegration_SvgValidationNull_NullStreamThrowsArgumentNullException - SvgCodec_Load_NullStream_ThrowsArgumentNullException - SvgCodec_Load_NullPath_ThrowsArgumentNullException - SvgCodec_GetInfo_NullStream_ThrowsArgumentNullException @@ -384,6 +395,7 @@ sections: children: - CanvasNetSvg-SvgCodec-ValidationEmptyPath tests: + - CanvasNetSvg_SystemIntegration_SvgValidationEmptyPath_EmptyPathThrowsArgumentException - SvgCodec_Load_EmptyPath_ThrowsArgumentException - SvgCodec_Load_WhitespacePath_ThrowsArgumentException - SvgCodec_GetInfo_EmptyPath_ThrowsArgumentException @@ -401,6 +413,7 @@ sections: - CanvasNetSvg-SvgCodec-MalformedXmlRejected - CanvasNetSvg-SvgCodec-MalformedPathDataRejected tests: + - CanvasNetSvg_SystemIntegration_SvgUnsupportedFormatValidation_MalformedXmlThrowsInvalidDataException - SvgCodec_Load_MalformedXml_ThrowsInvalidDataException - SvgCodec_Load_MalformedViewBoxWrongNumberCount_ThrowsInvalidDataException - SvgCodec_Load_ViewBoxNonPositiveWidth_ThrowsInvalidDataException @@ -422,6 +435,7 @@ sections: children: - CanvasNetSvg-SvgCodec-XxeHardening tests: + - CanvasNetSvg_SystemIntegration_SvgXxeHardening_DoctypeDeclarationThrowsInvalidDataException - SvgCodec_Load_DocumentWithDoctypeDeclaration_ThrowsInvalidDataException - SvgCodec_Load_DocumentWithExternalEntityDoctype_ThrowsInvalidDataException - SvgCodec_GetInfo_DocumentWithExternalEntityDoctype_ThrowsInvalidDataException @@ -438,6 +452,7 @@ sections: children: - CanvasNetSvg-SvgCodec-UnsupportedConstructsIgnored tests: + - CanvasNetSvg_SystemIntegration_SvgTolerateUnsupportedConstructs_StillRendersRestOfDocument - SvgCodec_Load_UnsupportedConstructs_StillRendersRestOfDocument - SvgCodec_Load_ToleratesUnsupportedConstructFixture_StillRendersRemainingContent @@ -452,6 +467,7 @@ sections: - CanvasNetSvg-SvgCodec-ValidationNull - CanvasNetSvg-SvgCodec-ValidationEmptyPath tests: + - CanvasNetSvg_SystemIntegration_SvgGetInfoValidation_NullStreamThrowsArgumentNullException - SvgCodec_GetInfo_NullStream_ThrowsArgumentNullException - SvgCodec_GetInfo_NullPath_ThrowsArgumentNullException - SvgCodec_GetInfo_EmptyPath_ThrowsArgumentException @@ -477,4 +493,4 @@ sections: - CanvasNetSvg-SvgCodec-CssThreeTierPrecedence - CanvasNetSvg-SvgCodec-CssResourceSafety tests: - - CanvasNet_SystemIntegration_SvgLoadWithCssStyleElement_ReturnsExpectedPixel + - CanvasNetSvg_SystemIntegration_SvgLoadWithCssStyleElement_ReturnsExpectedPixel diff --git a/docs/reqstream/canvas-net-svg/platform-requirements.yaml b/docs/reqstream/canvas-net-svg/platform-requirements.yaml new file mode 100644 index 000000000..e7aa3e5d3 --- /dev/null +++ b/docs/reqstream/canvas-net-svg/platform-requirements.yaml @@ -0,0 +1,72 @@ +--- +# System-Level Platform Requirements +# +# These requirements specify the platforms and frameworks the CanvasNetSvg package must support. +# They ensure the package works across the required execution environments - identical to the +# CanvasNet system it depends on (see docs/design/canvas-net-svg.md's Platform Support section). +# +# Test links can include a source filter prefix (e.g. "windows@", "ubuntu@", "net8.0@") to restrict +# which test results count as evidence for a requirement. This is critical for platform and framework +# requirements - removing these filters invalidates the evidence-based proof. +# +# Source filter prefixes: +# windows@TestName - proves the test passed on a Windows platform +# ubuntu@TestName - proves the test passed on a Linux (Ubuntu) platform +# macos@TestName - proves the test passed on a macOS platform +# net8.0@TestName - proves the test passed under the .NET 8 runtime +# net9.0@TestName - proves the test passed under the .NET 9 runtime +# net10.0@TestName - proves the test passed under the .NET 10 runtime + +sections: + - title: Platform Support + requirements: + - id: CanvasNetSvg-Platform-Windows + title: The library shall build and run on Windows platforms. + tags: [system] + justification: | + DEMA Consulting libraries must support Windows as a major development platform. + tests: + # Tests link to "windows" to ensure results come from Windows platform + - "windows@CanvasNetSvg_SystemIntegration_SvgLoad_ReturnsExpectedPixel" + + - id: CanvasNetSvg-Platform-Linux + title: The library shall build and run on Linux platforms. + tags: [system] + justification: | + DEMA Consulting libraries must support Linux for CI/CD and containerized environments. + tests: + # Tests link to "ubuntu" to ensure results come from Linux platform + - "ubuntu@CanvasNetSvg_SystemIntegration_SvgLoad_ReturnsExpectedPixel" + + - id: CanvasNetSvg-Platform-MacOS + title: The library shall build and run on macOS platforms. + tags: [system] + justification: | + DEMA Consulting libraries must support macOS for developers using Apple platforms. + tests: + # Tests link to "macos" to ensure results come from macOS platform + - "macos@CanvasNetSvg_SystemIntegration_SvgLoad_ReturnsExpectedPixel" + + - id: CanvasNetSvg-Platform-Net8 + title: The library shall support .NET 8 runtime. + tags: [system] + justification: | + .NET 8 is an LTS release providing long-term stability for enterprise users. + tests: + - "net8.0@CanvasNetSvg_SystemIntegration_SvgLoad_ReturnsExpectedPixel" + + - id: CanvasNetSvg-Platform-Net9 + title: The library shall support .NET 9 runtime. + tags: [system] + justification: | + .NET 9 support enables users to leverage the latest .NET features. + tests: + - "net9.0@CanvasNetSvg_SystemIntegration_SvgLoad_ReturnsExpectedPixel" + + - id: CanvasNetSvg-Platform-Net10 + title: The library shall support .NET 10 runtime. + tags: [system] + justification: | + .NET 10 support ensures the library remains compatible with the latest .NET ecosystem. + tests: + - "net10.0@CanvasNetSvg_SystemIntegration_SvgLoad_ReturnsExpectedPixel" diff --git a/docs/reqstream/canvas-net-svg/svg-codec.yaml b/docs/reqstream/canvas-net-svg/svg-codec.yaml index 7f09f79ec..1a0e0b3df 100644 --- a/docs/reqstream/canvas-net-svg/svg-codec.yaml +++ b/docs/reqstream/canvas-net-svg/svg-codec.yaml @@ -1432,7 +1432,7 @@ sections: - SvgCodec_Load_CssPrecedenceTier2_StylesheetOverridesPresentationAttribute - SvgCodec_Load_CssPrecedenceTier3_InlineStyleOverridesStylesheet - SvgCodec_Load_CssStylingFixture_AppliesEverySelectorKindAndPrecedenceTier - - CanvasNet_SystemIntegration_SvgLoadWithCssStyleElement_ReturnsExpectedPixel + - CanvasNetSvg_SystemIntegration_SvgLoadWithCssStyleElement_ReturnsExpectedPixel - id: CanvasNetSvg-SvgCodec-CssResourceSafety title: >- diff --git a/docs/sysml2/model/canvas-net-svg.sysml b/docs/sysml2/model/canvas-net-svg.sysml index 6b0af7773..cb44e8334 100644 --- a/docs/sysml2/model/canvas-net-svg.sysml +++ b/docs/sysml2/model/canvas-net-svg.sysml @@ -6,7 +6,7 @@ package CanvasNet { comment designRef /* Design: docs/design/canvas-net-svg.md */ comment verificationRef /* Verification: docs/verification/canvas-net-svg.md */ comment reqRef /* Requirements: docs/reqstream/canvas-net-svg.yaml */ - comment /* CanvasNetSvg depends on the sibling CanvasNet system's Canvas subsystem (for the Surface pixel buffer SvgCodec rasterizes into), Geometry subsystem (for Path/Rect/BezierFlattening/SvgArcConverter), Drawing subsystem (for PathFiller/PathStroker/GradientPaint rasterization), and Fonts subsystem (for TrueTypeFont glyph-outline text rendering) - modeled below as ordinary part usages of those existing subsystem part defs, since both systems live in this same repository/package rather than being third-party (OTS) or Shared Package dependencies. */ + comment /* CanvasNetSvg depends on the sibling CanvasNet system's Canvas subsystem (for the Surface pixel buffer SvgCodec rasterizes into), Geometry subsystem (for Path/Rect/BezierFlattening/SvgArcConverter), Drawing subsystem (for PathFiller/PathStroker/GradientPaint rasterization), and Fonts subsystem (for TrueTypeFont glyph-outline text rendering) - modeled below as ordinary part usages of those existing subsystem part defs, since both systems live in this same git repository (though each is distributed as its own separate NuGet package - CanvasNetSvg is not folded into the CanvasNet package) rather than being third-party (OTS) or Shared Package dependencies (both of which are reserved for a package produced by a different repository). */ part svgCodec : SvgCodec; diff --git a/docs/verification/canvas-net-svg.md b/docs/verification/canvas-net-svg.md index 94c1a15e6..aeafa4b48 100644 --- a/docs/verification/canvas-net-svg.md +++ b/docs/verification/canvas-net-svg.md @@ -24,15 +24,18 @@ System tests reside in `SvgSystemIntegrationTests.cs` within the ## External Interface Simulation -The system has no external interfaces requiring simulation. It is a pure in-process .NET library -with no I/O, network calls, or platform services. System tests call the public API directly -with controlled inputs and verify returned values and thrown exceptions. +The system has no external network or service interfaces requiring simulation - no HTTP calls, +databases, or remote services are involved. It does support local file-path-based I/O through its +public API (`Load(string path, ...)`/`GetInfo(string path)` read an SVG document from a local +file path), which system tests exercise using in-memory streams in preference to on-disk fixtures +wherever a scenario does not specifically target the file-path overloads. System tests call the +public API directly with controlled inputs and verify returned values and thrown exceptions. ## System-Level Test Scenarios ### Integration: Svg Load Returns Expected Pixel -**Test**: `CanvasNet_SystemIntegration_SvgLoad_ReturnsExpectedPixel` +**Test**: `CanvasNetSvg_SystemIntegration_SvgLoad_ReturnsExpectedPixel` Exercises end-to-end system behavior for the `SvgCodec` unit: rasterizes a minimal SVG document (a `viewBox` matching the requested raster exactly, containing one rectangle filled with a @@ -45,7 +48,7 @@ no "Save" half to this round-trip: `SvgCodec` is decode/rasterize-only. ### Integration: Svg Load With Css Style Element Returns Expected Pixel -**Test**: `CanvasNet_SystemIntegration_SvgLoadWithCssStyleElement_ReturnsExpectedPixel` +**Test**: `CanvasNetSvg_SystemIntegration_SvgLoadWithCssStyleElement_ReturnsExpectedPixel` Exercises end-to-end system behavior for the `SvgCodec` unit's CSS engine: rasterizes an SVG document whose only source of color is a `" + ""; - using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(svg)); + using var stream = ToStream(svg); // Act: rasterize the document onto a new Surface through the public API var surface = SvgCodec.Load(stream, 10, 10); @@ -53,4 +146,393 @@ public void CanvasNet_SystemIntegration_SvgLoadWithCssStyleElement_ReturnsExpect // Assert: the system produces the expected integrated rasterized pixel value Assert.Equal(new Rgba32(11, 22, 33, 255), surface[5, 5]); } + + /// + /// Proves that the system rasterizes a marker referenced from a line element's + /// marker-end attribute, placing it at the line's end vertex, through the public + /// API. See SvgCodecTests for the full unit test coverage of marker orientation, + /// scale, and reference-cycle rejection. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgMarkerRendering_RendersMarkerAtLineEnd() + { + // Arrange: a horizontal line from (0,5) to (8,5); its marker-end places a 4x4 + // "userSpaceOnUse" red square anchored at (2,2) (refX/refY), so at the (8,5) end vertex + // the square occupies (6,3)-(10,7) + const string svg = """ + + + + + + + + + """; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 10, 10); + + // Assert: the marker's red square is visible past the line's own x2=8 end point + Assert.Equal(new Rgba32(255, 0, 0, 255), surface[9, 5]); + } + + /// + /// Proves that the system rasterizes a filter chain (feFlood/feComposite/feGaussianBlur/ + /// feMerge) referenced from a shape's filter attribute, through the public API. See + /// SvgCodecTests for the full unit test coverage of the individual filter + /// primitives. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgFilterRendering_AppliesFilterChainToShape() + { + // Arrange + const string svg = """ + + + + + + + + + + + + + + + """; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: the rect's own fill remains fully opaque and unaffected at its center + Assert.Equal(new Rgba32(0, 128, 0, 255), surface[50, 50]); + } + + /// + /// Proves that the system rasterizes a clipPath element referenced from a shape's + /// clip-path attribute, hard-clipping to the referenced shape, through the public + /// API. See SvgCodecTests for the full unit test coverage of clip/mask unit systems + /// and effect ordering. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgClipPathRendering_ClipsContentToReferencedShape() + { + // Arrange: a 60x60 red rect at (20,20)-(80,80), clipped by a circle centered at (50,50) + // with radius 20 (i.e. covering (30,30)-(70,70)) + const string svg = """ + + + + + + + + + """; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: inside the clip circle, the rect's own red fill is visible + Assert.Equal(new Rgba32(255, 0, 0, 255), surface[50, 50]); + // Assert: outside the clip circle but inside the rect's own bounds, nothing was painted + Assert.Equal(0, surface[22, 22].A); + } + + /// + /// Proves that the system tiles a pattern element referenced from a shape's + /// fill attribute across the shape's own bounding box, through the public API. See + /// SvgCodecTests for the full unit test coverage of pattern unit systems, href + /// inheritance, and resource safety. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgPatternRendering_TilesPatternAcrossShape() + { + // Arrange: a 60x60 bounding box (20,20)-(80,80); the pattern's own width/height (1,1) are + // objectBoundingBox-interpreted (the default patternUnits), so exactly one tile spans the + // whole bounding box + const string svg = """ + + + + + + + + + + """; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: the pattern's own tile content is visible inside the filled shape's bounding box + Assert.Equal(new Rgba32(0, 255, 0, 255), surface[50, 50]); + } + + /// + /// Proves that the system decodes and rasterizes an image element's base64-encoded + /// PNG data URI at the element's own placement rect, through the public API. See + /// SvgCodecTests for the full unit test coverage of other raster formats, + /// preserveAspectRatio, effects integration, and resource safety. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgImageRendering_RendersEmbeddedRasterImage() + { + // Arrange: a 2x2 solid blue PNG, placed at (20,20) with a 60x60 placement rect + using var source = BuildSolidSurface(2, 2, new Rgba32(0, 0, 255, 255)); + var dataUri = BuildPngDataUri(source); + var svg = $""" + + + + """; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: the decoded blue pixel is visible inside the placement rect + Assert.Equal(new Rgba32(0, 0, 255, 255), surface[50, 50]); + // Assert: outside the placement rect, nothing was painted + Assert.Equal(0, surface[10, 10].A); + } + + /// + /// Proves that the system fits a wide (landscape) viewBox into a square raster, + /// letterboxing with transparent bars above and below the centered content, through the + /// public API. See SvgCodecTests for the full unit test coverage of other + /// preserveAspectRatio align/meet-or-slice combinations. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgViewBoxFitting_LetterboxesWideViewBox() + { + // Arrange: 200x100 viewBox (2:1) into a 100x100 raster; scale equals 0.5, content + // occupies y equals 25 to 75, leaving transparent bars above/below + const string svg = ""; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: content band is filled + Assert.Equal(255, surface[50, 50].A); + // Assert: top and bottom letterbox bars are transparent + Assert.Equal(0, surface[50, 5].A); + Assert.Equal(0, surface[50, 95].A); + } + + /// + /// Proves that the system resolves a rect's width percentage against the + /// current viewport width rather than rejecting it, through the public API. See + /// SvgCodecTests for the full per-attribute-family basis matrix coverage. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgPercentageGeometryResolution_ResolvesWidthPercentage() + { + // Arrange: width="50%" of a 100-wide viewBox resolves to width=50; the rect spans x=[0,50) + const string svg = ""; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: the percentage-resolved width is honored + Assert.Equal(new Rgba32(255, 0, 0, 255), surface[25, 5]); + Assert.Equal(0, surface[75, 5].A); + } + + /// + /// Proves that the system reports an SVG document's resolved viewBox dimensions via + /// the public entry point. See SvgCodecTests + /// for the full unit test coverage of the width/height/CSS-default fallback chain. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgGetInfo_ReturnsViewBoxDimensions() + { + // Arrange + const string svg = ""; + + // Act: query the document's intrinsic size through the public API + using var stream = ToStream(svg); + var info = SvgCodec.GetInfo(stream); + + // Assert: the viewBox dimensions win over the width/height attributes + Assert.Equal(40, info.Width); + Assert.Equal(20, info.Height); + Assert.Equal(4, info.Channels); + Assert.True(info.HasAlpha); + } + + /// + /// Proves that the system renders an SVG text element's characters as glyph + /// outlines from a caller-supplied font, through the public API. See + /// SvgCodecTests/SvgFixtureTests for the full unit test coverage of + /// text-anchor, kerning, and font-family fallback. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgTextRendering_RendersGlyphAtExpectedPosition() + { + // Arrange: font-size equals the font's em-square (100), so scale is 1:1; the square glyph + // for 'A' should render spanning x equals 10 to 60, y equals 10 to 60 (baseline at y=60) + const string svg = "A"; + var fonts = new Dictionary { ["TestFont"] = BuildTestFont() }; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100, fonts); + + // Assert: inside the glyph square + Assert.Equal(255, surface[35, 35].A); + // Assert: outside the glyph square (above baseline extent and off to the side) + Assert.Equal(0, surface[5, 5].A); + } + + /// + /// Proves that the system selects a registered bold face over a registered normal face for + /// a text element with font-weight="bold", through the public + /// + /// entry point. See SvgCodecTests for the full unit test coverage of font-style + /// matching and legacy single-font-per-family compatibility. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgFontWeightStyleMatching_SelectsBoldFaceOverNormalFace() + { + // Arrange: font-size equals the shared 100-unit em-square, so scale is 1:1. The narrow + // face fills canvas x equals 10 to 60; the wide face fills canvas x equals 10 to 90 - x + // equals 75 is filled only by the wide (bold) face. + const string svg = """ + + A + A + + """; + var faces = new Dictionary> + { + ["TestFont"] = + [ + new SvgFontFace(BuildTestFont(), Weight: 400), + new SvgFontFace(BuildBoldTestFont(), Weight: 700) + ] + }; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.LoadWithFontFaces(stream, 100, 100, faces); + + // Assert: the font-weight="bold" text selected the wide face + Assert.Equal(255, surface[75, 35].A); + // Assert: the sibling text with no font-weight still selected the narrow face + Assert.Equal(0, surface[75, 70].A); + } + + /// + /// Proves that the system rejects a null stream argument to + /// + /// with through the public API. See + /// SvgCodecTests for the full unit test coverage of the other null-argument + /// variants (null path, GetInfo overloads). + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgValidationNull_NullStreamThrowsArgumentNullException() + { + // Arrange, Act & Assert: passing a null stream through the public API is rejected + Assert.Throws(() => SvgCodec.Load((Stream)null!, 10, 10)); + } + + /// + /// Proves that the system rejects an empty path argument to + /// + /// with through the public API. See + /// SvgCodecTests for the full unit test coverage of the whitespace-only variant. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgValidationEmptyPath_EmptyPathThrowsArgumentException() + { + // Arrange, Act & Assert: passing an empty path through the public API is rejected + Assert.Throws(() => SvgCodec.Load(string.Empty, 10, 10)); + } + + /// /// Proves that the system rejects malformed (non-well-formed) SVG XML with + /// through the public API. See SvgCodecTests for + /// the full unit test coverage of the other malformed-input variants (viewBox, transform, + /// path data). + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgUnsupportedFormatValidation_MalformedXmlThrowsInvalidDataException() + { + // Arrange: an unclosed root element - not well-formed XML + const string svg = "(() => SvgCodec.Load(stream, 100, 100)); + } + + /// + /// Proves that the system rejects an SVG document containing a DOCTYPE declaration with + /// through the public API, defending against XXE + /// injection. See SvgCodecTests for the full unit test coverage of the external + /// entity variant and the GetInfo path. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgXxeHardening_DoctypeDeclarationThrowsInvalidDataException() + { + // Arrange: a well-formed document that is otherwise entirely valid, except for a DOCTYPE + // declaration + const string svg = "]>"; + + // Act & Assert: the DOCTYPE-bearing document is rejected through the public API + using var stream = ToStream(svg); + Assert.Throws(() => SvgCodec.Load(stream, 100, 100)); + } + + /// + /// Proves that the system silently skips well-formed but out-of-scope SVG constructs, + /// continuing to render the rest of the document, through the public API. See + /// SvgCodecTests for the full unit test coverage of individual unsupported + /// construct kinds. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgTolerateUnsupportedConstructs_StillRendersRestOfDocument() + { + // Arrange: a nested inner element is out of scope; the sibling plain rect after it + // should still render + const string svg = """ + + + + + """; + + // Act: rasterize the document onto a new Surface through the public API + using var stream = ToStream(svg); + var surface = SvgCodec.Load(stream, 100, 100); + + // Assert: the plain rect after the unsupported construct still rendered + Assert.Equal(255, surface[20, 20].A); + } + + /// + /// Proves that the system rejects a null stream argument to + /// with the same contract as + /// , + /// through the public API. See SvgCodecTests for the full unit test coverage of the + /// other GetInfo validation variants. + /// + [Fact] + public void CanvasNetSvg_SystemIntegration_SvgGetInfoValidation_NullStreamThrowsArgumentNullException() + { + // Arrange, Act & Assert: passing a null stream to GetInfo through the public API is + // rejected exactly as Load rejects one + Assert.Throws(() => SvgCodec.GetInfo((Stream)null!)); + } } From ea3fa791a2605aa158163482c4abaf8cf564a859 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 28 Sep 2026 21:15:35 -0400 Subject: [PATCH 04/10] Revise finding #1 fix: expose public PathCommand.ComputeTangents API Supersede the earlier option (a) fix (a private, SVG-package-local tangent helper) with option (b): a deliberate, documented, tested PUBLIC core API, since a future PDF/PPTX/VSDX codec package will plausibly need the same path-segment-tangent computation for its own marker/arrowhead-style rendering. - Add PathCommand.ComputeTangents(start) (public instance method) to DemaConsulting.CanvasNet, computing a command's outgoing/incoming unit tangent directions for LineTo/QuadraticBezierTo/CubicBezierTo, returning (null, null) for ArcTo/Close. - Make PathCommand.LineTo(end) public (previously internal), so an external consumer can synthesize a standalone line-segment command (needed to represent an implicit closing edge, which is never itself recorded as its own PathCommand). - Update SvgCodec.Markers.cs to call command.ComputeTangents(current) and PathCommand.LineTo(subpath.Start).ComputeTangents(...) instead of its own private duplicate of this logic. - Add PathCommandTests.cs (9 tests) to DemaConsulting.CanvasNet.Tests covering LineTo and ComputeTangents for every PathCommandType. - Add CanvasNet-Geometry-PathCommand-PublicLineToFactory and CanvasNet-Geometry-PathCommand-ComputeTangents requirements to docs/reqstream/canvas-net/geometry/path.yaml, and corresponding design/verification coverage in docs/design/canvas-net/geometry/path.md and docs/verification/canvas-net/geometry/path.md. - Add the new test file to the CanvasNet-Geometry-Path review-set in .reviewmark.yaml. The cross-package InternalsVisibleTo grant remains removed, as before; SvgCodec.Markers.cs no longer needs it because it now calls only PathCommand's public API. --- .reviewmark.yaml | 1 + docs/design/canvas-net/geometry/path.md | 51 ++++- docs/reqstream/canvas-net/geometry/path.yaml | 52 ++++- docs/verification/canvas-net/geometry/path.md | 40 +++- .../SvgCodec.Markers.cs | 78 ++----- .../Geometry/PathCommand.cs | 97 ++++++++- .../Geometry/PathCommandTests.cs | 194 ++++++++++++++++++ 7 files changed, 424 insertions(+), 89 deletions(-) create mode 100644 test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs diff --git a/.reviewmark.yaml b/.reviewmark.yaml index 3dcc4026e..55f45cbd6 100644 --- a/.reviewmark.yaml +++ b/.reviewmark.yaml @@ -298,6 +298,7 @@ reviews: - "src/DemaConsulting.CanvasNet/Geometry/PathCommandType.cs" # supporting data type source - "test/DemaConsulting.CanvasNet.Tests/Geometry/PathBuilderTests.cs" # unit tests - "test/DemaConsulting.CanvasNet.Tests/Geometry/PathTests.cs" # unit tests + - "test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs" # unit tests # CanvasNet-Geometry-CornerRoundEffect Review (one per unit) - id: CanvasNet-Geometry-CornerRoundEffect diff --git a/docs/design/canvas-net/geometry/path.md b/docs/design/canvas-net/geometry/path.md index d3dd36424..fd4bca906 100644 --- a/docs/design/canvas-net/geometry/path.md +++ b/docs/design/canvas-net/geometry/path.md @@ -44,12 +44,15 @@ directly as its own `Start` field, and `PathCommandType` only enumerates the com legally follow a subpath's start. This makes "a subpath's first point" a structural guarantee rather than a convention every consumer must separately validate. -`PathCommand` is a flat readonly struct (not a class hierarchy) with a private constructor and -internal static factory methods (`LineTo`, `QuadraticBezierTo`, `CubicBezierTo`, `ArcTo`, -`Close`) used only by `PathBuilder`, carrying every field any command kind might need -(`EndPoint`, `Control1`, `Control2`, `Radius`, `RotationDegrees`, `LargeArc`, `Sweep`); which -fields are meaningful is determined by `Type`. This keeps `Path`'s internal storage a simple, -allocation-friendly array of value-type structs rather than an array of polymorphic references. +`PathCommand` is a flat readonly struct (not a class hierarchy) with a private constructor, +carrying every field any command kind might need (`EndPoint`, `Control1`, `Control2`, `Radius`, +`RotationDegrees`, `LargeArc`, `Sweep`); which fields are meaningful is determined by `Type`. +This keeps `Path`'s internal storage a simple, allocation-friendly array of value-type structs +rather than an array of polymorphic references. Every static factory method (`QuadraticBezierTo`, +`CubicBezierTo`, `ArcTo`, `Close`) is internal, used only by `PathBuilder`, except `LineTo`, which +is public: a straight line segment is the simplest possible `PathCommand`, and a consumer outside +this package (see `PathCommand.ComputeTangents` below) legitimately needs to synthesize one of +its own. **Architectural decision: `PathBuilder.ArcTo` stores raw SVG parameters only.** `ArcTo` never pre-inspects or pre-converts its `radius`/`rotationDegrees`/`largeArc`/`sweep`/`end` parameters; @@ -125,6 +128,34 @@ subpath's own contribution. Never throws. +#### PathCommand.LineTo(end) + +A public static factory constructing a standalone `LineTo` command, independent of +`PathBuilder`. Unlike every other factory on this type, this one is public: a consumer outside +this package (for example, a format codec computing a marker/arrowhead orientation) legitimately +needs to synthesize a straight-line command of its own - for example, to represent a closed +subpath's implicit closing edge, which is never itself recorded as its own `PathCommand` (a +`Close` command carries no `EndPoint`). + +#### PathCommand.ComputeTangents(start) + +Computes this command's outgoing (leaving `start`) and incoming (arriving at `EndPoint`) unit +tangent directions. For `LineTo`, both tangents are the normalized direction of travel. For +`QuadraticBezierTo`/`CubicBezierTo`, the outgoing tangent points toward the first non-coincident +control point (falling back through the remaining control points, then to `EndPoint`, when every +earlier one coincides with `start`), and the incoming tangent points away from the last +non-coincident control point (falling back symmetrically toward `start`). Returns +`(null, null)` for `ArcTo` (whose tangent depends on its Bezier conversion via +`SvgArcConverter`, which this method does not perform) and `Close` (which carries no `EndPoint` +of its own), and `null` for either tangent whenever the relevant direction is zero-length. + +This is the shared geometry building block a marker/arrowhead-orientation feature needs - +first introduced for `DemaConsulting.CanvasNet.Svg`'s own marker rendering, but deliberately +placed on `PathCommand` itself, in core, rather than duplicated privately inside that package: a +future format codec package (for example, a PDF, PPTX, or VSDX codec rendering its own connector +arrowheads) needing the same tangent/direction computation can call this same public API instead +of reimplementing it. + ### Error Handling `PathBuilder`'s drawing-command guard (`InvalidOperationException` before the first `MoveTo`, or @@ -145,4 +176,10 @@ and by its `ArcTo` handling, respectively). `PathBuilder` and `Path` are public API entry points, invoked externally by consumers of the CanvasNet package. `Path` has no dependency on any consumer; `Geometry` has no runnable end-to-end example yet within this library, since no rasterizer (the reserved `Drawing` -subsystem) exists yet to consume a `Path`. +subsystem) exists yet to consume a `Path`. `PathCommand.LineTo` and `PathCommand.ComputeTangents` +are, likewise, public API entry points with an external caller: the separate +`DemaConsulting.CanvasNet.Svg` package's marker-rendering feature calls both - synthesizing a +`LineTo` command for a closed subpath's implicit closing edge and computing every marker +vertex's tangent via `ComputeTangents` - rather than depending on cross-package internal access +to this package's `PathBuilder`-only factory methods, which would be fragile once the two +packages are independently NuGet versioned. diff --git a/docs/reqstream/canvas-net/geometry/path.yaml b/docs/reqstream/canvas-net/geometry/path.yaml index f174c8286..f565ca3ac 100644 --- a/docs/reqstream/canvas-net/geometry/path.yaml +++ b/docs/reqstream/canvas-net/geometry/path.yaml @@ -4,10 +4,12 @@ # These requirements describe the design-level behavior of the Path and PathBuilder unit, # within the Geometry subsystem. Path is an immutable snapshot produced only by # PathBuilder.Build(); PathBuilder is the mutable, fluent builder used to construct it. The -# supporting types Subpath, PathCommand, and PathCommandType have no requirements of their own -# (they are plain data carriers with no independently testable behavior) and are covered here -# inline, following the precedent set by Rgba32 being covered inline within the Surface unit's -# requirements. +# supporting types Subpath and PathCommandType have no requirements of their own (they are plain +# data carriers with no independently testable behavior) and are covered here inline, following +# the precedent set by Rgba32 being covered inline within the Surface unit's requirements. +# PathCommand is likewise mostly a plain data carrier, except for its public LineTo factory and +# ComputeTangents method, which have independently testable behavior and their own requirements +# below. sections: - title: CanvasNet Requirements @@ -275,3 +277,45 @@ sections: - PathBuilder_TangentArcTo_ZeroRadius_DegradesToLineToCorner - PathBuilder_TangentArcTo_NegativeRadius_ThrowsArgumentOutOfRangeException - PathBuilder_TangentArcTo_NoCurrentPoint_ThrowsInvalidOperationException + + - id: CanvasNet-Geometry-PathCommand-PublicLineToFactory + title: >- + The PathCommand class shall provide a public LineTo(end) static factory that + constructs a standalone LineTo command, independent of PathBuilder. + justification: | + A consumer outside this package (for example, a format codec computing a + marker/arrowhead orientation for a closed subpath's implicit closing edge, which + is never itself recorded as its own PathCommand) legitimately needs to + synthesize a straight-line command to feed into ComputeTangents, without relying + on cross-package internal access to this package's own PathBuilder-only factory + methods, which is fragile once the two packages are independently NuGet + versioned. + tests: + - PathCommand_LineTo_GivenEndPoint_ConstructsLineToCommandWithThatEndPoint + + - id: CanvasNet-Geometry-PathCommand-ComputeTangents + title: >- + The PathCommand class shall provide a ComputeTangents(start) method returning + the command's outgoing and incoming unit tangent directions for LineTo, + QuadraticBezierTo, and CubicBezierTo commands - falling back, for a Bezier + command, to the nearest non-coincident control point or endpoint when a control + point coincides with the command's start or end point - and returning + (null, null) for ArcTo and Close commands and for any command whose relevant + direction is zero-length. + justification: | + A path segment's tangent direction is the shared building block any + marker/arrowhead-orientation feature (or any other future consumer needing a + segment's direction of travel, such as a future PDF/PPTX/VSDX format codec + package rendering its own connector arrowheads) needs; centralizing this + computation on PathCommand itself - rather than duplicating it privately inside + each consuming package - keeps the geometry authoritative in one place and + usable across every current and future package built on top of Path. + tests: + - PathCommand_ComputeTangents_LineTo_ReturnsSameNormalizedDirectionForBothTangents + - PathCommand_ComputeTangents_LineToWithCoincidentStartAndEnd_ReturnsNullTangents + - PathCommand_ComputeTangents_QuadraticBezierTo_PointsTowardThenAwayFromControlPoint + - PathCommand_ComputeTangents_QuadraticBezierToWithControlCoincidentWithStart_FallsBackToEndDirection + - PathCommand_ComputeTangents_CubicBezierTo_PointsTowardFirstThenAwayFromSecondControlPoint + - PathCommand_ComputeTangents_CubicBezierToWithBothControlPointsCoincidentWithEndpoints_FallsBackToEndDirection + - PathCommand_ComputeTangents_ArcTo_ReturnsNullTangents + - PathCommand_ComputeTangents_Close_ReturnsNullTangents diff --git a/docs/verification/canvas-net/geometry/path.md b/docs/verification/canvas-net/geometry/path.md index 0d8b710bf..96e10f62b 100644 --- a/docs/verification/canvas-net/geometry/path.md +++ b/docs/verification/canvas-net/geometry/path.md @@ -1,18 +1,21 @@ ## Path Unit Verification Design This document describes the unit-level verification strategy for the `Path` and `PathBuilder` -classes (and their supporting `Subpath`, `PathCommand`, and `PathCommandType` data types). +classes (and their supporting `Subpath` and `PathCommandType` data types, plus `PathCommand`'s own +`LineTo` factory and `ComputeTangents` method). ### Verification Approach The `Path`/`PathBuilder` unit is verified through unit tests that exercise every fluent builder method, the `InvalidOperationException` guards, `Build()`'s snapshot semantics, `Clear()`, -`Path.Empty`, and both modes of `Path.GetBounds`, in isolation. Expected bounding rectangles are -hand-computed independently of the implementation for both the conservative (control-point -convex-hull) mode and the flattening-based tighter mode. +`Path.Empty`, both modes of `Path.GetBounds`, and `PathCommand`'s own public `LineTo`/ +`ComputeTangents` API, in isolation. Expected bounding rectangles are hand-computed independently +of the implementation for both the conservative (control-point convex-hull) mode and the +flattening-based tighter mode; expected tangent directions are likewise hand-computed via +`Vector2.Normalize` of the geometrically-expected direction, independent of the implementation. -Unit tests reside in `PathBuilderTests.cs` within the `DemaConsulting.CanvasNet.Tests.Geometry` -project namespace. +Unit tests reside in `PathBuilderTests.cs` and `PathCommandTests.cs` within the +`DemaConsulting.CanvasNet.Tests.Geometry` project namespace. ### Test Environment @@ -164,6 +167,31 @@ Calls `Path.Circle` with a negative `radius` and asserts the result equals `Path confirming the "non-positive radius returns an empty path" contract holds for negative values, not only for exactly zero. +#### CanvasNet-Geometry-PathCommand-PublicLineToFactory: Public LineTo Factory + +**Test**: `PathCommand_LineTo_GivenEndPoint_ConstructsLineToCommandWithThatEndPoint` + +Calls the public `PathCommand.LineTo` factory directly (not through `PathBuilder`) and asserts +the resulting command's `Type` is `LineTo` and its `EndPoint` matches the value supplied. + +#### CanvasNet-Geometry-PathCommand-ComputeTangents: Tangent Computation Per Command Type + +**Tests**: `PathCommand_ComputeTangents_LineTo_ReturnsSameNormalizedDirectionForBothTangents`, +`PathCommand_ComputeTangents_LineToWithCoincidentStartAndEnd_ReturnsNullTangents`, +`PathCommand_ComputeTangents_QuadraticBezierTo_PointsTowardThenAwayFromControlPoint`, +`PathCommand_ComputeTangents_QuadraticBezierToWithControlCoincidentWithStart_FallsBackToEndDirection`, +`PathCommand_ComputeTangents_CubicBezierTo_PointsTowardFirstThenAwayFromSecondControlPoint`, +`PathCommand_ComputeTangents_CubicBezierToWithBothControlPointsCoincidentWithEndpoints_FallsBackToEndDirection`, +`PathCommand_ComputeTangents_ArcTo_ReturnsNullTangents`, +`PathCommand_ComputeTangents_Close_ReturnsNullTangents` + +Exercises `ComputeTangents` for every command type: a `LineTo` yields the same normalized +direction for both tangents, or `null` for both when its start and end coincide; a +`QuadraticBezierTo`/`CubicBezierTo` yields tangents pointing toward/away from its control +point(s), falling back to the straight start-to-end direction when every control point +coincides with its nearest endpoint; an `ArcTo` and a `Close` both yield `(null, null)` +unconditionally. + ### Acceptance Criteria A unit test run passes when every scenario above passes without error or unexpected exception. diff --git a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Markers.cs b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Markers.cs index 19d438f03..cbfd8f854 100644 --- a/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Markers.cs +++ b/src/DemaConsulting.CanvasNet.Svg/SvgCodec.Markers.cs @@ -236,7 +236,7 @@ private static bool TryResolveUseTarget(XElement useElement, XElement target, Re /// Either tangent is at an open subpath's first (no incoming /// segment) or last (no outgoing segment) vertex, or when the adjacent segment itself /// degenerates to a zero-length direction (for example a repeated coordinate) - see - /// . + /// . /// private readonly struct MarkerVertex(Vector2 position, Vector2? incomingTangent, Vector2? outgoingTangent) { @@ -323,7 +323,7 @@ private static List BuildMarkerVertices(Path localPath) continue; } - var (outgoing, incoming) = ComputeCommandTangents(command, current); + var (outgoing, incoming) = command.ComputeTangents(current); // Fold this command's outgoing tangent into the vertex it starts from (the // previously-added vertex, whether that was the subpath's own Start or a prior @@ -342,76 +342,22 @@ private static List BuildMarkerVertices(Path localPath) var lastIndex = vertices.Count - 1; if (closed && lastIndex != subpathStartIndex) { - // Computed directly (rather than via ComputeCommandTangents with a constructed - // PathCommand) because PathCommand's factory methods are internal to the core - // package - this package and the core package are independently versioned NuGet - // packages, so relying on cross-package internal access is fragile. A LineTo's - // outgoing/incoming tangents are both simply the normalized direction of travel, - // which is exactly what is computed here for the implicit closing edge. - var closingDirection = NormalizeOrNull(subpath.Start - vertices[lastIndex].Position); - vertices[lastIndex] = vertices[lastIndex].WithOutgoingTangent(closingDirection); - vertices[subpathStartIndex] = vertices[subpathStartIndex].WithIncomingTangent(closingDirection); + // The implicit closing edge is not itself recorded as a PathCommand in + // subpath.Commands (a Close command carries no EndPoint of its own), so a + // standalone LineTo command representing it is synthesized here via + // PathCommand's own public LineTo factory, then handed to the same + // ComputeTangents this class uses for every other segment - rather than + // reimplementing tangent math independently in this package. + var (closingOutgoing, closingIncoming) = + PathCommand.LineTo(subpath.Start).ComputeTangents(vertices[lastIndex].Position); + vertices[lastIndex] = vertices[lastIndex].WithOutgoingTangent(closingOutgoing); + vertices[subpathStartIndex] = vertices[subpathStartIndex].WithIncomingTangent(closingIncoming); } } return vertices; } - /// - /// Computes one path command's outgoing (leaving its start point) and incoming (arriving - /// at its end point) unit tangent directions, per this class's documented per-command-type - /// rules. - /// - /// The command to inspect - a , , or . - /// The command's start point (the previous vertex's position). - /// - /// The outgoing/incoming unit tangents, or for either when the - /// relevant control points/endpoints are coincident (a zero-length direction has no - /// meaningful tangent). - /// - /// - /// is deliberately not one of this method's cases: - /// every one of this class's own shape builders (, - /// , and 's own arc handling) - /// converts an SVG arc to cubic Bezier segments immediately, via / - /// , before ever building a - - /// confirmed directly from this codec's own source, not merely assumed - so an - /// command never actually appears in a local-space - /// this method is called against. The default case below still - /// handles it (and , though that is filtered out by - /// before reaching here) defensively, returning "no - /// tangent" rather than throwing, so a future change elsewhere in this class that ever did - /// produce one would degrade to an un-oriented marker rather than an uncaught exception. - /// - private static (Vector2? Outgoing, Vector2? Incoming) ComputeCommandTangents(PathCommand command, Vector2 start) - { - switch (command.Type) - { - case PathCommandType.LineTo: - var lineDirection = NormalizeOrNull(command.EndPoint - start); - return (lineDirection, lineDirection); - - case PathCommandType.QuadraticBezierTo: - var outgoingQuad = NormalizeOrNull(command.Control1 - start) - ?? NormalizeOrNull(command.EndPoint - start); - var incomingQuad = NormalizeOrNull(command.EndPoint - command.Control1) - ?? NormalizeOrNull(command.EndPoint - start); - return (outgoingQuad, incomingQuad); - - case PathCommandType.CubicBezierTo: - var outgoingCubic = NormalizeOrNull(command.Control1 - start) - ?? NormalizeOrNull(command.Control2 - start) - ?? NormalizeOrNull(command.EndPoint - start); - var incomingCubic = NormalizeOrNull(command.EndPoint - command.Control2) - ?? NormalizeOrNull(command.EndPoint - command.Control1) - ?? NormalizeOrNull(command.EndPoint - start); - return (outgoingCubic, incomingCubic); - - default: - return (null, null); - } - } - /// Normalizes , tolerating a zero-length or non-finite result. /// The vector to normalize. /// diff --git a/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs b/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs index 90c31d44e..28316b4e0 100644 --- a/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs +++ b/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs @@ -11,10 +11,12 @@ namespace DemaConsulting.CanvasNet.Geometry; /// is expected to be walked in tight loops by a future /// rasterizer/stroker, and a single flat, non-nullable value type keeps that walk allocation- /// free with no virtual dispatch. Not every field is meaningful for every ; -/// see each field's own documentation for which command types populate it. Instances are -/// produced only by 's internal factory methods, so a +/// see each field's own documentation for which command types populate it. A /// list is guaranteed to only ever contain well-formed -/// commands. +/// commands, since every factory method other than is internal to this +/// package and used only by ; alone is public, +/// for an external consumer to synthesize a standalone straight-line command to pass to +/// (see its own documentation for why). /// public readonly struct PathCommand { @@ -101,12 +103,24 @@ private PathCommand( } /// - /// Creates a command. Used only by - /// . + /// Creates a command. /// /// The point the line segment draws to. /// The constructed command. - internal static PathCommand LineTo(Vector2 end) => + /// + /// Unlike this struct's other factory methods, is public rather than + /// internal: a straight line segment is the simplest possible , + /// and consumers outside this package legitimately need to synthesize one - for example, a + /// format codec computing a marker/arrowhead orientation for a closed subpath's implicit + /// closing edge (which is not itself recorded as its own - see + /// ) can build a command representing + /// that edge and pass it to , rather than reimplementing + /// tangent math of its own. , , + /// , and remain internal because only + /// - which alone knows how to keep a 's + /// accumulated state consistent for those richer command shapes - constructs them. + /// + public static PathCommand LineTo(Vector2 end) => new(PathCommandType.LineTo, end, default, default, default, 0f, false, false); /// @@ -157,4 +171,75 @@ internal static PathCommand ArcTo(Vector2 radius, float rotationDegrees, bool la /// The constructed command. internal static PathCommand Close() => new(PathCommandType.Close, default, default, default, default, 0f, false, false); + + /// + /// Computes this command's outgoing (leaving ) and incoming + /// (arriving at ) unit tangent directions. + /// + /// The command's start point (the previous vertex's position). + /// + /// The outgoing/incoming unit tangents, or for either when the + /// relevant control points/endpoints are coincident (a zero-length direction has no + /// meaningful tangent), for , + /// , and + /// . Returns (null, null) for + /// and - an arc's + /// tangent depends on its converted Bezier representation (see + /// ), which this method does not perform, and a + /// command carries no of its + /// own to compute a direction from at all. + /// + /// + /// This is the shared building block a marker/arrowhead-orientation feature (or any other + /// consumer needing a path segment's direction of travel) needs: a straight line's + /// outgoing and incoming tangents are both simply its normalized direction of travel; a + /// Bezier curve's outgoing tangent points toward its first non-coincident control point + /// (falling back to its end point when every control point coincides with + /// ), and its incoming tangent points away from its last + /// non-coincident control point (falling back to when every + /// control point coincides with ). + /// + public (Vector2? Outgoing, Vector2? Incoming) ComputeTangents(Vector2 start) + { + switch (Type) + { + case PathCommandType.LineTo: + var lineDirection = NormalizeOrNull(EndPoint - start); + return (lineDirection, lineDirection); + + case PathCommandType.QuadraticBezierTo: + var outgoingQuad = NormalizeOrNull(Control1 - start) + ?? NormalizeOrNull(EndPoint - start); + var incomingQuad = NormalizeOrNull(EndPoint - Control1) + ?? NormalizeOrNull(EndPoint - start); + return (outgoingQuad, incomingQuad); + + case PathCommandType.CubicBezierTo: + var outgoingCubic = NormalizeOrNull(Control1 - start) + ?? NormalizeOrNull(Control2 - start) + ?? NormalizeOrNull(EndPoint - start); + var incomingCubic = NormalizeOrNull(EndPoint - Control2) + ?? NormalizeOrNull(EndPoint - Control1) + ?? NormalizeOrNull(EndPoint - start); + return (outgoingCubic, incomingCubic); + + default: + return (null, null); + } + } + + /// Normalizes , tolerating a zero-length or non-finite result. + /// The vector to normalize. + /// + /// The unit-length direction, or if 's + /// length is zero, subnormal-to-zero, or non-finite (a degenerate direction has no + /// meaningful orientation to contribute). + /// + private static Vector2? NormalizeOrNull(Vector2 vector) + { + var lengthSquared = vector.LengthSquared(); + return float.IsFinite(lengthSquared) && lengthSquared > float.Epsilon + ? Vector2.Normalize(vector) + : null; + } } diff --git a/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs b/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs new file mode 100644 index 000000000..6abd09dc3 --- /dev/null +++ b/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs @@ -0,0 +1,194 @@ +using System.Numerics; +using DemaConsulting.CanvasNet.Geometry; + +namespace DemaConsulting.CanvasNet.Tests.Geometry; + +/// +/// Unit tests for the PathCommand type's public API: the LineTo factory method and the +/// ComputeTangents instance method. +/// +public class PathCommandTests +{ + /// + /// Proves that the public LineTo factory constructs a LineTo command carrying the given + /// end point, usable by a consumer outside this package that needs to synthesize a + /// standalone straight-line command (for example, an implicit closing edge that is not + /// itself recorded as its own PathCommand). + /// + [Fact] + public void PathCommand_LineTo_GivenEndPoint_ConstructsLineToCommandWithThatEndPoint() + { + // Arrange + var end = new Vector2(3, 4); + + // Act + var command = PathCommand.LineTo(end); + + // Assert + Assert.Equal(PathCommandType.LineTo, command.Type); + Assert.Equal(end, command.EndPoint); + } + + /// + /// Proves that a LineTo command's outgoing and incoming tangents are both the normalized + /// direction of travel from its start point to its end point. + /// + [Fact] + public void PathCommand_ComputeTangents_LineTo_ReturnsSameNormalizedDirectionForBothTangents() + { + // Arrange: a horizontal line segment from (0,0) to (5,0) + var command = PathCommand.LineTo(new Vector2(5, 0)); + + // Act + var (outgoing, incoming) = command.ComputeTangents(new Vector2(0, 0)); + + // Assert + Assert.Equal(new Vector2(1, 0), outgoing); + Assert.Equal(new Vector2(1, 0), incoming); + } + + /// + /// Proves that a LineTo command whose start and end points coincide has no meaningful + /// direction, returning null for both tangents rather than an undefined normalized + /// zero-length vector. + /// + [Fact] + public void PathCommand_ComputeTangents_LineToWithCoincidentStartAndEnd_ReturnsNullTangents() + { + // Arrange + var point = new Vector2(2, 2); + var command = PathCommand.LineTo(point); + + // Act + var (outgoing, incoming) = command.ComputeTangents(point); + + // Assert + Assert.Null(outgoing); + Assert.Null(incoming); + } + + /// + /// Proves that a QuadraticBezierTo command's outgoing tangent points toward its control + /// point, and its incoming tangent points away from that same control point toward its + /// end point. + /// + [Fact] + public void PathCommand_ComputeTangents_QuadraticBezierTo_PointsTowardThenAwayFromControlPoint() + { + // Arrange: a quadratic curve bowing upward from (0,0) to (4,0) via control (2,4) + var start = new Vector2(0, 0); + var control = new Vector2(2, 4); + var end = new Vector2(4, 0); + var command = PathCommand.QuadraticBezierTo(control, end); + + // Act + var (outgoing, incoming) = command.ComputeTangents(start); + + // Assert + Assert.Equal(Vector2.Normalize(control - start), outgoing); + Assert.Equal(Vector2.Normalize(end - control), incoming); + } + + /// + /// Proves that a QuadraticBezierTo command whose control point coincides with its start + /// point falls back to the straight start-to-end direction for its outgoing tangent, + /// rather than an undefined zero-length direction. + /// + [Fact] + public void PathCommand_ComputeTangents_QuadraticBezierToWithControlCoincidentWithStart_FallsBackToEndDirection() + { + // Arrange: control point equals start, so the curve is effectively a straight line + var start = new Vector2(0, 0); + var end = new Vector2(4, 0); + var command = PathCommand.QuadraticBezierTo(start, end); + + // Act + var (outgoing, incoming) = command.ComputeTangents(start); + + // Assert + Assert.Equal(Vector2.Normalize(end - start), outgoing); + Assert.Equal(Vector2.Normalize(end - start), incoming); + } + + /// + /// Proves that a CubicBezierTo command's outgoing tangent points toward its first control + /// point, and its incoming tangent points away from its second control point. + /// + [Fact] + public void PathCommand_ComputeTangents_CubicBezierTo_PointsTowardFirstThenAwayFromSecondControlPoint() + { + // Arrange: an S-shaped cubic curve from (0,0) to (6,0) + var start = new Vector2(0, 0); + var control1 = new Vector2(1, 3); + var control2 = new Vector2(5, -3); + var end = new Vector2(6, 0); + var command = PathCommand.CubicBezierTo(control1, control2, end); + + // Act + var (outgoing, incoming) = command.ComputeTangents(start); + + // Assert + Assert.Equal(Vector2.Normalize(control1 - start), outgoing); + Assert.Equal(Vector2.Normalize(end - control2), incoming); + } + + /// + /// Proves that a CubicBezierTo command whose control points both coincide with its start + /// and end points respectively falls back, in stages, to the straight start-to-end + /// direction for both tangents. + /// + [Fact] + public void PathCommand_ComputeTangents_CubicBezierToWithBothControlPointsCoincidentWithEndpoints_FallsBackToEndDirection() + { + // Arrange: both control points equal their nearest endpoint, so the curve is effectively + // a straight line + var start = new Vector2(0, 0); + var end = new Vector2(6, 0); + var command = PathCommand.CubicBezierTo(start, end, end); + + // Act + var (outgoing, incoming) = command.ComputeTangents(start); + + // Assert + Assert.Equal(Vector2.Normalize(end - start), outgoing); + Assert.Equal(Vector2.Normalize(end - start), incoming); + } + + /// + /// Proves that an ArcTo command returns null for both tangents: this method deliberately + /// does not compute an arc's tangent directly, since doing so correctly requires the same + /// Bezier conversion SvgArcConverter already performs, which this method does not + /// duplicate. + /// + [Fact] + public void PathCommand_ComputeTangents_ArcTo_ReturnsNullTangents() + { + // Arrange + var command = PathCommand.ArcTo(new Vector2(1, 1), 0, largeArc: false, sweep: false, new Vector2(2, 2)); + + // Act + var (outgoing, incoming) = command.ComputeTangents(new Vector2(0, 0)); + + // Assert + Assert.Null(outgoing); + Assert.Null(incoming); + } + + /// + /// Proves that a Close command returns null for both tangents: it carries no EndPoint of + /// its own to compute a direction from. + /// + [Fact] + public void PathCommand_ComputeTangents_Close_ReturnsNullTangents() + { + // Arrange + var command = PathCommand.Close(); + + // Act + var (outgoing, incoming) = command.ComputeTangents(new Vector2(0, 0)); + + // Assert + Assert.Null(outgoing); + Assert.Null(incoming); + } +} From d439e505f193aca625fa99c01c1d07a21c9d50ff Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 28 Sep 2026 21:36:54 -0400 Subject: [PATCH 05/10] Fix orphaned requirements from PathCommand public API addition The CI "Build Documents" job failed reqstream --enforce with 2 orphaned requirements: CanvasNet-Geometry-PathCommand-PublicLineToFactory and CanvasNet-Geometry-PathCommand-ComputeTangents. These leaf requirements were added to docs/reqstream/canvas-net/geometry/path.yaml but never linked into the System -> Unit -> leaf decomposition chain (reqstream requires exact-id children references at every tier, not prefix matching). Add both ids to the existing CanvasNet-Geometry-Path unit-level requirement's children list in docs/reqstream/canvas-net/geometry.yaml, and update its title/justification to describe the new public LineTo/ComputeTangents surface. Also updates the corresponding system-level CanvasNet-Lib-GeometryPath title/justification in docs/reqstream/canvas-net.yaml for consistency (children unchanged, since CanvasNet-Geometry-Path already covers the new leaves). Verified locally: dotnet reqstream --enforce no longer reports any orphaned requirements; build.ps1 and lint.ps1 both pass cleanly. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/reqstream/canvas-net.yaml | 10 ++++++++-- docs/reqstream/canvas-net/geometry.yaml | 12 ++++++++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/docs/reqstream/canvas-net.yaml b/docs/reqstream/canvas-net.yaml index e5e091242..fa1aa0b84 100644 --- a/docs/reqstream/canvas-net.yaml +++ b/docs/reqstream/canvas-net.yaml @@ -968,12 +968,18 @@ sections: The library shall provide an immutable vector path type, built via a mutable, fluent builder supporting move, line, quadratic and cubic Bezier, SVG-style elliptical arc, and close-subpath commands, and shall compute an axis-aligned bounding rectangle for a path - in either a conservative or a tighter, flattening-based mode. + in either a conservative or a tighter, flattening-based mode; individual path commands + shall also expose a public standalone-line-segment factory and tangent-direction + computation for use by external format-codec packages implementing marker/arrowhead + rendering. tags: [system] justification: | A vector path is the foundational shape-description primitive future drawing/rendering functionality in this library will consume; callers need to build one incrementally, - using a single reusable builder instance, and to reason about its extent. + using a single reusable builder instance, and to reason about its extent. Format-codec + packages built on top of Path (such as the SVG codec's marker rendering) additionally + need a shared, authoritative way to compute a path segment's direction of travel, + without duplicating that math themselves or depending on this package's internals. children: - CanvasNet-Geometry-Path tests: diff --git a/docs/reqstream/canvas-net/geometry.yaml b/docs/reqstream/canvas-net/geometry.yaml index e2aaa595d..47a213600 100644 --- a/docs/reqstream/canvas-net/geometry.yaml +++ b/docs/reqstream/canvas-net/geometry.yaml @@ -42,13 +42,19 @@ sections: mutable, fluent, allocation-conscious builder supporting move, line, quadratic and cubic Bezier, SVG-style elliptical arc, and close-subpath commands, and shall compute an axis-aligned bounding rectangle for a path in either a conservative - (control-point convex hull) or tighter (flattening-based) mode. + (control-point convex hull) or tighter (flattening-based) mode; individual path + commands shall also expose a public standalone-line-segment factory and a + tangent-direction computation for use by external format-codec packages + implementing marker/arrowhead rendering. justification: | A vector path (potentially several independent subpaths of mixed line, curve, and arc segments) is the foundational shape-description primitive future drawing/rendering functionality in this library will consume; callers need to build one incrementally and reuse a single builder instance across many paths without - per-path allocation overhead. + per-path allocation overhead. Format-codec packages built on top of Path (such as + the SVG codec's marker rendering) additionally need a shared, authoritative way to + compute a path segment's direction of travel, without duplicating that math + themselves or depending on this package's internals. children: - CanvasNet-Geometry-Path-BuildEveryCommandType - CanvasNet-Geometry-Path-ArcToStoresRawParameters @@ -70,6 +76,8 @@ sections: - CanvasNet-Geometry-Path-RoundRectangle - CanvasNet-Geometry-Path-Circle - CanvasNet-Geometry-PathBuilder-TangentArcTo + - CanvasNet-Geometry-PathCommand-PublicLineToFactory + - CanvasNet-Geometry-PathCommand-ComputeTangents tests: - PathBuilder_Build_EveryCommandType_RecordsCommandsInOrder - Path_GetBounds_ConservativeMode_CubicWithControlPointsOutsideChord_ReturnsControlPointConvexHull From 181f021e14542b89c97123715bcdd3dd1e39424f Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 28 Sep 2026 21:55:16 -0400 Subject: [PATCH 06/10] Fix second Copilot review pass findings on PR #30 - lint.ps1: fix macOS dotnet-format fallback regex to match the actual MSBuild-style ': error :' diagnostic text instead of a nonexistent 'failed to verify formatting' phrase - PathCommand.NormalizeOrNull: compute squared length in double precision to avoid spurious float-squaring overflow for large-but- finite vectors (~1.8e19+ magnitude), which previously caused valid directions to be misreported as degenerate; add a covering unit test - SvgSystemIntegrationTests: strengthen the SvgFilterRendering system test to assert a halo pixel outside the source rect (matching the unit-level assertion), proving the filter chain actually ran - docs/reqstream/canvas-net-svg.yaml: reword the SvgFilterRendering parent requirement to reflect the true split behavior - oversized filter regions/blur radii are tolerated (skipped/clamped) while excessive convolution-order/morphology-radius/turbulence-octave parameters are rejected with InvalidDataException, matching the FilterPrimitiveResourceSafety child requirement and its tests - docs/reqstream/canvas-net-svg.yaml and docs/reqstream/canvas-net-svg/svg-codec.yaml: replace out-of-scope construct examples that contradicted this same file's own supported- feature requirements (filters, masks, style, clipPath, pattern, image) with the actual unsupported constructs per the design doc (nested svg, SMIL animation elements, foreignObject) - SvgSystemIntegrationTests.cs: fix a duplicated '///' XML-doc marker embedded in a summary comment's text - cspell: add SMIL to canvas-net-svg.yaml's ignore list - docs/reqstream/canvas-net.yaml: CanvasNet-Lib-GeometryPath's title promises the public PathCommand.LineTo factory and ComputeTangents behavior, but its only linked system test never exercised either API; add CanvasNet_SystemIntegration_LineToAndComputeTangents_ ReturnsNormalizedDirection to test/DemaConsulting.CanvasNet.Tests/ CanvasNetTests.cs exercising both through the public API, and link it on the requirement alongside the existing test --- docs/reqstream/canvas-net-svg.yaml | 13 +++++---- docs/reqstream/canvas-net-svg/svg-codec.yaml | 5 ++-- docs/reqstream/canvas-net.yaml | 1 + lint.ps1 | 11 +++++--- .../Geometry/PathCommand.cs | 27 ++++++++++++++++--- .../SvgSystemIntegrationTests.cs | 8 +++++- .../CanvasNetTests.cs | 25 +++++++++++++++++ .../Geometry/PathCommandTests.cs | 24 +++++++++++++++++ 8 files changed, 97 insertions(+), 17 deletions(-) diff --git a/docs/reqstream/canvas-net-svg.yaml b/docs/reqstream/canvas-net-svg.yaml index 1b2945aac..20aade4dc 100644 --- a/docs/reqstream/canvas-net-svg.yaml +++ b/docs/reqstream/canvas-net-svg.yaml @@ -10,7 +10,7 @@ # pixel buffer, Geometry path/flattening primitives, Drawing rasterization, and Fonts glyph # outlines - see docs/design/canvas-net-svg.md's Dependencies section for details. # -# cspell:ignore rasterizing letterboxing renderable Dasharray xlink Pillarboxes +# cspell:ignore rasterizing letterboxing renderable Dasharray xlink Pillarboxes SMIL sections: - title: SVG Codec API @@ -83,8 +83,10 @@ sections: feDropShadow/feImage/feDiffuseLighting/feSpecularLighting/feTurbulence/feBlend primitive chain against that element's own content within a bounded-size temporary offscreen surface, and shall tolerate a dangling filter reference, a genuinely - unrecognized primitive type, and pathological filter-region, convolution-order, - morphology-radius, or turbulence-octave inputs without failing or hanging. + unrecognized primitive type, and a pathological filter-region or blur-radius input + by skipping or clamping rather than failing, while rejecting an excessive + convolution-order, morphology-radius, or turbulence-octave parameter with + InvalidDataException rather than performing unbounded per-pixel work. tags: [system] justification: | Real-world SVG documents use much more than the initial flood/blur/offset/composite @@ -447,8 +449,9 @@ sections: tags: [system] justification: | Real-world SVG documents commonly include constructs outside this codec's supported - subset (such as filters or masks); rejecting the entire document because of one such - element would be needlessly strict when the rest of the document is renderable. + subset (such as a nested svg element, SMIL animation elements, or foreignObject); + rejecting the entire document because of one such element would be needlessly strict + when the rest of the document is renderable. children: - CanvasNetSvg-SvgCodec-UnsupportedConstructsIgnored tests: diff --git a/docs/reqstream/canvas-net-svg/svg-codec.yaml b/docs/reqstream/canvas-net-svg/svg-codec.yaml index 1a0e0b3df..1f79fae60 100644 --- a/docs/reqstream/canvas-net-svg/svg-codec.yaml +++ b/docs/reqstream/canvas-net-svg/svg-codec.yaml @@ -565,9 +565,8 @@ sections: - id: CanvasNetSvg-SvgCodec-UnsupportedConstructsIgnored title: >- The SvgCodec class shall silently skip well-formed but out-of-scope elements - (including style, mask, clipPath, pattern, a nested svg, - animate/SMIL, image, and foreignObject), continuing to render the rest of the - document. + (including a nested svg, animate/other SMIL animation elements, and + foreignObject), continuing to render the rest of the document. justification: | Real-world SVG documents commonly include constructs outside this codec's supported subset; rejecting the entire document because of one such element diff --git a/docs/reqstream/canvas-net.yaml b/docs/reqstream/canvas-net.yaml index fa1aa0b84..46ee289b5 100644 --- a/docs/reqstream/canvas-net.yaml +++ b/docs/reqstream/canvas-net.yaml @@ -984,6 +984,7 @@ sections: - CanvasNet-Geometry-Path tests: - CanvasNet_SystemIntegration_BuildFlattenAndBoundPath_ReturnsExpectedBounds + - CanvasNet_SystemIntegration_LineToAndComputeTangents_ReturnsNormalizedDirection - id: CanvasNet-Lib-GeometryBezierFlattening title: >- diff --git a/lint.ps1 b/lint.ps1 index 876b9f871..5573c7699 100644 --- a/lint.ps1 +++ b/lint.ps1 @@ -145,12 +145,15 @@ if (-not $skipDotnetFormat) { # moves, or any other change that git's stash/pop cannot losslessly # round-trip. Instead, run in dry-run mode and treat BOTH the exit code # AND the tool's own diagnostic text as signals - `--verify-no-changes` - # always prints a "failed to verify formatting" line per affected file - # regardless of which platform's exit-code bug is in play, so the text - # check is a reliable fallback. This never mutates the working tree. + # always emits MSBuild-style diagnostic lines (e.g. + # "File.cs(1,17): error WHITESPACE: Fix whitespace formatting. ...") for + # each affected file regardless of which platform's exit-code bug is in + # play, so matching the generic "`: error :`" pattern (not any one + # hardcoded rule code) is a reliable fallback. This never mutates the + # working tree. $formatOutput = dotnet format --verify-no-changes --no-restore 2>&1 $formatOutput | ForEach-Object { Write-Host $_ } - if ($LASTEXITCODE -ne 0 -or ($formatOutput -join "`n") -match 'failed to verify formatting') { + if ($LASTEXITCODE -ne 0 -or ($formatOutput -join "`n") -match ': error [A-Z0-9]+:') { $lintError = $true Write-Host "dotnet format found formatting issues; run fix.ps1 locally and commit the results." } diff --git a/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs b/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs index 28316b4e0..e0d9e9ec7 100644 --- a/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs +++ b/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs @@ -235,11 +235,30 @@ internal static PathCommand Close() => /// length is zero, subnormal-to-zero, or non-finite (a degenerate direction has no /// meaningful orientation to contribute). /// + /// + /// The squared length is accumulated in rather than + /// precision because Vector2.LengthSquared() squares both + /// components in arithmetic, which spuriously overflows to + /// for finite coordinates whose magnitude exceeds + /// roughly 1.8e19 - well before the coordinates themselves overflow. Using + /// for the length calculation avoids that false-positive + /// degeneracy while still correctly reporting a genuinely zero-length or non-finite input. + /// private static Vector2? NormalizeOrNull(Vector2 vector) { - var lengthSquared = vector.LengthSquared(); - return float.IsFinite(lengthSquared) && lengthSquared > float.Epsilon - ? Vector2.Normalize(vector) - : null; + // Accumulate the squared length in double precision to avoid the float-squaring + // overflow that would otherwise misclassify large-but-finite vectors as degenerate + double x = vector.X; + double y = vector.Y; + var lengthSquared = (x * x) + (y * y); + if (!double.IsFinite(lengthSquared) || lengthSquared <= float.Epsilon) + { + return null; + } + + // Divide by the double-precision length (cast back to float) so the resulting + // direction remains a valid unit vector even for very large input magnitudes + var length = (float)Math.Sqrt(lengthSquared); + return new Vector2(vector.X / length, vector.Y / length); } } diff --git a/test/DemaConsulting.CanvasNet.Svg.Tests/SvgSystemIntegrationTests.cs b/test/DemaConsulting.CanvasNet.Svg.Tests/SvgSystemIntegrationTests.cs index 0e0fc4287..13306a892 100644 --- a/test/DemaConsulting.CanvasNet.Svg.Tests/SvgSystemIntegrationTests.cs +++ b/test/DemaConsulting.CanvasNet.Svg.Tests/SvgSystemIntegrationTests.cs @@ -211,6 +211,11 @@ public void CanvasNetSvg_SystemIntegration_SvgFilterRendering_AppliesFilterChain // Assert: the rect's own fill remains fully opaque and unaffected at its center Assert.Equal(new Rgba32(0, 128, 0, 255), surface[50, 50]); + + // Assert: just outside the rect's own edge (which a fill-only render would leave fully + // transparent), a softened orange halo pixel is visible - proving the filter chain + // actually ran end-to-end through the public API rather than being silently ignored + Assert.Equal(new Rgba32(255, 161, 0, 19), surface[61, 50]); } /// @@ -461,7 +466,8 @@ public void CanvasNetSvg_SystemIntegration_SvgValidationEmptyPath_EmptyPathThrow Assert.Throws(() => SvgCodec.Load(string.Empty, 10, 10)); } - /// /// Proves that the system rejects malformed (non-well-formed) SVG XML with + /// + /// Proves that the system rejects malformed (non-well-formed) SVG XML with /// through the public API. See SvgCodecTests for /// the full unit test coverage of the other malformed-input variants (viewBox, transform, /// path data). diff --git a/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs b/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs index 24f72527c..cce477e74 100644 --- a/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/CanvasNetTests.cs @@ -546,6 +546,31 @@ public void CanvasNet_SystemIntegration_BuildFlattenAndBoundPath_ReturnsExpected Assert.True(bounds.Height > 0); } + /// + /// Proves that the system can synthesize a standalone line-segment command via the public + /// factory and compute a sane tangent direction from it + /// via , through the public API - the shared + /// building block an external format-codec package (such as the SVG codec's marker/ + /// arrowhead rendering) needs to orient a decoration at a path segment's end, without + /// depending on this package's internal Path/PathBuilder construction. + /// + [Fact] + public void CanvasNet_SystemIntegration_LineToAndComputeTangents_ReturnsNormalizedDirection() + { + // Arrange: a standalone horizontal line segment from (0,0) to (10,0), synthesized + // directly via the public LineTo factory rather than via PathBuilder + var command = PathCommand.LineTo(new Vector2(10, 0)); + + // Act: compute the command's outgoing/incoming tangents from its start point + var (outgoing, incoming) = command.ComputeTangents(new Vector2(0, 0)); + + // Assert: both tangents are the same sane, unit-length direction of travel + Assert.NotNull(outgoing); + Assert.NotNull(incoming); + Assert.Equal(new Vector2(1, 0), outgoing); + Assert.Equal(new Vector2(1, 0), incoming); + } + /// /// Proves that the system silently no-ops, through PathFiller's public API, when filling /// an empty Path or a Path whose bounds do not intersect the target Surface - in both diff --git a/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs b/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs index 6abd09dc3..12051b364 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs @@ -67,6 +67,30 @@ public void PathCommand_ComputeTangents_LineToWithCoincidentStartAndEnd_ReturnsN Assert.Null(incoming); } + /// + /// Proves that a LineTo command with very large but finite coordinates (magnitudes around + /// 1e20 to 1e25) still returns a valid unit tangent rather than null. Squaring such large + /// components in float precision overflows to positive infinity well before the + /// coordinates themselves overflow, which previously caused NormalizeOrNull to + /// misclassify a perfectly valid direction as degenerate. + /// + [Fact] + public void PathCommand_ComputeTangents_LineToWithLargeFiniteCoordinates_ReturnsValidNormalizedDirection() + { + // Arrange: a horizontal line segment whose end point has a huge but finite X coordinate + var start = new Vector2(1e20f, 0f); + var command = PathCommand.LineTo(new Vector2(1e25f, 0f)); + + // Act + var (outgoing, incoming) = command.ComputeTangents(start); + + // Assert: the direction is purely along +X, so both tangents are the unit X vector + Assert.NotNull(outgoing); + Assert.NotNull(incoming); + Assert.Equal(new Vector2(1, 0), outgoing); + Assert.Equal(new Vector2(1, 0), incoming); + } + /// /// Proves that a QuadraticBezierTo command's outgoing tangent points toward its control /// point, and its incoming tangent points away from that same control point toward its From 9e182e4abbea9b3d187c46f7ab4597ac674067cc Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 28 Sep 2026 22:24:08 -0400 Subject: [PATCH 07/10] fix: widen PathCommand tangent delta computation to double before subtraction NormalizeOrNull previously accepted a pre-subtracted Vector2, so the point-to-point delta (e.g. EndPoint - start) still overflowed in float for finite-but-extreme coordinates (near +/-float.MaxValue) before any double-precision widening could help. NormalizeOrNull now accepts the two endpoints directly and computes the delta in double, fixing ComputeTangents for such inputs. Also replaced exact-float-equality assertions in PathCommandTests with a tolerance-based AssertDirectionApproximatelyEqual helper, since the production code's double-widened computation and the tests' pure-float Vector2.Normalize(...) reference values can legitimately differ by a single ULP. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/reqstream/canvas-net/geometry/path.yaml | 2 + .../Geometry/PathCommand.cs | 70 ++++++++++--------- .../Geometry/PathCommandTests.cs | 60 +++++++++++++--- 3 files changed, 92 insertions(+), 40 deletions(-) diff --git a/docs/reqstream/canvas-net/geometry/path.yaml b/docs/reqstream/canvas-net/geometry/path.yaml index f565ca3ac..97094cfa7 100644 --- a/docs/reqstream/canvas-net/geometry/path.yaml +++ b/docs/reqstream/canvas-net/geometry/path.yaml @@ -313,6 +313,8 @@ sections: tests: - PathCommand_ComputeTangents_LineTo_ReturnsSameNormalizedDirectionForBothTangents - PathCommand_ComputeTangents_LineToWithCoincidentStartAndEnd_ReturnsNullTangents + - PathCommand_ComputeTangents_LineToWithLargeFiniteCoordinates_ReturnsValidNormalizedDirection + - PathCommand_ComputeTangents_LineToWithFarApartNearMaxFiniteCoordinates_ReturnsValidNormalizedDirection - PathCommand_ComputeTangents_QuadraticBezierTo_PointsTowardThenAwayFromControlPoint - PathCommand_ComputeTangents_QuadraticBezierToWithControlCoincidentWithStart_FallsBackToEndDirection - PathCommand_ComputeTangents_CubicBezierTo_PointsTowardFirstThenAwayFromSecondControlPoint diff --git a/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs b/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs index e0d9e9ec7..f23bcacaa 100644 --- a/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs +++ b/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs @@ -204,23 +204,23 @@ internal static PathCommand Close() => switch (Type) { case PathCommandType.LineTo: - var lineDirection = NormalizeOrNull(EndPoint - start); + var lineDirection = NormalizeOrNull(start, EndPoint); return (lineDirection, lineDirection); case PathCommandType.QuadraticBezierTo: - var outgoingQuad = NormalizeOrNull(Control1 - start) - ?? NormalizeOrNull(EndPoint - start); - var incomingQuad = NormalizeOrNull(EndPoint - Control1) - ?? NormalizeOrNull(EndPoint - start); + var outgoingQuad = NormalizeOrNull(start, Control1) + ?? NormalizeOrNull(start, EndPoint); + var incomingQuad = NormalizeOrNull(Control1, EndPoint) + ?? NormalizeOrNull(start, EndPoint); return (outgoingQuad, incomingQuad); case PathCommandType.CubicBezierTo: - var outgoingCubic = NormalizeOrNull(Control1 - start) - ?? NormalizeOrNull(Control2 - start) - ?? NormalizeOrNull(EndPoint - start); - var incomingCubic = NormalizeOrNull(EndPoint - Control2) - ?? NormalizeOrNull(EndPoint - Control1) - ?? NormalizeOrNull(EndPoint - start); + var outgoingCubic = NormalizeOrNull(start, Control1) + ?? NormalizeOrNull(start, Control2) + ?? NormalizeOrNull(start, EndPoint); + var incomingCubic = NormalizeOrNull(Control2, EndPoint) + ?? NormalizeOrNull(Control1, EndPoint) + ?? NormalizeOrNull(start, EndPoint); return (outgoingCubic, incomingCubic); default: @@ -228,37 +228,43 @@ internal static PathCommand Close() => } } - /// Normalizes , tolerating a zero-length or non-finite result. - /// The vector to normalize. + /// + /// Computes the normalized direction from to , + /// tolerating a zero-length or non-finite result. + /// + /// The direction's start point. + /// The direction's end point. /// - /// The unit-length direction, or if 's - /// length is zero, subnormal-to-zero, or non-finite (a degenerate direction has no + /// The unit-length direction, or if the two points coincide, or + /// the direction is subnormal-to-zero or non-finite (a degenerate direction has no /// meaningful orientation to contribute). /// /// - /// The squared length is accumulated in rather than - /// precision because Vector2.LengthSquared() squares both - /// components in arithmetic, which spuriously overflows to - /// for finite coordinates whose magnitude exceeds - /// roughly 1.8e19 - well before the coordinates themselves overflow. Using - /// for the length calculation avoids that false-positive - /// degeneracy while still correctly reporting a genuinely zero-length or non-finite input. + /// Every step of this computation - the point-to-point delta and its squared length - + /// is performed in rather than + /// precision. Computing the delta as a subtraction first would + /// itself overflow to for finite points as close + /// together (in magnitude terms) as (-float.MaxValue, 0) and + /// (float.MaxValue, 0), before the squared-length widening in a prior revision of + /// this method ever got a chance to help; widening at the point-to-point delta itself, + /// rather than only at the squared-length step, avoids that false-positive degeneracy + /// while still correctly reporting a genuinely zero-length or non-finite direction. /// - private static Vector2? NormalizeOrNull(Vector2 vector) + private static Vector2? NormalizeOrNull(Vector2 from, Vector2 to) { - // Accumulate the squared length in double precision to avoid the float-squaring - // overflow that would otherwise misclassify large-but-finite vectors as degenerate - double x = vector.X; - double y = vector.Y; - var lengthSquared = (x * x) + (y * y); + // Compute the delta itself in double precision so that neither the subtraction nor the + // squared-length step can spuriously overflow for finite, far-apart points + double dx = (double)to.X - from.X; + double dy = (double)to.Y - from.Y; + var lengthSquared = (dx * dx) + (dy * dy); if (!double.IsFinite(lengthSquared) || lengthSquared <= float.Epsilon) { return null; } - // Divide by the double-precision length (cast back to float) so the resulting - // direction remains a valid unit vector even for very large input magnitudes - var length = (float)Math.Sqrt(lengthSquared); - return new Vector2(vector.X / length, vector.Y / length); + // Divide by the double-precision length so the resulting direction remains a valid unit + // vector even for very large or far-apart input magnitudes + var length = Math.Sqrt(lengthSquared); + return new Vector2((float)(dx / length), (float)(dy / length)); } } diff --git a/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs b/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs index 12051b364..16a59c3c4 100644 --- a/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs +++ b/test/DemaConsulting.CanvasNet.Tests/Geometry/PathCommandTests.cs @@ -9,6 +9,25 @@ namespace DemaConsulting.CanvasNet.Tests.Geometry; /// public class PathCommandTests { + /// + /// Asserts that two unit-direction vectors are equal within a small tolerance, rather + /// than requiring bit-exact equality. computes + /// its result via an intermediate pipeline (to avoid the + /// float-precision overflow covered by other tests in this class), which can legitimately + /// differ from a purely -precision reference computation (such as + /// ) in the last representable bit, without either + /// result being wrong. + /// + /// The expected unit direction, computed via a reference method. + /// The actual unit direction returned by the method under test. + private static void AssertDirectionApproximatelyEqual(Vector2 expected, Vector2? actual) + { + Assert.NotNull(actual); + Assert.True( + Vector2.Distance(expected, actual.Value) < 1e-6f, + $"Expected direction approximately {expected} but was {actual.Value}."); + } + /// /// Proves that the public LineTo factory constructs a LineTo command carrying the given /// end point, usable by a consumer outside this package that needs to synthesize a @@ -91,6 +110,31 @@ public void PathCommand_ComputeTangents_LineToWithLargeFiniteCoordinates_Returns Assert.Equal(new Vector2(1, 0), incoming); } + /// + /// Proves that a LineTo command still returns a valid unit tangent when its start and end + /// points are individually finite but so far apart (near opposite ends of the float + /// range) that computing their delta as a float Vector2 subtraction would itself overflow + /// to positive/negative infinity, before any widening of the squared-length step ever gets + /// a chance to help. The delta itself must be computed in double precision. + /// + [Fact] + public void PathCommand_ComputeTangents_LineToWithFarApartNearMaxFiniteCoordinates_ReturnsValidNormalizedDirection() + { + // Arrange: a horizontal line segment whose endpoints are each individually finite, but + // whose float-precision delta (EndPoint - start) would overflow to infinity + var start = new Vector2(-float.MaxValue, 0f); + var command = PathCommand.LineTo(new Vector2(float.MaxValue, 0f)); + + // Act + var (outgoing, incoming) = command.ComputeTangents(start); + + // Assert: the direction is unambiguously +X, so both tangents are the unit X vector + Assert.NotNull(outgoing); + Assert.NotNull(incoming); + Assert.Equal(new Vector2(1, 0), outgoing); + Assert.Equal(new Vector2(1, 0), incoming); + } + /// /// Proves that a QuadraticBezierTo command's outgoing tangent points toward its control /// point, and its incoming tangent points away from that same control point toward its @@ -109,8 +153,8 @@ public void PathCommand_ComputeTangents_QuadraticBezierTo_PointsTowardThenAwayFr var (outgoing, incoming) = command.ComputeTangents(start); // Assert - Assert.Equal(Vector2.Normalize(control - start), outgoing); - Assert.Equal(Vector2.Normalize(end - control), incoming); + AssertDirectionApproximatelyEqual(Vector2.Normalize(control - start), outgoing); + AssertDirectionApproximatelyEqual(Vector2.Normalize(end - control), incoming); } /// @@ -130,8 +174,8 @@ public void PathCommand_ComputeTangents_QuadraticBezierToWithControlCoincidentWi var (outgoing, incoming) = command.ComputeTangents(start); // Assert - Assert.Equal(Vector2.Normalize(end - start), outgoing); - Assert.Equal(Vector2.Normalize(end - start), incoming); + AssertDirectionApproximatelyEqual(Vector2.Normalize(end - start), outgoing); + AssertDirectionApproximatelyEqual(Vector2.Normalize(end - start), incoming); } /// @@ -152,8 +196,8 @@ public void PathCommand_ComputeTangents_CubicBezierTo_PointsTowardFirstThenAwayF var (outgoing, incoming) = command.ComputeTangents(start); // Assert - Assert.Equal(Vector2.Normalize(control1 - start), outgoing); - Assert.Equal(Vector2.Normalize(end - control2), incoming); + AssertDirectionApproximatelyEqual(Vector2.Normalize(control1 - start), outgoing); + AssertDirectionApproximatelyEqual(Vector2.Normalize(end - control2), incoming); } /// @@ -174,8 +218,8 @@ public void PathCommand_ComputeTangents_CubicBezierToWithBothControlPointsCoinci var (outgoing, incoming) = command.ComputeTangents(start); // Assert - Assert.Equal(Vector2.Normalize(end - start), outgoing); - Assert.Equal(Vector2.Normalize(end - start), incoming); + AssertDirectionApproximatelyEqual(Vector2.Normalize(end - start), outgoing); + AssertDirectionApproximatelyEqual(Vector2.Normalize(end - start), incoming); } /// From 798ea84a4d611a79c19b0851ab3e67c00028a9c5 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 28 Sep 2026 22:37:21 -0400 Subject: [PATCH 08/10] fix: reject only zero-length tangent deltas and model SVG's subsystem uses as dependencies - NormalizeOrNull was comparing the double-precision squared length against float.Epsilon, which rejected valid tiny-but-distinct segments (e.g. length ~1e-30) even though the public contract promises a unit tangent for every nonzero finite direction. Now rejects only an exactly zero squared length. - Added the two large-coordinate ComputeTangents tests to the CanvasNet-Geometry-PathCommand-ComputeTangents verification scenario, which previously omitted them despite listing them as evidence. - Modeled CanvasNetSvgSystem's use of the core CanvasNet system's Canvas/Geometry/Drawing/Fonts subsystems as non-owning dependency relationships instead of ordinary part usages, since the latter incorrectly modeled them as additional owned children of CanvasNetSvgSystem (duplicating core subsystems in architecture queries/diagrams) rather than as a dependency on the sibling system. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/sysml2/model/canvas-net-svg.sysml | 10 +++++----- docs/verification/canvas-net/geometry/path.md | 12 +++++++----- src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs | 2 +- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/docs/sysml2/model/canvas-net-svg.sysml b/docs/sysml2/model/canvas-net-svg.sysml index cb44e8334..0b2034560 100644 --- a/docs/sysml2/model/canvas-net-svg.sysml +++ b/docs/sysml2/model/canvas-net-svg.sysml @@ -6,13 +6,13 @@ package CanvasNet { comment designRef /* Design: docs/design/canvas-net-svg.md */ comment verificationRef /* Verification: docs/verification/canvas-net-svg.md */ comment reqRef /* Requirements: docs/reqstream/canvas-net-svg.yaml */ - comment /* CanvasNetSvg depends on the sibling CanvasNet system's Canvas subsystem (for the Surface pixel buffer SvgCodec rasterizes into), Geometry subsystem (for Path/Rect/BezierFlattening/SvgArcConverter), Drawing subsystem (for PathFiller/PathStroker/GradientPaint rasterization), and Fonts subsystem (for TrueTypeFont glyph-outline text rendering) - modeled below as ordinary part usages of those existing subsystem part defs, since both systems live in this same git repository (though each is distributed as its own separate NuGet package - CanvasNetSvg is not folded into the CanvasNet package) rather than being third-party (OTS) or Shared Package dependencies (both of which are reserved for a package produced by a different repository). */ + comment /* CanvasNetSvg depends on the sibling CanvasNet system's Canvas subsystem (for the Surface pixel buffer SvgCodec rasterizes into), Geometry subsystem (for Path/Rect/BezierFlattening/SvgArcConverter), Drawing subsystem (for PathFiller/PathStroker/GradientPaint rasterization), and Fonts subsystem (for TrueTypeFont glyph-outline text rendering) - modeled below as non-owning `dependency` relationships to those existing subsystem part defs (not ordinary `part` usages, which would incorrectly model them as owned children of CanvasNetSvgSystem), since both systems live in this same git repository (though each is distributed as its own separate NuGet package - CanvasNetSvg is not folded into the CanvasNet package) rather than being third-party (OTS) or Shared Package dependencies (both of which are reserved for a package produced by a different repository). */ part svgCodec : SvgCodec; - part usesCanvas : Canvas; - part usesGeometry : Geometry; - part usesDrawing : Drawing; - part usesFonts : Fonts; + dependency usesCanvas from CanvasNetSvgSystem to Canvas; + dependency usesGeometry from CanvasNetSvgSystem to Geometry; + dependency usesDrawing from CanvasNetSvgSystem to Drawing; + dependency usesFonts from CanvasNetSvgSystem to Fonts; } } diff --git a/docs/verification/canvas-net/geometry/path.md b/docs/verification/canvas-net/geometry/path.md index 96e10f62b..4f7ab96bc 100644 --- a/docs/verification/canvas-net/geometry/path.md +++ b/docs/verification/canvas-net/geometry/path.md @@ -178,6 +178,7 @@ the resulting command's `Type` is `LineTo` and its `EndPoint` matches the value **Tests**: `PathCommand_ComputeTangents_LineTo_ReturnsSameNormalizedDirectionForBothTangents`, `PathCommand_ComputeTangents_LineToWithCoincidentStartAndEnd_ReturnsNullTangents`, +`PathCommand_ComputeTangents_LineToWithFarApartNearMaxFiniteCoordinates_ReturnsValidNormalizedDirection`, `PathCommand_ComputeTangents_QuadraticBezierTo_PointsTowardThenAwayFromControlPoint`, `PathCommand_ComputeTangents_QuadraticBezierToWithControlCoincidentWithStart_FallsBackToEndDirection`, `PathCommand_ComputeTangents_CubicBezierTo_PointsTowardFirstThenAwayFromSecondControlPoint`, @@ -186,11 +187,12 @@ the resulting command's `Type` is `LineTo` and its `EndPoint` matches the value `PathCommand_ComputeTangents_Close_ReturnsNullTangents` Exercises `ComputeTangents` for every command type: a `LineTo` yields the same normalized -direction for both tangents, or `null` for both when its start and end coincide; a -`QuadraticBezierTo`/`CubicBezierTo` yields tangents pointing toward/away from its control -point(s), falling back to the straight start-to-end direction when every control point -coincides with its nearest endpoint; an `ArcTo` and a `Close` both yield `(null, null)` -unconditionally. +direction for both tangents, or `null` for both when its start and end coincide, or a valid +normalized direction even when its start and end coordinates are near opposite ends of the +finite `float` range; a `QuadraticBezierTo`/`CubicBezierTo` yields tangents pointing +toward/away from its control point(s), falling back to the straight start-to-end direction +when every control point coincides with its nearest endpoint; an `ArcTo` and a `Close` both +yield `(null, null)` unconditionally. ### Acceptance Criteria diff --git a/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs b/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs index f23bcacaa..614c7a723 100644 --- a/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs +++ b/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs @@ -257,7 +257,7 @@ internal static PathCommand Close() => double dx = (double)to.X - from.X; double dy = (double)to.Y - from.Y; var lengthSquared = (dx * dx) + (dy * dy); - if (!double.IsFinite(lengthSquared) || lengthSquared <= float.Epsilon) + if (!double.IsFinite(lengthSquared) || lengthSquared <= 0) { return null; } From 943a7f296322aed8e473446593a44940e448da55 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 28 Sep 2026 22:49:36 -0400 Subject: [PATCH 09/10] docs: fix stale design contracts and add missing Codecs dependency - Documented Surface's full valid width/height range (non-positive AND exceeding Surface.MaxDimension (8192) both throw ArgumentOutOfRangeException) in canvas-net-svg.md's API description, interface constraints table, and data-flow validation step. - Updated the Geometry Path unit's caller description to name the in-repository Drawing.PathFiller/PathStroker callers instead of claiming no rasterizer exists, while retaining the external SVG marker caller. - Added the missing Codecs subsystem dependency to the CanvasNetSvgSystem sysml2 model (SvgCodec.GetInfo returns the shared Codecs.ImageInfo record struct). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/canvas-net-svg.md | 10 +++++----- docs/design/canvas-net/geometry/path.md | 7 ++++--- docs/sysml2/model/canvas-net-svg.sysml | 5 +++-- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/docs/design/canvas-net-svg.md b/docs/design/canvas-net-svg.md index cdc530c91..f46167a82 100644 --- a/docs/design/canvas-net-svg.md +++ b/docs/design/canvas-net-svg.md @@ -48,7 +48,7 @@ class: `ArgumentNullException` for a null `stream`/`path`, `ArgumentException` for an empty/whitespace `path`, `InvalidDataException` for malformed or unsupported SVG data, and `ArgumentOutOfRangeException` (propagated, unwrapped, from `Surface`'s own constructor) for a - non-positive `width`/`height`. + non-positive `width`/`height` or a `width`/`height` exceeding `Surface.MaxDimension` (8192). - **SvgCodec.LoadWithFontFaces(Stream stream, int width, int height, fontFaces)** / **SvgCodec.LoadWithFontFaces(string path, int width, int height, fontFaces)**: The richer loading entry point, accepting more than one registered `SvgFontFace` (weight/style variant) @@ -65,8 +65,8 @@ class: | Interface | Direction | Format | Constraints | | -------------------------------------- | ---------------- | ------------------------------ | ------------------------------- | -| `SvgCodec.Load(...)` | Inbound/Outbound | Method call / `Surface` return | Valid SVG stream or path; `width`/`height` > 0 | -| `SvgCodec.LoadWithFontFaces(...)` | Inbound/Outbound | Method call / `Surface` return | Valid SVG stream or path; `width`/`height` > 0 | +| `SvgCodec.Load(...)` | Inbound/Outbound | Method call / `Surface` return | Valid SVG stream or path; `0 < width, height <= 8192` | +| `SvgCodec.LoadWithFontFaces(...)` | Inbound/Outbound | Method call / `Surface` return | Valid SVG stream or path; `0 < width, height <= 8192` | | `SvgCodec.GetInfo(...)` | Inbound/Outbound | Method call / `ImageInfo` return | Valid SVG stream or path | @@ -140,8 +140,8 @@ so this risk control is inherently contained within it (IEC 62304 Β§5.3.3). `ArgumentNullException`, an empty/whitespace `path` with `ArgumentException`, and malformed or resource-disproportionate SVG data (non-well-formed XML, a DOCTYPE declaration, a malformed `viewBox`/`transform`/path `d` attribute, or a budget exceeded) with `InvalidDataException`; - a non-positive `width`/`height` propagates, unwrapped, as `Surface`'s own - `ArgumentOutOfRangeException` + a non-positive `width`/`height`, or a `width`/`height` exceeding `Surface.MaxDimension` (8192), + propagates, unwrapped, as `Surface`'s own `ArgumentOutOfRangeException` 3. **Processing**: Parses the document with `System.Xml.Linq`, builds an idβ†’element index, resolves the root `viewBox`/`width`/`height` into an intrinsic size and computes the `preserveAspectRatio`-driven fit transform into the requested raster, then recursively walks diff --git a/docs/design/canvas-net/geometry/path.md b/docs/design/canvas-net/geometry/path.md index fd4bca906..9a80d44db 100644 --- a/docs/design/canvas-net/geometry/path.md +++ b/docs/design/canvas-net/geometry/path.md @@ -174,9 +174,10 @@ and by its `ArcTo` handling, respectively). ### Callers `PathBuilder` and `Path` are public API entry points, invoked externally by consumers of the -CanvasNet package. `Path` has no dependency on any consumer; `Geometry` has no runnable -end-to-end example yet within this library, since no rasterizer (the reserved `Drawing` -subsystem) exists yet to consume a `Path`. `PathCommand.LineTo` and `PathCommand.ComputeTangents` +CanvasNet package. `Path` has no dependency on any consumer; within this repository, `Path` is +consumed by the `Drawing` subsystem's `PathFiller` (scan-conversion fill rasterization) and +`PathStroker` (stroke-outline generation), both of which rasterize a `Path` into a `Surface`. +`PathCommand.LineTo` and `PathCommand.ComputeTangents` are, likewise, public API entry points with an external caller: the separate `DemaConsulting.CanvasNet.Svg` package's marker-rendering feature calls both - synthesizing a `LineTo` command for a closed subpath's implicit closing edge and computing every marker diff --git a/docs/sysml2/model/canvas-net-svg.sysml b/docs/sysml2/model/canvas-net-svg.sysml index 0b2034560..d83421dd0 100644 --- a/docs/sysml2/model/canvas-net-svg.sysml +++ b/docs/sysml2/model/canvas-net-svg.sysml @@ -1,12 +1,12 @@ package CanvasNet { part def CanvasNetSvgSystem { - doc /* CanvasNetSvg is a decode/rasterize-only SVG codec system, distributed as the separate DemaConsulting.CanvasNet.Svg NuGet package, which depends on the core CanvasNet system's Canvas, Geometry, Drawing, and Fonts subsystems. */ + doc /* CanvasNetSvg is a decode/rasterize-only SVG codec system, distributed as the separate DemaConsulting.CanvasNet.Svg NuGet package, which depends on the core CanvasNet system's Canvas, Geometry, Drawing, Fonts, and Codecs subsystems. */ comment testRef /* Test: test/DemaConsulting.CanvasNet.Svg.Tests/SvgSystemIntegrationTests.cs */ comment designRef /* Design: docs/design/canvas-net-svg.md */ comment verificationRef /* Verification: docs/verification/canvas-net-svg.md */ comment reqRef /* Requirements: docs/reqstream/canvas-net-svg.yaml */ - comment /* CanvasNetSvg depends on the sibling CanvasNet system's Canvas subsystem (for the Surface pixel buffer SvgCodec rasterizes into), Geometry subsystem (for Path/Rect/BezierFlattening/SvgArcConverter), Drawing subsystem (for PathFiller/PathStroker/GradientPaint rasterization), and Fonts subsystem (for TrueTypeFont glyph-outline text rendering) - modeled below as non-owning `dependency` relationships to those existing subsystem part defs (not ordinary `part` usages, which would incorrectly model them as owned children of CanvasNetSvgSystem), since both systems live in this same git repository (though each is distributed as its own separate NuGet package - CanvasNetSvg is not folded into the CanvasNet package) rather than being third-party (OTS) or Shared Package dependencies (both of which are reserved for a package produced by a different repository). */ + comment /* CanvasNetSvg depends on the sibling CanvasNet system's Canvas subsystem (for the Surface pixel buffer SvgCodec rasterizes into), Geometry subsystem (for Path/Rect/BezierFlattening/SvgArcConverter), Drawing subsystem (for PathFiller/PathStroker/GradientPaint rasterization), Fonts subsystem (for TrueTypeFont glyph-outline text rendering), and Codecs subsystem (for the shared Codecs.ImageInfo record struct returned by SvgCodec.GetInfo) - modeled below as non-owning `dependency` relationships to those existing subsystem part defs (not ordinary `part` usages, which would incorrectly model them as owned children of CanvasNetSvgSystem), since both systems live in this same git repository (though each is distributed as its own separate NuGet package - CanvasNetSvg is not folded into the CanvasNet package) rather than being third-party (OTS) or Shared Package dependencies (both of which are reserved for a package produced by a different repository). */ part svgCodec : SvgCodec; @@ -14,5 +14,6 @@ package CanvasNet { dependency usesGeometry from CanvasNetSvgSystem to Geometry; dependency usesDrawing from CanvasNetSvgSystem to Drawing; dependency usesFonts from CanvasNetSvgSystem to Fonts; + dependency usesCodecs from CanvasNetSvgSystem to Codecs; } } From 02b5549de4b0875d9dfb5428ed87dc8ac41e0f08 Mon Sep 17 00:00:00 2001 From: Malcolm Nixon Date: Mon, 28 Sep 2026 23:01:49 -0400 Subject: [PATCH 10/10] docs: list Codecs dependency for CanvasNetSvg and fix stale factory-method comment - Added the Codecs subsystem to introduction.md's three CanvasNetSvg dependency mentions and to canvas-net.sysml's reverse-dependency comment, matching the sysml2 model's usesCodecs dependency and SvgCodec.GetInfo's actual use of Codecs.ImageInfo. - Added the missing large-finite-coordinate LineTo test name to the ComputeTangents verification scenario. - Corrected PathCommand's private constructor doc comment, which still said only "internal factory methods" construct instances even though LineTo is now a public factory method. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/design/introduction.md | 14 +++++++------- docs/sysml2/model/canvas-net.sysml | 2 +- docs/verification/canvas-net/geometry/path.md | 4 +++- .../Geometry/PathCommand.cs | 2 +- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/docs/design/introduction.md b/docs/design/introduction.md index 280df9ccb..8fed0e61f 100644 --- a/docs/design/introduction.md +++ b/docs/design/introduction.md @@ -56,8 +56,8 @@ software items, specifically: - **CanvasNetSvg (System)** β€” A separate, independently-distributed software system providing SVG (Scalable Vector Graphics) rasterization, containing a single unit, `SvgCodec`, which decodes/rasterizes a subset of SVG vector documents into a `CanvasNet.Canvas.Surface`. - `CanvasNetSvg` depends on this `CanvasNet` system's `Canvas`, `Geometry`, `Drawing`, and `Fonts` - subsystems β€” see _CanvasNetSvg System Design_ (`canvas-net-svg.md`) + `CanvasNetSvg` depends on this `CanvasNet` system's `Canvas`, `Geometry`, `Drawing`, `Fonts`, + and `Codecs` subsystems β€” see _CanvasNetSvg System Design_ (`canvas-net-svg.md`) The following OTS items are also covered: @@ -118,8 +118,8 @@ interfaces and responsibilities. A sibling top-level system, `CanvasNetSvg`, lives in this same repository alongside `CanvasNet` (rather than as one of its subsystems): its sole unit, `SvgCodec`, namespace `DemaConsulting.CanvasNet.Svg`, is distributed as its own separate NuGet package and depends on -the `CanvasNet` system's `Canvas`, `Geometry`, `Drawing`, and `Fonts` subsystems β€” see the Folder -Layout section below and _CanvasNetSvg System Design_ (`canvas-net-svg.md`). +the `CanvasNet` system's `Canvas`, `Geometry`, `Drawing`, `Fonts`, and `Codecs` subsystems β€” see +the Folder Layout section below and _CanvasNetSvg System Design_ (`canvas-net-svg.md`). ## Folder Layout @@ -227,9 +227,9 @@ expand further to mirror the software architecture. `Canvas/Surface.cs` also gai `CompositeOverSpan` method used internally by `Drawing/PathFiller.cs`, and the `Drawing` subsystem now includes the additional stroking files listed above, along with the gradient paint files added for linear/radial gradient support in `PathFiller`. The sibling `CanvasNetSvg` -system's sole unit, `SvgCodec`, depends on the `CanvasNet` system's `Geometry`, `Drawing`, and -`Fonts` subsystems (not only `Canvas`) to build and rasterize the vector paths and text it -decodes from SVG documents β€” see _CanvasNetSvg System Design_ (`canvas-net-svg.md`). +system's sole unit, `SvgCodec`, depends on the `CanvasNet` system's `Geometry`, `Drawing`, +`Fonts`, and `Codecs` subsystems (not only `Canvas`) to build and rasterize the vector paths and +text it decodes from SVG documents β€” see _CanvasNetSvg System Design_ (`canvas-net-svg.md`). ## Document Conventions diff --git a/docs/sysml2/model/canvas-net.sysml b/docs/sysml2/model/canvas-net.sysml index ad46681bf..e5f33feb8 100644 --- a/docs/sysml2/model/canvas-net.sysml +++ b/docs/sysml2/model/canvas-net.sysml @@ -13,7 +13,7 @@ package CanvasNet { comment verificationRef /* Verification: docs/verification/canvas-net.md */ comment reqRef /* Requirements: docs/reqstream/canvas-net.yaml */ comment /* The Drawing subsystem renders Geometry.Path geometry onto a Canvas.Surface through PathFiller (direct fill, solid color or GradientPaint), PathStroker (stroke-to-fill conversion), and GradientPaint (linear/radial gradient evaluation), while the Fonts subsystem loads glyph-based TrueType fonts and produces Geometry.Path glyph outlines plus metrics and kerning for callers that want text rendering. */ - comment /* The sibling CanvasNetSvgSystem (distributed as the separate DemaConsulting.CanvasNet.Svg package) depends on this system's Canvas, Geometry, Drawing, and Fonts subsystems - see docs/sysml2/model/canvas-net-svg.sysml. */ + comment /* The sibling CanvasNetSvgSystem (distributed as the separate DemaConsulting.CanvasNet.Svg package) depends on this system's Canvas, Geometry, Drawing, Fonts, and Codecs subsystems - see docs/sysml2/model/canvas-net-svg.sysml. */ part canvas : Canvas; part codecs : Codecs; diff --git a/docs/verification/canvas-net/geometry/path.md b/docs/verification/canvas-net/geometry/path.md index 4f7ab96bc..258d5ac2a 100644 --- a/docs/verification/canvas-net/geometry/path.md +++ b/docs/verification/canvas-net/geometry/path.md @@ -178,6 +178,7 @@ the resulting command's `Type` is `LineTo` and its `EndPoint` matches the value **Tests**: `PathCommand_ComputeTangents_LineTo_ReturnsSameNormalizedDirectionForBothTangents`, `PathCommand_ComputeTangents_LineToWithCoincidentStartAndEnd_ReturnsNullTangents`, +`PathCommand_ComputeTangents_LineToWithLargeFiniteCoordinates_ReturnsValidNormalizedDirection`, `PathCommand_ComputeTangents_LineToWithFarApartNearMaxFiniteCoordinates_ReturnsValidNormalizedDirection`, `PathCommand_ComputeTangents_QuadraticBezierTo_PointsTowardThenAwayFromControlPoint`, `PathCommand_ComputeTangents_QuadraticBezierToWithControlCoincidentWithStart_FallsBackToEndDirection`, @@ -188,7 +189,8 @@ the resulting command's `Type` is `LineTo` and its `EndPoint` matches the value Exercises `ComputeTangents` for every command type: a `LineTo` yields the same normalized direction for both tangents, or `null` for both when its start and end coincide, or a valid -normalized direction even when its start and end coordinates are near opposite ends of the +normalized direction even when its coordinates are very large but finite (magnitudes around +`1e25`) or when its start and end coordinates are near opposite ends of the finite `float` range; a `QuadraticBezierTo`/`CubicBezierTo` yields tangents pointing toward/away from its control point(s), falling back to the straight start-to-end direction when every control point coincides with its nearest endpoint; an `ArcTo` and a `Close` both diff --git a/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs b/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs index 614c7a723..33cf1b4df 100644 --- a/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs +++ b/src/DemaConsulting.CanvasNet/Geometry/PathCommand.cs @@ -79,7 +79,7 @@ public readonly struct PathCommand /// /// Initializes every field of the tagged union directly. Private because only this - /// struct's own internal factory methods below construct instances, keeping every field + /// struct's own factory methods below construct instances, keeping every field /// combination that is ever produced consistent with its . /// private PathCommand(