isard 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.
Files changed (84) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/LICENSE +21 -0
  3. package/README.md +150 -2
  4. package/dist/basemap.worker.d.ts +66 -0
  5. package/dist/basemap.worker.js +4 -0
  6. package/dist/basemap.worker.js.map +13 -0
  7. package/dist/basemaps.d.ts +46 -0
  8. package/dist/basemaps.js +95 -0
  9. package/dist/basemaps.js.map +1 -0
  10. package/dist/color.d.ts +8 -0
  11. package/dist/color.js +98 -0
  12. package/dist/color.js.map +1 -0
  13. package/dist/controls.d.ts +43 -0
  14. package/dist/controls.js +115 -0
  15. package/dist/controls.js.map +1 -0
  16. package/dist/decoder.worker.js +6 -0
  17. package/dist/decoder.worker.js.map +12 -0
  18. package/dist/decoders.d.ts +27 -0
  19. package/dist/decoders.js +109 -0
  20. package/dist/decoders.js.map +1 -0
  21. package/dist/equirectangular.d.ts +35 -0
  22. package/dist/equirectangular.js +113 -0
  23. package/dist/equirectangular.js.map +1 -0
  24. package/dist/extrusions.d.ts +79 -0
  25. package/dist/extrusions.js +215 -0
  26. package/dist/extrusions.js.map +1 -0
  27. package/dist/features.d.ts +159 -0
  28. package/dist/features.js +387 -0
  29. package/dist/features.js.map +1 -0
  30. package/dist/geoplateforme.d.ts +35 -0
  31. package/dist/geoplateforme.js +56 -0
  32. package/dist/geoplateforme.js.map +1 -0
  33. package/dist/glyphs.d.ts +104 -0
  34. package/dist/glyphs.js +383 -0
  35. package/dist/glyphs.js.map +1 -0
  36. package/dist/index.d.ts +34 -0
  37. package/dist/index.js +25 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/interaction.d.ts +50 -0
  40. package/dist/interaction.js +243 -0
  41. package/dist/interaction.js.map +1 -0
  42. package/dist/isard_bg.wasm +0 -0
  43. package/dist/isard_core_bg.wasm +0 -0
  44. package/dist/layers.d.ts +100 -0
  45. package/dist/layers.js +281 -0
  46. package/dist/layers.js.map +1 -0
  47. package/dist/loader.d.ts +30 -0
  48. package/dist/loader.js +102 -0
  49. package/dist/loader.js.map +1 -0
  50. package/dist/map.d.ts +203 -0
  51. package/dist/map.js +1083 -0
  52. package/dist/map.js.map +1 -0
  53. package/dist/mvt.d.ts +19 -0
  54. package/dist/mvt.js +231 -0
  55. package/dist/mvt.js.map +1 -0
  56. package/dist/overlay.d.ts +118 -0
  57. package/dist/overlay.js +334 -0
  58. package/dist/overlay.js.map +1 -0
  59. package/dist/protocol.d.ts +30 -0
  60. package/dist/protocol.js +2 -0
  61. package/dist/protocol.js.map +1 -0
  62. package/dist/style.d.ts +7 -0
  63. package/dist/style.js +130 -0
  64. package/dist/style.js.map +1 -0
  65. package/dist/symbols.d.ts +61 -0
  66. package/dist/symbols.js +238 -0
  67. package/dist/symbols.js.map +1 -0
  68. package/dist/terrain.d.ts +14 -0
  69. package/dist/terrain.js +44 -0
  70. package/dist/terrain.js.map +1 -0
  71. package/dist/types.d.ts +304 -0
  72. package/dist/types.js +2 -0
  73. package/dist/types.js.map +1 -0
  74. package/dist/vectorstyle.d.ts +83 -0
  75. package/dist/vectorstyle.js +518 -0
  76. package/dist/vectorstyle.js.map +1 -0
  77. package/dist/vectortiles.d.ts +121 -0
  78. package/dist/vectortiles.js +507 -0
  79. package/dist/vectortiles.js.map +1 -0
  80. package/dist/wasm/isard.d.ts +611 -0
  81. package/dist/wasm/isard.js +2606 -0
  82. package/dist/wasm/isard_core.d.ts +468 -0
  83. package/dist/wasm/isard_core.js +2360 -0
  84. package/package.json +49 -4
