Introducing a new way to review your PRs.

Read the announcement

maplibre / martin

Blazing fast and lightweight PostGIS, MBtiles and PMtiles tile server, tile generation, and mbtiles tooling.

View on GitHub

22 documents · Updated Nov 23, 2026

docs / geometry-and-tile-primitives

Geometry and tile primitives

The geometry and tile primitives turn spatial features into tile-local data and back again. Map Tile Toolkit handles integer geometry slicing, safe quantization, and mosaic reassembly. Martin tile utilities define tile addresses, coordinate grids, tile rectangles, geographic bounds, and payload decoding for the services that use those tiles. See the parent page Geospatial tooling for the wider tile flow.

Tile coordinate spaces

Tile work uses two related coordinate spaces. Martin addresses a tile as z/x/y in an XYZ matrix, while Map Tile Toolkit works in integer tile space after projection and scaling. A tile has an extent that is both its side length and its output resolution. The tile's local frame starts at its global origin, and a buffer widens the area that the tile keeps around its edge.

The main contract between these spaces is:

ConceptRole
TileCoordValidated zoom, column, and row address in Martin's XYZ scheme
TileGridCoordinate reference system, world origin, zoom scale, matrix size, and wrap behavior
TileIdInteger tile address used by Map Tile Toolkit during geometry work
extentTile side and integer output range in Map Tile Toolkit
bufferShared margin that lets neighboring tiles keep border geometry
Tile originGlobal coordinate of a tile's local (0, 0) corner

Martin's TileGrid maps a CRS box to a rectangular tile range. Map Tile Toolkit then expects the caller to project, simplify, scale, and round source geometry into integer tile space before slicing. This keeps geographic projection policy in the grid and service layer while keeping geometry operations exact and independent of a specific CRS.

References: martin-tile-utils/…/coordinate.rs• L1-79 martin-tile-utils/…/grid.rs• L123-145 martin-tile-utils/…/grid.rs• L318-367 map-tile-toolkit/…/tile.rs• L1-56 map-tile-toolkit/…/grid.rs• L198-233

Geometry slicing

Slicer divides one line, point, or polygon into the tiles whose buffered boxes the geometry reaches. It returns lazy tile-local views, so a caller can stop early and can keep feature attributes outside the geometry engine. The default clipped mode keeps only the per-tile geometry; unclipped mode reports the same reached tiles but gives each tile the whole geometry for renderers that perform their own clipping.

The slicing flow is:

flowchart LR
    A[Projected and scaled geometry] --> B[Integer tile space]
    B --> C[Tile reach and bounds]
    C --> D{Geometry type}
    D -->|Line| E[Original-vertex runs]
    D -->|Point| F[One to four local points]
    D -->|Polygon| G[Edge pieces and fill runs]
    E --> H[Tile-local output]
    F --> H
    G --> H

Lines are kept as contiguous runs of original vertices. A segment that crosses a tile can appear in that tile even when neither endpoint is inside it. The slicer does not add an interpolated vertex at the tile edge, so the same border-crossing segment remains identical in each tile that carries it. A short excursion outside a tile can remain part of one run, while a longer excursion creates separate runs.

Points use the simpler shared-edge rule. A point belongs to its owner tile and can also appear in neighboring tiles when it lies inside their buffered boxes. The buffer is constrained to less than half the extent, so a point reaches at most four tiles.

Polygons produce a piece for each edge tile and a compact FillRun for consecutive tiles covered by the polygon. Polygon rings keep their input winding. Synthetic corners close clipped rings outside the buffered box, which preserves the area seen by a tile while allowing the reassembly step to remove those synthetic edges. A valid input polygon normally produces a valid standalone piece; malformed input remains bounded by the clipping limits rather than gaining a guarantee of validity.

References: map-tile-toolkit/…/slicer.rs• L1-41 map-tile-toolkit/…/slicer.rs• L56-99 map-tile-toolkit/…/slicer.rs• L157-245 map-tile-toolkit/…/slicer.rs• L266-333 map-tile-toolkit/…/clip_polyline.rs• L1-61 map-tile-toolkit/…/clip_polygon.rs• L1-15 map-tile-toolkit/…/polygon.rs• L1-34

Line and point slices

Line and point slices provide the small, tile-local units consumed by encoders and renderers. Local views subtract the tile origin when they are read, and payloads attached to vertices remain unchanged. This lets a feature id, measure, or other per-vertex value travel with its position without interpolation.

The line and point behavior differs in one important way:

  • A line can yield several runs for one tile if it leaves and later re-enters that tile.
  • A point yields one copy per buffered tile and has no clipped or unclipped mode.

