In this section
- Drums transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/drums.mjs lines 1–288
- Fence transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/fence.mjs lines 1–271
- Input transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/input.mjs lines 1–93
Drums
A JavaScript module in the world folder of GlobalGrid2050 that works with cables, 33kV and 66kV.
Set aside from the main view: 99% of its lines are the same as solar-design-studio/202609270439-site-world/world/drums.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Drums; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9916 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270439-site-world/world/drums.mjs:1-288 ea23d78617345e6023f03522a17f9392cddcd5a0
- sha256 a76fb2775871bde14d0053d80b5a400c1c5b5ed2471e759fc19645abf77d481b
- target sha256 d49af2516ade41189e88a5925fff19abf376a4639704ae2b14b25a9912efad6a
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/drums.mjs · lines 1–288 of 288 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern drawJointBays (shared by 2 files)
- What it does
- It calculates cables, 33kV and 66kV. Defines 16 functions or classes, including val, massPerMetre, barrelRule, drumCapacity, chooseDrum.
- 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, 33kV, 66kV, 2kV.
- Inputs & outputs
- Voltage levels named: 66kV, 33kV, 2kV.
- Downstream impact
- Used directly by 1 file: Design Earthworks (globalgrid2050).
- What it achieves
- It draws joint bays (`drawJointBays`) and is built from the val step (`val`) and the mass per metre helper (`massPerMetre`). Split a cable route into drum lengths, place joint bays, and produce a drum schedule. Its code works with 33 kV, 66 kV and 2 kV.
- Why it matters
- Imported by Design Earthworks.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- Boq Assumptions (import)
- Used by
- imported by Design Earthworks (import), mentioned in Standalone (comment link)
- Produces
- ASSUMED, DRUMS, massPerMetre, barrelRule, drumCapacity, chooseDrum, planDrums, drawJointBays
- Defines here
- val, massPerMetre, barrelRule, drumCapacity, chooseDrum, profile, interp, pointAt, bayProblems, planDrums, coreLen, need, fits, reach, drawJointBays, seg
- 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/202609270005-site-world-v3/world/drums.mjs:1-288 · blob 5bb26c73546acffd21a9414523fe46292cc526ed · 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: duplicate_candidate
// Drums: split a cable route into drum lengths, place joint bays, and produce a drum schedule.
// Pure: no DOM, no WebGL; imports only the shared cable allowances from boq-assumptions.mjs. Local east (x), north (y), up (z), metres, as cable-route.mjs.
//
// planDrums({ route, cable, rules, crossings, groundAt, options })
// route the object returned by routeCable() in cable-route.mjs
// cable one entry of web/world/data/cables.json "cables"
// rules the "rules" array of the same file (used for the drum barrel bend check); optional
// crossings [{ at }] or [{ from, to }] plan chainages (metres) of roads, pipes, ditches; optional
// groundAt (x, y) -> ground height, for the top of the drawn joint bays; optional
// options overrides for any value in ASSUMED below, plus drums (a drum table) and maxDrumLength
//
// Lengths are true 3D lengths along each core (the three cores differ slightly in bends), plus allowances.
// Every figure not taken from cables.json is an assumption, listed in ASSUMED with its basis, and
// returned in the schedule so nobody mistakes it for a measured value.
import { CABLE_ALLOWANCES } from './boq-assumptions.mjs';
// Termination tail and snaking come from CABLE_ALLOWANCES, the one set the bill of quantities uses too.
export const ASSUMED = {
terminationAllowance: { value: CABLE_ALLOWANCES.terminationM.value, unit: CABLE_ALLOWANCES.terminationM.unit, basis: CABLE_ALLOWANCES.terminationM.basis },
jointAllowance: { value: 1.5, unit: 'm per core per cable end at a joint', basis: 'Assumed: overlap and cut-back needed in the bay to make the joint.' },
snaking: { value: CABLE_ALLOWANCES.snakingPct.value / 100, unit: 'fraction of 3D route length', basis: CABLE_ALLOWANCES.snakingPct.basis },
drumEndWaste: { value: 2, unit: 'm per drum', basis: 'Assumed: inner end left on the drum for sealing and testing, and the damaged pulling end.' },
orderIncrement: { value: 10, unit: 'm', basis: 'Assumed: each drum length is ordered rounded up to this step.' },
freeboard: { value: 0.075, unit: 'm', basis: 'Assumed: clearance between the outer layer and the flange rim, at least one cable diameter.' },
maxFlange: { value: 4.3, unit: 'm', basis: 'Assumed: on a low-loader deck of about 0.5 m the loaded height stays below 5.03 m '
+ '(16 ft 6 in), the GB bridge height below which bridges carry height signs; there is no general legal height limit.' },
maxPullLength: { value: 1000, unit: 'm per section', basis: 'Assumed cap on one pull, no source: stands in for a pulling-tension '
+ 'and sidewall-pressure check, which this module does not yet make. Drum capacity alone would allow pulls of 2 km or more.' },
maxPayload: { value: 25, unit: 't cable per drum', basis: 'Assumed: a 44 t six-axle articulated vehicle (GB authorised weight) less tractor, trailer and drum.' },
bayLength: { value: 8, unit: 'm (33 kV); 10 m above 66 kV', basis: 'Assumed typical joint bay length for three single-core joints side by side.' },
bayWidth: { value: 1.8, unit: 'm (33 kV); 2.5 m above 66 kV', basis: 'Assumed typical joint bay width.' },
bayFloorBelowCable: { value: 0.3, unit: 'm', basis: 'Assumed: working space below the cable in the bay.' },
bayMargin: { value: 3, unit: 'm', basis: 'Assumed: straight run needed beyond each end of the bay before a bend starts.' },
maxBaySlope: { value: 0.05, unit: 'rise over run', basis: 'Assumed 1 in 20: bays are kept near level so the joint sits flat and water drains away.' },
crossingClearance: { value: 10, unit: 'm', basis: 'Assumed: keep a bay this far from any crossing so the crossing is not re-excavated.' },
coverIfNoGround: { value: 1.0, unit: 'm', basis: 'Assumed: drawn bay rim height above the cable when no ground function is given.' },
endClearance: { value: 20, unit: 'm', basis: 'Assumed: keep a bay this far from either end of the route.' },
densityAl: { value: 1.6, unit: 't/m3 over the outer diameter', basis: 'Assumed equivalent density to estimate mass per metre of an aluminium cable when none is given.' },
densityCu: { value: 2.5, unit: 't/m3 over the outer diameter', basis: 'Assumed; close to the 2.5-2.7 implied by the purchaser figures (S7) in cables.json.' },
densityOther: { value: 2.2, unit: 't/m3 over the outer diameter', basis: 'Assumed for a conductor metal not stated.' },
};
// Typical drum sizes, rounded; assumed, not copied from any maker's table. Check against the supplier's drum schedule.
export const DRUMS = [
{ id: 'D18', flange: 1.8, barrel: 1.0, width: 1.1, tare: 0.35 },
{ id: 'D22', flange: 2.2, barrel: 1.3, width: 1.3, tare: 0.6 },
{ id: 'D26', flange: 2.6, barrel: 1.6, width: 1.5, tare: 0.9 },
{ id: 'D30', flange: 3.0, barrel: 1.8, width: 1.8, tare: 1.4 },
{ id: 'D36', flange: 3.6, barrel: 2.2, width: 2.2, tare: 2.2 },
{ id: 'D40', flange: 4.0, barrel: 2.4, width: 2.4, tare: 3.0 },
{ id: 'D43', flange: 4.3, barrel: 2.8, width: 2.4, tare: 3.6 },
];
const val = (opts, k) => (opts[k] !== undefined ? opts[k] : ASSUMED[k].value);
// Mass per metre: the catalogue figure if cables.json gives one, else estimated from the outer diameter.
export function massPerMetre(cable, opts = {}) {
if (cable.mass_kg_m > 0) return { kgPerM: cable.mass_kg_m, basis: 'cables.json mass_kg_m' };
const k = cable.conductor === 'Al' ? 'densityAl' : cable.conductor === 'Cu' ? 'densityCu' : 'densityOther';
const d = cable.od_mm / 1000;
return { kgPerM: val(opts, k) * 1000 * Math.PI * d * d / 4, basis: `estimated from OD with ${k} (assumed)` };
}
// The static (final position) bend multiple from cables.json that sets the drum barrel: barrel >= 2 x multiple x OD,
// i.e. 30 x OD for a 33 kV single core. ASSUMED AND CONSERVATIVE: drum packaging rules allow tighter barrels (NEMA WC 26
// Table 3-1, as reported by the tester: 12 x OD for extruded wire-shielded cable over 2 kV, 14 x OD tape-shielded; more
// for metallic sheaths), because a cable wound slowly on a supported drum may bend tighter than when installed.
// The maker's drum schedule governs.
export function barrelRule(cable, rules = []) {
const armoured = /armoured/.test(cable.id);
const want = cable.voltage_kv > 66 ? 'single_core_metallic_sheath' : armoured ? 'single_core_armoured' : 'single_core_unarmoured';
const fits = rules.filter((r) => r.voltage_kv === cable.voltage_kv && r.when === 'final' && r.status === 'verified' && r.multiple_of_od > 0);
const pool = fits.filter((r) => r.construction === want).length ? fits.filter((r) => r.construction === want) : fits;
if (!pool.length) return { multiple: 15, source: 'No verified static rule in cables.json for this cable; 15 x OD assumed.' };
const r = pool.reduce((a, b) => (b.multiple_of_od < a.multiple_of_od ? b : a));
return { multiple: r.multiple_of_od, source: r.source };
}
// Length a drum can hold, square-wound layers: each layer i holds floor(width / OD) turns at diameter barrel + (2i - 1) OD.
export function drumCapacity(drum, odM, freeboard) {
const layers = Math.floor((drum.flange - drum.barrel - 2 * Math.max(freeboard, odM)) / (2 * odM));
const turns = Math.floor(drum.width / odM);
let len = 0;
for (let i = 1; i <= layers; i++) len += Math.PI * (drum.barrel + (2 * i - 1) * odM) * turns;
return Math.max(0, len);
}
// Choose the drum that carries the longest length within the flange, payload and barrel limits.
export function chooseDrum(cable, rules, opts = {}) {
const od = cable.od_mm / 1000;
const mass = massPerMetre(cable, opts);
const bend = barrelRule(cable, rules);
const minBarrel = 2 * bend.multiple * od;
const table = opts.drums || DRUMS;
let best = null;
const rejected = [];
for (const d of table) {
if (d.flange > val(opts, 'maxFlange') + 1e-9) { rejected.push({ id: d.id, reason: 'flange above the transport limit' }); continue; }
if (d.barrel < minBarrel - 1e-9) { rejected.push({ id: d.id, reason: `barrel below ${minBarrel.toFixed(2)} m (2 x ${bend.multiple} x OD, assumed conservative)` }); continue; }
const capacity = drumCapacity(d, od, val(opts, 'freeboard'));
const byWeight = Math.max(0, (val(opts, 'maxPayload') - (d.tare || 0)) * 1000 / mass.kgPerM);
let maxLength = Math.min(capacity, byWeight);
let governs = capacity <= byWeight ? 'drum capacity' : 'payload weight';
const cap = val(opts, 'maxPullLength');
if (cap > 0 && cap < maxLength) { maxLength = cap; governs = 'pulling length cap (assumed)'; }
if (opts.maxDrumLength > 0 && opts.maxDrumLength < maxLength) { maxLength = opts.maxDrumLength; governs = 'maxDrumLength option'; }
const c = { ...d, capacity, byWeight, maxLength, governs };
if (!best || c.maxLength > best.maxLength) best = c;
}
return { drum: best, rejected, mass, bend, minBarrel };
}
// Per-sample arrays along the route: plan chainage, 3D distance, and 3D length of each core.
function profile(route) {
const cl = route.centreline;
const n = cl.length;
const plan = [0], d3 = [0];
for (let k = 1; k < n; k++) {
const dx = cl[k][0] - cl[k - 1][0], dy = cl[k][1] - cl[k - 1][1], dz = cl[k][2] - cl[k - 1][2];
plan.push(plan[k - 1] + Math.hypot(dx, dy));
d3.push(d3[k - 1] + Math.hypot(dx, dy, dz));
}
// Chords are a hair shorter than arcs; scale so the plan chainage matches the route's exact length2d.
const f = plan[n - 1] > 0 ? route.length2d / plan[n - 1] : 1;
for (let k = 0; k < n; k++) plan[k] *= f;
const cores = (route.cores && route.cores.length ? route.cores : [{ polyline: cl }]).map((c) => {
const acc = [0];
for (let k = 1; k < n; k++) {
const p = c.polyline[k], q = c.polyline[k - 1];
acc.push(acc[k - 1] + Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]));
}
return acc;
});
return { cl, plan, d3, cores, n, xs: cl.map((p) => p[0]), ys: cl.map((p) => p[1]), zs: cl.map((p) => p[2]) };
}
// Linear interpolation of any per-sample array at 3D distance t.
function interp(pr, arr, t) {
const { d3, n } = pr;
if (t <= 0) return arr[0];
if (t >= d3[n - 1]) return arr[n - 1];
let lo = 0, hi = n - 1;
while (hi - lo > 1) { const m = (lo + hi) >> 1; if (d3[m] <= t) lo = m; else hi = m; }
const u = (t - d3[lo]) / (d3[hi] - d3[lo] || 1);
return arr[lo] + (arr[hi] - arr[lo]) * u;
}
function pointAt(pr, t) {
return [interp(pr, pr.xs, t), interp(pr, pr.ys, t), interp(pr, pr.zs, t)];
}
// Why a bay centred at 3D distance t is not acceptable; empty when it is.
function bayProblems(pr, route, t, cfg, crossings) {
const out = [];
const total = pr.d3[pr.n - 1];
const half = cfg.bayLength / 2;
if (t - half < cfg.endClearance || t + half > total - cfg.endClearance) out.push('too near a route end');
const s = interp(pr, pr.plan, t);
const a = interp(pr, pr.plan, t - half) - cfg.bayMargin, b = interp(pr, pr.plan, t + half) + cfg.bayMargin;
for (const g of route.segments) if (g.type === 'arc' && g.s1 > a && g.s0 < b) { out.push('on or near a bend'); break; }
const za = interp(pr, pr.zs, t - half), zb = interp(pr, pr.zs, t + half);
const run = interp(pr, pr.plan, t + half) - interp(pr, pr.plan, t - half);
if (run > 0 && Math.abs(zb - za) / run > cfg.maxBaySlope) out.push('slope above the limit');
for (const c of crossings) {
const lo = (c.from !== undefined ? c.from : c.at) - cfg.crossingClearance - half;
const hi = (c.to !== undefined ? c.to : c.at) + cfg.crossingClearance + half;
if (s > lo && s < hi) { out.push('near a crossing'); break; }
}
return out;
}
export function planDrums({ route, cable, rules = [], crossings = [], groundAt = null, options = {} } = {}) {
if (!route || !Array.isArray(route.centreline) || route.centreline.length < 2) throw Error('planDrums needs a route from routeCable');
if (!cable || !(cable.od_mm > 0)) throw Error('planDrums needs a cable with od_mm');
const opts = options;
const hv = cable.voltage_kv > 66;
const cfg = {};
for (const k of Object.keys(ASSUMED)) cfg[k] = val(opts, k);
if (opts.bayLength === undefined && hv) cfg.bayLength = 10;
if (opts.bayWidth === undefined && hv) cfg.bayWidth = 2.5;
const pick = chooseDrum(cable, rules, opts);
if (!pick.drum) throw Error('no drum in the table meets the flange, barrel and payload limits');
const maxL = pick.drum.maxLength;
const pr = profile(route);
const total = pr.d3[pr.n - 1];
const step = opts.searchStep || 1;
const coreLen = (t0, t1) => Math.max(...pr.cores.map((c) => interp(pr, c, t1) - interp(pr, c, t0)));
// Ordered length of one core for the section between 3D distances t0 and t1 (before rounding).
const need = (t0, t1) => {
const ends = (t0 <= 0 ? cfg.terminationAllowance : cfg.jointAllowance) + (t1 >= total ? cfg.terminationAllowance : cfg.jointAllowance);
return coreLen(t0, t1) * (1 + cfg.snaking) + ends + cfg.drumEndWaste;
};
const fits = (t0, t1) => Math.ceil(need(t0, t1) / cfg.orderIncrement - 1e-9) * cfg.orderIncrement <= maxL + 1e-9;
// Farthest end t1 reachable from t0 on one drum (bisection on the monotone need()).
const reach = (t0) => {
if (fits(t0, total)) return total;
let lo = t0, hi = total;
for (let i = 0; i < 60; i++) { const m = (lo + hi) / 2; if (fits(t0, m)) lo = m; else hi = m; }
return lo;
};
const issues = [];
let joints = [];
// Fewest drums first, then balance: aim each joint at an equal share of what is left, move it to the nearest
// acceptable spot that the drum can still reach. Add a drum and retry when the balanced plan does not close.
const n0 = Math.max(1, Math.ceil(total * (1 + cfg.snaking) / maxL));
for (let n = n0; ; n++) {
if (n > n0 + 200) { issues.push('no balanced plan found within 200 extra drums per core'); break; }
const placed = [];
let prev = 0;
for (let k = 1; k < n; k++) {
const far = reach(prev);
const target = prev + (total - prev) / (n - k + 1);
let best = null;
for (let d = 0; d <= far - prev; d += step) {
for (const t of d === 0 ? [target] : [target - d, target + d]) {
if (t <= prev + cfg.bayLength || t > far) continue;
if (!bayProblems(pr, route, t, cfg, crossings).length) { best = t; break; }
}
if (best !== null) break;
}
if (best === null) { best = Math.min(target, far); placed.push({ t: best, forced: true }); } else placed.push({ t: best, forced: false });
prev = best;
}
joints = placed;
if (fits(prev, total)) break; // the last section ends at the termination: test it with that allowance
}
const cuts = [0, ...joints.map((j) => j.t), total];
const cores = pr.cores.length;
const sections = [];
for (let i = 0; i < cuts.length - 1; i++) {
const t0 = cuts[i], t1 = cuts[i + 1];
const len = coreLen(t0, t1);
const ordered = Math.ceil(need(t0, t1) / cfg.orderIncrement - 1e-9) * cfg.orderIncrement;
sections.push({
index: i + 1, from: t0, to: t1, fromChainage: interp(pr, pr.plan, t0), toChainage: interp(pr, pr.plan, t1),
routeLength3d: t1 - t0, coreLength3d: len, snaking: len * cfg.snaking,
endAllowances: need(t0, t1) - len * (1 + cfg.snaking) - cfg.drumEndWaste, drumEndWaste: cfg.drumEndWaste,
orderedPerCore: ordered, drums: cores, withinDrum: ordered <= maxL + 1e-9,
});
}
const bays = joints.map((j, i) => {
const [x, y, z] = pointAt(pr, j.t);
const q = pointAt(pr, Math.min(total, j.t + 0.5)), p = pointAt(pr, Math.max(0, j.t - 0.5));
const problems = bayProblems(pr, route, j.t, cfg, crossings);
if (problems.length) issues.push(`joint bay ${i + 1} at ${interp(pr, pr.plan, j.t).toFixed(1)} m: ${problems.join(', ')}`);
return { index: i + 1, distance3d: j.t, chainage: interp(pr, pr.plan, j.t), x, y, z, heading: Math.atan2(q[1] - p[1], q[0] - p[0]), problems };
});
for (const s of sections) if (!s.withinDrum) issues.push(`section ${s.index} needs ${s.orderedPerCore} m per core, over the ${maxL.toFixed(0)} m drum limit`);
const installed = sections.reduce((a, s) => a + s.coreLength3d * (1 + cfg.snaking), 0) * cores;
const ordered = sections.reduce((a, s) => a + s.orderedPerCore, 0) * cores;
const schedule = {
cable: { id: cable.id, od_mm: cable.od_mm, massKgPerM: pick.mass.kgPerM, massBasis: pick.mass.basis },
drum: { id: pick.drum.id, flange: pick.drum.flange, barrel: pick.drum.barrel, width: pick.drum.width, capacity: pick.drum.capacity,
byWeight: pick.drum.byWeight, maxLength: maxL, governs: pick.drum.governs, minBarrel: pick.minBarrel, barrelRule: pick.bend, rejected: pick.rejected,
basis: opts.drums ? 'drum table passed in' : "assumed typical drum sizes, not a maker's table" },
sections,
joints: bays,
totals: {
routeLength3d: total, cores, drums: sections.length * cores, jointBays: bays.length, joints: bays.length * cores,
orderedPerCore: ordered / cores, orderedTotal: ordered, installedTotal: installed, waste: ordered - installed,
wasteFraction: ordered > 0 ? (ordered - installed) / ordered : 0,
},
assumptions: Object.keys(ASSUMED).map((k) => ({ name: k, value: cfg[k], unit: ASSUMED[k].unit, basis: ASSUMED[k].basis, overridden: opts[k] !== undefined })),
issues,
};
schedule.drawLines = () => drawJointBays(bays, cfg, groundAt);
return schedule;
}
// Joint bays as small outlined pits: rim rectangle at ground, floor rectangle, four corner edges. Float32Array of x,y,z pairs.
export function drawJointBays(bays, cfg = {}, groundAt = null) {
const L = cfg.bayLength || ASSUMED.bayLength.value, W = cfg.bayWidth || ASSUMED.bayWidth.value;
const below = cfg.bayFloorBelowCable !== undefined ? cfg.bayFloorBelowCable : ASSUMED.bayFloorBelowCable.value;
const cover = cfg.coverIfNoGround !== undefined ? cfg.coverIfNoGround : ASSUMED.coverIfNoGround.value;
const out = new Float32Array(bays.length * 12 * 6);
let o = 0;
const seg = (a, b) => { out[o++] = a[0]; out[o++] = a[1]; out[o++] = a[2]; out[o++] = b[0]; out[o++] = b[1]; out[o++] = b[2]; };
for (const b of bays) {
const c = Math.cos(b.heading), s = Math.sin(b.heading);
const corners = [[-L / 2, -W / 2], [L / 2, -W / 2], [L / 2, W / 2], [-L / 2, W / 2]].map(([u, v]) => [b.x + u * c - v * s, b.y + u * s + v * c]);
const floor = b.z - below;
const top = corners.map(([x, y]) => [x, y, groundAt ? groundAt(x, y) : b.z + cover]);
const bot = corners.map(([x, y]) => [x, y, floor]);
for (let i = 0; i < 4; i++) { seg(top[i], top[(i + 1) % 4]); seg(bot[i], bot[(i + 1) % 4]); seg(top[i], bot[i]); }
}
return out;
}Fence
A JavaScript module in the world folder of GlobalGrid2050 that works with box over (`boxOver`) and calculates planar distances, using BS 1722-12 and BS 1722-14.
transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/fence.mjs · lines 1–271 of 271 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern solids (shared by 4 files)
- What it does
- It calculates its inputs. Defines 14 functions or classes, including createFence, wrap, pointAt, zAt, profile.
- 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: Design Earthworks (globalgrid2050); Design Earthworks (globalgrid2050).
- What it achieves
- It is built from the wrap step (`wrap`), the point at helper (`pointAt`) and the z at helper (`zAt`). Perimeter and compound fences laid over the ground.
- Why it matters
- Imported by Design Earthworks.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Design Earthworks (import), imported by Design Earthworks (import)
- Produces
- CORNER_TURN_DEG, GATE_CLEAR_M, FENCE_TYPES, createFence
- Defines here
- createFence, wrap, pointAt, zAt, profile, at3d, count, boxOver, chunksOf, solids, lines, P3, L, inside
- 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/202609270005-site-world-v3/world/fence.mjs:1-271 · blob 08d2b6a4ffe74273d2ecefb4340ad0fed6101e6c · 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
// fence.mjs: perimeter and compound fences laid over the ground. Pure: no imports, no DOM.
//
// Local metres: x east, y north, z up. The ground is any function groundAt(x, y).
// A fence is a closed polygon (the last point joins the first). Posts stand at every corner, at both sides of
// every gate and at the chosen spacing between, measured along the ground, so no bay on a slope is longer than
// the spacing. Wire fences (deer) also get intermediate strainers at a maximum interval. The fence top follows
// the ground at a constant height. Solids are short axis-aligned boxes along the line, so a walker cannot pass
// through and the drone can only cross above the fence top. An open gate leaves its opening free.
//
// createFence({ polygon, type = 'mesh', height?, postSpacing?, strainerMaxM?, gates = [], groundAt, chunk? })
// polygon: [[x, y], ...] with at least three distinct points, either winding.
// gates: [{ at, width, open? }] with at the gate centre as perimeter chainage from the first point (2D metres),
// or [{ edge, offset, width, open? }] with offset along that edge from its first point.
//
// EVERY DIMENSION BELOW IS TYPICAL OR ASSUMED, NOT A DESIGN. Each value says which; check the standard before use.
const STEP = 0.25; // sampling step along the ground, metres
const LINE_STEP = 1; // wireframe draping step, metres
const EPS = 1e-9;
// Turn at a vertex below which it is a line post, not a corner (assumed, 15 degrees). FC Technical Guide 2 puts
// straining assemblies at major changes of direction; a traced or curved boundary has many small turns, and a real
// fence would not put a strainer and two struts at each. A long run of small turns is not treated as a corner.
export const CORNER_TURN_DEG = 15;
// Least distance from a gate post to a corner, metres (assumed): room for the corner strainer and its strut.
export const GATE_CLEAR_M = 0.5;
// Fence types:
// - deer: woven or high-tensile wire on timber stakes. Forestry Commission Technical Guide 2, "Forest fencing"
// (Trout and Pepper, 2006), which replaced FC Bulletin 102 (1992): Table 2 gives a maximum stake spacing of 10 m
// for roe, muntjac and red, sika or fallow deer; Table 3, note 3, at least 1.8 m high for fallow, roe or muntjac
// and 2 m for red and sika (areas over 5 ha or beside roads). Section 1: straining assemblies at major changes of
// direction and ground contour; on long straight lines on flat ground up to 1000 m apart. The 1000 m interval here
// is that upper figure (assumed as the default); strainers at hollows and crests are not added.
// - palisade: steel palisade to BS 1722-12, stock heights 1.8, 2.0, 2.4 and 3.0 m; 2.4 m is the usual choice round
// electrical compounds (typical). Posts at 2.75 m centres (typical panel length). Rigid panels: no strainers.
// - mesh: welded open-mesh steel panels to BS 1722-14. Height 2.0 m and posts at 2.5 m centres (typical).
// rails: heights (fractions of the fence height) of the horizontal lines drawn between posts.
export const FENCE_TYPES = Object.freeze({
deer: { label: 'Deer fence (roe, fallow, muntjac)', height: 1.8, postSpacing: 10, strainerMaxM: 1000, tensioned: true,
rails: [0.03, 0.5, 1], basis: 'FC Technical Guide 2 (2006): 1.8 m (Table 3), stakes 10 m maximum (Table 2), strainers at '
+ 'major changes of direction, up to 1000 m apart on straight flat lines (section 1)' },
deerRedSika: { label: 'Deer fence (red, sika)', height: 2.0, postSpacing: 10, strainerMaxM: 1000, tensioned: true,
rails: [0.03, 0.5, 1], basis: 'FC Technical Guide 2 (2006): 2 m for red and sika (Table 3, note 3), stakes 10 m '
+ 'maximum (Table 2), strainers at major changes of direction, up to 1000 m apart (section 1)' },
palisade: { label: 'Security palisade', height: 2.4, postSpacing: 2.75, strainerMaxM: null, tensioned: false,
rails: [0.03, 0.15, 0.85, 1], basis: 'BS 1722-12 heights; 2.4 m and 2.75 m centres typical' },
mesh: { label: 'Mesh panel fence', height: 2.0, postSpacing: 2.5, strainerMaxM: null, tensioned: false,
rails: [0.03, 1], basis: 'BS 1722-14 panels; 2.0 m and 2.5 m centres typical' },
});
export function createFence({ polygon, type = 'mesh', height, postSpacing, strainerMaxM, gates = [], groundAt, chunk = 1 }) {
const spec = FENCE_TYPES[type];
if (!spec) throw new Error(`fence: unknown type ${type}; use ${Object.keys(FENCE_TYPES).join(', ')}`);
if (typeof groundAt !== 'function') throw new Error('fence: groundAt(x, y) is required; the fence follows the ground');
const H = height ?? spec.height, SP = postSpacing ?? spec.postSpacing;
const SMAX = spec.tensioned ? (strainerMaxM ?? spec.strainerMaxM) : null;
if (!(H > 0) || !(SP > 0) || !(chunk > 0)) throw new Error('fence: height, postSpacing and chunk must be positive');
if (SMAX !== null && !(SMAX >= SP)) throw new Error('fence: strainerMaxM must be at least the post spacing');
// Ring: drop repeats and a closing duplicate.
if (!Array.isArray(polygon)) throw new Error('fence: polygon must be an array of [x, y]');
const pts = [];
for (const p of polygon) {
const q = [Number(p[0]), Number(p[1])];
if (!Number.isFinite(q[0]) || !Number.isFinite(q[1])) throw new Error('fence: polygon points must be finite');
const last = pts[pts.length - 1];
if (!last || Math.hypot(q[0] - last[0], q[1] - last[1]) > 1e-6) pts.push(q);
}
while (pts.length > 1 && Math.hypot(pts[0][0] - pts.at(-1)[0], pts[0][1] - pts.at(-1)[1]) <= 1e-6) pts.pop();
if (pts.length < 3) throw new Error('fence: polygon needs three distinct points');
let area2 = 0;
for (let i = 0; i < pts.length; i++) { const a = pts[i], b = pts[(i + 1) % pts.length]; area2 += a[0] * b[1] - b[0] * a[1]; }
if (Math.abs(area2) < 1e-6) throw new Error('fence: polygon encloses no area');
const n = pts.length, edges = [];
let P = 0;
for (let i = 0; i < n; i++) {
const [ax, ay] = pts[i], [bx, by] = pts[(i + 1) % n], len = Math.hypot(bx - ax, by - ay);
edges.push({ ax, ay, dx: (bx - ax) / len, dy: (by - ay) / len, len, s0: P });
P += len;
}
const perimeter2d = P;
const wrap = (s) => ((s % P) + P) % P;
function pointAt(s) {
const c = wrap(s);
let e = edges[n - 1];
for (const g of edges) if (c < g.s0 + g.len) { e = g; break; }
const t = Math.min(Math.max(c - e.s0, 0), e.len);
return [e.ax + e.dx * t, e.ay + e.dy * t];
}
const zAt = (s) => { const [x, y] = pointAt(s); return groundAt(x, y); };
// Corners: vertices that turn by at least CORNER_TURN_DEG.
const cosTurn = Math.cos(CORNER_TURN_DEG * Math.PI / 180);
const corners = [];
for (let i = 0; i < n; i++) {
const a = edges[(i - 1 + n) % n], b = edges[i];
if (a.dx * b.dx + a.dy * b.dy < cosTurn) corners.push(b.s0);
}
// Gates: resolve, validate, sort.
const gl = gates.map((g, k) => {
let at = g.at;
if (g.edge !== undefined) {
const e = edges[g.edge];
if (!e) throw new Error(`fence: gate ${k} names edge ${g.edge}; the polygon has ${n}`);
at = e.s0 + Number(g.offset);
}
if (!Number.isFinite(at) || !(g.width > 0)) throw new Error(`fence: gate ${k} needs a finite position and a positive width`);
const s = wrap(at), half = g.width / 2;
if (g.width >= P / 2) throw new Error(`fence: gate ${k} is wider than half the perimeter`);
for (const c of corners) {
const d = Math.abs(wrap(c - s + P / 2) - P / 2);
if (d < half + GATE_CLEAR_M - EPS) throw new Error(`fence: gate ${k} is within ${GATE_CLEAR_M} m of a corner; move it along the edge`);
}
return { index: k, at: s, width: g.width, open: !!g.open, sA: s - half, sB: s + half };
}).sort((a, b) => a.at - b.at);
for (let k = 0; k < gl.length; k++) {
const a = gl[k], b = gl[(k + 1) % gl.length];
const gap = k + 1 < gl.length ? b.sA - a.sB : b.sA + P - a.sB;
if (gl.length > 1 && gap < 2 * GATE_CLEAR_M - EPS) throw new Error(`fence: gates ${a.index} and ${b.index} overlap or touch`);
}
// Stops: posts that end a run (corners and gate posts). Runs lie between stops, skipping gate openings.
const stops = [...corners.map((s) => ({ s, kind: 'corner' }))];
for (const g of gl) stops.push({ s: wrap(g.sA), kind: 'gate' }, { s: wrap(g.sB), kind: 'gate', opensBefore: g });
if (!stops.length) stops.push({ s: 0, kind: 'end' }); // a smooth ring still needs one end post to tension from
stops.sort((a, b) => a.s - b.s);
const runs = [];
for (let k = 0; k < stops.length; k++) {
const a = stops[k], b = stops[(k + 1) % stops.length];
const sb = k + 1 < stops.length ? b.s : b.s + P;
if (b.opensBefore && Math.abs(wrap(b.opensBefore.sA) - a.s) < 1e-6) continue; // the gate opening itself
runs.push({ sa: a.s, sb: sb === a.s ? a.s + P : sb });
}
// Samples along a stretch: 2D chainage and cumulative 3D length, vertices included exactly.
function profile(sa, sb) {
const marks = new Set([sa, sb]);
const steps = Math.max(1, Math.ceil((sb - sa) / STEP));
for (let k = 1; k < steps; k++) marks.add(sa + (sb - sa) * k / steps);
for (const e of edges) for (const v of [e.s0, e.s0 + P]) if (v > sa && v < sb) marks.add(v);
const s = [...marks].sort((a, b) => a - b), c = [0];
let [px, py] = pointAt(s[0]), pz = groundAt(px, py);
for (let k = 1; k < s.length; k++) {
const [x, y] = pointAt(s[k]), z = groundAt(x, y);
c.push(c[k - 1] + Math.hypot(x - px, y - py, z - pz));
px = x; py = y; pz = z;
}
return { s, c, len: c.at(-1) };
}
const at3d = (pr, d) => { // 2D chainage at 3D distance d along the profile
let k = 1;
while (k < pr.c.length - 1 && pr.c[k] < d) k++;
const f = (d - pr.c[k - 1]) / Math.max(pr.c[k] - pr.c[k - 1], EPS);
return pr.s[k - 1] + (pr.s[k] - pr.s[k - 1]) * Math.min(Math.max(f, 0), 1);
};
// Posts. Stops first, then strainers and line posts at equal 3D bays within each run.
const posts = stops.map((st) => ({ s: st.s, kind: st.kind }));
let fenceLen3d = 0, maxBay = 0;
for (const r of runs) {
const pr = profile(r.sa, r.sb);
fenceLen3d += pr.len;
const sections = SMAX ? Math.max(1, Math.ceil(pr.len / SMAX - EPS)) : 1;
const perSection = Math.max(1, Math.ceil(pr.len / sections / SP - EPS));
const bays = sections * perSection;
maxBay = Math.max(maxBay, pr.len / bays);
for (let k = 1; k < bays; k++) {
posts.push({ s: wrap(at3d(pr, pr.len * k / bays)), kind: SMAX && k % perSection === 0 ? 'strainer' : 'line' });
}
}
for (const p of posts) { const [x, y] = pointAt(p.s); p.x = x; p.y = y; p.z = groundAt(x, y); }
posts.sort((a, b) => a.s - b.s);
const count = (k) => posts.filter((p) => p.kind === k).length;
const cornerN = count('corner'), gateN = count('gate'), midStrainers = count('strainer'), endN = count('end');
// Struts (assumed practice): one per direction of pull. Gate strainers one; corner, intermediate and a ring's end
// post (pulled from both sides) two.
const tensioned = spec.tensioned;
const counts = {
posts: posts.length, cornerPosts: cornerN, gatePosts: gateN, linePosts: count('line'),
strainers: tensioned ? cornerN + gateN + midStrainers + endN : 0, endStrainers: tensioned ? endN : 0,
intermediateStrainers: tensioned ? midStrainers : 0,
struts: tensioned ? gateN + 2 * (cornerN + midStrainers + endN) : 0,
gates: gl.length,
};
// Perimeter 3D length including gate openings.
const whole = profile(0, P);
// Solids: chunks along each run, and closed gate leaves. Thickness assumed 0.1 m (post width).
const T = 0.05;
function boxOver(sa, sb) {
const m = Math.max(1, Math.ceil((sb - sa) / STEP));
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity, lo = Infinity, hi = -Infinity;
for (let k = 0; k <= m; k++) {
const [x, y] = pointAt(sa + (sb - sa) * k / m), z = groundAt(x, y);
x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y);
lo = Math.min(lo, z); hi = Math.max(hi, z);
}
return { min: [x0 - T, y0 - T, lo - 0.5], max: [x1 + T, y1 + T, hi + H] };
}
function chunksOf(sa, sb, out, extra) {
const cuts = [sa, sb];
for (const e of edges) for (const v of [e.s0, e.s0 + P]) if (v > sa && v < sb) cuts.push(v);
cuts.sort((a, b) => a - b);
for (let i = 0; i < cuts.length - 1; i++) {
const m = Math.max(1, Math.ceil((cuts[i + 1] - cuts[i]) / chunk - EPS));
for (let k = 0; k < m; k++) {
const a = cuts[i] + (cuts[i + 1] - cuts[i]) * k / m, b = cuts[i] + (cuts[i + 1] - cuts[i]) * (k + 1) / m;
out.push({ ...boxOver(a, b), ...extra });
}
}
}
function solids() {
const out = [];
for (const r of runs) chunksOf(r.sa, r.sb, out, { kind: 'fence' });
for (const g of gl) if (!g.open) chunksOf(g.sA, g.sB, out, { kind: 'gate', gate: g.index });
return out;
}
// Wireframe: gl.LINES pairs relative to origin o. Rails draped on the ground, posts upright, gates framed.
function lines(o = [0, 0, 0]) {
const v = [];
const P3 = (s, up) => { const [x, y] = pointAt(s); return [x - o[0], y - o[1], groundAt(x, y) + up - o[2]]; };
const L = (a, b) => v.push(a[0], a[1], a[2], b[0], b[1], b[2]);
for (const r of runs) {
const cuts = [r.sa, r.sb];
for (const e of edges) for (const w of [e.s0, e.s0 + P]) if (w > r.sa && w < r.sb) cuts.push(w);
cuts.sort((a, b) => a - b);
for (let i = 0; i < cuts.length - 1; i++) {
const m = Math.max(1, Math.ceil((cuts[i + 1] - cuts[i]) / LINE_STEP - EPS));
for (let k = 0; k < m; k++) {
const a = cuts[i] + (cuts[i + 1] - cuts[i]) * k / m, b = cuts[i] + (cuts[i + 1] - cuts[i]) * (k + 1) / m;
for (const f of spec.rails) L(P3(a, f * H), P3(b, f * H));
}
}
}
for (const p of posts) {
const top = H * (p.kind === 'line' ? 1 : 1.05); // strainers and gate posts drawn a little proud
L([p.x - o[0], p.y - o[1], p.z - o[2]], [p.x - o[0], p.y - o[1], p.z + top - o[2]]);
}
for (const g of gl) {
if (g.open) continue; // an open gate is drawn as its posts only
const a0 = P3(g.sA, 0.05), a1 = P3(g.sA, H * 0.95), b0 = P3(g.sB, 0.05), b1 = P3(g.sB, H * 0.95);
L(a0, b0); L(a1, b1); L(a0, b1); // bottom, top and a diagonal brace
}
return new Float32Array(v);
}
// Inside the enclosed area (even-odd rule), for placing things within the compound.
function inside(x, y) {
let c = false;
for (let i = 0, j = n - 1; i < n; j = i++) {
const [xi, yi] = pts[i], [xj, yj] = pts[j];
if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) c = !c;
}
return c;
}
return {
type, label: spec.label, basis: spec.basis, height: H, postSpacing: SP, strainerMaxM: SMAX,
polygon: pts, areaM2: Math.abs(area2) / 2,
perimeter2d, perimeter3d: whole.len, length3d: fenceLen3d, maxBay3d: maxBay,
gates: gl.map((g) => ({ index: g.index, at: g.at, width: g.width, open: g.open, centre: pointAt(g.at), z: zAt(g.at) })),
posts, counts, runs: runs.length,
pointAt, inside, lines, solids,
};
}Input
A JavaScript module in the world folder of GlobalGrid2050 that clamps px (`clampPx`) and calculates planar distances.
transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/input.mjs · lines 1–93 of 93 · version 2026-09-27 00:05 · Entry point · pattern attachInput (shared by 2 files)
- What it does
- It calculates its inputs. Defines 10 functions or classes, including attachInput, set, moveKnob, release, up.
- 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 3 files: Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Substrate (globalgrid2050); 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 clamps px (`clampPx`) and is built from the set step (`set`) and the move knob helper (`moveKnob`). Keyboard, mouse and touch turned into one small state. It responds to keydown, keyup and blur events.
- Why it matters
- Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/. Also imported by Substrate, from Graphics Engines Open Source.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Substrate (import), imported by Substrate (import)
- Produces
- attachInput
- Defines here
- attachInput, set, moveKnob, release, up, any, axis, clamp, capture, clampPx
- 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/202609270005-site-world-v3/world/input.mjs:1-93 · blob 14be1a74b8ee43fa859c29463b591ab791106736 · 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
// Input: keyboard, mouse and touch turned into one small state. Knows nothing about the world.
// Keys: W / S or up / down move, A / D or left / right turn, Shift held = slow and precise,
// F drone on and off (Space / E up, Q down). Mouse: drag to look.
// Touch: the joypad moves (up and down) and turns (sideways); dragging anywhere else looks.
// A press released within CLICK_PX of where it went down is a click: onClick(x, y) in canvas CSS pixels.
const VIEW_KEYS = { KeyF: 'aerial' };
const MOVE_KEYS = new Set(['KeyW', 'KeyA', 'KeyS', 'KeyD', 'KeyE', 'KeyQ', 'Space', 'ShiftLeft', 'ShiftRight',
'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']);
const LOOK_PER_PX = 0.004, TURN_PER_S = 1.8, STICK_PX = 45, CLICK_PX = 4;
export function attachInput(canvas, pad, { onChange, onLook, onView, onClick = () => {} }) {
const keys = new Set();
let stick = null, lookPtr = null, mouse = null, lift = 0, press = null;
const set = (k, down) => { const had = keys.has(k); down ? keys.add(k) : keys.delete(k); if (had !== down) onChange(); };
addEventListener('keydown', e => {
if (e.target instanceof HTMLButtonElement && (e.code === 'Space' || e.code === 'Enter')) return;
if (e.ctrlKey || e.metaKey || e.altKey) return; // leave browser shortcuts such as Ctrl+F alone
if (e.target instanceof HTMLSelectElement || e.target instanceof HTMLInputElement) return; // typing in a form field
if (VIEW_KEYS[e.code] && !e.repeat) { onView(VIEW_KEYS[e.code]); return; }
if (MOVE_KEYS.has(e.code)) { set(e.code, true); e.preventDefault(); }
});
addEventListener('keyup', e => set(e.code, false));
addEventListener('blur', () => { keys.clear(); stick = lookPtr = mouse = null; lift = 0; knob.style.transform = ''; onChange(); });
// joypad: its centre is the rest position; the knob follows the thumb up to the rim
const knob = pad.firstElementChild;
const moveKnob = () => { knob.style.transform = stick ? `translate(${clampPx(stick.dx)}px, ${clampPx(stick.dy)}px)` : ''; };
pad.addEventListener('pointerdown', e => {
if (stick) return;
capture(pad, e);
const r = pad.getBoundingClientRect();
stick = { id: e.pointerId, x0: r.left + r.width / 2, y0: r.top + r.height / 2, dx: 0, dy: 0 };
stick.dx = e.clientX - stick.x0; stick.dy = e.clientY - stick.y0;
moveKnob(); onChange(); e.preventDefault();
});
pad.addEventListener('pointermove', e => {
if (!stick || e.pointerId !== stick.id) return;
stick.dx = e.clientX - stick.x0; stick.dy = e.clientY - stick.y0; moveKnob(); onChange();
});
const release = e => { if (stick && e.pointerId === stick.id) { stick = null; moveKnob(); onChange(); } };
pad.addEventListener('pointerup', release); pad.addEventListener('pointercancel', release);
canvas.addEventListener('pointerdown', e => {
capture(canvas, e);
if (!press) press = { id: e.pointerId, x: e.clientX, y: e.clientY };
if (e.pointerType === 'touch') lookPtr = { id: e.pointerId, x: e.clientX, y: e.clientY };
else mouse = { x: e.clientX, y: e.clientY };
onChange();
});
canvas.addEventListener('pointermove', e => {
const p = lookPtr && e.pointerId === lookPtr.id ? lookPtr : mouse;
if (!p) return;
if (p === mouse && e.buttons === 0) { mouse = null; return; } // released outside the window
onLook((e.clientX - p.x) * LOOK_PER_PX, -(e.clientY - p.y) * LOOK_PER_PX);
p.x = e.clientX; p.y = e.clientY;
});
const up = e => {
if (press && e.pointerId === press.id) {
const click = e.type === 'pointerup' && Math.hypot(e.clientX - press.x, e.clientY - press.y) <= CLICK_PX;
press = null;
if (click) { const r = canvas.getBoundingClientRect(); onClick(e.clientX - r.left, e.clientY - r.top); }
}
if (lookPtr && e.pointerId === lookPtr.id) lookPtr = null;
else mouse = null;
onChange();
};
canvas.addEventListener('pointerup', up); canvas.addEventListener('pointercancel', up);
const any = list => list.some(k => keys.has(k));
const axis = (plus, minus) => (any(plus) ? 1 : 0) - (any(minus) ? 1 : 0);
return {
// forward, strafe, rise in [-1, 1]; turn in radians per second; slow = precise movement
get() {
const s = stick ? [clamp(stick.dx / STICK_PX), clamp(-stick.dy / STICK_PX)] : [0, 0];
return {
forward: clamp(axis(['KeyW', 'ArrowUp'], ['KeyS', 'ArrowDown']) + s[1]),
strafe: 0,
rise: clamp(axis(['Space', 'KeyE'], ['KeyQ']) + lift),
turn: clamp(axis(['KeyD', 'ArrowRight'], ['KeyA', 'ArrowLeft']) + s[0]) * TURN_PER_S,
slow: any(['ShiftLeft', 'ShiftRight'])
};
},
active() { const i = this.get(); return !!(i.forward || i.strafe || i.rise || i.turn); },
// held on-screen Up / Down buttons: +1, -1 or 0
setLift(v) { if (lift !== v) { lift = v; onChange(); } }
};
}
const clamp = v => Math.max(-1, Math.min(1, v));
const capture = (el, e) => { try { el.setPointerCapture(e.pointerId); } catch { /* pointer already gone */ } };
const clampPx = v => Math.max(-STICK_PX, Math.min(STICK_PX, v));