File size: 13,023 Bytes
966b234 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | // The recording's own controller: what its inputs do to a first-person camera, as measured from the footage
// (controller.json; scripts/probe.py steps the same numbers in Python).
//
// import { loadController } from './controller.js';
// const player = await loadController('./'); // reads controller.json beside the page
// player.step(dt); player.apply(camera); // every frame; reads the keyboard and a gamepad's sticks
//
// `player.state` is {x, z, yaw, pitch, vx, vz, turning, pitching} in metres, radians and their rates: the origin is on the floor under the
// first frame's camera, which looks along -z; yaw is positive to the right. In third person (`player.numbers.view`
// is "third") x and z are where the character stands, the origin is under the character in the first frame, yaw
// and pitch are still the camera's and the movement keys go by them; `apply` puts the camera on its arm: round a
// pivot `pivot_m` over the character's feet, `orbit_m` behind it and `shoulder_m` to its right along the camera's
// own axes.
//
// Where controller.json names a `heading_track` the recording's view followed something else than the look inputs
// (it was locked onto an enemy, or turned by a mouse): the file beside it holds where the camera faced (t, yaw,
// pitch) and the camera faces as it says, in step with the keys the way scripts/probe.py has it (the state of
// second u faces as the recording's frame of u less the lead did), so a replay of the recording's keys comes
// out as recorded. A game that knows what the view follows sets `player.heading` to a function
// (state, seconds) => [yaw, pitch] or null: its answer is where the camera faces (null: as the file says, or
// without one as the look inputs do), with `seconds` the time on the keys' clock of the state it is asked about.
//
// A vehicle (`drive` in controller.json, scripts/probe.py's poses() says what its numbers are): the forward and
// back keys are the pedals and the turning keys the wheel; `state.speed` is its speed along its own heading
// `state.car_yaw` (negative: reversing), `state.steer` how far the wheel is turned (-1..1), x and z where it is,
// and yaw and pitch still the camera's, on its arm behind the vehicle and following its heading.
//
// `cuts` in controller.json (a recording whose picture jumps: scripts/splat/cuts.py) are moments on the keys'
// clock with where the state is then; the state is put there when the clock passes one (`state.take` counts
// them). A game that is not replaying the recording empties `player.numbers.cuts`, or jumps by itself.
//
// A mouse turns the camera too, where the recording's did (`mouse_yaw_deg` and `mouse_pitch_deg` in
// controller.json: degrees a count to the right and a count down, signed): mousemove counts (movementX,
// movementY) while the pointer is locked, which a click on the page asks for when the controller has those
// numbers, and the moves a replay dispatches (not the user's own, so they count without the lock: a replay
// cannot take it). `player.mouse(dx, dy)` adds counts from anywhere else. The walker is kept out of the solid
// cells of walls.json (`player.solid`: "i,j" keys of floor-plan cells); a game adds its own collisions by
// correcting state.x and state.z after step(). `apply` sets a three.js camera, including the lead: the
// recording's picture runs `lead_frames` ahead of its keys (negative: behind), and a replay has to as well;
// `page_lead_frames` is added to it: how far a page lags the recording when the same keys are replayed into it.
//
// `apply` is also how a build is looked at from where the recording never stood: opened with
// `?pose=x,y,z,yaw_deg,pitch_deg` it puts the camera there and leaves it. Keep `player.apply(camera)` as the
// one thing that places the camera (correct `player.state` for collisions, do not set the camera yourself).
export async function loadController(base = './') {
const C = await fetch(base + 'controller.json').then(r => r.json());
const keys = new Set();
addEventListener('keydown', e => keys.add(e.code)); addEventListener('keyup', e => keys.delete(e.code));
const role = { forward: 'KeyW', back: 'KeyS', left: 'KeyA', right: 'KeyD', turn_left: 'ArrowLeft', turn_right: 'ArrowRight', look_up: 'ArrowUp', look_down: 'ArrowDown', sprint: 'ShiftLeft', ...(C.keys || {}) };
const held = (a, b) => (keys.has(role[a]) ? 1 : 0) - (keys.has(role[b]) ? 1 : 0);
const PLACED = (new URLSearchParams(location.search).get('pose') || '').split(',').map(Number);
const LEAD = +(C.lead_frames || 0) + +(C.page_lead_frames || 0), TURN = C.turn_deg_s * Math.PI / 180, PITCH = C.pitch_deg_s * Math.PI / 180, past = [];
const state = { x: 0, z: 0, yaw: 0, pitch: 0, vx: 0, vz: 0, turning: 0, pitching: 0, speed: 0, car_yaw: 0, steer: 0, take: 0 };
const D = C.drive;
// A gamepad's sticks beside the keys: a stick past its dead zone overrides that stick's keys and gives a
// part of the full rate (dead zone, curve and which way each axis counts are in controller.json).
const DEAD = C.stick_dead ?? 0.1, POWER = C.stick_power ?? 1, SIGNS = C.stick_signs || [1, 1, 1, 1];
const curve = v => Math.abs(v) <= DEAD ? 0 : Math.sign(v) * ((Math.abs(v) - DEAD) / (1 - DEAD)) ** POWER;
// What stands in the walker's way, where the build has a map of it (walls.json: the solid cells of the floor plan
// and the walker's radius, from the splats). `player.solid` is a Set of "i,j": add to it or delete from it as a game needs.
const WALLS = await fetch(base + 'walls.json').then(r => r.ok ? r.json() : null).catch(() => null) || { cell: 1, radius: 0, solid: [] };
const CELL = WALLS.cell, WIDE = WALLS.radius, solid = new Set(WALLS.solid.map(([i, j]) => i + ',' + j));
function pushed(q) { // out of the solid cells within reach (twice, so corners settle)
for (let pass = 0; pass < (solid.size ? 2 : 0); pass++)
for (let i = Math.floor((q.x - WIDE) / CELL); i <= Math.floor((q.x + WIDE) / CELL); i++)
for (let j = Math.floor((q.z - WIDE) / CELL); j <= Math.floor((q.z + WIDE) / CELL); j++) {
const nx = Math.min(Math.max(q.x, i * CELL), (i + 1) * CELL), nz = Math.min(Math.max(q.z, j * CELL), (j + 1) * CELL), gap = Math.hypot(q.x - nx, q.z - nz);
if (solid.has(i + ',' + j) && gap > 1e-9 && gap < WIDE) { q.x = nx + (q.x - nx) / gap * WIDE; q.z = nz + (q.z - nz) / gap * WIDE; }
}
}
function sticks() {
const pad = [...(navigator.getGamepads ? navigator.getGamepads() : [])].find(p => p && p.axes && p.axes.length >= 4);
return pad ? pad.axes.slice(0, 4).map((v, i) => curve(v * SIGNS[i])) : [0, 0, 0, 0];
}
// Where the camera faced in the recording, when that was not the look inputs' doing (heading.json: t, yaw, pitch).
const TRACK = C.heading_track ? await fetch(base + C.heading_track).then(r => r.ok ? r.json() : null).catch(() => null) : null;
function tracked(t) {
const T = TRACK.t, last = T.length - 1;
if (t <= T[0] || last < 1) return [TRACK.yaw[0], TRACK.pitch[0]];
if (t >= T[last]) return [TRACK.yaw[last], TRACK.pitch[last]];
let a = 0, b = last;
while (b - a > 1) { const m = (a + b) >> 1; if (T[m] <= t) a = m; else b = m; }
const u = (t - T[a]) / (T[b] - T[a] || 1);
return [TRACK.yaw[a] + (TRACK.yaw[b] - TRACK.yaw[a]) * u, TRACK.pitch[a] + (TRACK.pitch[b] - TRACK.pitch[a]) * u];
}
let clock = 0, now = 0; // seconds stepped so far, and the second the state is of
const MOUSE = [(C.mouse_yaw_deg || 0) * Math.PI / 180, (C.mouse_pitch_deg || 0) * Math.PI / 180]; let moved = [0, 0]; // radians a count; counts since the last step
addEventListener('mousemove', e => { if (document.pointerLockElement || !e.isTrusted) { moved[0] += e.movementX; moved[1] += e.movementY; } });
if (MOUSE[0] || MOUSE[1]) addEventListener('mousedown', e => { const c = document.querySelector('canvas'); if (e.isTrusted && c && !document.pointerLockElement) c.requestPointerLock?.(); });
function advance(q, dt, seconds, counts = [0, 0]) {
const [lx, ly, rx, ry] = sticks(), CUTS = C.cuts || [];
while (q.take < CUTS.length && seconds >= CUTS[q.take].t + (C.lead_frames || 0) / 30 - 1e-6) {
const to = CUTS[q.take++], turn = to.yaw - q.yaw, c = Math.cos(turn), s = Math.sin(turn);
q.x = to.x; q.z = to.z; q.yaw = to.yaw; q.pitch = to.pitch ?? q.pitch; q.car_yaw += turn; [q.vx, q.vz] = [q.vx * c - q.vz * s, q.vz * c + q.vx * s];
}
let k = Math.min(1, (C.look_response_per_s || 30) * dt);
q.turning += ((rx || held('turn_right', 'turn_left')) * TURN - q.turning) * k;
q.pitching += ((-ry || held('look_up', 'look_down')) * PITCH - q.pitching) * k;
let faces = player.heading ? player.heading(q, seconds) : null;
if (faces) faces = [q.yaw + Math.atan2(Math.sin(faces[0] - q.yaw), Math.cos(faces[0] - q.yaw)), faces[1]]; // (the same turn of the circle)
else if (TRACK) faces = tracked(seconds - (C.lead_frames || 0) / 30);
if (D) { // a vehicle: pedals and wheel, the camera following its heading
const pedal = -ly || held('forward', 'back'), wheel = lx || held('turn_right', 'turn_left') || held('right', 'left');
const [toward, rate] = pedal > 0 ? [D.top_m_s * pedal, q.speed >= 0 ? D.accel_per_s : D.brake_per_s]
: pedal < 0 ? [D.reverse_m_s * pedal, q.speed > 0 ? D.brake_per_s : D.accel_per_s] : [0, D.coast_per_s];
q.speed += (toward - q.speed) * Math.min(1, rate * dt);
q.steer += (wheel - q.steer) * Math.min(1, (D.steer_per_s || 30) * dt);
const follow = Math.min(1, (D.follow_per_s || 30) * dt);
if (faces && follow > 0) { q.car_yaw = q.yaw + (faces[0] - q.yaw) / follow; q.yaw = faces[0]; q.pitch = faces[1]; }
else {
q.car_yaw += q.steer * Math.sign(q.speed) * Math.min(Math.abs(q.speed) / D.turn_radius_m, (D.turn_deg_s || 1e9) * Math.PI / 180) * dt;
q.yaw += (q.car_yaw - q.yaw) * follow; q.pitch = (D.pitch_deg || 0) * Math.PI / 180;
}
q.vx = Math.sin(q.car_yaw) * q.speed; q.vz = -Math.cos(q.car_yaw) * q.speed;
q.x += q.vx * dt; q.z += q.vz * dt; pushed(q);
return;
}
let turned = q.turning * dt + counts[0] * MOUSE[0], tilted = q.pitching * dt + counts[1] * MOUSE[1];
if (faces && dt > 0) { q.turning = (faces[0] - q.yaw) / dt; q.pitching = (faces[1] - q.pitch) / dt; turned = q.turning * dt; tilted = q.pitching * dt; }
q.yaw += turned;
q.pitch = Math.max(-1.4, Math.min(1.4, q.pitch + tilted));
const f = -ly || held('forward', 'back'), r = lx || held('right', 'left'), speed = keys.has(role.sprint) && f > 0 ? (C.sprint_m_s || C.walk_m_s) : C.walk_m_s;
k = Math.min(1, (C.response_per_s || 30) * dt);
if (C.velocity_turns) { // the speed built up so far turns with the camera
const a = turned, c = Math.cos(a), s = Math.sin(a); [q.vx, q.vz] = [q.vx * c - q.vz * s, q.vz * c + q.vx * s];
}
q.vx += ((Math.sin(q.yaw) * f + Math.cos(q.yaw) * r) * speed - q.vx) * k; q.vz += ((-Math.cos(q.yaw) * f + Math.sin(q.yaw) * r) * speed - q.vz) * k;
q.x += q.vx * dt; q.z += q.vz * dt; pushed(q);
}
function shown() {
let q = { ...state };
if (LEAD > 0) { for (let i = 0; i < Math.floor(LEAD); i++) advance(q, 1 / 30, now + (i + 1) / 30); if (LEAD % 1) advance(q, (LEAD % 1) / 30, now + LEAD / 30); } // ahead: carry on with the keys as they are
if (LEAD < 0) { // behind: where the camera was that many frames ago
const at = Math.max(0, past.length - 1 + LEAD), a = past[Math.floor(at)], b = past[Math.min(past.length - 1, Math.floor(at) + 1)], u = at % 1;
if (a.take !== b.take) q = { ...(u >= 0.5 ? b : a) };
else for (const k in q) q[k] = a[k] + (b[k] - a[k]) * u;
}
return q;
}
const player = {
numbers: C, state, keys, solid, heading: null,
mouse(dx, dy) { moved[0] += dx; moved[1] += dy; },
step(dt) { now = clock; clock += dt; const counts = moved; moved = [0, 0]; advance(state, dt, now, counts); if (LEAD < 0) { past.push({ ...state }); if (past.length > Math.ceil(-LEAD) + 1) past.shift(); } },
shown,
apply(camera) {
camera.rotation.order = 'YXZ';
if (PLACED.length === 5 && PLACED.every(Number.isFinite)) {
camera.rotation.set(PLACED[4] * Math.PI / 180, -PLACED[3] * Math.PI / 180, 0); camera.position.set(PLACED[0], PLACED[1], PLACED[2]);
return;
}
const q = shown(); camera.rotation.set(q.pitch, -q.yaw, 0);
if (C.view !== 'third') { camera.position.set(q.x, C.eye_m, q.z); return; }
const orbit = C.orbit_m || 0, shoulder = C.shoulder_m || 0, cy = Math.cos(q.yaw), sy = Math.sin(q.yaw), cp = Math.cos(q.pitch);
camera.position.set(q.x + shoulder * cy - orbit * sy * cp, (C.pivot_m ?? C.eye_m) - orbit * Math.sin(q.pitch), q.z + shoulder * sy + orbit * cy * cp);
},
};
return player;
}
|