GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-design-studio/202609271853-site-world/world

Plant Lod and 2 more files

A JavaScript module in the world folder of GlobalGrid2050 that runs outline (`runOutline`), converts to group (`toGroup`) and calculates planar distances. It runs outline (`runOutline`) and creates lod (`createLod`).

515 lines of JavaScript from globalgrid2050, in 3 files. Topic: Solar and storage design. Section 191 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Plant Lod transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-lod.mjs lines 1–224
  2. Plant Pack render · globalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-pack.mjs lines 1–154
  3. Plant Packing transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-packing.mjs lines 1–137

Plant Lod

A JavaScript module in the world folder of GlobalGrid2050 that runs outline (`runOutline`), converts to group (`toGroup`) and calculates planar distances. It runs outline (`runOutline`) and creates lod (`createLod`).

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-lod.mjs · lines 1–224 of 224 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern runsOf (shared by 2 files)

What it does
It calculates its inputs. Defines 19 functions or classes, including plantLevel, cellLevel, boxDistance, surfaceOf, outlineOf.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 1 file: Plant UI (globalgrid2050).
What it achieves
A large plant drawn from its pack (`plant-pack.mjs`) at the detail the distance allows.
Why it matters
Imported by Plant UI.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Plant Pack (import)
Used by
imported by Plant UI (import)
Produces
PLANT_BANDS, CELL_BANDS, DETAIL, HYSTERESIS, BUILD_MS, plantLevel, cellLevel, boxDistance, moduleGridOf, runsOf, hull, createLod
Defines here
plantLevel, cellLevel, boxDistance, surfaceOf, outlineOf, seg, moduleGridOf, seg, runsOf, runOutline, hull, createLod, cellBox, get, evict, K, batches, toGroup, dispose
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/plant-lod.mjs:1-224 · blob 99373eb1bd003cbe9ee08a346b77bfa4dcc3e3c4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// plant-lod.mjs: a large plant drawn from its pack (plant-pack.mjs) at the detail the distance allows.
//
//   L0 outline      eye over 3 km above the plant (leave under 2.4 km): the used land as one hull
//   L1 blocks       below that: one rectangle per block, the stations and the feeder graph to the compound (hidden under 300 m)
//   L2 table runs   a 250 m cell within 2 km of the eye (leave beyond 2.4 km): the tables of a row merged into one run
//   L3 tables       a cell within 600 m (leave beyond 720 m): every table's outline, ridge or tube
//   L4 full table   a 50 m sub-cell within 80 m (leave beyond 100 m): the module grid on the table, and extra(i) (the piles)
// The level is decided inside the draw from the camera, with 20 % hysteresis, so a still camera decides nothing (0 fps).
// A cell keeps drawing its old level until the new one is built; building is capped per frame, and the rest waits for the
// next frame (onPending asks for one). Built batches live in a least-recently-used cache; an evicted batch's GPU buffer is
// freed through release(key) (lines.mjs). Positions are relative to each batch's own base, so floats stay small.
// Pure apart from the clock: no DOM, no WebGL.

import { axesOf, cornersOf, cellTables } from './plant-pack.mjs';

export const PLANT_BANDS = Object.freeze({ outline: [3000, 2400], blocks: [300, 250] }); // [enter, leave] eye height (m)
export const CELL_BANDS = Object.freeze([[600, 3], [2000, 2]]);                         // [enter distance (m), level]
export const DETAIL = Object.freeze({ subM: 50, enterM: 80, leaveM: 100 });
export const HYSTERESIS = 1.2;
export const BUILD_MS = 6;
const GROUP = 4; // cells a side in one L2 batch

// Plant-wide: 0 outline, 1 blocks, 2 blocks hidden (close to the ground), from the eye height above the plant.
export function plantLevel(h, prev = null) {
  const [oIn, oOut] = PLANT_BANDS.outline, [bIn, bOut] = PLANT_BANDS.blocks;
  if (h > oIn || (prev === 0 && h > oOut)) return 0;
  if (h > bIn || (prev === 1 && h > bOut)) return 1;
  return 2;
}

// A cell's level from its distance: the most detailed band it is inside; a more detailed previous level is kept until
// the distance passes its band times the hysteresis. 1 = nothing drawn per cell (the blocks cover it).
export function cellLevel(dist, prev = 1, bands = CELL_BANDS) {
  let level = 1;
  for (const [enter, l] of bands) if (dist < enter) { level = Math.max(level, l); }
  if (prev > level) { const b = bands.find(([, l]) => l === prev); if (b && dist < b[0] * HYSTERESIS) return prev; }
  return level;
}

// Distance from a point to an axis-aligned box.
export const boxDistance = (p, [x0, y0, z0, x1, y1, z1]) =>
  Math.hypot(Math.max(x0 - p[0], 0, p[0] - x1), Math.max(y0 - p[1], 0, p[1] - y1), Math.max(z0 - p[2], 0, p[2] - z1));

// Height on a table's module surface at local (a along, d across): the corners bilinear, an east-west ridge rising in the middle.
function surfaceOf(pack, i) {
  const T = pack.types[pack.type[i]], C = cornersOf(pack, i), L = T.lenU / 2, D = T.depth / 2, { ax, dx } = axesOf(pack.heading[i]);
  const ridge = T.faces === 2 ? T.rise : 0, x = pack.x[i], y = pack.y[i];
  return (a, d) => {
    const s = (a + L) / (2 * L), t = (d + D) / (2 * D);
    const z = (1 - t) * ((1 - s) * C[0][2] + s * C[1][2]) + t * ((1 - s) * C[3][2] + s * C[2][2]) + ridge * (1 - Math.abs(d) / D);
    return [x + a * ax[0] + d * dx[0], y + a * ax[1] + d * dx[1], z];
  };
}

