Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ Sources/Mapnik/
├── Mapnik.swift # public entry point: stylesheet loading, tile
│ # rendering, free-form rendering, SVG/PDF/PS,
│ # layers, palettes, metatile rendering, XML round trip
├── Metatile.swift # Metatile block descriptor, MetatileOptions,
│ # MetatileRendered (crop + encode from raw RGBA)
├── Metatile.swift # Metatile block descriptor, MetatileRendered
│ # (crop + encode from raw RGBA)
├── RenderOptions.swift # ImageFormat (mapnik type strings) + RenderOptions
├── MapnikConfig.swift # one-time global init (plugin + font paths)
├── MapnikDatasource.swift # datasource from parameters + inspect() → DatasourceInfo
Expand Down
13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,18 +156,21 @@ try map.renderPostScript(to: url) // .ps output
A metatile is a block of N×N XYZ tiles rendered as one image in a single pass. This halves (quarters, ...) the number of datasource queries — a 4×4 metatile needs one query per layer instead of 16 — and lets mapnik's label placement (collision detection) see the whole block, so labels no longer clip at tile edges inside the block. Tile servers use this technique to keep label rendering consistent across tile boundaries.

```swift
// Render a 4×4 block starting at tile (1080, 712)
let metatile = try map.renderMetatile(origin: MapTile(x: 1080, y: 712, z: 11), metaSize: 4)
// A 4×4 block starting at tile (1080, 712)
let block = try Metatile(origin: MapTile(x: 1080, y: 712, z: 11), metaSize: 4)

// Crop individual tiles out of the block on demand (WebP by default)
// Render it; RenderOptions controls the per-tile rendering only
let metatile = try map.renderMetatile(block, options: .tile(format: .png()))

// Crop individual tiles out of the block on demand
let tile = try metatile?.tile(at: MapTile(x: 1082, y: 715, z: 11))
try tile?.write(to: outputURL)

// Or by offset within the block
let byOffset = try metatile?.tile(dx: 2, dy: 3, format: .png256)
```

`MetatileOptions` controls the block size (`metaSize`, 1...16) and the per-tile `RenderOptions` (tile size, scale factor, format, buffer). The rendered block is returned as a `MetatileRendered` holding the raw RGBA pixels; crop tiles out of it, then drop it. A fully transparent block returns `nil`, like `renderTile`.
The block size comes from `Metatile.metaSize` (1...16); `RenderOptions` only controls the per-tile rendering (tile size, scale factor, format, buffer), so there is a single source of truth for the block dimensions. The rendered block is returned as a `MetatileRendered` holding the raw RGBA pixels; crop tiles out of it, then drop it. A fully transparent block returns `nil`, like `renderTile`.

Like `renderTile`, the block is always rendered in Web Mercator XYZ geometry regardless of the map's SRS. The buffer (padding) applies around the whole block, not per tile — raise `bufferSize` if edge padding matters for your style.

