In this section
- Accuracy geodesy · globalgrid2050 / solar-design-studio/202609271853-site-world/world/accuracy.mjs lines 1–146
- Binoculars Lens geodesy · globalgrid2050 / solar-design-studio/202609271853-site-world/world/binoculars-lens.mjs lines 1–182
- Binoculars Mount render · globalgrid2050 / solar-design-studio/202609271853-site-world/world/binoculars-mount.mjs lines 1–148
- Bs7671 Checks transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/bs7671-checks.mjs lines 1–39
- Buggy Mount render · globalgrid2050 / solar-design-studio/202609271853-site-world/world/buggy-mount.mjs lines 1–60
Accuracy
A JavaScript module in the world folder of GlobalGrid2050 that works with 66kV, 33kV, 220kV and 275kV, using Helmert and OSTN15.
geodesyglobalgrid2050 / solar-design-studio/202609271853-site-world/world/accuracy.mjs · lines 1–146 of 146 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern curvatureDrop (shared by 2 files)
- What it does
- It calculates 66kV, 33kV, 220kV and 275kV. Defines 13 functions or classes, including haversineM, chordToArcM, pointToSegment, nearestOnPolyline, lineOf.
- 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. Domain terms in the code: 66kV, 33kV, 220kV, 275kV, 400kV, 132kV.
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 400kV, 275kV, 220kV, 132kV, 66kV, 33kV.
- Downstream impact
- Used directly by 1 file: First Showing (globalgrid2050).
- What it achieves
- It is built from the haversine m helper (`haversineM`), the chord to arc m helper (`chordToArcM`) and the point to segment helper (`pointToSegment`). The world's accuracy constants and the small pure maths that uses them. Its code works with 33 kV, 66 kV and 132 kV.
- Why it matters
- Imported by First Showing.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- none found
- Used by
- imported by First Showing (import)
- Produces
- EARTH_RADIUS_M, EARTH_RADIUS_NAME, haversineM, chordToArcM, pointToSegment, nearestOnPolyline, nearestLine, REFRACTION_K, REFRACTION_NOTE, CURVATURE_PER_M2, curvatureDrop, horizonDistanceM
- Defines here
- haversineM, chordToArcM, pointToSegment, nearestOnPolyline, lineOf, nearestLine, curvatureDrop, horizonDistanceM, styleClass, hexToRgb, decimalsFor, formatAtAccuracy, groundWords
- 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/accuracy.mjs:1-146 · blob 04151d296d55f4ba77c83bb874765bce967a06da · 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
// accuracy.mjs: the world's accuracy constants and the small pure maths that uses them. No imports, no DOM.
// From the accuracy study (quick wins 1-5): one earth radius; distance to a line, not to a vertex; earth curvature and
// refraction for far ground; one voltage style contract shared with GridAtlas; display precision no finer than the
// stated accuracy of the source. Layers that run from a blob URL (layers/grid.mjs, layers/national.mjs) cannot import
// this file; they carry copies of the style table and tests/accuracy.test.mjs holds the copies equal to this one.
// ---- 1. One earth radius -----------------------------------------------------------------------------------------
// The WGS84 semi-major axis (NIMA TR8350.2), which is the estate's default sphere R_ATLAS (ventus-grid-engine
// engine/geo-core.js; grid-distance-maths docs/EARTH-MODEL.md). Every great-circle or chord distance in the world and
// its tools uses this one value, so a distance here matches GridAtlas exactly. Do not "correct" it to the IUGG mean
// radius 6,371,008.8 m: at GB latitudes that doubles the error (about -2,194 ppm against about -1,078 ppm).
export const EARTH_RADIUS_M = 6378137;
export const EARTH_RADIUS_NAME = 'R_ATLAS, the WGS84 semi-major axis (6,378,137 m)';
const RAD = Math.PI / 180;
/** Great-circle distance in metres between two lon/lat points (degrees, GeoJSON order) on the named sphere. */
export function haversineM(lon1, lat1, lon2, lat2, R = EARTH_RADIUS_M) {
const p1 = lat1 * RAD, p2 = lat2 * RAD, dp = p2 - p1, dl = (lon2 - lon1) * RAD;
const h = Math.sin(dp / 2) ** 2 + Math.cos(p1) * Math.cos(p2) * Math.sin(dl / 2) ** 2;
return 2 * R * Math.atan2(Math.sqrt(Math.min(1, Math.max(0, h))), Math.sqrt(Math.min(1, Math.max(0, 1 - h))));
}
/** Arc length in metres for a straight chord between two unit vectors (the GPU form of the same distance). */
export const chordToArcM = (chord, R = EARTH_RADIUS_M) => 2 * R * Math.asin(Math.min(1, Math.max(0, chord / 2)));
// ---- 2. Distance to a line, not to a vertex ------------------------------------------------------------------------
// Plan (horizontal) metres on the national grid. Measuring to the nearest tower overstates the distance to the line by
// about 130 m on average (up to 560 m) in the Atlas study; the nearest point on a span is the true answer.
/** The nearest point on segment a-b to p: { d, k (0..1 along the segment), x, y }. A zero-length segment is its end. */
export function pointToSegment(px, py, ax, ay, bx, by) {
const dx = bx - ax, dy = by - ay, L2 = dx * dx + dy * dy;
const k = L2 > 0 ? Math.min(1, Math.max(0, ((px - ax) * dx + (py - ay) * dy) / L2)) : 0;
const x = ax + k * dx, y = ay + k * dy;
return { d: Math.hypot(px - x, py - y), k, x, y };
}
/** Nearest point of a polyline [[e, n], ...] to [e, n]: { d, seg, foot: [e, n], vertexD }, or null with no point. */
export function nearestOnPolyline([pe, pn], pts) {
const P = (pts || []).filter(q => Array.isArray(q) && Number.isFinite(q[0]) && Number.isFinite(q[1]));
if (!P.length || !Number.isFinite(pe) || !Number.isFinite(pn)) return null;
let best = null, vertexD = Infinity;
for (const q of P) vertexD = Math.min(vertexD, Math.hypot(q[0] - pe, q[1] - pn));
const segs = P.length > 1 ? P.length - 1 : 1;
for (let i = 0; i < segs; i++) {
const a = P[i], b = P[Math.min(i + 1, P.length - 1)], s = pointToSegment(pe, pn, a[0], a[1], b[0], b[1]);
if (!best || s.d < best.d) best = { d: s.d, seg: i, foot: [s.x, s.y] };
}
return { ...best, vertexD };
}
// The line a tower belongs to: its `line` field, else the "L<i>" prefix of the grid layer's tower ids ("L3T12").
const lineOf = t => (t.line != null ? String(t.line) : (/^(L\d+)T\d+$/.exec(String(t.id || '')) || [])[1] || null);
/**
* The nearest overhead line to at = { e, n } from towers [{ kind?, e, n, kv?, id | line }] in order along each line:
* { d, vertexD, foot: [e, n], kv, label, line } measured to the nearest span, or null when no tower is known.
* Towers with no line id stand alone (distance to the tower itself).
*/
export function nearestLine(at, towers) {
const lines = new Map();
(towers || []).forEach((t, i) => {
if (!t || (t.kind && t.kind !== 'tower') || !Number.isFinite(t.e) || !Number.isFinite(t.n)) return;
const key = lineOf(t) ?? `solo${i}`;
if (!lines.has(key)) lines.set(key, { kv: t.kv ?? null, pts: [] });
lines.get(key).pts.push([t.e, t.n]);
});
let best = null;
for (const [line, l] of lines) {
const r = nearestOnPolyline([at?.e, at?.n], l.pts);
if (r && (!best || r.d < best.d)) best = { d: r.d, vertexD: r.vertexD, foot: r.foot, kv: l.kv, line };
}
return best && { ...best, label: Number(best.kv) > 0 ? `${best.kv} kV line` : 'overhead line' };
}
// ---- 3. Earth curvature and refraction for far ground ----------------------------------------------------------------
// Seen from the eye, ground at horizontal distance d sits lower than on a flat earth by (1 - k) d^2 / 2R. k = 0.13 is the
// conventional coefficient of terrestrial refraction used in geodetic levelling and viewshed tools: a convention, not a
// measurement (the real value moves with the weather, and can go negative over warm ground). 6.8 cm at 1 km, 61 cm at 3 km.
export const REFRACTION_K = 0.13;
export const REFRACTION_NOTE = 'k = 0.13, the conventional coefficient of refraction (a convention; weather changes it)';
/** Drop per square metre of horizontal distance: the renderer's uniform. */
export const CURVATURE_PER_M2 = (1 - REFRACTION_K) / (2 * EARTH_RADIUS_M);
/** Apparent drop (m) of ground d metres away, with refraction k. */
export const curvatureDrop = (d, k = REFRACTION_K, R = EARTH_RADIUS_M) => ((1 - k) * d * d) / (2 * R);
/** Distance (m) to the sea-level horizon from an eye h metres up, with refraction k; NaN for a negative height. */
export const horizonDistanceM = (h, k = REFRACTION_K, R = EARTH_RADIUS_M) => (h >= 0 ? Math.sqrt((2 * R * h) / (1 - k)) : NaN);
// ---- 4. Voltage style contract ---------------------------------------------------------------------------------------
// Classes and colours follow GridAtlas (data-gridatlas@8bf88da contracts/202608291015-v8-layer-config.json, group
// "Topology": 400, 275, 220, 132 and 66 kV lines). 220 kV and 66 kV keep their own classes. 33 kV is not an Atlas line
// class: it takes the grids pack's cyan (#00b8d4), so the world and the pack draw one palette. Alpha is the world's quiet scheme on its dark background.
// Tower shapes, clearances and compound sizes still come in four structure classes (400/275/132/33); that collapse is a
// rule of the structure tables (220 draws a 275 kV tower, 66 a 132 kV one), never of the colour or the label.
export const VOLTAGE_STYLE = Object.freeze([
{ cls: '400kV', minKv: 345, hex: '#0054ff', alpha: 0.62, source: 'GridAtlas' },
{ cls: '275kV', minKv: 250, hex: '#ff0000', alpha: 0.55, source: 'GridAtlas' },
{ cls: '220kV', minKv: 200, hex: '#ff9900', alpha: 0.52, source: 'GridAtlas' },
{ cls: '132kV', minKv: 100, hex: '#00cc00', alpha: 0.5, source: 'GridAtlas' },
{ cls: '66kV', minKv: 50, hex: '#b200ff', alpha: 0.48, source: 'GridAtlas' },
{ cls: '33kV', minKv: 0, hex: '#00b8d4', alpha: 0.45, source: 'grids pack cyan (no Atlas line class)' }
]);
/** The style class of a nominal kV; unknown or non-positive voltages are the lowest class. */
export function styleClass(kv) {
const v = Number(kv);
if (!(v > 0)) return '33kV';
return VOLTAGE_STYLE.find(s => v >= s.minKv).cls;
}
export const hexToRgb = h => [1, 3, 5].map(i => Math.round((parseInt(h.slice(i, i + 2), 16) / 255) * 1000) / 1000);
/** { cls: [r, g, b, a] } for the renderer. */
export const STYLE_COLORS = Object.freeze(Object.fromEntries(VOLTAGE_STYLE.map(s => [s.cls, [...hexToRgb(s.hex), s.alpha]])));
// ---- 5. Precision to the accuracy of the source ------------------------------------------------------------------------
// A number is shown no finer than the stated accuracy of where it came from. Accuracies are as the providers state them.
export const SOURCE_ACCURACY = Object.freeze({
terrain: { m: 0.15, basis: 'Environment Agency LIDAR DTM 1 m: stated vertical accuracy about 15 cm RMSE' },
'terrain-live': { m: 0.15, basis: 'Environment Agency LIDAR DTM 1 m (live service): stated vertical accuracy about 15 cm RMSE' },
coarse: { m: 4, basis: 'Copernicus DEM GLO-30: stated absolute vertical accuracy under 4 m (90 % linear error)' },
'bng-helmert': { m: 3.5, basis: 'national grid by the 7-parameter transform without the shift grid: about 3.5 m' },
ostn15: { m: 0.1, basis: 'national grid by the OSTN15 shift grid: about 0.1 m' }
});
/** Decimal places for a stated accuracy (m): the digit of the accuracy's own order. 0.15 -> 1, 3.5 -> 0, 30 -> -1. */
export function decimalsFor(accuracyM) {
const a = Number(accuracyM);
if (!(a > 0) || !Number.isFinite(a)) return null; // no stated accuracy: no digits can be justified
return Math.ceil(-Math.log10(a) - 1e-9) + 0; // + 0: no -0
}
/** value rounded to the accuracy, as text: "12.3", "12", "1,230"; "n/a" for a non-number or no stated accuracy. */
export function formatAtAccuracy(value, accuracyM) {
const dp = decimalsFor(accuracyM), v = Number(value);
if (dp === null || value === null || value === '' || !Number.isFinite(v)) return 'n/a';
if (dp >= 0) { const s = v.toFixed(dp); return /^-0(\.0*)?$/.test(s) ? s.slice(1) : s; }
const q = 10 ** -dp, r = Math.round(v / q) * q;
return (r === 0 ? 0 : r).toLocaleString('en-GB');
}
/** The ground height and eye height words for the Controls detail line, rounded to the ground source's accuracy. */
export function groundWords(source, groundM, eyeM, known) {
const acc = known ? SOURCE_ACCURACY[source]?.m : null;
const eye = acc ? formatAtAccuracy(eyeM, acc) : formatAtAccuracy(eyeM, 1);
const horizon = horizonDistanceM(eyeM); // over ground as level as the spot underfoot: hills bring it nearer
return `eye ${eye} m above the ground${acc ? ` · ground ${formatAtAccuracy(groundM, acc)} m above sea level (±${acc} m stated)` : ''}`
+ (eyeM > 0 && Number.isFinite(horizon) ? ` · level-ground horizon ${formatAtAccuracy(horizon / 1000, 0.1)} km (${REFRACTION_NOTE})` : '');
}Binoculars Lens
A JavaScript module in the world folder of GlobalGrid2050 that works with substations, motorways, solar and LiDAR terrain.
geodesyglobalgrid2050 / solar-design-studio/202609271853-site-world/world/binoculars-lens.mjs · lines 1–182 of 182 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern curvatureDrop (shared by 2 files)
- What it does
- It calculates substations, motorways, solar and LiDAR terrain. Defines 17 functions or classes, including fovFor, stepZoom, curvatureDrop, convergence, bearingDeg.
- 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. Domain terms in the code: substations, motorways, solar, LiDAR terrain, 400kV, 275kV.
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid). Voltage levels named: 400kV, 275kV, 132kV, 33kV.
- Downstream impact
- Used directly by 1 file: Binoculars Mount (globalgrid2050).
- What it achieves
- It is built from the fov for helper (`fovFor`), the step zoom helper (`stepZoom`) and the curvature drop helper (`curvatureDrop`). Binoculars, the lens: magnification and field of view, the rangefinder under the reticle, and what it reads in words. Its code works with 132 kV, 275 kV and 33 kV.
- Why it matters
- Imported by Binoculars Mount.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- Camera (import), Bng (import)
- Used by
- imported by Binoculars Mount (import)
- Produces
- STEPS, BASE_FOV, EARTH_R, SKY_AOD_M, MAX_RANGE_M, GAP_M, fovFor, stepZoom, curvatureDrop, convergence, bearingDeg, rangeAlong
- Defines here
- fovFor, stepZoom, curvatureDrop, convergence, bearingDeg, rangeAlong, at, above, kindOfKey, rayToSegment, thingOnRay, drapeAt, labelFor, reading, deg, distanceText, readingLines
- 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/binoculars-lens.mjs:1-182 · blob 00ba949292f18004164af79c05a0e17660b109ed · 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
// Binoculars, the lens: magnification and field of view, the rangefinder under the reticle, and what it reads in words.
// Named as in Ventusltd/binoculars: a lens (this file, /src/lenses) and a mount (binoculars-mount.mjs, /src/mounts).
// Pure: no DOM, no WebGL. The mount (binoculars-mount.mjs) steadies the look, adds the horizon profile and draws the page.
// Local east (x), north (y), up (z) metres from the site origin; heights are metres above Ordnance Datum Newlyn (the
// terrain layers' own datum). Grid north is +y. The camera is camera.mjs's: yaw 0 north, +π/2 east, pitch up +.
//
// What the rangefinder rests on (nothing is guessed):
// ground: measuredAt(x, y), the measured LiDAR tiles (1 m, and the far ring's 8 and 16 m tiles); NaN = not measured.
// Past measured ground the reading is "beyond measured ground", never an extrapolated hill.
// Earth curvature with standard refraction: drop = d²(1 − k) / 2R, R 6,371 km, k 0.13 (ASSUMED coefficient; the real
// one varies with the air). It matters past a few kilometres: 1.7 m at 5 km, 6.8 m at 10 km.
// Things: the lines drawn in the last frame (grid, national, water, roads, design tables), matched by batch key.
import { direction } from './camera.mjs';
import { tmInverse } from './bng.mjs';
export const STEPS = Object.freeze([7, 10]); // magnification steps (×)
export const BASE_FOV = 70 * Math.PI / 180; // the world's own vertical field of view (substrate.mjs)
export const EARTH_R = 6371000, REFRACTION_K = 0.13;
export const SKY_AOD_M = 1400; // above any ground in Great Britain (Ben Nevis 1,345 m)
export const MAX_RANGE_M = 40000;
export const GAP_M = 60; // a LiDAR void (water, a missing tile) shorter than this is crossed
// The narrow field of view for magnification m: the same scene m times larger in the middle of the screen.
export const fovFor = (m, base = BASE_FOV) => 2 * Math.atan(Math.tan(base / 2) / Math.max(1, m));
// The next step up or down (wheel, pinch, typed zoom).
export function stepZoom(m, dir) {
const i = STEPS.indexOf(m);
if (i < 0) return STEPS[0];
return STEPS[Math.max(0, Math.min(STEPS.length - 1, i + Math.sign(dir)))];
}
export const curvatureDrop = (d, k = REFRACTION_K, R = EARTH_R) => (d * d * (1 - k)) / (2 * R);
// Grid convergence at national grid (e, n), radians: true bearing = grid bearing + γ. Transverse Mercator,
// γ = atan(tan Δλ · sin φ) on the Airy latitude (to about 0.001° over Great Britain); central meridian 2° W.
export function convergence(e, n) {
const { lat, lon } = tmInverse(e, n), dl = lon + 2 * Math.PI / 180;
return Math.atan(Math.tan(dl) * Math.sin(lat));
}
export const bearingDeg = yaw => ((yaw * 180 / Math.PI) % 360 + 360) % 360;
// March a ray from eye along dir against measured ground. Returns
// { kind: 'ground', d, point, horizontal } | { kind: 'beyond', d (last measured), reached } | { kind: 'sky', d }
export function rangeAlong(eye, dir, measuredAt, { maxM = MAX_RANGE_M, k = REFRACTION_K } = {}) {
const hz = Math.hypot(dir[0], dir[1]);
const at = d => [eye[0] + dir[0] * d, eye[1] + dir[1] * d, eye[2] + dir[2] * d];
// How far the ray is above the ground at d (positive = above), NaN where the ground is not measured.
const above = d => { const p = at(d), g = measuredAt(p[0], p[1]); return Number.isFinite(g) ? p[2] - (g - curvatureDrop(d * hz, k)) : NaN; };
let d = 0.3, prev = null, lastMeasured = null, gapFrom = null;
while (d <= maxM) {
const a = above(d);
if (Number.isFinite(a)) {
gapFrom = null;
if (a <= 0) {
let lo = prev ?? 0, hi = d; // bisect to 1 cm or better
for (let i = 0; i < 24 && hi - lo > 0.01; i++) { const m = (lo + hi) / 2, am = above(m); if (Number.isFinite(am) && am <= 0) hi = m; else lo = m; }
return { kind: 'ground', d: hi, point: at(hi), horizontal: hi * hz };
}
prev = d; lastMeasured = d;
} else {
if (gapFrom === null) gapFrom = d;
if (d - gapFrom > GAP_M) return { kind: 'beyond', d: lastMeasured, reached: gapFrom };
}
if (dir[2] > 0 && at(d)[2] > SKY_AOD_M) return { kind: 'sky', d };
d += Math.min(25, 0.25 + d * 0.004);
}
return { kind: 'beyond', d: lastMeasured, reached: maxM };
}
// What kind of thing a drawn batch is, by its key; null for ground drapes that describe the ground itself.
export function kindOfKey(key) {
if (/^grid\/substation\/|^national\/[^/]+\/sub\//.test(key)) return 'substation';
if (/^grid\/line\/|^national\/[^/]+\/power\//.test(key)) return 'line';
if (/^(plant|block):T/.test(key) || /^module-/.test(key)) return 'table';
if (/^water\/line\//.test(key)) return 'water';
if (/^national\/[^/]+\/rail$/.test(key) || /\/rail$/.test(key)) return 'railway';
if (/^ways\/|^national\/[^/]+\/roads\//.test(key)) return 'road';
if (/^canopy\/(tree|hedge)/.test(key)) return 'hedge or tree';
return null;
}
const STANDING = new Set(['substation', 'line', 'table', 'hedge or tree']);
const DRAPED = { water: 3, road: 4, railway: 3 }; // metres either side of the drawn line that still count as on it
// Closest approach of the ray (eye, unit dir) to segment a-b: { t along the ray, miss metres }.
function rayToSegment(eye, dir, a, b) {
const u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], w = [eye[0] - a[0], eye[1] - a[1], eye[2] - a[2]];
const A = 1, B = dir[0] * u[0] + dir[1] * u[1] + dir[2] * u[2], C = u[0] * u[0] + u[1] * u[1] + u[2] * u[2];
const D = dir[0] * w[0] + dir[1] * w[1] + dir[2] * w[2], E = u[0] * w[0] + u[1] * w[1] + u[2] * w[2];
const den = A * C - B * B;
let s = den > 1e-12 ? (A * E - B * D) / den : 0; s = Math.max(0, Math.min(1, s));
const t = Math.max(0, B * s - D);
const p = [eye[0] + dir[0] * t, eye[1] + dir[1] * t, eye[2] + dir[2] * t], q = [a[0] + u[0] * s, a[1] + u[1] * s, a[2] + u[2] * s];
return { t, miss: Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]), q };
}
// The nearest drawn thing standing in the reticle before maxD: { kind, key, t, point, color } or null.
// tol: radians either side of the centre that still count (a couple of screen pixels at the current zoom).
export function thingOnRay(batches, eye, dir, maxD, tol, { budget = 400000 } = {}) {
let best = null, seen = 0;
for (const b of batches) {
const kind = b && !b.occluder && b.positions && kindOfKey(String(b.key || ''));
if (!kind || !STANDING.has(kind)) continue;
const o = b.origin || [0, 0, 0], P = b.positions;
for (let i = 0; i + 5 < P.length && seen < budget; i += 6, seen++) {
const a = [P[i] + o[0], P[i + 1] + o[1], P[i + 2] + o[2]], c = [P[i + 3] + o[0], P[i + 4] + o[1], P[i + 5] + o[2]];
const r = rayToSegment(eye, dir, a, c);
if (r.t < 1 || r.t > maxD || r.miss > Math.max(0.3, r.t * tol)) continue;
if (!best || r.t < best.t) best = { kind, key: b.key, t: r.t, point: r.q, color: b.color, vertical: Math.abs(c[2] - a[2]) };
}
}
return best;
}
// Which draped thing (water, road, railway) lies under a ground point, by plan distance to the drawn lines.
export function drapeAt(batches, p) {
let best = null;
for (const b of batches) {
const kind = b && !b.occluder && b.positions && kindOfKey(String(b.key || ''));
if (!kind || !(kind in DRAPED)) continue;
const o = b.origin || [0, 0, 0], P = b.positions, x = p[0] - o[0], y = p[1] - o[1], r = DRAPED[kind];
for (let i = 0; i + 5 < P.length; i += 6) {
const ax = P[i], ay = P[i + 1], bx = P[i + 3], by = P[i + 4];
if (Math.max(ax, bx) < x - r || Math.min(ax, bx) > x + r || Math.max(ay, by) < y - r || Math.min(ay, by) > y + r) continue;
const dx = bx - ax, dy = by - ay, L = dx * dx + dy * dy, s = L > 0 ? Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / L)) : 0;
const m = Math.hypot(ax + dx * s - x, ay + dy * s - y);
if (m <= r && (!best || m < best.m)) best = { kind, key: b.key, m };
}
}
return best;
}
// A public-infrastructure label only (never a project, owner or person): voltage class for lines and substations,
// road class for roads.
export function labelFor(thing, { lineClass = () => null } = {}) {
if (!thing) return 'ground';
const cls = (/\/(400kV|275kV|132kV|33kV)$/.exec(thing.key) || [])[1] || lineClass(thing.key);
const kv = cls ? ` (${cls.replace('kV', ' kV')})` : '';
if (thing.kind === 'line') return (thing.pylon ? 'pylon' : 'overhead line') + kv;
if (thing.kind === 'substation') return 'substation' + kv;
if (thing.kind === 'table') return 'solar table (design)';
if (thing.kind === 'road') { const c = (/roads\/([^/]+)$/.exec(thing.key) || [])[1]; return c && /^(A|B|motorway)$/.test(c) ? `${c === 'motorway' ? 'motorway' : c + ' road'}` : 'road'; }
if (thing.kind === 'water') return 'water (watercourse)';
return thing.kind;
}
// One full rangefinder reading for a pose: distance, bearings, angle, height and what it is. Pure but for the inputs.
// w: { pos, yaw, pitch, origin: { e, n }, measuredAt, batches, tol, towers: [[x, y]] local, lineClass(key), gpuDistance? }
export function reading(w) {
const dir = direction(w.yaw, w.pitch), eye = w.pos;
const r = rangeAlong(eye, dir, w.measuredAt);
const reach = r.kind === 'ground' ? r.d : r.kind === 'beyond' ? (r.reached ?? MAX_RANGE_M) : MAX_RANGE_M;
let thing = thingOnRay(w.batches || [], eye, dir, reach + 1, w.tol ?? 0.002);
if (thing?.kind === 'line') thing.pylon = (w.towers || []).some(([x, y]) => Math.hypot(thing.point[0] - x, thing.point[1] - y) < 8) || thing.vertical > 3;
const gpu = Number.isFinite(w.gpuDistance) && w.gpuDistance < 1e29 ? w.gpuDistance : null;
let d = null, point = null, source = null;
if (thing) { d = thing.t; point = thing.point; source = 'drawn line'; }
else if (r.kind === 'ground') {
d = r.d; point = r.point; source = 'terrain tiles';
if (gpu !== null && Math.abs(gpu - r.d) < Math.max(5, r.d * 0.02)) { d = gpu; source = 'GPU ray cast (WebGL2), tiles agree'; }
else if (gpu !== null) source = `terrain tiles (GPU ray cast says ${Math.round(gpu)} m)`;
const drape = drapeAt(w.batches || [], point);
if (drape) thing = drape;
}
const o = w.origin || { e: 0, n: 0 }, gridB = bearingDeg(w.yaw);
let gamma = 0;
try { gamma = convergence(o.e + eye[0], o.n + eye[1]) * 180 / Math.PI; } catch { gamma = 0; }
const out = { status: d === null ? r.kind : 'hit', gridBearing: gridB, trueBearing: ((gridB + gamma) % 360 + 360) % 360, convergence: gamma,
angle: w.pitch * 180 / Math.PI, what: d === null ? null : labelFor(thing, w), distance: d, horizontal: d === null ? null : d * Math.hypot(dir[0], dir[1]),
aod: point ? point[2] : null, point, source, lastMeasured: r.kind === 'beyond' ? r.d : null };
return out;
}
const deg = (v, dp = 1) => `${v.toFixed(dp)}°`;
export const distanceText = d => (d >= 10000 ? `${(d / 1000).toFixed(2)} km` : d >= 1000 ? `${(d / 1000).toFixed(3)} km` : `${d.toFixed(d < 100 ? 1 : 0)} m`);
// The reading in the words the reticle box shows, one line each.
export function readingLines(r) {
const ang = r.angle >= 0 ? `elevation +${deg(r.angle, 2)}` : `depression ${deg(-r.angle, 2)}`;
const bear = `bearing ${deg(r.trueBearing)} true · ${deg(r.gridBearing)} grid`;
if (r.status === 'sky') return ['sky: no ground on this line', bear, ang];
if (r.status !== 'hit') return [`beyond measured ground${r.lastMeasured ? ` (measured to ${distanceText(r.lastMeasured)})` : ''}`, bear, ang];
return [`${r.what} · ${distanceText(r.distance)}`, bear, `${ang} · ${r.aod.toFixed(1)} m AOD`, `from ${r.source}`];
}Binoculars Mount
A JavaScript module in the world folder of GlobalGrid2050 that works with horizon profile (`horizonProfile`) and line class (`lineClass`), calculates planar distances and angles and draws SVG graphics.
renderglobalgrid2050 / solar-design-studio/202609271853-site-world/world/binoculars-mount.mjs · lines 1–148 of 148 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern lineClass (shared by 2 files)
- What it does
- It draws its content. Defines 10 functions or classes, including horizonProfile, horizonText, createBinoculars, towers, lineClass. Side effects: changes the web page (DOM).
- 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.
- Inputs & outputs
- Out: SVG drawing.
- Downstream impact
- Used directly by 1 file: Senses Mount (globalgrid2050).
- What it achieves
- It creates binoculars (`createBinoculars`) and is built from the horizon profile helper (`horizonProfile`) and the horizon text helper (`horizonText`). Binoculars, the mount: holds the lens (`binoculars-lens.mjs`) steady and reads the horizon along the bearing. It responds to wheel, pointerdown and pointermove events.
- Why it matters
- Imported by Senses Mount.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- Binoculars Lens (import)
- Used by
- imported by Senses Mount (dynamic import)
- Produces
- horizonProfile, horizonText, createBinoculars
- Defines here
- horizonProfile, horizonText, createBinoculars, towers, lineClass, gpuDistance, probe, measure, zoom, set
- 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/binoculars-mount.mjs:1-148 · blob aedc4a731e24bed5a589bce587d7563a10819f0f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Binoculars, the mount: holds the lens (binoculars-lens.mjs) steady and reads the horizon along the bearing.
// Loaded the first time the binoculars are switched on (senses-mount.mjs). While on: the view narrows to 7× or 10×
// (wheel or pinch to step), the look is steadied by the same factor (substrate.mjs divides every look by the
// magnification), a soft circular vignette frames the view and the reticle reads what lies under the centre.
// Horizon profile: along the bearing, the measured ground that makes the skyline (the highest angle seen from the eye,
// Earth curvature and standard refraction included). Its distance comes from the WebGL2 ray cast where "Solid ground
// (GPU)" is on (raycast.mjs, near 2 m and far 8 m grids; the lines stay WebGL1), else from the terrain tiles.
// Nothing is drawn by the mount itself: readings are worked out after frames the world already draws, and once more
// when the view comes to rest, so a still view stays at 0 fps.
import { STEPS, fovFor, stepZoom, curvatureDrop, reading, readingLines, distanceText, GAP_M, REFRACTION_K, MAX_RANGE_M } from './binoculars-lens.mjs';
// Pure: the skyline along grid bearing yaw from eye over measured ground. Returns
// { skyline: { d, angle (deg), aod, point } | null, end: { d, reason: 'beyond' | 'range' }, open: skyline may lie further }.
export function horizonProfile(eye, yaw, measuredAt, { maxM = MAX_RANGE_M, k = REFRACTION_K } = {}) {
const sx = Math.sin(yaw), sy = Math.cos(yaw);
let d = 2, best = null, last = null, gapFrom = null, reason = 'range';
while (d <= maxM) {
const x = eye[0] + sx * d, y = eye[1] + sy * d, g = measuredAt(x, y);
if (Number.isFinite(g)) {
gapFrom = null; last = d;
const z = g - curvatureDrop(d, k), a = Math.atan2(z - eye[2], d);
if (!best || a > best.a) best = { d, a, aod: g, point: [x, y, z] };
} else {
if (gapFrom === null) gapFrom = d;
if (d - gapFrom > GAP_M) { reason = 'beyond'; break; }
}
d += Math.min(20, 1 + d * 0.005);
}
if (!best) return { skyline: null, end: { d: last ?? 0, reason }, open: true };
const endD = last ?? best.d;
const open = reason === 'beyond' && best.d >= endD - Math.max(200, 0.05 * endD);
return { skyline: { d: best.d, angle: best.a * 180 / Math.PI, aod: best.aod, point: best.point }, end: { d: endD, reason }, open };
}
export function horizonText(h, gpu = null) {
if (!h.skyline) return 'Horizon: beyond measured ground along this bearing.';
const s = h.skyline, where = gpu ? `${distanceText(gpu)} (GPU ray cast)` : `${distanceText(s.d)} (terrain tiles)`;
if (h.open) return `Horizon: beyond measured ground; the highest measured ground is ${where}, ${s.aod.toFixed(0)} m AOD`;
return `Horizon: ${where}, ${s.aod.toFixed(0)} m AOD, ${s.angle >= 0 ? '+' : ''}${s.angle.toFixed(2)}°`;
}
const CSS = `
#bino { position: fixed; inset: 0; pointer-events: none; }
#bino[hidden] { display: none; }
#bino .vig { position: absolute; inset: 0; background: radial-gradient(circle at 50% 50%, transparent 0, transparent 40vmin,
rgba(0, 0, 0, 0.22) 48vmin, rgba(0, 0, 0, 0.55) 62vmin, rgba(0, 0, 0, 0.78) 85vmin); }
#bino svg { position: absolute; left: 50%; top: 50%; width: 120px; height: 120px; transform: translate(-50%, -50%); overflow: visible; }
#bino svg * { stroke: var(--line); stroke-width: 1; fill: none; vector-effect: non-scaling-stroke; }
#bino .box { position: absolute; left: 50%; bottom: calc(var(--foot) + 12px); transform: translateX(-50%); width: min(440px, calc(100vw - 32px));
box-sizing: border-box; padding: 6px 10px; background: var(--panel); border: 1px solid var(--edge); border-radius: 6px; color: var(--text);
font-variant-numeric: tabular-nums; font-size: 12px; line-height: 1.5; }
#bino .box div:first-child { color: #fff; } #bino .box .dim { color: var(--dim); }
#bino .mag { position: absolute; left: calc(50% + 66px); top: calc(50% - 76px); color: var(--dim); font-size: 11px; }
@media (pointer: coarse) { #bino .box { bottom: auto; top: calc(var(--btn) + 40px); } }`;
const RETICLE = '<svg viewBox="-60 -60 120 120" aria-hidden="true"><circle r="3"/><path d="M-60 0h48M12 0h48M0 -60v48M0 12v48"/>'
+ '<path d="M-36 -3v6M-24 -3v6M24 -3v6M36 -3v6M-3 24h6M-3 36h6"/></svg>';
const EVERY_MS = 100, REST_MS = 180;
// deps: { api (substrate extension api), world (window.world), doc, onChange() when switched }
export function createBinoculars({ api, world, doc = document, onChange = () => {} }) {
let on = false, mag = STEPS[0], last = null, lastAt = -Infinity, rest = null, pinch = null;
const style = doc.createElement('style'); style.textContent = CSS; doc.head.appendChild(style);
const root = doc.createElement('div');
root.id = 'bino'; root.hidden = true;
root.innerHTML = `<div class="vig"></div>${RETICLE}<div class="mag"></div><div class="box" role="status" aria-live="polite"></div>`;
(api.canvas.parentNode ? api.canvas.after(root) : doc.body.appendChild(root)); // behind the dash, panels and credits
const box = root.querySelector('.box'), magEl = root.querySelector('.mag');
// Tower positions (local metres) from the grid and national layers, to tell a pylon from the wire it carries.
function towers() {
const o = api.origin(), out = [];
const model = api.live().find(l => l.id === 'grid')?.layer?.debug?.()?.model;
for (const l of model?.lines || []) for (const t of l.towers || []) out.push([t.e - o.e, t.n - o.n]);
for (const t of api.live().find(l => l.id === 'national')?.layer?.towers?.() || []) out.push([t.e - o.e, t.n - o.n]);
return out;
}
const lineClass = key => {
const i = Number((/^grid\/line\/(\d+)$/.exec(key) || [])[1]);
return Number.isInteger(i) ? api.live().find(l => l.id === 'grid')?.layer?.debug?.()?.model?.lines?.[i]?.cls ?? null : null;
};
// One pixel of the WebGL2 ray cast along (yaw, pitch): metres to measured ground, or null where it is off or finds none.
function gpuDistance(s, yaw, pitch) {
const rc = world.raycastApi?.();
if (!rc?.on?.() || !rc.readData) return null;
try { const px = rc.readData({ eye: s.pos, yaw, pitch, fovy: api.FOV, width: 1, height: 1 }); return px && px[0] < 1e29 ? px[0] : null; }
catch { return null; }
}
// A reading for the current pose, or for pose { pos, yaw, pitch } near it (tests and the console: worldSenses.binoculars().probe()).
function probe(pose = null) {
const s = { ...api.state(), ...(pose || {}) }, c = api.canvas, tol = 3 * api.FOV / Math.max(1, c.clientHeight);
const r = reading({ pos: s.pos, yaw: s.yaw, pitch: s.pitch, origin: api.origin(), measuredAt: api.measuredAt, batches: api.batches(),
tol, towers: towers(), lineClass, gpuDistance: gpuDistance(s, s.yaw, s.pitch) });
const h = horizonProfile(s.pos, s.yaw, api.measuredAt);
const hg = h.skyline && !h.open ? gpuDistance(s, s.yaw, h.skyline.angle * Math.PI / 180 - 1e-4) : null;
const agree = hg !== null && Math.abs(hg - h.skyline.d) <= Math.max(20, 0.03 * h.skyline.d) ? hg : null;
return { ...r, horizon: { ...h, gpu: agree }, mag, at: new Date().toISOString() };
}
function measure() {
last = probe();
const r = last, h = last.horizon, agree = h.gpu;
const lines = [...readingLines(r), horizonText(h, agree)];
box.replaceChildren(...lines.map((t, i) => { const d = doc.createElement('div'); d.textContent = t; if (i >= 3) d.className = 'dim'; return d; }));
magEl.textContent = `${mag}×`;
return last;
}
// After every frame the world draws (throttled), and once when it comes to rest.
api.hooks.after.add(now => {
if (!on) return;
if (now - lastAt >= EVERY_MS) { lastAt = now; measure(); }
clearTimeout(rest); rest = setTimeout(() => { if (on) measure(); }, REST_MS);
});
const view = api.canvas;
view.addEventListener('wheel', e => { if (!on) return; e.preventDefault(); e.stopImmediatePropagation(); zoom(stepZoom(mag, -e.deltaY)); },
{ passive: false, capture: true });
const touches = new Map();
view.addEventListener('pointerdown', e => { if (e.pointerType === 'touch') touches.set(e.pointerId, [e.clientX, e.clientY]); });
view.addEventListener('pointermove', e => {
if (!on || !touches.has(e.pointerId)) return;
touches.set(e.pointerId, [e.clientX, e.clientY]);
if (touches.size !== 2) { pinch = null; return; }
const [a, b] = [...touches.values()], d = Math.hypot(a[0] - b[0], a[1] - b[1]);
if (!pinch) pinch = d; else if (d > pinch * 1.25) { zoom(stepZoom(mag, 1)); pinch = d; } else if (d < pinch / 1.25) { zoom(stepZoom(mag, -1)); pinch = d; }
});
for (const ev of ['pointerup', 'pointercancel']) view.addEventListener(ev, e => { touches.delete(e.pointerId); if (touches.size < 2) pinch = null; });
function zoom(m) {
const next = STEPS.includes(Number(m)) ? Number(m) : null;
if (next === null) throw Error(`the binoculars have ${STEPS.join('× and ')}× steps`);
mag = next; if (on) api.setMagnification(mag);
magEl.textContent = `${mag}×`;
return mag;
}
function set(v) {
on = !!v; root.hidden = !on;
api.setMagnification(on ? mag : 1);
if (on) { measure(); api.redraw(); }
onChange(on);
return on;
}
return {
set, on: () => on, zoom, mag: () => mag, fov: () => fovFor(mag),
// The reading in words: worked out now if the binoculars are up, else the last one taken.
rangeText() { const r = on ? measure() : last; return r ? [...readingLines(r), horizonText(r.horizon, r.horizon.gpu)].join('; ') : 'No reading yet.'; },
lastText: () => (last ? [...readingLines(last), horizonText(last.horizon, last.horizon.gpu)].join('; ') : null),
reading: () => last, probe,
debug: () => ({ on, mag, fovDeg: fovFor(mag) * 180 / Math.PI, reading: last })
};
}Bs7671 Checks
A JavaScript module in the world folder of GlobalGrid2050 that works with cables, using BS 7671.
transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/bs7671-checks.mjs · lines 1–39 of 39 · version 2026-09-27 18:53 · pattern buriedProtection (shared by 3 files)
- What it does
- It calculates cables. Defines buriedOverload, buriedProtection, disconnection.
- 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. Domain terms in the code: cables.
- Downstream impact
- Used directly by 2 files: Earth Photovoltaic (PV) (globalgrid2050); LV DC Sizing (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 buried overload helper (`buriedOverload`), the buried protection helper (`buriedProtection`) and the disconnection step (`disconnection`). Checks on the LV cable engines from a cross-check against the national wiring rules.
- Why it matters
- Imported by Earth Photovoltaic (PV) and LV DC Sizing.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- none found
- Used by
- imported by Earth Photovoltaic (PV) (import), imported by LV DC Sizing (import)
- Produces
- SOIL_SENSITIVITY, BURIED, buriedOverload, buriedProtection, DISCONNECT_S, disconnection
- Defines here
- buriedOverload, buriedProtection, disconnection
- 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/bs7671-checks.mjs:1-39 · blob 14883fb8cb01c646cfbdbc8703e73db195aa9c2c · 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
// bs7671-checks.mjs: checks on the LV cable engines from a cross-check against the national wiring rules. Clauses are
// cited by number only; no table, figure or wording of the rules is held here. Every value below is ours, an input,
// and editable. Illustrative, early design, no warranty: confirm with a qualified engineer.
// ---- overload of buried cables (BS 7671 433.1.203) ----
// The general condition (433.1.1) is kept; for a cable in the ground the check is also made with the soil thermal
// resistivity raised by this factor (our sensitivity margin, not a figure from the rules), because a buried cable's
// rating falls as the ground dries. The verdict at the stated soil and at the raised soil are both reported.
export const SOIL_SENSITIVITY = 1.25;
export const BURIED = new Set(['buried', 'ducts', 'direct', 'duct']);
/** buriedOverload({ In, izAt(soilKmW), soilKmW, factor }) -> { name, ok, value, limit, soilKmW } (value In, limit Iz there). */
export function buriedOverload({ In, izAt, soilKmW, factor = SOIL_SENSITIVITY }) {
const soil = soilKmW * factor, Iz = izAt(soil);
return { name: `buried cable: In <= Iz at soil +${Math.round((factor - 1) * 100)} % (BS 7671 433.1.203)`, ok: In <= Iz + 1e-9,
value: In, limit: Iz, soilKmW: soil };
}
// ---- protection of buried LV and DC cable (BS 7671 522.8.10) ----
/** buriedProtection({ armoured, ducted, kind }) -> a check: a cable in the ground needs an earthed armour or metal sheath,
* or a duct giving like protection. Unarmoured cable laid direct fails. */
export function buriedProtection({ armoured = false, ducted = false, kind = 'LV' } = {}) {
const ok = !!armoured || !!ducted;
return { name: `${kind} cable in the ground: armoured and earthed, or in a duct (BS 7671 522.8.10)`, ok,
value: armoured ? 'armoured' : ducted ? 'ducted' : 'unarmoured, laid direct', limit: 'armour or duct' };
}
// ---- disconnection time by circuit type (BS 7671 411.3.2) ----
// Distribution circuits (411.3.2.3) are allowed longer than small final circuits (411.3.2.2). The times are inputs:
// the distribution time follows 411.3.2.3; the final-circuit time is an input to set from 411.3.2.2 for the circuit.
export const DISCONNECT_S = Object.freeze({ distribution: 5, final: 0.4 });
/** disconnection(p) -> { circuit, permittedS, ia, fastIa }: Ia is the device's current at the permitted time (from its curve,
* as a multiple of In: p.iaMultipleAtPermitted, assumed); fastIa is its instantaneous pick-up (p.tripMultiple). */
export function disconnection(p) {
const circuit = p.circuit === 'final' ? 'final' : 'distribution', permittedS = p.permittedS ?? DISCONNECT_S[circuit];
const mult = circuit === 'final' ? p.tripMultiple : (p.iaMultipleAtPermitted ?? p.tripMultiple);
return { circuit, permittedS, ia: p.inA * mult, fastIa: p.inA * p.tripMultiple };
}Buggy Mount
A JavaScript module in the world folder of GlobalGrid2050. It parses buggy (`parseBuggy`) and is built from the typing step (`typing`) and the mount buggy helper (`mountBuggy`).
renderglobalgrid2050 / solar-design-studio/202609271853-site-world/world/buggy-mount.mjs · lines 1–60 of 60 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern typing (shared by 7 files)
- What it does
- It draws its content. Defines parseBuggy, typing, mountBuggy, load. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'buggy'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- What it achieves
- Buggy mode's only part that loads with the world (just after the first frame): the E key, a small mount chip (not a dash button: the dash keeps its five), and the typed "buggy" commands. It responds to click and keydown events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- Buggy UI (dynamic import)
- Used by
- none found
- Produces
- LIMITS, parseBuggy, mountBuggy
- Defines here
- parseBuggy, typing, mountBuggy, load
- 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/buggy-mount.mjs:1-60 · blob 09871fe971c2443db4b8c09990b92ffde1e179e6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
// buggy-mount.mjs: Buggy mode's only part that loads with the world (just after the first frame): the E key, a small
// mount chip (not a dash button: the dash keeps its five), and the typed "buggy" commands. The driving itself
// (buggy-ui.mjs and buggy-physics.mjs) loads the first time any of them is used.
// buggy on | off · buggy speed 15 (km/h, 1 to 25) · buggy grip 0.4 (0.1 to 1) · buggy ground grass|wet|gravel · buggy seat|chase
export const LIMITS = Object.freeze({ speed: { min: 1, max: 25, unit: 'km/h', label: 'top speed' },
grip: { min: 0.1, max: 1, unit: '', label: 'grip (friction coefficient)' } });
const WORDS = ['on', 'off', 'seat', 'chase', 'grass', 'wet', 'gravel'];
const USAGE = 'buggy on|off · buggy speed 15 · buggy grip 0.4 · buggy ground grass|wet|gravel · buggy seat|chase';
// A typed line to a buggy command: null when the line is not about the buggy; { ok: false, why } refuses it in words,
// never clamps; { ok: true, act, value } otherwise.
export function parseBuggy(line) {
const t = String(line ?? '').trim().toLowerCase().split(/\s+/).filter(Boolean);
if (t[0] !== 'buggy') return null;
const [, a, b, extra] = t, no = why => ({ ok: false, why: `${why} (${USAGE}). Nothing was changed.` });
if (!a) return { ok: true, act: 'toggle' };
if (extra !== undefined) return no(`buggy does not read "${extra}"`);
if (a === 'speed' || a === 'grip') {
const L = LIMITS[a], v = Number(String(b ?? '').replace(/km\/?h$/, ''));
if (b === undefined || !Number.isFinite(v)) return no(`buggy ${a} needs a number`);
if (v < L.min || v > L.max) return no(`${L.label} must be a number from ${L.min} to ${L.max}${L.unit ? ' ' + L.unit : ''}; you typed ${b}`);
return { ok: true, act: a, value: v };
}
if (a === 'ground' && ['grass', 'wet', 'gravel'].includes(b)) return { ok: true, act: 'ground', value: b };
if (b === undefined && WORDS.includes(a)) return ['grass', 'wet', 'gravel'].includes(a) ? { ok: true, act: 'ground', value: a } : { ok: true, act: a };
return no(`buggy does not read "${b ?? a}"`);
}
const typing = t => t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement || t instanceof HTMLSelectElement || t?.isContentEditable;
const CSS = `#buggy-chip { position: fixed; left: 10px; bottom: calc(var(--foot) + 30px); min-height: 26px; padding: 0 9px; border-radius: 13px;
background: var(--panel); color: var(--dim); border: 1px solid var(--edge); cursor: pointer; font: inherit; font-size: 11px; }
#buggy-chip[aria-pressed="true"] { color: #ffc773; border-color: #ffc773; }
body[data-panel="design"] #buggy-chip { display: none; }
@media (pointer: coarse) { #buggy-chip { left: 156px; bottom: calc(var(--foot) + 36px); min-height: 40px; padding: 0 12px; } } /* beside the joypad */`;
// deps: { api (the substrate's extension api: state, setDriver, hooks.commands), doc }
export function mountBuggy({ api, doc = document }) {
let ui = null, loading = null;
const style = doc.createElement('style'); style.textContent = CSS; doc.head.append(style);
const chip = doc.createElement('button');
chip.type = 'button'; chip.id = 'buggy-chip'; chip.textContent = 'Buggy'; chip.setAttribute('aria-pressed', 'false');
chip.title = 'Get on the site buggy and drive the ground (E on a keyboard)';
doc.body.append(chip);
const load = () => (loading ||= import('./buggy-ui.mjs').then(m => (ui = m.createDriver({ api, doc, chip })))
.catch(e => { loading = null; console.warn('buggy: ' + e.message); throw e; }));
chip.addEventListener('click', () => { load().then(u => u.toggle()).catch(() => {}); (doc.getElementById('view') || doc.body).focus?.(); });
doc.addEventListener('keydown', e => {
if (e.code !== 'KeyE' || e.repeat || e.ctrlKey || e.metaKey || e.altKey || typing(e.target)) return;
if (api.state().view === 'aerial') return; // E flies the drone up
load().then(u => u.toggle()).catch(() => {});
});
api.hooks.commands?.add(line => {
const p = parseBuggy(line);
if (!p) return null;
if (!p.ok) return { ok: false, text: p.why, line, quiet: true };
return load().then(u => ({ ok: true, text: u.command(p), line, quiet: true }));
});
return { load, ui: () => ui, debug: () => ui?.debug() ?? { mounted: false, loaded: false } };
}