// ---- builders: each writes x,y,z pairs (relative to base) into an array ----
function outlineOf(pack, i, v, base) {
  const T = pack.types[pack.type[i]], P = surfaceOf(pack, i), L = T.lenU / 2, D = T.depth / 2;
  const seg = (a, b) => { for (const p of [a, b]) v.push(p[0] - base[0], p[1] - base[1], p[2] - base[2]); };
  const A = P(-L, -D), B = P(L, -D), C = P(L, D), E = P(-L, D);
  if (T.faces === 2) {                                        // east-west: both low edges, the ridge, and the gables
    const M = P(-L, 0), N = P(L, 0);
    seg(A, B); seg(E, C); seg(M, N); seg(A, M); seg(M, E); seg(B, N); seg(N, C);
  } else {
    seg(A, B); seg(B, C); seg(C, E); seg(E, A);
    if (T.tracker) seg(P(-L, 0), P(L, 0));                    // the torque tube
  }
}

export function moduleGridOf(pack, i, v, base) {
  const T = pack.types[pack.type[i]], P = surfaceOf(pack, i), L = T.lenU / 2, D = T.depth / 2;
  const seg = (a, b) => { for (const p of [a, b]) v.push(p[0] - base[0], p[1] - base[1], p[2] - base[2]); };
  const cols = T.tracker ? T.modules : T.modules / 2;
  const bands = T.faces === 2 ? [[-D, 0], [0, D]] : [[-D, D]];
  for (const [d0, d1] of bands) for (let c = 0; c <= cols; c++) { const a = -L + 2 * L * c / cols; seg(P(a, d0), P(a, d1)); }
  if (T.south) seg(P(-L, 0), P(L, 0));                        // two modules up the slope: the line between them
}

// Tables of a cell merged into runs: same heading, same row (across position within 0.1 m), gaps under 1 m.
export function runsOf(pack, ids) {
  const rows = new Map();
  for (const i of ids) {
    const { ax, dx } = axesOf(pack.heading[i]), a = pack.x[i] * ax[0] + pack.y[i] * ax[1], d = pack.x[i] * dx[0] + pack.y[i] * dx[1];
    const k = `${pack.heading[i]}:${pack.type[i]}:${Math.round(d * 10)}`;
    if (!rows.has(k)) rows.set(k, []);
    rows.get(k).push([a, i]);
  }
  const runs = [];
  for (const list of rows.values()) {
    list.sort((p, q) => p[0] - q[0]);
    let cur = null;
    for (const [a, i] of list) {
      const L = pack.types[pack.type[i]].lenU / 2;
      if (cur && a - L - cur.a1 < 1) { cur.a1 = a + L; cur.last = i; cur.n++; } else runs.push(cur = { a0: a - L, a1: a + L, first: i, last: i, n: 1 });
    }
  }
  return runs;
}
function runOutline(pack, run, v, base) {
  const T = pack.types[pack.type[run.first]], D = T.depth / 2, L = T.lenU / 2;
  const P0 = surfaceOf(pack, run.first), P1 = surfaceOf(pack, run.last);
  const A = P0(-L, -D), E = P0(-L, D), B = P1(L, -D), C = P1(L, D);
  for (const [p, q] of [[A, B], [B, C], [C, E], [E, A]]) for (const s of [p, q]) v.push(s[0] - base[0], s[1] - base[1], s[2] - base[2]);
}

// Convex hull (monotone chain) of 2-D points.
export function hull(pts) {
  const p = [...pts].sort((a, b) => a[0] - b[0] || a[1] - b[1]), cross = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
  const lo = [], hi = [];
  for (const q of p) { while (lo.length >= 2 && cross(lo.at(-2), lo.at(-1), q) <= 0) lo.pop(); lo.push(q); }
  for (const q of p.reverse()) { while (hi.length >= 2 && cross(hi.at(-2), hi.at(-1), q) <= 0) hi.pop(); hi.push(q); }
  return lo.slice(0, -1).concat(hi.slice(0, -1));
}

