diff --git a/docs/INFRASTRUCTURE-LAYERS.md b/docs/INFRASTRUCTURE-LAYERS.md index 239e1d31f..9c358f487 100644 --- a/docs/INFRASTRUCTURE-LAYERS.md +++ b/docs/INFRASTRUCTURE-LAYERS.md @@ -61,9 +61,13 @@ Features keep their own simplestyle `fill`, `fill-opacity`, `stroke`, `stroke-opacity`, `stroke-width`, `marker-color` and `marker-size`, given as hex, `rgb()` or `hsl()` colours or by the CSS colour names the default renderer knows (it has no `rebeccapurple`, and spells `lavenderblush` `lavendar_blush`); -a `marker-symbol` draws the plain pin. Polygons with heights are drawn at them, -outlined; points with heights stand their pin on the stem's tip. Edges follow -rhumb lines. +a `marker-symbol` is stamped on the pin as the default renderer stamped it: a +one-character string as bold upper-case text, any other value as the Maki icon +of that id from the renderer's assets, the plain pin when the icon cannot be +loaded. The assets are found as the renderer finds them from a page script: the +`CESIUM_BASE_URL` global, else the folder `Cesium.js` is loaded from; a +page bundling Cesium as modules sets `CESIUM_BASE_URL` for icon pins. Polygons with heights are drawn at them, outlined; points with +heights stand their pin on the stem's tip. Edges follow rhumb lines. `gods-eye-view/infrastructure/geojson` exports the lower-level `createLocalGeoJsonLayer(options, services)` and existing infrastructure overlay diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index bad7cd007..172a936cb 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -8,6 +8,7 @@ "modules": [ "src/data/infrastructure.js", "src/data/localGeojsonCore.js", + "src/data/geojsonPins.js", "src/render/cesium/heights.js", "src/render/cesium/camera.js", "src/data/iconSetPrimitive.js", @@ -3314,6 +3315,7 @@ "src/data/layerStateTokenReservations.json", "src/data/lifecycle.js", "src/data/localGeojsonCore.js", + "src/data/geojsonPins.js", "src/data/localGeojsonLod.js", "src/data/local_data/natural_earth/marine.json", "src/data/local_data/natural_earth/regions.json", @@ -4299,6 +4301,7 @@ "src/data/layerState.js", "src/data/layerStateTokenReservations.json", "src/data/localGeojsonCore.js", + "src/data/geojsonPins.js", "src/data/localGeojsonLod.js", "src/data/local_data/natural_earth/marine.json", "src/data/local_data/natural_earth/regions.json", diff --git a/src/data/geojsonPins.js b/src/data/geojsonPins.js new file mode 100644 index 000000000..ef1eef9b5 --- /dev/null +++ b/src/data/geojsonPins.js @@ -0,0 +1,320 @@ +/** + * @module data/geojsonPins + * @description The map pins a GeoJSON point stands on, drawn as the default + * renderer's GeoJSON loader drew them: its pin shape in the marker colour, + * outlined in that colour brightened, and a simplestyle `marker-symbol` + * stamped on it in white outlined in black: a single character as bold + * text, anything longer as that Maki icon from the renderer's assets. A + * symbol that cannot be drawn leaves the plain pin, as the loader did. + */ + +/** The pin's outline, in its own 24-unit box. */ +const PIN_PATH = + 'M6.72 0.422L17.28 0.422C18.553 0.422 19.577 1.758 19.577 3.415L19.577 10.973' + + 'C19.577 12.63 18.553 13.966 17.282 13.966L14.386 14.008L11.826 23.578L9.614 14.008' + + 'L6.719 13.965C5.446 13.983 4.422 12.629 4.422 10.972L4.422 3.416C4.423 1.76 5.447 0.423 6.718 0.423Z'; + +/** A colour channel as a CSS byte, as the default renderer writes one. */ +const cssByte = (value) => (value === 1 ? 255 : (value * 256) | 0); + +/** `[r, g, b, a]` as the default renderer writes a CSS colour. */ +export function pinCss([r, g, b, a]) { + return a === 1 + ? `rgb(${cssByte(r)},${cssByte(g)},${cssByte(b)})` + : `rgba(${cssByte(r)},${cssByte(g)},${cssByte(b)},${a})`; +} + +/** `rgba` brightened by 0.6, as the pin's outline is. */ +const brighter = (rgba) => [ + 1 - (1 - rgba[0]) * 0.4, + 1 - (1 - rgba[1]) * 0.4, + 1 - (1 - rgba[2]) * 0.4, + rgba[3], +]; + +/** `[r, g, b, a]` as the plain pin has always written it, alpha and all. */ +const svgCss = ([r, g, b, a]) => + `rgba(${cssByte(r)},${cssByte(g)},${cssByte(b)},${a})`; + +/** + * The plain pin at `size` pixels in `rgba`, as SVG. + * @param {number[]} rgba + * @param {number} size + * @returns {{svg: string}} + */ +export function plainPin(rgba, size) { + return { + svg: + `` + + ``, + }; +} + +/** + * Draw the pin, as the loader's pin builder does. + * @param {CanvasRenderingContext2D} context + * @param {number[]} rgba + * @param {number} size + */ +function drawPin(context, rgba, size) { + context.save(); + context.scale(size / 24, size / 24); + context.fillStyle = pinCss(rgba); + context.strokeStyle = pinCss(brighter(rgba)); + context.lineWidth = 0.846; + context.beginPath(); + context.moveTo(6.72, 0.422); + context.lineTo(17.28, 0.422); + context.bezierCurveTo(18.553, 0.422, 19.577, 1.758, 19.577, 3.415); + context.lineTo(19.577, 10.973); + context.bezierCurveTo(19.577, 12.63, 18.553, 13.966, 17.282, 13.966); + context.lineTo(14.386, 14.008); + context.lineTo(11.826, 23.578); + context.lineTo(9.614, 14.008); + context.lineTo(6.719, 13.965); + context.bezierCurveTo(5.446, 13.983, 4.422, 12.629, 4.422, 10.972); + context.lineTo(4.422, 3.416); + context.bezierCurveTo(4.423, 1.76, 5.447, 0.423, 6.718, 0.423); + context.closePath(); + context.fill(); + context.stroke(); + context.restore(); +} + +/** + * Stamp `image` on the pin's head: only its alpha counts, drawn white with + * a one-pixel black edge, as the loader's pin builder stamps it. + * @param {CanvasRenderingContext2D} context + * @param {{width: number, height: number}} image + * @param {number} size + */ +function drawIcon(context, image, size) { + const imageSize = size / 2.5; + let sizeX = imageSize; + let sizeY = imageSize; + if (image.width > image.height) + sizeY = imageSize * (image.height / image.width); + else if (image.width < image.height) + sizeX = imageSize * (image.width / image.height); + const x = Math.round((size - sizeX) / 2); + const y = Math.round((7 / 24) * size - sizeY / 2); + + context.globalCompositeOperation = 'destination-out'; + context.drawImage(image, x - 1, y, sizeX, sizeY); + context.drawImage(image, x, y - 1, sizeX, sizeY); + context.drawImage(image, x + 1, y, sizeX, sizeY); + context.drawImage(image, x, y + 1, sizeX, sizeY); + + context.globalCompositeOperation = 'destination-over'; + context.fillStyle = 'rgb(0,0,0)'; + context.fillRect(x - 1, y - 1, sizeX + 2, sizeY + 2); + + context.globalCompositeOperation = 'destination-out'; + context.drawImage(image, x, y, sizeX, sizeY); + + context.globalCompositeOperation = 'destination-over'; + context.fillStyle = 'rgb(255,255,255)'; + context.fillRect(x - 1, y - 2, sizeX + 2, sizeY + 2); +} + +/** + * `text` written white on a canvas just big enough for it, in `font`, as + * the default renderer writes text to a canvas. + * @param {(width: number, height: number) => HTMLCanvasElement} makeCanvas + * @param {string} text + * @param {string} font + */ +function textCanvas(makeCanvas, text, font) { + const canvas = makeCanvas(1, 1); + let context = canvas.getContext('2d', { willReadFrequently: true }); + context.font = font; + const metrics = context.measureText(text); + const blank = !/\S/.test(text); + const ascent = blank ? 0 : Math.round(metrics.actualBoundingBoxAscent); + const descent = blank ? 0 : Math.round(metrics.actualBoundingBoxDescent); + const height = blank ? 0 : Math.max(ascent + descent, 1); + const x = blank ? 0 : Math.round(metrics.actualBoundingBoxLeft); + canvas.width = Math.ceil(metrics.width) + x; + canvas.height = height; + // Resizing a canvas resets its context's state. + context = canvas.getContext('2d', { willReadFrequently: true }); + context.font = font; + context.lineJoin = 'round'; + context.lineWidth = 1; + context.imageSmoothingEnabled = false; + context.fillStyle = 'rgb(255,255,255)'; + context.fillText(text, x, ascent); + return canvas; +} + +/** The renderer's script on the page, and the folder it is served from. */ +const RENDERER_SCRIPT = /((?:.*\/)|^)Cesium\.js(?:\?|#|$)/; + +/** + * Where the renderer's assets are served, as the renderer finds them: the + * `CESIUM_BASE_URL` global, else the folder of its script on the page; null + * when neither says (a renderer bundled as modules, which finds them from + * its own module address). + */ +function assetBase() { + const document = globalThis.document; + let base = globalThis.CESIUM_BASE_URL; + if (typeof base !== 'string' || !base) { + base = null; + for (const script of document?.getElementsByTagName?.('script') ?? []) { + const found = RENDERER_SCRIPT.exec(script.getAttribute?.('src') ?? ''); + if (found) { + base = found[1]; + break; + } + } + } + if (base === null) return null; + // The renderer reads its base as a folder, slash or not; a script beside + // the page is in the page's own folder. + if (base === '') base = './'; + else if (!base.endsWith('/')) base += '/'; + try { + return new URL(base, document?.baseURI).href; + } catch { + return null; + } +} + +/** + * The Maki icon `id` from the renderer's assets, or null when it cannot be + * loaded. + * @param {string} id + * @param {AbortSignal} [signal] + * @returns {Promise} + */ +export async function loadMaki(id, signal) { + const base = assetBase(); + if (!base || typeof globalThis.createImageBitmap !== 'function') return null; + try { + const url = new URL( + `Assets/Textures/maki/${encodeURIComponent(id)}.png`, + base, + ); + const response = await fetch(url, signal ? { signal } : undefined); + if (!response.ok) return null; + return await globalThis.createImageBitmap(await response.blob()); + } catch { + return null; + } +} + +/** A canvas on the page, when there is one to draw on. */ +function documentCanvas(width, height) { + const canvas = globalThis.document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + return canvas; +} + +/** + * Makes the pins a set of points stands on. Symbols are loaded first + * (`load`), so the pins can then be made at once (`pin`). + * @param {object} [options] + * @param {(width: number, height: number) => HTMLCanvasElement} [options.makeCanvas] + * Default: a canvas on the page; without a page every pin is plain. + * @param {(id: string, signal?: AbortSignal) => Promise} [options.loadIcon] + * A Maki icon by id. Default: from the renderer's assets. + */ +export function createGeojsonPins({ makeCanvas, loadIcon = loadMaki } = {}) { + const canvasFor = + makeCanvas ?? + (typeof globalThis.document?.createElement === 'function' + ? documentCanvas + : null); + /** Maki icons by id; null for one that failed. */ + const icons = new Map(); + const pins = new Map(); + + return { + /** Let go of every pin and icon made so far. */ + clear() { + icons.clear(); + pins.clear(); + }, + + /** + * Load the icons `symbols` need. One that fails stays the plain pin. + * @param {Iterable} symbols `marker-symbol` values. + * @param {{signal?: AbortSignal}} [options] Ends the loads early. + */ + async load(symbols, { signal } = {}) { + if (!canvasFor) return; + const wanted = new Set(); + for (const symbol of symbols) + if (isIconSymbol(symbol) && !icons.has(String(symbol))) + wanted.add(String(symbol)); + await Promise.all( + [...wanted].map(async (id) => { + const icon = await Promise.resolve() + .then(() => loadIcon(id, signal)) + .catch(() => null); + // An aborted load is not a missing icon: a later load asks again. + if (!signal?.aborted) icons.set(id, icon ?? null); + }), + ); + }, + + /** + * The pin for a marker: its colour, size and symbol (none for the + * plain pin). One image per distinct marker, shared. + * @param {{color: number[], size: number, symbol?: unknown}} marker + * @returns {import('../render/contract/draw').ImageRef} + */ + pin({ color, size, symbol }) { + const drawn = hasSymbol(symbol) && canvasFor ? symbol : undefined; + const key = JSON.stringify([stampKey(drawn), color, size]); + let image = pins.get(key); + if (!image) { + image = symbolPin(drawn, color, size) ?? plainPin(color, size); + pins.set(key, image); + } + return image; + }, + }; + + function symbolPin(symbol, color, size) { + if (symbol === undefined) return null; + let stamp; + if (isIconSymbol(symbol)) { + stamp = icons.get(String(symbol)); + if (!stamp) return null; + } else + stamp = textCanvas( + canvasFor, + symbol.toUpperCase(), + `bold ${size}px sans-serif`, + ); + const canvas = canvasFor(size, size); + const context = canvas.getContext('2d'); + drawPin(context, color, size); + drawIcon(context, stamp, size); + return { + canvas, + key: `geojson-pin:${JSON.stringify([stampKey(symbol), color, size])}`, + }; + } +} + +/** Whether a `marker-symbol` asks for a symbol, as the loader reads one. */ +const hasSymbol = (symbol) => symbol !== undefined && symbol !== null; + +/** + * What a symbol stamps, as the loader's pin builder told its pins apart: + * text by its upper-cased character, an icon by its id. + */ +const stampKey = (symbol) => + symbol === undefined + ? null + : isIconSymbol(symbol) + ? ['icon', String(symbol)] + : ['text', symbol.toUpperCase()]; + +/** Whether a symbol is an icon (anything but a single-character string). */ +const isIconSymbol = (symbol) => + hasSymbol(symbol) && !(typeof symbol === 'string' && symbol.length === 1); diff --git a/src/data/geojsonPins.test.mjs b/src/data/geojsonPins.test.mjs new file mode 100644 index 000000000..119664ecd --- /dev/null +++ b/src/data/geojsonPins.test.mjs @@ -0,0 +1,269 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + createGeojsonPins, + loadMaki, + pinCss, + plainPin, +} from './geojsonPins.js'; + +/** A canvas whose context records what is drawn on it. */ +function fakeCanvas(width, height) { + const calls = []; + const state = {}; + const context = { + calls, + save: () => calls.push(['save']), + restore: () => calls.push(['restore']), + scale: (...a) => calls.push(['scale', ...a]), + beginPath: () => calls.push(['beginPath']), + moveTo: () => {}, + lineTo: () => {}, + bezierCurveTo: () => {}, + closePath: () => {}, + fill: () => calls.push(['fill', state.fillStyle]), + stroke: () => calls.push(['stroke', state.strokeStyle, state.lineWidth]), + fillRect: (...a) => + calls.push([ + 'fillRect', + state.globalCompositeOperation, + state.fillStyle, + ...a, + ]), + drawImage: (image, ...a) => + calls.push([ + 'drawImage', + state.globalCompositeOperation, + image.tag, + ...a, + ]), + fillText: (...a) => calls.push(['fillText', state.font, ...a]), + measureText: (text) => ({ + width: text.length * 10, + actualBoundingBoxAscent: 9.4, + actualBoundingBoxDescent: 0.6, + actualBoundingBoxLeft: 0, + }), + }; + for (const key of [ + 'fillStyle', + 'strokeStyle', + 'lineWidth', + 'globalCompositeOperation', + 'font', + 'lineJoin', + 'imageSmoothingEnabled', + ]) + Object.defineProperty(context, key, { + get: () => state[key], + set: (value) => (state[key] = value), + }); + return { width, height, tag: 'canvas', getContext: () => context, context }; +} + +test('a pin with no symbol is the plain pin, in the marker colour outlined brighter', () => { + const pins = createGeojsonPins({ makeCanvas: fakeCanvas }); + const pin = pins.pin({ color: [1, 0, 0, 1], size: 48 }); + assert.deepEqual(pin, plainPin([1, 0, 0, 1], 48)); + assert.match(pin.svg, /width="48" height="48"/); + assert.match(pin.svg, /fill="rgba\(255,0,0,1\)"/); + assert.match(pin.svg, /stroke="rgba\(255,153,153,1\)"/); + assert.equal(pins.pin({ color: [1, 0, 0, 1], size: 48 }), pin, 'shared'); + assert.equal(pinCss([0, 0.5, 1, 0.3]), 'rgba(0,128,255,0.3)'); +}); + +test('a single-character symbol is stamped on the pin as bold upper-case text', async () => { + const made = []; + const pins = createGeojsonPins({ + makeCanvas: (w, h) => { + const canvas = fakeCanvas(w, h); + made.push(canvas); + return canvas; + }, + }); + await pins.load(['a']); + const pin = pins.pin({ color: [0, 0, 1, 1], size: 48, symbol: 'a' }); + assert.equal(typeof pin.key, 'string'); + assert.match(pin.key, /^geojson-pin:/); + const [text, canvas] = made; + assert.equal(pin.canvas, canvas); + assert.deepEqual([canvas.width, canvas.height], [48, 48]); + // The text canvas: just big enough for the text. + assert.deepEqual([text.width, text.height], [10, 10]); + assert.deepEqual( + text.context.calls.find((c) => c[0] === 'fillText'), + ['fillText', 'bold 48px sans-serif', 'A', 0, 9], + ); + const calls = canvas.context.calls; + assert.deepEqual( + calls.find((c) => c[0] === 'scale'), + ['scale', 2, 2], + ); + assert.deepEqual( + calls.find((c) => c[0] === 'fill'), + ['fill', 'rgb(0,0,255)'], + ); + assert.deepEqual( + calls.find((c) => c[0] === 'stroke'), + ['stroke', 'rgb(153,153,255)', 0.846], + ); + // Stamped white with a black edge, centred on the pin's head: the text + // is 10 wide in a 19.2 box, so it is drawn square at 19.2. + const stamps = calls.filter( + (c) => c[0] === 'drawImage' || c[0] === 'fillRect', + ); + const x = Math.round((48 - 19.2) / 2); + const y = Math.round((7 / 24) * 48 - 19.2 / 2); + assert.deepEqual(stamps, [ + ['drawImage', 'destination-out', 'canvas', x - 1, y, 19.2, 19.2], + ['drawImage', 'destination-out', 'canvas', x, y - 1, 19.2, 19.2], + ['drawImage', 'destination-out', 'canvas', x + 1, y, 19.2, 19.2], + ['drawImage', 'destination-out', 'canvas', x, y + 1, 19.2, 19.2], + ['fillRect', 'destination-over', 'rgb(0,0,0)', x - 1, y - 1, 21.2, 21.2], + ['drawImage', 'destination-out', 'canvas', x, y, 19.2, 19.2], + [ + 'fillRect', + 'destination-over', + 'rgb(255,255,255)', + x - 1, + y - 2, + 21.2, + 21.2, + ], + ]); + assert.equal( + pins.pin({ color: [0, 0, 1, 1], size: 48, symbol: 'a' }), + pin, + 'one image per distinct marker', + ); +}); + +test('a longer symbol is that icon, loaded first; one that fails leaves the plain pin', async () => { + const asked = []; + const pins = createGeojsonPins({ + makeCanvas: fakeCanvas, + loadIcon: async (id) => { + asked.push(id); + if (id === 'rail') return { width: 30, height: 15, tag: 'rail' }; + if (id === 'boom') throw new Error('boom'); + return null; + }, + }); + await pins.load(['rail', 'nope', 'boom', 'x', 7, null, undefined, 'rail']); + assert.deepEqual(asked.sort(), ['7', 'boom', 'nope', 'rail']); + const rail = pins.pin({ color: [1, 1, 1, 1], size: 24, symbol: 'rail' }); + const draws = rail.canvas.context.calls.filter((c) => c[0] === 'drawImage'); + // Wider than high: its height is scaled down. + assert.deepEqual(draws.at(-1), [ + 'drawImage', + 'destination-out', + 'rail', + 7, + 5, + 9.6, + 4.8, + ]); + for (const symbol of ['nope', 'boom', 7]) + assert.deepEqual( + pins.pin({ color: [1, 1, 1, 1], size: 24, symbol }), + plainPin([1, 1, 1, 1], 24), + ); + // Loaded again, a known icon is not fetched again. + await pins.load(['rail']); + assert.equal(asked.length, 4); +}); + +test('without a page to draw on, every pin is plain', async () => { + const pins = createGeojsonPins({ loadIcon: () => assert.fail('no load') }); + await pins.load(['rail']); + assert.deepEqual( + pins.pin({ color: [1, 1, 1, 1], size: 8, symbol: 'a' }), + plainPin([1, 1, 1, 1], 8), + ); +}); + +test('a number is an icon id and a character is text, each pinned apart; text by its upper case', async () => { + const loaded = []; + const pins = createGeojsonPins({ + makeCanvas: fakeCanvas, + loadIcon: async (id) => (loaded.push(id), { width: 4, height: 4, tag: id }), + }); + await pins.load([7, '7', 'a', 'A']); + assert.deepEqual(loaded, ['7']); + const icon = pins.pin({ color: [1, 1, 1, 1], size: 24, symbol: 7 }); + const text = pins.pin({ color: [1, 1, 1, 1], size: 24, symbol: '7' }); + assert.notEqual(icon, text); + assert.notEqual(icon.key, text.key); + assert.equal( + pins.pin({ color: [1, 1, 1, 1], size: 24, symbol: 'a' }), + pins.pin({ color: [1, 1, 1, 1], size: 24, symbol: 'A' }), + ); +}); + +test('an aborted icon load is asked again later; a failing loader leaves the plain pin', async () => { + const controller = new AbortController(); + let calls = 0; + const pins = createGeojsonPins({ + makeCanvas: fakeCanvas, + loadIcon: (id) => { + calls += 1; + if (id === 'sync') throw new Error('sync'); + controller.abort(); + return Promise.resolve(null); + }, + }); + await pins.load(['rail'], { signal: controller.signal }); + await pins.load(['rail']); + assert.equal(calls, 2); + await pins.load(['sync']); + assert.deepEqual( + pins.pin({ color: [1, 1, 1, 1], size: 24, symbol: 'sync' }), + plainPin([1, 1, 1, 1], 24), + ); +}); + +test('icons come from the renderer’s assets: its base global, else its script’s folder', async (t) => { + const saved = { + document: globalThis.document, + base: globalThis.CESIUM_BASE_URL, + bitmap: globalThis.createImageBitmap, + fetch: globalThis.fetch, + }; + t.after(() => { + for (const [key, name] of [ + ['document', 'document'], + ['base', 'CESIUM_BASE_URL'], + ['bitmap', 'createImageBitmap'], + ['fetch', 'fetch'], + ]) + if (saved[key] === undefined) delete globalThis[name]; + else globalThis[name] = saved[key]; + }); + const asked = []; + globalThis.fetch = async (url) => { + asked.push(String(url)); + return { ok: true, blob: async () => 'png' }; + }; + globalThis.createImageBitmap = async () => ({ width: 1, height: 1 }); + const scripts = []; + globalThis.document = { + baseURI: 'http://gev.test/app/', + getElementsByTagName: () => + scripts.map((src) => ({ getAttribute: () => src })), + }; + globalThis.CESIUM_BASE_URL = '/assets/cesium'; + assert.ok(await loadMaki('rail')); + delete globalThis.CESIUM_BASE_URL; + scripts.push('/other.js', 'lib/Cesium.js?v=1'); + assert.ok(await loadMaki('a b')); + scripts.length = 0; + scripts.push('Cesium.js'); + assert.ok(await loadMaki('dam')); + scripts.length = 0; + assert.equal(await loadMaki('rail'), null, 'nothing says where'); + assert.deepEqual(asked, [ + 'http://gev.test/assets/cesium/Assets/Textures/maki/rail.png', + 'http://gev.test/app/lib/Assets/Textures/maki/a%20b.png', + 'http://gev.test/app/Assets/Textures/maki/dam.png', + ]); +}); diff --git a/src/data/infrastructure.test.mjs b/src/data/infrastructure.test.mjs index 359395501..15d116ba5 100644 --- a/src/data/infrastructure.test.mjs +++ b/src/data/infrastructure.test.mjs @@ -207,6 +207,7 @@ test('consumer build includes only infrastructure code and resolves assets under 'drawHit.js', 'ellipsoid.js', 'follow.js', + 'geojsonPins.js', 'heights.js', 'infrastructure.js', 'infrastructureData.js', diff --git a/src/data/localGeojsonCore.js b/src/data/localGeojsonCore.js index 68b0d362c..589f4f182 100644 --- a/src/data/localGeojsonCore.js +++ b/src/data/localGeojsonCore.js @@ -18,6 +18,7 @@ import { parseGeojsonLines, } from '../sources/infrastructureData.js'; import { createInfrastructureOverlayEntry } from './infrastructureOverlayEntry.js'; +import { createGeojsonPins } from './geojsonPins.js'; import { inputFor as defaultInputFor } from '../input/dispatcher.js'; import { selectInfraLod, @@ -314,36 +315,6 @@ const STEM_WIDTH_PX = 3.5; const PIN_SIZE_PX = 8; const BLACK = Object.freeze([0, 0, 0, 1]); -/** A colour channel as a CSS byte, as the default renderer writes one. */ -const cssByte = (value) => (value === 1 ? 255 : (value * 256) | 0); -const cssRgba = ([r, g, b, a]) => - `rgba(${cssByte(r)},${cssByte(g)},${cssByte(b)},${a})`; - -/** - * The pin a Point feature stands on: the GeoJSON loader's default marker, - * its pin path at `size` pixels, filled in `rgba` and outlined in that - * colour brightened by 0.6. - * @param {number[]} rgba - * @param {number} [size] - * @returns {{svg: string}} - */ -function pinImage(rgba, size = PIN_SIZE_PX) { - const brighter = [ - 1 - (1 - rgba[0]) * 0.4, - 1 - (1 - rgba[1]) * 0.4, - 1 - (1 - rgba[2]) * 0.4, - rgba[3], - ]; - return { - svg: - `` + - '`, - }; -} - /** The GeoJSON loader's `marker-size` names, in pixels. */ const MARKER_SIZES = Object.freeze({ small: 24, medium: 48, large: 64 }); /** @@ -407,6 +378,23 @@ function markerOf(properties, rgba) { return { color: color ?? rgba, size }; } +/** Whether a geometry has a point among its parts. */ +const hasPoint = (shape) => + shape?.type === 'Point' || + shape?.type === 'MultiPoint' || + (shape?.type === 'GeometryCollection' && + Array.isArray(shape.geometries) && + shape.geometries.some(hasPoint)); + +/** The `marker-symbol` of every feature that draws a pin. */ +function* markerSymbols(features) { + for (const feature of features) { + const symbol = feature?.properties?.['marker-symbol']; + if (symbol !== undefined && symbol !== null && hasPoint(feature.geometry)) + yield symbol; + } +} + /** * Ground `coordinates` as `{lon, lat}` degrees along the rhumb lines * between them, as the GeoJSON loader drew its draped edges. @@ -550,6 +538,8 @@ export function createLocalGeoJsonLayer( }, ) { const setPrefix = `${id}:${++layerInstances}`; + /** The pins its points stand on, one image per distinct marker. */ + const pinMaker = createGeojsonPins(); /** What this layer draws while built: its sets and parts, or null. */ let _drawn = null; let _enabled = false; @@ -714,15 +704,6 @@ export function createLocalGeoJsonLayer( const draw = drawOf(viewer); const rgba = cssColor(color) ?? [1, 1, 1, 1]; const fillColor = [rgba[0], rgba[1], rgba[2], FILL_ALPHA]; - // One image per marker colour and size, shared by the pins wearing it. - const pinImages = new Map(); - const pinFor = (marker) => { - const key = `${marker.color.join()}|${marker.size}`; - let image = pinImages.get(key); - if (!image) - pinImages.set(key, (image = pinImage(marker.color, marker.size))); - return image; - }; const parts = localGeojsonParts(features); const sets = {}; const built = { sets, parts: new Map(), records: [], count: parts.length }; @@ -801,7 +782,10 @@ export function createLocalGeoJsonLayer( part.pinClamped = part.coordinates.length <= 2; part.pinPos = { lon, lat }; const marker = markerOf(style, rgba); - part.pin = pinFor(marker); + part.pin = pinMaker.pin({ + ...marker, + symbol: style?.['marker-symbol'], + }); part.pinSize = marker.size; } @@ -1041,6 +1025,11 @@ export function createLocalGeoJsonLayer( _cachedFeatures = features; } + // The loader drew its pins' symbols before it finished loading. + await pinMaker.load(markerSymbols(features), { + signal: _loadController?.signal, + }); + if (_destroyed) return; const built = buildDrawn(viewer, features); _count = built.count; _stemRecords = built.records; @@ -1318,6 +1307,7 @@ export function createLocalGeoJsonLayer( _clickSubscription = null; _overlayPublisher.destroy(); _cachedFeatures = null; + pinMaker.clear(); _stemRecords = []; _count = 0; _lastUpdate = null; diff --git a/src/data/localGeojsonDraw.test.mjs b/src/data/localGeojsonDraw.test.mjs index 841d67055..49ad98a59 100644 --- a/src/data/localGeojsonDraw.test.mjs +++ b/src/data/localGeojsonDraw.test.mjs @@ -66,11 +66,15 @@ async function enabledLayer(t, features) { const originalFetch = globalThis.fetch; const originalWindow = globalThis.window; globalThis.window = { dispatchEvent() {} }; - globalThis.fetch = async () => ({ - ok: true, - status: 200, - text: async () => features.map((f) => JSON.stringify(f)).join('\n'), - }); + globalThis.fetch = async (url) => + String(url).includes('/maki/') + ? // The renderer's icons: only `rail` is there. + { ok: String(url).endsWith('/rail.png'), blob: async () => 'rail' } + : { + ok: true, + status: 200, + text: async () => features.map((f) => JSON.stringify(f)).join('\n'), + }; const viewer = {}; const fake = bindFakeGroundRenderer(viewer, { eye: { lon: 0.005, lat: 0.005, height: 50_000 }, @@ -312,3 +316,74 @@ test('long edges follow rhumb lines', async (t) => { // Split as the default renderer splits a draped rhumb line: under 10 km. assert.ok(positions.length > 150, `${positions.length} points`); }); + +test('a marker-symbol is stamped on its pin: a character as text, a longer one as the renderer’s icon', async (t) => { + const saved = { + document: globalThis.document, + base: globalThis.CESIUM_BASE_URL, + bitmap: globalThis.createImageBitmap, + }; + const stamped = []; + const canvas = () => { + const context = new Proxy( + { + measureText: (text) => ({ + width: text.length * 10, + actualBoundingBoxAscent: 9, + actualBoundingBoxDescent: 1, + actualBoundingBoxLeft: 0, + }), + }, + { + get: (target, key) => + key in target + ? target[key] + : key === 'drawImage' + ? (image) => stamped.push(image.tag ?? 'text') + : () => {}, + set: () => true, + }, + ); + return { width: 0, height: 0, getContext: () => context }; + }; + globalThis.document = { createElement: canvas, baseURI: 'http://gev.test/' }; + globalThis.CESIUM_BASE_URL = '/cesium/'; + globalThis.createImageBitmap = async (blob) => ({ + width: 10, + height: 10, + tag: blob, + }); + t.after(() => { + for (const [key, name] of [ + ['document', 'document'], + ['base', 'CESIUM_BASE_URL'], + ['bitmap', 'createImageBitmap'], + ]) + if (saved[key] === undefined) delete globalThis[name]; + else globalThis[name] = saved[key]; + }); + const point = (id, x, symbol) => + feature( + id, + { type: 'Point', coordinates: [x, 0] }, + { 'marker-symbol': symbol, 'marker-color': '#ff0000' }, + ); + const env = await enabledLayer(t, [ + point('letter', 0.001, 'h'), + point('icon', 0.002, 'rail'), + point('missing', 0.003, 'no-such-icon'), + point('plain', 0.004, null), + ]); + const pins = env.fake.set('pins').items; + const letter = pins.get('letter').image; + assert.match(letter.key, /^geojson-pin:/); + assert.ok(letter.canvas); + const icon = pins.get('icon').image; + assert.match(icon.key, /^geojson-pin:/); + assert.notEqual(icon.key, letter.key); + assert.ok(stamped.includes('rail'), 'the icon is stamped on its pin'); + assert.ok(stamped.includes('text'), 'and the letter on its own'); + // An icon the renderer does not have leaves the plain pin, as no symbol does. + assert.match(pins.get('missing').image.svg, /fill="rgba\(255,0,0,1\)"/); + assert.deepEqual(pins.get('missing').image, pins.get('plain').image); +}); diff --git a/src/data/localGeojsonLifecycle.test.mjs b/src/data/localGeojsonLifecycle.test.mjs index 40f19b19b..fd82f1cd3 100644 --- a/src/data/localGeojsonLifecycle.test.mjs +++ b/src/data/localGeojsonLifecycle.test.mjs @@ -166,3 +166,43 @@ test('a toggle-off frees the entities and a toggle-on rebuilds them from the cac assert.equal(fetchMock.mock.callCount(), 1, 'no second fetch for a bundled dataset'); assert.equal(env.layer.getLodDiagnostics().total, 1); }); + +test('destroy while a pin icon loads cancels it and leaves no late objects', async t => { + const saved = { + document: globalThis.document, CESIUM_BASE_URL: globalThis.CESIUM_BASE_URL, + createImageBitmap: globalThis.createImageBitmap, + }; + globalThis.document = { createElement: () => ({ getContext: () => ({}) }), baseURI: 'http://gev.test/' }; + globalThis.CESIUM_BASE_URL = '/cesium/'; + globalThis.createImageBitmap = async () => ({ width: 1, height: 1 }); + t.after(() => { + for (const [name, value] of Object.entries(saved)) + if (value === undefined) delete globalThis[name]; + else globalThis[name] = value; + }); + const env = harness(t); + const entered = deferred(); + const release = deferred(); + let iconSignal; + const pinned = JSON.stringify({ + type: 'Feature', id: 'pin', properties: { 'marker-symbol': 'rail' }, + geometry: { type: 'Point', coordinates: [0, 0] }, + }); + t.mock.method(globalThis, 'fetch', async (url, options) => { + if (!String(url).includes('/maki/')) return { ok: true, text: async () => pinned }; + iconSignal = options.signal; + entered.resolve(); + await release.promise; + return { ok: false }; + }); + const loading = env.layer.enable(env.viewer); + await entered.promise; + env.layer.destroy(env.viewer); + assert.equal(iconSignal.aborted, true); + release.resolve(); + await loading; + assert.equal(env.fake.liveSets().length, 0); + assert.equal(env.listeners.size, 0); + assert.equal(env.handlers(), 0); + assert.equal(getContextStore().entities.size, 0); +});