@@ -0,0 +1,56 @@
1
+ /** Credits of the Géoplateforme's data: its basemaps, hillshade, terrain model, rasters and features */
2
+ export const IGN_ATTRIBUTION = '<a href="https://www.ign.fr/">© IGN</a> – <a href="https://geoservices.ign.fr/">Géoplateforme</a>';
3
+ /**
4
+ * A layer of the Géoplateforme's WMTS (its Web Mercator grid, PM) as raster options for `addRaster`, crediting the
5
+ * IGN: `geoplateformeWmts('ORTHOIMAGERY.ORTHOPHOTOS', { format: 'image/jpeg' })`. The layer names are those of its
6
+ * capabilities (https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetCapabilities)
7
+ */
8
+ export function geoplateformeWmts(layer, options = {}) {
9
+ const { format = 'image/png', style = 'normal', ...raster } = options;
10
+ return {
11
+ maxZoom: 19,
12
+ attribution: IGN_ATTRIBUTION,
13
+ ...raster,
14
+ url: `https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&STYLE=${encodeURIComponent(style)}` +
15
+ `&TILEMATRIXSET=PM&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&LAYER=${encodeURIComponent(layer)}&FORMAT=${format}`,
16
+ };
17
+ }
18
+ /**
19
+ * Layers of the Géoplateforme's WMS (raster, `wms-r`) as raster options for `addRaster`, crediting the IGN: 256 px
20
+ * images of each tile asked for in EPSG:3857, transparent where empty. `geoplateformeWms('CADASTRALPARCELS.PARCELLAIRE_EXPRESS')`
21
+ */
22
+ export function geoplateformeWms(layers, options = {}) {
23
+ const { format = 'image/png', styles = '', ...raster } = options;
24
+ return {
25
+ maxZoom: 20,
26
+ attribution: IGN_ATTRIBUTION,
27
+ ...raster,
28
+ url: 'https://data.geopf.fr/wms-r/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&CRS=EPSG:3857&BBOX={bbox}' +
29
+ `&WIDTH=256&HEIGHT=256&TRANSPARENT=TRUE&LAYERS=${encodeURIComponent(layers)}` +
30
+ `&STYLES=${encodeURIComponent(styles)}&FORMAT=${format}`,
31
+ };
32
+ }
33
+ /**
34
+ * Features of the Géoplateforme's WFS in a box (west, south, east, north, degrees), as GeoJSON in longitudes and
35
+ * latitudes: `await geoplateformeWfs('BDTOPO_V3:batiment', [2.41, 48.84, 2.43, 48.85])`. At most `count` features
36
+ * (default 5000). The type names are those of its capabilities (BD TOPO, ADMIN EXPRESS…)
37
+ */
38
+ export async function geoplateformeWfs(typeName, [west, south, east, north], options = {}) {
39
+ const url = new URL('https://data.geopf.fr/wfs/ows');
40
+ url.search = new URLSearchParams({
41
+ SERVICE: 'WFS',
42
+ VERSION: '2.0.0',
43
+ REQUEST: 'GetFeature',
44
+ TYPENAMES: typeName,
45
+ OUTPUTFORMAT: 'application/json',
46
+ SRSNAME: 'EPSG:4326',
47
+ // WFS 2.0 in EPSG:4326: latitude first
48
+ BBOX: `${south},${west},${north},${east},urn:ogc:def:crs:EPSG::4326`,
49
+ COUNT: String(options.count ?? 5000),
50
+ }).toString();
51
+ const response = await fetch(url, options.signal ? { signal: options.signal } : {});
52
+ if (!response.ok)
53
+ throw new Error(`isard: ${typeName}: ${response.status}`);
54
+ return response.json();
55
+ }
56
+ //# sourceMappingURL=geoplateforme.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geoplateforme.js","sourceRoot":"","sources":["../src/geoplateforme.ts"],"names":[],"mappings":"AAQA,wGAAwG;AACxG,MAAM,CAAC,MAAM,eAAe,GAC1B,mGAAmG,CAAC;AAEtG;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAC/B,KAAa,EACb,UAA4E,EAAE;IAE9E,MAAM,EAAE,MAAM,GAAG,WAAW,EAAE,KAAK,GAAG,QAAQ,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC;IACtE,OAAO;QACL,OAAO,EAAE,EAAE;QACX,WAAW,EAAE,eAAe;QAC5B,GAAG,MAAM;QACT,GAAG,EACD,+EAA+E,kBAAkB,CAAC,KAAK,CAAC,EAAE;YAC1G,kEAAkE,kBAAkB,CAAC,KAAK,CAAC,WAAW,MAAM,EAAE;KACjH,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAC9B,MAAc,EACd,UAA6E,EAAE;IAE/E,MAAM,EAAE,MAAM,GAAG,WAAW,EAAE,MAAM,GAAG,EAAE,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC;IACjE,OAAO;QAC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WFS features as\n * GeoJSON. Its basemaps, hillshade, terrain model and vector styles are named options of the map (`'ign-plan'`,\n * `hillshade`, `terrain: 'ign'`, `PLAN_STYLES`); the rasters credit the IGN by themselves.\n */\nimport type { FeatureCollection, Properties } from './features.ts';\nimport type { RasterOptions } from './types.ts';\n\n/** Credits of the Géoplateforme's data: its basemaps, hillshade, terrain model, rasters and features */\nexport const IGN_ATTRIBUTION =\n '<a href=\"https://www.ign.fr/\">© IGN</a> – <a href=\"https://geoservices.ign.fr/\">Géoplateforme</a>';\n\n/**\n * A layer of the Géoplateforme's WMTS (its Web Mercator grid, PM) as raster options for `addRaster`, crediting the\n * IGN: `geoplateformeWmts('ORTHOIMAGERY.ORTHOPHOTOS', { format: 'image/jpeg' })`. The layer names are those of its\n * capabilities (https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetCapabilities)\n */\nexport function geoplateformeWmts(\n layer: string,\n options: { format?: string; style?: string } & Omit<RasterOptions, 'url'> = {},\n): RasterOptions {\n const { format = 'image/png', style = 'normal', ...raster } = options;\n return {\n maxZoom: 19,\n attribution: IGN_ATTRIBUTION,\n ...raster,\n url:\n `https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&STYLE=${encodeURIComponent(style)}` +\n `&TILEMATRIXSET=PM&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&LAYER=${encodeURIComponent(layer)}&FORMAT=${format}`,\n };\n}\n\n/**\n * Layers of the Géoplateforme's WMS (raster, `wms-r`) as raster options for `addRaster`, crediting the IGN: 256 px\n * images of each tile asked for in EPSG:3857, transparent where empty. `geoplateformeWms('CADASTRALPARCELS.PARCELLAIRE_EXPRESS')`\n */\nexport function geoplateformeWms(\n layers: string,\n options: { format?: string; styles?: string } & Omit<RasterOptions, 'url'> = {},\n): RasterOptions {\n const { format = 'image/png', styles = '', ...raster } = options;\n return {\n maxZoom: 20,\n attribution: IGN_ATTRIBUTION,\n ...raster,\n url:\n 'https://data.geopf.fr/wms-r/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&CRS=EPSG:3857&BBOX={bbox}' +\n `&WIDTH=256&HEIGHT=256&TRANSPARENT=TRUE&LAYERS=${encodeURIComponent(layers)}` +\n `&STYLES=${encodeURIComponent(styles)}&FORMAT=${format}`,\n };\n}\n\n/**\n * Features of the Géoplateforme's WFS in a box (west, south, east, north, degrees), as GeoJSON in longitudes and\n * latitudes: `await geoplateformeWfs('BDTOPO_V3:batiment', [2.41, 48.84, 2.43, 48.85])`. At most `count` features\n * (default 5000). The type names are those of its capabilities (BD TOPO, ADMIN EXPRESS…)\n */\nexport async function geoplateformeWfs<P = Properties>(\n typeName: string,\n [west, south, east, north]: [number, number, number, number],\n options: { count?: number; signal?: AbortSignal } = {},\n): Promise<FeatureCollection<P>> {\n const url = new URL('https://data.geopf.fr/wfs/ows');\n url.search = new URLSearchParams({\n SERVICE: 'WFS',\n VERSION: '2.0.0',\n REQUEST: 'GetFeature',\n TYPENAMES: typeName,\n OUTPUTFORMAT: 'application/json',\n SRSNAME: 'EPSG:4326',\n // WFS 2.0 in EPSG:4326: latitude first\n BBOX: `${south},${west},${north},${east},urn:ogc:def:crs:EPSG::4326`,\n COUNT: String(options.count ?? 5000),\n }).toString();\n const response = await fetch(url, options.signal ? { signal: options.signal } : {});\n if (!response.ok) throw new Error(`isard: ${typeName}: ${response.status}`);\n return response.json() as Promise<FeatureCollection<P>>;\n}\n"]}
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Glyphs for the symbol layers: signed distance fields in MapLibre's glyph format (ranges of 256 code points per
3
+ * protobuf file, 24 px glyphs with a 3 px buffer), loaded on first use (from OpenFreeMap's fonts by default, a vector
4
+ * basemap's labels from the glyphs of its style), packed into an atlas the engine samples; and the shaping of a label: its lines (explicit and wrapped), their glyphs placed around
5
+ * the anchor.
6
+ *
7
+ * The atlas has pages of one size: the first one grows up to the page size limit, then pages are added, so it never
8
+ * runs out. A glyph's atlas row counts the rows of the pages before its own (`y + page × size`, the pages stacked):
9
+ * the coordinates of the glyphs placed so far stay valid as the atlas grows.
10
+ */
11
+ import type { Anchor } from './overlay.ts';
12
+ import type { Engine } from './wasm/isard.js';
13
+ /** OpenFreeMap's fonts, those of its styles (Noto Sans Regular, Bold, Italic) */
14
+ export declare const GLYPHS_URL = "https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf";
15
+ /** The font of labels that name none */
16
+ export declare const DEFAULT_FONT = "Noto Sans Regular";
17
+ export interface Glyph {
18
+ width: number;
19
+ height: number;
20
+ left: number;
21
+ top: number;
22
+ advance: number;
23
+ /**
24
+ * Place of its bitmap ((width + 6) × (height + 6)) in the atlas, `y` counting the rows of the pages before its
25
+ * own; undefined for an empty one (a space)
26
+ */
27
+ x?: number;
28
+ y?: number;
29
+ /** Its page of the atlas */
30
+ page?: number;
31
+ }
32
+ /** The glyphs of a map and their atlas */
33
+ export declare class Glyphs {
34
+ private readonly url;
35
+ /** Side of the pages */
36
+ private size;
37
+ private pages;
38
+ /** Pages allocated in the engine (doubled when more are needed: fewer reallocations) */
39
+ private capacity;
40
+ private shelves;
41
+ private readonly fonts;
42
+ private readonly ranges;
43
+ /** Glyph URLs of fonts other than the map's (those of a vector basemap's style) */
44
+ private readonly sources;
45
+ private engine;
46
+ /** Rows of each page changed since the last upload: first, end */
47
+ private readonly dirty;
48
+ /** The atlas has its most pages: new glyphs stay blank */
49
+ private full;
50
+ /** Largest side of a page */
51
+ private readonly maxSize;
52
+ /** `maxSize`: the GPU's texture size limit if known (the pages are at most 2048 × 2048) */
53
+ constructor(url?: string, maxSize?: number);
54
+ /** Sends the whole atlas to an engine (a new one after a context loss) */
55
+ attach(engine: Engine): void;
56
+ /** Side of the pages of the atlas */
57
+ get atlasSize(): number;
58
+ get pageCount(): number;
59
+ /** Loads these fonts from another glyph URL (a style's `glyphs`); a font keeps the first URL given for it */
60
+ register(url: string, fonts: Iterable<string>): void;
61
+ /** Loads the glyphs of these code points in a font */
62
+ load(font: string, codes: Iterable<number>): Promise<Map<number, Glyph>>;
63
+ private range;
64
+ /** Allocates the pages in the engine and sends them all */
65
+ private upload;
66
+ /** Sends the rows changed since the last upload to the engine */
67
+ private flush;
68
+ /**
69
+ * Places a bitmap in the atlas (growing the first page, then adding pages when full); `flush` sends it to the
70
+ * engine
71
+ */
72
+ private pack;
73
+ /** Doubles the only page; the glyphs keep their places (texel coordinates) */
74
+ private grow;
75
+ /** A new empty page, after the others; the engine's pages are allocated again only past its capacity */
76
+ private addPage;
77
+ }
78
+ /** A run of text with its own scale (MapLibre's `format` with `font-scale`) and font */
79
+ export interface TextPart {
80
+ text: string;
81
+ scale?: number;
82
+ font?: string;
83
+ }
84
+ export type { Anchor } from './overlay.ts';
85
+ export interface Shaping {
86
+ /** Glyph quads: x, y, width, height (CSS pixels from the anchor), atlas u0, v0, u1, v1, font scale */
87
+ quads: number[][];
88
+ /** Ink box from the anchor: min x, min y, max x, max y */
89
+ box: [number, number, number, number];
90
+ }
91
+ /** Code points of a text, for loading */
92
+ export declare function codes(parts: readonly TextPart[]): Set<number>;
93
+ /**
94
+ * Lays out a label: lines split at `\n` and wrapped at `maxWidth` ems, centered, the block placed by `anchor` around
95
+ * the anchor point and moved by `offset` (ems); `size` in CSS pixels. Glyphs not loaded take no room.
96
+ */
97
+ export declare function shape(parts: readonly TextPart[], glyphsOf: (font: string) => Map<number, Glyph> | undefined, options: {
98
+ font: string;
99
+ size: number;
100
+ maxWidth: number;
101
+ lineHeight: number;
102
+ anchor: Anchor;
103
+ offset: [number, number];
104
+ }): Shaping;
package/dist/glyphs.js ADDED
@@ -0,0 +1,383 @@
1
+ /** OpenFreeMap's fonts, those of its styles (Noto Sans Regular, Bold, Italic) */
2
+ export const GLYPHS_URL = 'https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf';
3
+ /** The font of labels that name none */
4
+ export const DEFAULT_FONT = 'Noto Sans Regular';
5
+ /** Size the glyphs are drawn at in the files, and their buffer */
6
+ const EM = 24;
7
+ const BUFFER = 3;
8
+ /** Largest side of a page of the atlas, and most pages (WebGL2 guarantees 256 layers of a texture array) */
9
+ const PAGE_MAX = 2048;
10
+ const MAX_PAGES = 256;
11
+ /** A protobuf reader, enough for the glyph files */
12
+ class Reader {
13
+ buf;
14
+ pos = 0;
15
+ constructor(buf) {
16
+ this.buf = buf;
17
+ }
18
+ get done() {
19
+ return this.pos >= this.buf.length;
20
+ }
21
+ varint() {
22
+ let value = 0;
23
+ let shift = 0;
24
+ for (;;) {
25
+ const b = this.buf[this.pos++] ?? 0;
26
+ value += (b & 0x7f) * 2 ** shift;
27
+ if (b < 0x80)
28
+ return value;
29
+ shift += 7;
30
+ }
31
+ }
32
+ sint() {
33
+ const v = this.varint();
34
+ return v % 2 === 1 ? -(v + 1) / 2 : v / 2;
35
+ }
36
+ bytes() {
37
+ const n = this.varint();
38
+ const out = this.buf.subarray(this.pos, this.pos + n);
39
+ this.pos += n;
40
+ return out;
41
+ }
42
+ skip(wire) {
43
+ if (wire === 0)
44
+ this.varint();
45
+ else if (wire === 2)
46
+ this.pos += this.varint();
47
+ else if (wire === 5)
48
+ this.pos += 4;
49
+ else if (wire === 1)
50
+ this.pos += 8;
51
+ }
52
+ }
53
+ /** Glyphs of a range file: id → metrics and bitmap */
54
+ function parse(buffer) {
55
+ const out = new Map();
56
+ const root = new Reader(new Uint8Array(buffer));
57
+ while (!root.done) {
58
+ const tag = root.varint();
59
+ if (tag >> 3 !== 1) {
60
+ root.skip(tag & 7);
61
+ continue;
62
+ }
63
+ // A fontstack
64
+ const stack = new Reader(root.bytes());
65
+ while (!stack.done) {
66
+ const t = stack.varint();
67
+ if (t >> 3 !== 3) {
68
+ stack.skip(t & 7);
69
+ continue;
70
+ }
71
+ const g = new Reader(stack.bytes());
72
+ let id = 0;
73
+ let bitmap = new Uint8Array(0);
74
+ const glyph = { width: 0, height: 0, left: 0, top: 0, advance: 0 };
75
+ while (!g.done) {
76
+ const f = g.varint();
77
+ switch (f >> 3) {
78
+ case 1:
79
+ id = g.varint();
80
+ break;
81
+ case 2:
82
+ bitmap = g.bytes();
83
+ break;
84
+ case 3:
85
+ glyph.width = g.varint();
86
+ break;
87
+ case 4:
88
+ glyph.height = g.varint();
89
+ break;
90
+ case 5:
91
+ glyph.left = g.sint();
92
+ break;
93
+ case 6:
94
+ glyph.top = g.sint();
95
+ break;
96
+ case 7:
97
+ glyph.advance = g.varint();
98
+ break;
99
+ default:
100
+ g.skip(f & 7);
101
+ }
102
+ }
103
+ out.set(id, { glyph, bitmap });
104
+ }
105
+ }
106
+ return out;
107
+ }
108
+ /** The glyphs of a map and their atlas */
109
+ export class Glyphs {
110
+ url;
111
+ /** Side of the pages */
112
+ size = 512;
113
+ pages = [new Uint8Array(512 * 512)];
114
+ /** Pages allocated in the engine (doubled when more are needed: fewer reallocations) */
115
+ capacity = 1;
116
+ shelves = [];
117
+ fonts = new Map();
118
+ ranges = new Map();
119
+ /** Glyph URLs of fonts other than the map's (those of a vector basemap's style) */
120
+ sources = new Map();
121
+ engine;
122
+ /** Rows of each page changed since the last upload: first, end */
123
+ dirty = new Map();
124
+ /** The atlas has its most pages: new glyphs stay blank */
125
+ full = false;
126
+ /** Largest side of a page */
127
+ maxSize;
128
+ /** `maxSize`: the GPU's texture size limit if known (the pages are at most 2048 × 2048) */
129
+ constructor(url = GLYPHS_URL, maxSize = 4096) {
130
+ this.url = url;
131
+ this.maxSize = Math.max(512, Math.min(PAGE_MAX, maxSize));
132
+ }
133
+ /** Sends the whole atlas to an engine (a new one after a context loss) */
134
+ attach(engine) {
135
+ this.engine = engine;
136
+ this.dirty.clear();
137
+ this.upload();
138
+ }
139
+ /** Side of the pages of the atlas */
140
+ get atlasSize() {
141
+ return this.size;
142
+ }
143
+ get pageCount() {
144
+ return this.pages.length;
145
+ }
146
+ /** Loads these fonts from another glyph URL (a style's `glyphs`); a font keeps the first URL given for it */
147
+ register(url, fonts) {
148
+ for (const font of fonts)
149
+ if (!this.sources.has(font))
150
+ this.sources.set(font, url);
151
+ }
152
+ /** Loads the glyphs of these code points in a font */
153
+ async load(font, codes) {
154
+ const glyphs = this.fonts.get(font) ?? new Map();
155
+ this.fonts.set(font, glyphs);
156
+ const starts = new Set();
157
+ for (const code of codes)
158
+ if (!glyphs.has(code))
159
+ starts.add(Math.floor(code / 256) * 256);
160
+ await Promise.all([...starts].map((start) => this.range(font, start, glyphs)));
161
+ return glyphs;
162
+ }
163
+ range(font, start, glyphs) {
164
+ const key = `${font}/${start}`;
165
+ let pending = this.ranges.get(key);
166
+ if (!pending) {
167
+ const url = (this.sources.get(font) ?? this.url)
168
+ .replace('{fontstack}', encodeURIComponent(font))
169
+ .replace('{range}', `${start}-${start + 255}`);
170
+ pending = fetch(url)
171
+ .then((r) => (r.ok ? r.arrayBuffer() : Promise.reject(new Error(`${url}: ${r.status}`))))
172
+ .then((buffer) => {
173
+ for (const [id, { glyph, bitmap }] of parse(buffer)) {
174
+ if (glyph.width > 0 && bitmap.length >= (glyph.width + 2 * BUFFER) * (glyph.height + 2 * BUFFER)) {
175
+ this.pack(glyph, bitmap);
176
+ }
177
+ glyphs.set(id, glyph);
178
+ }
179
+ // One upload for the range
180
+ this.flush();
181
+ })
182
+ .catch((error) => {
183
+ // A missing range is not retried this session; its characters stay blank
184
+ console.warn('isard: glyphs', error);
185
+ });
186
+ this.ranges.set(key, pending);
187
+ }
188
+ return pending;
189
+ }
190
+ /** Allocates the pages in the engine and sends them all */
191
+ upload() {
192
+ const engine = this.engine;
193
+ if (!engine)
194
+ return;
195
+ engine.setGlyphPages(this.size, this.size, this.capacity);
196
+ this.pages.forEach((page, i) => {
197
+ engine.updateGlyphPage(i, 0, 0, this.size, this.size, page);
198
+ });
199
+ }
200
+ /** Sends the rows changed since the last upload to the engine */
201
+ flush() {
202
+ for (const [page, [y0, y1]] of this.dirty) {
203
+ const data = this.pages[page];
204
+ if (data)
205
+ this.engine?.updateGlyphPage(page, 0, y0, this.size, y1 - y0, data.subarray(y0 * this.size, y1 * this.size));
206
+ }
207
+ this.dirty.clear();
208
+ }
209
+ /**
210
+ * Places a bitmap in the atlas (growing the first page, then adding pages when full); `flush` sends it to the
211
+ * engine
212
+ */
213
+ pack(glyph, bitmap) {
214
+ const w = glyph.width + 2 * BUFFER;
215
+ const h = glyph.height + 2 * BUFFER;
216
+ // One texel of padding between bitmaps: linear filtering never reads a neighbour
217
+ let shelf = this.shelves.find((s) => s.height >= h && s.height <= h + 4 && s.x + w + 1 <= this.size);
218
+ if (!shelf) {
219
+ const page = this.pages.length - 1;
220
+ // New shelves go on the last page only: the last shelf is on it, unless the page is new
221
+ const last = this.shelves.at(-1);
222
+ const y = last && last.page === page ? last.y + last.height + 1 : 0;
223
+ if (y + h > this.size) {
224
+ if (this.pages.length === 1 && this.size * 2 <= this.maxSize)
225
+ this.grow();
226
+ else if (this.pages.length < MAX_PAGES)
227
+ this.addPage();
228
+ else {
229
+ // Full: the glyph takes its room in the text but is not drawn
230
+ if (!this.full)
231
+ console.warn(`isard: the glyph atlas is full (${MAX_PAGES} pages)`);
232
+ this.full = true;
233
+ return;
234
+ }
235
+ this.pack(glyph, bitmap);
236
+ return;
237
+ }
238
+ shelf = { page, y, height: h, x: 0 };
239
+ this.shelves.push(shelf);
240
+ }
241
+ const data = this.pages[shelf.page];
242
+ if (!data)
243
+ return;
244
+ glyph.x = shelf.x;
245
+ glyph.y = shelf.page * this.size + shelf.y;
246
+ glyph.page = shelf.page;
247
+ shelf.x += w + 1;
248
+ for (let row = 0; row < h; row += 1) {
249
+ data.set(bitmap.subarray(row * w, row * w + w), (shelf.y + row) * this.size + glyph.x);
250
+ }
251
+ const dirty = this.dirty.get(shelf.page);
252
+ this.dirty.set(shelf.page, [Math.min(dirty?.[0] ?? shelf.y, shelf.y), Math.max(dirty?.[1] ?? 0, shelf.y + h)]);
253
+ }
254
+ /** Doubles the only page; the glyphs keep their places (texel coordinates) */
255
+ grow() {
256
+ const size = this.size * 2;
257
+ const old = this.pages[0] ?? new Uint8Array(this.size * this.size);
258
+ const page = new Uint8Array(size * size);
259
+ for (let row = 0; row < this.size; row += 1) {
260
+ page.set(old.subarray(row * this.size, (row + 1) * this.size), row * size);
261
+ }
262
+ this.size = size;
263
+ this.pages = [page];
264
+ // The whole atlas is sent with what it holds so far
265
+ this.dirty.clear();
266
+ this.upload();
267
+ }
268
+ /** A new empty page, after the others; the engine's pages are allocated again only past its capacity */
269
+ addPage() {
270
+ this.pages.push(new Uint8Array(this.size * this.size));
271
+ if (this.pages.length > this.capacity) {
272
+ this.capacity = Math.min(MAX_PAGES, this.capacity * 2);
273
+ // The pages are allocated again: everything is sent, pending changes included
274
+ this.dirty.clear();
275
+ this.upload();
276
+ }
277
+ }
278
+ }
279
+ /** Code points of a text, for loading */
280
+ export function codes(parts) {
281
+ const out = new Set();
282
+ for (const p of parts)
283
+ for (const ch of p.text)
284
+ out.add(ch.codePointAt(0) ?? 32);
285
+ return out;
286
+ }
287
+ /**
288
+ * Lays out a label: lines split at `\n` and wrapped at `maxWidth` ems, centered, the block placed by `anchor` around
289
+ * the anchor point and moved by `offset` (ems); `size` in CSS pixels. Glyphs not loaded take no room.
290
+ */
291
+ export function shape(parts, glyphsOf, options) {
292
+ const { size, maxWidth, lineHeight, anchor, offset } = options;
293
+ const k = size / EM;
294
+ const lines = [[]];
295
+ for (const part of parts) {
296
+ const glyphs = glyphsOf(part.font ?? options.font);
297
+ for (const ch of part.text) {
298
+ if (ch === '\n') {
299
+ lines.push([]);
300
+ continue;
301
+ }
302
+ const code = ch.codePointAt(0) ?? 32;
303
+ lines.at(-1)?.push({ glyph: glyphs?.get(code), scale: part.scale ?? 1, space: /\s/.test(ch) });
304
+ }
305
+ }
306
+ const advance = (c) => (c.glyph?.advance ?? (c.space ? EM / 4 : 0)) * c.scale;
307
+ // Wrapping at spaces, greedy
308
+ const limit = maxWidth * EM;
309
+ const wrapped = [];
310
+ for (const line of lines) {
311
+ let current = [];
312
+ let width = 0;
313
+ let lastSpace = -1;
314
+ for (const c of line) {
315
+ current.push(c);
316
+ width += advance(c);
317
+ if (c.space)
318
+ lastSpace = current.length - 1;
319
+ if (width > limit && lastSpace > 0) {
320
+ wrapped.push(current.slice(0, lastSpace));
321
+ current = current.slice(lastSpace + 1);
322
+ width = current.reduce((s, x) => s + advance(x), 0);
323
+ lastSpace = -1;
324
+ }
325
+ }
326
+ wrapped.push(current);
327
+ }
328
+ // Glyphs on their lines, each line centered on x = 0, in units of the 24 px font
329
+ const quads = [];
330
+ let [x0, y0, x1, y1] = [
331
+ Number.POSITIVE_INFINITY,
332
+ Number.POSITIVE_INFINITY,
333
+ Number.NEGATIVE_INFINITY,
334
+ Number.NEGATIVE_INFINITY,
335
+ ];
336
+ let baseline = 0;
337
+ wrapped.forEach((line, i) => {
338
+ const scale = Math.max(1, ...line.map((c) => c.scale));
339
+ if (i > 0)
340
+ baseline += lineHeight * EM * scale;
341
+ const width = line.reduce((s, c) => s + advance(c), 0);
342
+ let pen = -width / 2;
343
+ for (const c of line) {
344
+ const g = c.glyph;
345
+ if (g && g.x !== undefined && g.y !== undefined && g.width > 0) {
346
+ const qx = pen + (g.left - BUFFER) * c.scale;
347
+ const qy = baseline - (g.top + BUFFER) * c.scale;
348
+ const qw = (g.width + 2 * BUFFER) * c.scale;
349
+ const qh = (g.height + 2 * BUFFER) * c.scale;
350
+ quads.push([qx, qy, qw, qh, g.x, g.y, g.x + g.width + 2 * BUFFER, g.y + g.height + 2 * BUFFER, c.scale]);
351
+ x0 = Math.min(x0, qx + BUFFER * c.scale);
352
+ y0 = Math.min(y0, qy + BUFFER * c.scale);
353
+ x1 = Math.max(x1, qx + qw - BUFFER * c.scale);
354
+ y1 = Math.max(y1, qy + qh - BUFFER * c.scale);
355
+ }
356
+ pen += advance(c);
357
+ }
358
+ });
359
+ if (!quads.length)
360
+ return { quads, box: [0, 0, 0, 0] };
361
+ // The block placed around the anchor by its ink box
362
+ // The side of the box at the anchor: its start, its end, or its middle
363
+ const side = (start, end, lo, hi) => {
364
+ if (start)
365
+ return -lo;
366
+ if (end)
367
+ return -hi;
368
+ return -(lo + hi) / 2;
369
+ };
370
+ const horizontal = side(anchor.includes('left'), anchor.includes('right'), x0, x1);
371
+ const vertical = side(anchor.startsWith('top'), anchor.startsWith('bottom'), y0, y1);
372
+ const dx = horizontal + offset[0] * EM;
373
+ const dy = vertical + offset[1] * EM;
374
+ for (const q of quads) {
375
+ q[0] = ((q[0] ?? 0) + dx) * k;
376
+ q[1] = ((q[1] ?? 0) + dy) * k;
377
+ q[2] = (q[2] ?? 0) * k;
378
+ q[3] = (q[3] ?? 0) * k;
379
+ q[8] = (q[8] ?? 1) * k;
380
+ }
381
+ return { quads, box: [(x0 + dx) * k, (y0 + dy) * k, (x1 + dx) * k, (y1 + dy) * k] };
382
+ }
383
+ //# sourceMappingURL=glyphs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"glyphs.js","sourceRoot":"","sources":["../src/glyphs.ts"],"names":[],"mappings":"AAaA,iFAAiF;AACjF,MAAM,CAAC,MAAM,UAAU,GAAG,6DAA6D,CAAC;AAExF,wCAAwC;AACxC,MAAM,CAAC,MAAM,YAAY,GAAG,mBAAmB,CAAC;AAEhD,kEAAkE;AAClE,MAAM,EAAE,GAAG,EAAE,CAAC;AACd,MAAM,MAAM,GAAG,CAAC,CAAC;AAkBjB,4GAA4G;AAC5G,MAAM,QAAQ,GAAG,IAAI,CAAC;AACtB,MAAM,SAAS,GAAG,GAAG,CAAC;AAEtB,oDAAoD;AACpD,MAAM,MAAM;IAEmB;IAD7B,GAAG,GAAG,CAAC,CAAC;IACR,YAA6B,GAAe;QAAf,QAAG,GAAH,GAAG,CAAY;IAAG,CAAC;IAChD,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC;IACrC,CAAC;IACD,MAAM;QACJ,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,SAAS,CAAC;YACR,MAAM,CAAC,GAAG,IA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ranges of 256 code points per\n * protobuf file, 24 px glyphs with a 3 px buffer), loaded on first use (from OpenFreeMap's fonts by default, a vector\n * basemap's labels from the glyphs of its style), packed into an atlas the engine samples; and the shaping of a label: its lines (explicit and wrapped), their glyphs placed around\n * the anchor.\n *\n * The atlas has pages of one size: the first one grows up to the page size limit, then pages are added, so it never\n * runs out. A glyph's atlas row counts the rows of the pages before its own (`y + page × size`, the pages stacked):\n * the coordinates of the glyphs placed so far stay valid as the atlas grows.\n */\nimport type { Anchor } from './overlay.ts';\nimport type { Engine } from './wasm/isard.js';\n\n/** OpenFreeMap's fonts, those of its styles (Noto Sans Regular, Bold, Italic) */\nexport const GLYPHS_URL = 'https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf';\n\n/** The font of labels that name none */\nexport const DEFAULT_FONT = 'Noto Sans Regular';\n\n/** Size the glyphs are drawn at in the files, and their buffer */\nconst EM = 24;\nconst BUFFER = 3;\n\nexport interface Glyph {\n width: number;\n height: number;\n left: number;\n top: number;\n advance: number;\n /**\n * Place of its bitmap ((width + 6) × (height + 6)) in the atlas, `y` counting the rows of the pages before its\n * own; undefined for an empty one (a space)\n */\n x?: number;\n y?: number;\n /** Its page of the atlas */\n page?: number;\n}\n\n/** Largest side of a page of the atlas, and most pages (WebGL2 guarantees 256 layers of a texture array) */\nconst PAGE_MAX = 2048;\nconst MAX_PAGES = 256;\n\n/** A protobuf reader, enough for the glyph files */\nclass Reader {\n pos = 0;\n constructor(private readonly buf: Uint8Array) {}\n get done(): boolean {\n return this.pos >= this.buf.length;\n }\n varint(): number {\n let value = 0;\n let shift = 0;\n for (;;) {\n const b = this.buf[this.pos++] ?? 0;\n value += (b & 0x7f) * 2 ** shift;\n if (b < 0x80) return value;\n shift += 7;\n }\n }\n sint(): number {\n const v = this.varint();\n return v % 2 === 1 ? -(v + 1) / 2 : v / 2;\n }\n bytes(): Uint8Array {\n const n = this.varint();\n const out = this.buf.subarray(this.pos, this.pos + n);\n this.pos += n;\n return out;\n }\n skip(wire: number): void {\n if (wire === 0) this.varint();\n else if (wire === 2) this.pos += this.varint();\n else if (wire === 5) this.pos += 4;\n else if (wire === 1) this.pos += 8;\n }\n}\n\n/** Glyphs of a range file: id → metrics and bitmap */\nfunction parse(buffer: ArrayBuffer): Map<number, { glyph: Glyph; bitmap: Uint8Array }> {\n const out = new Map<number, { glyph: Glyph; bitmap: Uint8Array }>();\n const root = new Reader(new Uint8Array(buffer));\n while (!root.done) {\n const tag = root.varint();\n if (tag >> 3 !== 1) {\n root.skip(tag & 7);\n continue;\n }\n // A fontstack\n const stack = new Reader(root.bytes());\n while (!stack.done) {\n const t = stack.varint();\n if (t >> 3 !== 3) {\n stack.skip(t & 7);\n continue;\n }\n const g = new Reader(stack.bytes());\n let id = 0;\n let bitmap: Uint8Array = new Uint8Array(0);\n const glyph: Glyph = { width: 0, height: 0, left: 0, top: 0, advance: 0 };\n while (!g.done) {\n const f = g.varint();\n switch (f >> 3) {\n case 1:\n id = g.varint();\n break;\n case 2:\n bitmap = g.bytes();\n break;\n case 3:\n glyph.width = g.varint();\n break;\n case 4:\n glyph.height = g.varint();\n break;\n case 5:\n glyph.left = g.sint();\n break;\n case 6:\n glyph.top = g.sint();\n break;\n case 7:\n glyph.advance = g.varint();\n break;\n default:\n g.skip(f & 7);\n }\n }\n out.set(id, { glyph, bitmap });\n }\n }\n return out;\n}\n\n/** A shelf of the packer: its page, y, height, and the x of the next free place */\ninterface Shelf {\n page: number;\n y: number;\n height: number;\n x: number;\n}\n\n/** The glyphs of a map and their atlas */\nexport class Glyphs {\n /** Side of the pages */\n private size = 512;\n private pages: Uint8Array[] = [new Uint8Array(512 * 512)];\n /** Pages allocated in the engine (doubled when more are needed: fewer reallocations) */\n private capacity = 1;\n private shelves: Shelf[] = [];\n private readonly fonts = new Map<string, Map<number, Glyph>>();\n private readonly ranges = new Map<string, Promise<void>>();\n /** Glyph URLs of fonts other than the map's (those of a vector basemap's style) */\n private readonly sources = new Map<string, string>();\n private engine: Engine | undefined;\n /** Rows of each page changed since the last upload: first, end */\n private readonly dirty = new Map<number, [number, number]>();\n /** The atlas has its most pages: new glyphs stay blank */\n private full = false;\n /** Largest side of a page */\n private readonly maxSize: number;\n\n /** `maxSize`: the GPU's texture size limit if known (the pages are at most 2048 × 2048) */\n constructor(\n private readonly url = GLYPHS_URL,\n maxSize = 4096,\n ) {\n this.maxSize = Math.max(512, Math.min(PAGE_MAX, maxSize));\n }\n\n /** Sends the whole atlas to an engine (a new one after a context loss) */\n attach(engine: Engine): void {\n this.engine = engine;\n this.dirty.clear();\n this.upload();\n }\n\n /** Side of the pages of the atlas */\n get atlasSize(): number {\n return this.size;\n }\n\n get pageCount(): number {\n return this.pages.length;\n }\n\n /** Loads these fonts from another glyph URL (a style's `glyphs`); a font keeps the first URL given for it */\n register(url: string, fonts: Iterable<string>): void {\n for (const font of fonts) if (!this.sources.has(font)) this.sources.set(font, url);\n }\n\n /** Loads the glyphs of these code points in a font */\n async load(font: string, codes: Iterable<number>): Promise<Map<number, Glyph>> {\n const glyphs = this.fonts.get(font) ?? new Map<number, Glyph>();\n this.fonts.set(font, glyphs);\n const starts = new Set<number>();\n for (const code of codes) if (!glyphs.has(code)) starts.add(Math.floor(code / 256) * 256);\n await Promise.all([...starts].map((start) => this.range(font, start, glyphs)));\n return glyphs;\n }\n\n private range(font: string, start: number, glyphs: Map<number, Glyph>): Promise<void> {\n const key = `${font}/${start}`;\n let pending = this.ranges.get(key);\n if (!pending) {\n const url = (this.sources.get(font) ?? this.url)\n .replace('{fontstack}', encodeURIComponent(font))\n .replace('{range}', `${start}-${start + 255}`);\n pending = fetch(url)\n .then((r) => (r.ok ? r.arrayBuffer() : Promise.reject(new Error(`${url}: ${r.status}`))))\n .then((buffer) => {\n for (const [id, { glyph, bitmap }] of parse(buffer)) {\n if (glyph.width > 0 && bitmap.length >= (glyph.width + 2 * BUFFER) * (glyph.height + 2 * BUFFER)) {\n this.pack(glyph, bitmap);\n }\n glyphs.set(id, glyph);\n }\n // One upload for the range\n this.flush();\n })\n .catch((error: unknown) => {\n // A missing range is not retried this session; its characters stay blank\n console.warn('isard: glyphs', error);\n });\n this.ranges.set(key, pending);\n }\n return pending;\n }\n\n /** Allocates the pages in the engine and sends them all */\n private upload(): void {\n const engine = this.engine;\n if (!engine) return;\n engine.setGlyphPages(this.size, this.size, this.capacity);\n this.pages.forEach((page, i) => {\n engine.updateGlyphPage(i, 0, 0, this.size, this.size, page);\n });\n }\n\n /** Sends the rows changed since the last upload to the engine */\n private flush(): void {\n for (const [page, [y0, y1]] of this.dirty) {\n const data = this.pages[page];\n if (data)\n this.engine?.updateGlyphPage(page, 0, y0, this.size, y1 - y0, data.subarray(y0 * this.size, y1 * this.size));\n }\n this.dirty.clear();\n }\n\n /**\n * Places a bitmap in the atlas (growing the first page, then adding pages when full); `flush` sends it to the\n * engine\n */\n private pack(glyph: Glyph, bitmap: Uint8Array): void {\n const w = glyph.width + 2 * BUFFER;\n const h = glyph.height + 2 * BUFFER;\n // One texel of padding between bitmaps: linear filtering never reads a neighbour\n let shelf = this.shelves.find((s) => s.height >= h && s.height <= h + 4 && s.x + w + 1 <= this.size);\n if (!shelf) {\n const page = this.pages.length - 1;\n // New shelves go on the last page only: the last shelf is on it, unless the page is new\n const last = this.shelves.at(-1);\n const y = last && last.page === page ? last.y + last.height + 1 : 0;\n if (y + h > this.size) {\n if (this.pages.length === 1 && this.size * 2 <= this.maxSize) this.grow();\n else if (this.pages.length < MAX_PAGES) this.addPage();\n else {\n // Full: the glyph takes its room in the text but is not drawn\n if (!this.full) console.warn(`isard: the glyph atlas is full (${MAX_PAGES} pages)`);\n this.full = true;\n return;\n }\n this.pack(glyph, bitmap);\n return;\n }\n shelf = { page, y, height: h, x: 0 };\n this.shelves.push(shelf);\n }\n const data = this.pages[shelf.page];\n if (!data) return;\n glyph.x = shelf.x;\n glyph.y = shelf.page * this.size + shelf.y;\n glyph.page = shelf.page;\n shelf.x += w + 1;\n for (let row = 0; row < h; row += 1) {\n data.set(bitmap.subarray(row * w, row * w + w), (shelf.y + row) * this.size + glyph.x);\n }\n const dirty = this.dirty.get(shelf.page);\n this.dirty.set(shelf.page, [Math.min(dirty?.[0] ?? shelf.y, shelf.y), Math.max(dirty?.[1] ?? 0, shelf.y + h)]);\n }\n\n /** Doubles the only page; the glyphs keep their places (texel coordinates) */\n private grow(): void {\n const size = this.size * 2;\n const old = this.pages[0] ?? new Uint8Array(this.size * this.size);\n const page = new Uint8Array(size * size);\n for (let row = 0; row < this.size; row += 1) {\n page.set(old.subarray(row * this.size, (row + 1) * this.size), row * size);\n }\n this.size = size;\n this.pages = [page];\n // The whole atlas is sent with what it holds so far\n this.dirty.clear();\n this.upload();\n }\n\n /** A new empty page, after the others; the engine's pages are allocated again only past its capacity */\n private addPage(): void {\n this.pages.push(new Uint8Array(this.size * this.size));\n if (this.pages.length > this.capacity) {\n this.capacity = Math.min(MAX_PAGES, this.capacity * 2);\n // The pages are allocated again: everything is sent, pending changes included\n this.dirty.clear();\n this.upload();\n }\n }\n}\n\n/** A run of text with its own scale (MapLibre's `format` with `font-scale`) and font */\nexport interface TextPart {\n text: string;\n scale?: number;\n font?: string;\n}\n\nexport type { Anchor } from './overlay.ts';\n\nexport interface Shaping {\n /** Glyph quads: x, y, width, height (CSS pixels from the anchor), atlas u0, v0, u1, v1, font scale */\n quads: number[][];\n /** Ink box from the anchor: min x, min y, max x, max y */\n box: [number, number, number, number];\n}\n\n/** Code points of a text, for loading */\nexport function codes(parts: readonly TextPart[]): Set<number> {\n const out = new Set<number>();\n for (const p of parts) for (const ch of p.text) out.add(ch.codePointAt(0) ?? 32);\n return out;\n}\n\n/**\n * Lays out a label: lines split at `\\n` and wrapped at `maxWidth` ems, centered, the block placed by `anchor` around\n * the anchor point and moved by `offset` (ems); `size` in CSS pixels. Glyphs not loaded take no room.\n */\nexport function shape(\n parts: readonly TextPart[],\n glyphsOf: (font: string) => Map<number, Glyph> | undefined,\n options: {\n font: string;\n size: number;\n maxWidth: number;\n lineHeight: number;\n anchor: Anchor;\n offset: [number, number];\n },\n): Shaping {\n const { size, maxWidth, lineHeight, anchor, offset } = options;\n const k = size / EM;\n // Characters with their glyph and scale, split into lines\n type Char = { glyph: Glyph | undefined; scale: number; space: boolean };\n const lines: Char[][] = [[]];\n for (const part of parts) {\n const glyphs = glyphsOf(part.font ?? options.font);\n for (const ch of part.text) {\n if (ch === '\\n') {\n lines.push([]);\n continue;\n }\n const code = ch.codePointAt(0) ?? 32;\n lines.at(-1)?.push({ glyph: glyphs?.get(code), scale: part.scale ?? 1, space: /\\s/.test(ch) });\n }\n }\n const advance = (c: Char) => (c.glyph?.advance ?? (c.space ? EM / 4 : 0)) * c.scale;\n // Wrapping at spaces, greedy\n const limit = maxWidth * EM;\n const wrapped: Char[][] = [];\n for (const line of lines) {\n let current: Char[] = [];\n let width = 0;\n let lastSpace = -1;\n for (const c of line) {\n current.push(c);\n width += advance(c);\n if (c.space) lastSpace = current.length - 1;\n if (width > limit && lastSpace > 0) {\n wrapped.push(current.slice(0, lastSpace));\n current = current.slice(lastSpace + 1);\n width = current.reduce((s, x) => s + advance(x), 0);\n lastSpace = -1;\n }\n }\n wrapped.push(current);\n }\n // Glyphs on their lines, each line centered on x = 0, in units of the 24 px font\n const quads: number[][] = [];\n let [x0, y0, x1, y1] = [\n Number.POSITIVE_INFINITY,\n Number.POSITIVE_INFINITY,\n Number.NEGATIVE_INFINITY,\n Number.NEGATIVE_INFINITY,\n ];\n let baseline = 0;\n wrapped.forEach((line, i) => {\n const scale = Math.max(1, ...line.map((c) => c.scale));\n if (i > 0) baseline += lineHeight * EM * scale;\n const width = line.reduce((s, c) => s + advance(c), 0);\n let pen = -width / 2;\n for (const c of line) {\n const g = c.glyph;\n if (g && g.x !== undefined && g.y !== undefined && g.width > 0) {\n const qx = pen + (g.left - BUFFER) * c.scale;\n const qy = baseline - (g.top + BUFFER) * c.scale;\n const qw = (g.width + 2 * BUFFER) * c.scale;\n const qh = (g.height + 2 * BUFFER) * c.scale;\n quads.push([qx, qy, qw, qh, g.x, g.y, g.x + g.width + 2 * BUFFER, g.y + g.height + 2 * BUFFER, c.scale]);\n x0 = Math.min(x0, qx + BUFFER * c.scale);\n y0 = Math.min(y0, qy + BUFFER * c.scale);\n x1 = Math.max(x1, qx + qw - BUFFER * c.scale);\n y1 = Math.max(y1, qy + qh - BUFFER * c.scale);\n }\n pen += advance(c);\n }\n });\n if (!quads.length) return { quads, box: [0, 0, 0, 0] };\n // The block placed around the anchor by its ink box\n // The side of the box at the anchor: its start, its end, or its middle\n const side = (start: boolean, end: boolean, lo: number, hi: number) => {\n if (start) return -lo;\n if (end) return -hi;\n return -(lo + hi) / 2;\n };\n const horizontal = side(anchor.includes('left'), anchor.includes('right'), x0, x1);\n const vertical = side(anchor.startsWith('top'), anchor.startsWith('bottom'), y0, y1);\n const dx = horizontal + offset[0] * EM;\n const dy = vertical + offset[1] * EM;\n for (const q of quads) {\n q[0] = ((q[0] ?? 0) + dx) * k;\n q[1] = ((q[1] ?? 0) + dy) * k;\n q[2] = (q[2] ?? 0) * k;\n q[3] = (q[3] ?? 0) * k;\n q[8] = (q[8] ?? 1) * k;\n }\n return { quads, box: [(x0 + dx) * k, (y0 + dy) * k, (x1 + dx) * k, (y1 + dy) * k] };\n}\n"]}