Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
8ed2b29
Update shared infrastructure for V2
JimBobSquarePants Oct 27, 2026
7438e1d
Fix contour hierarchy, winding caches and small intersections
JimBobSquarePants Oct 27, 2026
51fdb4f
Fix tiny intersections in the vertex overload
JimBobSquarePants Oct 27, 2026
74b1aff
Add single-pass Martinez fill-rule clipping
JimBobSquarePants Oct 27, 2026
62dc90a
Fix cancelled determinants and collinear event ordering
JimBobSquarePants Oct 29, 2026
9b79427
Complete the V2 Martinez fill-rule implementation
JimBobSquarePants Oct 29, 2026
fcd1407
Classify segment overlaps from source coordinates
JimBobSquarePants Oct 29, 2026
631b39f
Retain cached events when pooled storage grows
JimBobSquarePants Oct 29, 2026
d2b8522
Reduce Martinez sweep overhead and output allocations
JimBobSquarePants Oct 29, 2026
f9d56fc
Reduce NonZero fill-rule sweep overhead
JimBobSquarePants Oct 29, 2026
0a65a5b
Use Normalize as the single-polygon cleanup API
JimBobSquarePants Oct 29, 2026
ceb4a9f
Fix point intersection symmetry and resolve axis crossings exactly
JimBobSquarePants Oct 29, 2026
4f814c3
Support open contour clipping in the Martinez sweep
JimBobSquarePants Oct 30, 2026
545b6c0
Record clipping benchmarks and verify dense-star boundaries
JimBobSquarePants Oct 30, 2026
eb5cb19
Add SVG test output and curved open-path coverage
JimBobSquarePants Oct 30, 2026
20b46de
Preserve exact axis-aligned stroke intersections
JimBobSquarePants Oct 30, 2026
48a4e26
Validate stroke widths and return empty geometry for zero width
JimBobSquarePants Oct 30, 2026
878291c
Match ImageSharp generated image output ignores
JimBobSquarePants Oct 30, 2026
ebbb879
Add polygon offsets and publish console benchmark results
JimBobSquarePants Oct 30, 2026
6faa3c8
Optimize sweep queue comparisons and scratch buffer allocations
JimBobSquarePants Nov 2, 2026
0fd1130
Optimize offsets and output assembly and expose struct enumerators
JimBobSquarePants Nov 2, 2026
e38580a
Set PolygonClipper V2 version floor and package metadata
JimBobSquarePants Nov 2, 2026
8553f2b
Fix CI restore and project reference casing
JimBobSquarePants Nov 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
max_line_length = 160

##########################################
# File Extension Settings
Expand Down Expand Up @@ -134,6 +135,10 @@ csharp_style_prefer_null_check_over_type_check = true:warning
# C# Style Rules
# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules#c-style-rules
[*.{cs,csx,cake}]
# Report lines exceeding the shared editor limit during analysis and builds.
roslynator_max_line_length = 160
dotnet_diagnostic.RCS0056.severity = warning

# 'var' preferences
csharp_style_var_for_built_in_types = false:error
csharp_style_var_when_type_is_apparent = false:error
Expand Down
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@
*.ktx filter=lfs diff=lfs merge=lfs -text
*.ktx2 filter=lfs diff=lfs merge=lfs -text
*.astc filter=lfs diff=lfs merge=lfs -text
*.uastc filter=lfs diff=lfs merge=lfs -text
*.raw filter=lfs diff=lfs merge=lfs -text
*.pam filter=lfs diff=lfs merge=lfs -text
*.pbm filter=lfs diff=lfs merge=lfs -text
*.pgm filter=lfs diff=lfs merge=lfs -text
Expand Down
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ project.lock.json
project.fragment.lock.json
artifacts/

# Test image output
**/Images/ActualOutput
**/Images/ReferenceOutput

# StyleCop
StyleCopReport.xml

Expand Down
32 changes: 17 additions & 15 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ These instructions apply to the entire repository. More-specific `AGENTS.md` fil

## Working Practices

