Metadata-Version: 2.5
Name: rotau
Version: 0.2.0
Summary: Rotation algorithms for grid-based art: pixel art, tilemaps, material IDs. Never blends, never invents a value. Zero dependencies.
Project-URL: Homepage, https://github.com/rotau/rotau
Project-URL: Issues, https://github.com/rotau/rotau/issues
Author: davedude101
License: This is free and unencumbered software released into the public domain.
        
        Anyone is free to copy, modify, publish, use, compile, sell, or
        distribute this software, either in source code form or as a compiled
        binary, for any purpose, commercial or non-commercial, and by any
        means.
        
        In jurisdictions that recognize copyright laws, the author or authors
        of this software dedicate any and all copyright interest in the
        software to the public domain. We make this dedication for the benefit
        of the public at large and to the detriment of our heirs and
        successors. We intend this dedication to be an overt act of
        relinquishment in perpetuity of all present and future rights to this
        software under copyright law.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
        EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
        MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
        IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
        OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
        ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
        OTHER DEALINGS IN THE SOFTWARE.
        
        For more information, please refer to <https://unlicense.org>
        
        ---
        
        ONE EXCEPTION
        
        The `cleanedge` algorithm is a port of torcado's cleanEdge shader, which is
        MIT licensed. Public-domain dedication is not ours to make for someone else's
        work, so that one algorithm stays under its original MIT terms: keep the
        notice in THIRD-PARTY.md with any copy you distribute. Everything else in
        this repository - written by davedude101 - is public domain as above, with no
        conditions of any kind.
        
        If you want a distribution with no obligations whatsoever, delete the
        `cleanedge` entry from the algorithm registry and the functions it names; the
        other five algorithms have no third-party provenance.
License-File: LICENSE
License-File: THIRD-PARTY.md
Keywords: cleanedge,gamedev,grid,material-id,nearest-neighbour,pixel-art,pixelart,raster,resampling,rotation,rotsprite,sprite,tilemap,voxel
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: The Unlicense (Unlicense)
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Games/Entertainment
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Scientific/Engineering :: Image Processing
Classifier: Typing :: Typed
Requires-Python: >=3.9
Provides-Extra: dev
Requires-Dist: numpy>=1.20; extra == 'dev'
Requires-Dist: pillow>=9; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Provides-Extra: image
Requires-Dist: pillow>=9; extra == 'image'
Description-Content-Type: text/markdown

# rotau

Rotation algorithms for grid-based art, optimised for **quality over speed**.

A grid of items in, a rotated grid of the same items out. Nothing is ever
blended, averaged or interpolated — so the result is meaningful whether the
items are colours, palette indices, tile names or material IDs.

```python
from rotau import rotate

result = rotate(items, width, height, 37.0, empty=0)
result.items  # flat list, same items, never a new one
result.width, result.height
```

**No dependencies.** The core is standard library only; Pillow and numpy are
optional extras used solely for reading image files.

---

## Why

Every other pixel-art rotator is shaped by a real-time budget. RotSprite has to
fit in a sprite pipeline; cleanEdge has to fit in a fragment shader, so it gets
one 5×5 neighbourhood and no memory. That budget is why they reconstruct *some*
slopes (1:1, 2:1) from a hardcoded pattern table and step-render the rest, and
why every output cell is decided on its own with no idea what the cell next to
it did.

`rotau`'s own algorithm is built for pre-computation. It is allowed to look at
the whole grid, solve small linear programs, and iterate. In exchange it
recovers the shape that was actually drawn — at *any* rational slope, as arcs
where arcs were drawn — and then decides the whole output as one structured
problem rather than cell by cell.

---

## Install

```bash
pip install rotau              # core, no dependencies
pip install rotau[image]       # + Pillow, for reading and writing image files
```

Python 3.9+.

## Quickstart

Four ways in, depending on what you already have. All return a `Result`.

