In this section
- Grid ingest · graphics-engines-open-source / web/versions/202609262227-site-world/world/layers/grid.mjs lines 1–214
- Lines render · graphics-engines-open-source / web/versions/202609262227-site-world/world/lines.mjs lines 1–154
- Overhead transform · graphics-engines-open-source / web/versions/202609262227-site-world/world/overhead.mjs lines 1–199
Grid
A JavaScript module in the layers folder of Graphics Engines Open Source that works with voltage class (`voltageClass`) and measured spans (`measuredSpans`) and calculates planar distances (units: kV), using SHA-256.
ingestgraphics-engines-open-source / web/versions/202609262227-site-world/world/layers/grid.mjs · lines 1–214 of 214 · version 2026-09-26 22:27 · Not reached from any entry point (candidate for review) · pattern clearanceStatus (shared by 3 files)
- What it does
- It lists and searches substations, 33kV, 400kV and 275kV. Defines 15 functions or classes, including voltageClass, finite, isPt, parseGridFile, compound.
- Why it exists in the grid workflow
- Domain terms in the code: substations, 33kV, 400kV, 275kV, 132kV.
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid). Voltage levels named: 400kV, 275kV, 132kV, 33kV.
- What it achieves
- It parses grid file (`parseGridFile`) and is built from the voltage class helper (`voltageClass`) and the finite step (`finite`). Overhead lines and substations from a per-site file, drawn as quiet wireframe on the ground. Its code works with 33 kV, 132 kV and 275 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- graphics-engines-open-source · web/versions/202609262227-site-world/world/layers · JavaScript module
- Uses
- none found
- Used by
- mentioned in Standalone (comment link)
- Produces
- voltageClass, COLORS, COMPOUND, FENCE_H, parseGridFile, compound, measuredSpans, clearanceStatus, buildGrid, createGrid
- Defines here
- voltageClass, finite, isPt, parseGridFile, compound, P, L, measuredSpans, clearanceStatus, fmt, straightGround, buildGrid, local, createGrid, load
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/versions/202609262227-site-world/world/layers/grid.mjs:1-214 · blob 9b84538e051dc5c7df307392d3d2c72f0b8cbe96 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
// Layer: grid. Overhead lines and substations from a per-site file, drawn as quiet wireframe on the ground.
// Self-contained: no imports (it runs from a blob URL). The towers and conductors come from the shared overhead
// builder the substrate hands in as api.lib.overhead.buildOverhead; without it the layer draws nothing and says so.
//
// Config (manifest): { path, sha256 } of the site file, fetched through the substrate's hash check. File format:
// { licence, attribution,
// lines: [{ voltage_kv, operator, points: [[e, n], ...], towers: [indices into points] }],
// substations: [{ e, n, voltage_kv, operator }] }
// in British National Grid metres. Positions are turned into local metres with api.origin(). Where a line gives
// no towers, every point is a tower. Points that are not towers are ignored: a span runs straight tower to tower.
//
// Towers stand on the ground (ctx.heightAt). Clearance is measured against the same ground, 1 m along each
// conductor, and the lowest per span is shown in layer.status. Towers and compounds are solids (walkers and the
// drone are blocked). The geometry is rebuilt when the ground or the origin changes.
//
// TOWER SHAPES, SAG AND COMPOUND SIZES ARE ASSUMED (typical, not surveyed). Positions and voltages are the file's.
// Voltage class from a nominal kV. Bands: >= 345 is 400 kV, >= 220 is 275 kV, >= 66 is 132 kV, else 33 kV.
export function voltageClass(kv) {
const v = Number(kv);
if (!(v > 0)) return '33kV';
return v >= 345 ? '400kV' : v >= 220 ? '275kV' : v >= 66 ? '132kV' : '33kV';
}
// Quiet colours on the dark background, by class. Blue for 400 and red for 275 follow the usual UK map convention.
export const COLORS = {
'400kV': [0.55, 0.66, 1.00, 0.62],
'275kV': [1.00, 0.56, 0.56, 0.55],
'132kV': [1.00, 0.80, 0.48, 0.50],
'33kV': [0.56, 0.86, 0.62, 0.45],
};
// Compound footprint (east-west by north-south, metres) and fence height by class. ASSUMED: typical outdoor
// air-insulated compounds, proportioned by eye, not from any survey or public source checked in this session.
export const COMPOUND = {
'400kV': { w: 300, d: 200 },
'275kV': { w: 220, d: 150 },
'132kV': { w: 90, d: 60 },
'33kV': { w: 30, d: 20 },
};
export const FENCE_H = 2.4; // assumed palisade fence height, metres
const FENCE_STEP = 10; // fence line drapes on the ground every 10 m or less
const LIST_MAX = 30; // spans listed by name in the status line
const finite = (h, d = 0) => (Number.isFinite(h) ? h : d);
const isPt = p => Array.isArray(p) && Number.isFinite(p[0]) && Number.isFinite(p[1]);
// Pure: the file -> { lines: [{ cls, operator, towers: [{ id, e, n }] }], substations: [{ cls, e, n, operator }] }.
// Throws on a file that is not the expected shape; skips individual entries that are unusable.
export function parseGridFile(j) {
if (!j || typeof j !== 'object' || !Array.isArray(j.lines)) throw Error('grid file has no lines list');
const lines = [];
j.lines.forEach((l, i) => {
const pts = Array.isArray(l?.points) ? l.points : [];
let idx = Array.isArray(l?.towers) && l.towers.length ? l.towers : pts.map((_, k) => k);
idx = [...new Set(idx.filter(k => Number.isInteger(k) && k >= 0 && k < pts.length && isPt(pts[k])))].sort((a, b) => a - b);
if (!idx.length) return;
const cls = voltageClass(l.voltage_kv);
lines.push({ cls, kv: l.voltage_kv, operator: l.operator || '', towers: idx.map(k => ({ id: `L${i}T${k}`, e: pts[k][0], n: pts[k][1] })) });
});
const substations = (Array.isArray(j.substations) ? j.substations : [])
.filter(s => s && Number.isFinite(s.e) && Number.isFinite(s.n))
.map(s => ({ cls: voltageClass(s.voltage_kv), kv: s.voltage_kv, operator: s.operator || '', e: s.e, n: s.n }));
return { lines, substations, licence: j.licence || '', attribution: j.attribution || '' };
}
// Pure: a compound's fence as line pairs relative to o, draped on heightAt, plus its solid box (absolute local).
export function compound(x, y, cls, heightAt, o = [0, 0, 0]) {
const { w, d } = COMPOUND[cls] || COMPOUND['33kV'];
const c = [[x - w / 2, y - d / 2], [x + w / 2, y - d / 2], [x + w / 2, y + d / 2], [x - w / 2, y + d / 2]];
const out = [], g = (px, py) => finite(heightAt(px, py), finite(heightAt(x, y)));
let lo = Infinity, hi = -Infinity;
const P = (px, py, up) => { const z = g(px, py); lo = Math.min(lo, z); hi = Math.max(hi, z); return [px - o[0], py - o[1], z + up - o[2]]; };
const L = (a, b) => out.push(a[0], a[1], a[2], b[0], b[1], b[2]);
for (let k = 0; k < 4; k++) {
const [ax, ay] = c[k], [bx, by] = c[(k + 1) % 4];
const m = Math.max(1, Math.ceil(Math.hypot(bx - ax, by - ay) / FENCE_STEP));
for (let i = 0; i < m; i++) {
const f0 = i / m, f1 = (i + 1) / m;
const x0 = ax + (bx - ax) * f0, y0 = ay + (by - ay) * f0, x1 = ax + (bx - ax) * f1, y1 = ay + (by - ay) * f1;
L(P(x0, y0, 0), P(x1, y1, 0)); // foot of the fence
L(P(x0, y0, FENCE_H), P(x1, y1, FENCE_H)); // top rail
}
L(P(ax, ay, 0), P(ax, ay, FENCE_H)); // corner post
}
// A cross at the centre marks the compound from the air.
const s = Math.min(w, d) * 0.15;
L(P(x - s, y, 0.2), P(x + s, y, 0.2)); L(P(x, y - s, 0.2), P(x, y + s, 0.2));
return { positions: out, solid: { min: [x - w / 2, y - d / 2, lo], max: [x + w / 2, y + d / 2, hi + FENCE_H] } };
}
// Pure: for each span, true when both towers and every point under it (5 m steps) have measured ground.
export function measuredSpans(towers, measuredAt) {
const out = [];
for (let k = 0; k + 1 < towers.length; k++) {
const A = towers[k], B = towers[k + 1], n = Math.max(2, Math.ceil(Math.hypot(B.x - A.x, B.y - A.y) / 5));
let ok = true;
for (let s = 0; s <= n && ok; s++) ok = Number.isFinite(measuredAt(A.x + (B.x - A.x) * s / n, A.y + (B.y - A.y) * s / n));
out.push(ok);
}
return out;
}
// Pure: the status line from per-span clearances.
export function clearanceStatus(model, clearances) {
const nT = model.lines.reduce((s, l) => s + l.towers.length, 0);
const head = `grid: ${model.lines.length} lines, ${nT} towers, ${model.substations.length} substations`;
if (!clearances.length) return `${head}; no spans; tower and compound sizes assumed`;
const fmt = c => (Number.isFinite(c.minClearance) ? c.minClearance.toFixed(1) + (c.minClearance < c.required ? '!' : '') : 'not measured');
const shown = clearances.slice(0, LIST_MAX).map(c => `${c.from}-${c.to} ${fmt(c)}`);
if (clearances.length > LIST_MAX) shown.push(`+${clearances.length - LIST_MAX} more`);
const measured = clearances.filter(c => Number.isFinite(c.minClearance));
const ASSUMED = 'assumed: tower positions inferred from OpenStreetMap, attachment heights and sag typical,'
+ ' required clearance figure to be confirmed against ESQCR, compound sizes';
if (!measured.length) return `${head}; clearance not measured yet (walk or fly near the line so its ground loads); ${ASSUMED}`;
const low = measured.reduce((a, b) => (b.minClearance < a.minClearance ? b : a));
const below = measured.filter(c => c.minClearance < c.required).length;
return `${head}; min ground clearance per span (m): ${shown.join(', ')}; lowest measured ${fmt(low)} on ${low.from}-${low.to}` +
` (needs ${low.required}); ${below} measured span${below === 1 ? '' : 's'} below the figure; ${ASSUMED}`;
}
// Ground on the straight line between the tower grounds of the span nearest (x, y).
function straightGround(towers, x, y) {
if (towers.length < 2) return towers[0]?.ground ?? 0;
let best = Infinity, h = towers[0].ground;
for (let k = 0; k + 1 < towers.length; k++) {
const A = towers[k], B = towers[k + 1], dx = B.x - A.x, dy = B.y - A.y, L2 = dx * dx + dy * dy || 1;
const f = Math.min(1, Math.max(0, ((x - A.x) * dx + (y - A.y) * dy) / L2));
const d = Math.hypot(A.x + dx * f - x, A.y + dy * f - y);
if (d < best) { best = d; h = A.ground + (B.ground - A.ground) * f; }
}
return h;
}
// Pure: build every batch, solid and clearance for the model at the given origin and ground.
export function buildGrid(model, origin, heightAt, buildOverhead, measuredAt = heightAt) {
const batches = [], solids = [], clearances = [];
const local = (e, n) => [e - origin.e, n - origin.n];
model.lines.forEach((l, i) => {
const towers = l.towers.map(t => { const [x, y] = local(t.e, t.n); return { id: t.id, x, y, ground: finite(heightAt(x, y)), type: l.cls }; });
const known = measuredSpans(towers, measuredAt);
// Off the loaded ground, clearance is measured to the straight line between the nearest span's tower grounds.
const out = buildOverhead(towers, {
groundAt: (x, y) => { const h = heightAt(x, y); return Number.isFinite(h) ? h : straightGround(towers, x, y); }
});
const o = [towers[0].x, towers[0].y, towers[0].ground], pos = new Float32Array(out.lines.length);
for (let k = 0; k < pos.length; k += 3) { pos[k] = out.lines[k] - o[0]; pos[k + 1] = out.lines[k + 1] - o[1]; pos[k + 2] = out.lines[k + 2] - o[2]; }
batches.push({ key: `grid/line/${i}`, origin: o, color: COLORS[l.cls], positions: pos });
solids.push(...out.solids);
// Clearance is only reported where the whole span stands on measured LiDAR ground; elsewhere it is not measured.
clearances.push(...out.clearances.map(c => (known[c.span] ? { ...c, line: i, cls: l.cls }
: { ...c, minClearance: NaN, at: null, line: i, cls: l.cls, note: 'ground not measured under this span' })));
});
model.substations.forEach((s, i) => {
const [x, y] = local(s.e, s.n), o = [x, y, finite(heightAt(x, y))];
const c = compound(x, y, s.cls, heightAt, o);
batches.push({ key: `grid/substation/${i}`, origin: o, color: COLORS[s.cls], positions: new Float32Array(c.positions) });
solids.push(c.solid);
});
return { batches, solids, clearances };
}
export function createGrid() {
let api = null, model = null, state = 'idle'; // idle | loading | ready | failed
let built = { version: null, batches: [], solids: [], clearances: [] };
function load() {
if (state !== 'idle' || !api) return;
const path = api.config?.path, sha = api.config?.sha256;
if (!path || !sha) { state = 'failed'; layer.status = 'no grid file configured (config.path and config.sha256)'; return; }
state = 'loading'; layer.status = 'loading ' + path;
Promise.resolve().then(() => api.fetchJSON(path, sha)).then(j => {
model = parseGridFile(j);
state = 'ready';
layer.status = `grid file loaded: ${model.lines.length} lines, ${model.substations.length} substations`;
api.invalidate({ ground: false });
}).catch(e => { state = 'failed'; layer.status = 'grid file failed: ' + e.message; });
}
const layer = {
id: 'grid',
status: 'waiting for init',
clearances: [],
init(a) { api = a; layer.status = 'ready to load'; load(); },
lines(ctx) {
if (!api) return [];
if (state === 'idle') load();
if (state !== 'ready') return [];
const lib = api.lib?.overhead;
if (!lib || typeof lib.buildOverhead !== 'function') { layer.status = 'waiting: api.lib.overhead.buildOverhead not provided'; return []; }
const o = typeof api.origin === 'function' ? api.origin() : { e: 0, n: 0, id: 0 };
const heightAt = typeof ctx.heightAt === 'function' ? ctx.heightAt : () => NaN;
const version = `${o.e},${o.n},${o.id}@${ctx.groundVersion ?? 0}`;
if (built.version === version && built.heightAt === heightAt) return built.batches;
try {
const measured = typeof ctx.measuredAt === 'function' ? ctx.measuredAt : heightAt;
const g = buildGrid(model, o, heightAt, lib.buildOverhead, measured);
built = { version, heightAt, ...g, batches: g.batches.map(b => ({ ...b, version })) };
layer.clearances = g.clearances;
layer.status = clearanceStatus(model, g.clearances);
} catch (e) {
built = { version, heightAt, batches: [], solids: [], clearances: [] };
layer.status = 'grid build failed: ' + e.message;
}
return built.batches;
},
// Boxes from the last build (towers and compounds). Empty until the first frame has drawn the grid.
solids() { return built.solids; },
debug: () => ({ state, model, version: built.version })
};
return layer;
}
export default createGrid();Lines
A JavaScript module in the world folder of Graphics Engines Open Source that splits batches (`splitBatches`), calculates planar distances and renders with WebGL.
rendergraphics-engines-open-source / web/versions/202609262227-site-world/world/lines.mjs · lines 1–154 of 154 · version 2026-09-26 22:27 · pattern occluderFollower (shared by 4 files)
- What it does
- It draws its content. Defines 8 functions or classes, including offsetOf, splitBatches, occluderMesh, put, occluderFollower. Side effects: changes the web page (DOM).
- Inputs & outputs
- Out: WebGL/WebGPU drawing.
- Downstream impact
- Used directly by 1 file: Substrate (graphics-engines-open-source). Reached from 2 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/).
- What it achieves
- It splits batches (`splitBatches`) and is built from the offset of helper (`offsetOf`) and the occluder mesh helper (`occluderMesh`). Line renderer: raw WebGL 1, flat colour, lines fade with distance. It responds to webglcontextlost and webglcontextrestored events.
- Why it matters
- Imported by Substrate.
- Application
- graphics-engines-open-source · web/versions/202609262227-site-world/world · JavaScript module
- Uses
- none found
- Used by
- imported by Substrate (import), mentioned in Standalone (comment link)
- Produces
- offsetOf, BACKGROUND, splitBatches, occluderMesh, occluderFollower, createLines
- Defines here
- offsetOf, splitBatches, occluderMesh, put, occluderFollower, createLines, init, bind
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/versions/202609262227-site-world/world/lines.mjs:1-154 · blob 564146739768b925df35593039fc80b19e8b1f40 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: duplicate_candidate
// Line renderer: raw WebGL 1, flat colour, lines fade with distance. No textures, no sky, no lighting.
// Survives a lost WebGL context: every buffer is rebuilt from the layers' own data on restore.
// Drawing is relative to the eye: the matrix is built with the eye at [0, 0, 0], and each batch is moved by
// u_off = (batch origin - eye), worked out in JavaScript doubles. A batch with an origin keeps its
// positions small, so 32-bit floats stay sharp however far the viewer walks from the site origin.
// Occlusion: batches marked { occluder: true, triangles } (a coarse ground mesh) are drawn first into the
// depth buffer only; then every line batch is depth tested against them, so lines behind a hill are hidden.
// Lines never write depth, so they never hide each other; only occluders hide anything.
const VS = `attribute vec3 a_p; uniform mat4 u_m; uniform vec3 u_off; uniform float u_fade; varying float v_a;
void main() { vec3 p = a_p + u_off; gl_Position = u_m * vec4(p, 1.0); v_a = clamp(1.0 - length(p) / u_fade, 0.0, 1.0); }`;
const ZERO = [0, 0, 0];
// The offset from the eye to a batch's origin, in doubles; only the small result goes to the GPU.
export const offsetOf = (origin, eye) => {
const o = origin || ZERO;
return [o[0] - eye[0], o[1] - eye[1], o[2] - eye[2]];
};
const FS = `precision mediump float; uniform vec4 u_c; varying float v_a;
void main() { gl_FragColor = vec4(u_c.rgb, u_c.a * v_a); }`;
export const BACKGROUND = [10 / 255, 10 / 255, 10 / 255, 1]; // #0a0a0a
// Occluders first (depth only), then lines; order within each group is kept.
export const splitBatches = batches => {
const occluders = [], lines = [];
for (const b of batches) (b.occluder ? occluders : lines).push(b);
return { occluders, lines };
};
// A coarse ground mesh around (x, y) for occlusion, as an occluder batch. Pure: it only calls heightAt.
// The centre snaps to the cell grid so the mesh does not swim as the viewer moves; positions are relative
// to that centre (the batch origin), so they stay small. sink lowers the mesh so lines lying on finer
// ground than these cells are not buried where the coarse surface cuts above the true one.
// Cells with a corner that has no finite height are left out (nothing is hidden there).
export function occluderMesh(heightAt, x, y, { cell = 8, radius = 400, sink = 0.5, key = 'occluder', version } = {}) {
if (!(cell > 0) || !(radius > 0)) throw Error('occluderMesh needs a positive cell and radius');
const cx = Math.round(x / cell) * cell, cy = Math.round(y / cell) * cell;
const n = Math.ceil(radius / cell), side = 2 * n + 1;
const h = new Float64Array(side * side);
for (let j = 0; j < side; j++) for (let i = 0; i < side; i++) {
const v = heightAt(cx + (i - n) * cell, cy + (j - n) * cell);
h[j * side + i] = Number.isFinite(v) ? v - sink : NaN;
}
const out = new Float32Array((side - 1) * (side - 1) * 18);
let k = 0;
const put = (i, j) => { out[k++] = (i - n) * cell; out[k++] = (j - n) * cell; out[k++] = h[j * side + i]; };
for (let j = 0; j < side - 1; j++) for (let i = 0; i < side - 1; i++) {
const a = h[j * side + i], b = h[j * side + i + 1], c = h[(j + 1) * side + i], d = h[(j + 1) * side + i + 1];
if (!Number.isFinite(a + b + c + d)) continue;
put(i, j); put(i + 1, j); put(i + 1, j + 1);
put(i, j); put(i + 1, j + 1); put(i, j + 1);
}
return { key, version: version ?? `${cx},${cy},${cell},${radius},${sink}`, occluder: true,
triangles: out.subarray(0, k), origin: [cx, cy, 0] };
}
// Keeps one occluder mesh and rebuilds it only when the viewer has moved `every` metres from where it was
// built, or the ground has changed (groundVersion). Returns the same batch object while nothing changed.
export function occluderFollower({ every = 64, ...opts } = {}) {
let last = null, at = null, gv;
return (heightAt, pos, groundVersion = 0) => {
if (!last || gv !== groundVersion || Math.hypot(pos[0] - at[0], pos[1] - at[1]) > every) {
at = [pos[0], pos[1]]; gv = groundVersion;
const m = occluderMesh(heightAt, pos[0], pos[1], opts);
last = { ...m, version: `${m.version},g${groundVersion}` };
}
return last;
};
}
export function createLines(canvas, { onRestore = () => {} } = {}) {
let gl, prog, loc, lost = false, scale = 0;
const cache = new Map(); // batch key -> { buf, version, count }
function init() {
gl = canvas.getContext('webgl', { antialias: true, alpha: false, depth: true, powerPreference: 'low-power' });
if (!gl) throw Error('WebGL is not available in this browser');
prog = gl.createProgram();
for (const [type, src] of [[gl.VERTEX_SHADER, VS], [gl.FRAGMENT_SHADER, FS]]) {
const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS) && !gl.isContextLost()) throw Error(gl.getShaderInfoLog(s));
gl.attachShader(prog, s);
}
gl.linkProgram(prog);
loc = { p: gl.getAttribLocation(prog, 'a_p'), m: gl.getUniformLocation(prog, 'u_m'), off: gl.getUniformLocation(prog, 'u_off'),
fade: gl.getUniformLocation(prog, 'u_fade'), c: gl.getUniformLocation(prog, 'u_c') };
gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.depthFunc(gl.LEQUAL); gl.clearDepth(1);
cache.clear();
}
canvas.addEventListener('webglcontextlost', e => { e.preventDefault(); lost = true; cache.clear(); });
canvas.addEventListener('webglcontextrestored', () => { init(); lost = false; scale = 0; onRestore(); });
init();
// Uploads a batch's data once per version and binds it; returns its vertex count.
function bind(b, data) {
let c = cache.get(b.key);
if (!c || c.version !== b.version) {
if (!c) c = { buf: gl.createBuffer() };
gl.bindBuffer(gl.ARRAY_BUFFER, c.buf); gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
c.version = b.version; c.count = data.length / 3; cache.set(b.key, c);
}
gl.bindBuffer(gl.ARRAY_BUFFER, c.buf); gl.vertexAttribPointer(loc.p, 3, gl.FLOAT, false, 0, 0);
return c.count;
}
return {
lost: () => lost,
// returns true when the drawing buffer changed size
resize(nextScale) {
const w = Math.max(1, Math.round(canvas.clientWidth * nextScale)), h = Math.max(1, Math.round(canvas.clientHeight * nextScale));
if (canvas.width === w && canvas.height === h && scale === nextScale) return false;
canvas.width = w; canvas.height = h; scale = nextScale;
return true;
},
// matrix: projection times the view built at the eye, i.e. view([0, 0, 0], yaw, pitch).
// eye: the viewer's position in local metres (doubles). fade: distance in metres where lines vanish.
// batches: [{ key, version, positions: Float32Array of x,y,z pairs, color: [r,g,b,a], origin?: [x,y,z] }]
// and occluders: { key, version, occluder: true, triangles: Float32Array of x,y,z triples, origin? }
// Returns the number of line vertices drawn (occluder vertices are not counted).
draw(matrix, eye, fade, batches) {
if (lost) return 0;
const { occluders, lines } = splitBatches(batches);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(...BACKGROUND); gl.depthMask(true); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.useProgram(prog);
gl.uniformMatrix4fv(loc.m, false, matrix); gl.uniform1f(loc.fade, fade);
gl.enableVertexAttribArray(loc.p);
gl.enable(gl.DEPTH_TEST);
// Depth only: no colour, pushed slightly back so lines lying on the surface do not z-fight with it.
gl.colorMask(false, false, false, false);
gl.enable(gl.POLYGON_OFFSET_FILL); gl.polygonOffset(1, 4);
for (const b of occluders) {
const count = bind(b, b.triangles);
gl.uniform3fv(loc.off, offsetOf(b.origin, eye));
gl.drawArrays(gl.TRIANGLES, 0, count);
}
gl.disable(gl.POLYGON_OFFSET_FILL);
gl.colorMask(true, true, true, true);
gl.depthMask(false); // lines are tested against the ground but never hide each other
let vertices = 0;
for (const b of lines) {
const count = bind(b, b.positions);
gl.uniform3fv(loc.off, offsetOf(b.origin, eye));
gl.uniform4fv(loc.c, b.color); gl.drawArrays(gl.LINES, 0, count);
vertices += count;
}
gl.depthMask(true);
return vertices;
}
};
}Overhead
A JavaScript module in the world folder of Graphics Engines Open Source that works with 400kV, 275kV, 132kV and 33kV.
transformgraphics-engines-open-source / web/versions/202609262227-site-world/world/overhead.mjs · lines 1–199 of 199 · version 2026-09-26 22:27 · pattern buildOverhead (shared by 2 files)
- What it does
- It calculates 400kV, 275kV, 132kV and 33kV. Defines 17 functions or classes, including coshm1, levelSag, paramFromSag, catenarySpan, z.
- Why it exists in the grid workflow
- Domain terms in the code: 400kV, 275kV, 132kV, 33kV.
- Inputs & outputs
- Voltage levels named: 400kV, 275kV, 132kV, 33kV.
- Downstream impact
- Used directly by 1 file: Layers (graphics-engines-open-source). Reached from 3 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/); Substrate (graphics-engines-open-source).
- What it achieves
- It draws tower (`drawTower`) and is built from the coshm1 step (`coshm1`) and the level sag helper (`levelSag`). Overhead lines: lattice towers, wood poles and catenary conductors as light wireframe. Its code works with 400 kV, 132 kV and 275 kV.
- Why it matters
- Imported by Layers.
- Application
- graphics-engines-open-source · web/versions/202609262227-site-world/world · JavaScript module
- Uses
- none found
- Used by
- imported by Layers (import), mentioned in Standalone (comment link)
- Produces
- SAG_TO_SPAN, STEP, MIN_CLEARANCE, TOWER_TYPES, levelSag, paramFromSag, catenarySpan, buildOverhead
- Defines here
- coshm1, levelSag, paramFromSag, catenarySpan, z, unit, directionAt, specOf, attachments, at, drawTower, P, L, ring, solidOf, buildOverhead, xy
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/versions/202609262227-site-world/world/overhead.mjs:1-199 · blob cd789c8c88a42420da0b4919de9e5d1752704920 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
// Overhead lines: lattice towers, wood poles and catenary conductors as light wireframe. Pure: no imports, no DOM.
// Local east (x), north (y), up (z), metres. Output lines are gl.LINES pairs: x,y,z, x,y,z per segment.
//
// buildOverhead(towers, opts) -> { lines: Float32Array, solids: [{ min, max }], clearances: [{ span, minClearance, at, conductor, required }] }
// towers: [{ id, x, y, ground, type?: '400kV'|'275kV'|'132kV'|'33kV' }] in order along the line
// opts.groundAt(x, y): ground height under the span (default: straight between the two tower grounds)
// opts.tensionPerWeight: catenary parameter a = H/w in metres (horizontal tension over weight per metre); wins if given
// opts.sagRatio: mid-span sag / span on the equivalent level span (default SAG_TO_SPAN); a is solved from it
// opts.step: conductor sample spacing in metres (default 5)
//
// EVERY DIMENSION BELOW IS TYPICAL, NOT SURVEYED. They draw a believable outline; they are not a design of any real line.
// Default sag: 3.5 % of span. Typical, not surveyed. UK 400 kV spans of ~360 m commonly sag 10-13 m at maximum
// design temperature, i.e. roughly 3-4 %. No single public source was checked for this figure in this session.
export const SAG_TO_SPAN = 0.035;
export const STEP = 5; // conductor sample spacing, metres
const CLEAR_STEP = 1; // clearance search spacing, metres (finer than the drawing, so a hill top is not missed)
// Minimum conductor-to-ground clearance, metres, by nominal voltage. As commonly quoted from the Electricity Safety,
// Quality and Continuity Regulations 2002 (ESQCR), Schedule 2, for ground not over a road: <=33 kV 5.2 m,
// 66-132 kV 6.7 m, 275 kV 7.0 m, 400 kV 7.3 m. Quoted from memory, not re-read in this session: check before use.
export const MIN_CLEARANCE = { '400kV': 7.3, '275kV': 7.0, '132kV': 6.7, '33kV': 5.2 };
// Tower classes. Typical, not surveyed. z = height above the tower's ground; half = half-width across the line.
// arms: cross-arm levels, each carrying one phase per side (double circuit). insulator: string length hanging below the arm.
// Public context (not re-checked in this session):
// - 400 kV: National Grid describes its standard lattice pylons (L6, and the later L12) as about 50 m tall,
// with a typical span of about 360 m. Arm widths here are proportioned by eye from published elevations.
// - 275 kV: the L2 design (1950s) is a smaller double-circuit lattice, commonly given as about 40-45 m.
// - 132 kV: the PL1 / PL16 family is commonly given as about 26-27 m, spans about 250-300 m.
// - 33 kV: wood poles, commonly 10-13 m long with about 1.5-2 m in the ground, spans about 80-120 m.
export const TOWER_TYPES = {
'400kV': { kind: 'lattice', height: 50, baseHalf: 4.5, topHalf: 1.0, peakHalf: 0.4, insulator: 5.0,
arms: [{ z: 44, half: 6.1 }, { z: 35.5, half: 7.9 }, { z: 27, half: 6.9 }] },
'275kV': { kind: 'lattice', height: 41, baseHalf: 3.8, topHalf: 0.9, peakHalf: 0.35, insulator: 3.5,
arms: [{ z: 36, half: 5.2 }, { z: 29, half: 6.4 }, { z: 22, half: 5.6 }] },
'132kV': { kind: 'lattice', height: 27, baseHalf: 2.5, topHalf: 0.7, peakHalf: 0.3, insulator: 1.8,
arms: [{ z: 24, half: 3.4 }, { z: 20, half: 3.8 }, { z: 16, half: 3.4 }] },
'33kV': { kind: 'pole', height: 9.5, radius: 0.15, armZ: 8.9, armHalf: 1.2, pin: 0.3 },
};
const DEFAULT_TYPE = '400kV';
// ---- catenary maths -------------------------------------------------------------------------------------------------
const coshm1 = (u) => { const s = Math.sinh(u / 2); return 2 * s * s; }; // cosh(u) - 1 without cancellation
// Mid-span sag of a level span of horizontal length L with parameter a: a (cosh(L / 2a) - 1).
export const levelSag = (L, a) => a * coshm1(L / (2 * a));
// The catenary parameter a whose level span of length L sags sagRatio * L. Sag falls as a grows, so bisect (in log a).
export function paramFromSag(L, sagRatio) {
if (!(L > 0) || !(sagRatio > 0)) throw Error('span and sag ratio must be positive');
const target = sagRatio * L;
let lo = Math.log(L * 1e-3), hi = Math.log(L * 1e7);
for (let i = 0; i < 200; i++) {
const mid = (lo + hi) / 2;
if (levelSag(L, Math.exp(mid)) > target) lo = mid; else hi = mid;
}
return Math.exp((lo + hi) / 2);
}
// A span of horizontal length L from height h1 (s = 0) to h2 (s = L). The curve is z = zLow + a (cosh((s - s0) / a) - 1),
// i.e. y = a cosh(x / a) shifted so its vertex sits at (s0, zLow). Solving both end conditions gives
// s0 = L/2 - a asinh((h2 - h1) / (2 a sinh(L / 2a)))
// so the vertex moves toward the lower support, and past it when the slope is steep (then s0 < 0 or s0 > L).
export function catenarySpan(L, h1, h2, a) {
const s0 = L / 2 - a * Math.asinh((h2 - h1) / (2 * a * Math.sinh(L / (2 * a))));
const zLow = h1 - a * coshm1(s0 / a);
const z = (s) => zLow + a * coshm1((s - s0) / a);
const sMin = Math.min(L, Math.max(0, s0)); // lowest point actually on the wire
return { s0, zLow, z, sMin, zMin: z(sMin) };
}
// ---- tower geometry ------------------------------------------------------------------------------------------------
const unit = (dx, dy) => { const l = Math.hypot(dx, dy); return l > 0 ? [dx / l, dy / l] : [0, 0]; };
// Line direction at tower k: the bisector of the incoming and outgoing spans (a single tower faces north).
function directionAt(towers, k) {
let dx = 0, dy = 0;
if (k > 0) { const u = unit(towers[k].x - towers[k - 1].x, towers[k].y - towers[k - 1].y); dx += u[0]; dy += u[1]; }
if (k < towers.length - 1) { const u = unit(towers[k + 1].x - towers[k].x, towers[k + 1].y - towers[k].y); dx += u[0]; dy += u[1]; }
const d = unit(dx, dy);
return d[0] === 0 && d[1] === 0 ? [0, 1] : d;
}
function specOf(t) {
const spec = TOWER_TYPES[t.type || DEFAULT_TYPE];
if (!spec) throw Error(`unknown tower type ${t.type} on ${t.id}`);
return spec;
}
// Conductor attachment points in world coordinates, in a fixed order so phase j meets phase j on the next tower.
function attachments(t, spec, d, p) {
const at = (across, z) => [t.x + p[0] * across, t.y + p[1] * across, t.ground + z];
if (spec.kind === 'pole') {
const z = spec.armZ + spec.pin;
return [at(-spec.armHalf, z), at(0, spec.height), at(spec.armHalf, z)];
}
const out = [];
for (const side of [-1, 1]) for (const arm of spec.arms) out.push(at(side * arm.half, arm.z - spec.insulator));
return out;
}
// Wireframe for one tower into seg (flat array of x,y,z pairs). d = along the line, p = across it.
function drawTower(seg, t, spec, d, p) {
const P = (along, across, z) => [t.x + d[0] * along + p[0] * across, t.y + d[1] * along + p[1] * across, t.ground + z];
const L = (a, b) => seg.push(a[0], a[1], a[2], b[0], b[1], b[2]);
if (spec.kind === 'pole') {
L(P(0, 0, 0), P(0, 0, spec.height));
L(P(0, -spec.armHalf, spec.armZ), P(0, spec.armHalf, spec.armZ));
L(P(0, -spec.armHalf * 0.6, spec.armZ), P(0, 0, spec.armZ - 0.8)); // crossarm braces
L(P(0, spec.armHalf * 0.6, spec.armZ), P(0, 0, spec.armZ - 0.8));
return;
}
// Body: a square tapering from baseHalf at the ground to topHalf at the top arm, then a peak for the earth wire.
const topZ = spec.arms[0].z, halfAt = (z) => spec.baseHalf + (spec.topHalf - spec.baseHalf) * Math.min(1, z / topZ);
const levels = [0, ...spec.arms.map((a) => a.z).sort((a, b) => a - b)];
if (levels[1] > 10) levels.splice(1, 0, levels[1] * 0.45); // a waist panel below the lowest arm
const corners = [[1, 1], [-1, 1], [-1, -1], [1, -1]];
const ring = (z) => corners.map(([i, j]) => P(i * halfAt(z), j * halfAt(z), z));
for (let n = 0; n < levels.length; n++) {
const r = ring(levels[n]);
for (let c = 0; c < 4; c++) L(r[c], r[(c + 1) % 4]); // horizontal ring
if (n === 0) continue;
const q = ring(levels[n - 1]);
for (let c = 0; c < 4; c++) {
L(q[c], r[c]); // leg
L(q[c], r[(c + 1) % 4]); L(q[(c + 1) % 4], r[c]); // X bracing on each face
}
}
const top = ring(topZ), peak = P(0, 0, spec.height);
for (let c = 0; c < 4; c++) L(top[c], peak);
// Cross-arms: a triangle each side, top chord level, bottom chord rising to the tip; a short line for the insulator.
for (const arm of spec.arms) {
const h = halfAt(arm.z), depth = Math.min(3, arm.half * 0.35);
for (const side of [-1, 1]) {
const tip = P(0, side * arm.half, arm.z);
for (const along of [-1, 1]) {
L(P(along * h, side * h, arm.z), tip);
L(P(along * h, side * h, arm.z - depth), tip);
}
L(tip, P(0, side * arm.half, arm.z - spec.insulator));
}
}
}
function solidOf(t, spec) {
const r = spec.kind === 'pole' ? spec.radius : spec.baseHalf; // an axis-aligned box that covers the base at any heading
const h = spec.kind === 'pole' ? spec.height : spec.arms[spec.arms.length - 1].z;
return { min: [t.x - r, t.y - r, t.ground], max: [t.x + r, t.y + r, t.ground + h] };
}
// ---- the line --------------------------------------------------------------------------------------------------------
export function buildOverhead(towers, opts = {}) {
const step = opts.step > 0 ? opts.step : STEP;
const seg = [], solids = [], clearances = [], hangs = [];
towers.forEach((t, k) => {
const spec = specOf(t), d = directionAt(towers, k), p = [d[1], -d[0]]; // p points to the right of travel
drawTower(seg, t, spec, d, p);
solids.push(solidOf(t, spec));
hangs.push(attachments(t, spec, d, p));
});
for (let k = 0; k + 1 < towers.length; k++) {
const A = towers[k], B = towers[k + 1];
const groundAt = typeof opts.groundAt === 'function' ? opts.groundAt : (x, y) => {
const L = Math.hypot(B.x - A.x, B.y - A.y) || 1, f = ((x - A.x) * (B.x - A.x) + (y - A.y) * (B.y - A.y)) / (L * L);
return A.ground + (B.ground - A.ground) * Math.min(1, Math.max(0, f));
};
const required = Math.max(MIN_CLEARANCE[A.type || DEFAULT_TYPE], MIN_CLEARANCE[B.type || DEFAULT_TYPE]);
let best = { span: k, from: A.id, to: B.id, minClearance: Infinity, at: null, conductor: -1, required };
const n = Math.min(hangs[k].length, hangs[k + 1].length);
for (let j = 0; j < n; j++) {
const a0 = hangs[k][j], b0 = hangs[k + 1][j];
const L = Math.hypot(b0[0] - a0[0], b0[1] - a0[1]);
if (!(L > 0)) continue;
const a = opts.tensionPerWeight > 0 ? opts.tensionPerWeight : paramFromSag(L, opts.sagRatio > 0 ? opts.sagRatio : SAG_TO_SPAN);
const c = catenarySpan(L, a0[2], b0[2], a);
const xy = (s) => [a0[0] + (b0[0] - a0[0]) * s / L, a0[1] + (b0[1] - a0[1]) * s / L];
const m = Math.max(1, Math.ceil(L / step - 1e-9)); // samples no more than `step` apart
let prev = [a0[0], a0[1], a0[2]];
for (let i = 1; i <= m; i++) {
const s = L * i / m, [x, y] = xy(s), cur = [x, y, i === m ? b0[2] : c.z(s)];
seg.push(prev[0], prev[1], prev[2], cur[0], cur[1], cur[2]);
prev = cur;
}
const mc = Math.max(1, Math.ceil(L / CLEAR_STEP)), check = (s) => {
const [x, y] = xy(s), z = c.z(s), gap = z - groundAt(x, y);
if (gap < best.minClearance) best = { ...best, minClearance: gap, at: [x, y, z], conductor: j };
};
for (let i = 0; i <= mc; i++) check(L * i / mc);
check(c.sMin); // the exact lowest point of the wire
}
clearances.push(best);
}
return { lines: new Float32Array(seg), solids, clearances };
}