- Inspect the relevant implementation, tests, benchmarks, project files, and nearby code before proposing or making changes. Do not infer current behavior when the source is available.
- Inspect only the source and supporting files needed for the task before proposing or making changes. Do not infer current behavior when the source is available.
- Make the smallest complete change that solves the requested problem. Avoid unrelated cleanup, speculative abstractions, and formatting churn.
- Match established architecture, naming, formatting, documentation, and test patterns. Treat `.editorconfig`, analyzers, and repository build settings as authoritative.
- Trace the existing execution path before changing it. Extend and optimize the existing implementation within the requested behavior and affected path.
- Before implementing an operation, find and inspect the existing APIs that provide it. Use or extend those APIs instead of writing equivalent logic elsewhere. This includes color conversion, pixel conversion, memory management, and vectorized operations. If an API lacks required behavior, improve its owning implementation rather than bypassing it with a separate implementation.
- Follow existing naming, formatting, documentation, and test patterns. Treat `.editorconfig`, analyzers, and repository build settings as authoritative.
- Use simple technical English in all communication, documentation, and comments. Use short sentences, active voice, and existing code terminology.
- Preserve public API and observable behavior unless the task explicitly requires a change. Public API documentation must describe observable behavior, not implementation details.
- Do not use reflection against built assemblies, ad hoc assembly loading, or temporary probe projects unless explicitly requested.
- Build .NET projects in Release configuration unless explicitly instructed otherwise.
Expand All @@ -15,27 +18,26 @@ These instructions apply to the entire repository. More-specific `AGENTS.md` fil

- Treat throughput, latency, memory use, and binary size as design constraints, especially in pixel-processing, drawing, parsing, encoding, and other hot paths.
- Avoid unnecessary allocations, copies, boxing, closures, interface dispatch, repeated enumeration, and extra passes over data.
- Reuse the repository's existing memory ownership, pooling, span, vectorization, and parallelization patterns. Do not introduce a new mechanism when an established one fits.
- Keep hot loops simple and bounds-check-friendly. Hoist invariant work, preserve locality, and use the narrowest suitable data types without sacrificing correctness.
- Do not trade correctness or maintainability for assumed speed. Support non-obvious optimizations with measurements or clear evidence, and add or update benchmarks when performance is the purpose of the change.
- Reuse existing memory ownership, pooling, span, vectorization, and parallelization mechanisms.
- Use a SIMD-first design for suitable data processing code. Build on existing vectorized operations, dispatch mechanisms, and scalar fallbacks. Keep hot loops simple, hoist invariant work, and preserve memory locality.
- Preserve correctness and maintainability during optimization. Distinguish source-based reasoning from measured results. Claim a speedup only with measurements. Use existing benchmarks first. Add or update cases only when they measure relevant behavior that existing benchmarks miss.
- Consider all supported target frameworks and runtime capabilities. Do not regress fallback paths while optimizing newer runtimes.

## C# Conventions

- Follow the existing code around the change; local patterns take precedence over generic preferences.
- Follow local patterns when they comply with the explicit rules.
- Do not use `record` or `record struct` types.
- Prefer established invariants over redundant guards. Validate at real external boundaries and do not add defensive checks for internally controlled states.
- Do not extract single-use helpers merely to name a block. Extract only for genuine reuse, an established local pattern, or meaningful complexity reduction.
- Do not extract single-use helpers merely to name a block. Extract only for genuine reuse, an established local pattern, or independently complex logic.
- Add vertical whitespace after multi-line statements and declarations and between distinct logical stages. Never add trailing whitespace.
- Document every method, constructor, and property, regardless of whether it is public, internal, protected, or private. Keep public API documentation limited to observable behavior; use private and internal documentation to capture the contract and intent needed to maintain the code.
- Add inline comments throughout complex code. Explain algorithms, formulas, invariants, ownership, compatibility behavior, and performance tradeoffs at the operations and decisions they govern. Explain why the code is shaped that way rather than narrating the syntax.
- Document SIMD code especially thoroughly. Explain the vector layout, lane meaning, widening or narrowing, masks, shuffles, constants, alignment or remainder handling, supported instruction paths, scalar equivalence, and the reason each non-obvious operation is correct.
- Write algorithm and SIMD comments for a maintainer who is unfamiliar with the implementation. The reader should not need to reconstruct intent from external documentation, issue history, or benchmark results.
- Document every added method, constructor, and property, regardless of visibility. Update documentation when a member's behavior or contract changes. Keep public API documentation limited to observable behavior. Use private and internal documentation to explain the contract and intent.
- Add inline comments that explain why complex code works. Explain algorithms, formulas, invariants, memory ownership, compatibility behavior, and performance decisions where they apply.
- For SIMD, explain lane layouts, operations, alignment, remainders, and scalar equivalence so an unfamiliar maintainer can follow the code.