```python
import rotau

# 1. a flat, row-major sequence
res = rotau.rotate(items, width, height, angle=37.0, empty=0)

# 2. nested rows
res = rotau.rotate_rows([[0, 1, 1], [0, 1, 0], [1, 1, 0]], 30.0, empty=0)

# 3. a Grid you built earlier
grid = rotau.Grid(items, width, height, empty=0)
res = rotau.rotate_grid(grid, 30.0)

# 4. prepared once, then many angles (much faster, and self-consistent)
rot = rotau.Rotator(grid)
frames = rot.frames(
    [i * 360 / 64 for i in range(64)],
    pivot=(8.0, 12.0),
    size=(32, 32),
    out_pivot=(16.0, 16.0),
    workers=8,
)
```

### The Result

```python
res.items  # flat list, row-major
res.width, res.height
res.rows()  # nested lists
res.at(x, y)
res.pivot  # the cell the input pivot landed on, as ints
res.target_of(x, y)  # map an input coordinate into the output
res.source_of(x, y)  # and back again
res.to_grid()  # feed straight into another rotation
```

### The pivot is a cell, and it stays that cell

A pivot is a **cell index**: `(3, 4)` means the cell at column 3, row 4. The
pivot that comes back is another cell index — always whole numbers, never a
fraction — and it names the cell holding what the source pivot cell held.

```python
res = rotau.rotate_grid(grid, 37.0, pivot=(9, 1))
res.pivot  # e.g. (8, 2) - the same cell, relocated
res.at(*res.pivot)  # whatever was at (9, 1) in the source
```

That is a guarantee, not a rounding: the canvas is positioned so the pivot
lands exactly on a cell centre rather than between two.

A fractional pivot is **refused** in this mode rather than quietly rounded —
half a cell along is not a cell, so there would be no cell to report back.
Use `pivot_mode="exact"` if you want sub-cell pivots. A pivot outside the grid
is fine, and the pivot that comes back may then be negative or past the far
edge; it is still the same point, and `target_of` / `source_of` still map it.

* `pivot` — centre of rotation. Defaults to the middle cell. May be outside
  the grid.
* `size` — output canvas `(width, height)`. Defaults to a tight fit.
* `out_pivot` — where the pivot lands in the output.

Angles are degrees, counter-clockwise. Grids need not be square — width and
height are independent everywhere, and a quarter turn of an 11×4 grid returns
a 4×11 one.

#### Sub-cell pivots

`pivot_mode="exact"` switches to a continuous coordinate system where cell
`(x, y)` spans `[x, x+1] × [y, y+1]`, so `(0, 0)` is the grid's top-left corner
and `(0.5, 0.5)` is the centre of the first cell. Pivots may then be
fractional, and `result.pivot` is a float. `target_of` / `source_of` map any
point either way, in that system, in both modes:

```python
opts = rotau.Options(pivot_mode="exact")
res = rotau.rotate_grid(grid, 37.0, pivot=(9.5, 1.5), options=opts)
res.pivot  # e.g. (8.894, 2.193)
res.source_of(*res.pivot) == (9.5, 1.5)  # exact round trip
```

### The canvas is trimmed to the content

The output holds no empty border. If your sprite has a margin, that margin is
not carried into the result, and rotation does not amplify it — a 35×30 sprite
with a two-cell margin turns 45° into 31×35, not 46×46.

`fit="source"` keeps the whole box the rotated source rectangle sweeps, which
is what 0.1.x did:

```python
rotau.rotate_grid(grid, 45.0)  # trimmed
rotau.rotate_grid(grid, 45.0, options=rotau.Options(fit="source"))  # not
```

#### Frames of a turn

Trimmed frames each have their own size, and their pivots register them: place
each frame so its `pivot` sits at a common point and you get back exactly the
shared-canvas layout, cell for cell. That is the usual sprite-atlas shape —
tight frames plus an origin.

If you would rather every frame share one canvas, pass `size` and `out_pivot`.
An explicit `size` is never trimmed, precisely so frames stay registered:

```python
frames = rotau.rotate_frames(grid, range(0, 360, 15), size=(64, 64), out_pivot=(32, 32))
```

### Items can be anything

```python
from enum import Enum

Mat = Enum("Mat", "STONE WATER LAVA")

rotau.rotate_rows([[Mat.STONE, Mat.WATER], [Mat.LAVA, None]], 30.0, empty=None)
```

