master
AdityaAngajala v0.12.8 160fd3c
// Board layers from signed distance fields (ADOM_board_layers), viewer code for the wiki's Babylon viewer.
// Installed once per scene, before loading models. The shader is the selected Round 3 implementation.
//
// Same data and same picture as sdf/viewer-sdf.js (sdf-k2), drawn with less GPU time (sdf-lite round 3).
// A normalized board GLB can carry, on its Adom.Board.Top and Adom.Board.Bottom materials, the optional
// glTF extension ADOM_board_layers: the signed distance (positive inside) to the copper, mask-opening
// and silk edges on the same UV mapping as the base colour map, either as one RGB texture ("dense") or
// as an atlas of tiles plus a tile map ("sparse": tiles far from every edge are a flag, not texels),
// and the colours, roughness and metallic values the board look composes them with. Close up, a shader
// step paints the board from the distance fields: edges stay sharp at any zoom, anti-aliased from the
// pixel's own footprint, and composed like normalize's texture (surface.py compose(), mixed in sRGB).
// Farther away, where a base colour texel covers about a pixel or more, it hands over smoothly to the
// base colour and metallic-roughness maps, so whole-board views are today's mip-mapped texture.
//
// Where the time goes: almost every board pixel is far from every edge, relative to its footprint. There
// each layer's coverage is exactly 0 or 1, so such a pixel reads one texel of the field, takes its region's
// colours (already linear) from a table of eight, and skips the gradient taps, the coverage arithmetic,
// the sRGB curve, and the PBR shader's own base colour and metallic-roughness samples, which the field
// fully replaces there. Only pixels near an edge run the full path.
//
// Models without the extension, other materials, WebGPU and WebGL 1 are left alone; if anything fails,
// a shader that does not compile included, the material keeps today's texture. waitReady() settles the
// extension loads before the viewer reports model readiness.
import { MaterialPluginBase } from '@babylonjs/core/Materials/materialPluginBase';
import { Texture } from '@babylonjs/core/Materials/Textures/texture';
import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';