## Verification

- Add or update focused tests when behavior changes, following the test framework and conventions already used by the project.
- Never hack, weaken, skip, conditionally bypass, or otherwise manipulate a test to make it pass. Fix the production defect or the genuine test defect while preserving the test's intended coverage and sensitivity.
- Do not update golden files, reference images, snapshots, baselines, or expected-output artifacts to resolve a test failure. Treat a mismatch as evidence to investigate and correct the implementation.
- Run the narrowest relevant formatting, test, and Release build commands, then expand verification in proportion to the risk and scope of the change.
- Add or update tests only when they prove a required behavior or expose a real defect. Derive expectations from established contracts, explicit requirements, or defect evidence. Use source to identify contracts and integration points, not to copy implementation results into expectations. Prefer extending existing tests. Avoid redundant cases and assertions that merely repeat the implementation.
- Never weaken, skip, or bypass a valid test to make it pass. Fix the production defect or the genuine test defect. Replace or remove a test only with evidence that its expectation is invalid or its coverage is redundant.
- Do not update golden files, reference images, snapshots, baselines, or expected-output artifacts merely to silence a failure. Investigate mismatches. Update expected results only for an established requirement change or an incorrect reference result proved by independent contract or defect evidence.
- Test the actual behavior through the existing execution path. Synthetic inputs must exercise an established requirement or reproduce a real defect. Do not invent requirements or substitute internal structure and helper calls for assertions about required behavior. Run the narrowest relevant formatting, test, and Release build commands.
- Report what changed, the verification performed, and any remaining risks or unverified assumptions.
130 changes: 102 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,47 +13,97 @@ SixLabors.PolygonClipper

</div>

SixLabors.PolygonClipper provides high-performance polygon clipping and stroking in C#.
Boolean operations (union, intersection, difference, xor) are implemented with a Martínez-Rueda sweep-line pipeline for complex polygons with holes and multiple contours.
Contour normalization is handled by a dedicated Vatti/Clipper2-inspired pipeline (`PolygonClipper.Normalize`) that resolves self-intersections/overlaps into positive-winding output.
`PolygonStroker` can optionally run that normalization pass on emitted stroke geometry.
SixLabors.PolygonClipper performs polygon clipping, stroking and offsets in C#.
It uses the Martinez-Rueda algorithm with double coordinates. It supports holes,
self-intersections, overlapping edges, and multiple contours.

## Features
## Clipping

- Works with non-convex polygons, including holes and multiple disjoint regions
- Handles edge cases like overlapping edges and vertical segments
- Preserves topology: output polygons include hole/contour hierarchy
- Deterministic and robust sweep line algorithm with O((n + k) log n) complexity
- Includes `PolygonClipper.Normalize` (Clipper2-inspired) for positive-winding contour normalization
- Includes `PolygonStroker` for configurable geometric stroking (joins, caps, miter limits)
- Uses double precision geometry without coordinate quantization
The Boolean operations are `Intersection`, `Union`, `Difference`, and `Xor`.
Each combines a subject polygon with a clip polygon. Both operands can contain open and closed contours.
Each accepts `EvenOdd`, `NonZero`, `Positive`, or `Negative` filling.