Strings, ints, tuples, enum members, dataclasses — anything comparable with
`==`. Two cells belong to the same feature exactly when they hold the same
item, and `empty` names the item meaning "nothing here". That is the entire
contract.

### Images

```python
from rotau import image, rotate_grid

grid = image.load("hero.png")  # Grid of RGBA tuples
res = rotate_grid(grid, 37.0, options=image.colour_options())
image.save(res, "turned.png")

# or straight from/to numpy
grid = image.from_array(arr)
arr = image.to_array(res)
```

`image.colour_options()` supplies the three colour-specific behaviours the core
deliberately leaves open: when two colours count as the same feature
(`similar_colours(threshold)`), which of two outranks the other, and how far
apart they are. Only `cleanedge` consults the latter two.

---

## Algorithms

Every algorithm has the **same signature**, so swapping is a one-word change:

```python
algorithm(grid, angle, *, pivot=None, size=None, out_pivot=None,
          options=None, **specific) -> Result
```

| name | what it is | reconstructs edges? |
|---|---|---|
| `reconstruct` | this library's own: rebuild the shape, rotate it, resample by exact area. Best quality. **Default.** | globally |
| `cleanedge` | torcado's 2022 shader, ported to the CPU and generalised off colour | locally, 5×5 |
| `rotsprite` | Xenowhirl's 2007 upscale-rotate-vote approach | locally, via Scale2x |
| `area` | exact analytic area coverage of the raw cells, winner takes the cell | no |
| `supersample` | k×k plurality sampling per output cell | no |
| `nearest` | plain nearest-neighbour point sampling | no |

They form a ladder. Pick by how much time you have — see the measured numbers
below. `area` is the useful middle rung: no reconstruction, so it cannot
straighten an edge, but coverage is still *exact* rather than sampled, which
makes it meaningfully better than `supersample` for about the same work.

```python
rotau.rotate_grid(grid, 45.0, algorithm="rotsprite")
rotau.rotate_grid(grid, 45.0, algorithm="cleanedge", line_width=0.707)
rotau.rotate_grid(grid, 45.0, algorithm="supersample", samples=16)

rotau.algorithm_names()  # ['reconstruct','cleanedge','rotsprite','area','supersample','nearest']
rotau.DESCRIPTIONS  # one-liners for each
rotau.get_algorithm("area")  # the callable, if you would rather dispatch yourself
```

Algorithm-specific arguments: `cleanedge` takes `line_width`, `slope`,
`cleanup`; `rotsprite` takes `scale` and `scaler` (`"scale2x"` or `"eagle"`);
`supersample` takes `samples`.

---

## Command line

```bash
rotau in.png -o out.png --angle 30
rotau in.png --frames 32 --pivot 8,12 --size 32x32 --out-dir frames/ --workers 8
rotau map.csv -o turned.csv --angle 45 --empty 0
rotau tiles.txt -o turned.txt --angle 20
rotau in.png -a rotsprite --scaler eagle --angle 45 -o out.png
rotau in.png -a supersample --samples 16 --angle 45 -o out.png
rotau in.png -a area --angle 45 -o out.png
rotau --list-algorithms
rotau in.png --info
```

Formats are picked from the extension:

| extension | format |
|---|---|
| `.png .gif .bmp .webp .jpg` | images, RGBA tuples (needs Pillow) |
| `.json` | `{"width": w, "height": h, "items": [...], "empty": x}`, or a bare nested array |
| `.csv` | comma-separated tokens; integers stay integers |
| `.txt` | one line per row, one character per cell — tilemaps, ASCII art |

`--help` lists the tuning flags.

---

## How `reconstruct` works

Seven stages. The first four build a resolution-independent reconstruction of
the grid *once*; the last three run per angle.

### 1. Connectivity — which diagonals are really joined

A square lattice is ambiguous: when two diagonally-touching cells match and the
other two cells of the 2×2 block match each other, only one of the two
diagonals can be connected, and the grid does not say which. Getting this wrong
is how a rotator snips off a one-cell antenna.

We build the 8-neighbour similarity graph and resolve every crossing with
Kopf & Lischinski's three heuristics — *curve length*, *sparse cells*, and
*islands* (never orphan a lone cell). These are arguments about the whole
picture; cleanEdge's equivalent is a handful of local tests inside one 5×5
window.