References: map-tile-toolkit/…/slicer.rs• L336-419 map-tile-toolkit/…/slicer.rs• L493-513 map-tile-toolkit/…/slicer.rs• L830-944 map-tile-toolkit/…/vertex.rs• L1-96

Polygon pieces and fill runs

Polygon slicing separates boundary work from interior coverage. Edge tiles receive ring pieces with the rings that reach them. Interior tiles are represented as row spans, so work follows the polygon boundary instead of emitting one event for every covered tile during the scan.

The polygon path uses a row-based view of the shape. It first finds the polygon bounds, then visits rows that the buffered geometry reaches. Each row can identify edge tiles, determine whether the exterior and holes cover the tiles between them, and emit either a piece or a fill span. A fill span can later provide the same closed fill ring for each tile in that span.

References: map-tile-toolkit/…/polygon.rs• L55-114 map-tile-toolkit/…/polygon.rs• L567-610 map-tile-toolkit/…/polygon.rs• L613-695 map-tile-toolkit/…/polygon.rs• L933-1048

Quantized polygon geometry

Quantizer converts floating-point polygon rings in grid units to integer rings without treating rounding as a point-by-point operation only. Independent rounding can make close edges cross, fold, or collapse a narrow part. The quantizer therefore keeps the simple rounded result when it is valid and otherwise rebuilds the covered area on the integer grid.

The quantization choices are:

InputResult
One valid polygonZero or more valid integer polygons after rounding or repair
Several valid partsParts that remain apart stay separate; parts that meet after rounding merge
Any polygon shapemake_valid rebuilds the area described by exterior-minus-hole winding
Degenerate ring after roundingThe ring is dropped; if it is the exterior, that polygon is dropped

Rounding uses ties-to-even behavior. When repair is needed, the quantizer snap-rounds edges through relevant grid points, combines coincident edge contributions, and traces the resulting boundary. This can merge close tips, turn a hole into a notch, drop a collapsed fold, or split a narrow neck into separate polygons. Output rings are open and use positive exterior area with negative hole area.

Quantization is the bridge between floating source geometry and the integer contract required by Slicer. It does not replace projection or simplification, and finite coordinates must still fit the supported integer range.

References: map-tile-toolkit/…/quantize.rs• L1-11 map-tile-toolkit/…/quantize.rs• L261-385 map-tile-toolkit/…/quantize.rs• L404-439 map-tile-toolkit/…/quantize.rs• L442-647 map-tile-toolkit/…/quantize.rs• L722-730

Geometry mosaics

Mosaic and PolygonMosaic reassemble tile-local results into global features. They reverse the tile-origin shift and index directed edges so overlapping copies collapse into one geometry. The mosaic can accept tiles in any order and can replace or remove a tile without rebuilding all other contributions.

The relationship between slicing and reassembly is:

sequenceDiagram
    participant S as Slicer
    participant T as Tile store or renderer
    participant M as Mosaic
    S->>T: Emit local runs or polygon pieces
    T->>M: Add tile geometry
    M->>M: Rebase and deduplicate directed edges
    M-->>T: Global stitched features

Mosaic uses every consecutive line edge and needs only the extent. PolygonMosaic keeps only ring edges that touch the tile's buffered box. That rule drops synthetic clip corners, fill boxes, and bridge chords while retaining each real edge in the tile that owns its start. It therefore needs both extent and buffer. A tile that contains only a synthetic fill contributes no edge because polygon interior is represented by ring winding.

The shared-edge contract also detects inconsistent tile sets. A conflict can come from different payloads on the same edge or from a tile that should contain an owned edge but does not. The failed add leaves the mosaic unchanged and identifies the conflicting tile addresses.

References: map-tile-toolkit/…/mosaic.rs• L1-39 map-tile-toolkit/…/mosaic.rs• L51-189 map-tile-toolkit/…/mosaic.rs• L191-285 map-tile-toolkit/…/mosaic.rs• L287-387 map-tile-toolkit/…/mosaic.rs• L411-461

Tile grids and rectangles

Martin's TileGrid describes how a tile address covers a coordinate reference system. It supports built-in Web Mercator, geographic, polar, local projected, and simple planar grids. A grid defines its CRS, top-left origin, zoom-zero size, zoom-zero matrix, and whether columns wrap around the world.

TileGrid::tile_range converts a CRS bounding box into an inclusive TileRect. TileRect is the unit used for tile-area requests and rectangle set management. It can test overlap, count its tiles, and let append_rect split a new rectangle into non-overlapping parts before adding it to a collection.

The grid model preserves the distinction between geographic bounds and tile-space bounds:

  • The grid owns CRS units, axis order, world coverage, and zoom scale.
  • The rectangle owns an inclusive range of tile columns and rows at one zoom.
  • The geometry slicer owns integer local coordinates inside one tile extent.