// ---- the level-of-detail drawer ----
// opts: { colours: { outline, blocks, stations, runs, tables, detail }, release(key), onPending(), extra(i, v, base) more L4 lines,
//   maxBytes: the cache size, now() }
export function createLod(pack, { colours, release = () => {}, onPending = () => {}, extra = null, maxBytes = 24 << 20, now = () => performance.now(), version = 0 } = {}) {
  const G = pack.grid, cache = new Map(), levels = new Map(), detailOn = new Set(), lastRuns = new Map();
  let plant = null, frame = 0, bytes = 0;
  const stats = { built: 0, evicted: 0, pending: 0, batches: 0, vertices: 0, levels: [0, 0, 0, 0, 0] };
  const zMean = pack.n ? pack.z.reduce((t, z) => t + z, 0) / pack.n : 0;
  const cellBox = c => { const i = c % G.cols, j = Math.floor(c / G.cols);
    return [G.x0 + i * G.cellM, G.y0 + j * G.cellM, G.zMin[c], G.x0 + (i + 1) * G.cellM, G.y0 + (j + 1) * G.cellM, G.zMax[c]]; };
  let budgetEnd = 0;
  // A batch for key, built by fill(v, base) once per version; null while over this frame's build budget.
  function get(key, base, colour, fill) {
    let e = cache.get(key);
    if (!e) {
      if (now() > budgetEnd) { stats.pending++; return null; }
      const v = []; fill(v, base);
      e = { key, base, colour, positions: new Float32Array(v) }; cache.set(key, e); bytes += e.positions.byteLength; stats.built++;
    }
    e.used = frame;
    return e;
  }
  function evict() {
    if (bytes <= maxBytes) return;
    for (const e of [...cache.values()].sort((a, b) => a.used - b.used)) {
      if (bytes <= maxBytes || e.used === frame) break;
      cache.delete(e.key); bytes -= e.positions.byteLength; release(e.key); stats.evicted++;
    }
  }
  const K = s => `plant-lod-${version}-${s}`;

  // eye: [x, y, z] in pack coordinates; toOrigin(base) -> the batch origin the renderer wants. Returns line batches.
  function batches(eye, toOrigin) {
    frame++; budgetEnd = now() + BUILD_MS; stats.pending = 0; stats.levels = [0, 0, 0, 0, 0];
    const out = [], push = (e, colour) => { if (e && e.positions.length >= 6) out.push({ key: e.key, version: 0, positions: e.positions, color: colour, origin: toOrigin(e.base) }); };
    plant = plantLevel(eye[2] - zMean, plant);
    const base0 = [0, 0, zMean];
    if (plant === 0) {
      stats.levels[0] = 1;
      push(get(K('outline'), base0, colours.outline, (v, b) => {
        const H = hull(pack.blocks.flatMap(k => k.rect));
        H.forEach((p, k) => { const q = H[(k + 1) % H.length]; v.push(p[0] - b[0], p[1] - b[1], 1, q[0] - b[0], q[1] - b[1], 1); });
      }), colours.outline);
    }
    if (plant === 1) {
      stats.levels[1] = 1;
      push(get(K('blocks'), base0, colours.blocks, (v, b) => {
        for (const k of pack.blocks) k.rect.forEach((p, m) => { const q = k.rect[(m + 1) % 4]; v.push(p[0] - b[0], p[1] - b[1], k.z - b[2] + 2, q[0] - b[0], q[1] - b[1], k.z - b[2] + 2); });
      }), colours.blocks);
      push(get(K('graph'), base0, colours.stations, (v, b) => {
        const g = pack.graph, S = g?.stations || [], lift = 6, r = 12;
        for (const s of S) { const [x, y] = s.at, z = (pack.blocks[s.block]?.z ?? b[2]) - b[2] + lift;
          v.push(x - r - b[0], y - b[1], z, x + r - b[0], y - b[1], z, x - b[0], y - r - b[1], z, x - b[0], y + r - b[1], z); }
        if (g?.compound) for (const f of g.feeders) {                 // each feeder's chain of stations, then home to the compound
          const pts = [...f.stations.map(k => S[k]?.at).filter(Boolean), g.compound.at];
          for (let m = 1; m < pts.length; m++) v.push(pts[m - 1][0] - b[0], pts[m - 1][1] - b[1], lift, pts[m][0] - b[0], pts[m][1] - b[1], lift);
        }
      }), colours.stations);
    }
    // Cells within reach of the eye: L2 runs, L3 tables.
    const reach = CELL_BANDS.at(-1)[0] * HYSTERESIS;
    const i0 = Math.max(0, Math.floor((eye[0] - reach - G.x0) / G.cellM)), i1 = Math.min(G.cols - 1, Math.floor((eye[0] + reach - G.x0) / G.cellM));
    const j0 = Math.max(0, Math.floor((eye[1] - reach - G.y0) / G.cellM)), j1 = Math.min(G.rows - 1, Math.floor((eye[1] + reach - G.y0) / G.cellM));
    // L3 is one batch a cell; L2 runs are merged into one batch per 1 km group of 4 x 4 cells (draw calls stay under 80).
    const seen = new Set(), groups = new Map();
    const toGroup = c => { const g = Math.floor(Math.floor(c / G.cols) / GROUP) * 65536 + Math.floor((c % G.cols) / GROUP);
      if (!groups.has(g)) groups.set(g, []); groups.get(g).push(c); };
    for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
      const c = j * G.cols + i, ids = cellTables(pack, c);
      if (!ids.length) continue;
      seen.add(c);
      const box = cellBox(c), old = levels.get(c) ?? 1, want = cellLevel(boxDistance(eye, box), old);
      let shown = want;
      if (want === 3) {
        const e = get(K(`L3-${c}`), [box[0], box[1], box[2]], colours.tables, (v, b) => { for (const t of ids) outlineOf(pack, t, v, b); });
        if (e) { push(e, colours.tables); stats.levels[3]++; } else shown = old === 3 ? 1 : old; // keep the runs until the tables are built
      }
      if (shown === 2) toGroup(c);
      levels.set(c, shown);
    }
    for (const [g, cells] of groups) {
      cells.sort((a, b) => a - b);
      const gi = g % 65536, gj = Math.floor(g / 65536), base = [G.x0 + gi * GROUP * G.cellM, G.y0 + gj * GROUP * G.cellM, zMean];
      let e = get(K(`L2-${g}-${cells.join('.')}`), base, colours.runs, (v, b) => { for (const c of cells) for (const r of runsOf(pack, cellTables(pack, c))) runOutline(pack, r, v, b); });
      if (e) lastRuns.set(g, e.key); else if ((e = cache.get(lastRuns.get(g)) || null)) e.used = frame;   // the group's last runs until rebuilt
      if (e) { push(e, colours.runs); stats.levels[2] += cells.length; }
    }
    for (const c of [...levels.keys()]) if (!seen.has(c)) levels.delete(c);
    // L4: 50 m sub-cells near the eye, the module grid (and extra lines) of every table whose centre is inside.
    const S = DETAIL.subM, r4 = DETAIL.leaveM, hAbove = eye[2] - zMean;
    if (hAbove < r4 + 50) for (let sj = Math.floor((eye[1] - r4) / S); sj <= Math.floor((eye[1] + r4) / S); sj++)
      for (let si = Math.floor((eye[0] - r4) / S); si <= Math.floor((eye[0] + r4) / S); si++) {
        const key = `${si},${sj}`, box = [si * S, sj * S, zMean - 50, (si + 1) * S, (sj + 1) * S, zMean + 50], d = boxDistance(eye, box);
        const on = d < DETAIL.enterM || (detailOn.has(key) && d < DETAIL.leaveM);
        if (!on) { detailOn.delete(key); continue; }
        const ci = Math.floor((si * S + S / 2 - G.x0) / G.cellM), cj = Math.floor((sj * S + S / 2 - G.y0) / G.cellM);
        if (ci < 0 || cj < 0 || ci >= G.cols || cj >= G.rows) continue;
        const ids = [...cellTables(pack, cj * G.cols + ci)].filter(t => pack.x[t] >= box[0] && pack.x[t] < box[3] && pack.y[t] >= box[1] && pack.y[t] < box[4]);
        if (!ids.length) continue;
        const e = get(K(`L4-${key}`), [box[0], box[1], zMean], colours.detail, (v, b) => { for (const t of ids) { moduleGridOf(pack, t, v, b); extra?.(t, v, b); } });
        if (e) { detailOn.add(key); push(e, colours.detail); stats.levels[4]++; }
      }
    evict();
    stats.batches = out.length; stats.vertices = out.reduce((t, b) => t + b.positions.length / 3, 0); stats.bytes = bytes;
    if (stats.pending) onPending();
    return out;
  }
  // Frees every cached buffer (a new layout, or the plant cleared).
  function dispose() { for (const k of cache.keys()) release(k); cache.clear(); levels.clear(); detailOn.clear(); lastRuns.clear(); bytes = 0; }
  return { batches, dispose, stats: () => ({ ...stats, plantLevel: plant, cached: cache.size }) };
}

