In this section
- Sun transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/sun.mjs lines 1–156
- Tour transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/tour.mjs lines 1–281
- Xr Pose ingest · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/xr-pose.mjs lines 1–160
Sun
A JavaScript module in the world folder of GlobalGrid2050 that works with solar. It clamps ms (`clampMs`) and applies time (`applyTime`).
transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/sun.mjs · lines 1–156 of 156 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern solarPosition (shared by 2 files)
- What it does
- It calculates solar. Defines 14 functions or classes, including fix360, julianDay, sunPlace, refraction, solarPosition.
- 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: solar.
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- Downstream impact
- Used directly by 3 files: Sun UI (globalgrid2050); Sun Day (globalgrid2050); Sun Mode (globalgrid2050).
- What it achieves
- Sun position for a place and a moment, the sun's direction in the world's axes, and a date/time model.
- Why it matters
- Imported by Sun UI, Sun Day and Sun Mode.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Sun UI (import), imported by Sun Day (import), imported by Sun Mode (import)
- Produces
- MIN_MS, julianDay, sunPlace, refraction, solarPosition, sunDirection, solarNoon, gridConvergence, timeState, applyTime, timeView, sunAt
- Defines here
- fix360, julianDay, sunPlace, refraction, solarPosition, sunDirection, solarNoon, gridConvergence, clampMs, timeState, applyTime, num, timeView, sunAt
- 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/sun.mjs:1-156 · blob 5f2cc20f502d4d5637bfbf33d3043e8b0d48582e · 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
// Sun position for a place and a moment, the sun's direction in the world's axes, and a date/time model.
// Pure module: no DOM, no clock reads, no imports. Every function takes its time as UTC milliseconds.
//
// Method: the NOAA Global Monitoring Laboratory solar calculator equations, which follow J. Meeus,
// "Astronomical Algorithms" (2nd ed., Willmann-Bell, 1998), chapters 22, 25 and 28:
// https://gml.noaa.gov/grad/solcalc/calcdetails.html (NOAA_Solar_Calculations_day.xls)
// NOAA states the equations are accurate to about 0.01 degree for dates 1800-2100 (before refraction).
// Tests check the result against the worked example of the NREL Solar Position Algorithm
// (I. Reda and A. Andreas, "Solar Position Algorithm for Solar Radiation Applications",
// NREL/TP-560-34302, 2003, rev. 2008, Table A4.1), whose stated uncertainty is 0.0003 degree.
// The NOAA equations use UT throughout; the difference to Terrestrial Time (about 69 s) moves the sun
// by under 0.001 degree, which is below the method's accuracy.
//
// World axes: x east, y north, z up (local metres), as in web/world. Azimuth is clockwise from true
// north. Grid north on the national grid differs from true north by up to about 3.5 degrees across Great Britain
// (about 3 in East Anglia, 3.5 in western Scotland); callers that
// need grid azimuth subtract the grid convergence at the site (see gridConvergence below).
const RAD = Math.PI / 180, DEG = 180 / Math.PI;
const DAY_MS = 86400000, MINUTE_MS = 60000;
export const MIN_MS = Date.UTC(1800, 0, 1), MAX_MS = Date.UTC(2100, 11, 31, 23, 59);
const fix360 = a => ((a % 360) + 360) % 360;
// Julian day from UTC milliseconds (Unix epoch = JD 2440587.5).
export const julianDay = ms => ms / DAY_MS + 2440587.5;
// The sun's apparent place for a moment: declination (degrees) and equation of time (minutes).
export function sunPlace(ms) {
const T = (julianDay(ms) - 2451545) / 36525; // Julian centuries from J2000.0
const L0 = fix360(280.46646 + T * (36000.76983 + T * 0.0003032)); // geometric mean longitude
const M = 357.52911 + T * (35999.05029 - 0.0001537 * T); // mean anomaly
const e = 0.016708634 - T * (0.000042037 + 0.0000001267 * T); // orbit eccentricity
const Mr = M * RAD;
const C = Math.sin(Mr) * (1.914602 - T * (0.004817 + 0.000014 * T))
+ Math.sin(2 * Mr) * (0.019993 - 0.000101 * T) + Math.sin(3 * Mr) * 0.000289; // equation of centre
const omega = (125.04 - 1934.136 * T) * RAD;
const lambda = (L0 + C - 0.00569 - 0.00478 * Math.sin(omega)) * RAD; // apparent longitude
const eps0 = 23 + (26 + (21.448 - T * (46.815 + T * (0.00059 - T * 0.001813))) / 60) / 60;
const eps = (eps0 + 0.00256 * Math.cos(omega)) * RAD; // corrected obliquity
const decl = Math.asin(Math.sin(eps) * Math.sin(lambda)) * DEG;
const y = Math.tan(eps / 2) ** 2, L0r = L0 * RAD;
const eot = 4 * DEG * (y * Math.sin(2 * L0r) - 2 * e * Math.sin(Mr) + 4 * e * y * Math.sin(Mr) * Math.cos(2 * L0r)
- 0.5 * y * y * Math.sin(4 * L0r) - 1.25 * e * e * Math.sin(2 * Mr));
return { declination: decl, equationOfTime: eot, julianCentury: T };
}
// Atmospheric refraction in degrees for a true elevation in degrees (NOAA's piecewise fit, standard
// atmosphere at 1010 hPa and 10 C). pressure (hPa) and temperature (C) scale it as Meeus eq. 16.4 does.
export function refraction(elevation, { pressure = 1010, temperature = 10 } = {}) {
if (!Number.isFinite(elevation) || elevation > 85) return 0;
const t = Math.tan(elevation * RAD);
let arcsec;
if (elevation > 5) arcsec = 58.1 / t - 0.07 / t ** 3 + 0.000086 / t ** 5;
else if (elevation > -0.575) arcsec = 1735 + elevation * (-518.2 + elevation * (103.4 + elevation * (-12.79 + elevation * 0.711)));
else arcsec = -20.772 / t;
return (arcsec / 3600) * (pressure / 1010) * (283 / (273 + temperature));
}
// Solar position for latitude and longitude (degrees, east positive) at UTC milliseconds.
// Returns { azimuth, elevation, zenith, trueElevation, hourAngle, declination, equationOfTime } in degrees
// (equation of time in minutes). elevation includes refraction unless opts.refraction === false.
export function solarPosition(lat, lon, ms, opts = {}) {
if (![lat, lon, ms].every(Number.isFinite)) throw Error('solar position needs a finite latitude, longitude and time');
if (Math.abs(lat) > 90) throw Error(`latitude ${lat} is outside -90..90`);
const { declination, equationOfTime } = sunPlace(ms);
const minutes = (((ms % DAY_MS) + DAY_MS) % DAY_MS) / MINUTE_MS; // minutes past 00:00 UTC
const tst = ((minutes + equationOfTime + 4 * lon) % 1440 + 1440) % 1440; // true solar time
const H = tst / 4 - 180; // hour angle, noon = 0
const la = lat * RAD, de = declination * RAD, h = H * RAD;
const cosZ = Math.min(1, Math.max(-1, Math.sin(la) * Math.sin(de) + Math.cos(la) * Math.cos(de) * Math.cos(h)));
const zenithTrue = Math.acos(cosZ) * DEG;
// atan2 form of the azimuth (Meeus eq. 13.5, turned to count from north): well defined at the poles too
const azimuth = fix360(Math.atan2(Math.sin(h), Math.cos(h) * Math.sin(la) - Math.tan(de) * Math.cos(la)) * DEG + 180);
const trueElevation = 90 - zenithTrue;
const elevation = opts.refraction === false ? trueElevation : trueElevation + refraction(trueElevation, opts);
return { azimuth, elevation, zenith: 90 - elevation, trueElevation, hourAngle: H, declination, equationOfTime };
}
// Unit vector towards the sun in world axes (x east, y north, z up).
export function sunDirection({ azimuth, elevation }) {
const a = azimuth * RAD, e = elevation * RAD;
return [Math.sin(a) * Math.cos(e), Math.cos(a) * Math.cos(e), Math.sin(e)];
}
// Solar noon at a longitude on the UTC day containing ms, as UTC milliseconds (two passes, since the
// equation of time is taken at noon itself).
export function solarNoon(lon, ms) {
const day = Math.floor(ms / DAY_MS) * DAY_MS;
let noon = day + (720 - 4 * lon) * MINUTE_MS;
for (let k = 0; k < 2; k++) noon = day + (720 - 4 * lon - sunPlace(noon).equationOfTime) * MINUTE_MS;
return Math.round(noon);
}
// Grid convergence (degrees) of a transverse Mercator grid at (lat, lon): true north minus grid north,
// first-order term gamma = (lon - lon0) * sin(lat). lon0 = -2 for the British national grid.
// Accurate to about 0.01 degree over Great Britain; grid azimuth = true azimuth - gamma.
export const gridConvergence = (lat, lon, lon0 = -2) => (lon - lon0) * Math.sin(lat * RAD);
// ---------------------------------------------------------------- date and time model (pure)
// State: { utcMs, stepMinutes }. Every action returns a new state; the input is never changed.
// Times are clamped to MIN_MS..MAX_MS, the range the method is stated for.
const clampMs = ms => Math.min(MAX_MS, Math.max(MIN_MS, Math.round(ms)));
export function timeState(utcMs, stepMinutes = 15) {
if (!Number.isFinite(utcMs)) throw Error('time state needs UTC milliseconds');
if (!(stepMinutes > 0)) throw Error('step must be a positive number of minutes');
return Object.freeze({ utcMs: clampMs(utcMs), stepMinutes });
}
// actions: { type: 'set', utcMs } | { type: 'date', year, month (1-12), day } keeps the time of day
// | { type: 'minuteOfDay', minute } keeps the date | { type: 'step', count } moves by count steps
// | { type: 'days', count } | { type: 'stepSize', minutes } | { type: 'solarNoon', lon }
export function applyTime(state, action = {}) {
const ms = state.utcMs, day = Math.floor(ms / DAY_MS) * DAY_MS, tod = ms - day;
const num = (v, what) => { if (!Number.isFinite(v)) throw Error(`${what} must be a number`); return v; };
switch (action.type) {
case 'set': return timeState(num(action.utcMs, 'time'), state.stepMinutes);
case 'date': {
const y = num(action.year, 'year'), m = num(action.month, 'month'), d = num(action.day, 'day');
if (m < 1 || m > 12 || d < 1 || d > 31) throw Error(`date ${y}-${m}-${d} is not a calendar date`);
const start = Date.UTC(y, m - 1, d);
if (new Date(start).getUTCDate() !== d) throw Error(`date ${y}-${m}-${d} does not exist`);
return timeState(start + tod, state.stepMinutes);
}
case 'minuteOfDay': {
const minute = Math.min(1439, Math.max(0, Math.round(num(action.minute, 'minute'))));
return timeState(day + minute * MINUTE_MS, state.stepMinutes);
}
case 'step': return timeState(ms + num(action.count ?? 1, 'count') * state.stepMinutes * MINUTE_MS, state.stepMinutes);
case 'days': return timeState(ms + num(action.count ?? 1, 'count') * DAY_MS, state.stepMinutes);
case 'stepSize': return timeState(ms, num(action.minutes, 'step'));
case 'solarNoon': return timeState(solarNoon(num(action.lon, 'longitude'), ms), state.stepMinutes);
default: throw Error(`unknown time action "${action.type}"`);
}
}
// What a date/time control shows: fields for inputs and a plain label.
export function timeView(state) {
const d = new Date(state.utcMs), p = (v, n = 2) => String(v).padStart(n, '0');
const year = d.getUTCFullYear(), month = d.getUTCMonth() + 1, day = d.getUTCDate();
const minuteOfDay = d.getUTCHours() * 60 + d.getUTCMinutes();
const dayOfYear = Math.floor((Date.UTC(year, month - 1, day) - Date.UTC(year, 0, 1)) / DAY_MS) + 1;
const date = `${p(year, 4)}-${p(month)}-${p(day)}`, time = `${p(d.getUTCHours())}:${p(d.getUTCMinutes())}`;
return { year, month, day, minuteOfDay, dayOfYear, date, time, label: `${date} ${time} UTC` };
}
// Everything the world needs for one moment at one place: position, direction and a status line.
export function sunAt(lat, lon, state, opts = {}) {
const pos = solarPosition(lat, lon, state.utcMs, opts);
const up = pos.elevation > 0;
const status = up
? `sun ${pos.elevation.toFixed(1)} deg up, bearing ${pos.azimuth.toFixed(1)} deg (${timeView(state).label})`
: `sun below the horizon (${timeView(state).label})`;
return { ...pos, direction: sunDirection(pos), up, status };
}Tour
A JavaScript module in the world folder of GlobalGrid2050 that creates recorder (`createRecorder`) and player (`createPlayer`), using SHA-256. It creates recorder (`createRecorder`) and creates player (`createPlayer`).
Set aside from the main view: 95% of its lines are the same as solar-design-studio/202609270439-site-world/world/tour.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 94% of lines shared with Tour; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9476 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270439-site-world/world/tour.mjs:1-291 31c2a4f473026ce5d9fa8471f410e07dc5954fb3
- sha256 110cda467c7467d28cc8af85270b06411e7316b45659a0be71114b31b3663103
- target sha256 57ae26ca4820271a5c8782081c0a11ab817dc4ad193b16d47e3c02d49cb008fe
- 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/tour.mjs · lines 1–281 of 281 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern createRecorder (shared by 2 files)
- What it does
- It calculates its inputs. Defines 23 functions or classes, including mm, rad, ms, turn, keyframe.
- 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
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- Downstream impact
- Used directly by 1 file: Project UI (globalgrid2050).
- What it achieves
- Tours: record a walk or a drone flight, play it back smoothly, save it, and present it.
- Why it matters
- Imported by Project UI.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- Origin (import)
- Used by
- imported by Project UI (import), mentioned in Standalone (comment link)
- Produces
- SCHEMA, PLAY_FPS, LIMITS, keyframe, createRecorder, makeTour, sha256, exportTour, importTour, compile, gridPoseAt, poseAt
- Defines here
- mm, rad, ms, turn, keyframe, createRecorder, push, pick, makeTour, body, sha256, exportTour, importTour, compile, hermite, gridPoseAt, at, poseAt, captionAt, createPlayer, show, draw, present
- 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/tour.mjs:1-281 · blob 59c81e629a422afeac7f46e260ed6e1fb68c67ea · 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
// Tours: record a walk or a drone flight, play it back smoothly, save it, and present it.
// Keyframes are held in British National Grid metres ({ e, n, z }), never in local metres, so a tour
// survives any origin rebase and plays the same on any machine. Playback is a pure function of the
// tour and the time: the same tour gives the same pose at the same time, every time.
// No DOM and no randomness; the caller supplies time, the origin and the frame gate.
import { toLocal, toBng } from './origin.mjs';
export const SCHEMA = 'world.tour.v1';
export const PLAY_FPS = 30;
const KINDS = ['walk', 'drone'];
// The national grid extent. Its south-west 10 km corner is open sea, so a point there is almost
// certainly local metres given by mistake and is refused too.
const GRID = { e: [0, 700000], n: [0, 1300000], sea: 10000 };
const HEX64 = /^[0-9a-f]{64}$/;
// A phone must be able to open any tour it is given, so files and their parts are capped by name.
export const LIMITS = Object.freeze({ fileBytes: 8 * 1024 * 1024, keyframes: 100000, caption: 280, name: 200 });
const TOP_FIELDS = ['schema', 'kind', 'name', 'keyframes', 'sha256'];
const KEY_FIELDS = ['t', 'e', 'n', 'z', 'yaw', 'pitch', 'caption', 'hold'];
// Quantise on the way in, so a saved tour reads back as the very same numbers (whole millimetres, no float noise).
const mm = x => Math.round(x * 1e3) / 1e3;
const rad = x => Math.round(x * 1e6) / 1e6;
const ms = x => Math.round(x * 1e3) / 1e3;
const TAU = 2 * Math.PI;
const turn = (from, to) => {
const d = (to - from) % TAU;
return d > Math.PI ? d - TAU : d < -Math.PI ? d + TAU : d;
};
// ---------- keyframes ----------
// One keyframe from a local pose and the origin it was taken under. Returns grid metres.
export function keyframe(t, origin, pose, { caption = '', hold = 0 } = {}) {
const g = toBng(origin, pose.pos[0], pose.pos[1]);
const k = { t: ms(t), e: mm(g.e), n: mm(g.n), z: mm(pose.pos[2]), yaw: rad(pose.yaw), pitch: rad(pose.pitch) };
if (caption) k.caption = String(caption);
if (hold > 0) k.hold = ms(hold);
return k;
}
// Recorder. sample() is called every frame with the time in seconds since recording began;
// a keyframe is kept at most every `every` seconds. mark() pins a caption (and an optional hold)
// to a keyframe taken at that moment. stop() returns the tour.
export function createRecorder({ kind = 'walk', name = '', every = 0.25 } = {}) {
if (!KINDS.includes(kind)) throw Error(`tour kind must be one of ${KINDS.join(', ')}`);
const frames = [];
let last = null;
const push = k => {
if (frames.length && k.t <= frames[frames.length - 1].t) {
if (k.caption || k.hold) Object.assign(frames[frames.length - 1], pick(k, ['caption', 'hold']));
return;
}
frames.push(k);
};
return {
sample(t, origin, pose) {
last = { t, origin: { ...origin }, pose: { pos: [...pose.pos], yaw: pose.yaw, pitch: pose.pitch } };
if (!frames.length || t - frames[frames.length - 1].t >= every) push(keyframe(t, origin, pose));
},
mark(caption, hold = 0) {
if (!last) throw Error('nothing recorded yet to caption');
push(keyframe(last.t, last.origin, last.pose, { caption, hold }));
},
count: () => frames.length,
stop() {
if (last && frames.length && last.t > frames[frames.length - 1].t) push(keyframe(last.t, last.origin, last.pose));
return makeTour({ kind, name, keyframes: frames });
}
};
}
const pick = (o, keys) => Object.fromEntries(keys.filter(k => o[k] !== undefined).map(k => [k, o[k]]));
// Build a tour in canonical form: fixed key order, times from zero, quantised values. Throws on bad input.
export function makeTour({ kind = 'walk', name = '', keyframes }) {
if (!KINDS.includes(kind)) throw Error(`tour kind must be one of ${KINDS.join(', ')}`);
if (!Array.isArray(keyframes) || keyframes.length < 2) throw Error('a tour needs at least two keyframes');
if (keyframes.length > LIMITS.keyframes) throw Error(`a tour has ${keyframes.length} keyframes, over the limit of ${LIMITS.keyframes}`);
if (String(name).length > LIMITS.name) throw Error(`the tour name is over ${LIMITS.name} characters`);
const t0 = keyframes[0].t;
const out = keyframes.map((k, i) => {
for (const f of ['t', 'e', 'n', 'z', 'yaw', 'pitch']) {
if (!Number.isFinite(k[f])) throw Error(`keyframe ${i}: ${f} is not a finite number`);
}
if ('x' in k || 'y' in k || 'pos' in k) throw Error(`keyframe ${i}: local coordinates are not accepted; use grid e and n`);
if (k.e < GRID.e[0] || k.e > GRID.e[1] || k.n < GRID.n[0] || k.n > GRID.n[1] || (k.e < GRID.sea && k.n < GRID.sea)) {
throw Error(`keyframe ${i}: ${k.e}, ${k.n} is not on the national grid (local metres?)`);
}
if (k.hold !== undefined && !(k.hold >= 0 && Number.isFinite(k.hold))) throw Error(`keyframe ${i}: hold must be zero or more`);
if (k.caption && String(k.caption).length > LIMITS.caption) throw Error(`keyframe ${i}: caption is over ${LIMITS.caption} characters`);
const c = { t: ms(k.t - t0), e: mm(k.e), n: mm(k.n), z: mm(k.z), yaw: rad(k.yaw), pitch: rad(k.pitch) };
if (k.caption) c.caption = String(k.caption);
if (k.hold > 0) c.hold = ms(k.hold);
return c;
});
for (let i = 1; i < out.length; i++) {
if (!(out[i].t > out[i - 1].t)) throw Error(`keyframe ${i}: time must increase`);
}
return { schema: SCHEMA, kind, name: String(name), keyframes: out };
}
// ---------- JSON with a SHA-256 ----------
const body = tour => JSON.stringify({ schema: SCHEMA, kind: tour.kind, name: tour.name, keyframes: tour.keyframes });
export async function sha256(text) {
const bytes = new TextEncoder().encode(text);
const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes);
return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('');
}
// The hash covers the canonical body (everything but the hash itself), so re-exporting is stable.
export async function exportTour(tour) {
const t = makeTour(tour);
const sha = await sha256(body(t));
return JSON.stringify({ ...t, sha256: sha }, null, 1);
}
// Parse, check the schema and the hash, and return the tour. Throws with a plain reason on any fault.
export async function importTour(text) {
const bytes = new TextEncoder().encode(String(text)).length;
if (bytes > LIMITS.fileBytes) throw Error(`tour file is ${bytes} bytes, over the limit of ${LIMITS.fileBytes}`);
let raw;
try { raw = JSON.parse(String(text).replace(/^/, '')); } catch { throw Error('tour file is not valid JSON'); }
if (raw?.schema !== SCHEMA) throw Error(`tour file schema is not ${SCHEMA}`);
const extra = Object.keys(raw).filter(k => !TOP_FIELDS.includes(k));
if (extra.length) throw Error(`tour file has unexpected fields: ${extra.join(', ')}`);
if (!HEX64.test(String(raw.sha256 ?? '').toLowerCase())) throw Error('tour file has no valid sha256');
const t = makeTour(raw);
raw.keyframes.forEach((k, i) => {
const odd = Object.keys(k).filter(f => !KEY_FIELDS.includes(f));
if (odd.length) throw Error(`keyframe ${i} has unexpected fields: ${odd.join(', ')}`);
});
const sha = await sha256(body(t));
if (sha !== raw.sha256.toLowerCase()) throw Error('tour file sha256 does not match its contents');
return t;
}
// ---------- playback ----------
// Compile a tour into a timeline. Holds become a second keyframe in the same place; the first, last,
// captioned and held keyframes are stops, where the camera comes to rest as it does on arrival.
export function compile(tour) {
const src = tour.keyframes;
const pts = [];
let shift = 0, yaw = src[0].yaw;
src.forEach((k, i) => {
yaw = i ? yaw + turn(pts[pts.length - 1].raw, k.yaw) : k.yaw; // unwrap, so each step turns the short way
const stop = i === 0 || i === src.length - 1 || !!k.caption || k.hold > 0;
const p = { t: k.t + shift, v: [k.e, k.n, k.z, yaw, k.pitch], raw: k.yaw, stop, caption: k.caption || '', src: i };
pts.push(p);
if (k.hold > 0) { shift += k.hold; pts.push({ ...p, t: k.t + shift, caption: '', held: true }); }
});
// Tangents: zero at stops, otherwise the time-weighted Catmull-Rom slope through the neighbours.
for (let i = 0; i < pts.length; i++) {
const a = pts[i - 1], b = pts[i], c = pts[i + 1];
b.m = b.stop || !a || !c ? [0, 0, 0, 0, 0] : b.v.map((_, j) => (c.v[j] - a.v[j]) / (c.t - a.t));
}
const captions = pts.filter(p => p.caption).map(p => ({ t: p.t, text: p.caption, keyframe: p.src }));
const stops = pts.filter(p => p.stop && !p.held).map(p => p.t);
return Object.freeze({ tour, pts, captions, stops, duration: pts[pts.length - 1].t });
}
// Cubic Hermite between two points with the given tangents; u in [0, 1], h the span in seconds.
function hermite(a, b, u, h, j) {
const u2 = u * u, u3 = u2 * u;
return (2 * u3 - 3 * u2 + 1) * a.v[j] + (u3 - 2 * u2 + u) * h * a.m[j] + (-2 * u3 + 3 * u2) * b.v[j] + (u3 - u2) * h * b.m[j];
}
// The pose at time t (seconds from the start) in grid metres: { e, n, z, yaw, pitch }.
// Times before the start or after the end give the first or last pose exactly.
export function gridPoseAt(line, t) {
const p = line.pts;
const at = v => ({ e: v[0], n: v[1], z: v[2], yaw: v[3], pitch: v[4] });
if (!(t > p[0].t)) return at(p[0].v);
if (t >= line.duration) return at(p[p.length - 1].v);
let lo = 0, hi = p.length - 1; // binary search: p[lo].t <= t < p[hi].t
while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (p[mid].t <= t) lo = mid; else hi = mid; }
const a = p[lo], b = p[hi], h = b.t - a.t, u = (t - a.t) / h;
return at(a.v.map((_, j) => hermite(a, b, u, h, j)));
}
// The same pose in local metres under the current origin, ready for the camera: { pos, yaw, pitch }.
export function poseAt(line, t, origin) {
const g = gridPoseAt(line, t);
const [x, y] = toLocal(origin, g.e, g.n);
return { pos: [x, y, g.z], yaw: g.yaw, pitch: g.pitch };
}
// The caption showing at time t: from its keyframe until the next captioned keyframe, or `showFor`
// seconds, whichever is sooner. Returns { text, index } or null.
export function captionAt(line, t, { showFor = 6 } = {}) {
const cs = line.captions;
for (let i = cs.length - 1; i >= 0; i--) {
if (cs[i].t <= t) {
const until = Math.min(cs[i + 1]?.t ?? Infinity, cs[i].t + showFor);
return t < until ? { text: cs[i].text, index: i } : null;
}
}
return null;
}
// ---------- player and presentation ----------
// Player. apply(pose, t) receives the local pose for each drawn frame; getOrigin() gives the current
// origin. gate is a frame gate (frame-gate.mjs): while playing it runs at 30 fps at most, and when
// paused or finished it is told to stop, so an idle tour draws nothing at all.
// The caller's draw routine calls player.frame(now); now is in milliseconds, as from the gate.
export function createPlayer(tour, { gate, getOrigin, apply = () => {}, onCaption = () => {}, onEnd = () => {}, clock = () => performance.now(), showFor = 6 } = {}) {
const line = compile(tour);
let playing = false, t = 0, startedAt = 0, shown;
const show = () => {
const c = captionAt(line, t, { showFor });
const key = c ? c.index : -1;
if (key !== shown) { shown = key; onCaption(c ? c.text : '', c); }
};
const draw = () => { apply(poseAt(line, t, getOrigin()), t); show(); };
const self = {
line,
get playing() { return playing; },
get time() { return t; },
play() {
if (playing) return;
if (t >= line.duration) t = 0;
playing = true; startedAt = clock() - t * 1000;
gate?.setMoving(true, PLAY_FPS);
},
pause() {
if (!playing) return;
t = Math.min(line.duration, (clock() - startedAt) / 1000);
playing = false;
gate?.setMoving(false);
gate?.invalidate(); // one last frame at the exact paused time, then nothing
},
toggle() { playing ? self.pause() : self.play(); },
// Jump to a time in seconds; keeps playing if it was.
seek(s) {
if (!Number.isFinite(s)) return; // a bad time is ignored, never played forever
t = Math.max(0, Math.min(line.duration, s));
if (playing) startedAt = clock() - t * 1000;
else gate?.invalidate();
},
// Presentation steps: go to the next or previous stop (a captioned or held keyframe, or an end).
next() { const s = line.stops.find(x => x > t + 1e-9); self.seek(s ?? line.duration); },
previous() { const s = [...line.stops].reverse().find(x => x < t - 1e-9); self.seek(s ?? 0); },
// Called from the gate's draw. Works out the tour time from the clock, applies the pose.
frame(now = clock()) {
if (!Number.isFinite(now)) now = clock();
if (playing) {
t = Math.min(line.duration, (now - startedAt) / 1000);
if (t >= line.duration) { playing = false; gate?.setMoving(false); draw(); onEnd(); return; }
}
draw();
}
};
return self;
}
// Presentation mode: play a saved tour for a meeting. Takes the tour file's text, checks its hash,
// and returns a player whose captions go to captionEl (any object with textContent and hidden) or
// onCaption. Keys: space plays or pauses, right and left arrows step between stops, Escape ends.
export async function present(text, { captionEl, onCaption, onExit = () => {}, autoplay = true, ...opts } = {}) {
const tour = await importTour(text);
const player = createPlayer(tour, {
...opts,
onCaption(textNow, c) {
if (captionEl) { captionEl.textContent = textNow; captionEl.hidden = !textNow; }
onCaption?.(textNow, c);
}
});
player.key = code => {
if (code === ' ' || code === 'Space') player.toggle();
else if (code === 'ArrowRight') player.next();
else if (code === 'ArrowLeft') player.previous();
else if (code === 'Escape') { player.pause(); onExit(); }
else return false;
return true;
};
if (autoplay) player.play();
return player;
}Xr Pose
A JavaScript module in the world folder of GlobalGrid2050 that converts to world (`toWorld`), snaps turn (`snapTurn`) and reads controllers (`readControllers`).
ingestglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/xr-pose.mjs · lines 1–160 of 160 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern rotate (shared by 3 files)
- What it does
- It lists and searches its content. Defines 21 functions or classes, including xrToWorld, rotYaw, rotate, dirToWorld, toWorld.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Downstream impact
- Used directly by 1 file: Xr (globalgrid2050).
- What it achieves
- It turns about (`turnAbout`), snaps turn (`snapTurn`) and reads controllers (`readControllers`). Headset view pose maths. Pure: no DOM, no WebXR objects, only plain numbers and arrays. Its code works with 72 Hz.
- Why it matters
- Imported by Xr.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- Views (import), Camera (import), Device Budget (import)
- Used by
- imported by Xr (import), mentioned in Standalone (comment link)
- Produces
- SNAP, SNAP_ON, DEADZONE, MIN_FRAME_RATE, xrToWorld, rotYaw, rotate, dirToWorld, toWorld, eyeMatrix, headLook, turnAbout
- Defines here
- xrToWorld, rotYaw, rotate, dirToWorld, toWorld, eyeMatrix, headLook, turnAbout, snapTurn, deadzone, readControllers, pressed, movementInput, settle, locomote, enterRig, leaveRig, chooseFrameRate, headsetBudget, adjustHeadset, wrap
- 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/xr-pose.mjs:1-160 · blob db7f963f81df2ff97778435150bd96cdbc639699 · 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
// Headset view pose maths. Pure: no DOM, no WebXR objects, only plain numbers and arrays.
// WebXR reference space: x right, y up, z towards the viewer (right-handed), metres.
// World: x east, y north, z up, metres (as camera.mjs). The rig is where the reference space's origin
// sits in the world, in float64, plus a yaw (as views.mjs: 0 looks north, +π/2 looks east).
// The headset reports the head and each eye relative to the rig; the thumbstick and snap turn move the rig.
// Drawing stays camera-relative per eye: each eye gets a rotation-only matrix and its own world position,
// and lines.mjs moves each batch by (batch origin - that eye) in doubles, exactly as on the flat screen.
import { VIEWS, step, AERIAL_MIN_CLEARANCE, PITCH_LIMIT } from './views.mjs';
import { multiply } from './camera.mjs';
import { initialBudget, adjust } from './device-budget.mjs';
export const SNAP = Math.PI / 6; // 30 degrees per flick: a common comfortable snap
export const SNAP_ON = 0.7, SNAP_OFF = 0.3; // flick past 0.7 to turn; return inside 0.3 before the next
export const DEADZONE = 0.15;
export const MIN_FRAME_RATE = 72; // the lowest rate headsets treat as comfortable
// Reference-space axes to world axes: right stays east, up becomes z, towards-the-viewer becomes south.
export const xrToWorld = ([x, y, z]) => [x, -z, y];
// Turns a world vector clockwise seen from above by yaw, so north becomes (sin yaw, cos yaw).
export function rotYaw(yaw, [x, y, z]) {
const c = Math.cos(yaw), s = Math.sin(yaw);
return [c * x + s * y, -s * x + c * y, z];
}
// Rotates vector v by unit quaternion q = [x, y, z, w].
export function rotate([qx, qy, qz, qw], [vx, vy, vz]) {
const tx = 2 * (qy * vz - qz * vy), ty = 2 * (qz * vx - qx * vz), tz = 2 * (qx * vy - qy * vx);
return [vx + qw * tx + (qy * tz - qz * ty), vy + qw * ty + (qz * tx - qx * tz), vz + qw * tz + (qx * ty - qy * tx)];
}
// A direction in the reference space as a world direction.
export const dirToWorld = (rig, v) => rotYaw(rig.yaw, xrToWorld(v));
// A point in the reference space as world metres, in doubles.
export function toWorld(rig, p) {
const d = dirToWorld(rig, p);
return [rig.pos[0] + d[0], rig.pos[1] + d[1], rig.pos[2] + d[2]];
}
// The matrix for one eye: its projection times a rotation-only view (the eye sits at [0, 0, 0]).
// Rows of the view are the eye's right, up and back axes in world terms, the layout camera.mjs view() uses.
export function eyeMatrix(projection, rig, orientation) {
const r = dirToWorld(rig, rotate(orientation, [1, 0, 0]));
const u = dirToWorld(rig, rotate(orientation, [0, 1, 0]));
const b = dirToWorld(rig, rotate(orientation, [0, 0, 1]));
const v = new Float32Array(16);
v[0] = r[0]; v[4] = r[1]; v[8] = r[2];
v[1] = u[0]; v[5] = u[1]; v[9] = u[2];
v[2] = b[0]; v[6] = b[1]; v[10] = b[2];
v[15] = 1;
return multiply(projection, v);
}
// Where the head looks, as views.mjs yaw and pitch in the world.
export function headLook(rig, orientation) {
const f = dirToWorld(rig, rotate(orientation, [0, 0, -1]));
const pitch = Math.asin(Math.max(-1, Math.min(1, f[2])));
return { yaw: Math.atan2(f[0], f[1]), pitch: Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, pitch)) };
}
// Turns the rig by dYaw about the head, so the head stays exactly where it is in the world.
export function turnAbout(rig, head, dYaw) {
const h = toWorld(rig, head), yaw = wrap(rig.yaw + dYaw), d = rotYaw(yaw, xrToWorld(head));
return { ...rig, yaw, pos: [h[0] - d[0], h[1] - d[1], rig.pos[2]] };
}
// Snap turning with hysteresis: one step per flick, re-armed only once the stick is back near the centre.
// Stick right (x > 0) turns right, i.e. yaw increases. Returns { armed, turn } with turn in radians.
export function snapTurn(armed, x, { step: size = SNAP, on = SNAP_ON, off = SNAP_OFF } = {}) {
if (armed && Math.abs(x) >= on) return { armed: false, turn: Math.sign(x) * size };
if (!armed && Math.abs(x) < off) return { armed: true, turn: 0 };
return { armed, turn: 0 };
}
// Rescales past the dead zone so a small drift reads 0 and full tilt still reads 1.
export function deadzone(v, dz = DEADZONE) {
if (!Number.isFinite(v) || Math.abs(v) <= dz) return 0;
return Math.sign(v) * Math.min(1, (Math.abs(v) - dz) / (1 - dz));
}
// Controllers as plain objects: [{ handedness, gamepad: { axes, buttons: [{ pressed }] } }].
// The xr-standard mapping puts the thumbstick on axes 2 and 3 (0 and 1 are a touchpad); a two-axis pad is
// read from 0 and 1. Stick up reads negative. Returns sticks per hand and the buttons that matter.
export function readControllers(sources) {
const out = { left: [0, 0], right: [0, 0], toggle: false, slow: false };
for (const s of sources || []) {
const g = s && s.gamepad;
if (!g || (s.handedness !== 'left' && s.handedness !== 'right')) continue;
const a = g.axes || [], i = a.length >= 4 ? 2 : 0;
out[s.handedness] = [deadzone(a[i]), deadzone(a[i + 1])];
const pressed = n => !!(g.buttons && g.buttons[n] && g.buttons[n].pressed);
if (s.handedness === 'right' && pressed(4)) out.toggle = true; // A: Walk / Drone
if (s.handedness === 'left' && pressed(1)) out.slow = true; // left grip: slow and precise
}
return out;
}
// Controllers to the same movement input the flat screen uses. Left stick walks and strafes; in Drone the
// right stick's up and down climbs and descends. Turning is by snap only, so it is not part of this.
export function movementInput(c, view) {
return {
forward: -c.left[1], strafe: c.left[0], slow: c.slow,
rise: VIEWS[view] && VIEWS[view].eye === null ? -c.right[1] : 0
};
}
// The rig's height rule. lift: how far the reference origin sits above the ground in Walk (0 for a floor-
// level space, the standing eye height for a head-level one). Walk is ground-locked under the head; a drone
// keeps its height but never lets the head come closer to the ground than the drone's clearance.
export function settle(rig, head, view, heightAt, lift) {
const h = toWorld(rig, head), g = heightAt(h[0], h[1]);
if (!Number.isFinite(g)) return rig;
if (VIEWS[view].eye !== null) return { ...rig, pos: [rig.pos[0], rig.pos[1], g + lift] };
const low = g + AERIAL_MIN_CLEARANCE - h[2];
return low > 0 ? { ...rig, pos: [rig.pos[0], rig.pos[1], rig.pos[2] + low] } : rig;
}
// One movement step, reusing views.mjs step(): same speeds (Walk 8 m/s, Drone 25 m/s), same solids and
// sliding. Movement follows where the head looks; the rig moves by however far step() moved the head.
export function locomote(rig, head, orientation, input, dt, view, heightAt, solids = [], lift = 0) {
if (!(dt > 0) || !(input.forward || input.strafe || input.rise)) return settle(rig, head, view, heightAt, lift);
const h = toWorld(rig, head), v = VIEWS[view], { yaw } = headLook(rig, orientation);
const from = [h[0], h[1], v.eye === null ? h[2] : heightAt(h[0], h[1]) + v.eye];
const next = step({ view, pos: from, yaw, pitch: 0 }, input, dt, heightAt, solids).pos;
const dz = v.eye === null ? next[2] - from[2] : 0;
const moved = { ...rig, pos: [rig.pos[0] + next[0] - from[0], rig.pos[1] + next[1] - from[1], rig.pos[2] + dz] };
return settle(moved, head, view, heightAt, lift);
}
// Entering: the head appears where the flat-screen viewer stood, looking the same way.
export function enterRig(state, head, orientation, heightAt, lift) {
const local = headLook({ pos: [0, 0, 0], yaw: 0 }, orientation).yaw;
const yaw = wrap(state.yaw - local), d = rotYaw(yaw, xrToWorld(head));
const rig = { pos: [state.pos[0] - d[0], state.pos[1] - d[1], state.pos[2] - d[2]], yaw };
return settle(rig, head, state.view, heightAt, lift);
}
// Leaving: the flat-screen viewer takes over where the head was, looking where it looked.
export function leaveRig(rig, head, orientation, view) {
const { yaw, pitch } = headLook(rig, orientation);
return { view, pos: toWorld(rig, head), yaw, pitch };
}
// Frame rate: the lowest the headset offers at or above 72 Hz (less heat, more time per frame);
// null to leave the headset's own choice when it offers none.
export function chooseFrameRate(supported, floor = MIN_FRAME_RATE) {
const rates = Array.from(supported || []).filter(r => Number.isFinite(r) && r > 0).sort((a, b) => a - b);
if (!rates.length) return null;
return rates.find(r => r >= floor) ?? rates[rates.length - 1];
}
// Resolution budget for a headset: a headset must get a frame every refresh, so frames are never skipped;
// instead the eye buffers shrink (down to half) when frames run late and grow back when they keep up.
// Reuses device-budget.mjs with a cap of the headset's own recommended size (scale 1).
export const headsetBudget = () => initialBudget(1);
export const adjustHeadset = (b, intervalMs, frameRate) => adjust(b, intervalMs, 1000 / (frameRate || MIN_FRAME_RATE));
const wrap = a => Math.atan2(Math.sin(a), Math.cos(a));