isard 0.3.0 → 0.5.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 (62) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +11 -3
  3. package/dist/basemap.worker.d.ts +10 -3
  4. package/dist/basemap.worker.js +2 -2
  5. package/dist/basemap.worker.js.map +4 -4
  6. package/dist/decoder.worker.js +4 -4
  7. package/dist/decoder.worker.js.map +7 -6
  8. package/dist/decoders.d.ts +3 -2
  9. package/dist/decoders.js +28 -5
  10. package/dist/decoders.js.map +1 -1
  11. package/dist/engine-loader.d.ts +8 -4
  12. package/dist/engine-loader.js +10 -3
  13. package/dist/engine-loader.js.map +1 -1
  14. package/dist/formats.d.ts +11 -0
  15. package/dist/formats.js +12 -0
  16. package/dist/formats.js.map +1 -0
  17. package/dist/glyphs.d.ts +3 -0
  18. package/dist/glyphs.js +12 -2
  19. package/dist/glyphs.js.map +1 -1
  20. package/dist/icons.d.ts +146 -0
  21. package/dist/icons.js +333 -0
  22. package/dist/icons.js.map +1 -0
  23. package/dist/index.d.ts +8 -5
  24. package/dist/index.js +2 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/isard_bg.wasm +0 -0
  27. package/dist/isard_core_bg.wasm +0 -0
  28. package/dist/isard_points_bg.wasm +0 -0
  29. package/dist/layers.d.ts +88 -1
  30. package/dist/layers.js +165 -4
  31. package/dist/layers.js.map +1 -1
  32. package/dist/loader.d.ts +9 -3
  33. package/dist/loader.js +22 -3
  34. package/dist/loader.js.map +1 -1
  35. package/dist/map.d.ts +37 -3
  36. package/dist/map.js +76 -10
  37. package/dist/map.js.map +1 -1
  38. package/dist/pointclouds.d.ts +98 -0
  39. package/dist/pointclouds.js +232 -0
  40. package/dist/pointclouds.js.map +1 -0
  41. package/dist/projections.d.ts +13 -0
  42. package/dist/projections.js +13 -0
  43. package/dist/projections.js.map +1 -0
  44. package/dist/protocol.d.ts +17 -0
  45. package/dist/protocol.js.map +1 -1
  46. package/dist/symbols.d.ts +42 -8
  47. package/dist/symbols.js +160 -35
  48. package/dist/symbols.js.map +1 -1
  49. package/dist/types.d.ts +8 -3
  50. package/dist/types.js.map +1 -1
  51. package/dist/vectorstyle.d.ts +32 -3
  52. package/dist/vectorstyle.js.map +1 -1
  53. package/dist/vectortiles.d.ts +10 -5
  54. package/dist/vectortiles.js +54 -29
  55. package/dist/vectortiles.js.map +1 -1
  56. package/dist/wasm/isard.d.ts +168 -11
  57. package/dist/wasm/isard.js +234 -9
  58. package/dist/wasm/isard_core.d.ts +28 -3
  59. package/dist/wasm/isard_core.js +77 -4
  60. package/dist/wasm/isard_points.d.ts +43 -0
  61. package/dist/wasm/isard_points.js +212 -0
  62. package/package.json +17 -1
@@ -15,13 +15,14 @@ import type { CompressedTexture, DracoGeometry, DracoRequest, TextureFormats } f
15
15
  * to your server and give their folders in `GeoMapOptions.decoders`.
16
16
  */
17
17
  export interface DecoderUrls {
18
- /** Folder of `draco_wasm_wrapper_gltf.js` and `draco_decoder_gltf.wasm` */
18
+ /** Folder of `draco_wasm_wrapper_gltf.js` and `draco_decoder_gltf.wasm` (and, for Draco point clouds, of the full
19
+ * decoder `draco_wasm_wrapper.js` and `draco_decoder.wasm`) */
19
20
  draco: string;
20
21
  /** Folder of `basis_transcoder.js` and `basis_transcoder.wasm` */
21
22
  basis: string;
22
23
  }
23
24
  export declare const DEFAULT_DECODERS: DecoderUrls;
24
- /** Decodes the Draco primitives of a tile */
25
+ /** Decodes the Draco primitives of a tile (their points alone for point clouds) */
25
26
  export declare function decodeDraco(urls: DecoderUrls, requests: DracoRequest[]): Promise<DracoGeometry[]>;
26
27
  /** Transcodes a KTX2 image for the GPU */
27
28
  export declare function transcodeKtx2(urls: DecoderUrls, formats: TextureFormats, bytes: Uint8Array): Promise<CompressedTexture>;
package/dist/decoders.js CHANGED
@@ -16,17 +16,28 @@ async function instantiate(base, script, wasm, name) {
16
16
  return create({ wasmBinary: binary });
17
17
  }
18
18
  let draco;
19
+ /** The full Draco decoder: the glTF build decodes meshes only, not the point clouds */
20
+ let dracoPoints;
19
21
  let basis;