## Usage
```csharp
using SixLabors.PolygonClipper;

Polygon subject =
[
[new Vertex(0, 0), new Vertex(10, 0), new Vertex(10, 10), new Vertex(0, 10)]
];
Polygon clip =
[
[new Vertex(5, 5), new Vertex(15, 5), new Vertex(15, 15), new Vertex(5, 15)]
];

// Intersect both polygons using NonZero filling.
Polygon result = PolygonClipper.Intersection(subject, clip, FillRule.NonZero);
```

The API centers around `Polygon` and `Contour` types. Construct input polygons using contours, then apply Boolean operations via `PolygonClipper`:
The subject and clip can use different fill rules:

```csharp
Polygon result = PolygonClipper.Union(subject, clipping);
// Use EvenOdd for the subject and NonZero for the clip.
Polygon result = PolygonClipper.Intersection(subject, clip, FillRule.EvenOdd, FillRule.NonZero);
```

Boolean operations can process self-intersecting inputs directly.
Use normalization when you want canonical positive-winding contours (for example, before export or rendering pipelines that rely on winding semantics):
These operations apply the fill rules during the clipping sweep. They do not require
an input normalization pass. Coordinates must be finite doubles.

Fill rules interpret closed input contours. Closed results use positive orientation:
counterclockwise exterior contours and islands, with clockwise holes, in Cartesian coordinates.
Use `NonZero`, `EvenOdd`, or `Positive` filling to consume the resolved area.
`Negative` selects negatively wound input; it does not request negatively oriented output.

## Normalization

`Normalize(polygon, fillRule)` cleans one polygon. It resolves self-intersections and overlaps in filled boundaries
and retains their full contour hierarchy. It also resolves overlapping open paths without filling them.
It reads the original contour directions without changing the input or applying a preparation pass.

```csharp
Polygon clean = PolygonClipper.Normalize(input);
// Clean the NonZero-filled area and retain parent and hole information.
Polygon result = PolygonClipper.Normalize(subject, FillRule.NonZero);
```