Plant Pack

A JavaScript module in the world folder of GlobalGrid2050 that works with pack plant (`packPlant`) and index pack (`indexPack`) (units: MW, MVA).

renderglobalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-pack.mjs · lines 1–154 of 154 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern graphOf (shared by 2 files)

What it does
Defines 10 functions or classes, including axesOf, cornersOf, packPlant, allocate, graphOf.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 2 files: Plant Lod (globalgrid2050); Plant UI (globalgrid2050).
What it achieves
It indexes pack (`indexPack`), encodes pack (`encodePack`) and decodes pack (`decodePack`). A laid-out plant as a compact pack, the one source every overview level is drawn from. Its code works with 500 MW.
Why it matters
Imported by Plant Lod and Plant UI.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Pile Rules (import)
Used by
imported by Plant Lod (import), imported by Plant UI (import)
Produces
BYTES_PER_TABLE, CELL_M, axesOf, cornersOf, packPlant, indexPack, cellTables, encodePack, decodePack, packSize
Defines here
axesOf, cornersOf, packPlant, allocate, graphOf, indexPack, cellTables, encodePack, decodePack, packSize
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/plant-pack.mjs:1-154 · blob 605b59bb91786d792551c6c16ae7b14827b54e47 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// plant-pack.mjs: a laid-out plant as a compact pack, the one source every overview level is drawn from.
//
// Stage 1 of the 500 MW overview (reviews 500mw-lod 1-5): the layout's result (plant-layout.mjs) is packed into typed arrays,
// 26 bytes a table, plus the block / station / feeder graph and a uniform grid index, so a plant of 20,000 tables is
// about 0.5 MB and the whole plant can be drawn from it at any distance without keeping one big line batch.
//
// Per table (structure of arrays, local metres from one plant origin held in doubles):
//   x, y, z  Float32 x3   centre of the table in plan, and the mean height of its four surface corners
//   heading  Int16        the table's long axis, hundredths of a degree anticlockwise from east
//   tilt     Uint8        quarter degrees
//   type     Uint8        index into the pack's table types (sizes, faces, rise)
//   block    Uint16       the block (station) the table belongs to
//   dz       Int16 x4     the four surface corners less z, in centimetres, in local order (-L/2,-D/2), (+L/2,-D/2),
//                          (+L/2,+D/2), (-L/2,+D/2): along the long axis, then across it; the -D/2 edge is the low edge.
// The corners are the module plane as built: on its piles where it has them, else the ground plus the design heights.
// East-west ridges and tracker tubes are derived from the corners and the type, never stored.
// Pure: no DOM, no WebGL.

import { trackerHub } from './pile-rules.mjs';

export const BYTES_PER_TABLE = 26;
export const CELL_M = 250;
const MAGIC = 0x4b505047, VERSION = 1; // 'GPPK'

// Local unit axes for a heading in hundredths of a degree: along (the long axis) and across (90 degrees anticlockwise).
export function axesOf(h) {
  const a = h * Math.PI / 18000, c = Math.cos(a), s = Math.sin(a);
  return { ax: [c, s], dx: [-s, c] };
}