20
- /** Decodes the Draco primitives of a tile */
22
+ /** Decodes the Draco primitives of a tile (their points alone for point clouds) */
21
23
  export async function decodeDraco(urls, requests) {
22
- draco ??= instantiate(urls.draco, 'draco_wasm_wrapper_gltf.js', 'draco_decoder_gltf.wasm', 'DracoDecoderModule');
23
- const module = await draco;
24
+ const meshes = requests.some((r) => !r.points);
25
+ if (meshes) {
26
+ draco ??= instantiate(urls.draco, 'draco_wasm_wrapper_gltf.js', 'draco_decoder_gltf.wasm', 'DracoDecoderModule');
27
+ }
28
+ if (requests.some((r) => r.points)) {
29
+ dracoPoints ??= instantiate(urls.draco, 'draco_wasm_wrapper.js', 'draco_decoder.wasm', 'DracoDecoderModule');
30
+ }
31
+ const [forMeshes, forPoints] = await Promise.all([meshes ? draco : undefined, dracoPoints]);
24
32
  return requests.map((request) => {
33
+ const module = (request.points ? forPoints : forMeshes);
25
34
  const decoder = new module.Decoder();
26
- const mesh = new module.Mesh();
35
+ const mesh = request.points ? new module.PointCloud() : new module.Mesh();
27
36
  try {
28
37
  const data = new Int8Array(request.data.buffer, request.data.byteOffset, request.data.byteLength);
29
- const status = decoder.DecodeArrayToMesh(data, data.byteLength, mesh);
38
+ const status = request.points
39
+ ? decoder.DecodeArrayToPointCloud(data, data.byteLength, mesh)
40
+ : decoder.DecodeArrayToMesh(data, data.byteLength, mesh);
30
41
  if (!status.ok())
31
42
  throw new Error(`Draco: ${status.error_msg()}`);
32
43
  const floats = (id) => {
@@ -41,6 +52,18 @@ export async function decodeDraco(urls, requests) {
41
52
  module._free(pointer);
42
53
  }
43
54
  };
55
+ if (request.points) {
56
+ const geometry = {
57
+ mesh: request.mesh,
58
+ primitive: request.primitive,
59
+ positions: floats(request.position),
60
+ };
61
+ if (request.color !== undefined)
62
+ geometry.colors = floats(request.color);
63
+ if (request.normal !== undefined)
64
+ geometry.normals = floats(request.normal);
65
+ return geometry;
66
+ }
44
67
  const count = mesh.num_faces() * 3;
45
68
  const pointer = module._malloc(count * 4);
46
69
  let indices;
@@ -1 +1 @@
1
- {"version":3,"file":"decoders.js","sourceRoot":"","sources":["../src/decoders.ts"],"names":[],"mappings":"AAwBA,MAAM,CAAC,MAAM,gBAAgB,GAAgB;IAC3C,KAAK,EAAE,yDAAyD;IAChE,KAAK,EAAE,qEAAqE;CAC7E,CAAC;AAmEF;yEACyE;AACzE,KAAK,UAAU,OAAO,CAAI,GAAW,EAAE,IAAY;IACjD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAC/C,OAAO,IAAI,QAAQ,CAAC,GAAG,MAAM,YAAY,IAAI,GAAG,CAAC,EAAgB,CAAC;AACpE,CAAC;AAED,KAAK,UAAU,WAAW,CAAI,IAAY,EAAE,MAAc,EAAE,IAAY,EAAE,IAAY;IACpF,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACzC,OAAO,CAAI,GAAG,IAAI,GAAG,MAAM,EAAE,EAAE,IAAI,CAAC;QACpC,KAAK,CAAC,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;KACrD,CAAC,CAAC;IACH,OAAO,MAAM,CAAC,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAC;AACxC,CAAC;AAED,IAAI,KAAuC,CAAC;AAC5C,IAAI,KAAuC,CAAC;AAE5C,6CAA6C;AAC7C,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,IAAiB,EAAE,QAAwB;IAC3E,KAAK,KAAK,WAAW,CACnB,IAAI,CAAC,KAAK,EACV,4BAA4B,EAC5B,yBAAyB,EACzB,oBAAoB,CACrB,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,KA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AE,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC;QAClE,MAAM,MAAM,GAAgC,EAAE,CAAC;QAC/C,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,SAAS,EAAE,EAAE,KAAK,EAAE,EAAE,CAAC;YACtD,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YACrF,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,6BAA6B,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;YACrF,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;YAC5G,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACvC,CAAC;QACD,OAAO,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC;IAChC,CAAC;YAAS,CAAC;QACT,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,IAAI,CAAC,MAAM,EAAE,CAAC;IAChB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Optional decoders of the worker, loaded on first use from configurable URLs (the official builds three.js and\n * Cesium use): Draco geometry (`KHR_draco_mesh_compression`) and KTX2 / Basis Universal textures (`KHR_texture_basisu`),\n * transcoded to the best compressed format the GPU supports.\n */\nimport type { CompressedTexture, DracoGeometry, DracoRequest, TextureFormats } from './wasm/isard.js';\n\n/**\n * Base URLs of the decoders (each ending with `/`).\n *\n * The decoders are Emscripten builds published as classic scripts: the worker fetches the script and runs it with\n * `new Function`, so a Content Security Policy must allow `'unsafe-eval'` in `script-src` (or `worker-src`) for 3D\n * Tiles that use Draco or KTX2. They are fetched from the default CDNs; to self-host them (offline, locked-down\n * networks, no third-party requests), copy the four files (`draco_wasm_wrapper_gltf.js`, `draco_decoder_gltf.wasm`\n * from the Draco release, `basis_transcoder.js`, `basis_transcoder.wasm` from three.js's `examples/jsm/libs/basis/`)\n * to your server and give their folders in `GeoMapOptions.decoders`.\n */\nexport interface DecoderUrls {\n /** Folder of `draco_wasm_wrapper_gltf.js` and `draco_decoder_gltf.wasm` */\n draco: string;\n /** Folder of `basis_transcoder.js` and `basis_transcoder.wasm` */\n basis: string;\n}\n\nexport const DEFAULT_DECODERS: DecoderUrls = {\n draco: 'https://www.gstatic.com/draco/versioned/decoders/1.5.7/',\n basis: 'https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/libs/basis/',\n};\n\n// ── Draco (the subset of its Emscripten API used here) ──\n\ninterface DracoStatus {\n ok(): boolean;\n error_msg(): string;\n}\ninterface DracoMesh {\n num_points(): number;\n num_faces(): number;\n}\ninterface DracoAttribute {\n num_components(): number;\n}\ninterface DracoDecoder {\n DecodeArrayToMesh(data: Int8Array, size: number, mesh: DracoMesh): DracoStatus;\n GetAttributeByUniqueId(mesh: DracoMesh, id: number): DracoAttribute;\n GetAttributeDataArrayForAllPoints(\n mesh: DracoMesh,\n attribute: DracoAttribute,\n type: number,\n bytes: number,\n pointer: number,\n ): boolean;\n GetTrianglesUInt32Array(mesh: DracoMesh, bytes: number, pointer: number): boolean;\n}\ninterface DracoModule {\n Decoder: new () => DracoDecoder;\n Mesh: new () => DracoMesh;\n DT_FLOAT32: number;\n HEAPF32: Float32Array;\n HEAPU32: Uint32Array;\n _malloc(bytes: number): number;\n _free(pointer: number): void;\n destroy(object: object): void;\n}\n\n// ── Basis Universal transcoder ──\n\ninterface KTX2File {\n isValid(): boolean;\n getLevels(): number;\n getHasAlpha(): boolean;\n startTranscoding(): boolean;\n getImageLevelInfo(level: number, layer: number, face: number): { origWidth: number; origHeight: number };\n getImageTranscodedSizeInBytes(level: number, layer: number, face: number, format: number): number;\n transcodeImage(\n target: Uint8Array,\n level: number,\n layer: number,\n face: number,\n format: number,\n alphaForOpaque: number,\n channel0: number,\n channel1: number,\n ): boolean;\n close(): void;\n delete(): void;\n}\ninterface BasisModule {\n initializeBasis(): void;\n KTX2File: new (data: Uint8Array) => KTX2File;\n}\n\ntype Factory<T> = (options: { wasmBinary: ArrayBuffer }) => Promise<T>;\n\n/** Loads an Emscripten factory published as a classic script (module workers have no importScripts); needs\n * `'unsafe-eval'` under a Content Security Policy (see `DecoderUrls`) */\nasync function factory<T>(url: string, name: string): Promise<Factory<T>> {\n const source = await (await fetch(url)).text();\n return new Function(`${source}\\nreturn ${name};`)() as Factory<T>;\n}\n\nasync function instantiate<T>(base: string, script: string, wasm: string, name: string): Promise<T> {\n const [create, binary] = await Promise.all([\n factory<T>(`${base}${script}`, name),\n fetch(`${base}${wasm}`).then((r) => r.arrayBuffer()),\n ]);\n return create({ wasmBinary: binary });\n}\n\nlet draco: Promise<DracoModule> | undefined;\nlet basis: Promise<BasisModule> | undefined;\n\n/** Decodes the Draco primitives of a tile */\nexport async function decodeDraco(urls: DecoderUrls, requests: DracoRequest[]): Promise<DracoGeometry[]> {\n draco ??= instantiate<DracoModule>(\n urls.draco,\n 'draco_wasm_wrapper_gltf.js',\n 'draco_decoder_gltf.wasm',\n 'DracoDecoderModule',\n );\n const module = await draco;\n return requests.map((request) => {\n const decoder = new module.Decoder();\n const mesh = new module.Mesh();\n try {\n const data = new Int8Array(request.data.buffer, request.data.byteOffset, request.data.byteLength);\n const status = decoder.DecodeArrayToMesh(data, data.byteLength, mesh);\n if (!status.ok()) throw new Error(`Draco: ${status.error_msg()}`);\n const floats = (id: number): Float32Array => {\n const attribute = decoder.GetAttributeByUniqueId(mesh, id);\n const count = mesh.num_points() * attribute.num_components();\n const pointer = module._malloc(count * 4);\n try {\n decoder.GetAttributeDataArrayForAllPoints(mesh, attribute, module.DT_FLOAT32, count * 4, pointer);\n return module.HEAPF32.slice(pointer / 4, pointer / 4 + count);\n } finally {\n module._free(pointer);\n }\n };\n const count = mesh.num_faces() * 3;\n const pointer = module._malloc(count * 4);\n let indices: Uint32Array;\n try {\n decoder.GetTrianglesUInt32Array(mesh, count * 4, pointer);\n indices = module.HEAPU32.slice(pointer / 4, pointer / 4 + count);\n } finally {\n module._free(pointer);\n }\n const geometry: DracoGeometry = {\n mesh: request.mesh,\n primitive: request.primitive,\n positions: floats(request.position),\n indices,\n };\n if (request.uv !== undefined) geometry.uvs = floats(request.uv);\n return geometry;\n } finally {\n module.destroy(mesh);\n module.destroy(decoder);\n }\n });\n}\n\n/** Basis target format and WebGL internal format, best first */\nfunction target(formats: TextureFormats, alpha: boolean): { basis: number; gl: number } {\n if (formats.astc) return { basis: 10, gl: 0x93b0 }; // ASTC 4×4\n if (formats.bptc) return { basis: 6, gl: 0x8e8c }; // BC7\n if (formats.etc) return alpha ? { basis: 1, gl: 0x9278 } : { basis: 0, gl: 0x9274 }; // ETC2 RGBA / ETC1 as ETC2 RGB\n if (formats.s3tc) return alpha ? { basis: 3, gl: 0x83f3 } : { basis: 2, gl: 0x83f0 }; // BC3 / BC1\n return { basis: 13, gl: 0x8058 }; // RGBA8, uncompressed\n}\n\n/** Transcodes a KTX2 image for the GPU */\nexport async function transcodeKtx2(\n urls: DecoderUrls,\n formats: TextureFormats,\n bytes: Uint8Array,\n): Promise<CompressedTexture> {\n basis ??= instantiate<BasisModule>(urls.basis, 'basis_transcoder.js', 'basis_transcoder.wasm', 'BASIS').then((m) => {\n m.initializeBasis();\n return m;\n });\n const module = await basis;\n const file = new module.KTX2File(bytes);\n try {\n if (!file.isValid() || !file.startTranscoding()) throw new Error('KTX2: invalid file');\n const { basis: format, gl } = target(formats, file.getHasAlpha());\n const levels: CompressedTexture['levels'] = [];\n for (let level = 0; level < file.getLevels(); level++) {\n const { origWidth: width, origHeight: height } = file.getImageLevelInfo(level, 0, 0);\n const data = new Uint8Array(file.getImageTranscodedSizeInBytes(level, 0, 0, format));\n if (!file.transcodeImage(data, level, 0, 0, format, 0, -1, -1)) throw new Error('KTX2: transcoding failed');\n levels.push({ width, height, data });\n }\n return { format: gl, levels };\n } finally {\n file.close();\n file.delete();\n }\n}\n"]}
1
+ {"version":3,"file":"decoders.js","sourceRoot":"","sources":["../src/decoders.ts"],"names":[],"mappings":"AAyBA,MAAM,CAAC,MAAM,gBAAgB,GAAgB;IAC3C,KAAK,EAAE,yDAAyD;IAChE,KAAK,EAAE,qEAAqE;CAC7E,CAAC;AAqEF;yEACyE;AACzE,KAAK,UAAU,OAAO,CAAI,GAAW,EAAE,IAAY;IACjD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAC/C,OAAO,IAAI,QAAQ,CAAC,GAAG,MAAM,YAAY,IAAI,GAAG,CAAC,EAAgB,CAAC;AACpE,CAAC;AAED,KAAK,UAAU,WAAW,CAAI,IAAY,EAAE,MAAc,EAAE,IAAY,EAAE,IAAY;IACpF,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACzC,OAAO,CAAI,GAAG,IAAI,GAAG,MAAM,EAAE,EAAE,IAAI,CAAC;QACpC,KAAK,CAAC,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;KACrD,CAAC,CAAC;IACH,OAAO,MAAM,CAAC,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAC;AACxC,CAAC;AAED,IAAI,KAAuC,CAAC;AAC5C,uFAAuF;AACvF,IAAI,WAA6C,CAAC;AAClD,IAAI,KAAuC,CAAC;AAE5C,mFAAmF;AACnF,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,IAAiB,EAAE,QA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ACxC,IAAI,CAAC;QACH,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;QACvF,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,GAAG,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC;QAClE,MAAM,MAAM,GAAgC,EAAE,CAAC;QAC/C,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,SAAS,EAAE,EAAE,KAAK,EAAE,EAAE,CAAC;YACtD,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YACrF,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,6BAA6B,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;YACrF,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;YAC5G,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACvC,CAAC;QACD,OAAO,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC;IAChC,CAAC;YAAS,CAAC;QACT,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,IAAI,CAAC,MAAM,EAAE,CAAC;IAChB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Optional decoders of the worker, loaded on first use from configurable URLs (the official builds three.js and\n * Cesium use): Draco geometry (`KHR_draco_mesh_compression`) and KTX2 / Basis Universal textures (`KHR_texture_basisu`),\n * transcoded to the best compressed format the GPU supports.\n */\nimport type { CompressedTexture, DracoGeometry, DracoRequest, TextureFormats } from './wasm/isard.js';\n\n/**\n * Base URLs of the decoders (each ending with `/`).\n *\n * The decoders are Emscripten builds published as classic scripts: the worker fetches the script and runs it with\n * `new Function`, so a Content Security Policy must allow `'unsafe-eval'` in `script-src` (or `worker-src`) for 3D\n * Tiles that use Draco or KTX2. They are fetched from the default CDNs; to self-host them (offline, locked-down\n * networks, no third-party requests), copy the four files (`draco_wasm_wrapper_gltf.js`, `draco_decoder_gltf.wasm`\n * from the Draco release, `basis_transcoder.js`, `basis_transcoder.wasm` from three.js's `examples/jsm/libs/basis/`)\n * to your server and give their folders in `GeoMapOptions.decoders`.\n */\nexport interface DecoderUrls {\n /** Folder of `draco_wasm_wrapper_gltf.js` and `draco_decoder_gltf.wasm` (and, for Draco point clouds, of the full\n * decoder `draco_wasm_wrapper.js` and `draco_decoder.wasm`) */\n draco: string;\n /** Folder of `basis_transcoder.js` and `basis_transcoder.wasm` */\n basis: string;\n}\n\nexport const DEFAULT_DECODERS: DecoderUrls = {\n draco: 'https://www.gstatic.com/draco/versioned/decoders/1.5.7/',\n basis: 'https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/libs/basis/',\n};\n\n// ── Draco (the subset of its Emscripten API used here) ──\n\ninterface DracoStatus {\n ok(): boolean;\n error_msg(): string;\n}\ninterface DracoMesh {\n num_points(): number;\n num_faces(): number;\n}\ninterface DracoAttribute {\n num_components(): number;\n}\ninterface DracoDecoder {\n DecodeArrayToMesh(data: Int8Array, size: number, mesh: DracoMesh): DracoStatus;\n DecodeArrayToPointCloud(data: Int8Array, size: number, cloud: DracoMesh): DracoStatus;\n GetAttributeByUniqueId(mesh: DracoMesh, id: number): DracoAttribute;\n GetAttributeDataArrayForAllPoints(\n mesh: DracoMesh,\n attribute: DracoAttribute,\n type: number,\n bytes: number,\n pointer: number,\n ): boolean;\n GetTrianglesUInt32Array(mesh: DracoMesh, bytes: number, pointer: number): boolean;\n}\ninterface DracoModule {\n Decoder: new () => DracoDecoder;\n Mesh: new () => DracoMesh;\n PointCloud: new () => DracoMesh;\n DT_FLOAT32: number;\n HEAPF32: Float32Array;\n HEAPU32: Uint32Array;\n _malloc(bytes: number): number;\n _free(pointer: number): void;\n destroy(object: object): void;\n}\n\n// ── Basis Universal transcoder ──\n\ninterface KTX2File {\n isValid(): boolean;\n getLevels(): number;\n getHasAlpha(): boolean;\n startTranscoding(): boolean;\n getImageLevelInfo(level: number, layer: number, face: number): { origWidth: number; origHeight: number };\n getImageTranscodedSizeInBytes(level: number, layer: number, face: number, format: number): number;\n transcodeImage(\n target: Uint8Array,\n level: number,\n layer: number,\n face: number,\n format: number,\n alphaForOpaque: number,\n channel0: number,\n channel1: number,\n ): boolean;\n close(): void;\n delete(): void;\n}\ninterface BasisModule {\n initializeBasis(): void;\n KTX2File: new (data: Uint8Array) => KTX2File;\n}\n\ntype Factory<T> = (options: { wasmBinary: ArrayBuffer }) => Promise<T>;\n\n/** Loads an Emscripten factory published as a classic script (module workers have no importScripts); needs\n * `'unsafe-eval'` under a Content Security Policy (see `DecoderUrls`) */\nasync function factory<T>(url: string, name: string): Promise<Factory<T>> {\n const source = await (await fetch(url)).text();\n return new Function(`${source}\\nreturn ${name};`)() as Factory<T>;\n}\n\nasync function instantiate<T>(base: string, script: string, wasm: string, name: string): Promise<T> {\n const [create, binary] = await Promise.all([\n factory<T>(`${base}${script}`, name),\n fetch(`${base}${wasm}`).then((r) => r.arrayBuffer()),\n ]);\n return create({ wasmBinary: binary });\n}\n\nlet draco: Promise<DracoModule> | undefined;\n/** The full Draco decoder: the glTF build decodes meshes only, not the point clouds */\nlet dracoPoints: Promise<DracoModule> | undefined;\nlet basis: Promise<BasisModule> | undefined;\n\n/** Decodes the Draco primitives of a tile (their points alone for point clouds) */\nexport async function decodeDraco(urls: DecoderUrls, requests: DracoRequest[]): Promise<DracoGeometry[]> {\n const meshes = requests.some((r) => !r.points);\n if (meshes) {\n draco ??= instantiate<DracoModule>(\n urls.draco,\n 'draco_wasm_wrapper_gltf.js',\n 'draco_decoder_gltf.wasm',\n 'DracoDecoderModule',\n );\n }\n if (requests.some((r) => r.points)) {\n dracoPoints ??= instantiate<DracoModule>(\n urls.draco,\n 'draco_wasm_wrapper.js',\n 'draco_decoder.wasm',\n 'DracoDecoderModule',\n );\n }\n const [forMeshes, forPoints] = await Promise.all([meshes ? draco : undefined, dracoPoints]);\n return requests.map((request) => {\n const module = (request.points ? forPoints : forMeshes) as DracoModule;\n const decoder = new module.Decoder();\n const mesh = request.points ? new module.PointCloud() : new module.Mesh();\n try {\n const data = new Int8Array(request.data.buffer, request.data.byteOffset, request.data.byteLength);\n const status = request.points\n ? decoder.DecodeArrayToPointCloud(data, data.byteLength, mesh)\n : decoder.DecodeArrayToMesh(data, data.byteLength, mesh);\n if (!status.ok()) throw new Error(`Draco: ${status.error_msg()}`);\n const floats = (id: number): Float32Array => {\n const attribute = decoder.GetAttributeByUniqueId(mesh, id);\n const count = mesh.num_points() * attribute.num_components();\n const pointer = module._malloc(count * 4);\n try {\n decoder.GetAttributeDataArrayForAllPoints(mesh, attribute, module.DT_FLOAT32, count * 4, pointer);\n return module.HEAPF32.slice(pointer / 4, pointer / 4 + count);\n } finally {\n module._free(pointer);\n }\n };\n if (request.points) {\n const geometry: DracoGeometry = {\n mesh: request.mesh,\n primitive: request.primitive,\n positions: floats(request.position),\n };\n if (request.color !== undefined) geometry.colors = floats(request.color);\n if (request.normal !== undefined) geometry.normals = floats(request.normal);\n return geometry;\n }\n const count = mesh.num_faces() * 3;\n const pointer = module._malloc(count * 4);\n let indices: Uint32Array;\n try {\n decoder.GetTrianglesUInt32Array(mesh, count * 4, pointer);\n indices = module.HEAPU32.slice(pointer / 4, pointer / 4 + count);\n } finally {\n module._free(pointer);\n }\n const geometry: DracoGeometry = {\n mesh: request.mesh,\n primitive: request.primitive,\n positions: floats(request.position),\n indices,\n };\n if (request.uv !== undefined) geometry.uvs = floats(request.uv);\n return geometry;\n } finally {\n module.destroy(mesh);\n module.destroy(decoder);\n }\n });\n}\n\n/** Basis target format and WebGL internal format, best first */\nfunction target(formats: TextureFormats, alpha: boolean): { basis: number; gl: number } {\n if (formats.astc) return { basis: 10, gl: 0x93b0 }; // ASTC 4×4\n if (formats.bptc) return { basis: 6, gl: 0x8e8c }; // BC7\n if (formats.etc) return alpha ? { basis: 1, gl: 0x9278 } : { basis: 0, gl: 0x9274 }; // ETC2 RGBA / ETC1 as ETC2 RGB\n if (formats.s3tc) return alpha ? { basis: 3, gl: 0x83f3 } : { basis: 2, gl: 0x83f0 }; // BC3 / BC1\n return { basis: 13, gl: 0x8058 }; // RGBA8, uncompressed\n}\n\n/** Transcodes a KTX2 image for the GPU */\nexport async function transcodeKtx2(\n urls: DecoderUrls,\n formats: TextureFormats,\n bytes: Uint8Array,\n): Promise<CompressedTexture> {\n basis ??= instantiate<BasisModule>(urls.basis, 'basis_transcoder.js', 'basis_transcoder.wasm', 'BASIS').then((m) => {\n m.initializeBasis();\n return m;\n });\n const module = await basis;\n const file = new module.KTX2File(bytes);\n try {\n if (!file.isValid() || !file.startTranscoding()) throw new Error('KTX2: invalid file');\n const { basis: format, gl } = target(formats, file.getHasAlpha());\n const levels: CompressedTexture['levels'] = [];\n for (let level = 0; level < file.getLevels(); level++) {\n const { origWidth: width, origHeight: height } = file.getImageLevelInfo(level, 0, 0);\n const data = new Uint8Array(file.getImageTranscodedSizeInBytes(level, 0, 0, format));\n if (!file.transcodeImage(data, level, 0, 0, format, 0, -1, -1)) throw new Error('KTX2: transcoding failed');\n levels.push({ width, height, data });\n }\n return { format: gl, levels };\n } finally {\n file.close();\n file.delete();\n }\n}\n"]}
@@ -1,7 +1,8 @@
1
1
  import { TileLoader } from './loader.ts';
2
2
  import type { GeoMapOptions } from './types.ts';
3
3
  import type { Camera, Engine } from './wasm/isard.js';
4
- export type EngineClass = new (canvas: HTMLCanvasElement, redraw: () => void) => Engine;
4
+ /** The class of an engine build: its constructor and its static `customMatrix` (custom layers) */
5
+ export type EngineClass = (new (canvas: HTMLCanvasElement, redraw: () => void) => Engine) & Pick<typeof Engine, 'customMatrix'>;
5
6
  /** An engine loaded: its compiled module and its class */
6
7
  export interface Bindings {
7
8
  module: WebAssembly.Module;
@@ -19,9 +20,12 @@ export declare function loadFullEngineLater(url: string | URL): Promise<Bindings
19
20
  /** Downloads and compiles the full engine when the page is idle, without running it; a failure is left to the first
20
21
  * 3D Tiles layer, which tries again */
21
22
  export declare function preloadFullEngine(url: string | URL, wanted: () => boolean): void;
22
- /** The decoding workers of 3D Tiles, running the full engine's module, unless turned off (`workers: false` or 0, or
23
- * no workers in this environment) */
24
- export declare function startTileLoader(module: WebAssembly.Module, options: Pick<GeoMapOptions, 'workers' | 'workerUrl' | 'decoders'>, engine: Engine): TileLoader | undefined;
23
+ /** Where the workers load the point cloud module from (`isard_points_bg.wasm`, the LAZ decoder): the option, or next
24
+ * to the module; absolute, the workers being elsewhere */
25
+ export declare function pointsUrl(options: Pick<GeoMapOptions, 'pointsWasmUrl'>): string;
26
+ /** The decoding workers of 3D Tiles and point clouds, running the full engine's module, unless turned off (`workers:
27
+ * false` or 0, or no workers in this environment) */
28
+ export declare function startTileLoader(module: WebAssembly.Module, options: Pick<GeoMapOptions, 'workers' | 'workerUrl' | 'decoders' | 'pointsWasmUrl'>, engine: Engine): TileLoader | undefined;
25
29
  /** The engine of a destroyed map: every method a no-op returning undefined, but the camera (the last one) and the
26
30
  * bounds, which late callers read */
27
31
  export declare function destroyedEngine(camera: Camera): Engine;
@@ -87,14 +87,21 @@ async function compile(url) {
87
87
  return WebAssembly.compile(await response.arrayBuffer());
88
88
  }
89
89
  }
90
- /** The decoding workers of 3D Tiles, running the full engine's module, unless turned off (`workers: false` or 0, or
91
- * no workers in this environment) */
90
+ /** Where the workers load the point cloud module from (`isard_points_bg.wasm`, the LAZ decoder): the option, or next
91
+ * to the module; absolute, the workers being elsewhere */
92
+ export function pointsUrl(options) {
93
+ const url = options.pointsWasmUrl ?? new URL('./isard_points_bg.wasm', import.meta.url);
94
+ const base = typeof document === 'undefined' ? undefined : document.baseURI;
95
+ return base ? new URL(url, base).href : String(url);
96
+ }
97
+ /** The decoding workers of 3D Tiles and point clouds, running the full engine's module, unless turned off (`workers:
98
+ * false` or 0, or no workers in this environment) */
92
99
  export function startTileLoader(module, options, engine) {
93
100
  const { workers: count, workerUrl, decoders } = options;
94
101
  const workers = count ?? defaultWorkerCount();
95
102
  if (workers === false || workers <= 0 || typeof Worker === 'undefined')
96
103
  return undefined;
97
- return new TileLoader(module, workerUrl ?? new URL('./decoder.worker.js', import.meta.url), workers, { ...DEFAULT_DECODERS, ...decoders }, engine.textureFormats());
104
+ return new TileLoader(module, workerUrl ?? new URL('./decoder.worker.js', import.meta.url), workers, { ...DEFAULT_DECODERS, ...decoders }, engine.textureFormats(), pointsUrl(options));
98
105
  }
99
106
  /** The engine of a destroyed map: every method a no-op returning undefined, but the camera (the last one) and the
100
107
  * bounds, which late callers read */
@@ -1 +1 @@
1
- {"version":3,"file":"engine-loader.js","sourceRoot":"","sources":["../src/engine-loader.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AActD;;gGAEgG;AAChG,MAAM,OAAO,GAA2D,EAAE,CAAC;AAC3E;wFACwF;AACxF,MAAM,OAAO,GAA+E,EAAE,CAAC;AAE/F,mDAAmD;AACnD,MAAM,UAAU,aAAa;IAC3B,KAAK,MAAM,IAAI,IAAI,CAAC,MAAM,EAAE,MAAM,CAAU,EAAE,CAAC;QAC7C,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;QACrB,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;I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AAE,OAAO,GAAG,EAAE,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;YACxE,OAAO,GAAG,EAAE,CAAC,SAAS,CAAC;QACzB,CAAC;KACF,CACQ,CAAC;AACd,CAAC","sourcesContent":["/**\n * The two builds of the engine, downloaded, compiled and instantiated once per page; the decoding workers of 3D Tiles\n * that run the full one; the engine of a destroyed map.\n */\nimport { DEFAULT_DECODERS } from './decoders.ts';\nimport { TileLoader } from './loader.ts';\nimport type { GeoMapOptions } from './types.ts';\nimport { defaultWorkerCount } from './vectortiles.ts';\nimport type { Camera, Engine } from './wasm/isard.js';\n\nexport type EngineClass = new (canvas: HTMLCanvasElement, redraw: () => void) => Engine;\n\n/** An engine loaded: its compiled module and its class */\nexport interface Bindings {\n module: WebAssembly.Module;\n Engine: EngineClass;\n}\n\n/** `core`: the engine without 3D Tiles; `full`: with them */\nexport type EngineKind = 'core' | 'full';\n\n/** The two builds of the engine, each compiled once per page: `core` without 3D Tiles (a third smaller), loaded by\n * every map; `full` with them, loaded for the first 3D Tiles layer, its module shared with the decoding workers. The\n * core engine has the same API but the 3D Tiles methods: its class is typed as the full one. */\nconst engines: { core?: Promise<Bindings>; full?: Promise<Bindings> } = {};\n/** The modules compiled (downloaded and compiled off the main thread, not instantiated): `tiles3d: 'preload'`\n * compiles the full engine ahead, its first 3D Tiles layer then only instantiates it */\nconst modules: { core?: Promise<WebAssembly.Module>; full?: Promise<WebAssembly.Module> } = {};\n\n/** @internal Forgets the engines loaded (tests) */\nexport function forgetEngines(): void {\n for (const kind of ['core', 'full'] as const) {\n delete engines[kind];\n delete modules[kind];\n }\n}\n\n/** Where a build of the engine is loaded from: the option, or next to the module */\nexport function engineUrl(kind: EngineKind, options: Pick<GeoMapOptions, 'wasmUrl' | 'coreWasmUrl'>): string | URL {\n return kind === 'full'\n ? (options.wasmUrl ?? new URL('./isard_bg.wasm', import.meta.url))\n : (options.coreWasmUrl ?? new URL('./isard_core_bg.wasm', import.meta.url));\n}\n\n/** Downloads and compiles a build (once per page, unless it failed: a later call tries again) */\nfunction compileEngine(kind: EngineKind, url: string | URL): Promise<WebAssembly.Module> {\n const compiled = modules[kind];\n if (compiled) return compiled;\n const compiling = compile(url).catch((error: unknown) => {\n // A later call tries again (a network error, a wrong URL fixed)\n delete modules[kind];\n throw error;\n });\n modules[kind] = compiling;\n return compiling;\n}\n\n/** A build compiled and instantiated with its bindings (once per page, unless it failed) */\nexport function loadEngine(kind: EngineKind, url: string | URL): Promise<Bindings> {\n const loaded = engines[kind];\n if (loaded) return loaded;\n const loading = (async () => {\n // The bindings by dynamic import: an application bundles the ones it loads only\n const [module, bindings] = await Promise.all([\n compileEngine(kind, url),\n kind === 'core' ? import('./wasm/isard_core.js') : import('./wasm/isard.js'),\n ]);\n await bindings.default({ module_or_path: module });\n return { module, Engine: bindings.Engine as unknown as EngineClass };\n })().catch((error: unknown) => {\n delete engines[kind];\n throw error;\n });\n engines[kind] = loading;\n return loading;\n}\n\n/** The full engine for a map on the core one, resolved in a task of its own, not in the one that instantiated it:\n * the map rebuilt on it there, two shorter tasks */\nexport function loadFullEngineLater(url: string | URL): Promise<Bindings> {\n return loadEngine('full', url).then(\n (bindings) => new Promise<Bindings>((resolve) => setTimeout(() => resolve(bindings), 0)),\n );\n}\n\n/** Downloads and compiles the full engine when the page is idle, without running it; a failure is left to the first\n * 3D Tiles layer, which tries again */\nexport function preloadFullEngine(url: string | URL, wanted: () => boolean): void {\n const start = () => {\n if (wanted()) compileEngine('full', url).catch(() => undefined);\n };\n if (typeof requestIdleCallback === 'function') requestIdleCallback(start, { timeout: 2000 });\n else setTimeout(start, 0);\n}\n\nasync function compile(url: string | URL): Promise<WebAssembly.Module> {\n const response = await fetch(url);\n if (!response.ok) throw new Error(`isard: failed to load the engine from ${url}: ${response.status}`);\n try {\n return await WebAssembly.compileStreaming(response.clone());\n } catch {\n // Servers that do not send application/wasm\n return WebAssembly.compile(await response.arrayBuffer());\n }\n}\n\n/** The decoding workers of 3D Tiles, running the full engine's module, unless turned off (`workers: false` or 0, or\n * no workers in this environment) */\nexport function startTileLoader(\n module: WebAssembly.Module,\n options: Pick<GeoMapOptions, 'workers' | 'workerUrl' | 'decoders'>,\n engine: Engine,\n): TileLoader | undefined {\n const { workers: count, workerUrl, decoders } = options;\n const workers = count ?? defaultWorkerCount();\n if (workers === false || workers <= 0 || typeof Worker === 'undefined') return undefined;\n return new TileLoader(\n module,\n workerUrl ?? new URL('./decoder.worker.js', import.meta.url),\n workers,\n { ...DEFAULT_DECODERS, ...decoders },\n engine.textureFormats(),\n );\n}\n\n/** The engine of a destroyed map: every method a no-op returning undefined, but the camera (the last one) and the\n * bounds, which late callers read */\nexport function destroyedEngine(camera: Camera): Engine {\n return new Proxy(\n {},\n {\n get: (_, name) => {\n if (name === 'camera') return () => camera;\n if (name === 'bounds') return () => Float64Array.of(-180, -85, 180, 85);\n return () => undefined;\n },\n },\n ) as Engine;\n}\n"]}
1
+ {"version":3,"file":"engine-loader.js","sourceRoot":"","sources":["../src/engine-loader.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAmBtD;;gGAEgG;AAChG,MAAM,OAAO,GAA2D,EAAE,CAAC;AAC3E;wFACwF;AACxF,MAAM,OAAO,GAA+E,EAAE,CAAC;AAE/F,mDAAmD;AACnD,MAAM,UAAU,aAAa;IAC3B,KAAK,MAAM,IAAI,IAAI,CAAC,MAAM,EAAE,MAAM,CAAU,EAAE,CAAC;QAC7C,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;QACrB,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;AACH,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU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AAI,CAAC,GAAG,CAAC,EAC5D,OAAO,EACP,EAAE,GAAG,gBAAgB,EAAE,GAAG,QAAQ,EAAE,EACpC,MAAM,CAAC,cAAc,EAAE,EACvB,SAAS,CAAC,OAAO,CAAC,CACnB,CAAC;AACJ,CAAC;AAED;qCACqC;AACrC,MAAM,UAAU,eAAe,CAAC,MAAc;IAC5C,OAAO,IAAI,KAAK,CACd,EAAE,EACF;QACE,GAAG,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE;YACf,IAAI,IAAI,KAAK,QAAQ;gBAAE,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC;YAC3C,IAAI,IAAI,KAAK,QAAQ;gBAAE,OAAO,GAAG,EAAE,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;YACxE,OAAO,GAAG,EAAE,CAAC,SAAS,CAAC;QACzB,CAAC;KACF,CACQ,CAAC;AACd,CAAC","sourcesContent":["/**\n * The two builds of the engine, downloaded, compiled and instantiated once per page; the decoding workers of 3D Tiles\n * that run the full one; the engine of a destroyed map.\n */\nimport { DEFAULT_DECODERS } from './decoders.ts';\nimport { TileLoader } from './loader.ts';\nimport type { GeoMapOptions } from './types.ts';\nimport { defaultWorkerCount } from './vectortiles.ts';\nimport type { Camera, Engine } from './wasm/isard.js';\n\n/** The class of an engine build: its constructor and its static `customMatrix` (custom layers) */\nexport type EngineClass = (new (\n canvas: HTMLCanvasElement,\n redraw: () => void,\n) => Engine) &\n Pick<typeof Engine, 'customMatrix'>;\n\n/** An engine loaded: its compiled module and its class */\nexport interface Bindings {\n module: WebAssembly.Module;\n Engine: EngineClass;\n}\n\n/** `core`: the engine without 3D Tiles; `full`: with them */\nexport type EngineKind = 'core' | 'full';\n\n/** The two builds of the engine, each compiled once per page: `core` without 3D Tiles (a third smaller), loaded by\n * every map; `full` with them, loaded for the first 3D Tiles layer, its module shared with the decoding workers. The\n * core engine has the same API but the 3D Tiles methods: its class is typed as the full one. */\nconst engines: { core?: Promise<Bindings>; full?: Promise<Bindings> } = {};\n/** The modules compiled (downloaded and compiled off the main thread, not instantiated): `tiles3d: 'preload'`\n * compiles the full engine ahead, its first 3D Tiles layer then only instantiates it */\nconst modules: { core?: Promise<WebAssembly.Module>; full?: Promise<WebAssembly.Module> } = {};\n\n/** @internal Forgets the engines loaded (tests) */\nexport function forgetEngines(): void {\n for (const kind of ['core', 'full'] as const) {\n delete engines[kind];\n delete modules[kind];\n }\n}\n\n/** Where a build of the engine is loaded from: the option, or next to the module */\nexport function engineUrl(kind: EngineKind, options: Pick<GeoMapOptions, 'wasmUrl' | 'coreWasmUrl'>): string | URL {\n return kind === 'full'\n ? (options.wasmUrl ?? new URL('./isard_bg.wasm', import.meta.url))\n : (options.coreWasmUrl ?? new URL('./isard_core_bg.wasm', import.meta.url));\n}\n\n/** Downloads and compiles a build (once per page, unless it failed: a later call tries again) */\nfunction compileEngine(kind: EngineKind, url: string | URL): Promise<WebAssembly.Module> {\n const compiled = modules[kind];\n if (compiled) return compiled;\n const compiling = compile(url).catch((error: unknown) => {\n // A later call tries again (a network error, a wrong URL fixed)\n delete modules[kind];\n throw error;\n });\n modules[kind] = compiling;\n return compiling;\n}\n\n/** A build compiled and instantiated with its bindings (once per page, unless it failed) */\nexport function loadEngine(kind: EngineKind, url: string | URL): Promise<Bindings> {\n const loaded = engines[kind];\n if (loaded) return loaded;\n const loading = (async () => {\n // The bindings by dynamic import: an application bundles the ones it loads only\n const [module, bindings] = await Promise.all([\n compileEngine(kind, url),\n kind === 'core' ? import('./wasm/isard_core.js') : import('./wasm/isard.js'),\n ]);\n await bindings.default({ module_or_path: module });\n return { module, Engine: bindings.Engine as unknown as EngineClass };\n })().catch((error: unknown) => {\n delete engines[kind];\n throw error;\n });\n engines[kind] = loading;\n return loading;\n}\n\n/** The full engine for a map on the core one, resolved in a task of its own, not in the one that instantiated it:\n * the map rebuilt on it there, two shorter tasks */\nexport function loadFullEngineLater(url: string | URL): Promise<Bindings> {\n return loadEngine('full', url).then(\n (bindings) => new Promise<Bindings>((resolve) => setTimeout(() => resolve(bindings), 0)),\n );\n}\n\n/** Downloads and compiles the full engine when the page is idle, without running it; a failure is left to the first\n * 3D Tiles layer, which tries again */\nexport function preloadFullEngine(url: string | URL, wanted: () => boolean): void {\n const start = () => {\n if (wanted()) compileEngine('full', url).catch(() => undefined);\n };\n if (typeof requestIdleCallback === 'function') requestIdleCallback(start, { timeout: 2000 });\n else setTimeout(start, 0);\n}\n\nasync function compile(url: string | URL): Promise<WebAssembly.Module> {\n const response = await fetch(url);\n if (!response.ok) throw new Error(`isard: failed to load the engine from ${url}: ${response.status}`);\n try {\n return await WebAssembly.compileStreaming(response.clone());\n } catch {\n // Servers that do not send application/wasm\n return WebAssembly.compile(await response.arrayBuffer());\n }\n}\n\n/** Where the workers load the point cloud module from (`isard_points_bg.wasm`, the LAZ decoder): the option, or next\n * to the module; absolute, the workers being elsewhere */\nexport function pointsUrl(options: Pick<GeoMapOptions, 'pointsWasmUrl'>): string {\n const url = options.pointsWasmUrl ?? new URL('./isard_points_bg.wasm', import.meta.url);\n const base = typeof document === 'undefined' ? undefined : document.baseURI;\n return base ? new URL(url, base).href : String(url);\n}\n\n/** The decoding workers of 3D Tiles and point clouds, running the full engine's module, unless turned off (`workers:\n * false` or 0, or no workers in this environment) */\nexport function startTileLoader(\n module: WebAssembly.Module,\n options: Pick<GeoMapOptions, 'workers' | 'workerUrl' | 'decoders' | 'pointsWasmUrl'>,\n engine: Engine,\n): TileLoader | undefined {\n const { workers: count, workerUrl, decoders } = options;\n const workers = count ?? defaultWorkerCount();\n if (workers === false || workers <= 0 || typeof Worker === 'undefined') return undefined;\n return new TileLoader(\n module,\n workerUrl ?? new URL('./decoder.worker.js', import.meta.url),\n workers,\n { ...DEFAULT_DECODERS, ...decoders },\n engine.textureFormats(),\n pointsUrl(options),\n );\n}\n\n/** The engine of a destroyed map: every method a no-op returning undefined, but the camera (the last one) and the\n * bounds, which late callers read */\nexport function destroyedEngine(camera: Camera): Engine {\n return new Proxy(\n {},\n {\n get: (_, name) => {\n if (name === 'camera') return () => camera;\n if (name === 'bounds') return () => Float64Array.of(-180, -85, 180, 85);\n return () => undefined;\n },\n },\n ) as Engine;\n}\n"]}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `isard/formats`: KML, GPX and TopoJSON read into GeoJSON feature collections, for the feature layers.
3
+ *
4
+ * ```ts
5
+ * import { parseGpx } from 'isard/formats';
6
+ * map.addLines({ data: parseGpx(await (await fetch('track.gpx')).text()), color: '#0057b8' });
7
+ * ```
8
+ */
9
+ export { parseGpx } from './gpx.ts';
10
+ export { parseKml } from './kml.ts';
11
+ export { parseTopoJson, type TopoGeometry, type Topology } from './topojson.ts';
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `isard/formats`: KML, GPX and TopoJSON read into GeoJSON feature collections, for the feature layers.
3
+ *
4
+ * ```ts
5
+ * import { parseGpx } from 'isard/formats';
6
+ * map.addLines({ data: parseGpx(await (await fetch('track.gpx')).text()), color: '#0057b8' });
7
+ * ```
8
+ */
9
+ export { parseGpx } from "./gpx.js";
10
+ export { parseKml } from "./kml.js";
11
+ export { parseTopoJson } from "./topojson.js";
12
+ //# sourceMappingURL=formats.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formats.js","sourceRoot":"","sources":["../src/formats.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,EAAE,aAAa,EAAoC,MAAM,eAAe,CAAC","sourcesContent":["/**\n * `isard/formats`: KML, GPX and TopoJSON read into GeoJSON feature collections, for the feature layers.\n *\n * ```ts\n * import { parseGpx } from 'isard/formats';\n * map.addLines({ data: parseGpx(await (await fetch('track.gpx')).text()), color: '#0057b8' });\n * ```\n */\nexport { parseGpx } from './gpx.ts';\nexport { parseKml } from './kml.ts';\nexport { parseTopoJson, type TopoGeometry, type Topology } from './topojson.ts';\n"]}
package/dist/glyphs.d.ts CHANGED
@@ -94,6 +94,9 @@ export interface Shaping {
94
94
  quads: number[][];
95
95
  /** Ink box from the anchor: min x, min y, max x, max y */
96
96
  box: [number, number, number, number];
97
+ /** Layout box from the anchor, what an icon fitted to the text frames: the advances of its widest line across, its
98
+ * lines' height (`lineHeight` each) down, centered on the ink */
99
+ layout: [number, number, number, number];
97
100
  }
98
101
  /** Code points of a text, for loading */
99
102
  export declare function codes(parts: readonly TextPart[]): Set<number>;
package/dist/glyphs.js CHANGED
@@ -346,11 +346,15 @@ export function shape(parts, glyphsOf, options) {
346
346
  Number.NEGATIVE_INFINITY,
347
347
  ];
348
348
  let baseline = 0;
349
+ let widest = 0;
350
+ let height = 0;
349
351
  wrapped.forEach((line, i) => {
350
352
  const scale = Math.max(1, ...line.map((c) => c.scale));
351
353
  if (i > 0)
352
354
  baseline += lineHeight * EM * scale;
355
+ height += lineHeight * EM * scale;
353
356
  const width = line.reduce((s, c) => s + advance(c), 0);
357
+ widest = Math.max(widest, width);
354
358
  let pen = -width / 2;
355
359
  for (const c of line) {
356
360
  const g = c.glyph;
@@ -369,7 +373,7 @@ export function shape(parts, glyphsOf, options) {
369
373
  }
370
374
  });
371
375
  if (!quads.length)
372
- return { quads, box: [0, 0, 0, 0] };
376
+ return { quads, box: [0, 0, 0, 0], layout: [0, 0, 0, 0] };
373
377
  // The block placed around the anchor by its ink box
374
378
  // The side of the box at the anchor: its start, its end, or its middle
375
379
  const side = (start, end, lo, hi) => {
@@ -390,6 +394,12 @@ export function shape(parts, glyphsOf, options) {
390
394
  q[3] = (q[3] ?? 0) * k;
391
395
  q[8] = (q[8] ?? 1) * k;
392
396
  }
393
- return { quads, box: [(x0 + dx) * k, (y0 + dy) * k, (x1 + dx) * k, (y1 + dy) * k] };
397
+ const middle = (y0 + y1) / 2 + dy;
398
+ height = Math.max(height, y1 - y0);
399
+ return {
400
+ quads,
401
+ box: [(x0 + dx) * k, (y0 + dy) * k, (x1 + dx) * k, (y1 + dy) * k],
402
+ layout: [(dx - widest / 2) * k, (middle - height / 2) * k, (dx + widest / 2) * k, (middle + height / 2) * k],
403
+ };
394
404
  }
395
405
  //# sourceMappingURL=glyphs.js.map
@@ -1 +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,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;YACpC,KAAK,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC;YACjC,IAAI,CAAC,GAAG,IAAI;gBAAE,OAAO,KAAK,CAAC;YAC3B,KAAK,IAAI,CAAC,CAAC;QACb,CAAC;IACH,CAAC;IACD,IAAI;QACF,MAAM,CAAC,G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AAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;AACtF,CAAC","sourcesContent":["/**\n * Glyphs for the symbol layers: signed distance fields in MapLibre's glyph format (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:\n * its lines (explicit and wrapped), their glyphs placed around 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 /** Rows of each page holding glyphs (from its top): the rest is blank, never sent */\n private readonly used: number[] = [0];\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 /** Bumped each time glyphs are added: labels shaped while some of theirs were missing are shaped again */\n version = 0;\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 this.version += 1;\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 /**\n * Allocates the pages in the engine and sends what they hold (their rows with glyphs). The engine allocates its\n * pages again empty: everything is sent each time, the pages doubled to make it rare\n */\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 const rows = this.used[i] ?? 0;\n if (rows > 0) engine.updateGlyphPage(i, 0, 0, this.size, rows, page.subarray(0, rows * this.size));\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 this.used[shelf.page] = Math.max(this.used[shelf.page] ?? 0, shelf.y + h);\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 this.used.push(0);\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"]}
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,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;YACpC,KAAK,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC;YACjC,IAAI,CAAC,GAAG,IAAI;gBAAE,OAAO,KAAK,CAAC;YAC3B,KAAK,IAAI,CAAC,CAAC;QACb,CAAC;IACH,CAAC;IACD,IAAI;QACF,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QACxB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAA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I,CAAC,CAAC,GAAG,CAAC,CAAC;QACvB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;IACzB,CAAC;IACD,MAAM,MAAM,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;IAClC,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC;IACnC,OAAO;QACL,KAAK;QACL,GAAG,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC;QACjE,MAAM,EAAE,CAAC,CAAC,EAAE,GAAG,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,GAAG,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;KAC7G,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Glyphs for the symbol layers: signed distance fields in MapLibre's glyph format (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:\n * its lines (explicit and wrapped), their glyphs placed around 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 /** Rows of each page holding glyphs (from its top): the rest is blank, never sent */\n private readonly used: number[] = [0];\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 /** Bumped each time glyphs are added: labels shaped while some of theirs were missing are shaped again */\n version = 0;\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 this.version += 1;\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 /**\n * Allocates the pages in the engine and sends what they hold (their rows with glyphs). The engine allocates its\n * pages again empty: everything is sent each time, the pages doubled to make it rare\n */\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 const rows = this.used[i] ?? 0;\n if (rows > 0) engine.updateGlyphPage(i, 0, 0, this.size, rows, page.subarray(0, rows * this.size));\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 this.used[shelf.page] = Math.max(this.used[shelf.page] ?? 0, shelf.y + h);\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 this.used.push(0);\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 /** Layout box from the anchor, what an icon fitted to the text frames: the advances of its widest line across, its\n * lines' height (`lineHeight` each) down, centered on the ink */\n layout: [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 let widest = 0;\n let height = 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 height += lineHeight * EM * scale;\n const width = line.reduce((s, c) => s + advance(c), 0);\n widest = Math.max(widest, width);\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], layout: [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 const middle = (y0 + y1) / 2 + dy;\n height = Math.max(height, y1 - y0);\n return {\n quads,\n box: [(x0 + dx) * k, (y0 + dy) * k, (x1 + dx) * k, (y1 + dy) * k],\n layout: [(dx - widest / 2) * k, (middle - height / 2) * k, (dx + widest / 2) * k, (middle + height / 2) * k],\n };\n}\n"]}