export function installBoardLayers(scene) {
  const EXT = 'ADOM_board_layers';
  const B = { MaterialPluginBase, Texture, SceneLoader };
  let disposed = false;
  const pending = new Set();
  const textures = new Set();
  const deadMaterials = new WeakSet();
  const engine = scene.getEngine();
  const usable = !engine.isWebGPU && (engine.webGLVersion || 1) >= 2 && !!B.MaterialPluginBase && !!B.SceneLoader && !!B.SceneLoader.OnPluginActivatedObservable;
  const state = { plugins: [], failed: 0 };
  // Hand-over from the distance fields to the texture, in base colour texels per pixel along the longer
  // axis of the pixel's footprint: all distance field below LO, all texture above HI.
  const LO = 0.55, HI = 0.9;
  let uid = 0;

  const GLSL_DEFS = `
#ifdef ADOMBOARDLAYERS
uniform sampler2D adomLayersSampler;
#ifdef ADOMSPARSE
uniform sampler2D adomTilesSampler;
#endif
vec3 adomAlbedo;
vec2 adomMR;
float adomW;
vec3 adomToLinear(vec3 c) {
#ifdef GAMMAALBEDO
  return toLinearSpace(c);
#else
  return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), c));
#endif
}
// Coverage of one layer from its signed distance d (texels of the field) and its change per texel step
// in x and y (gx, gy): the anti-aliasing width is how much d changes across one pixel along the edge
// normal (jx, jy: the field's texels per pixel step in screen x and y).
float adomCover(float d, float gx, float gy, vec2 jx, vec2 jy, float wIso) {
  vec2 g = vec2(gx, gy);
  float len = length(g);
  float w = len > 0.25 ? length(vec2(dot(g, jx), dot(g, jy))) / len : wIso;
  return clamp(0.5 + d / max(w, 1e-4), 0.0, 1.0);
}
void adomLayersEval(vec2 uv) {
  adomAlbedo = vec3(0.0);
  adomMR = vec2(0.0);
  adomW = 0.0;
  vec2 st = uv * adomLayersInfo.xy;
  vec2 jx = dFdx(st), jy = dFdy(st);
  float xx = dot(jx, jx), yy = dot(jy, jy);
  // Weight: 1 - smoothstep(LO, HI, footprint in base texels), compared squared in field texels
  // (adomFast.x and .y) so that the common cases need no square root.
  float f2 = max(xx, yy);
  if (f2 >= adomFast.y) return;
  if (f2 <= adomFast.x) adomW = 1.0;
  else adomW = 1.0 - smoothstep(adomBlend.x, adomBlend.y, sqrt(f2) / adomLayersInfo.w);
  // Every coverage width w is at most the footprint's diagonal sqrt(xx + yy), so a layer whose |d|
  // exceeds half of it has coverage exactly 0 or 1. Compared on the stored value t = byte / 255 - 0.5:
  // |d| = |t| * 2 * band, h2 = (xx + yy) / 4 / (2 * band)^2.
  float h2 = (xx + yy) * adomFast.z;
  vec3 t = vec3(0.0);
  float idx;
  bool edge;
#ifdef ADOMSPARSE
  float T = adomBlend.z;
  vec2 tile = clamp(floor(st * adomFast.w), vec2(0.0), adomAtlas.zw - 1.0);
  vec4 ind = texelFetch(adomTilesSampler, ivec2(tile), 0);
  vec2 p = vec2(0.0), local = vec2(0.0);
  if (ind.a < 0.99) {
    // A tile with no edge near it: its alpha holds the three inside bits.
    idx = floor(ind.a * 255.0 + 0.5);
    edge = false;
  } else {
    vec3 c = floor(ind.rgb * 255.0 + 0.5);
    vec2 at = vec2(c.r + 256.0 * mod(c.b, 16.0), c.g + 256.0 * floor(c.b / 16.0));
    local = clamp(st - tile * T, vec2(0.0), vec2(T));
    p = at * (T + 2.0) + 1.0 + local;
    t = textureLod(adomLayersSampler, p * adomAtlas.xy, 0.0).rgb - 0.5;
    vec3 t2 = t * t;
    edge = min(min(t2.r, t2.g), t2.b) <= h2;
    idx = dot(step(vec3(0.0), t), vec3(1.0, 2.0, 4.0));
  }
#else
  t = textureLod(adomLayersSampler, uv, 0.0).rgb - 0.5;
  vec3 t2 = t * t;
  edge = min(min(t2.r, t2.g), t2.b) <= h2;
  idx = dot(step(vec3(0.0), t), vec3(1.0, 2.0, 4.0));
#endif
  if (!edge) {
    // adomPal: entry i = (linear rgb, roughness), entry 8 + i = (metallic, 0, 0, 0), for the inside
    // bits i = copper + 2 mask + 4 silk.
    int i = int(idx);
    vec4 a = adomPal[i];
    adomAlbedo = a.rgb;
    adomMR = vec2(adomPal[i + 8].x, a.a);
    return;
  }
  float b2 = 2.0 * adomLayersInfo.z;
  vec3 d0 = t * b2, dx, dy;
#ifdef ADOMSPARSE
  vec2 ainv = adomAtlas.xy;
  // Half-texel steps toward the tile's middle, so every tap stays inside the tile and its ring.
  vec2 o = vec2(local.x < 0.5 * T ? 0.5 : -0.5, local.y < 0.5 * T ? 0.5 : -0.5);
  dx = ((textureLod(adomLayersSampler, (p + vec2(o.x, 0.0)) * ainv, 0.0).rgb - 0.5) * b2 - d0) / o.x;
  dy = ((textureLod(adomLayersSampler, (p + vec2(0.0, o.y)) * ainv, 0.0).rgb - 0.5) * b2 - d0) / o.y;
#else
  vec2 ts = 1.0 / adomLayersInfo.xy;
  dx = ((textureLod(adomLayersSampler, uv + vec2(0.5 * ts.x, 0.0), 0.0).rgb - 0.5) * b2 - d0) * 2.0;
  dy = ((textureLod(adomLayersSampler, uv + vec2(0.0, 0.5 * ts.y), 0.0).rgb - 0.5) * b2 - d0) * 2.0;
#endif
  float wIso = sqrt(0.5 * (xx + yy));
  float c = adomCover(d0.r, dx.r, dy.r, jx, jy, wIso);
  float m = adomCover(d0.g, dx.g, dy.g, jx, jy, wIso);
  float s = adomCover(d0.b, dx.b, dy.b, jx, jy, wIso);
  // surface.py compose(): exposed copper gets the finish, copper under the mask tints it, bare laminate
  // shows in openings without copper, silk is never printed on exposed copper.
  float ae = c * m, ao = c * (1.0 - m), al = (1.0 - c) * m, asl = s * (1.0 - ae);
  vec3 rgb = adomMask.rgb;
  rgb = mix(rgb, adomOver.rgb, ao);
  rgb = mix(rgb, adomLam.rgb, al);
  rgb = mix(rgb, adomFin.rgb, ae);
  rgb = mix(rgb, adomSilk.rgb, asl);
  float rough = adomMask.a;
  rough = mix(rough, adomLam.a, al);
  rough = mix(rough, adomFin.a, ae);
  rough = mix(rough, adomSilk.a, asl);
  float metal = adomMetal.x;
  metal = mix(metal, adomMetal.y, al);
  metal = mix(metal, adomMetal.z, ae);
  metal = mix(metal, adomMetal.w, asl);
  adomAlbedo = adomToLinear(clamp(rgb, 0.0, 1.0));
  adomMR = vec2(metal, rough);
}
#endif
`;
  // The PBR shader's base colour and metallic-roughness samples, replaced where the field carries the
  // whole look (weight 1). A quad on the border of that region can sample with derivatives from its
  // neighbours; those pixels' texture weight there is close to 0 (the smoothstep starts flat).
  const ALBEDO_SAMPLE = `#ifdef ADOMBOARDLAYERS
vec4 albedoTexture=vec4(1.0);
if (adomW < 1.0) albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);
#else
vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);
#endif
`;
  const MR_SAMPLE = `#ifdef ADOMBOARDLAYERS
vec4 surfaceMetallicOrReflectivityColorMap=vec4(1.0);
if (adomW < 1.0) surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);
#else
vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);
#endif
`;
  const UNIFORMS = ['adomLayersInfo', 'adomBlend', 'adomMask', 'adomOver', 'adomLam', 'adomFin', 'adomSilk', 'adomMetal', 'adomAtlas', 'adomFast'];
  const srgbToLinear = (c) => (c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4));
  const clamp01 = (x) => Math.min(1, Math.max(0, x));

  class BoardLayersPlugin extends B.MaterialPluginBase {
    constructor(material, ext, tex, tiles) {
      super(material, 'AdomBoardLayers', 300, { ADOMBOARDLAYERS: false, ADOMSPARSE: false });
      this._tex = tex; this._tiles = tiles; this._on = false;
      const e = ext, c = e.colors, r = e.roughness, mt = e.metallic;
      const ts = tex.getSize(), ms = tiles ? tiles.getSize() : { width: 1, height: 1 };
      const fw = e.size[0] / e.baseColorTexels[0], b2 = 2 * e.band;
      this._vals = {
        adomLayersInfo: [e.size[0], e.size[1], e.band, fw],
        adomBlend: [LO, HI, tiles ? e.tileSize : 0, 0],
        adomMask: [...c.mask, r.mask], adomOver: [...c.copperUnderMask, r.mask], adomLam: [...c.laminate, r.laminate],
        adomFin: [...c.finish, r.finish], adomSilk: [...c.silk, r.silk], adomMetal: [mt.mask, mt.laminate, mt.finish, mt.silk],
        adomAtlas: [1 / ts.width, 1 / ts.height, ms.width, ms.height],
        adomFast: [(LO * fw) ** 2, (HI * fw) ** 2, 0.25 / (b2 * b2), tiles ? 1 / e.tileSize : 0],
      };
      this._pal = {};
    }
    get on() { return this._on; }
    set on(v) { if (this._on === v) return; this._on = v; this.markAllDefinesAsDirty(); this._enable(v); }
    get ready() { return this._tex.isReady() && (!this._tiles || this._tiles.isReady()); }
    getClassName() { return 'AdomBoardLayersPlugin'; }
    isCompatible(lang) { return lang === (B.ShaderLanguage ? B.ShaderLanguage.GLSL : 0); }
    isReadyForSubMesh() { return !this._on || this.ready; }
    prepareDefines(defines) { defines.ADOMBOARDLAYERS = this._on; defines.ADOMSPARSE = this._on && !!this._tiles; }
    getSamplers(samplers) { samplers.push('adomLayersSampler', 'adomTilesSampler'); }
    getActiveTextures(list) { if (this._on) { list.push(this._tex); if (this._tiles) list.push(this._tiles); } }
    hasTexture(t) { return t === this._tex || (!!this._tiles && t === this._tiles); }
    getUniforms() {
      return { ubo: [...UNIFORMS.map((name) => ({ name, size: 4, type: 'vec4' })), { name: 'adomPal', size: 4, type: 'vec4', arraySize: 16 }],
        fragment: '#ifdef ADOMBOARDLAYERS\n' + UNIFORMS.map((n) => `uniform vec4 ${n};`).join('\n') + '\nuniform vec4 adomPal[16];\n#endif\n' };
    }
    // The look of each region where all three coverages are 0 or 1 (surface.py compose() with 0/1
    // weights), its colour in the shader's linear space: toLinearSpace() when the base colour map is
    // decoded in the shader (GAMMAALBEDO), the sRGB curve otherwise, as adomToLinear() does.
    _palette(gamma) {
      const key = gamma ? (engine.useExactSrgbConversions ? 'x' : 'p') : 's';
      if (!this._pal[key]) {
        const f = key === 'p' ? (x) => Math.pow(x, 2.2) : srgbToLinear;
        const V = this._vals, out = new Float32Array(64);
        for (let i = 0; i < 8; i++) {
          const c = i & 1, m = (i >> 1) & 1, s = (i >> 2) & 1;
          const ae = c * m, ao = c * (1 - m), al = (1 - c) * m, asl = s * (1 - ae);
          let rgb = V.adomMask.slice(0, 3), rough = V.adomMask[3], metal = V.adomMetal[0];
          if (ao) rgb = V.adomOver.slice(0, 3);
          if (al) { rgb = V.adomLam.slice(0, 3); rough = V.adomLam[3]; metal = V.adomMetal[1]; }
          if (ae) { rgb = V.adomFin.slice(0, 3); rough = V.adomFin[3]; metal = V.adomMetal[2]; }
          if (asl) { rgb = V.adomSilk.slice(0, 3); rough = V.adomSilk[3]; metal = V.adomMetal[3]; }
          out.set([...rgb.map((x) => f(clamp01(x))), rough], 4 * i);
          out.set([metal, 0, 0, 0], 4 * (8 + i));
        }
        this._pal[key] = out;
      }
      return this._pal[key];
    }
    bindForSubMesh(ubo, sc, eng, subMesh) {
      if (!this._on) return;
      for (const n of UNIFORMS) { const v = this._vals[n]; ubo.updateFloat4(n, v[0], v[1], v[2], v[3]); }
      const defs = subMesh && (subMesh.materialDefines || subMesh._materialDefines);
      ubo.updateFloatArray('adomPal', this._palette(!!(defs && defs.GAMMAALBEDO)));
      ubo.setTexture('adomLayersSampler', this._tex);
      if (this._tiles) ubo.setTexture('adomTilesSampler', this._tiles);
    }
    getCustomCode(type) {
      if (type !== 'fragment') return null;
      return {
        CUSTOM_FRAGMENT_DEFINITIONS: GLSL_DEFS,
        CUSTOM_FRAGMENT_MAIN_BEGIN: '#ifdef ADOMBOARDLAYERS\nadomLayersEval(vAlbedoUV);\n#endif\n',
        CUSTOM_FRAGMENT_UPDATE_ALBEDO: '#ifdef ADOMBOARDLAYERS\nsurfaceAlbedo = mix(surfaceAlbedo, vAlbedoColor.rgb * adomAlbedo, adomW);\n#endif\n',
        CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS: '#ifdef ADOMBOARDLAYERS\nmetallicRoughness = mix(metallicRoughness, reflectivityColor.rg * adomMR, adomW);\n#endif\n',
        // Keys starting with "!" are regular expressions over the PBR fragment shader (Babylon's plugin code injection).
        '!vec4 albedoTexture=texture2D\\(albedoSampler,vAlbedoUV\\+uvOffset\\);': ALBEDO_SAMPLE,
        '!vec4 surfaceMetallicOrReflectivityColorMap=texture2D\\(reflectivitySampler,vReflectivityUV\\+uvOffset\\);': MR_SAMPLE,
      };
    }
    // The textures belong to this plugin alone: they go with it, whatever the material's dispose asks.
    dispose() { this._release(); }
    _release() {
      if (this._tex) this._tex.dispose();
      if (this._tiles) this._tiles.dispose();
      textures.delete(this._tex); textures.delete(this._tiles);
      const i = state.plugins.indexOf(this); if (i >= 0) state.plugins.splice(i, 1);
    }
  }

  const isVec3 = (v) => Array.isArray(v) && v.length === 3 && v.every(Number.isFinite);
  const valid = (e) => e && (e.layout === 'dense' || e.layout === 'sparse') && e.texture && Number.isInteger(e.texture.index) && e.texture.index >= 0 &&
    (e.layout === 'dense' || (e.indirection && Number.isInteger(e.indirection.index) && e.tileSize > 0)) &&
    [e.size, e.baseColorTexels].every(v => Array.isArray(v) && v.length === 2 && v.every(n => Number.isSafeInteger(n) && n > 0)) && Number.isFinite(e.band) && e.band > 0 &&
    e.colors && e.roughness && e.metallic && ['mask', 'copperUnderMask', 'laminate', 'finish', 'silk'].every(k => isVec3(e.colors[k]) && e.colors[k].every(n => n >= 0 && n <= 1)) &&
    ['mask', 'laminate', 'finish', 'silk'].every(k => [e.roughness[k], e.metallic[k]].every(n => Number.isFinite(n) && n >= 0 && n <= 1));

  // The bytes of a texture's PNG image from the GLB's BIN chunk, or null.
  const imageBytes = (data, index) => {
    const json = data.json;
    const tx = json.textures && json.textures[index];
    const img = tx && json.images && json.images[tx.source];
    const bv = img && img.bufferView != null && json.bufferViews && json.bufferViews[img.bufferView];
    if (!bv || bv.buffer !== 0 || !data.bin || !Number.isSafeInteger(bv.byteLength) || bv.byteLength < 24 || bv.byteLength > 128 * 1024 * 1024 || !Number.isSafeInteger(bv.byteOffset || 0) || (bv.byteOffset || 0) < 0) return null;
    return data.bin.readAsync(bv.byteOffset || 0, bv.byteLength).then((b) => ({ bytes: new Uint8Array(b.buffer, b.byteOffset, b.byteLength), mime: img.mimeType || 'image/png' }));
  };
  const makeTexture = (img, name, mode) => new Promise((ok, no) => {
    if (disposed) return no(new Error('scene disposed'));
    const bytes = img.bytes;
    const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const cap = engine.getCaps().maxTextureSize;
    if (bytes.length < 24 || header.getUint32(0) !== 0x89504e47 || header.getUint32(4) !== 0x0d0a1a0a ||
        !header.getUint32(16) || !header.getUint32(20) || header.getUint32(16) > cap || header.getUint32(20) > cap) {
      return no(new Error('board layer PNG exceeds texture limits or has an invalid header'));
    }
    let settled = false;
    const done = (error) => {
      if (settled) return;
      settled = true; clearTimeout(timer);
      if (error || disposed) { t.dispose(); textures.delete(t); no(error || new Error('scene disposed')); }
      else ok(t);
    };
    const t = new B.Texture(null, scene, { noMipmap: true, invertY: false, samplingMode: mode, mimeType: 'image/png',
      onLoad: () => done(), onError: (m, e) => done(e instanceof Error ? e : new Error(name + ': ' + (m || 'failed to load'))) });
    const timer = setTimeout(() => done(new Error('board layer texture load timed out')), 10000);
    textures.add(t);
    t.name = name;
    t.wrapU = t.wrapV = B.Texture.CLAMP_ADDRESSMODE;
    t.anisotropicFilteringLevel = 1;
    t.gammaSpace = false;
    t.updateURL('data:adom-board-layers-' + (++uid) + '-' + name, bytes);
  });

  const attach = async (mat, ext, data) => {
    const reads = [imageBytes(data, ext.texture.index), ext.layout === 'sparse' ? imageBytes(data, ext.indirection.index) : null];
    if (!reads[0] || (ext.layout === 'sparse' && !reads[1])) return;
    const [main, tilesImg] = await Promise.all(reads);
    const made = await Promise.allSettled([makeTexture(main, `${mat.name}.layers`, B.Texture.BILINEAR_SAMPLINGMODE),
      tilesImg ? makeTexture(tilesImg, `${mat.name}.layers.tiles`, B.Texture.NEAREST_SAMPLINGMODE) : null]);
    const [tex, tiles] = made.map((r) => (r.status === 'fulfilled' ? r.value : null));
    if (!tex || (tilesImg && !tiles) || (disposed || deadMaterials.has(mat))) {
      if (tex) tex.dispose(); if (tiles) tiles.dispose();
      throw made.find((r) => r.status === 'rejected')?.reason || new Error('material gone');
    }
    const plugin = new BoardLayersPlugin(mat, ext, tex, tiles);
    state.plugins.push(plugin);
    mat.onDisposeObservable.addOnce(() => plugin._release());
    // A shader that does not compile on this GPU must not keep the board from drawing, or the scene from becoming
    // ready: every board material drops back to today's texture, and the failed effect leaves the engine's cache
    // (it never becomes ready, and while it is cached engine.areAllEffectsReady() and so scene.isReady() stay
    // false). The board materials share one compiled effect, so only one of them may hear of it.
    const onError = mat.onError;
    mat.onError = (effect, errors) => {
      if (state.plugins.some((q) => q.on)) { console.warn('[board layers] shader:', errors); state.failed++; }
      for (const q of state.plugins) q.on = false;
      setTimeout(() => { try { if (effect && !effect.isReady()) effect.dispose(true); } catch (e) { console.warn('[board layers]', e); } }, 0);
      if (onError) onError(effect, errors);
    };
    plugin.on = true;
  };

  const observer = usable ? B.SceneLoader.OnPluginActivatedObservable.add((loader) => {
    if (disposed || !loader || loader.name !== 'gltf' || !loader.onParsedObservable || !loader.onMaterialLoadedObservable) return;
    let data = null;
    loader.onParsedObservable.add((d) => { data = d?.json?.extensionsUsed?.includes(EXT) ? d : null; });
    loader.onMaterialLoadedObservable.add((mat) => {
      if (disposed || !data || mat?.getScene() !== scene || mat.getClassName() !== 'PBRMaterial') return;
      const ptr = mat._internalMetadata?.gltf?.pointers?.find(p => /^\/materials\/\d+$/.test(p));
      const ext = ptr && data.json.materials?.[+ptr.split('/')[2]]?.extensions?.[EXT];
      if (!valid(ext)) return;
      const d = data;
      mat.onDisposeObservable.addOnce(() => deadMaterials.add(mat));
      const work = new Promise(resolve => {
        const tryAttach = n => {
          if (disposed || deadMaterials.has(mat) || n <= 0) return resolve();
          const at = mat.albedoTexture;
          if (!at) { setTimeout(() => tryAttach(n - 1), 20); return; }
          if ((at.coordinatesIndex || 0) !== 0) return resolve();
          attach(mat, ext, d).catch(e => { state.failed++; console.warn('[board layers]', mat.name, e); }).finally(resolve);
        };
        Promise.resolve().then(() => tryAttach(500));
      });
      pending.add(work);
      work.finally(() => pending.delete(work));
    });
  }) : null;
  const dispose = () => {
    if (disposed) return;
    disposed = true;
    if (observer) B.SceneLoader.OnPluginActivatedObservable.remove(observer);
    for (const plugin of [...state.plugins]) plugin._release();
    for (const texture of textures) texture.dispose();
    textures.clear();
  };
  scene.onDisposeObservable.addOnce(dispose);
  return {
    async waitReady() { while (pending.size && !disposed) await Promise.allSettled([...pending]); },
    dispose,
  };
}