// The four surface corners of table i as [x, y, z] local to the pack origin, in pack order.
export function cornersOf(pack, i) {
  const T = pack.types[pack.type[i]], { ax, dx } = axesOf(pack.heading[i]), L = T.lenU / 2, D = T.depth / 2;
  const x = pack.x[i], y = pack.y[i], z = pack.z[i], out = [];
  for (const [k, [a, d]] of [[-L, -D], [L, -D], [L, D], [-L, D]].entries())
    out.push([x + a * ax[0] + d * dx[0], y + a * ax[1] + d * dx[1], z + pack.dz[i * 4 + k] / 100]);
  return out;
}

// r: a layoutPlant result; surface(q) -> [[a0, a1], [m0, m1], [b0, b1]] the fitted module edges of table q (plant-piles
// edges) or null. Without it, the corners are the ground plus the layout's low edge and rise (as plant-ui draws them).
export function packPlant(r, { surface = null } = {}) {
  const F = r.frame, T = r.table, P = r.params, t = r.tables, n = t.length / 6;
  const bx = r.boundary.map(([u, v]) => F.en(u, v));
  const origin = [Math.min(...bx.map(p => p[0])), Math.min(...bx.map(p => p[1])), 0];
  const heading = F.swap ? -9000 : 0;                       // south rows run east; east-west and tracker rows run north
  const type = { layout: r.layout, lenU: T.lenU, depth: T.depth, rise: T.rise || 0, modules: T.modules, strings: T.strings,
    tracker: !!T.tracker, south: !!T.south, faces: T.south || T.tracker ? 1 : 2, tiltDeg: (T.tilt || 0) * 180 / Math.PI, kWp: T.kWp };
  const pack = allocate(n, origin, [type]);
  const lo = P.lowEdgeM, hi = lo + (T.rise || 0), hub = trackerHub().hub;
  // Block of each table: tables come out in station order, a prefix sum of stations[s].tables.
  let s = 0, left = r.stations[0]?.tables ?? n;
  for (let q = 0; q < n; q++) {
    while (left <= 0 && s < r.stations.length - 1) left = r.stations[++s].tables;
    left--;
    const [ua, va, h0, h1, h2, h3] = t.subarray(q * 6, q * 6 + 6), ub = ua + T.lenU, vb = va + T.depth;
    const tube = T.tracker ? [(h0 + h3) / 2 + hub, (h1 + h2) / 2 + hub] : null;   // a tracker at stow: flat across, on its tube
    const E = surface?.(q) || (tube ? [tube, tube, tube] : [[h0 + lo, h1 + lo], null, T.south ? [h3 + hi, h2 + hi] : [h3 + lo, h2 + lo]]);
    // Surface heights at the frame corners A (ua,va), B (ub,va), C (ub,vb), D (ua,vb).
    const A = E[0][0], B = E[0][1], C = E[2][1], D = E[2][0];
    // Pack order: south (heading 0) is A B C D; swapped frames (heading -90) put +along at ua, -across at va: B A D C.
    const cz = F.swap ? [B, A, D, C] : [A, B, C, D], z = (cz[0] + cz[1] + cz[2] + cz[3]) / 4;
    const [e, nn] = F.en((ua + ub) / 2, (va + vb) / 2);
    pack.x[q] = e - origin[0]; pack.y[q] = nn - origin[1]; pack.z[q] = z;
    pack.heading[q] = heading; pack.tilt[q] = Math.round(type.tiltDeg * 4); pack.type[q] = 0; pack.block[q] = s;
    for (let k = 0; k < 4; k++) pack.dz[q * 4 + k] = Math.round((cz[k] - z) * 100);
  }
  pack.graph = graphOf(r, origin);
  pack.fence = bx.map(([e, nn]) => [e - origin[0], nn - origin[1]]);
  indexPack(pack);
  return pack;
}

function allocate(n, origin, types) {
  return { n, origin, types, x: new Float32Array(n), y: new Float32Array(n), z: new Float32Array(n), heading: new Int16Array(n),
    tilt: new Uint8Array(n), type: new Uint8Array(n), block: new Uint16Array(n), dz: new Int16Array(n * 4), graph: null, fence: [], grid: null };
}

// Blocks (one per station): the tables' extent in the plant's own axes, as a rectangle; stations and feeders as a graph.
function graphOf(r, origin) {
  const F = r.frame, loc = (u, v) => { const [e, n] = F.en(u, v); return [e - origin[0], n - origin[1]]; };
  const stations = r.stations.map((s, i) => ({ id: s.id, block: i, at: loc(s.u, s.v), mva: s.mva, inverters: s.inverters, tables: s.tables }));
  const byId = new Map(stations.map(s => [s.id, s]));
  const cm = r.compound, compound = cm ? { at: loc(cm.u, cm.v), w: cm.w, d: cm.d } : null;
  const feeders = (r.electrical?.feeders || []).map(f => ({ id: f.id, stations: f.stations.map(id => byId.get(id)?.block ?? -1), dropPct: f.dropPct }));
  for (const f of feeders) for (const b of f.stations) if (stations[b]) stations[b].feeder = f.id;
  return { stations, compound, feeders };
}