Expand Down Expand Up @@ -391,7 +394,7 @@ Sources/Mapnik/
├── Mapnik.swift # map lifecycle, tile/metatile/free-form/vector
│ # rendering, XML round trip, layers, palettes
├── RenderOptions.swift # ImageFormat + RenderOptions
├── Metatile.swift # Metatile, MetatileOptions, MetatileRendered
├── Metatile.swift # Metatile, MetatileRendered
├── MapnikConfig.swift # one-time global init (plugins + fonts)
├── MapnikDatasource.swift# datasource from parameters + inspect()
├── MapnikError.swift # error type bridging the C error strings
Expand Down
76 changes: 29 additions & 47 deletions Sources/Mapnik/Mapnik.swift
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,11 @@ public final class Mapnik: @unchecked Sendable {
/// The individual tiles are cropped out of the returned
/// `MetatileRendered` on demand.
///
/// The block's size comes from `metatile.metaSize`; `options` only
/// controls the per-tile rendering (size, scale, format, buffer). Only the
/// origin and block size of `metatile` matter here — its tile list is
/// ignored, so crop what you need from the result.
///
/// Like `renderTile`, the block is always rendered in Web Mercator XYZ
/// geometry regardless of the map's `srs`. The render options' buffer
/// (padding) applies around the whole block, not per tile — with the
Expand All @@ -363,54 +368,22 @@ public final class Mapnik: @unchecked Sendable {
/// style.
///
/// - Parameters:
/// - origin: The block's top-left (north-west) tile.
/// - metaSize: Tiles per metatile edge, 1...16.
/// - options: Per-tile render options (tile size, scale, format, buffer).
/// - metatile: The block to render; only `origin` and `metaSize` are
/// used.
/// - options: Per-tile render options (tile size, scale, format,
/// buffer).
/// - Returns: The rendered metatile, or `nil` if the whole block is fully
/// transparent and `skipFullyTransparent` is set.
/// - Throws: `MapnikError.invalidInput` for out-of-range tiles or options,
/// `MapnikError.renderingFailed` if rendering failed.
public func renderMetatile(
origin: MapTile,
metaSize: Int,
options: RenderOptions = .tile(),
) throws -> MetatileRendered? {
guard metaSize >= 1, metaSize <= MetatileOptions.maxMetaSize else {
throw MapnikError.invalidInput(
"metaSize must be in 1...\(MetatileOptions.maxMetaSize), got \(metaSize)")
}

return try renderMetatile(Metatile(
origin: origin,
metaSize: metaSize,
tiles: []), options: options)
}

/// Renders the tiles of a `Metatile` block in one pass.
///
/// Only the origin and block size of `metatile` matter for rendering;
/// its tile list is ignored (crop what you need from the result).
public func renderMetatile(
_ metatile: Metatile,
options: RenderOptions = .tile(),
) throws -> MetatileRendered? {
try renderMetatile(metatile, options: MetatileOptions(metaSize: metatile.metaSize, render: options))
}

/// Renders a metatile with full option control.
public func renderMetatile(
_ metatile: Metatile,
options: MetatileOptions,
) throws -> MetatileRendered? {
try options.validate()
guard options.metaSize == metatile.metaSize else {
throw MapnikError.invalidInput(
"options.metaSize (\(options.metaSize)) does not match the metatile's metaSize (\(metatile.metaSize))")
}

try validateMetatile(metatile)
try validateMetatile(metatile, options: options)

let previousBuffer = applyBuffer(options.render.bufferSize)
let previousBuffer = applyBuffer(options.bufferSize)
defer {
if let previousBuffer {
setBufferSize(previousBuffer)
Expand All @@ -429,11 +402,11 @@ public final class Mapnik: @unchecked Sendable {
Int32(clamping: metatile.origin.x),
Int32(clamping: metatile.origin.y),
Int32(clamping: metatile.origin.z),
Int32(clamping: options.render.width),
Int32(clamping: options.render.height),
options.render.scale,
Int32(clamping: options.metaSize),
options.render.skipFullyTransparent,
Int32(clamping: options.width),
Int32(clamping: options.height),
options.scale,
Int32(clamping: metatile.metaSize),
options.skipFullyTransparent,
&data,
&size,
&width,
Expand All @@ -446,7 +419,7 @@ public final class Mapnik: @unchecked Sendable {
throw MapnikError.renderingFailed("metatile render produced no output")
}

if isEmpty, options.render.skipFullyTransparent {
if isEmpty, options.skipFullyTransparent {
if let data {
mapnik_free_buffer(data)
}
Expand All @@ -467,8 +440,8 @@ public final class Mapnik: @unchecked Sendable {

return MetatileRendered(
origin: metatile.origin,
metaSize: options.metaSize,
options: options.render,
metaSize: metatile.metaSize,
options: options,
width: Int(width),
height: Int(height),
isFullyTransparent: isEmpty,
Expand Down Expand Up @@ -1270,7 +1243,7 @@ public final class Mapnik: @unchecked Sendable {

/// Throws `MapnikError.invalidInput` unless the whole metatile block is
/// inside the XYZ grid.
private func validateMetatile(_ metatile: Metatile) throws {
private func validateMetatile(_ metatile: Metatile, options: RenderOptions) throws {
try validateTile(metatile.origin)
let count = 1 << metatile.origin.z
guard metatile.origin.x + metatile.metaSize <= count,
Expand All @@ -1280,6 +1253,15 @@ public final class Mapnik: @unchecked Sendable {
"metatile block (\(metatile.origin.x), \(metatile.origin.y)) + "
+ "\(metatile.metaSize)×\(metatile.metaSize) exceeds the tile grid for zoom \(metatile.origin.z)")
}

// Guard against a block whose pixel buffer would not fit in memory.
guard let pixels = metatile.pixelSize(for: options),
Int64(pixels.width) * Int64(pixels.height) * 4 <= Int64(Int32.max)
else {
throw MapnikError.invalidInput(
"metatile pixel size for \(options.width)×\(options.height) at scale "
+ "\(options.scale) is out of range")
}
}

/// Zooms to the layer extent if the map has no usable extent yet.
Expand Down
97 changes: 21 additions & 76 deletions Sources/Mapnik/Metatile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,99 +88,44 @@ public struct Metatile: Sendable, Hashable {

}

/// Options controlling metatile rendering.
/// The pixel dimensions a metatile would have.
///
/// A metatile is a block of `metaSize` × `metaSize` tiles rendered as one
/// image in a single pass: one datasource query per layer instead of one per
/// tile, and label placement (collision detection) sees the whole block, so
/// labels no longer clip at tile edges inside the block.
///
/// ```swift
/// let options = MetatileOptions(metaSize: 4, render: .tile(format: .png()))
/// let block = Metatile(origin: MapTile(x: 1080, y: 712, z: 11), metaSize: 4)
/// let metatile = try map.renderMetatile(block, options: options)
/// let block = try Metatile(origin: MapTile(x: 1080, y: 712, z: 11), metaSize: 4)
/// let metatile = try map.renderMetatile(block, options: .tile(format: .png()))
/// let tile = try metatile?.tile(at: MapTile(x: 1082, y: 715, z: 11)) // crop one tile
/// ```
public struct MetatileOptions: Sendable {

/// The number of tiles per metatile edge. 1 renders plain tiles; 4 and 8
/// are common tile-server values. Larger blocks reduce datasource queries
/// further but hold more pixels in memory.
///
/// The maximum is 16 (a 16 × 16 metatile of 256-pixel tiles at scale 2
/// already holds 8192² pixels = 256 MB of RGBA data).
public static let maxMetaSize = Metatile.maxMetaSize

/// Tiles per metatile edge.
public var metaSize: Int

/// Per-tile render options: `width`/`height` are the tile edge lengths in
/// pixels, `scale` the scale factor, `format` the output format used when
/// cropping, `bufferSize` the padding applied around the whole metatile.
public var render: RenderOptions

/// Creates metatile options.
///
/// The values are validated when the options are used by a render call,
/// so this initializer stays non-throwing (it is used as a default
/// argument). Call ``validated(metaSize:render:)`` when you want the error
/// at the point of construction.
public init(metaSize: Int = 4, render: RenderOptions = .tile()) {
self.metaSize = metaSize
self.render = render
}

/// Creates metatile options and validates them immediately.
///
/// - Throws: `MapnikError.invalidInput` for out-of-range values.
public static func validated(
metaSize: Int = 4,
render: RenderOptions = .tile(),
) throws -> MetatileOptions {
let options = MetatileOptions(metaSize: metaSize, render: render)
try options.validate()
return options
}
extension Metatile {

/// The metatile's pixel dimensions (`metaSize * width * scale` by
/// `metaSize * height * scale`).
public var metatileWidth: Int {
Int(Double(render.width) * render.scale) * metaSize
}

/// The metatile's pixel height (`metaSize * height * scale`).
public var metatileHeight: Int {
Int(Double(render.height) * render.scale) * metaSize
}

/// The metatile's pixel dimensions, assuming square tiles.
/// `metaSize * height * scale`) for the given render options.
///
/// Use ``metatileWidth``/``metatileHeight`` for non-square tiles.
public var metatileSize: Int {
metatileWidth
}

/// Validates the options, throwing `MapnikError.invalidInput` for out of
/// range values.
func validate() throws {
guard metaSize >= 1, metaSize <= Self.maxMetaSize else {
throw MapnikError.invalidInput("metaSize must be in 1...\(Self.maxMetaSize), got \(metaSize)")
/// - Parameter render: The per-tile render options.
/// - Returns: The block's pixel width and height, or `nil` when the
/// dimensions do not fit in an `Int` (for example an enormous `scale`).
public func pixelSize(for render: RenderOptions) -> (width: Int, height: Int)? {
guard let width = Self.pixels(render.width, render.scale, metaSize: metaSize),
let height = Self.pixels(render.height, render.scale, metaSize: metaSize)
else {
return nil
}

try render.validate()
try Self.validatePixelSize(render.width, render.scale, metaSize: metaSize)
try Self.validatePixelSize(render.height, render.scale, metaSize: metaSize)
return (width, height)
}

/// Throws when `edge * scale * metaSize` does not fit in an `Int`.
private static func validatePixelSize(_ edge: Int, _ scale: Double, metaSize: Int) throws {
let pixels = Double(edge) * scale
guard pixels > 0, pixels.isFinite,
pixels * Double(metaSize) <= Double(Int.max)
else {
throw MapnikError.invalidInput(
"tile size × scale × metaSize is out of range, got \(edge) × \(scale) × \(metaSize)")
/// `edge * scale * metaSize` as an `Int`, or `nil` when it does not fit.
private static func pixels(_ edge: Int, _ scale: Double, metaSize: Int) -> Int? {
let value = (Double(edge) * scale).rounded() * Double(metaSize)
guard value.isFinite, value > 0, value <= Double(Int.max) else {
return nil
}

return Int(value)
}

}
Expand Down
8 changes: 4 additions & 4 deletions Sources/Mapnik/TileSequence.swift
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ public struct MetatileSequence: Sequence, Sendable {
/// - Parameters:
/// - bounds: The area to cover, in WGS 84 degrees.
/// - zoomRange: The zoom levels to visit, 0...30.
/// - metaSize: Tiles per metatile edge, 1...``MetatileOptions/maxMetaSize``.
/// - metaSize: Tiles per metatile edge, 1...``Metatile/maxMetaSize``.
/// - zoomOrder: The order in which zoom levels are visited.
/// - Throws: `MapnikError.invalidInput` when `metaSize` or the zoom range
/// is out of range.
Expand All @@ -300,9 +300,9 @@ public struct MetatileSequence: Sequence, Sendable {
metaSize: Int = 4,
zoomOrder: TileSequence.ZoomOrder = .descending,
) throws {
guard metaSize >= 1, metaSize <= MetatileOptions.maxMetaSize else {
guard metaSize >= 1, metaSize <= Metatile.maxMetaSize else {
throw MapnikError.invalidInput(
"metaSize must be in 1...\(MetatileOptions.maxMetaSize), got \(metaSize)")
"metaSize must be in 1...\(Metatile.maxMetaSize), got \(metaSize)")
}
guard zoomRange.lowerBound >= 0, zoomRange.upperBound <= 30 else {
throw MapnikError.invalidInput(
Expand Down Expand Up @@ -336,7 +336,7 @@ public struct MetatileSequence: Sequence, Sendable {
/// - x: Tile column.
/// - y: Tile row.
/// - zoom: Zoom level of the tile; stored on the returned origin so it
/// can be passed to `Mapnik.renderMetatile(origin:metaSize:)`.
/// can be passed to `Mapnik.renderMetatile(_:options:)`.
public func metatileOrigin(forX x: Int, forY y: Int, atZoom zoom: Int) -> MapTile {
MapTile(
x: x - ((x % metaSize) + metaSize) % metaSize,
Expand Down
2 changes: 1 addition & 1 deletion Tests/MapnikTests/MapnikTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ struct MapnikTests {
_ = try map.renderPNG256(colors: [0xFFFF_0000])
#expect(map.bufferSize == 16)

_ = try map.renderMetatile(origin: Fixtures.europeTile, metaSize: 2, options: RenderOptions(width: 256, height: 256, bufferSize: 32, format: .png()))
_ = try map.renderMetatile(Metatile(origin: Fixtures.europeTile, metaSize: 2), options: RenderOptions(width: 256, height: 256, bufferSize: 32, format: .png()))
#expect(map.bufferSize == 16)

// Renders without an explicit buffer keep the stylesheet's value.
Expand Down
Loading
Loading