`Normalize` uses a fixed positive-winding normalization path.
Clipping accepts raw contours and their fill rules directly. It does not require `Normalize` first.
The positive output orientation follows [Clipper2's output convention](https://www.angusj.com/clipper2/Docs/Overview.htm).

## Open paths

### Stroking
`Contour.IsClosed` controls the closing edge for both clipping and stroking.
Closed contours enclose filled areas. Open contours contain consecutive line segments with no filled interior.
Fill rules do not change open path membership.

Use `PolygonStroker` to generate filled stroke polygons from input contours:
All clipping operations return `Polygon`. Each result contour identifies its geometry:

- A closed contour is a filled boundary. Its first vertex is not repeated at the end.
- An open contour with two or more vertices is a line piece.
- An open contour with one vertex is an isolated point.

Clipping splits linework at intersections and retains the cut endpoints in each resulting piece.
Ordinary source bends stay connected. An explicit line cycle remains open and retains its repeated terminal vertex.
Open contours have no parent or holes. Covered linework and points are omitted when a retained area already represents them.

```csharp
Polygon stroked = PolygonStroker.Stroke(input, width: 12);
Contour horizontal = [new Vertex(-2, 0), new Vertex(2, 0)];
horizontal.IsClosed = false;
Contour vertical = [new Vertex(0, -2), new Vertex(0, 2)];
vertical.IsClosed = false;

// Return one open contour containing the crossing point (0, 0).
Polygon result = PolygonClipper.Intersection([horizontal], [vertical], FillRule.NonZero);
```

Configure join/cap behavior through `StrokeOptions`:
## Stroking

`PolygonStroker` creates stroke polygons with configurable joins, caps, and width.
Each source contour has an `IsClosed` property, which defaults to `true`.
Set it to `false` for an open source path. Endpoint coordinates and stroke width do not select closure.
One polygon can contain both open and closed stroke inputs.

Stroke output contains closed contours without a repeated closing vertex.
When `NormalizeOutput` is enabled, stroke cleanup calls `Normalize` with `NonZero` filling.
This preserves the raw outlines' filled area for either sign of stroke width.

```csharp
StrokeOptions options = new()
Expand All @@ -64,23 +114,47 @@ StrokeOptions options = new()
ArcDetailScale = 1
};

Polygon stroked = PolygonStroker.Stroke(input, width: 12, options);
// Build a stroke with width 12 and the specified joins and caps.
Polygon result = PolygonStroker.Stroke(subject, width: 12, options);
```

## Offsets

`PolygonOffsetter.Offset(polygon, delta, fillRule, options)` expands or contracts a filled polygon.
Positive distance expands exterior boundaries and shrinks holes. Negative distance contracts exterior boundaries and expands holes.
Collapsed holes and components disappear. Zero distance returns an independent, resolved copy of the source filled area.

All source contours must be closed. The fill rule interprets the original source contours before their boundaries are offset.
`OffsetOptions` selects the join style, miter limit and arc detail. Offset results always contain resolved boundaries.

```csharp
OffsetOptions offsetOptions = new() { LineJoin = LineJoin.Round };

// Expand the NonZero-filled area by two coordinate units with the selected joins.
Polygon expanded = PolygonOffsetter.Offset(subject, 2, FillRule.NonZero, offsetOptions);

// Contract the same source area by two coordinate units.
Polygon contracted = PolygonOffsetter.Offset(subject, -2, FillRule.NonZero, offsetOptions);
```

## Complexity

Martinez has a published complexity of `O((n + k) log n)` for `n` input edges and `k` intersections.

This implementation stores active edges in a list, so inserting or removing an edge can take linear time.
It does not guarantee that bound.

## Algorithm References

This project draws on the following algorithm and implementation references:

> F. Martínez et al., "A simple algorithm for Boolean operations on polygons", *Advances in Engineering Software*, 64 (2013), pp. 11-19.
> https://doi.org/10.1016/j.advengsoft.2013.04.004

> B. R. Vatti, "A generic solution to polygon clipping", *Communications of the ACM*, 35(7), 1992, pp. 56-63.
> https://dl.acm.org/doi/pdf/10.1145/129902.129906

> 21re, *rust-geo-booleanop* (Rust Martínez-Rueda implementation reference).
> https://github.com/21re/rust-geo-booleanop

> Angus Johnson, *Clipper2* polygon clipping library (reference implementation for the normalization pipeline).
> Angus Johnson, *Clipper2* polygon clipping library.
> https://github.com/AngusJohnson/Clipper2

## License
Expand Down
21 changes: 14 additions & 7 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,23 @@

## Supported Versions

Six Labors provides security fixes only for the latest major version of each library.
Six Labors provides security updates for the latest major version of each library.

Older major versions are end-of-life and do not receive security fixes.
Each major version remains eligible for security updates for 12 months after the first stable release of the next major version of that library.
After this period, that major version is end-of-life and does not receive security updates.

Users must upgrade to the latest major version to receive security fixes.
Users must install the latest available patch or minor release within a supported major version to receive security fixes.
Older releases within that major version are not maintained separately.

| Version | Supported |
| -------------------- | --------- |
| Latest major version | Yes |
| Older major versions | No |
| Version | Supported |
| ------- | --------- |
| Latest major version | Yes |
| Superseded major version within 12 months of the next major's first stable release | Yes |
| Superseded major version after that 12-month period | No |

Security updates may require a license key under the existing license terms. This does not change the license terms.

This policy covers security fixes only. It does not include feature backports or extend support for underlying .NET versions.

Security fixes, if any, are provided at Six Labors' discretion.

Expand Down
4 changes: 4 additions & 0 deletions src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@
</PropertyGroup>

<ItemGroup>
<!-- Use Source Link from the SDK instead of the older shared package. -->
<PackageReference Remove="Microsoft.SourceLink.GitHub" />

<InternalsVisibleTo Include="SixLabors.PolygonClipper.Tests" Key="$(SixLaborsPublicKey)" />
<InternalsVisibleTo Include="PolygonClipper.Benchmarks" Key="$(SixLaborsPublicKey)" />
</ItemGroup>

</Project>
Loading
Loading