// Blocks' rectangles and the uniform grid index (CSR: tables sorted by cell, cellStart gives each cell's range).
export function indexPack(pack, cellM = CELL_M) {
  const n = pack.n, blocks = new Map();
  let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
  for (let i = 0; i < n; i++) {
    x0 = Math.min(x0, pack.x[i]); y0 = Math.min(y0, pack.y[i]); x1 = Math.max(x1, pack.x[i]); y1 = Math.max(y1, pack.y[i]);
    const T = pack.types[pack.type[i]], { ax, dx } = axesOf(pack.heading[i]), a = pack.x[i] * ax[0] + pack.y[i] * ax[1], d = pack.x[i] * dx[0] + pack.y[i] * dx[1];
    let b = blocks.get(pack.block[i]);
    if (!b) blocks.set(pack.block[i], b = { id: pack.block[i], h: pack.heading[i], a0: Infinity, a1: -Infinity, d0: Infinity, d1: -Infinity, z: 0, tables: 0 });
    b.a0 = Math.min(b.a0, a - T.lenU / 2); b.a1 = Math.max(b.a1, a + T.lenU / 2);
    b.d0 = Math.min(b.d0, d - T.depth / 2); b.d1 = Math.max(b.d1, d + T.depth / 2); b.z += pack.z[i]; b.tables++;
  }
  pack.blocks = [...blocks.values()].sort((p, q) => p.id - q.id).map(b => {
    const { ax, dx } = axesOf(b.h), pt = (a, d) => [a * ax[0] + d * dx[0], a * ax[1] + d * dx[1]];
    return { id: b.id, tables: b.tables, z: b.z / b.tables, rect: [pt(b.a0, b.d0), pt(b.a1, b.d0), pt(b.a1, b.d1), pt(b.a0, b.d1)] };
  });
  if (!n) { pack.grid = { cellM, x0: 0, y0: 0, cols: 0, rows: 0, cellStart: new Uint32Array(1), cellTables: new Uint32Array(0), zMin: new Float32Array(0), zMax: new Float32Array(0) }; return pack; }
  const gx0 = Math.floor(x0 / cellM) * cellM, gy0 = Math.floor(y0 / cellM) * cellM;
  const cols = Math.floor((x1 - gx0) / cellM) + 1, rows = Math.floor((y1 - gy0) / cellM) + 1, cells = cols * rows;
  const cellOf = new Uint32Array(n), count = new Uint32Array(cells + 1);
  for (let i = 0; i < n; i++) { const c = Math.floor((pack.y[i] - gy0) / cellM) * cols + Math.floor((pack.x[i] - gx0) / cellM); cellOf[i] = c; count[c + 1]++; }
  for (let c = 0; c < cells; c++) count[c + 1] += count[c];
  const cellTables = new Uint32Array(n), fill = count.slice(0, cells), zMin = new Float32Array(cells).fill(Infinity), zMax = new Float32Array(cells).fill(-Infinity);
  for (let i = 0; i < n; i++) { const c = cellOf[i]; cellTables[fill[c]++] = i; zMin[c] = Math.min(zMin[c], pack.z[i]); zMax[c] = Math.max(zMax[c], pack.z[i]); }
  pack.grid = { cellM, x0: gx0, y0: gy0, cols, rows, cellStart: count, cellTables, zMin, zMax };
  return pack;
}

// The tables of one cell, as a subarray of table ids.
export const cellTables = (pack, c) => pack.grid.cellTables.subarray(pack.grid.cellStart[c], pack.grid.cellStart[c + 1]);

// ---- binary: header JSON (origin, types, graph, fence) + the eight arrays, 26 B a table ----
const FIELDS = [['x', Float32Array, 1], ['y', Float32Array, 1], ['z', Float32Array, 1], ['heading', Int16Array, 1],
  ['dz', Int16Array, 4], ['block', Uint16Array, 1], ['tilt', Uint8Array, 1], ['type', Uint8Array, 1]];

export function encodePack(pack) {
  const head = new TextEncoder().encode(JSON.stringify({ n: pack.n, origin: pack.origin, types: pack.types, graph: pack.graph, fence: pack.fence, cellM: pack.grid?.cellM ?? CELL_M }));
  const pad = (4 - ((12 + head.length) % 4)) % 4, body = pack.n * BYTES_PER_TABLE;
  const buf = new ArrayBuffer(12 + head.length + pad + body + 4), dv = new DataView(buf);
  dv.setUint32(0, MAGIC, true); dv.setUint32(4, VERSION, true); dv.setUint32(8, head.length, true);
  new Uint8Array(buf, 12, head.length).set(head);
  let at = 12 + head.length + pad;
  for (const [k, C, w] of FIELDS) {
    const bytes = pack.n * w * C.BYTES_PER_ELEMENT;
    new Uint8Array(buf, at, bytes).set(new Uint8Array(pack[k].buffer, pack[k].byteOffset, bytes)); at += bytes;
  }
  return buf;
}

export function decodePack(buf) {
  const dv = new DataView(buf);
  if (dv.getUint32(0, true) !== MAGIC) throw Error('not a plant pack');
  if (dv.getUint32(4, true) !== VERSION) throw Error(`plant pack version ${dv.getUint32(4, true)} is not ${VERSION}`);
  const len = dv.getUint32(8, true), head = JSON.parse(new TextDecoder().decode(new Uint8Array(buf, 12, len)));
  const pack = allocate(head.n, head.origin, head.types);
  let at = 12 + len + ((4 - ((12 + len) % 4)) % 4);
  for (const [k, C, w] of FIELDS) { const bytes = head.n * w * C.BYTES_PER_ELEMENT; pack[k] = new C(buf.slice(at, at + bytes)); at += bytes; }
  pack.graph = head.graph; pack.fence = head.fence;
  return indexPack(pack, head.cellM);
}