**Dither is not a bundle of diagonals.** In a checkerboard every lattice corner
is an ambiguous crossing, including the ones directly left, right, above and
below; along a genuine one-cell diagonal only the corners *along* the diagonal
are. Where the ambiguity spreads orthogonally we join neither diagonal, so a
dithered shading ramp stays a texture instead of smearing into ribbons.

`simgraph.py`

### 2. Cells — grid cells as interlocking polygons

Each cell becomes a polygon. Where the graph says a diagonal pair is connected,
those two cells reach across the lattice corner to meet and the other two are
notched back, so a one-cell diagonal becomes a genuinely connected ribbon of
area instead of a chain of corner-touching squares.

The cells still tile the plane *exactly*. That is load-bearing: it is what lets
the resampler compute coverage that sums to one.

`cells.py`, `contours.py`

### 3. Idealisation — the part that matters

For each boundary polyline we compute its **tangential cover**: every maximal
run of boundary edges that a single straight line can explain. Then each vertex
is *moved* onto the line or curve it was digitising. No vertex is deleted, so
neighbouring cells keep sharing them and the plane stays exactly tiled.

Two ideas make this work.

**Segmentation** uses the classical arithmetic digital-straight-segment test on
the crack path's own vertices. This is the part that must break at a corner,
and it does.

**Fitting** does *not* use those vertices. Fitting a staircase's corner points
is badly conditioned — the crack path contains the steps perpendicular to the
edge as well as along it, and including one step at either end drags the fit
off by a quarter cell, enough to shrink every curve in the picture by half a
cell. Instead we ask the question that was actually being answered: *where is
the line that puts these cells on this side and those cells on that side?* A run
is straight exactly when such a line exists, which is a 2-D linear program in
(slope, intercept), and the answer we take is the **maximum-margin** member of
the feasible set — the line best supported by the evidence, and the one least
likely to flip a cell when the grid is turned.

Consequences:

* **Every rational slope is recovered exactly.** 1:1, 2:1, 7:2, 9:5 — a shallow
  6:1 edge is understood as one straight line, not a flight of steps. cleanEdge
  structurally cannot do this; its pattern table stops at 2:1.
* **A flat edge reconstructs at exactly the cell boundary**, with margin 0.5.
* **Curves come back as curves** — but only where the boundary is bending the
  same way on both sides of a joint. An isolated gentle bend between two long
  straight runs is a slope change, not an arc, and blending across it bows an
  edge that was drawn straight.
* **Corners stay perfectly sharp**, placed at the intersection of the two edges.
* **Junctions** where three or more regions meet can be placed at the
  least-squares meeting point of the edges running into them.

`dss.py`, `idealize.py`

### 4. Rotation

The reconstruction is rotated about an arbitrary, sub-cell pivot. Because it is
built once and reused, a turn sequence is self-consistent — frames evolve from
one shape rather than from a fresh guess per frame. Whole quarter turns that
land on the lattice are detected and handled as index permutations, so
0°/90°/180°/270° are exact rearrangements of the source.

`transform.py`

### 5. Exact-area resampling

For every output cell we compute the **exact** fraction of its unit square
covered by each source region, by analytic polygon clipping. Because the input
really is a partition, the fractions sum to 1. Every other rotator point-samples
here; RotSprite approximates it by supersampling 8× and voting.

`raster.py`

### 6. Structural labelling

Taking the argmax of that coverage is already better than any point sample, but
it is still a per-cell decision — and per-cell decisions are how rotators break
one-cell outlines in half and scatter loose specks into the background.

So the argmax is only the starting point. We then require the output to keep the
**component structure** of the source: every connected blob of one item appears
as exactly one connected blob in the output — not zero (a feature deleted), not
two (a line broken). Breaks are repaired along the cheapest route in coverage
terms via Dijkstra; blobs with no ancestor are pruned. Enclosed empty blobs —
holes — are protected the same way.

`label.py`

---

## Measuring it