References: martin-tile-utils/…/grid.rs• L18-121 martin-tile-utils/…/grid.rs• L123-170 martin-tile-utils/…/grid.rs• L183-386 martin-tile-utils/…/rectangle.rs• L1-15 martin-tile-utils/…/rectangle.rs• L48-193

Tile payload decoding

Martin tile utilities treat tile bytes as a format plus an optional external encoding. The format layer distinguishes vector, raster, and JSON payloads. The decoder layer handles gzip, zlib, Brotli, and Zstandard so callers can normalize compressed tile data without changing payload semantics.

Format detection uses raster signatures first, then checks compressed or vector-like content for MLT and JSON, and falls back to MVT when no stronger signal exists. Encoding marked as internal or uncompressed passes through unchanged. Decode failures remain I/O errors rather than becoming geometry errors.

References: martin-tile-utils/…/lib.rs• L37-140 martin-tile-utils/…/lib.rs• L158-214 martin-tile-utils/…/lib.rs• L222-325 martin-tile-utils/…/decoders.rs• L1-87

Exact geometry predicates

The geometry layer supplies exact integer decisions for orientation, ring area, point containment, segment-box contact, and crossing positions. These decisions support clipping, polygon winding, tile coverage, and repair without float error in the integer stage.

signed_area_2x reports ring orientation and supports the MVT convention of positive exterior area and negative hole area in tile coordinates. The slicer preserves input winding, so callers normalize ring roles before slicing when an output format requires a fixed convention. Full-range coordinates use widened arithmetic where needed so boundary decisions do not silently overflow.

References: map-tile-toolkit/…/geom.rs• L1-10 map-tile-toolkit/…/geom.rs• L19-39 map-tile-toolkit/…/geom.rs• L72-115 map-tile-toolkit/…/clip_polyline.rs• L17-49

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the extent, buffer, tile origin, and local-frame rules aligned between Slicer, PolygonMosaic, and any tile encoder.
  • Preserve the rule that synthetic polygon edges stay outside the buffered box, or polygon reassembly can retain clipping artifacts.
  • Keep TileGrid axis order, origin, matrix size, and wrap behavior aligned with conversions to TileRect and TileCoord.
  • If payload or edge identity changes, review mosaic conflict detection because shared edges depend on both endpoint positions and vertex payloads.
  • If format detection or encoding names change, update the Format, Encoding, and decoder contract together.

Important failure modes

TriggerConsequenceGuard
Buffer is at least half the extentTile overlap can reach more than one neighbor per axis and slicing is rejectedCreate the grid with a buffer strictly below half the extent
Geometry or a buffered tile is outside the supported i32 rangeSlicing or reassembly returns Overflow instead of local geometryProject and scale into a range that leaves room for tile buffers and polygon synthetic corners
Rounded polygon edges cross or collapseIndependent rounded rings are replaced by a repaired integer areaUse Quantizer before slicing instead of rounding vertices separately
Tiles disagree on a shared edge or owned membershipMosaic add fails and leaves prior state unchangedFeed tiles made with the same extent, buffer, and feature payload contract
Tile rectangle coordinates use different zoom levelsOverlap logic treats the regions as unrelatedCompare and append rectangles only within the same zoom
Compressed or malformed tile bytes do not match their claimed encodingDecode or format detection fails or falls back to the safe vector defaultUse the matching decoder and treat detection as a content check, not metadata proof

Key files

FileWhy to read it
map-tile-toolkit/…/slicer.rsPublic geometry slicing model, clip modes, local views, and slice contracts
map-tile-toolkit/…/polygon.rsPolygon edge pieces, fill runs, and row-based coverage model
map-tile-toolkit/…/clip_polygon.rsPolygon ring closure and synthetic geometry boundary contract
map-tile-toolkit/…/quantize.rsFloat-to-integer polygon rounding and repair behavior
map-tile-toolkit/…/mosaic.rsTile-to-feature reassembly and shared-edge conflict rules
map-tile-toolkit/…/grid.rsInteger tile boxes, tile walks, buffers, and bounds checks
map-tile-toolkit/…/vertex.rsOriginal vertex and payload preservation model
martin-tile-utils/…/grid.rsCRS tile matrices, built-in grids, and CRS-box to tile-range mapping
martin-tile-utils/…/coordinate.rsValidated XYZ tile addresses
martin-tile-utils/…/rectangle.rsInclusive tile rectangles and non-overlapping rectangle management
martin-tile-utils/…/decoders.rsTile compression and decompression boundaries
martin-tile-utils/…/lib.rsTile formats, encodings, geographic helpers, and format detection