// What the pack holds, in the figures a reader checks: tables, bytes a table, bytes in all, blocks, cells.
export const packSize = pack => ({ tables: pack.n, bytesPerTable: BYTES_PER_TABLE, tableBytes: pack.n * BYTES_PER_TABLE,
  blocks: pack.blocks.length, stations: pack.graph?.stations.length ?? 0, feeders: pack.graph?.feeders.length ?? 0,
  cells: pack.grid.cols * pack.grid.rows, indexBytes: pack.grid.cellStart.byteLength + pack.grid.cellTables.byteLength });

Plant Packing

A JavaScript module in the world folder of GlobalGrid2050 that works with seg dist (`segDist`) and inside poly (`insidePoly`) and calculates planar distances.

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-packing.mjs · lines 1–137 of 137 · version 2026-09-27 18:53 · pattern packFields (shared by 3 files)

What it does
It calculates its inputs. Defines 10 functions or classes, including segDist, insidePoly, fieldsOf, fieldSet, within.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 1 file: Plant Layout (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
It is built from the seg dist helper (`segDist`), the inside poly helper (`insidePoly`) and the fields of helper (`fieldsOf`). How the tables of a plant fill its land.
Why it matters
Imported by Plant Layout.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
none found
Used by
imported by Plant Layout (import)
Produces
PACKINGS, FIELD_DEFAULTS, HEDGE_NEAR_M, fieldsOf, fieldSet, slice, packFields
Defines here
segDist, insidePoly, fieldsOf, fieldSet, within, okIn, slice, intersect, packFields, fits
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/plant-packing.mjs:1-137 · blob e9233715de5d7807666474c29f0f546d1863a759 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// plant-packing.mjs: how the tables of a plant fill its land. Two packings, both typed (packing fields | packing bands):
//
//   bands   the v09 rule: one row frame over the whole boundary, an east-west track every band (bandTargetM), runs of
//           tables at fixed places from the spine with a cross lane every run (runTargetM), whole tables only.
//   fields  a plant made of hedged fields packed as one set: each field keeps its own row origin (rows start at its own
//           south edge), its own slope-aware row gaps, and its own run origin (tables start at its own west edge, not
//           on a grid laid from the spine); half tables close the row ends; one spine, one compound and one set of
//           tracks serve every field, and tracks come only every bandTargetM (400 m by default: every table within
//           about 200 m of a road; the rows between are walked or driven down the row gaps). Edges a field shares with
//           another (a hedge between two fields of the plant) keep the hedge setback; outer edges keep the fence setback.
//
// Why: an open-data study of large operational UK plants found the v09 packing drew a median of about 0.72 of the rows
// built on the same land, the loss being the spine, the 150 m bands and the setbacks repeated on every hedged field;
// a fill that followed each field came within 1 % of a planning module count. Figures are illustrative rules, not a
// design; every one is typed and can be changed. Pure: no DOM, no imports.

export const PACKINGS = Object.freeze(['fields', 'bands']);
// Defaults the fields packing puts under whatever the owner typed (bands keeps the v09 figures of LAYOUT_DEFAULTS).
export const FIELD_DEFAULTS = Object.freeze({ bandTargetM: 400, runTargetM: 280, crossLaneM: 4 });
export const HEDGE_NEAR_M = 30; // an edge within this of another field of the plant is a hedge between them

const segDist = (x, y, ax, ay, bx, by) => {
  const dx = bx - ax, dy = by - ay, d2 = dx * dx + dy * dy, t = d2 ? Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / d2)) : 0;
  return Math.hypot(x - ax - t * dx, y - ay - t * dy);
};
const insidePoly = (poly, x, y) => {
  let c = false;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const [xi, yi] = poly[i], [xj, yj] = poly[j];
    if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) c = !c;
  }
  return c;
};

/** A boundary as a list of fields: one ring [[x, y]...] or several [[[x, y]...]...]. */
export function fieldsOf(boundary) {
  const b = boundary || [];
  return Array.isArray(b[0]?.[0]) ? b.filter(f => Array.isArray(f) && f.length >= 3) : [b];
}

/**
 * The fields in the layout frame with their setbacks: each edge takes the hedge setback where it lies within
 * HEDGE_NEAR_M of another field, else the fence setback. Returns { list, ok(u, v), okIn(i, u, v), inAny(u, v), box }.
 */