Claims about rotation quality are usually claims about taste. This repo scores
against a **known-correct target** instead. `tools/synth.py` defines shapes in
continuous space — discs, rings, a fan of bars at eight rational slopes, a thin
arc, a star, colour wedges, a shaded sphere, a checkerboard. For each, the ideal
rasterisation at angle 0 is a plausible input, and the ideal rasterisation at
angle θ is what a perfect rotator would produce.

### Results

Mean disagreement with ground truth, counted only on cells either side calls
solid. Lower is better.

**Grid-aligned** — edges on integer coordinates, the way art is usually drawn:

```
shape          reconstruct    cleanedge    rotsprite         area  supersample      nearest
disc                0.0176       0.0336       0.0257       0.0337       0.0377       0.0452
ring                0.0530       0.1003       0.0721       0.1164       0.1344       0.1955
square              0.0017       0.0017       0.0066       0.0017       0.0033       0.0033
diamond             0.1219       0.1217       0.1180       0.1179       0.1208       0.1230
slopefan            0.1942       0.2022       0.2147       0.2657       0.3170       0.3410
thinarc             0.2044       0.2315       0.2533       0.2825       0.2868       0.3398
glyph               0.0009       0.0018       0.0189       0.0009       0.0027       0.0027
star                0.0275       0.0459       0.0403       0.0619       0.0630       0.0822
wedges              0.0362       0.0306       0.0361       0.0369       0.0369       0.0442
shaded              0.0387       0.0557       0.0520       0.0603       0.0642       0.0754
checker             0.0523       0.1041       0.0906       0.0494       0.0293       0.0373
-------------------------------------------------------------------------------------------
MEAN err            0.0680       0.0845       0.0844       0.0934       0.0996       0.1172
MEAN IoU            0.9411       0.9260       0.9251       0.9171       0.9115       0.8952
```

Two results in there are worth noticing. `checker` is won by `supersample` and
`area`, not by the reconstructors: a rotated checkerboard is close to noise, and
trying to recover structure from it does more harm than good. And `area` beats
`rotsprite` and `cleanedge` on `glyph`, `diamond` and `checker` while being
simpler than either — exact coverage is worth a lot on its own, before any
edge reconstruction.

**Phase-averaged** — the same shapes at five sub-pixel offsets, 440 rotations
per method. An edge on an integer coordinate sits at one *extreme* of the band
of lines its raster is consistent with, so scoring only that alignment rewards
whichever bias happens to match. Averaging removes the privilege, and the task
gets genuinely harder for everyone:

```
MEAN err            0.1726          0.1356          0.1350        0.1249
MEAN IoU            0.8452          0.8772          0.8789        0.8870
```

### Detail retention

Across real sprites at four angles, the sources contain 1144 deliberate
single-cell details. `reconstruct` keeps essentially all of them; RotSprite
loses 19% and cleanEdge 13%. A rotator that smooths away eye dots and specular
highlights scores well on "tidiness" metrics while damaging the artwork.

### What is *not* winnable

`square` and `glyph` score the same for **every** method including nearest
neighbour once phases are averaged. A rectangle of integer cell width rasterises
identically at every sub-cell phase, so the raster carries no information about
which phase produced it; the reconstruction minimising expected error is the
centre of the feasible band, which is exactly what the maximum-margin separator
returns. There is nothing left to win there.

`checker` is similar — a rotated checkerboard is close to noise. `slopefan`'s
residual is single cells at bar endpoints: with a one-cell-wide feature, any
half-cell difference flips cells along its whole length.

### Performance

`reconstruct` builds its geometry once per grid and reuses it for every angle.
Cost is roughly linear in cell count, at 12–27 µs per cell per frame:

| grid | prepare | per frame | 64-frame turn |
|---|---|---|---|
| 32×32 | 0.15 s | 0.012 s | ~1 s |
| 35×30 | 0.08 s | 0.028 s | ~2 s |
| 100×84 | 1.0 s | 0.19 s | ~12 s (~3 s on 8 cores) |

`Rotator.frames(..., workers=N)` forks, so the children inherit the prepared
geometry and the results are identical to the serial path.

