SOURCE / PINNED RELEASE
Made of little things.
Faultline
- Release
- da1ffaa5624c…
- Author-recorded commit
- 60f5f03189db…
- License
- LICENSE
- Author’s source reference
- nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-6932b12c78c
Archive hash verified: 5a2e0492417ec4e7…. The source-to-build association is the author’s claim; it has not been independently rebuilt.
import { clamp } from './maps';
import { settings } from './napplet-settings';
import {
AIM,
DUCK,
FIRE,
JUMP,
RELOAD,
SPRINT,
THROW,
PRIMARY,
SECONDARY,
LEAN_LEFT,
LEAN_RIGHT,
type Input,
type Player,
} from './simulation';
const keyFlags: Record<string, number> = {
Digit1: PRIMARY,
Digit2: SECONDARY,
KeyF: FIRE,
KeyV: AIM,
Space: JUMP,
KeyC: DUCK,
KeyQ: LEAN_LEFT,
KeyE: LEAN_RIGHT,
KeyR: RELOAD,
KeyG: THROW,
ShiftLeft: SPRINT,
ShiftRight: SPRINT,
};
const padFlags = [JUMP, 0, RELOAD, 0, THROW, 0, AIM, FIRE, 0, 0, SPRINT, 0, PRIMARY, SECONDARY, LEAN_LEFT, LEAN_RIGHT];
const tapFlags: Record<string, number> = {
fire: FIRE,
aim: AIM,
jump: JUMP,
duck: DUCK,
left: LEAN_LEFT,
right: LEAN_RIGHT,
reload: RELOAD,
throw: THROW,
};
type MouseReport =
| { type: 'mouse.state'; captured: boolean }
| { type: 'mouse.input'; dx: number; dy: number; buttons: number };
type ShellMouse = { offer(listener: (event: MouseReport) => void): { close(): void } };
const shellMouse = () => (window as Window & { napplet?: { soyMouse?: ShellMouse } }).napplet?.soyMouse;
export class Controls {
yaw = 0;
pitch = 0;
active = false;
private keys = new Set<string>();
private presses = 0;
private mouse = 0;
private touches = new Map<number, number>();
private stick: [number, number] = [0, 0];
private toggles = 0;
private padMove: [number, number] = [0, 0];
private padHeld = 0;
private padPressed = 0;
private padCrouch = false;
private padSwap = false;
private shellCapture?: { close(): void };
private shellLocked = false;
private lockPending = false;
private denied = false;
private locked = false;
private swap = false;
private drag = -1;
private steerOrigin: number | null = null;
private steerRate = 0;
private lastX = 0;
private lastY = 0;
constructor(
private canvas: HTMLCanvasElement,
private pause: () => void,
private toggleCrouch: () => boolean,
) {
window.addEventListener('keydown', (e) => {
if (!this.active) return;
if (e.code === 'Escape' || e.code === 'KeyP') {
e.preventDefault();
if (!e.repeat) pause();
return;
}
if (
!/^(Key[WASDFVCRGQE]|Digit[12]|Arrow(Up|Down|Left|Right)|Shift(Left|Right)|Space)$/.test(e.code)
)
return;
e.preventDefault();
if (e.code === 'KeyC' && this.toggleCrouch()) {
if (!e.repeat) this.toggle(DUCK);
return;
}
if (!e.repeat) this.presses |= keyFlags[e.code] ?? 0;
this.keys.add(e.code);
});
window.addEventListener('keyup', (e) => this.keys.delete(e.code));
window.addEventListener('blur', () => this.clear());
document.addEventListener('pointerlockchange', () => {
const wasLocked = this.locked;
this.locked = document.pointerLockElement === canvas;
this.lockPending = false;
this.stopSteering();
if (this.locked && !this.active) {
document.exitPointerLock();
return;
}
this.updateCursor();
if (wasLocked && !this.locked && this.active) pause();
});
document.addEventListener('pointerlockerror', () => {
this.lockPending = false;
this.updateCursor();
});
document.addEventListener('visibilitychange', () => {
if (document.hidden) this.clear();
});
this.canvas.addEventListener('contextmenu', (e) => e.preventDefault());
canvas.addEventListener('mousedown', (e) => {
if (this.active && !this.shellLocked) this.mouseButtons(e.buttons);
if (e.button !== 1 || !this.active || this.locked || this.shellLocked) return;
e.preventDefault();
this.steerOrigin = e.clientX;
this.steerRate = 0;
});
window.addEventListener('mouseup', (e) => {
if (this.active && !this.shellLocked) this.mouseButtons(e.buttons);
if (e.button === 1) this.stopSteering();
});
canvas.addEventListener('auxclick', (e) => {
if (e.button === 1 && this.active) e.preventDefault();
});
this.canvas.addEventListener('pointerdown', (e) => {
if (!this.active) return;
if (e.pointerType !== 'mouse') e.preventDefault();
canvas.focus({ preventScroll: true });
if (e.pointerType === 'mouse') {
this.mouseButtons(e.buttons);
if (e.buttons & 4) { this.steerOrigin = e.clientX; this.steerRate = 0; }
this.lock();
}
this.drag = e.pointerId;
this.lastX = e.clientX;
this.lastY = e.clientY;
if (!this.locked && !canvas.hasPointerCapture(e.pointerId))
canvas.setPointerCapture(e.pointerId);
});
this.canvas.addEventListener('pointermove', (e) => {
if (!this.active) return;
if (e.pointerType === 'mouse') this.mouseButtons(e.buttons);
if (document.pointerLockElement === canvas) return;
if (e.pointerType === 'mouse' && this.steerOrigin !== null && (e.buttons & 4)) {
const dx = e.clientX - this.steerOrigin;
this.steerRate = Math.sign(dx) * clamp((Math.abs(dx) - 4) / 56, 0, 1);
this.turn(0, e.movementY);
this.lastX = e.clientX;
this.lastY = e.clientY;
return;
}
if (e.pointerType === 'mouse') {
this.stopSteering();
this.turn(e.movementX, e.movementY);
return;
}
if (e.pointerId !== this.drag) return;
this.turn(e.clientX - this.lastX, e.clientY - this.lastY);
this.lastX = e.clientX;
this.lastY = e.clientY;
});
document.addEventListener('mousemove', (e) => {
if (this.active && document.pointerLockElement === canvas) this.turn(e.movementX, e.movementY);
});
const release = (e: PointerEvent) => {
if (this.active && e.pointerType === 'mouse') this.mouseButtons(e.buttons);
if (e.pointerType === 'mouse' && !(e.buttons & 4)) this.stopSteering();
if (!e.buttons && this.drag === e.pointerId) this.drag = -1;
};
window.addEventListener('pointerup', release);
canvas.addEventListener('lostpointercapture', (e) => {
if (this.drag === e.pointerId) {
this.drag = -1;
this.stopSteering();
this.mouse = 0;
}
});
window.addEventListener('pointercancel', () => this.clear());
const stick = document.querySelector<HTMLElement>('#stick')!;
let finger = -1;
const move = (e: PointerEvent) => {
const box = stick.getBoundingClientRect(),
x = (e.clientX - box.left - box.width / 2) / 30,
y = (e.clientY - box.top - box.height / 2) / 30,
l = Math.max(1, Math.hypot(x, y));
this.stick = [x / l, -y / l];
stick.firstElementChild!.setAttribute(
'style',
'transform:translate(' + (x / l) * 23 + 'px,' + (y / l) * 23 + 'px)',
);
};
stick.onpointerdown = (e) => {
if (!this.active) return;
finger = e.pointerId;
stick.setPointerCapture(finger);
move(e);
};
stick.onpointermove = (e) => {
if (e.pointerId === finger) move(e);
};
stick.onlostpointercapture = () => {
finger = -1;
this.stick = [0, 0];
stick.firstElementChild!.removeAttribute('style');
};
for (const b of document.querySelectorAll<HTMLButtonElement>('[data-action]')) {
const flag = tapFlags[b.dataset.action!];
b.onpointerdown = (e) => {
if (!this.active) return;
e.preventDefault();
b.setPointerCapture(e.pointerId);
if (b.dataset.action === 'swap') {
this.swap = true;
return;
}
if (flag === AIM || (flag === DUCK && this.toggleCrouch())) {
this.toggle(flag);
} else {
this.touches.set(e.pointerId, flag);
this.presses |= flag;
}
};
b.onlostpointercapture = (e) => this.touches.delete(e.pointerId);
}
}
private toggle(flag: number) {
this.toggles ^= flag;
document
.querySelector('[data-action="' + (flag === DUCK ? 'duck' : 'aim') + '"]')
?.setAttribute('aria-pressed', String(Boolean(this.toggles & flag)));
}
private mouseButtons(buttons: number) {
const flags = (buttons & 1 ? FIRE : 0) | (buttons & 2 ? AIM : 0);
this.presses |= flags & ~this.mouse;
this.mouse = flags;
}
private offerShellMouse(api: ShellMouse) {
if (this.shellCapture) return;
this.shellCapture = api.offer(event => {
if (!this.active) return;
if (event.type === 'mouse.state') {
const lost = this.shellLocked && !event.captured;
this.shellLocked = event.captured;
this.stopSteering();
this.updateCursor();
if (lost) this.pause();
} else if (this.shellLocked) {
this.turn(event.dx, event.dy);
this.mouseButtons(event.buttons);
}
});
}
private stopSteering() {
this.steerOrigin = null;
this.steerRate = 0;
}
private turn(x: number, y: number) {
this.yaw += x * 0.004 * settings.sensitivity;
this.pitch = clamp(this.pitch - y * 0.0035 * settings.sensitivity, -1.36, 1.36);
}
clearPad() {
this.padMove = [0, 0];
this.padHeld = this.padPressed = 0;
this.padCrouch = this.padSwap = false;
}
gamepad(x: number, forward: number, lookX: number, lookY: number, dt: number, held: number, pressed: number) {
if (!this.active) return;
this.padMove = [x, forward];
this.yaw += lookX * dt * 3.2 * settings.sensitivity;
this.pitch = clamp(this.pitch - lookY * dt * 2.4 * settings.sensitivity, -1.36, 1.36);
if (this.toggleCrouch()) {
if (pressed & 2) this.padCrouch = !this.padCrouch;
} else this.padCrouch = Boolean(held & 2);
this.padHeld = this.padCrouch ? DUCK : 0;
if (pressed & 8) this.padSwap = true;
padFlags.forEach((flag, index) => {
if (held & (1 << index)) this.padHeld |= flag;
if (pressed & (1 << index)) this.padPressed |= flag;
});
}
clear() {
this.stopSteering();
this.clearPad();
this.swap = false;
this.mouse = this.presses = this.toggles = 0;
this.keys.clear();
this.touches.clear();
this.stick = [0, 0];
this.drag = -1;
document.querySelector('#stick i')?.removeAttribute('style');
document
.querySelectorAll('[aria-pressed="true"][data-action]')
.forEach((b) => b.setAttribute('aria-pressed', 'false'));
}
sync(p: Player) {
this.yaw = p.yaw;
this.pitch = p.pitch;
this.clear();
}
input(seq: number, p: Player, tick: number): Input {
const k = (s: string) => Number(this.active && this.keys.has(s));
this.yaw += ((k('ArrowRight') - k('ArrowLeft')) * 0.038 + this.steerRate * 0.07) * settings.sensitivity;
this.yaw = Math.atan2(Math.sin(this.yaw), Math.cos(this.yaw));
this.pitch = clamp(this.pitch + (k('ArrowUp') - k('ArrowDown')) * 0.029, -1.36, 1.36);
let flags = this.presses | this.mouse | this.toggles | this.padHeld | this.padPressed;
this.padPressed = 0;
if (this.swap || this.padSwap) {
this.padSwap = false;
flags |= p.gun < p.holster ? SECONDARY : PRIMARY;
this.swap = false;
}
this.presses = 0;
for (const s of this.keys) flags |= keyFlags[s] ?? 0;
for (const bit of this.touches.values()) flags |= bit;
return [
seq,
clamp(k('KeyW') - k('KeyS') + this.stick[1] + this.padMove[1], -1, 1),
clamp(k('KeyD') - k('KeyA') + this.stick[0] + this.padMove[0], -1, 1),
this.yaw,
this.pitch,
this.active ? flags : 0,
p.life,
tick,
];
}
private updateCursor() {
this.canvas.dataset.mouseLook = !this.active ? 'off' : this.locked || this.shellLocked ? 'locked' : 'free';
}
start() {
this.active = true;
this.canvas.focus({ preventScroll: true });
this.updateCursor();
if (!document.body.classList.contains('pad-mode') &&
(shellMouse() || navigator.userActivation?.isActive !== false)) this.lock();
}
stop() {
this.active = false;
this.shellCapture?.close();
this.shellCapture = undefined;
this.shellLocked = false;
this.clear();
this.updateCursor();
if (document.pointerLockElement === this.canvas) {
this.locked = false;
document.exitPointerLock();
}
}
private lock() {
const api = shellMouse();
if (this.active && api && matchMedia('(any-pointer:fine)').matches) {
this.offerShellMouse(api);
return;
}
if (
!this.active ||
this.locked ||
this.lockPending ||
this.denied ||
!matchMedia('(any-pointer:fine)').matches ||
!this.canvas.requestPointerLock
)
return;
this.lockPending = true;
try {
const result = this.canvas.requestPointerLock();
if (result)
void result.catch((err: unknown) => {
this.lockPending = false;
if (
err instanceof DOMException &&
err.name === 'SecurityError' &&
/sandbox/i.test(err.message)
)
this.denied = true;
this.updateCursor();
});
} catch {
this.lockPending = false;
this.updateCursor();
}
}
}