export function fieldSet(polys, { fenceSetbackM, hedgeSetbackM = fenceSetbackM }) {
  const list = polys.map(poly => {
    const box = [Math.min(...poly.map(q => q[0])), Math.max(...poly.map(q => q[0])), Math.min(...poly.map(q => q[1])), Math.max(...poly.map(q => q[1]))];
    return { poly, box, sb: null };
  });
  for (const [i, f] of list.entries()) {
    f.sb = f.poly.map((q, k) => {
      if (list.length < 2) return fenceSetbackM;
      const a = f.poly[(k || f.poly.length) - 1], mx = (a[0] + q[0]) / 2, my = (a[1] + q[1]) / 2;
      const near = list.some((g, j) => j !== i && mx > g.box[0] - HEDGE_NEAR_M && mx < g.box[1] + HEDGE_NEAR_M && my > g.box[2] - HEDGE_NEAR_M
        && my < g.box[3] + HEDGE_NEAR_M && g.poly.some((p, m) => segDist(mx, my, ...g.poly[(m || g.poly.length) - 1], ...p) < HEDGE_NEAR_M));
      return near ? Math.min(hedgeSetbackM, fenceSetbackM) : fenceSetbackM;
    });
  }
  const within = (f, u, v) => u >= f.box[0] && u <= f.box[1] && v >= f.box[2] && v <= f.box[3] && insidePoly(f.poly, u, v);
  const okIn = (i, u, v) => {
    const f = list[i];
    if (!within(f, u, v)) return false;
    for (let k = 0, j = f.poly.length - 1; k < f.poly.length; j = k++) if (segDist(u, v, ...f.poly[j], ...f.poly[k]) < f.sb[k] - 1e-9) return false;
    return true;
  };
  const all = list.flatMap(f => f.poly);
  return { list, okIn, ok: (u, v) => list.some((f, i) => okIn(i, u, v)), inAny: (u, v) => list.some(f => within(f, u, v)),
    box: [Math.min(...all.map(q => q[0])), Math.max(...all.map(q => q[0])), Math.min(...all.map(q => q[1])), Math.max(...all.map(q => q[1]))] };
}

/** Where a horizontal line v crosses a ring: the inside intervals [[u0, u1]...], sorted. */
export function slice(poly, v) {
  const xs = [];
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const [xi, yi] = poly[i], [xj, yj] = poly[j];
    if ((yi > v) !== (yj > v)) xs.push(xi + (v - yi) * (xj - xi) / (yj - yi));
  }
  xs.sort((a, b) => a - b);
  const out = [];
  for (let k = 0; k + 1 < xs.length; k += 2) out.push([xs[k], xs[k + 1]]);
  return out;
}
const intersect = (A, B) => {
  const out = [];
  for (const [a0, a1] of A) for (const [b0, b1] of B) { const lo = Math.max(a0, b0), hi = Math.min(a1, b1); if (hi > lo) out.push([lo, hi]); }
  return out;
};

/**
 * Fields packing, as a generator: every table position it tries goes to c.consider(ua, ub, va, vb, meta), which runs the
 * ground, road, water and overhead-line checks and keeps or counts it. c: { fields (fieldSet), T, p, us, spineHalf,
 * tracks, trackHalf, halfLen, halfUnits, stretch(i, va, vb) -> x >= 1, consider }. Yields progress every p.chunk tries.
 */
export function* packFields(c) {
  const { fields, T, p, us, spineHalf, tracks, trackHalf } = c, step = 1, eps = 1e-9;
  const runStep = Math.max(1, Math.round(p.runTargetM / (T.lenU + p.tableGapM))) * (T.lenU + p.tableGapM) - p.tableGapM + p.crossLaneM;
  const perRun = Math.max(1, Math.round(p.runTargetM / (T.lenU + p.tableGapM)));
  let n = 0;
  const stats = { half: 0, rows: 0, stretched: 0, maxStretch: 1 };
  for (const [fi, f] of fields.list.entries()) {
    const sb0 = Math.min(...f.sb);
    let va = f.box[2] + sb0, r = 0;
    while (va + T.depth <= f.box[3] - sb0 + eps) {
      const vb = va + T.depth, tk = tracks.findIndex(t => va < t + trackHalf && vb > t - trackHalf);
      if (tk >= 0) { va = tracks[tk] + trackHalf; r = 0; continue; }     // the row starts past the track
      let k = 0;
      for (let q = 0; q < tracks.length; q++) if (tracks[q] <= va) k = q;
      const strip = intersect(intersect(slice(f.poly, va + eps), slice(f.poly, (va + vb) / 2)), slice(f.poly, vb - eps));
      // Either side of the spine; a piece that starts at the field edge starts past its setback, one at the spine does not.
      const pieces = strip.flatMap(([u0, u1]) => [[u0, Math.min(u1, us - spineHalf), sb0], [Math.max(u0, us + spineHalf), u1, u0 >= us + spineHalf ? sb0 : 0]])
        .filter(([a, b]) => b - a >= c.halfLen);
      for (const [lo, hi, in0] of pieces) {
        let a = lo + in0, inRun = 0;
        while (a + c.halfLen <= hi + eps) {
          if (++n % p.chunk === 0) yield { phase: 'tables', candidates: n, accepted: c.accepted?.() };
          let len = T.lenU;
          const fits = L => a + L <= hi + eps && [[a, va], [a + L, va], [a, vb], [a + L, vb], [a + L / 2, va], [a + L / 2, vb]].every(([u, v]) => fields.okIn(fi, u, v));
          if (!fits(len)) {
            if (p.halfTables && c.halfLen < T.lenU && fits(c.halfLen)) len = c.halfLen;
            else { a += step; inRun = 0; continue; }
          }
          const units = len < T.lenU ? c.halfUnits : 1, mid = a + len / 2;
          if (units < 1) stats.half++;
          c.consider(a, a + len, va, vb, { k, s: mid >= us ? 1 : -1, j: Math.floor(Math.abs(mid - us) / runStep), r, i: inRun, units, field: fi });
          a += len + p.tableGapM; inRun++;
          if (inRun >= perRun) { a += p.crossLaneM - p.tableGapM; inRun = 0; }
        }
      }
      stats.rows++;
      const x = c.stretch(fi, va, vb);
      if (x > 1 + 1e-6) stats.stretched++;
      stats.maxStretch = Math.max(stats.maxStretch, x);
      va += T.pitch * x; r++;
    }
  }
  return { candidates: n, ...stats };
}