This is a pre-computation tool. A 512×512 grid extrapolates to roughly five
seconds a frame, which is fine for baking a turn sequence and not fine for
anything interactive. See `docs/ANALYSIS.md` for what would change that.

On the 440-rotation benchmark above, `reconstruct` takes 5.0 s against 16.0 s
for `cleanedge` and 20.0 s for `rotsprite` — but read that as a comparison of
*these* implementations, not of the algorithms in general: cleanEdge is a GPU
shader in its native form and RotSprite has fast native implementations. What
it does show is that the highest-quality option here is not the slow one.

### Running the tools

```bash
python3 tools/report.py            # everything above, all algorithms
python3 tools/phase_score.py       # reconstruct alone, large sample
python3 tools/roundtrip.py         # real-sprite round trip
python3 tools/sweep.py             # grid-search the options
python3 tools/errmap.py disc,star  # where the disagreements are, visually
python3 tools/conformance.py check # every recorded case still matches
python3 tests/test_rotau.py        # invariants
```

The tools use numpy and Pillow; the library does not.

### Working from a checkout

The package lives under `src/`, so it is not importable from the repository
root until it is installed. For the CLI and the tools, either install it
editable or point `PYTHONPATH` at the source tree:

```bash
pip install -e .                      # then: rotau in.png --angle 37
PYTHONPATH=src python3 -m rotau --help   # or, without installing
```

`tests/` and `tools/` add `src/` to the path themselves, so `pytest tests/`
and the scripts above work either way.

Linting and type checking are configured in `pyproject.toml`:

```bash
ruff check .        # lint
ruff format .       # format
mypy                # type check (files = src/rotau)
```

---

## Options

| option | default | what it does |
|---|---|---|
| `pivot_mode` | `"index"` | pivots are cell indices and stay whole numbers. `"exact"` for continuous, sub-cell coordinates |
| `fit` | `"content"` | trim empty edges off the output. `"source"` keeps the whole rotated source rectangle. Ignored when `size` is given |
| `similar` | `None` | looser test than `==` for "same feature". Leave `None` for material IDs |
| `priority` | `None` | ranking to break ties between overlapping features (cleanEdge only) |
| `distance` | `None` | how far apart two items are (cleanEdge only) |
| `corner_angle` | 20° | turns sharper than this are corners, gentler ones curve |
| `curve_min_run` | 4 | consecutive same-way bends before a joint counts as a curve. 1 bows straight edges; very high effectively disables curves |
| `cover_mode` | `"sep"` | `"path"` segments by the classical DSS test, `"dual"` uses path for corners and separability for fitting |
| `max_move` | 0.5 | how far a boundary vertex may slide. **Do not raise above 0.5 casually**: below half a cell a vertex cannot leave the four cells meeting at its corner, so the tiling provably cannot fold. Above it, cells can overlap — and a fold produces an overlap and a gap of exactly equal area, so no area or simple-polygon check will catch it |
| `structural` | `True` | set `False` for plain coverage argmax |
| `keep_holes` | `True` | protect enclosed empty blobs |
| `thin_boost` | `0.0` | extra coverage weight for hairline features — cleanEdge's `lineWidth` knob. Costs fidelity against ground truth, so off by default |

---

## A native core

`rust/` holds a dependency-free Rust port of the numeric core, validated
against the same conformance corpus — **all six algorithms, all 448 cases,
bit-identical to the Python**. On a 100×100 grid:

| algorithm | Python | Rust | |
|---|---|---|---|
| `nearest` | 0.0038 s | 0.0003 s | 13× |
| `supersample` | 0.2967 s | 0.0100 s | 30× |
| `area` | 0.1763 s | 0.0033 s | 53× |
| `rotsprite` | 0.4157 s | 0.0108 s | 38× |
| `cleanedge` | 0.2415 s | 0.0019 s | **127×** |
| `reconstruct` | 0.6916 s | 0.0412 s | 17× |

Built once and reused, `reconstruct` turns a 512×512 grid in 55 ms a frame
after a 0.7 s prepare — a size the Python cannot reach.

It ports cleanly because the core works on dense integer labels, never on
items: interning belongs to the binding layer, so the crate is `&[u32]` in and
`Vec<u32>` out with no generics. See `rust/README.md`.

