@ml2drender/wasm 0.1.0 → 0.3.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/README.md +15 -16
- package/dist/index.d.ts +19 -36
- package/dist/index.js +42 -99
- package/package.json +2 -2
- package/wasm/ml2drender_wasm.wasm +0 -0
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
- **Made for serverless.** The core does no network or file I/O; the host fetches everything.
|
|
12
12
|
|
|
13
13
|
> [!NOTE]
|
|
14
|
-
> ml2drender draws flat 2D maps. 3D features (fill-extrusion, terrain, globe, pitch) are out of scope; fill-extrusion
|
|
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
15
|
|
|
16
16
|
## Quick start
|
|
17
17
|
|
|
@@ -38,8 +38,8 @@ pip install ml2drender # Python
|
|
|
38
38
|
| Package | Runs in | API |
|
|
39
39
|
|---|---|---|
|
|
40
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) |
|
|
42
|
-
| [`ml2drender` on PyPI](https://github.com/Kanahiro/ml2drender/tree/main/crates/python#readme) | CPython 3.11+ (Linux, macOS, Windows) |
|
|
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
43
|
|
|
44
44
|
All three draw with the same Rust core. To build from source, see [Development](#development).
|
|
45
45
|
|
|
@@ -71,7 +71,7 @@ const utm = renderer.projected({
|
|
|
71
71
|
});
|
|
72
72
|
|
|
73
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],
|
|
74
|
+
await utm.render({ bbox: [300_000, 3_900_000, 500_000, 4_100_000], size: 512 }); // a box in CRS units
|
|
75
75
|
await utm.renderTile({ z: 3, x: 4, y: 2 }); // a tile of the CRS's grid
|
|
76
76
|
```
|
|
77
77
|
|
|
@@ -88,14 +88,17 @@ const tile = await renderer.projected(crs).getTile({ source, z, x, y }); // MVT,
|
|
|
88
88
|
|
|
89
89
|
// Browser: register the CRS with GL JS and draw the rewritten style
|
|
90
90
|
import { addProjection, Map } from 'maplibre-gl';
|
|
91
|
-
import
|
|
91
|
+
import proj4 from 'proj4';
|
|
92
92
|
|
|
93
|
-
addProjection({ name: crs.name, projection:
|
|
93
|
+
addProjection({ name: crs.name, projection: proj4(crs.projjson), tileMatrixSet: crs.tileMatrixSet });
|
|
94
94
|
const glStyle = renderer.projected(crs).toStyle({ tiles: (source) => `https://tiles.example.com/${source}/{z}/{x}/{y}` });
|
|
95
95
|
new Map({ container: 'map', style: glStyle });
|
|
96
96
|
```
|
|
97
97
|
|
|
98
|
-
|
|
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.
|
|
99
102
|
|
|
100
103
|
## JavaScript API
|
|
101
104
|
|
|
@@ -110,7 +113,6 @@ Takes a style object (the official `StyleSpecification` type) and loads the WASM
|
|
|
110
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. |
|
|
111
114
|
| `wasm` | bundled WASM | A compiled `WebAssembly.Module`. Required in Node.js and Cloudflare Workers. |
|
|
112
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. |
|
|
113
|
-
| `transformFillExtrusion` | convert to fill | Replaces each fill-extrusion layer with a 2D layer. By default it becomes a fill with the same color, opacity, pattern and translation. |
|
|
114
116
|
|
|
115
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).
|
|
116
118
|
|
|
@@ -133,7 +135,7 @@ Each one fetches what it needs and resolves to a `RenderedImage` of all the styl
|
|
|
133
135
|
| `renderTile({ z, x, y, tileSize? })` | An XYZ tile of the Web Mercator grid. `tileSize` defaults to 256. |
|
|
134
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. |
|
|
135
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`. |
|
|
136
|
-
| `projected(crs).render({ bbox,
|
|
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`. |
|
|
137
139
|
| `projected(crs).renderTile({ z, x, y, tileSize? })` | A tile of the CRS's grid. |
|
|
138
140
|
|
|
139
141
|
All of them also accept two options:
|
|
@@ -152,9 +154,10 @@ A `RenderedImage` has:
|
|
|
152
154
|
|
|
153
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`:
|
|
154
156
|
|
|
155
|
-
- `
|
|
156
|
-
- `
|
|
157
|
-
|
|
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.
|
|
158
161
|
|
|
159
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).
|
|
160
163
|
|
|
@@ -187,10 +190,6 @@ Returns the style given to `init`, rewritten so that GL JS can draw it in CRS `c
|
|
|
187
190
|
|
|
188
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.
|
|
189
192
|
|
|
190
|
-
### loadProjection(projjson, options?) and loadProjectionFactory(options?)
|
|
191
|
-
|
|
192
|
-
Return the same Rust projection code the renderer draws with. `forward([lng, lat])` returns CRS coordinates and `inverse([x, y])` returns lng/lat. Points that cannot be projected give NaN. Use them to compute tile ranges, or to pass to GL JS's `addProjection`. `loadProjectionFactory` resolves to a synchronous `(projjson) => Projection`, for places that cannot await, such as `setProjectionHandler` in GL JS's workers.
|
|
193
|
-
|
|
194
193
|
## Projected coordinate reference systems
|
|
195
194
|
|
|
196
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.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { StyleSpecification } from '@maplibre/maplibre-gl-style-spec';
|
|
2
2
|
/** A camera, of Web Mercator (`MapRenderer.renderView`) or of a CRS (`ProjectedRenderer.renderView`). */
|
|
3
3
|
export interface View {
|
|
4
4
|
/** Longitude and latitude of the image center, in degrees. */
|
|
@@ -46,19 +46,25 @@ export interface LngLatBox {
|
|
|
46
46
|
margin?: number;
|
|
47
47
|
}
|
|
48
48
|
/**
|
|
49
|
-
* A CRS
|
|
49
|
+
* A CRS, with MapLibre GL JS's tile grid and name for it: what `addProjection` registers, with the CRS as PROJJSON.
|
|
50
50
|
*/
|
|
51
51
|
export interface Crs {
|
|
52
|
-
/**
|
|
53
|
-
|
|
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;
|
|
54
57
|
/**
|
|
55
58
|
* PROJJSON of a geographic or projected CRS. Supported methods: Transverse Mercator, Mercator, Pseudo Mercator,
|
|
56
59
|
* Lambert Conic Conformal, Polar Stereographic, Lambert Azimuthal Equal Area, Equal Earth and PROJ's
|
|
57
60
|
* Geostationary Satellite, without datum shifts.
|
|
58
61
|
*/
|
|
59
62
|
projjson: object;
|
|
60
|
-
/**
|
|
61
|
-
|
|
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;
|
|
62
68
|
}
|
|
63
69
|
/**
|
|
64
70
|
* A box of a projected CRS (see `MapRenderer.projected`). Vector layers (background, fill, line, circle, heatmap,
|
|
@@ -66,12 +72,13 @@ export interface Crs {
|
|
|
66
72
|
* and warped.
|
|
67
73
|
*/
|
|
68
74
|
export interface ProjectedBox {
|
|
69
|
-
/**
|
|
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
|
+
*/
|
|
70
79
|
bbox: [minX: number, minY: number, maxX: number, maxY: number];
|
|
71
|
-
/** Positive integer CSS pixels. */
|
|
72
|
-
|
|
73
|
-
/** Positive integer CSS pixels. */
|
|
74
|
-
height: number;
|
|
80
|
+
/** Positive integer CSS pixels of the image's long side; the image has the box's aspect ratio. */
|
|
81
|
+
size: number;
|
|
75
82
|
/** Output pixels per CSS pixel. Default: 1. */
|
|
76
83
|
pixelRatio?: number;
|
|
77
84
|
/** Non-negative integer CSS pixels of extra coverage, cropped from the output. Default: 0. */
|
|
@@ -127,7 +134,7 @@ export interface ProjectedRenderer {
|
|
|
127
134
|
* `getTile`, whose URL templates (`{z}/{x}/{y}` of the CRS's grid) `tiles` gives for each source: vector and
|
|
128
135
|
* GeoJSON sources become vector sources (layers of a GeoJSON source read the layer named after it), raster and
|
|
129
136
|
* image sources raster sources, raster-dem sources terrarium ones, all of 512 px tiles. Layers of other sources
|
|
130
|
-
* (video) are left out. The style is the one given to `init
|
|
137
|
+
* (video) are left out. The style is the one given to `init`.
|
|
131
138
|
*/
|
|
132
139
|
toStyle(options: {
|
|
133
140
|
tiles: (source: string) => string;
|
|
@@ -148,10 +155,6 @@ export interface RenderedImage {
|
|
|
148
155
|
/** Encode `data` inside WASM as an owned JPEG of `quality` (1–100), flattened over black. */
|
|
149
156
|
toJpeg(quality: number): Uint8Array<ArrayBuffer>;
|
|
150
157
|
}
|
|
151
|
-
/** Style Spec layers supported by the 2D renderer. */
|
|
152
|
-
export type StyleLayer = Exclude<LayerSpecification, FillExtrusionLayerSpecification>;
|
|
153
|
-
/** A fill-extrusion layer, which `InitOptions.transformFillExtrusion` turns into a 2D layer. */
|
|
154
|
-
export type FillExtrusionLayer = FillExtrusionLayerSpecification;
|
|
155
158
|
export type { StyleSpecification };
|
|
156
159
|
/** Options of `MapRenderer.init`. */
|
|
157
160
|
export interface InitOptions {
|
|
@@ -171,27 +174,7 @@ export interface InitOptions {
|
|
|
171
174
|
/** Milliseconds; 0 or `Infinity` included. Default: 300 000 (5 minutes). */
|
|
172
175
|
ttlMs?: number;
|
|
173
176
|
};
|
|
174
|
-
/** Replace each fill-extrusion layer. Defaults to a fill preserving its 2D appearance. */
|
|
175
|
-
transformFillExtrusion?: (layer: FillExtrusionLayer) => StyleLayer;
|
|
176
|
-
}
|
|
177
|
-
/** A CRS's projection, computed by the renderer itself. */
|
|
178
|
-
export interface Projection {
|
|
179
|
-
/** `[lng, lat]` in degrees → `[x, y]` in CRS units; NaN where the CRS has no point (e.g. the far side of a geostationary view). */
|
|
180
|
-
forward(lngLat: number[]): number[];
|
|
181
|
-
/** `[x, y]` → `[lng, lat]` in degrees; NaN outside the projection's domain. */
|
|
182
|
-
inverse(xy: number[]): number[];
|
|
183
177
|
}
|
|
184
|
-
/**
|
|
185
|
-
* Load a PROJJSON CRS the way `MapRenderer.projected` reads `Crs.projjson`, e.g. to compute
|
|
186
|
-
* tile bounds or to register the CRS with MapLibre's `addProjection`, so both agree on the CRS.
|
|
187
|
-
* Throws for a CRS the renderer does not support.
|
|
188
|
-
*/
|
|
189
|
-
export declare function loadProjection(projjson: object, options?: Pick<InitOptions, 'wasm'>): Promise<Projection>;
|
|
190
|
-
/**
|
|
191
|
-
* Load the WASM once and return a synchronous `loadProjection`, for hosts that must build a
|
|
192
|
-
* projection without awaiting, such as MapLibre's worker `setProjectionHandler`.
|
|
193
|
-
*/
|
|
194
|
-
export declare function loadProjectionFactory(options?: Pick<InitOptions, 'wasm'>): Promise<(projjson: object) => Projection>;
|
|
195
178
|
/**
|
|
196
179
|
* Render a MapLibre Style as a static 2D RGBA image.
|
|
197
180
|
*
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
const encoder = new TextEncoder();
|
|
2
2
|
const decoder = new TextDecoder();
|
|
3
3
|
const DEFAULT_TTL_MS = 5 * 60 * 1000;
|
|
4
|
-
const SUPPORTED_LAYERS = new Set([
|
|
5
|
-
'background', 'fill', 'line', 'circle', 'raster', 'symbol', 'hillshade', 'color-relief', 'heatmap',
|
|
6
|
-
]);
|
|
7
4
|
async function fetchResource(url) {
|
|
8
5
|
const response = await fetch(url);
|
|
9
6
|
if (!response.ok) {
|
|
@@ -50,9 +47,8 @@ function withBytes(w, bytes, call) {
|
|
|
50
47
|
}
|
|
51
48
|
}
|
|
52
49
|
/**
|
|
53
|
-
* One WASM instance per module (the bundled one under `undefined`), shared by
|
|
54
|
-
*
|
|
55
|
-
* the next. (WASM memory never shrinks, and an instance per renderer holds its own until collected;
|
|
50
|
+
* One WASM instance per module (the bundled one under `undefined`), shared by renderers that keep
|
|
51
|
+
* nothing between renders (`ttlMs` 0): memory freed by one render is reused by the next. (WASM memory never shrinks, and an instance per renderer holds its own until collected;
|
|
56
52
|
* on Cloudflare Workers all of it counts towards the isolate's 128 MB.) A renderer that keeps
|
|
57
53
|
* resources gets its own instance, which goes with it.
|
|
58
54
|
*/
|
|
@@ -77,45 +73,6 @@ function discardInstance(module, instance, w) {
|
|
|
77
73
|
if (instances.get(module) === instance)
|
|
78
74
|
instances.delete(module);
|
|
79
75
|
}
|
|
80
|
-
const freeProjection = new FinalizationRegistry(({ w, handle }) => w.projection_free(handle));
|
|
81
|
-
/**
|
|
82
|
-
* Load a PROJJSON CRS the way `MapRenderer.projected` reads `Crs.projjson`, e.g. to compute
|
|
83
|
-
* tile bounds or to register the CRS with MapLibre's `addProjection`, so both agree on the CRS.
|
|
84
|
-
* Throws for a CRS the renderer does not support.
|
|
85
|
-
*/
|
|
86
|
-
export async function loadProjection(projjson, options = {}) {
|
|
87
|
-
return (await loadProjectionFactory(options))(projjson);
|
|
88
|
-
}
|
|
89
|
-
/**
|
|
90
|
-
* Load the WASM once and return a synchronous `loadProjection`, for hosts that must build a
|
|
91
|
-
* projection without awaiting, such as MapLibre's worker `setProjectionHandler`.
|
|
92
|
-
*/
|
|
93
|
-
export async function loadProjectionFactory(options = {}) {
|
|
94
|
-
const w = await sharedWasm(options.wasm);
|
|
95
|
-
return (projjson) => {
|
|
96
|
-
if (!projjson || typeof projjson !== 'object')
|
|
97
|
-
throw new TypeError('projjson must be a PROJJSON object');
|
|
98
|
-
const handle = withBytes(w, encoder.encode(JSON.stringify(projjson)), (ptr, len) => w.projection_new(ptr, len));
|
|
99
|
-
if (!handle)
|
|
100
|
-
throw new Error(decoder.decode(output(w)));
|
|
101
|
-
// A fresh view per call: memory growth detaches earlier ones.
|
|
102
|
-
const xy = () => [...new Float64Array(w.memory.buffer, w.xy_ptr(), 2)];
|
|
103
|
-
// The methods hold `owner`, which frees the handle once collected: callers may keep only them.
|
|
104
|
-
const owner = { handle };
|
|
105
|
-
const projection = {
|
|
106
|
-
forward: ([lng, lat]) => {
|
|
107
|
-
w.projection_forward(owner.handle, lng, lat);
|
|
108
|
-
return xy();
|
|
109
|
-
},
|
|
110
|
-
inverse: ([x, y]) => {
|
|
111
|
-
w.projection_inverse(owner.handle, x, y);
|
|
112
|
-
return xy();
|
|
113
|
-
},
|
|
114
|
-
};
|
|
115
|
-
freeProjection.register(owner, { w, handle });
|
|
116
|
-
return projection;
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
76
|
function viewArgs(view) {
|
|
120
77
|
const [lng, lat] = view.center;
|
|
121
78
|
for (const [name, value] of Object.entries({ lng, lat, zoom: view.zoom, bearing: view.bearing ?? 0 })) {
|
|
@@ -154,8 +111,6 @@ function tileView({ z, x, y, tileSize = 256, pixelRatio, margin }) {
|
|
|
154
111
|
}
|
|
155
112
|
const MAX_LAT = 85.0511287798066;
|
|
156
113
|
function fitLngLat({ bbox: [west, south, east, north], size, pixelRatio, margin }) {
|
|
157
|
-
if (!Number.isInteger(size) || size < 1 || size > 0xffffffff)
|
|
158
|
-
throw new RangeError('size must be a positive uint32 integer');
|
|
159
114
|
if (east < west)
|
|
160
115
|
east += 360;
|
|
161
116
|
[south, north] = [south, north].map((lat) => Math.max(-MAX_LAT, Math.min(MAX_LAT, lat)));
|
|
@@ -165,18 +120,25 @@ function fitLngLat({ bbox: [west, south, east, north], size, pixelRatio, margin
|
|
|
165
120
|
const my = (lat) => (1 - Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360)) / Math.PI) / 2;
|
|
166
121
|
const [y0, y1] = [my(north), my(south)];
|
|
167
122
|
const [dx, dy] = [(east - west) / 360, y1 - y0];
|
|
168
|
-
|
|
169
|
-
const scale = size / Math.max(dx, dy);
|
|
123
|
+
const [width, height, scale] = fitSize(dx, dy, size);
|
|
170
124
|
const lng = (west + east) / 2;
|
|
171
125
|
return {
|
|
172
126
|
center: [lng > 180 ? lng - 360 : lng, Math.atan(Math.sinh(Math.PI * (1 - (y0 + y1)))) * 180 / Math.PI],
|
|
127
|
+
// `scale` is CSS pixels per world.
|
|
173
128
|
zoom: Math.log2(scale / 512),
|
|
174
|
-
width
|
|
175
|
-
height
|
|
129
|
+
width,
|
|
130
|
+
height,
|
|
176
131
|
pixelRatio,
|
|
177
132
|
margin,
|
|
178
133
|
};
|
|
179
134
|
}
|
|
135
|
+
/** Width and height of a `dx` x `dy` box with `size` on the long side (at least 1 on the short one), and the scale. */
|
|
136
|
+
function fitSize(dx, dy, size) {
|
|
137
|
+
if (!Number.isInteger(size) || size < 1 || size > 0xffffffff)
|
|
138
|
+
throw new RangeError('size must be a positive uint32 integer');
|
|
139
|
+
const scale = size / Math.max(dx, dy);
|
|
140
|
+
return [Math.max(1, Math.round(dx * scale)), Math.max(1, Math.round(dy * scale)), scale];
|
|
141
|
+
}
|
|
180
142
|
function marginArg(value = 0) {
|
|
181
143
|
const margin = nonnegative(value, 'margin');
|
|
182
144
|
if (!Number.isInteger(margin) || margin > 0xffffffff)
|
|
@@ -188,41 +150,11 @@ function nonnegative(value, name) {
|
|
|
188
150
|
throw new RangeError(`${name} must be a finite, non-negative number`);
|
|
189
151
|
return value;
|
|
190
152
|
}
|
|
191
|
-
function
|
|
192
|
-
const { type, paint, layout, ...base } = layer;
|
|
193
|
-
// Shared paint properties have the same defaults; leaving absent values unset
|
|
194
|
-
// preserves them without duplicating Style Spec defaults. Expressions stay intact.
|
|
195
|
-
return {
|
|
196
|
-
...base,
|
|
197
|
-
type: 'fill',
|
|
198
|
-
layout: { visibility: layout?.visibility },
|
|
199
|
-
paint: {
|
|
200
|
-
'fill-color': paint?.['fill-extrusion-color'],
|
|
201
|
-
'fill-opacity': paint?.['fill-extrusion-opacity'],
|
|
202
|
-
'fill-pattern': paint?.['fill-extrusion-pattern'],
|
|
203
|
-
'fill-translate': paint?.['fill-extrusion-translate'],
|
|
204
|
-
'fill-translate-anchor': paint?.['fill-extrusion-translate-anchor'],
|
|
205
|
-
'fill-color-transition': paint?.['fill-extrusion-color-transition'],
|
|
206
|
-
'fill-opacity-transition': paint?.['fill-extrusion-opacity-transition'],
|
|
207
|
-
'fill-pattern-transition': paint?.['fill-extrusion-pattern-transition'],
|
|
208
|
-
'fill-translate-transition': paint?.['fill-extrusion-translate-transition'],
|
|
209
|
-
},
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
function prepareStyle(style, transform = flattenFillExtrusion) {
|
|
153
|
+
function prepareStyle(style) {
|
|
213
154
|
if (!style || typeof style !== 'object' || !Array.isArray(style.layers)) {
|
|
214
155
|
throw new Error('Style must contain a layers array');
|
|
215
156
|
}
|
|
216
|
-
|
|
217
|
-
if (!layer || typeof layer !== 'object' || !('type' in layer) || layer.type !== 'fill-extrusion')
|
|
218
|
-
return layer;
|
|
219
|
-
const replacement = transform(layer);
|
|
220
|
-
if (!replacement || typeof replacement.id !== 'string' || !SUPPORTED_LAYERS.has(replacement.type)) {
|
|
221
|
-
throw new Error(`Invalid replacement for fill-extrusion layer ${'id' in layer ? String(layer.id) : ''}`);
|
|
222
|
-
}
|
|
223
|
-
return replacement;
|
|
224
|
-
});
|
|
225
|
-
return encoder.encode(JSON.stringify({ ...style, layers }));
|
|
157
|
+
return encoder.encode(JSON.stringify(style));
|
|
226
158
|
}
|
|
227
159
|
/**
|
|
228
160
|
* Render a MapLibre Style as a static 2D RGBA image.
|
|
@@ -267,7 +199,7 @@ export class MapRenderer {
|
|
|
267
199
|
if (ttlMs !== Infinity)
|
|
268
200
|
nonnegative(ttlMs, 'cache.ttlMs');
|
|
269
201
|
const loadResource = options.loadResource ?? fetchResource;
|
|
270
|
-
const prepared = prepareStyle(style
|
|
202
|
+
const prepared = prepareStyle(style);
|
|
271
203
|
const instance = ttlMs === 0 ? sharedWasm(options.wasm) : loadWasm(options.wasm);
|
|
272
204
|
return new MapRenderer(options.wasm, instance, await instance, prepared, structuredClone(style), loadResource, ttlMs);
|
|
273
205
|
}
|
|
@@ -286,17 +218,21 @@ export class MapRenderer {
|
|
|
286
218
|
}
|
|
287
219
|
/** This renderer drawing in `crs`, on its tile grid. Resources fetched for one CRS serve the others too. */
|
|
288
220
|
projected(crs) {
|
|
289
|
-
if (typeof crs.name !== 'string' || !crs.name)
|
|
290
|
-
throw new TypeError('crs.name must be a name');
|
|
291
221
|
if (!crs.projjson || typeof crs.projjson !== 'object')
|
|
292
222
|
throw new TypeError('crs.projjson must be a PROJJSON object');
|
|
293
|
-
const
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
223
|
+
const grid = () => {
|
|
224
|
+
if (!crs.tileMatrixSet)
|
|
225
|
+
throw new TypeError('crs.tileMatrixSet is required for tiles and cameras');
|
|
226
|
+
const { origin, extentAtZoom0 } = crs.tileMatrixSet;
|
|
227
|
+
if (!origin.every(Number.isFinite) || !(extentAtZoom0 > 0 && Number.isFinite(extentAtZoom0))) {
|
|
228
|
+
throw new RangeError('crs.tileMatrixSet must have a finite origin and a finite, positive extentAtZoom0');
|
|
229
|
+
}
|
|
230
|
+
return crs.tileMatrixSet;
|
|
231
|
+
};
|
|
297
232
|
const projjson = encoder.encode(JSON.stringify(crs.projjson));
|
|
298
233
|
// The box of tile z/x/y of the grid.
|
|
299
234
|
const box = ({ z, x, y }) => {
|
|
235
|
+
const { origin, extentAtZoom0 } = grid();
|
|
300
236
|
const n = 2 ** z;
|
|
301
237
|
if (!Number.isInteger(z) || z < 0 || z > 30)
|
|
302
238
|
throw new RangeError('z must be an integer in 0..=30');
|
|
@@ -306,11 +242,15 @@ export class MapRenderer {
|
|
|
306
242
|
const [minX, maxY] = [origin[0] + x * s, origin[1] - y * s];
|
|
307
243
|
return [minX, maxY - s, minX + s, maxY];
|
|
308
244
|
};
|
|
309
|
-
const render = (view
|
|
245
|
+
const render = async (view) => this.draw(view, ...this.projectedArgs(projjson, view));
|
|
310
246
|
return {
|
|
311
247
|
crs,
|
|
312
|
-
render: (
|
|
313
|
-
|
|
248
|
+
render: async ({ bbox, size, pixelRatio, margin }) => {
|
|
249
|
+
const [minX, minY, maxX, maxY] = bbox;
|
|
250
|
+
const [width, height] = fitSize(maxX - minX, maxY - minY, size);
|
|
251
|
+
return render({ bbox, width, height, pixelRatio, margin });
|
|
252
|
+
},
|
|
253
|
+
renderTile: async ({ tileSize = 256, pixelRatio, margin, ...tile }) => {
|
|
314
254
|
if (!Number.isInteger(tileSize) || tileSize < 1)
|
|
315
255
|
throw new RangeError('tileSize must be a positive integer');
|
|
316
256
|
return render({ bbox: box(tile), width: tileSize, height: tileSize, pixelRatio, margin });
|
|
@@ -322,18 +262,20 @@ export class MapRenderer {
|
|
|
322
262
|
if (!Number.isFinite(x) || !Number.isFinite(y))
|
|
323
263
|
throw new RangeError('center is outside the CRS');
|
|
324
264
|
// CRS units per CSS pixel.
|
|
325
|
-
const unit = extentAtZoom0 / (512 * 2 ** zoom);
|
|
265
|
+
const unit = grid().extentAtZoom0 / (512 * 2 ** zoom);
|
|
326
266
|
const [w, h] = [(width / 2) * unit, (height / 2) * unit];
|
|
327
267
|
// The box at bearing 0, which the core turns around its center.
|
|
328
|
-
return render({ bbox: [x - w, y - h, x + w, y + h], width, height, pixelRatio, margin }
|
|
268
|
+
return render({ bbox: [x - w, y - h, x + w, y + h], bearing, width, height, pixelRatio, margin });
|
|
329
269
|
},
|
|
330
|
-
getTile: (tile) => {
|
|
270
|
+
getTile: async (tile) => {
|
|
331
271
|
if (typeof tile.source !== 'string' || !tile.source)
|
|
332
272
|
throw new TypeError('source must be a source id');
|
|
333
273
|
const view = { bbox: box(tile), width: 512, height: 512 };
|
|
334
274
|
return this.run(...this.projectedArgs(projjson, view), encoder.encode(tile.source), this.wasm.renderer_export_tile);
|
|
335
275
|
},
|
|
336
276
|
toStyle: ({ tiles }) => {
|
|
277
|
+
if (typeof crs.name !== 'string' || !crs.name)
|
|
278
|
+
throw new TypeError('crs.name is required for toStyle');
|
|
337
279
|
const style = this.original;
|
|
338
280
|
const sources = {};
|
|
339
281
|
for (const [id, source] of Object.entries(style.sources)) {
|
|
@@ -374,11 +316,12 @@ export class MapRenderer {
|
|
|
374
316
|
}
|
|
375
317
|
}
|
|
376
318
|
/** The core arguments and `setView` of a view of the CRS `projjson` (encoded), turned around its center by `bearing`. */
|
|
377
|
-
projectedArgs(projjson, view
|
|
319
|
+
projectedArgs(projjson, view) {
|
|
378
320
|
const margin = marginArg(view.margin);
|
|
379
321
|
const size = sizeArgs(view);
|
|
380
|
-
|
|
381
|
-
|
|
322
|
+
const bearing = view.bearing ?? 0;
|
|
323
|
+
if (![...view.bbox, bearing].every(Number.isFinite))
|
|
324
|
+
throw new RangeError('bbox and bearing must be finite');
|
|
382
325
|
// The initial camera is replaced before the first `needs`.
|
|
383
326
|
return [[0, 0, 0, 0, ...size, 0], (handle) => {
|
|
384
327
|
const ok = this.withBytes(projjson, (ptr, len) => this.wasm.renderer_set_projected_view(handle, ptr, len, ...view.bbox, bearing, ...size, margin));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ml2drender/wasm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "MapLibre style 2D renderer in pure Rust / WebAssembly, no GPU",
|
|
5
5
|
"license": "BSD-3-Clause",
|
|
6
6
|
"repository": {
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"scripts": {
|
|
40
40
|
"build": "tsc -p tsconfig.build.json",
|
|
41
41
|
"typecheck": "tsc --noEmit",
|
|
42
|
-
"test": "node tests/single-flight.ts && node tests/shared-instance.ts && node tests/projected-view.ts",
|
|
42
|
+
"test": "node tests/single-flight.ts && node tests/shared-instance.ts && node tests/projected-view.ts && node tests/unsupported-layers.ts",
|
|
43
43
|
"docs": "typedoc"
|
|
44
44
|
}
|
|
45
45
|
}
|
|
Binary file
|