@ml2drender/wasm 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +435 -0
- package/README.md +281 -2
- package/dist/index.d.ts +244 -0
- package/dist/index.js +465 -0
- package/package.json +42 -3
- package/src/wasm.d.ts +3 -0
- package/wasm/ml2drender_wasm.wasm +0 -0
package/README.md
CHANGED
|
@@ -1,3 +1,282 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ml2drender
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**A 2D map renderer for MapLibre styles, written in Rust. It needs no GPU.** It compiles to WebAssembly and runs in browsers, Cloudflare Workers, Deno and Node.js. Node-API and Python bindings are also included.
|
|
4
|
+
|
|
5
|
+
[Live demo](https://kanahiro.github.io/ml2drender/) · [API reference](https://kanahiro.github.io/ml2drender/api/) · [Quick start](#quick-start) · [Projected CRSs](#projected-coordinate-reference-systems) · [Node.js addon](https://github.com/Kanahiro/ml2drender/tree/main/packages/ml2drender-node#readme) · [Python](https://github.com/Kanahiro/ml2drender/tree/main/crates/python#readme)
|
|
6
|
+
|
|
7
|
+
- **No GPU, no native dependencies.** It is a software rasterizer in pure Rust. It runs on `wasm32-unknown-unknown` and links no C libraries.
|
|
8
|
+
- **Faithful to MapLibre.** Bucket building, shader math and quantization are ported from MapLibre GL JS. It passes 98.0% of the applicable upstream render tests at GL JS's own tolerances ([conformance](#conformance)).
|
|
9
|
+
- **Any projected CRS.** It draws maps directly in a CRS given as PROJJSON: UTM, national grids, LAEA, polar stereographic, Equal Earth, geostationary views and more.
|
|
10
|
+
- **MapLibre GL JS in any CRS.** Every source of a style (vector tiles, GeoJSON, raster, DEM) can be reprojected and served on a CRS's tile grid. MapLibre GL JS can then draw the original style in that CRS, with interaction and feature queries.
|
|
11
|
+
- **Made for serverless.** The core does no network or file I/O; the host fetches everything.
|
|
12
|
+
|
|
13
|
+
> [!NOTE]
|
|
14
|
+
> ml2drender draws flat 2D maps. 3D features (fill-extrusion, terrain, globe, pitch) are out of scope; layers of types it does not draw (fill-extrusion) are skipped, so rewrite them in the style beforehand if you want them drawn (for example as fills). Styles are fixed when a renderer is created: there is no API for changing a style at runtime.
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { MapRenderer } from '@ml2drender/wasm';
|
|
20
|
+
|
|
21
|
+
const style = await (await fetch('https://demotiles.maplibre.org/style.json')).json();
|
|
22
|
+
const renderer = await MapRenderer.init(style);
|
|
23
|
+
|
|
24
|
+
const image = await renderer.renderView({ center: [139.767, 35.681], zoom: 5, width: 512, height: 512 });
|
|
25
|
+
const png = image.toPng(); // or image.toWebp(), image.toJpeg(80); raw RGBA in image.data
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The renderer works out which tiles, TileJSON, sprites and glyphs it needs, and fetches them. In browsers (with Vite or similar), the bundled WASM loads automatically. Elsewhere, pass the compiled module as the `wasm` option: `await WebAssembly.compile(readFileSync(new URL(import.meta.resolve('@ml2drender/wasm/renderer.wasm'))))` in Node.js and Deno, or `import wasm from '@ml2drender/wasm/renderer.wasm'` in Cloudflare Workers (Wrangler).
|
|
29
|
+
|
|
30
|
+
### Installation
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
npm install @ml2drender/wasm # WebAssembly: browsers, Node.js, Deno, Workers
|
|
34
|
+
npm install @ml2drender/node # native Node.js addon
|
|
35
|
+
pip install ml2drender # Python
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
| Package | Runs in | API |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| [`@ml2drender/wasm`](#javascript-api) | browsers, Node.js, Deno, Cloudflare Workers | Everything below: fetching, Web Mercator and projected views, reprojected sources for GL JS. |
|
|
41
|
+
| [`@ml2drender/node`](https://github.com/Kanahiro/ml2drender/tree/main/packages/ml2drender-node#readme) | Node.js (Linux, macOS, Windows) | HTTP fetching by default, with an optional `loadResource(url)` callback. Web Mercator cameras; boxes, tiles and cameras of a projected CRS. Renders run in parallel off the JS thread. |
|
|
42
|
+
| [`ml2drender` on PyPI](https://github.com/Kanahiro/ml2drender/tree/main/crates/python#readme) | CPython 3.11+ (Linux, macOS, Windows) | Async HTTP fetching with HTTPX by default, with an optional async `load(url)` callback. Web Mercator cameras; boxes, tiles and cameras of a projected CRS. |
|
|
43
|
+
|
|
44
|
+
All three draw with the same Rust core. To build from source, see [Development](#development).
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
47
|
+
|
|
48
|
+
### Web Mercator images
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
const renderer = await MapRenderer.init(style);
|
|
52
|
+
|
|
53
|
+
await renderer.renderView({ center: [lng, lat], zoom: 12, bearing: 30, width: 800, height: 600 }); // a camera
|
|
54
|
+
await renderer.renderTile({ z: 12, x: 3638, y: 1612 }); // an XYZ tile
|
|
55
|
+
await renderer.render({ bbox: [139.5, 35.5, 140, 36], size: 1024 }); // a lng/lat box
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
In a browser, the pixels of a `RenderedImage` go straight onto a canvas:
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
canvas.getContext('2d')!.putImageData(new ImageData(image.data, image.width, image.height), 0, 0);
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Images in a projected CRS
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
const utm = renderer.projected({
|
|
68
|
+
name: 'EPSG:32654',
|
|
69
|
+
projjson: utm54n, // PROJJSON of EPSG:32654
|
|
70
|
+
tileMatrixSet: { origin: [-2_000_000, 6_000_000], extentAtZoom0: 4_000_000 },
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
await utm.renderView({ center: [139.767, 35.681], zoom: 6, bearing: 30, width: 800, height: 600 }); // a camera
|
|
74
|
+
await utm.render({ bbox: [300_000, 3_900_000, 500_000, 4_100_000], size: 512 }); // a box in CRS units
|
|
75
|
+
await utm.renderTile({ z: 3, x: 4, y: 2 }); // a tile of the CRS's grid
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`renderView` takes `center` as lng/lat and a zoom of the `tileMatrixSet` grid. It draws the same area as MapLibre GL JS does with that `center`, `zoom` and `bearing` once the CRS is registered with `addProjection`.
|
|
79
|
+
|
|
80
|
+
### MapLibre GL JS in any CRS
|
|
81
|
+
|
|
82
|
+
ml2drender returns each source reprojected onto the CRS's tile grid, and MapLibre GL JS draws the original style from those tiles. The CRS is registered with GL JS 6.15's experimental `addProjection`. GL JS draws the map with WebGL, so it stays interactive and features can be queried.
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
// Server (e.g. Workers): serve reprojected tiles of each source
|
|
86
|
+
const crs = { name: 'EPSG:32654', projjson: utm54n, tileMatrixSet };
|
|
87
|
+
const tile = await renderer.projected(crs).getTile({ source, z, x, y }); // MVT, PNG or terrarium PNG
|
|
88
|
+
|
|
89
|
+
// Browser: register the CRS with GL JS and draw the rewritten style
|
|
90
|
+
import { addProjection, Map } from 'maplibre-gl';
|
|
91
|
+
import proj4 from 'proj4';
|
|
92
|
+
|
|
93
|
+
addProjection({ name: crs.name, projection: proj4(crs.projjson), tileMatrixSet: crs.tileMatrixSet });
|
|
94
|
+
const glStyle = renderer.projected(crs).toStyle({ tiles: (source) => `https://tiles.example.com/${source}/{z}/{x}/{y}` });
|
|
95
|
+
new Map({ container: 'map', style: glStyle });
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`addProjection` takes any `forward` / `inverse` pair between lng/lat and CRS coordinates, such as a [proj4js](https://github.com/proj4js/proj4js) converter, which reads PROJJSON. ml2drender draws with its own formulas; for the CRSs of the demo the two agree within a few micrometres. Two things to know:
|
|
99
|
+
|
|
100
|
+
- proj4js does not read the Geostationary Satellite method from PROJJSON. Give it the PROJ string (`+proj=geos ...`) instead, as the [demo](https://github.com/Kanahiro/ml2drender/blob/main/examples/browser/src/proj.ts) does.
|
|
101
|
+
- If GL JS also draws GeoJSON sources itself, its workers need the same converter. Set it with `setProjectionHandler`, as the [demo](https://github.com/Kanahiro/ml2drender/blob/main/examples/browser/src/gl-projection-handler.ts) does.
|
|
102
|
+
|
|
103
|
+
## JavaScript API
|
|
104
|
+
|
|
105
|
+
The `@ml2drender/wasm` package (WebAssembly). This section is an overview. Every type and option is documented in the [API reference](https://kanahiro.github.io/ml2drender/api/).
|
|
106
|
+
|
|
107
|
+
### MapRenderer.init(style, options?)
|
|
108
|
+
|
|
109
|
+
Takes a style object (the official `StyleSpecification` type) and loads the WASM. The style is copied when `init` is called. Resource URLs reach `loadResource` exactly as the style writes them, so make `glyphs` and TileJSON `url`s absolute.
|
|
110
|
+
|
|
111
|
+
| Option | Default | Description |
|
|
112
|
+
|---|---|---|
|
|
113
|
+
| `loadResource` | HTTP `fetch` | `(url) => Promise<Uint8Array \| null>`. Fetches tiles, TileJSON, sprites and glyphs. Return `null` (HTTP 404) for a missing resource and rendering goes on without it; any other failure should reject. Concurrency limits, retries and caching belong here. |
|
|
114
|
+
| `wasm` | bundled WASM | A compiled `WebAssembly.Module`. Required in Node.js and Cloudflare Workers. |
|
|
115
|
+
| `cache.ttlMs` | `300_000` | How long the renderer inside WASM (decoded tiles, geometry, glyphs) is reused across renders. `0` creates and frees one per render, for the least memory; `Infinity` never expires. |
|
|
116
|
+
|
|
117
|
+
Concurrent requests for the same URL are fetched once. Fetched bytes are not cached: rely on the browser's HTTP cache, or cache inside `loadResource` (for example with the Cache API on Workers).
|
|
118
|
+
|
|
119
|
+
Renderers with `cache.ttlMs: 0` share one WASM instance per module, and WASM memory never shrinks. Overlapping renders each hold their decoded data while they wait for fetches, so peak memory grows with the number of renders in flight. Where memory is tight, limit that number yourself:
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import pLimit from 'p-limit';
|
|
123
|
+
|
|
124
|
+
const limit = pLimit(2); // one limit for every renderer of the module
|
|
125
|
+
const image = await limit(() => renderer.renderTile({ z, x, y }));
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Rendering methods
|
|
129
|
+
|
|
130
|
+
Each one fetches what it needs and resolves to a `RenderedImage` of all the style's layers. One renderer can mix views, methods and CRSs, even concurrently, and they share fetched resources.
|
|
131
|
+
|
|
132
|
+
| Method | Area drawn |
|
|
133
|
+
|---|---|
|
|
134
|
+
| `renderView({ center, zoom, bearing?, width, height })` | A Web Mercator camera. Zoom levels are GL JS's: at zoom 0 the world is 512 CSS px wide. |
|
|
135
|
+
| `renderTile({ z, x, y, tileSize? })` | An XYZ tile of the Web Mercator grid. `tileSize` defaults to 256. |
|
|
136
|
+
| `render({ bbox, size })` | A lng/lat box `[west, south, east, north]`, fitted so that its long side is `size` px. `west > east` crosses the antimeridian. |
|
|
137
|
+
| `projected(crs).renderView({ center, zoom, bearing?, width, height })` | A camera in the CRS, with the same arguments as the Mercator `renderView`. `center` is lng/lat. `bearing` is the angle clockwise from the CRS's y axis of the direction that is up, so at 0 the y axis is up. Zoom levels are those of GL JS with the CRS registered by `addProjection`: at zoom 0, tile 0/0/0 of the grid is 512 CSS px wide. A `center` outside the CRS's domain throws a `RangeError`. |
|
|
138
|
+
| `projected(crs).render({ bbox, size })` | A box `[minX, minY, maxX, maxY]` in CRS units (degrees for longlat), y axis up, fitted so that its long side is `size` px. For a rotated view, use `renderView`. |
|
|
139
|
+
| `projected(crs).renderTile({ z, x, y, tileSize? })` | A tile of the CRS's grid. |
|
|
140
|
+
|
|
141
|
+
All of them also accept two options:
|
|
142
|
+
|
|
143
|
+
- `pixelRatio` (default 1): the output has CSS px × `pixelRatio` pixels.
|
|
144
|
+
- `margin` (default 0): extra CSS px drawn on every side and then cropped. This reduces symbols that go missing because their anchor is just outside a tile.
|
|
145
|
+
|
|
146
|
+
A `RenderedImage` has:
|
|
147
|
+
|
|
148
|
+
- `width` and `height`.
|
|
149
|
+
- `data`: row-major RGBA pixels in a `Uint8ClampedArray`.
|
|
150
|
+
- `toPng()` and `toWebp()`: a lossless PNG or WebP, encoded inside WASM. WebP is about 30% smaller than PNG.
|
|
151
|
+
- `toJpeg(quality)`: a JPEG encoded inside WASM. `quality` is 1–100, chroma is subsampled 4:2:0, and transparent pixels become black.
|
|
152
|
+
|
|
153
|
+
### renderer.projected(crs)
|
|
154
|
+
|
|
155
|
+
Returns a `ProjectedRenderer` that draws in `crs`. The original renderer is unchanged. `crs` has the same shape as a CRS registered with MapLibre GL JS's `addProjection`:
|
|
156
|
+
|
|
157
|
+
- `projjson`: the CRS as PROJJSON. `render` of a box needs nothing else.
|
|
158
|
+
- `tileMatrixSet`: `{ origin: [minX, maxY], extentAtZoom0 }`, required by `renderTile`, `getTile` and `renderView`. A CRS has no tile grid of its own, so tiles and zoom levels mean nothing without one. Tile 0/0/0 is a square of side `extentAtZoom0` whose top-left corner is `origin`. Each zoom level splits every tile into four. x grows to the east and y to the south.
|
|
159
|
+
|
|
160
|
+
- `name`: the CRS's name in GL JS, required by `toStyle` only.
|
|
161
|
+
|
|
162
|
+
Projected renders pick a zoom level from CRS units per CSS px, read on EPSG:3857's scale at the equator (the idea behind OGC scale denominators; for longlat, 360° is one trip around the world). That zoom drives style evaluation and source tile selection. It does not depend on position, so tiles of one grid zoom line up at their edges. At high latitudes the zoom is higher than a Mercator map of the same ground resolution would use. It is not the grid zoom given to `renderView`: the two agree only when `extentAtZoom0` is the width of EPSG:3857's world (about 40,075 km, or 360° for longlat).
|
|
163
|
+
|
|
164
|
+
Besides `renderView`, `render` and `renderTile`, it has two methods for MapLibre GL JS:
|
|
165
|
+
|
|
166
|
+
#### getTile({ source, z, x, y })
|
|
167
|
+
|
|
168
|
+
Returns the data of one style source, reprojected into a tile of the grid, as a `Promise<Uint8Array>` that GL JS reads directly. It is data, not a picture: style layers and filters are not applied. Source data is fetched at the zoom the tile would have if drawn at 512 CSS px.
|
|
169
|
+
|
|
170
|
+
| Source | Result |
|
|
171
|
+
|---|---|
|
|
172
|
+
| vector / geojson | An MVT tile with extent 4096 and a buffer of 128 units. All layers, features and properties are kept. A GeoJSON source's layer is named after the source. |
|
|
173
|
+
| raster / image | A 512 px PNG, drawn as a raster layer with default paint. Image sources become tiles too. |
|
|
174
|
+
| raster-dem | A 512 px PNG of each pixel's elevation, bilinearly interpolated from the source DEM and encoded as `terrarium`. |
|
|
175
|
+
|
|
176
|
+
How vector data is reprojected:
|
|
177
|
+
|
|
178
|
+
- Polygons cut at source tile edges are merged with their fragments that have the same properties, and only then projected. Source tile boundaries leave no seams. IDs are kept only when all fragments share one.
|
|
179
|
+
- Lines stay split at source tile boundaries.
|
|
180
|
+
- Anything outside the projection's domain is removed (for example the far side of the globe in a geostationary view). Lines stop at the edge of the domain, and polygons are closed along it.
|
|
181
|
+
|
|
182
|
+
#### toStyle({ tiles })
|
|
183
|
+
|
|
184
|
+
Returns the style given to `init`, rewritten so that GL JS can draw it in CRS `crs.name` from `getTile`'s tiles.
|
|
185
|
+
|
|
186
|
+
- `tiles(sourceId)` returns the URL template of each source's tiles (`{z}/{x}/{y}` of the CRS's grid).
|
|
187
|
+
- vector and geojson sources become vector sources. raster and image sources become raster sources. raster-dem sources become terrarium raster-dem sources. All use 512 px tiles.
|
|
188
|
+
- Layers of GeoJSON sources get a `source-layer`.
|
|
189
|
+
- Other layers, fill-extrusion included, are kept. Layers of video sources are removed.
|
|
190
|
+
|
|
191
|
+
GL JS evaluates the style at its own zoom on the projected grid, and hillshade slopes come from the tile's zoom. Zoom-dependent styling may therefore look slightly different from ml2drender's own renders.
|
|
192
|
+
|
|
193
|
+
## Projected coordinate reference systems
|
|
194
|
+
|
|
195
|
+
CRSs are given as PROJJSON (`GeographicCRS` or `ProjectedCRS`). PROJ strings and WKT are not accepted. You can get PROJJSON from `projinfo -o PROJJSON -q EPSG:32654`, for example.
|
|
196
|
+
|
|
197
|
+
- **Supported methods:** longlat, Transverse Mercator (UTM, national grids), Mercator (including Web Mercator), Lambert Conformal Conic, Polar Stereographic, Lambert Azimuthal Equal Area, Equal Earth and Geostationary Satellite (geos). Any ellipsoid works. Units must be meters and the prime meridian Greenwich.
|
|
198
|
+
- **No datum transformations.** Style coordinates (WGS84) are projected as if they were lng/lat on the CRS's ellipsoid.
|
|
199
|
+
- **Axis order:** always easting first, then northing (longitude, latitude), whatever the CRS's declared axis order.
|
|
200
|
+
- **How layers are drawn:** background, fill, line, circle, heatmap and symbol layers are drawn from projected vertices directly into the output. Pixel lengths such as line widths, circle radii and text sizes stay constant on screen. raster, hillshade and color-relief layers are drawn in Web Mercator and warped onto a mesh. Areas outside the projection's domain are transparent.
|
|
201
|
+
|
|
202
|
+
## Other bindings
|
|
203
|
+
|
|
204
|
+
The core is a plain Rust crate with no I/O, so it can be wrapped for other hosts. Each host runs the same loop: ask the renderer what it `needs`, fetch it, `provide` the bytes, repeat until nothing is needed, then `render`.
|
|
205
|
+
|
|
206
|
+
- **Node.js (Node-API):** [`@ml2drender/node`](https://github.com/Kanahiro/ml2drender/tree/main/packages/ml2drender-node#readme), from [`crates/napi`](https://github.com/Kanahiro/ml2drender/tree/main/crates/napi).
|
|
207
|
+
- **Python:** [`ml2drender` on PyPI](https://github.com/Kanahiro/ml2drender/tree/main/crates/python#readme), from [`crates/python`](https://github.com/Kanahiro/ml2drender/tree/main/crates/python) (PyO3, abi3).
|
|
208
|
+
- **Rust:** the `ml2drender` crate in [`crates/core`](https://github.com/Kanahiro/ml2drender/tree/main/crates/core) (not on crates.io). `Renderer::new(style, View::tile(z, x, y, 256))`, then `needs()` / `provide()` / `render()`.
|
|
209
|
+
|
|
210
|
+
## Conformance
|
|
211
|
+
|
|
212
|
+
The [MapLibre GL JS render tests](https://github.com/maplibre/maplibre-gl-js/tree/main/test/integration/render) are run with GL JS's own comparison: pixelmatch, with each test's tolerances.
|
|
213
|
+
|
|
214
|
+
| Suite | Result |
|
|
215
|
+
|---|---|
|
|
216
|
+
| Render tests (1008 applicable) | 988 pass / 20 fail (98.0%) |
|
|
217
|
+
| Expression tests (Style Spec, 583) | 581 pass / 2 fail (99.7%) |
|
|
218
|
+
|
|
219
|
+
The 727 tests out of scope cover 3D, pitch, non-Mercator GL projections and runtime style changes. Main known gaps:
|
|
220
|
+
|
|
221
|
+
- Bidirectional text and Arabic shaping. Glyphs drawn with browser fonts (TinySDF) are not available either.
|
|
222
|
+
- History-dependent placement (`prevAnchor`, CrossTileSymbolIndex). Single still images cannot reproduce it.
|
|
223
|
+
- Locale-sensitive collation, and `number-format` in locales other than en-US.
|
|
224
|
+
|
|
225
|
+
## Architecture
|
|
226
|
+
|
|
227
|
+
```text
|
|
228
|
+
host (JS / Node-API / Python) core::Renderer (sans-IO Rust)
|
|
229
|
+
───────────────────────────── ─────────────────────────────
|
|
230
|
+
style + view ─────────────────────────────▶ style · expressions
|
|
231
|
+
◀───────────── needs(): URLs sources: MVT · GeoJSON · images · sprites
|
|
232
|
+
fetch symbols: shaping · placement
|
|
233
|
+
provide(url, bytes) ──────────────────────▶ projection · reprojection
|
|
234
|
+
◀──────────── render(): RGBA software GL rasterizer
|
|
235
|
+
◀─────── export_tile(): MVT/PNG
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
- [`crates/core`](https://github.com/Kanahiro/ml2drender/tree/main/crates/core) is a Rust library with no network, files, async, threads or clocks (sans-IO). It reports the URLs it needs through `needs()` and works on the bytes the host passes to `provide()`. What it needs becomes known step by step: tiles first, then the text they contain, then the glyph ranges for that text.
|
|
239
|
+
- [`crates/wasm`](https://github.com/Kanahiro/ml2drender/tree/main/crates/wasm) exposes the core through a plain C ABI, without wasm-bindgen.
|
|
240
|
+
- [`packages/ml2drender`](https://github.com/Kanahiro/ml2drender/blob/main/packages/ml2drender/src/index.ts) hides WASM memory handling and the fetch loop behind the TypeScript API.
|
|
241
|
+
|
|
242
|
+
The renderer does not imitate the GPU pipeline. It ports MapLibre's bucket building, shader math and quantization, and rasterizes with the same rules as GL.
|
|
243
|
+
|
|
244
|
+
## Development
|
|
245
|
+
|
|
246
|
+
```sh
|
|
247
|
+
pnpm install
|
|
248
|
+
pnpm build:wasm # WASM → packages/ml2drender/wasm/
|
|
249
|
+
pnpm demo # starts the demo (examples/browser)
|
|
250
|
+
pnpm test # Rust unit tests
|
|
251
|
+
pnpm typecheck # TypeScript type checks, including the API type tests
|
|
252
|
+
pnpm lint # rustfmt, clippy and Ruff
|
|
253
|
+
pnpm fixtures # fetches the upstream test data (first time only, about 144 MB)
|
|
254
|
+
pnpm test:render # render tests → target/test-report/render/
|
|
255
|
+
pnpm test:expression # expression tests → target/test-report/expression/
|
|
256
|
+
pnpm build:native # Node-API addon → packages/ml2drender-node/native/
|
|
257
|
+
pnpm test:node # Node-API addon tests
|
|
258
|
+
pnpm test:python # Python binding tests (uses uv)
|
|
259
|
+
pnpm build:docs # API reference (TypeDoc) → target/docs/
|
|
260
|
+
pnpm bench base=<dir> head=. # compares WASM performance between two checkouts
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
```text
|
|
264
|
+
crates/core/ rendering engine (sans-IO)
|
|
265
|
+
crates/wasm/ C ABI for WebAssembly
|
|
266
|
+
crates/napi/ Node-API addon
|
|
267
|
+
crates/python/ Python extension
|
|
268
|
+
crates/cli/ test runner and native checks
|
|
269
|
+
packages/ml2drender/ JavaScript API (WebAssembly)
|
|
270
|
+
packages/ml2drender-node/ Node-API addon package
|
|
271
|
+
examples/browser/ demo (Vite + MapLibre GL JS)
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
You need Node.js (version in `.node-version`), pnpm (version in `packageManager`), Rust via rustup (version in `rust-toolchain.toml`), and uv for Python. CI (`.github/workflows/build.yml`) builds and tests every package on Linux, macOS and Windows; `publish.yml` publishes to npm and PyPI.
|
|
275
|
+
|
|
276
|
+
Design constraints and conventions are described in [AGENTS.md](https://github.com/Kanahiro/ml2drender/blob/main/AGENTS.md) (in Japanese). Issues and pull requests are welcome. A change to rendering should keep `pnpm test:render` results unchanged, or explain why they change.
|
|
277
|
+
|
|
278
|
+
ml2drender was written largely with AI coding agents, using the MapLibre GL JS implementation as the reference.
|
|
279
|
+
|
|
280
|
+
## License
|
|
281
|
+
|
|
282
|
+
[BSD-3-Clause](https://github.com/Kanahiro/ml2drender/blob/main/LICENSE). Much of the code is ported from MapLibre GL JS and the MapLibre Style Spec (BSD-3-Clause), and from @maplibre/geojson-vt, supercluster, kdbush, polylabel and vt-pbf (MIT / ISC). Their copyright notices and licenses are reproduced in [LICENSE](https://github.com/Kanahiro/ml2drender/blob/main/LICENSE). The test data fetched by `pnpm fixtures` is under its own licenses.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import type { StyleSpecification } from '@maplibre/maplibre-gl-style-spec';
|
|
2
|
+
/** A camera, of Web Mercator (`MapRenderer.renderView`) or of a CRS (`ProjectedRenderer.renderView`). */
|
|
3
|
+
export interface View {
|
|
4
|
+
/** Longitude and latitude of the image center, in degrees. */
|
|
5
|
+
center: [lng: number, lat: number];
|
|
6
|
+
/** MapLibre GL JS zoom: the world (in a CRS: tile 0/0/0 of its grid) is 512 × 2^zoom CSS pixels wide. */
|
|
7
|
+
zoom: number;
|
|
8
|
+
/** Degrees clockwise from north (in a CRS: from its y axis) of the direction that is up. Default: 0. */
|
|
9
|
+
bearing?: number;
|
|
10
|
+
/** Positive integer CSS pixels. */
|
|
11
|
+
width: number;
|
|
12
|
+
/** Positive integer CSS pixels. */
|
|
13
|
+
height: number;
|
|
14
|
+
/** Output pixels per CSS pixel. Default: 1. */
|
|
15
|
+
pixelRatio?: number;
|
|
16
|
+
/** Non-negative integer CSS pixels of extra coverage, cropped from the output. Default: 0. */
|
|
17
|
+
margin?: number;
|
|
18
|
+
}
|
|
19
|
+
/** An XYZ tile of the Web Mercator grid (`tileSize` CSS pixels square). */
|
|
20
|
+
export interface Tile {
|
|
21
|
+
/** Zoom level: an integer in 0..=30. */
|
|
22
|
+
z: number;
|
|
23
|
+
/** Column, from the west: an integer in 0..2^z. */
|
|
24
|
+
x: number;
|
|
25
|
+
/** Row, from the north: an integer in 0..2^z. */
|
|
26
|
+
y: number;
|
|
27
|
+
/** CSS pixels. Default: 256. */
|
|
28
|
+
tileSize?: number;
|
|
29
|
+
/** Output pixels per CSS pixel. Default: 1. */
|
|
30
|
+
pixelRatio?: number;
|
|
31
|
+
/** Non-negative integer CSS pixels of extra coverage, cropped from the output. Default: 0. */
|
|
32
|
+
margin?: number;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* A longitude/latitude box in Web Mercator. The image has the box's aspect ratio, `size` on its long side,
|
|
36
|
+
* at the zoom that fits the box into it.
|
|
37
|
+
*/
|
|
38
|
+
export interface LngLatBox {
|
|
39
|
+
/** Degrees; `west > east` crosses the antimeridian. Latitudes are clamped to Web Mercator's ±85.0511°. */
|
|
40
|
+
bbox: [west: number, south: number, east: number, north: number];
|
|
41
|
+
/** Positive integer CSS pixels of the image's long side. */
|
|
42
|
+
size: number;
|
|
43
|
+
/** Output pixels per CSS pixel. Default: 1. */
|
|
44
|
+
pixelRatio?: number;
|
|
45
|
+
/** Non-negative integer CSS pixels of extra coverage, cropped from the output. Default: 0. */
|
|
46
|
+
margin?: number;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* A CRS, with MapLibre GL JS's tile grid and name for it: what `addProjection` registers, with the CRS as PROJJSON.
|
|
50
|
+
*/
|
|
51
|
+
export interface Crs {
|
|
52
|
+
/**
|
|
53
|
+
* The name GL JS knows the CRS by (`addProjection`'s `name`, `projection.type` of `toStyle`'s style). Required by
|
|
54
|
+
* `toStyle` only.
|
|
55
|
+
*/
|
|
56
|
+
name?: string;
|
|
57
|
+
/**
|
|
58
|
+
* PROJJSON of a geographic or projected CRS. Supported methods: Transverse Mercator, Mercator, Pseudo Mercator,
|
|
59
|
+
* Lambert Conic Conformal, Polar Stereographic, Lambert Azimuthal Equal Area, Equal Earth and PROJ's
|
|
60
|
+
* Geostationary Satellite, without datum shifts.
|
|
61
|
+
*/
|
|
62
|
+
projjson: object;
|
|
63
|
+
/**
|
|
64
|
+
* The CRS's tile grid, which a CRS does not have by itself. Required by `renderTile`, `getTile` and `renderView`
|
|
65
|
+
* (whose zoom is the grid's); `render` of a box works without it.
|
|
66
|
+
*/
|
|
67
|
+
tileMatrixSet?: TileMatrixSet;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* A box of a projected CRS (see `MapRenderer.projected`). Vector layers (background, fill, line, circle, heatmap,
|
|
71
|
+
* symbol) are drawn in it with projected vertices; raster, hillshade and color-relief are rendered in Web Mercator
|
|
72
|
+
* and warped.
|
|
73
|
+
*/
|
|
74
|
+
export interface ProjectedBox {
|
|
75
|
+
/**
|
|
76
|
+
* In CRS units (degrees for longlat), always easting/longitude first whatever the CRS's axis order; the CRS's y
|
|
77
|
+
* axis is up. For a rotated view, use `renderView`.
|
|
78
|
+
*/
|
|
79
|
+
bbox: [minX: number, minY: number, maxX: number, maxY: number];
|
|
80
|
+
/** Positive integer CSS pixels of the image's long side; the image has the box's aspect ratio. */
|
|
81
|
+
size: number;
|
|
82
|
+
/** Output pixels per CSS pixel. Default: 1. */
|
|
83
|
+
pixelRatio?: number;
|
|
84
|
+
/** Non-negative integer CSS pixels of extra coverage, cropped from the output. Default: 0. */
|
|
85
|
+
margin?: number;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* MapLibre GL JS's `TileMatrixSet` (`addProjection`): tile 0/0/0 is the square of side `extentAtZoom0` whose
|
|
89
|
+
* top-left corner is `origin`, and each zoom splits every tile in four; x grows east, y south.
|
|
90
|
+
*/
|
|
91
|
+
export interface TileMatrixSet {
|
|
92
|
+
/** CRS coordinates of the top-left corner of tile 0/0/0: [min x, max y]. */
|
|
93
|
+
origin: [number, number];
|
|
94
|
+
/** Width (= height) of tile 0/0/0 in CRS units. */
|
|
95
|
+
extentAtZoom0: number;
|
|
96
|
+
}
|
|
97
|
+
/** A source of the style in a tile of a CRS's grid (see `ProjectedRenderer.getTile`). */
|
|
98
|
+
export interface SourceTile {
|
|
99
|
+
/** A vector, GeoJSON, raster, raster-dem or image source of the style. */
|
|
100
|
+
source: string;
|
|
101
|
+
/** Zoom level of the CRS's grid: an integer in 0..=30. */
|
|
102
|
+
z: number;
|
|
103
|
+
/** Column, from the grid's west edge: an integer in 0..2^z. */
|
|
104
|
+
x: number;
|
|
105
|
+
/** Row, from the grid's north edge: an integer in 0..2^z. */
|
|
106
|
+
y: number;
|
|
107
|
+
}
|
|
108
|
+
/** A `MapRenderer` drawing in a CRS (see `MapRenderer.projected`). */
|
|
109
|
+
export interface ProjectedRenderer {
|
|
110
|
+
/** The CRS given to `MapRenderer.projected`. */
|
|
111
|
+
readonly crs: Crs;
|
|
112
|
+
/** Fetch required resources and return a new RGBA image of `box.bbox` (CRS units). */
|
|
113
|
+
render(box: ProjectedBox): Promise<RenderedImage>;
|
|
114
|
+
/** `render` of tile `z/x/y` of the CRS's grid, `tileSize` CSS pixels (default 256) on a side. */
|
|
115
|
+
renderTile(tile: Tile): Promise<RenderedImage>;
|
|
116
|
+
/**
|
|
117
|
+
* `render` of MapLibre GL JS's camera in the CRS (registered with `addProjection`): `center` in degrees, tile
|
|
118
|
+
* 0/0/0 of the grid in 512 CSS pixels at zoom 0, turned around `center` by `bearing`.
|
|
119
|
+
*/
|
|
120
|
+
renderView(view: View): Promise<RenderedImage>;
|
|
121
|
+
/**
|
|
122
|
+
* Fetch the data of `tile.source` and return it in tile `z/x/y` of the CRS's grid, for MapLibre GL JS to draw the
|
|
123
|
+
* style in the CRS from (see `toStyle`), not a picture of the map:
|
|
124
|
+
* - vector / GeoJSON: a vector tile (MVT, extent 4096). Layers, features and properties are kept as they are (a
|
|
125
|
+
* GeoJSON source's layer is named after the source).
|
|
126
|
+
* - raster / image: a 512 px PNG of the source as a raster layer with default paint draws it.
|
|
127
|
+
* - raster-dem: a 512 px PNG of its elevations in the `terrarium` encoding.
|
|
128
|
+
*
|
|
129
|
+
* Source data is fetched at the zoom of the tile drawn at 512 CSS pixels.
|
|
130
|
+
*/
|
|
131
|
+
getTile(tile: SourceTile): Promise<Uint8Array<ArrayBuffer>>;
|
|
132
|
+
/**
|
|
133
|
+
* The style for MapLibre GL JS to draw in the CRS (registered with `addProjection` as `crs.name`) from tiles of
|
|
134
|
+
* `getTile`, whose URL templates (`{z}/{x}/{y}` of the CRS's grid) `tiles` gives for each source: vector and
|
|
135
|
+
* GeoJSON sources become vector sources (layers of a GeoJSON source read the layer named after it), raster and
|
|
136
|
+
* image sources raster sources, raster-dem sources terrarium ones, all of 512 px tiles. Layers of other sources
|
|
137
|
+
* (video) are left out. The style is the one given to `init`.
|
|
138
|
+
*/
|
|
139
|
+
toStyle(options: {
|
|
140
|
+
tiles: (source: string) => string;
|
|
141
|
+
}): StyleSpecification;
|
|
142
|
+
}
|
|
143
|
+
/** A rendered RGBA image, with encoders that run inside WASM. */
|
|
144
|
+
export interface RenderedImage {
|
|
145
|
+
/** Pixels: CSS pixels × `pixelRatio`. */
|
|
146
|
+
width: number;
|
|
147
|
+
/** Pixels: CSS pixels × `pixelRatio`. */
|
|
148
|
+
height: number;
|
|
149
|
+
/** Row-major, 8-bit RGBA pixels. */
|
|
150
|
+
data: Uint8ClampedArray<ArrayBuffer>;
|
|
151
|
+
/** Encode `data` inside WASM as an owned, lossless RGBA8 PNG. */
|
|
152
|
+
toPng(): Uint8Array<ArrayBuffer>;
|
|
153
|
+
/** Encode `data` inside WASM as an owned, lossless WebP. */
|
|
154
|
+
toWebp(): Uint8Array<ArrayBuffer>;
|
|
155
|
+
/** Encode `data` inside WASM as an owned JPEG of `quality` (1–100), flattened over black. */
|
|
156
|
+
toJpeg(quality: number): Uint8Array<ArrayBuffer>;
|
|
157
|
+
}
|
|
158
|
+
export type { StyleSpecification };
|
|
159
|
+
/** Options of `MapRenderer.init`. */
|
|
160
|
+
export interface InitOptions {
|
|
161
|
+
/** Load complete resource bytes, or null for a missing resource (HTTP 404). Other failures must reject. */
|
|
162
|
+
loadResource?: (url: string) => Promise<Uint8Array<ArrayBuffer> | null>;
|
|
163
|
+
/** Precompiled WASM (required on Cloudflare Workers). Defaults to the bundled asset in browsers. */
|
|
164
|
+
wasm?: WebAssembly.Module;
|
|
165
|
+
/**
|
|
166
|
+
* Decoded resources (tiles and their layer geometry, sprites, glyphs) are kept inside the
|
|
167
|
+
* renderer and reused by later renders; the first render ttlMs or more after they started
|
|
168
|
+
* being kept drops them. 0 disables reuse, Infinity never expires. Default: 5 minutes.
|
|
169
|
+
* With 0, a render also drops each layer bucket once drawn, which lowers its peak memory
|
|
170
|
+
* (e.g. on Cloudflare Workers, whose 128 MB includes WASM memory, which never shrinks).
|
|
171
|
+
* Fetched bytes are not cached: rely on the HTTP cache, or cache in `loadResource`.
|
|
172
|
+
*/
|
|
173
|
+
cache?: {
|
|
174
|
+
/** Milliseconds; 0 or `Infinity` included. Default: 300 000 (5 minutes). */
|
|
175
|
+
ttlMs?: number;
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Render a MapLibre Style as a static 2D RGBA image.
|
|
180
|
+
*
|
|
181
|
+
* @example
|
|
182
|
+
* ```ts
|
|
183
|
+
* const renderer = await MapRenderer.init(style);
|
|
184
|
+
* const image = await renderer.renderTile({ z: 5, x: 28, y: 12 });
|
|
185
|
+
* const png = image.toPng();
|
|
186
|
+
* ```
|
|
187
|
+
*/
|
|
188
|
+
export declare class MapRenderer {
|
|
189
|
+
/** The reused core (none with a TTL of 0). */
|
|
190
|
+
private core?;
|
|
191
|
+
/** A trap (Rust panic or out of memory) left the WASM instance in an unknown state. */
|
|
192
|
+
private broken?;
|
|
193
|
+
/** Fetches in flight, shared by overlapping renders, with the newest ticket that awaits each. */
|
|
194
|
+
private readonly pending;
|
|
195
|
+
/** Tickets of the renders in progress: WASM keeps the tiles they need (`renderer_set_ticket`). */
|
|
196
|
+
private readonly tickets;
|
|
197
|
+
private lastTicket;
|
|
198
|
+
private readonly module;
|
|
199
|
+
private readonly instance;
|
|
200
|
+
private readonly wasm;
|
|
201
|
+
private readonly style;
|
|
202
|
+
/** The style as given, for `toStyle`. */
|
|
203
|
+
private readonly original;
|
|
204
|
+
private readonly loadResource;
|
|
205
|
+
private readonly ttlMs;
|
|
206
|
+
private constructor();
|
|
207
|
+
/** Snapshot a style object and load the renderer. Resource URLs are passed to `loadResource` as written. */
|
|
208
|
+
static init(style: StyleSpecification, options?: InitOptions): Promise<MapRenderer>;
|
|
209
|
+
/** Fetch required resources and return a new RGBA image of a Web Mercator camera. */
|
|
210
|
+
renderView(view: View): Promise<RenderedImage>;
|
|
211
|
+
/** `renderView` of an XYZ tile of the Web Mercator grid. */
|
|
212
|
+
renderTile(tile: Tile): Promise<RenderedImage>;
|
|
213
|
+
/** `renderView` of a longitude/latitude box, `box.size` CSS pixels on the long side. */
|
|
214
|
+
render(box: LngLatBox): Promise<RenderedImage>;
|
|
215
|
+
/** This renderer drawing in `crs`, on its tile grid. Resources fetched for one CRS serve the others too. */
|
|
216
|
+
projected(crs: Crs): ProjectedRenderer;
|
|
217
|
+
/** `[lng, lat]` in the CRS `projjson` (encoded); NaN where the CRS has no point. */
|
|
218
|
+
private forward;
|
|
219
|
+
private assertUsable;
|
|
220
|
+
/** The core arguments and `setView` of a view of the CRS `projjson` (encoded), turned around its center by `bearing`. */
|
|
221
|
+
private projectedArgs;
|
|
222
|
+
/** The fetch-and-render loop of images; `setView` points a core at the view. */
|
|
223
|
+
private draw;
|
|
224
|
+
/**
|
|
225
|
+
* The fetch loop of the view `setView` points a core at, for the export source `source` (empty: none), then
|
|
226
|
+
* `finish(handle, oldest)`'s output.
|
|
227
|
+
*/
|
|
228
|
+
private run;
|
|
229
|
+
private runOnce;
|
|
230
|
+
/**
|
|
231
|
+
* Fetch `url` once and provide it to `core`, which requested it, before it leaves `pending`. It is
|
|
232
|
+
* kept for the newest render awaiting it: while any of them is in progress, the oldest ticket in
|
|
233
|
+
* progress is at most that one.
|
|
234
|
+
*/
|
|
235
|
+
private fetch;
|
|
236
|
+
/**
|
|
237
|
+
* The current WASM renderer, replaced once older than the cache TTL. With a TTL of 0, each
|
|
238
|
+
* render gets its own, freed when the render ends.
|
|
239
|
+
*/
|
|
240
|
+
private acquire;
|
|
241
|
+
private release;
|
|
242
|
+
private output;
|
|
243
|
+
private withBytes;
|
|
244
|
+
}
|