### Using it from Python

The Rust crate builds a `cdylib` exposing a flat C ABI, which `rotau` loads
through `ctypes` — standard library, so **the package keeps its zero
dependencies** whether or not the native core is present.

```bash
cd rust && cargo build --release      # produces librotau.so / .dylib / .dll
```

It is then found automatically (next to the package, or in `rust/target/release`
from a checkout, or wherever `$ROTAU_NATIVE` points):

```python
import rotau

rotau.native_available()  # True
rotau.rotate_grid(grid, 37.0)  # backend="auto": native
rotau.rotate_grid(grid, 37.0, backend="python")  # force the reference

rot = rotau.Rotator(grid)  # also native
rot.uses_native  # True
```

`Rotator` gets a native *prepared handle*, so the geometry is built once inside
the core and reused per angle — the amortisation the class exists for happens
on the fast path too. When the native core is used the Python geometry is never
built at all; it is constructed lazily only if something asks for it.

End-to-end through Python, including marshalling, for `reconstruct` on a
120×120 grid:

| | Python | native |
|---|---|---|
| `Rotator(...)` build | 0.837 s | 0.067 s (12×) |
| then per frame | 0.0492 s | 0.0026 s (19×) |
| one-shot `rotate_grid` 256×256 | 2.845 s | 0.200 s (14×) |

The two backends are interchangeable, and a test asserts it over all 448
conformance cases — `auto` only ever changes how long it takes, never what you
get. The binding declines anything it cannot reproduce exactly rather than
approximating it: a custom `similar`, or a custom `priority`/`distance` with
`cleanedge`, is a Python callable that cannot cross a C boundary, so those fall
back to the reference implementation. `--backend native` on the CLI says so and
exits non-zero instead of silently doing something else.

The same ABI serves C, C++ and any engine that can load a shared library.

## Conformance corpus

`tests/conformance.json` pins 448 fully specified cases — grid, angle, pivot,
canvas, algorithm, options — to their exact expected output, in plain JSON with
integer items and run-length encoding. No image data, no floats in the grids.

It exists so that "it still behaves the same" is something you can *run*, not
something you believe. Any reimplementation — a Rust core, a TypeScript port, a
rewrite of this one — can be validated against it with a runner written in an
afternoon. That is not hypothetical: the numpy-to-stdlib rewrite of this
library was proven bit-for-bit identical over 192 rotations before it was
committed, which is the only reason it could be.

```bash
python3 tools/conformance.py generate   # rewrite it after an intended change
python3 tools/conformance.py check      # verify the current code
```

## Invariants under test

Thirty-one tests, none of which need a third-party package:

* **no item is ever invented** — for every algorithm, at every angle
* items need not be colours: strings, ints, tuples, enum members
* 0/90/180/270 are exact rearrangements, for every algorithm
* the pivot lands exactly where asked, and the inverse map round-trips
* the library imports and runs with numpy and Pillow **hard-blocked**
* cells tile the plane exactly, before and after idealisation
* no cell ever inverts or folds into a bow tie
* coverage never exceeds one, across every sprite, angle and canvas
* no connected feature is deleted; holes survive
* rotation by 0° into the same grid reproduces the source exactly
* every rational slope is recognised as a single straight segment
* a flat edge is not pulled inward
* dither is told apart from a one-cell diagonal
* parallel frame rendering matches serial exactly
* every name in `__all__` resolves and every registered algorithm is described
* all 448 conformance cases still produce their recorded output
* the native backend, when present, matches the pure-Python path exactly —
  one-shot and prepared — and declines rather than approximates anything it
  cannot reproduce
* **the result does not depend on the order the geometry is rasterised in** —
  reordering the polygons perturbs a coverage total by an ulp, and without this
  property that is enough to flip an argmax, reseed a repair and cascade into a
  dozen cells. A port in another language would otherwise have to reproduce
  Python's summation order to agree

---

## Credits

