SOURCE / PINNED RELEASE
Made of little things.
Drift City
- Release
- 098731aa0f0f…
- Author-recorded commit
- 2822ea0a4f5b…
- License
- LICENSE
- Author’s source reference
- nostr://npub12lm3rxsva8kfempyjkxupt09e02n3fezurkyadyqfejdc5e0r2kscqty6r/wss%3A%2F%2Fgit.napplet.soy%2F/n-a4c0039c855
Archive hash verified: b3323e408235502b…. The source-to-build association is the author’s claim; it has not been independently rebuilt.
import * as THREE from 'three';
import { START_S, type RaceRoute, type RaceSession } from './race.js';
import type { Collider, World } from './world.js';
import type { RoadGraph } from './traffic.js';
/** A chevron board's face: red, with white chevrons pointing right (or left). */
function chevronTexture(right: boolean): THREE.CanvasTexture {
const c = document.createElement('canvas');
c.width = 128;
c.height = 64;
const g = c.getContext('2d')!;
g.fillStyle = '#d8352a';
g.fillRect(0, 0, 128, 64);
g.fillStyle = '#f4f1e6';
for (const x0 of [14, 54, 94]) {
const x = right ? x0 : 128 - x0;
const d = right ? 1 : -1;
g.beginPath();
g.moveTo(x - 8 * d, 8);
g.lineTo(x + 6 * d, 8);
g.lineTo(x + 22 * d, 32);
g.lineTo(x + 6 * d, 56);
g.lineTo(x - 8 * d, 56);
g.lineTo(x + 8 * d, 32);
g.closePath();
g.fill();
}
g.strokeStyle = '#f4f1e6';
g.lineWidth = 4;
g.strokeRect(2, 2, 124, 60);
const t = new THREE.CanvasTexture(c);
t.colorSpace = THREE.SRGBColorSpace;
t.anisotropy = 4;
return t;
}
/** A barrier board's back: red and white diagonal stripes. */
function stripeTexture(): THREE.CanvasTexture {
const c = document.createElement('canvas');
c.width = 128;
c.height = 64;
const g = c.getContext('2d')!;
g.fillStyle = '#f4f1e6';
g.fillRect(0, 0, 128, 64);
g.fillStyle = '#d8352a';
for (let x = -64; x < 128; x += 32) {
g.beginPath();
g.moveTo(x, 64);
g.lineTo(x + 16, 64);
g.lineTo(x + 80, 0);
g.lineTo(x + 64, 0);
g.closePath();
g.fill();
}
const t = new THREE.CanvasTexture(c);
t.colorSpace = THREE.SRGBColorSpace;
return t;
}
/** A turn in the route at a junction: which roads lead out of it the wrong way. */
interface Turn {
node: number;
/** Heading coming in, and going out. */
inX: number;
inZ: number;
outX: number;
outZ: number;
/** The roads out of it that aren't the route. */
wrong: number[];
/** Where it is along the route. */
s: number;
}
/**
* The race's furniture along the route: a gantry over the start line and the finish
* (chequered, with a chequered stripe painted across the road), and a yellow arch at each
* checkpoint. Not solid: they stand clear of the road, the banners high over it.
*/
function bannerTexture(text: string, chequer: boolean): THREE.CanvasTexture {
const c = document.createElement('canvas');
c.width = 512;
c.height = 64;
const g = c.getContext('2d')!;
if (chequer) {
for (let x = 0; x < 512; x += 16) for (let y = 0; y < 64; y += 16) {
g.fillStyle = (x + y) / 16 % 2 ? '#111318' : '#f4f1e6';
g.fillRect(x, y, 16, 16);
}
g.fillStyle = 'rgba(17,19,24,0.85)';
g.fillRect(150, 8, 212, 48);
} else {
g.fillStyle = '#ffc93c';
g.fillRect(0, 0, 512, 64);
g.fillStyle = '#1b2140';
for (let x = -64; x < 512; x += 48) {
g.beginPath();
g.moveTo(x, 64);
g.lineTo(x + 24, 64);
g.lineTo(x + 40, 32);
g.lineTo(x + 24, 0);
g.lineTo(x, 0);
g.lineTo(x + 16, 32);
g.closePath();
g.globalAlpha = 0.18;
g.fill();
}
g.globalAlpha = 1;
}
g.font = 'italic 900 38px "Arial Black", Impact, sans-serif';
g.textAlign = 'center';
g.textBaseline = 'middle';
g.fillStyle = chequer ? '#ffc93c' : '#1b2140';
g.fillText(text, 256, 34);
const t = new THREE.CanvasTexture(c);
t.colorSpace = THREE.SRGBColorSpace;
t.anisotropy = 4;
return t;
}
function chequerTexture(): THREE.CanvasTexture {
const c = document.createElement('canvas');
c.width = 128;
c.height = 16;
const g = c.getContext('2d')!;
for (let x = 0; x < 128; x += 8) for (let y = 0; y < 16; y += 8) {
g.fillStyle = (x + y) / 8 % 2 ? '#15171c' : '#f4f1e6';
g.fillRect(x, y, 8, 8);
}
const t = new THREE.CanvasTexture(c);
t.colorSpace = THREE.SRGBColorSpace;
t.magFilter = THREE.NearestFilter;
return t;
}
const postMat = new THREE.MeshLambertMaterial({ color: 0x3a3e45 });
const _p = { x: 0, z: 0, tx: 0, tz: 1, hw: 4 };
export class RaceGates {
readonly root = new THREE.Group();
private readonly owned: { dispose(): void }[] = [];
/** Roads closed off by barriers (for the traffic to keep out of). */
readonly blocked: number[] = [];
private readonly colliders: Collider[] = [];
private readonly world: World;
constructor(world: World, route: RaceRoute, race: RaceSession, graph: RoadGraph) {
this.world = world;
this.turnBoards(world, route, graph);
const start = route.loop ? 'START / FINISH' : 'START';
this.gate(world, route, START_S, start, true);
this.stripe(world, route, START_S);
if (!route.loop) {
this.gate(world, route, race.finishS, 'FINISH', true);
this.stripe(world, route, race.finishS);
}
// One arch per checkpoint (on a circuit, the same ones serve every lap).
const seen = new Set<number>();
race.checkpoints.forEach((prog, i) => {
const s = route.loop ? (START_S + prog) % route.len : START_S + prog;
const key = Math.round(s);
if (seen.has(key) || Math.abs(s - START_S) < 5) return;
seen.add(key);
this.gate(world, route, s, `CHECKPOINT ${(i % Math.max(1, race.checkpoints.length / race.laps)) + 1}`, false);
});
}
private gate(world: World, route: RaceRoute, s: number, text: string, chequer: boolean): void {
const p = route.at(s, _p);
const half = p.hw + 1.6;
const yaw = Math.atan2(p.tx, p.tz);
const g = new THREE.Group();
g.position.set(p.x, 0, p.z);
g.rotation.y = yaw;
// Posts either side (their feet on the ground there), and the banner across the top.
for (const side of [-1, 1]) {
const wx = p.x - p.tz * side * half;
const wz = p.z + p.tx * side * half;
const foot = world.height(wx, wz, (p.y ?? 0) + 0.5) - 0.3;
const post = new THREE.Mesh(new THREE.BoxGeometry(0.35, 6.6, 0.35), postMat);
post.position.set(-side * half, foot + 3.3, 0);
post.castShadow = true;
g.add(post);
this.owned.push(post.geometry);
}
const y = world.height(p.x, p.z, (p.y ?? 0) + 0.5);
const tex = bannerTexture(text, chequer);
const mat = new THREE.MeshLambertMaterial({ map: tex });
const banner = new THREE.Mesh(new THREE.BoxGeometry(half * 2 + 0.4, 1.2, 0.25), [postMat, postMat, postMat, postMat, mat, mat]);
banner.position.set(0, y + 6.2, 0);
banner.castShadow = true;
g.add(banner);
this.owned.push(banner.geometry, mat, tex);
this.root.add(g);
}
private stripe(world: World, route: RaceRoute, s: number): void {
const p = route.at(s, _p);
const tex = chequerTexture();
const mat = new THREE.MeshLambertMaterial({ map: tex, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -4 });
const geo = new THREE.PlaneGeometry(p.hw * 2, 1.6).rotateX(-Math.PI / 2);
const m = new THREE.Mesh(geo, mat);
m.position.set(p.x, world.height(p.x, p.z, (p.y ?? 0) + 0.5) + 0.06, p.z);
m.rotation.y = Math.atan2(p.tx, p.tz);
m.receiveShadow = true;
this.root.add(m);
this.owned.push(geo, mat, tex);
}
/**
* At every junction where the route turns: a barrier of chevron boards across each road
* out of it that isn't the route, the chevrons pointing the way it goes, and (where no
* road carries straight on) a chevron sign on the outside of the turn.
*/
private turnBoards(world: World, route: RaceRoute, graph: RoadGraph): void {
const turns = findTurns(route, graph);
if (!turns.length) return;
const right = chevronTexture(true);
const left = chevronTexture(false);
const back = stripeTexture();
const side = new THREE.MeshLambertMaterial({ color: 0xd8352a });
const faceR = new THREE.MeshLambertMaterial({ map: right });
const faceL = new THREE.MeshLambertMaterial({ map: left });
const backM = new THREE.MeshLambertMaterial({ map: back });
const boardGeo = new THREE.BoxGeometry(1.7, 0.85, 0.12);
const legGeo = new THREE.BoxGeometry(0.1, 1, 0.1);
this.owned.push(right, left, back, side, faceR, faceL, backM, boardGeo, legGeo);
const legMat = new THREE.MeshLambertMaterial({ color: 0xf4f1e6 });
this.owned.push(legMat);
// Every board and leg goes into instanced meshes (a few draws however many turns).
const boardsR: THREE.Matrix4[] = [];
const boardsL: THREE.Matrix4[] = [];
const legs: THREE.Matrix4[] = [];
const q = new THREE.Quaternion();
const up = new THREE.Vector3(0, 1, 0);
/** A board at (x, z) facing along (nx, nz), its chevrons pointing towards (ex, ez), lifted by lift (on the level at about ly). */
const board = (x: number, z: number, nx: number, nz: number, ex: number, ez: number, lift: number, ly: number) => {
const yaw = Math.atan2(nx, nz);
// Seen from the front, the board's right is its local +x.
const rx = Math.cos(yaw);
const rz = -Math.sin(yaw);
const toRight = (ex - x) * rx + (ez - z) * rz >= 0;
const y = world.height(x, z, ly + 0.5);
q.setFromAxisAngle(up, yaw);
(toRight ? boardsR : boardsL).push(new THREE.Matrix4().compose(new THREE.Vector3(x, y + 0.75 + lift, z), q, new THREE.Vector3(1, 1, 1)));
for (const k of [-0.6, 0.6])
legs.push(new THREE.Matrix4().compose(new THREE.Vector3(x + rx * k, y + (0.4 + lift) / 2 + 0.1, z + rz * k), q, new THREE.Vector3(1, 0.4 + lift, 1)));
};
const instance = (geo: THREE.BufferGeometry, mat: THREE.Material | THREE.Material[], list: THREE.Matrix4[]) => {
if (!list.length) return;
const m = new THREE.InstancedMesh(geo, mat, list.length);
list.forEach((x, i) => m.setMatrixAt(i, x));
m.castShadow = true;
m.computeBoundingSphere();
this.root.add(m);
this.owned.push(m);
};
const at = { x: 0, z: 0, tx: 0, tz: 1 };
for (const t of turns) {
const n = graph.nodes[t.node]!;
const ex = n.x + t.outX * 40;
const ez = n.z + t.outZ * 40;
let straightOn = false;
for (const ei of t.wrong) {
const e = graph.edges[ei]!;
const dir: 1 | -1 = e.a === t.node ? 1 : -1;
const d = Math.min(e.city ? 14 : 11, e.len * 0.45);
graph.at({ edge: ei, dir, s: d }, 0, at);
if (at.tx * t.inX + at.tz * t.inZ > 0.7) straightOn = true;
const hw = e.kind === 'highway' ? 9 : e.city ? 8 : 6.5;
// Across the road: boards side by side, facing back into the junction; solid posts behind.
const across = { x: -at.tz, z: at.tx };
const count = Math.ceil((hw * 2) / 1.8);
// Nothing on the route itself, where the wrong road leaves the junction at a shallow
// angle to it (the suburbs' curving lanes).
const onRoute = (x: number, z: number) => {
const pr = route.project(x, z, route.len / 2, route.len / 2 + 10, route.len / 2 + 10);
return pr.d < route.at(pr.s, _p).hw + 1.4;
};
for (let k = 0; k < count; k++) {
const o = -hw + (hw * 2 * (k + 0.5)) / count;
if (onRoute(at.x + across.x * o, at.z + across.z * o)) continue;
board(at.x + across.x * o, at.z + across.z * o, -at.tx, -at.tz, ex, ez, 0, n.y);
}
for (let o = -hw; o <= hw + 0.01; o += 0.9) {
const x = at.x + across.x * o;
const z = at.z + across.z * o;
if (onRoute(x, z)) continue;
// Up on the highway, posts that anything passing underneath goes under.
const y = world.height(x, z, n.y + 0.5);
this.colliders.push(world.addPost(x, z, 0.45, y + 1.4, y > 3 ? y - 1.5 : undefined));
}
this.blocked.push(ei);
}
// A dead end ahead (the kerb, a building): a chevron sign on the outside of the turn.
if (!straightOn) {
const hw = graph.edges[n.edges[0]!]!.city ? 8 : 6.5;
const x = n.x + t.inX * (hw + 3.5);
const z = n.z + t.inZ * (hw + 3.5);
for (const k of [-1, 0, 1]) board(x - t.inZ * k * 1.75, z + t.inX * k * 1.75, -t.inX, -t.inZ, ex, ez, 0.9, n.y);
}
}
instance(boardGeo, [side, side, side, side, faceR, backM], boardsR);
instance(boardGeo, [side, side, side, side, faceL, backM], boardsL);
instance(legGeo, legMat, legs);
}
dispose(): void {
this.root.removeFromParent();
for (const o of this.owned) o.dispose();
this.world.removeColliders(this.colliders);
}
}
/** Each junction the route turns at, with the roads out of it that aren't the route. */
function findTurns(route: RaceRoute, graph: RoadGraph): Turn[] {
const pts = route.pts;
const m = pts.length;
const step = route.loop ? route.len / m : route.len / (m - 1);
// The roads the route runs along (away from junctions), never to be closed.
const used = new Set<number>();
for (const p of pts) {
if (graph.nodes.some((n) => Math.abs(n.x - p.x) < 14 && Math.abs(n.z - p.z) < 14 && Math.hypot(n.x - p.x, n.z - p.z) < 14)) continue;
used.add(graph.nearest(p.x, p.z, 0, p.y).cursor.edge);
}
const out: Turn[] = [];
const q = { x: 0, z: 0, tx: 0, tz: 1, hw: 4 };
const lv = { x: 0, z: 0, tx: 0, tz: 1 };
graph.nodes.forEach((n, ni) => {
if (n.edges.length < 3) return;
// Each pass of the route through the junction (on its level: not a junction under
// the highway, or one on it overhead): its nearest point.
const near = (p: { x: number; z: number; y?: number }) => Math.abs((p.y ?? 0) - n.y) < 2.5 && Math.hypot(p.x - n.x, p.z - n.z) <= 9;
let i = 0;
while (i < m) {
if (!near(pts[i]!)) {
i++;
continue;
}
let best = i;
while (i < m && near(pts[i]!)) {
if (Math.hypot(pts[i]!.x - n.x, pts[i]!.z - n.z) < Math.hypot(pts[best]!.x - n.x, pts[best]!.z - n.z)) best = i;
i++;
}
const s = best * step;
if (!route.loop && (s < 20 || s > route.len - 20)) continue;
route.at(s - 16, q);
const inX = q.tx;
const inZ = q.tz;
route.at(s + 16, q);
const outX = q.tx;
const outZ = q.tz;
const turn = Math.atan2(inX * outZ - inZ * outX, inX * outX + inZ * outZ);
if (Math.abs(turn) < 0.5) continue;
// The roads in and out: the ones leaving the junction most nearly back the way the
// route came, and the way it goes.
const dirs = n.edges.map((ei) => {
const e = graph.edges[ei]!;
graph.at({ edge: ei, dir: e.a === ni ? 1 : -1, s: Math.min(6, e.len / 2) }, 0, lv);
return { ei, x: lv.tx, z: lv.tz };
});
const inE = dirs.reduce((a, b) => (-(b.x * inX + b.z * inZ) > -(a.x * inX + a.z * inZ) ? b : a)).ei;
const outE = dirs.reduce((a, b) => (b.x * outX + b.z * outZ > a.x * outX + a.z * outZ ? b : a)).ei;
const wrong = n.edges.filter((ei) => ei !== inE && ei !== outE && !used.has(ei));
out.push({ node: ni, inX, inZ, outX, outZ, wrong, s });
}
});
return out;
}