* torcado — [cleanEdge](https://torcado.com/cleanEdge/) (MIT), ported here and
  the direct inspiration for this project. See `THIRD-PARTY.md`.
* Xenowhirl — RotSprite (2007).
* Johannes Kopf & Dani Lischinski — *Depixelizing Pixel Art* (SIGGRAPH 2011),
  source of the similarity graph and its crossing heuristics.
* Test sprites are CC0 / CC-BY assets from OpenGameArt and Kenney; see
  `assets/real/SOURCES.md`.

## Three packages, one version

The same core ships to three registries, always on the same version number:

| registry | install | what it is |
| --- | --- | --- |
| PyPI | `pip install rotau` | Python package; the Rust core via ctypes, pure-Python fallback |
| npm | `npm install rotau` | the core as WebAssembly, fully typed for TypeScript |
| crates.io | `cargo add rotau` | the Rust core itself |

All three are held to the same 448-case conformance corpus and produce
**bit-identical output** — same canvas, same pivot, same cell values.

The npm package is one self-contained WebAssembly module with no imports,
inlined into the JS, so it needs no loader config and behaves the same in Node,
Deno, Bun and the browser. Build it from a checkout with:

```bash
cargo build --release --target wasm32-unknown-unknown --manifest-path rust/Cargo.toml
cd js && node tools/embed.mjs && npm install && npm test
```

`npm test` runs the corpus and type-checks the declarations under `strict`,
including cases that must *fail* to compile.

## Publishing

`pip install rotau` should not need a Rust toolchain, so releases ship a
pre-built shared library per platform. The artifact is a plain C library
loaded through ctypes, not a CPython extension, so it carries no ABI tie to a
Python version: one `py3-none-<platform>` wheel per platform covers every
interpreter.

### From your machine

```bash
cp .env.example .env && chmod 600 .env   # once: fill in the tokens you want

./release.sh --dry-run        # build and verify, upload nothing
./release.sh --test           # TestPyPI + npm/cargo dry runs
./release.sh                  # bump the patch version and publish everywhere
./release.sh --bump minor     # 0.1.3 -> 0.2.0
./release.sh --only pypi,npm  # just these registries
```

It bumps the version in all four files that carry one and reads them back to
confirm they agree, runs all three conformance corpora and the test suites,
builds, retags the wheel, installs it into a scratch venv to prove it works,
and only then asks you to type the version to confirm. A run that does not
publish — a failing check, `--dry-run`, `--test`, a declined prompt, Ctrl-C —
puts every version back where it found it and leaves git alone.

Credentials come from `.env` (gitignored). A registry whose token is blank is
skipped with a warning rather than failing, so you can publish to one, two or
all three. There is no transaction across registries, so if one upload fails
the summary names exactly which ones went live, and `--only` retries the rest
without burning another version.

**A version is permanent.** Once `0.1.0` is on PyPI you cannot overwrite it,
and deleting it does not free the number. That is why the script bumps rather
than republishes, and why it refuses a version that already exists before
wasting a build on it. Use `--test` to practise.

### From CI

`.github/workflows/release.yml` builds all of them, plus the sdist, and
publishes on a `v*` tag through PyPI trusted publishing (no token stored
anywhere). Run it manually first and inspect the artifacts.

One trap worth knowing: a wheel built locally is tagged `linux_x86_64`, and
**PyPI rejects that tag** — only `manylinux`/`musllinux` are accepted. Nothing
is vendored into the wheel, so a retag is enough:

```bash
python -m wheel tags --platform-tag manylinux_2_35_x86_64 --remove dist/*.whl
```

Match the tag to the oldest glibc the library was built against —
`auditwheel show dist/*.whl` reports it. The release workflow builds inside a
manylinux2014 image so the floor is glibc 2.17 rather than whatever the build
machine happens to have.

The sdist has no such restriction and can always be uploaded on its own; it
compiles the core on the user's machine, or falls back to pure Python if no
toolchain is present.

---

## Licence

Public domain — [the Unlicense](https://unlicense.org). Copy it, sell it, ship
it, relicense it, no attribution required.

One exception, because it is not ours to give away: the `cleanedge` algorithm
is a port of torcado's MIT-licensed shader, so that algorithm keeps its MIT
notice (see `THIRD-PARTY.md`). The other five have no third-party provenance,
so deleting `cleanedge` leaves a package with no obligations at all.
