diff --git a/web/main.js b/web/main.js
index 7ee1f9e..5101fd5 100644
--- a/web/main.js
+++ b/web/main.js
@@ -252,18 +252,18 @@ if (PIXEL) {
// margins: centre it on screen, leave a margin, keep clear of the title above.
const ISO_DIR = (() => { const A = Math.PI / 4, E = Math.PI / 6; return new THREE.Vector3(Math.cos(E) * Math.cos(A), Math.sin(E), Math.cos(E) * Math.sin(A)); })();
let FIT = null;
-function fitFrame(aspect = viewW() / viewH(), bands = clearBands()) {
+function fitFrame(aspect = viewW() / viewH(), bands = clearBands(), only = null) { // (only: frame just these buildings)
const cam = camera.clone();
cam.position.copy(ISO_DIR).multiplyScalar(SIZE * 2); cam.lookAt(0, 0, 0); cam.updateMatrixWorld();
const inv = cam.matrixWorldInverse, v = new THREE.Vector3();
let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
const add = (x, y, z) => { v.set(x, y, z).applyMatrix4(inv); x0 = Math.min(x0, v.x); x1 = Math.max(x1, v.x); y0 = Math.min(y0, v.y); y1 = Math.max(y1, v.y); };
B.forEach((b, i) => {
- if (!(b.w > 0.01) || !Number.isFinite(b.x)) return;
+ if (!(b.w > 0.01) || !Number.isFinite(b.x) || only && !only.has(i)) return;
for (const sx of [-0.5, 0.5]) for (const sz of [-0.5, 0.5]) add(b.x + sx * b.w, b.y, b.z + sz * b.d);
add(b.x, b.y + b.h, b.z);
});
- for (const bl of layout?.blocks || []) for (const [x, z] of bl.poly) add(x, plateStep + (bl.h || 0), z);
+ if (!only) for (const bl of layout?.blocks || []) for (const [x, z] of bl.poly) add(x, plateStep + (bl.h || 0), z);
if (!Number.isFinite(x0)) return { center: new THREE.Vector3(), zoom: 1 };
const { top, bottom, left = 0, right = 0 } = bands;
// the city may use 90% of the width and what's left of the height between the title and the timeline
@@ -518,6 +518,51 @@ const buildings = studio ? studio.buildings : (() => {
scene.add(mesh);
return mesh;
})();
+// ---- markers: with one person's buildings lit, a little yellow arrow bobs over each of them, so a
+// handful of small buildings in a big city are found at a glance (and on their share card too: these
+// are in the scene, not on the page). Not when they have so many the city would be covered in them.
+const MARKS_UPTO = 24;
+const marks = (() => {
+ const pos = new Float32Array(N * 3), life = new Float32Array(N * 2);
+ B.forEach((b, i) => { pos.set([b.x || 0, (b.y || 0) + (b.h || 0), b.z || 0], i * 3); life.set([b.born ?? 0, b.died ?? 2], i * 2); });
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('aLife', new THREE.BufferAttribute(life, 2));
+ geo.setAttribute('aOn', new THREE.BufferAttribute(focusAttr, 1).setUsage(THREE.DynamicDrawUsage));
+ const pts = new THREE.Points(geo, new THREE.ShaderMaterial({
+ uniforms: { ...shared, uMarks: { value: 0 }, uArt: { value: PIXEL ? 1 : 0 }, uSize: { value: unit * 1.0 },
+ uFill: { value: new THREE.Color('#f2c14e') }, uInk: { value: new THREE.Color('#14121c') } },
+ depthTest: false, depthWrite: false, transparent: true,
+ vertexShader: GLSL_COMMON + `uniform float uMarks, uArt, uSize, uPx, uLit; attribute vec2 aLife; attribute float aOn;
+ void main(){
+ bool up = uMarks > 0.5 && uLit > 0.5 && aOn > 0.5 && uTimeline >= aLife.x * 0.97 + 0.03 && uTimeline < aLife.y * 0.97;
+ if (!up) { gl_Position = vec4(0., 0., -2., 1.); return; }
+ // it floats a little above the roof, bobbing (pixel art: in whole art pixels)
+ float bob = sin(uTime * 3.0 + position.x * 0.7) * 0.5 + 0.5;
+ vec3 p = position + vec3(0.0, uArt > 0.5 ? uPx * (14.0 + 2.0 * floor(bob * 3.0)) : uSize * (0.5 + bob * 0.3), 0.0);
+ vec4 mv = viewMatrix * modelMatrix * vec4(p, 1.);
+ gl_PointSize = uArt > 0.5 ? 18.0 : uSize * uPixel / -mv.z; // (pixel art: each of its 9×9 pixels two art pixels wide)
+ gl_Position = projectionMatrix * mv;
+ }`,
+ fragmentShader: `uniform vec3 uFill, uInk;
+ // a 9×9 pixel arrow pointing down, inked round its edge
+ bool inside(float x, float y) {
+ if (x < 0.0 || x > 8.0 || y < 0.0 || y > 7.0) return false;
+ float w = y <= 3.0 ? 4.0 : 7.0 - y;
+ return abs(x - 4.0) <= w && !(y == 0.0 && abs(x - 4.0) == 4.0);
+ }
+ void main(){
+ vec2 c = floor(gl_PointCoord * 9.0);
+ if (!inside(c.x, c.y)) discard;
+ bool edge = !(inside(c.x - 1.0, c.y) && inside(c.x + 1.0, c.y) && inside(c.x, c.y - 1.0) && inside(c.x, c.y + 1.0));
+ gl_FragColor = vec4(edge ? uInk : uFill, 1.0);
+ }`,
+ }));
+ pts.frustumCulled = false;
+ pts.renderOrder = 10;
+ scene.add(pts);
+ return pts;
+})();
// ---- the lots the deleted files leave (neon): dark rubble on a slab, its edge faintly lit
let rubble = studio?.rubble || null;
if (NEON && gone.length) {
@@ -848,16 +893,26 @@ $('#share').onclick = async () => {
setTimeout(() => { $('#share').textContent = 'share'; }, 1800);
return;
}
- openShareDialog(shareInfo());
+ const share = shareInfo();
+ // a person's link previews with their card, drawn when first asked for: ask now, so it's ready
+ // by the time the link is posted
+ if (route && share.info.person) fetch(`/api/card/${route[1]}/${route[2]}.png${new URL(share.link).search}`).catch(() => {});
+ openShareDialog(share);
};
// what a share card or film says about this city
function shareInfo() {
- const [owner, repo] = route ? [route[1], route[2]] : data.name.includes('/') ? data.name.split('/').slice(-2) : ['', data.name];
+ let [owner, repo] = route ? [route[1], route[2]] : data.name.includes('/') ? data.name.split('/').slice(-2) : ['', data.name];
const year = t => new Date(t * 1000).getFullYear();
+ // with someone's buildings lit, the card is theirs, and its link opens the city on them (on
+ // gitropolis.dev, which a city scanned here can be seen on too when it came from GitHub)
+ const p = lit >= 0 ? personInfo(lit) : null;
+ const home = route ? shareLink : data.github && `https://gitropolis.dev/${data.github}`;
+ const link = p && home ? `${home}?${new URLSearchParams({ by: authors[lit], ...(mode === 'm' && { most: '' }) })}`.replace(/=$/, '') : shareLink;
+ if (p && !route && data.github) [owner, repo] = data.github.split('/');
return {
- link: shareLink,
- badge: route ? shareLink : null,
- filename: `gitropolis-${owner ? owner + '-' : ''}${repo}`.replace(/[^\w.-]+/g, '-'),
+ link,
+ badge: route && !p ? shareLink : null,
+ filename: `gitropolis-${owner ? owner + '-' : ''}${repo}${p ? `-by-${p.name}` : ''}`.replace(/[^\w.-]+/g, '-'),
capture: captureCity,
stage: stageCity,
info: {
@@ -872,7 +927,8 @@ function shareInfo() {
const max = Math.max(1, ...bins);
return bins.map(v => v ? 0.15 + 0.85 * Math.sqrt(v / max) : 0);
},
- url: shareLink.replace(/^https:\/\//, ''),
+ url: link.replace(/^https:\/\//, ''),
+ ...(p && { person: p }),
},
};
}
@@ -885,9 +941,19 @@ function stageCity(artW, artH, bands) {
staged = true; playing = false;
camera.left = -ISO_H * artW / artH; camera.right = -camera.left;
const fit = fitFrame(artW / artH, bands);
+ // a person's card frames their buildings (though never so close the city around them is lost)
+ if (lit >= 0) {
+ const only = new Set();
+ for (let i = 0; i < LIVE; i++) if (focusAttr[i]) only.add(i);
+ const theirs = fitFrame(artW / artH, bands, only);
+ Object.assign(fit, { center: theirs.center, zoom: Math.min(theirs.zoom, fit.zoom * 2.5) });
+ }
aimPixel(fit.center, fit.zoom);
- shared.uFocus.value = -1; if (shared.uHover) shared.uHover.value = -1;
- const calm = () => { heat.fill(0); buildings.geometry.attributes.aHeat.needsUpdate = true; };
+ // someone's buildings lit stay lit: the card is theirs (any other focus is the live view's own)
+ if (lit < 0) shared.uFocus.value = -1;
+ if (shared.uHover) shared.uHover.value = -1;
+ // (and the pixel city's per-building state brought up to date: a card drawn headless has had no frame yet)
+ const calm = () => { heat.fill(0); buildings.geometry.attributes.aHeat.needsUpdate = true; studio?.update?.(); };
return {
// the finished city, no commit flashes
still() { setTimeline(1); calm(); return pix.capture(artW, artH); },
@@ -1085,11 +1151,14 @@ renderer.domElement.addEventListener('pointermove', e => {
// built from text nodes: a file name is data, never markup (a repo can name a file
![]()
)
const row = (...parts) => { const d = document.createElement('div'); for (const [k, v] of parts) { if (k) { const s = document.createElement('span'); s.textContent = k; d.append(s, ' '); } d.append(v); } return d; };
const name = document.createElement('b'); name.textContent = f.p;
+ // a person: their face and their name
+ const who = (k, a) => { const d = row([k, authors[a]]); d.classList.add('who'); d.insertBefore(faceEl(a), d.lastChild); return d; };
tip.replaceChildren(name,
row(['lines', `${f.loc.toLocaleString()} · `], ['commits', String(f.churn)]),
...(f.gone ? [] : [row(['imports', `${f.imp.length} · `], ['imported by', String(inDeg[hoverId])])]),
row(['born', `${fmtDate(f.born)} · `], ['last edit', fmtDate(f.last)]),
- ...(f.b !== undefined && authors[f.b] !== undefined ? [row(['built by', authors[f.b]])] : []),
+ ...(f.b !== undefined ? [who('built by', f.b)] : []),
+ ...(f.m !== undefined ? [who('most commits', f.m)] : []),
...(f.gone ? [row(['deleted', fmtDate(f.died)])] : []),
...(hoverLabel >= 0 ? [row(['district', `${labelSource[hoverLabel].path} · ${labelMembers[hoverLabel].filter(i => i < LIVE).length.toLocaleString()} files`])] : []));
tip.style.display = 'block';
@@ -1114,76 +1183,253 @@ function focus(id) {
}
buildings.geometry.attributes.aFocus.needsUpdate = true;
}
-addEventListener('keydown', e => { if (e.code === 'Escape') focus(-1); });
+addEventListener('keydown', e => { if (e.code === 'Escape' && !whoEscape()) focus(-1); });
-// ---- who built what: one builder's buildings lit, the rest of the city receding (a city scanned
-// before builders were recorded has none, and one built by one person has nothing to pick between)
+// ---- who built what: everyone who built the city, and one person's buildings lit, the rest of the
+// city fading to ghosts, with a card saying what they built and where. (A city scanned before builders
+// were recorded has none, and one built by one person has nothing to pick between.)
const authors = data.authors || [];
-const builtBy = authors.map(() => 0);
-for (let i = 0; i < LIVE; i++) if (files[i].b !== undefined) builtBy[files[i].b]++;
-const builders = authors.map((a, k) => k).filter(k => builtBy[k]).sort((x, y) => builtBy[y] - builtBy[x] || x - y);
-const whoBtn = $('#who'), whoPanel = $('#builders'), whoFind = $('#who-find'), whoList = $('#builders .list');
-const WHO_ROWS = 60; // the rest are a search away
+const faces = data.faces || [];
+const OWN = { b: f => f.b, m: f => f.m ?? f.b }; // whose a building is: who built it, or who made the most of its commits
+const tally = {};
+for (const m in OWN) {
+ tally[m] = authors.map(() => 0);
+ for (let i = 0; i < LIVE; i++) { const k = OWN[m](files[i]); if (k !== undefined) tally[m][k]++; }
+}
+const people = authors.map((a, k) => k).filter(k => tally.b[k] || tally.m[k])
+ .sort((x, y) => tally.b[y] - tally.b[x] || tally.m[y] - tally.m[x] || x - y);
+let mode = params.has('most') ? 'm' : 'b', whoOpen = false;
+const whoBtn = $('#who'), whoPanel = $('#builders'), whoFind = $('#who-find'), whoBody = $('#builders .body');
+const whoBack = $('#builders .back'), whoTitle = $('#builders .title');
+const WHO_ROWS = 400; // the rest are a search away
function light(k) {
focus(-1);
- if (k < 0) return;
- lit = k;
- // focused on no building in particular (N is none of them): no arcs, only the builder's buildings stand out
- shared.uFocus.value = N; shared.uLit.value = 1;
- for (let i = 0; i < N; i++) focusAttr[i] = files[i].b === k ? 1 : 0;
- buildings.geometry.attributes.aFocus.needsUpdate = true;
+ if (k >= 0) {
+ lit = k;
+ // someone who built none (only made the most commits on some) is shown by those instead
+ if (!tally[mode][k]) mode = mode === 'b' ? 'm' : 'b';
+ // focused on no building in particular (N is none of them): no arcs, only their buildings stand out
+ shared.uFocus.value = N; shared.uLit.value = 1;
+ let n = 0; // (the ones standing at the end, as their card counts them)
+ for (let i = 0; i < N; i++) { focusAttr[i] = OWN[mode](files[i]) === k ? 1 : 0; if (i < LIVE) n += focusAttr[i]; }
+ buildings.geometry.attributes.aFocus.needsUpdate = true;
+ // markers over them when they're few; and they flash, as when a commit touches them, to catch the eye
+ marks.material.uniforms.uMarks.value = n <= MARKS_UPTO ? 1 : 0;
+ marks.geometry.attributes.aOn.needsUpdate = true;
+ for (let i = 0; i < N; i++) if (focusAttr[i]) heat[i] = 1;
+ }
+ frameWho();
syncWho();
- note(`${authors[k]} built ${builtBy[k].toLocaleString()} of ${LIVE.toLocaleString()} buildings · Esc to clear`);
+}
+function showWho(open) {
+ whoOpen = open;
+ whoPanel.hidden = !open;
+ whoBtn.setAttribute('aria-expanded', String(open));
+ if (!open && lit >= 0) light(-1); else syncWho();
+ if (open && lit < 0 && !whoFind.hidden && matchMedia('(pointer: fine)').matches) whoFind.focus();
+}
+function setMode(m) {
+ mode = m;
+ if (lit >= 0) light(lit);
+}
+// the pixel city's camera glides to frame the lit person's buildings (clear of the panel), and back
+// to the whole city after
+let glideId = 0;
+function frameWho() {
+ if (!PIXEL || REC) return;
+ if (!FIT || FIT.aspect !== viewW() / viewH() || FIT.h !== viewH()) FIT = fitFrame();
+ let to = FIT;
+ if (lit >= 0) {
+ const only = new Set();
+ for (let i = 0; i < LIVE; i++) if (focusAttr[i]) only.add(i);
+ // beside the panel; on a phone, where it spans the screen's foot, above it
+ const r = whoPanel.getBoundingClientRect(), bands = clearBands();
+ if (r.width > innerWidth / 2) bands.bottom = Math.max(bands.bottom, (innerHeight - r.top + 16) / innerHeight);
+ else if (r.width) bands.right = (innerWidth - r.left + 16) / innerWidth;
+ to = fitFrame(viewW() / viewH(), bands, only);
+ to.zoom = Math.min(to.zoom, FIT.zoom * 3); // (one small building isn't a close-up)
+ }
+ const c0 = controls.target.clone(), z0 = camera.zoom, t0 = performance.now(), id = ++glideId;
+ const step = () => {
+ if (id !== glideId) return;
+ const u = Math.min(1, (performance.now() - t0) / 700), e = u * u * (3 - 2 * u);
+ aimPixel(c0.clone().lerp(to.center, e), z0 + (to.zoom - z0) * e);
+ if (u < 1) requestAnimationFrame(step);
+ };
+ step();
}
function syncWho() {
- whoBtn.classList.toggle('on', lit >= 0);
- whoBtn.title = lit >= 0 ? `Lit: ${authors[lit]}'s buildings (B to pick another)` : 'Who built what (B)';
- for (const el of whoList.children) el.classList?.toggle('on', +el.dataset.k === lit);
+ whoBtn.classList.toggle('on', whoOpen || lit >= 0);
+ whoBtn.title = 'Who built what (B)';
+ whoBack.hidden = lit < 0;
+ whoTitle.textContent = lit >= 0 ? '' : 'who built what';
+ whoFind.hidden = lit >= 0 || people.length <= 8;
+ if (lit >= 0) cardWho(lit); else listWho();
// the address says whose buildings are lit, so the link shows them too
if (REC) return;
const u = new URL(location.href);
if (lit >= 0) u.searchParams.set('by', authors[lit]); else u.searchParams.delete('by');
- history.replaceState(history.state, '', u);
+ if (lit >= 0 && mode === 'm') u.searchParams.set('most', ''); else u.searchParams.delete('most');
+ history.replaceState(history.state, '', u.toString().replace(/([?&]most)=(?=&|$)/, '$1'));
}
+// built from text nodes throughout: a name is data, never markup
+const tag = (name, cls, text) => { const e = document.createElement(name); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; };
function listWho() {
const q = whoFind.value.trim().toLowerCase();
- const match = q ? builders.filter(k => authors[k].toLowerCase().includes(q)) : builders;
- // built from text nodes: a name is data, never markup
- const rows = match.slice(0, WHO_ROWS).map(k => {
- const b = document.createElement('button'), name = document.createElement('span'), n = document.createElement('span');
- name.textContent = authors[k]; n.textContent = builtBy[k].toLocaleString();
- b.dataset.k = k; b.title = `Light up ${authors[k]}'s buildings`;
- b.classList.toggle('on', k === lit);
- b.append(name, n);
- b.onclick = () => { light(k === lit ? -1 : k); showWho(false); };
- return b;
+ const all = q ? people.filter(k => authors[k].toLowerCase().includes(q)) : people, match = all.slice(0, WHO_ROWS);
+ const rows = match.map(k => {
+ const r = tag('div', 'row'), b = tag('button');
+ b.title = `Light up ${authors[k]}'s buildings`;
+ b.append(tag('span', '', authors[k]), tag('span', '', tally.b[k] ? tally.b[k].toLocaleString() : '–'));
+ b.onclick = () => light(k);
+ r.append(faceEl(k, 'lazy'), b);
+ return r;
});
- if (match.length > WHO_ROWS) { const m = document.createElement('div'); m.className = 'more'; m.textContent = `and ${(match.length - WHO_ROWS).toLocaleString()} more: type a name`; rows.push(m); }
- if (!match.length) { const m = document.createElement('div'); m.className = 'more'; m.textContent = 'no builder by that name'; rows.push(m); }
- whoList.replaceChildren(...rows);
+ if (all.length > match.length) rows.push(tag('div', 'more', `and ${(all.length - match.length).toLocaleString()} more: type a name`));
+ if (q && !match.length) rows.push(tag('div', 'more', 'nobody by that name'));
+ const sub = tag('div', 'sum', `${people.length.toLocaleString()} people · buildings each one added`);
+ const list = tag('div', 'list');
+ list.append(...rows);
+ whoBody.replaceChildren(sub, list);
}
-function showWho(open) {
- whoPanel.hidden = !open;
- whoBtn.setAttribute('aria-expanded', String(open));
- if (!open) return;
- listWho();
- if (!whoFind.hidden) whoFind.focus();
+const ym = t => fmtDate(t);
+function cardWho(k) {
+ const f = faces[k] || {};
+ const top = tag('div', 'who');
+ const id = tag('div', 'id');
+ id.append(tag('b', '', authors[k]));
+ const gh = tag('a', 'gh'); gh.hidden = true; id.append(gh);
+ whoIs(k).then(v => { if (!v) return; gh.textContent = `@${v.login} ↗`; gh.href = `https://github.com/${encodeURIComponent(v.login)}`; gh.target = '_blank'; gh.rel = 'noopener'; gh.hidden = false; });
+ if (f.n) id.append(tag('small', '', `${f.n.toLocaleString()} commit${f.n > 1 ? 's' : ''} · ${ym(f.t[0])}${f.t[1] !== f.t[0] ? ` → ${ym(f.t[1])}` : ''}`));
+ top.append(faceEl(k), id);
+ // both counts side by side; the one picked says which of their buildings are lit
+ const stats = tag('div', 'stats');
+ stats.setAttribute('role', 'group'); stats.setAttribute('aria-label', 'Light up the buildings they');
+ for (const [m, text] of [['b', 'built'], ['m', 'most commits']]) {
+ const b = tag('button');
+ b.append(tag('span', '', tally[m][k].toLocaleString()), tag('small', '', text));
+ b.title = m === 'b' ? 'Buildings whose file they added' : 'Buildings where they made the most of the commits';
+ b.setAttribute('aria-pressed', String(m === mode));
+ b.disabled = !tally[m][k];
+ b.onclick = () => setMode(m);
+ stats.append(b);
+ }
+ const spots = whereOf(k);
+ const share = tag('button', 'share', 'share their buildings');
+ share.onclick = () => $('#share').click();
+ whoBody.replaceChildren(top, stats, tag('div', 'sum', `of ${LIVE.toLocaleString()} buildings${spots.length ? ` · in ${spots.join(' · ')}` : ''}`),
+ ...(pix && layout ? [share] : []));
+}
+// what a share card says about one person
+function personInfo(k) {
+ const f = faces[k] || {}, v = known.get(k);
+ const year = t => new Date(t * 1000).getFullYear();
+ return {
+ name: authors[k], initial: initialOf(k),
+ login: v?.login, img: v?.img,
+ n: tally[mode][k], of: LIVE, verb: mode === 'b' ? 'built' : 'made the most commits on',
+ where: whereOf(k).join(' · ') || null,
+ commits: f.n || 0, years: f.t ? f.t.map(year) : [year(data.start), year(data.end)],
+ };
}
-if (builders.length > 1) {
+// the districts someone's buildings stand in, most first, as "src 11" (none in a city without named districts)
+function whereOf(k) {
+ const where = new Map();
+ for (let i = 0; i < LIVE; i++) if (OWN[mode](files[i]) === k) where.set(fileLabel[i], (where.get(fileLabel[i]) || 0) + 1);
+ if (![...where].some(([d]) => d >= 0)) return [];
+ return [...where].sort((x, y) => y[1] - x[1]).slice(0, 4).map(([d, c]) => `${d >= 0 ? labelSource[d].data.name : 'elsewhere'} ${c}`);
+}
+const initialOf = k => (authors[k].match(/[\p{L}\p{N}]/u)?.[0] ?? '?').toUpperCase();
+
+// Faces: a GitHub avatar, linking to their profile, for an author GitHub knows; otherwise their initial.
+// A login comes from the scan (a no-reply email names it) or from GitHub, asked once which account made
+// a commit of theirs (and remembered: GitHub lets a visitor ask 60 times an hour)
+const GH = data.github || (route && `${route[1]}/${route[2]}`);
+const known = new Map(); // author -> { login, img } | null, once settled
+const asking = new Map();
+let ghTired = false; // GitHub said no more for now
+// (ask: false never asks GitHub, only says what's known already)
+function whoIs(k, ask = true) {
+ if (known.has(k)) return Promise.resolve(known.get(k));
+ if (asking.has(k)) return asking.get(k);
+ const f = faces[k], settle = v => { known.set(k, v); return v; };
+ // a card drawn headless for a link preview is handed the face of the person it's for ("login/id"),
+ // looked up by the site; it asks GitHub nothing itself
+ if (params.get('card')) {
+ const m = authors[k] === params.get('by') && /^([A-Za-z0-9-]{1,39})\/(\d{1,12})$/.exec(params.get('face') || '');
+ return Promise.resolve(settle(m ? { login: m[1], img: `https://avatars.githubusercontent.com/u/${m[2]}?v=4&s=64` } : null));
+ }
+ if (f?.u) return Promise.resolve(settle({ login: f.u, img: `https://avatars.githubusercontent.com/${encodeURIComponent(f.u)}?s=64` }));
+ if (REC || !GH || !f?.c || ghTired) return Promise.resolve(null);
+ const key = `gitropolis.face:${GH}:${f.c}`;
+ try { const v = localStorage.getItem(key); if (v !== null) return Promise.resolve(settle(v ? JSON.parse(v) : null)); } catch {}
+ if (!ask) return Promise.resolve(null);
+ const p = fetch(`https://api.github.com/repos/${GH}/commits/${f.c}`, { headers: { Accept: 'application/vnd.github+json' } })
+ .then(async r => {
+ // (only a clear answer is remembered: a GitHub hiccup is asked again next time)
+ if (!r.ok && r.status !== 404 && r.status !== 422) { if (r.status === 403 || r.status === 429) ghTired = true; asking.delete(k); return null; }
+ const a = r.ok ? (await r.json()).author : null;
+ const v = a?.login && /^https:\/\/avatars\.githubusercontent\.com\//.test(a.avatar_url)
+ ? { login: a.login, img: `${a.avatar_url}${a.avatar_url.includes('?') ? '&' : '?'}s=64` } : null;
+ try { localStorage.setItem(key, v ? JSON.stringify(v) : ''); } catch {}
+ return settle(v);
+ })
+ .catch(() => { asking.delete(k); return null; });
+ asking.set(k, p);
+ return p;
+}
+// a face, linking to GitHub once it's known. In a list ('lazy') it's only asked for once it scrolls
+// into view: GitHub is asked about everyone seen. On a district sign ('quiet') GitHub isn't asked at
+// all: there are signs enough to spend a visitor's hourly allowance before they've opened anything
+const sighted = new IntersectionObserver(es => { for (const e of es) if (e.isIntersecting) { sighted.unobserve(e.target); e.target.ask(); } });
+function faceEl(k, when = 'now') {
+ const el = document.createElement('a');
+ el.className = 'face';
+ el.textContent = initialOf(k);
+ const show = v => {
+ if (!v) return;
+ const img = new Image();
+ img.alt = ''; img.src = v.img; img.referrerPolicy = 'no-referrer';
+ // (once one has loaded, it's there at once: the tooltip is made anew on every move)
+ if (v.loaded) el.replaceChildren(img); else img.onload = () => { v.loaded = true; el.replaceChildren(img); };
+ el.href = `https://github.com/${encodeURIComponent(v.login)}`; el.target = '_blank'; el.rel = 'noopener';
+ el.title = `${v.login} on GitHub`;
+ };
+ if (known.has(k)) show(known.get(k));
+ else if (when === 'lazy') { el.ask = () => whoIs(k).then(show); sighted.observe(el); }
+ else whoIs(k, when !== 'quiet').then(show);
+ return el;
+}
+
+if (people.length > 1) {
whoBtn.hidden = false;
- whoFind.hidden = builders.length <= 8;
- whoBtn.onclick = () => showWho(whoPanel.hidden);
+ whoBtn.onclick = () => showWho(!whoOpen);
+ whoBack.onclick = () => light(-1);
+ $('#builders .x').onclick = () => showWho(false);
whoFind.oninput = listWho;
- whoFind.onkeydown = e => { if (e.key === 'Enter') whoList.querySelector('button')?.click(); };
+ whoFind.onkeydown = e => { if (e.key === 'Enter') whoBody.querySelector('.row button')?.click(); };
addEventListener('keydown', e => {
- if (e.code === 'Escape') showWho(false);
if (e.code !== 'KeyB' || e.metaKey || e.ctrlKey || e.target.closest?.('input, textarea')) return;
e.preventDefault(); // (or the b lands in the search box it opens)
- showWho(whoPanel.hidden);
+ showWho(!whoOpen);
});
- renderer.domElement.addEventListener('pointerdown', () => showWho(false));
const k = authors.indexOf(params.get('by'));
- if (k >= 0 && builtBy[k]) light(k);
+ if (k >= 0 && people.includes(k)) { showWho(true); light(k); }
+ // a sign names who founded its district: whoever built the most of it
+ labelEls.forEach(({ el }, d) => {
+ const n = new Map();
+ for (const i of labelMembers[d]) if (i < LIVE && files[i].b !== undefined) n.set(files[i].b, (n.get(files[i].b) || 0) + 1);
+ const [top] = [...n].sort((x, y) => y[1] - x[1])[0] ?? [];
+ if (top !== undefined) el.prepend(faceEl(top, 'quiet'));
+ });
+}
+// Esc steps back: from one person lit to everyone, and from everyone to the city (a focused building
+// first lets go of its focus)
+function whoEscape() {
+ if (lit >= 0) { light(-1); return true; }
+ if (!whoOpen || shared.uFocus.value >= 0) return false;
+ showWho(false);
+ return true;
}
diff --git a/web/streets.js b/web/streets.js
index f5fa74f..904549c 100644
--- a/web/streets.js
+++ b/web/streets.js
@@ -1,8 +1,8 @@
// Streets, derived rather than drawn: rasterise every city block, then a vector distance transform
// tells each patch of ground how far it is from the nearest block and in which direction. That one
// field gives us, for any city layout, where the streets are (near blocks), where their centre lines
-// run (where the distance peaks) and how wide each street is — so we can paint asphalt only where
-// streets actually are and drive traffic down the right lanes.
+// run (where two blocks are equally far) and how wide each street is — so we can paint asphalt only
+// where streets actually are and drive traffic down the right lanes.
import * as THREE from 'three';
import { LAND_LEAD } from './surfaces.js';
import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
@@ -83,17 +83,14 @@ export function buildStreets({ layout, B, files, inDeg, SIZE, t01 }) {
for (let i = 1; i < W; i++) relax(j * W + i, j * W + i - 1, -1, 0);
}
- // --- pack: R = distance in texels, B = across-street direction (to the nearest block) mod π
+ // --- pack: R = distance in texels; B, A = the street's centre line (below)
const data = new Uint8Array(W * W * 4);
const D = new Float32Array(W * W);
for (let p = 0; p < W * W; p++) {
const d = vx[p] === INF ? 255 : Math.sqrt(d2(p));
D[p] = d;
data[p * 4] = Math.min(255, Math.round(d));
- let a = Math.atan2(vz[p], vx[p]);
- if (a < 0) a += Math.PI;
- data[p * 4 + 2] = Math.round((a / Math.PI) * 255) % 256;
- data[p * 4 + 3] = 255;
+ data[p * 4 + 2] = 255;
}
const texture = new THREE.DataTexture(data, W, W, THREE.RGBAFormat);
texture.magFilter = THREE.LinearFilter;
@@ -103,6 +100,186 @@ export function buildStreets({ layout, B, files, inDeg, SIZE, t01 }) {
// streets are at most this far from a block (half an LA freeway); farther is open land
const maxHalf = Math.min(250, Math.max(3, (layout.unit * 1.2) / tex));
+ // --- centre lines: a street's centre is where its two blocks are equally far, so it runs where the
+ // nearest block changes from one texel to the next. From there a band a few texels wide either side
+ // learns which block is across the street; in it the distances to the two blocks' outlines give
+ // B = signed distance to the centre line (128 on it, 1/32 texel a step: signed, so it filters to 0
+ // on a line that falls between texels), A = 255 where a line may be drawn, and a second texture
+ // where along it the dashes fall: the length round the lower-numbered block's outline, as an angle
+ // (cos, sin) so it interpolates without a seam, over DASH_TURN dashes
+ const own = p => (vx[p] === INF ? -1 : label[p + vz[p] * W + vx[p]]);
+ const street = p => label[p] < 0 && D[p] <= maxHalf;
+ const other = new (blocks.length < 32767 ? Int16Array : Int32Array)(W * W).fill(-1);
+ const band = [];
+ // the centre: two street texels side by side whose nearest blocks differ, and face each other (not
+ // two blocks side by side, whose boundary runs on out into the street they both front)
+ const meet = (p, q) => {
+ if (!street(q)) return;
+ const mine = own(p), theirs = own(q);
+ if (mine < 0 || theirs < 0 || theirs === mine) return;
+ if (vx[p] * vx[q] + vz[p] * vz[q] > -0.5 * Math.hypot(vx[p], vz[p]) * Math.hypot(vx[q], vz[q])) return;
+ if (other[p] < 0) { other[p] = theirs; band.push(p); }
+ if (other[q] < 0) { other[q] = mine; band.push(q); }
+ };
+ for (let j = 0; j < W; j++) {
+ for (let i = 0; i < W; i++) {
+ const p = j * W + i;
+ if (!street(p)) continue;
+ if (i < W - 1) meet(p, p + 1);
+ if (j < W - 1) meet(p, p + W);
+ }
+ }
+ // out from the centre: far enough that every texel near the line has its neighbours filled in
+ const spread = (p, q) => {
+ if (other[q] >= 0 || !street(q)) return;
+ const theirs = own(q), across = theirs === own(p) ? other[p] : own(p);
+ if (theirs < 0 || across === theirs) return;
+ other[q] = across;
+ band.push(q);
+ };
+ for (let from = 0, depth = 0; depth < 8; depth++) {
+ const to = band.length;
+ for (let n = from; n < to; n++) {
+ const p = band[n], i = p % W;
+ if (i > 0) spread(p, p - 1);
+ if (i < W - 1) spread(p, p + 1);
+ if (p >= W) spread(p, p - W);
+ if (p < W * W - W) spread(p, p + W);
+ }
+ from = to;
+ }
+ // how far each street texel is from the water, in texels (8-neighbour steps, never more than the
+ // true distance; 255 = farther than a street is wide): which streets run along a bank, and how near
+ // the water a car may come
+ const toWater = new Uint8Array(W * W).fill(255);
+ let shore = [];
+ for (let p = 0; p < W * W; p++) {
+ if (wet[p] || !street(p)) continue;
+ const i = p % W;
+ if ((i > 0 && wet[p - 1]) || (i < W - 1 && wet[p + 1]) || (p >= W && wet[p - W]) || (p < W * W - W && wet[p + W])) { toWater[p] = 1; shore.push(p); }
+ }
+ for (let d = 2; d <= Math.min(254, maxHalf) && shore.length; d++) {
+ const next = [];
+ for (const p of shore) {
+ const i = p % W;
+ for (let dj = -W; dj <= W; dj += W) {
+ for (let di = -1; di <= 1; di++) {
+ const q = p + dj + di;
+ if ((di < 0 && i === 0) || (di > 0 && i === W - 1) || q < 0 || q >= W * W || toWater[q] !== 255 || wet[q] || !street(q)) continue;
+ toWater[q] = d;
+ next.push(q);
+ }
+ }
+ }
+ shore = next;
+ }
+ // the nearest point of a river bank or shore to (x, z): how far, and which way (fx, fz)
+ const banks = layout.groundIsWater ? [...layout.land, ...layout.shore, ...layout.water] : layout.water;
+ const bank = (x, z) => {
+ let best = Infinity, fx = 0, fz = 0;
+ for (const poly of banks) {
+ for (let m = 0; m < poly.length; m++) {
+ const a = poly[m], b = poly[(m + 1) % poly.length], ex = b[0] - a[0], ez = b[1] - a[1], L2 = ex * ex + ez * ez || 1;
+ const t = Math.max(0, Math.min(1, ((x - a[0]) * ex + (z - a[1]) * ez) / L2));
+ const px = a[0] + ex * t - x, pz = a[1] + ez * t - z;
+ if (px * px + pz * pz < best) { best = px * px + pz * pz; fx = px; fz = pz; }
+ }
+ }
+ const d = Math.sqrt(best);
+ return { d, fx: fx / (d || 1), fz: fz / (d || 1) };
+ };
+ // dashes a little over a quarter of a lot long, a power of two so the shader's pixel sizes divide it
+ const dash = 2 ** Math.round(Math.log2(layout.unit * 0.28)), DASH_TURN = 16;
+ const along = new Uint8Array(W * W * 2).fill(128);
+ const cum = new Map(); // block -> running length round its outline at each corner
+ const outline = id => {
+ if (!cum.has(id)) { const poly = blocks[id].poly, c = [0]; for (let k = 0; k < poly.length; k++) { const a = poly[k], b = poly[(k + 1) % poly.length]; c.push(c[k] + Math.hypot(b[0] - a[0], b[1] - a[1])); } cum.set(id, c); }
+ return cum.get(id);
+ };
+ // the side of a block's outline a street runs along at (x, z): of the sides about as near, the one
+ // running most along the street (across it is (nx, nz)). Distances are to that side's line, which
+ // carries on across the mouth of a side street, and so does the centre line; `over` is how far
+ // (x, z) is past the side's end, out into a junction
+ const ds = new Float64Array(Math.max(1, ...blocks.map(b => b.poly.length)));
+ const nearSide = (poly, x, z, nx, nz) => {
+ const n = poly.length;
+ let dMin = Infinity;
+ for (let m = 0; m < n; m++) {
+ const a = poly[m], b = poly[(m + 1) % n], ex = b[0] - a[0], ez = b[1] - a[1], L2 = ex * ex + ez * ez || 1;
+ const t = Math.max(0, Math.min(1, ((x - a[0]) * ex + (z - a[1]) * ez) / L2));
+ const dx = x - a[0] - ex * t, dz = z - a[1] - ez * t;
+ ds[m] = dx * dx + dz * dz;
+ if (ds[m] < dMin) dMin = ds[m];
+ }
+ const near = (Math.sqrt(dMin) + tex) ** 2;
+ let k = 0, bestAcross = Infinity;
+ for (let m = 0; m < n; m++) {
+ if (ds[m] > near) continue;
+ const a = poly[m], b = poly[(m + 1) % n], L = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;
+ const across = Math.abs(((b[0] - a[0]) * nx + (b[1] - a[1]) * nz) / L);
+ if (across < bestAcross) { bestAcross = across; k = m; }
+ }
+ const a = poly[k], b = poly[(k + 1) % poly.length], ex = b[0] - a[0], ez = b[1] - a[1], L = Math.hypot(ex, ez) || 1;
+ const t = ((x - a[0]) * ex + (z - a[1]) * ez) / L, side = ((x - a[0]) * ez - (z - a[1]) * ex) / L;
+ // (fx, fz): from (x, z) towards the side
+ return { k, t, d: Math.abs(side), fx: -Math.sign(side) * ez / L, fz: Math.sign(side) * ex / L, over: Math.max(0, -t, t - L) };
+ };
+ for (const p of band) {
+ if (wet[p]) continue;
+ const i = p % W, j = (p - i) / W;
+ const x = x0 + (i + 0.5) * tex, z = x0 + (j + 0.5) * tex;
+ const nL = Math.hypot(vx[p], vz[p]) || 1, nx = vx[p] / nL, nz = vz[p] / nL; // across the street
+ const a = Math.min(own(p), other[p]), b = Math.max(own(p), other[p]);
+ const sa = nearSide(blocks[a].poly, x, z, nx, nz), sb = nearSide(blocks[b].poly, x, z, nx, nz);
+ const width = (sa.d + sb.d) / tex;
+ if (width > maxHalf * 2 || width < 3) continue; // no block across; an alley
+ if (sa.fx * sb.fx + sa.fz * sb.fz > -0.5) continue; // not across the street from each other
+ // a river between them: the street runs along its bank (below), not across the river
+ if (toWater[p] * tex < Math.max(sa.d, sb.d)) {
+ const w = bank(x, z);
+ if ((w.fx * sa.fx + w.fz * sa.fz > 0.5 && w.d < sa.d) || (w.fx * sb.fx + w.fz * sb.fz > 0.5 && w.d < sb.d)) continue;
+ }
+ const off = (sb.d - sa.d) / 2 / tex;
+ data[p * 4 + 2] = Math.max(0, Math.min(255, Math.round(128 + off * 32)));
+ // across a side street narrower than this one the line carries on; out in a junction it stops.
+ // (Only near the line, so the mask's edge never falls where B changes sign)
+ if (Math.abs(off) < 3 && Math.max(sa.over, sb.over) <= (sa.d + sb.d) / 2 * 0.6) data[p * 4 + 3] = 255;
+ const turn = (outline(a)[sa.k] + sa.t) / (dash * DASH_TURN) * 2 * Math.PI;
+ along[p * 2] = Math.round(127.5 + 127.5 * Math.cos(turn));
+ along[p * 2 + 1] = Math.round(127.5 + 127.5 * Math.sin(turn));
+ }
+ // streets with a block on one side only: the asphalt stops maxHalf from the block where open land
+ // lies beyond, or at the bank of a river; the centre line runs halfway across
+ for (let p = 0; p < W * W; p++) {
+ if (data[p * 4 + 2] !== 255 || wet[p] || !street(p) || own(p) < 0) continue;
+ const d = D[p], w = toWater[p];
+ const byLand = Math.abs(d - maxHalf / 2) < 6, byWater = w < 255 && w >= d / 1.42 - 6 && w <= d + 6;
+ if (!byLand && !byWater) continue;
+ const i = p % W, j = (p - i) / W;
+ const x = x0 + (i + 0.5) * tex, z = x0 + (j + 0.5) * tex;
+ const nL = Math.hypot(vx[p], vz[p]) || 1, nx = vx[p] / nL, nz = vz[p] / nL; // towards the block
+ const a = own(p), sa = nearSide(blocks[a].poly, x, z, nx, nz);
+ let far = Infinity;
+ if (byWater) { const b = bank(x, z); if (b.fx * sa.fx + b.fz * sa.fz < -0.5) far = b.d; }
+ if (byLand) {
+ // open land past the far edge (not a wide street with a block across it)
+ const qi = Math.round(i - nx * (maxHalf - d + 2)), qj = Math.round(j - nz * (maxHalf - d + 2)), q = qj * W + qi;
+ if (qi >= 0 && qj >= 0 && qi < W && qj < W && label[q] < 0 && D[q] > maxHalf) far = Math.min(far, maxHalf * tex - sa.d);
+ }
+ if (!(far < Infinity) || (sa.d + far) / tex < 3) continue;
+ const off = (far - sa.d) / 2 / tex;
+ data[p * 4 + 2] = Math.max(0, Math.min(255, Math.round(128 + off * 32)));
+ if (Math.abs(off) < 3 && sa.over <= (sa.d + far) / 2 * 0.6) data[p * 4 + 3] = 255;
+ const turn = (outline(a)[sa.k] + sa.t) / (dash * DASH_TURN) * 2 * Math.PI;
+ along[p * 2] = Math.round(127.5 + 127.5 * Math.cos(turn));
+ along[p * 2 + 1] = Math.round(127.5 + 127.5 * Math.sin(turn));
+ }
+ const alongTexture = new THREE.DataTexture(along, W, W, THREE.RGFormat);
+ alongTexture.magFilter = THREE.LinearFilter;
+ alongTexture.minFilter = THREE.LinearFilter;
+ alongTexture.unpackAlignment = 1;
+ alongTexture.needsUpdate = true;
+
// --- which block each building stands on, for traffic weights and when the block "opens"
const sample = (x, z) => {
const i = Math.floor(toTex(x)), j = Math.floor(toTex(z));
@@ -138,7 +315,9 @@ export function buildStreets({ layout, B, files, inDeg, SIZE, t01 }) {
const bornAt = (x, z) => { const p = sample(x, z); return p < 0 ? 0 : bornOf(p); };
// --- lanes: every block is circled by a lane halfway between its kerb and the street's centre line,
- // so the two blocks either side of a street give it traffic in both directions
+ // so the two blocks either side of a street give it traffic in both directions. Each side of a block
+ // keeps its own distance, so a block with a wide road on one side and a canal on another drives
+ // both right
const lanes = [], curbs = [];
blocks.forEach((b, id) => {
if (b.type === 'park') return;
@@ -146,29 +325,51 @@ export function buildStreets({ layout, B, files, inDeg, SIZE, t01 }) {
let area = 0;
for (let k = 0, m = poly.length - 1; k < poly.length; m = k++) area += (poly[m][0] - poly[k][0]) * (poly[m][1] + poly[k][1]);
const out = area > 0 ? 1 : -1; // sign that turns an edge normal outward
- const gaps = [];
+ const gaps = poly.map(() => NaN), roads = poly.map(() => NaN);
for (let k = 0; k < poly.length; k++) {
const [ax, az] = poly[k], [bx, bz] = poly[(k + 1) % poly.length];
const L = Math.hypot(bx - ax, bz - az);
if (L < tex * 2) continue;
const nx = out * (bz - az) / L, nz = -out * (bx - ax) / L;
- // walk outward until the distance stops growing: that's the street's centre
- let best = 0;
- for (let s = 1; s < maxHalf; s++) {
- const p = sample((ax + bx) / 2 + nx * s * tex, (az + bz) / 2 + nz * s * tex);
- if (p < 0 || label[p] >= 0) break;
- if (D[p] < best - 0.5) break;
- best = Math.max(best, D[p]);
- }
- gaps.push(best);
+ // walk outward until the distance stops growing: that's the street's centre. A street with no
+ // block across has its centre halfway to the river bank, or to where the asphalt stops. A long
+ // side is walked from five places and the middle answer kept, so one bridge doesn't decide it
+ const walks = (L > tex * 16 ? [0.2, 0.35, 0.5, 0.65, 0.8] : [0.5]).map(f => {
+ let best = 0, s = 1;
+ for (; s < maxHalf; s++) {
+ const p = sample(ax + (bx - ax) * f + nx * s * tex, az + (bz - az) * f + nz * s * tex);
+ if (p < 0 || label[p] >= 0) break;
+ if (wet[p]) return [best, s / 2];
+ if (D[p] < best - 0.5) break;
+ best = Math.max(best, D[p]);
+ }
+ return [best, s >= maxHalf ? maxHalf / 2 : best];
+ });
+ const mid = i => walks.map(w => w[i]).sort((p, q) => p - q)[walks.length >> 1];
+ gaps[k] = mid(0);
+ roads[k] = mid(1);
}
- if (!gaps.length) return;
- gaps.sort((p, q) => p - q);
- const half = gaps[Math.floor(gaps.length * 0.3)];
+ const sides = gaps.filter(g => g === g).sort((p, q) => p - q);
+ if (!sides.length) return;
+ const typical = roads.filter(r => r === r).sort((p, q) => p - q);
+ const half = sides[Math.floor(sides.length * 0.3)], road = typical[Math.floor(typical.length * 0.3)];
if (half < 1.5) return; // alleys too narrow for a car
- lanes.push({ pts: offset(poly, out, half * tex * 0.5), lane: half * tex * 0.5, weight: 0.15 + 0.85 * Math.sqrt(weight[id] / maxW), born: Math.max(0, born[id] - LAND_LEAD) }); // traffic comes with the road
- // a line just off the kerb, where street trees go
- curbs.push({ pts: offset(poly, out, half * tex * 0.2), half: half * tex, born: born[id] });
+ // sides too short to measure (rounded corners) take the narrower of the sides either side of them
+ const fill = v => v.map((x, k) => {
+ if (x === x) return x;
+ let p = k, q = k;
+ do p = (p - 1 + v.length) % v.length; while (v[p] !== v[p]);
+ do q = (q + 1) % v.length; while (v[q] !== v[q]);
+ return Math.min(v[p], v[q]);
+ });
+ const lane = fill(roads).map(r => r * tex * 0.5), gap = fill(gaps);
+ if (road >= 1.5) lanes.push({ pts: offset(poly, out, lane), lane: road * tex * 0.5, weight: 0.15 + 0.85 * Math.sqrt(weight[id] / maxW), born: Math.max(0, born[id] - LAND_LEAD) }); // traffic comes with the road
+ // a line just off the kerb, where street trees go, kept far enough in from the lane that a tree's
+ // canopy (up to ~0.18 unit) clears a passing bus (~0.1 unit either side of the lane); a side too
+ // narrow for that gets none (where cars drive)
+ const room = lane.map(l => l - layout.unit * 0.28);
+ const kerb = room.map((r, k) => Math.max(0, Math.min(gap[k] * tex * 0.2, r)));
+ curbs.push({ pts: offset(poly, out, kerb), bare: room.map(r => road >= 1.5 && r < 0), half: half * tex, born: born[id] });
});
// --- boats: loops out on the water around each island
@@ -184,18 +385,25 @@ export function buildStreets({ layout, B, files, inDeg, SIZE, t01 }) {
const at = (x, z) => sample(x, z);
const drivable = (x, z) => { const p = at(x, z); return p >= 0 && label[p] < 0 && !wet[p] && D[p] <= maxHalf + 1; };
const navigable = (x, z) => { const p = at(x, z); return p >= 0 && wet[p] === 1; };
- return { texture, min: new THREE.Vector2(x0, x0), size: S, texel: tex, maxHalf, lanes, curbs, boats, drivable, navigable, blockBorn: born, bornAt };
+ // how far a car at (x, z) is from the water, at least
+ const clearance = (x, z) => { const p = at(x, z); return p < 0 || toWater[p] === 255 ? Infinity : (toWater[p] - 0.5) * tex; };
+ return { texture, alongTexture, dash, dashTurn: DASH_TURN, min: new THREE.Vector2(x0, x0), size: S, texel: tex, maxHalf, lanes, curbs, boats, drivable, navigable, clearance, blockBorn: born, bornAt };
}
// push a polygon outward by `d` (mitred corners, clamped so sharp corners don't spike)
+// d is one distance, or one per side (side k runs from poly[k] to poly[k + 1])
function offset(poly, out, d) {
const n = poly.length;
return poly.map((p, k) => {
const a = poly[(k - 1 + n) % n], b = poly[(k + 1) % n];
const e1 = norm([p[0] - a[0], p[1] - a[1]]), e2 = norm([b[0] - p[0], b[1] - p[1]]);
const n1 = [out * e1[1], -out * e1[0]], n2 = [out * e2[1], -out * e2[0]];
+ const d1 = typeof d === 'number' ? d : d[(k - 1 + n) % n], d2 = typeof d === 'number' ? d : d[k];
+ const det = n1[0] * n2[1] - n1[1] * n2[0];
+ // two sides at different distances meet where their offset lines cross; nearly straight on, halfway
+ if (d1 !== d2 && Math.abs(det) > 0.3) return [p[0] + (d1 * n2[1] - d2 * n1[1]) / det, p[1] + (d2 * n1[0] - d1 * n2[0]) / det];
const m = norm([n1[0] + n2[0], n1[1] + n2[1]]);
- const s = d / Math.max(0.35, m[0] * n1[0] + m[1] * n1[1]);
+ const s = (d1 + d2) / 2 / Math.max(0.35, m[0] * n1[0] + m[1] * n1[1]);
return [p[0] + m[0] * s, p[1] + m[1] * s];
});
}
@@ -252,7 +460,8 @@ export function buildTraffic({ streets, unit }) {
const routes = [];
const prep = (r, kind) => {
const step = Math.max(streets.texel, r.lane * 0.5);
- const pts = [], ok = [];
+ // each sample also keeps how far it is from the water: a car shows only where all of it is clear
+ const pts = [], ok = [], room = [];
for (let k = 0; k < r.pts.length; k++) {
const a = r.pts[k], b = r.pts[(k + 1) % r.pts.length];
const L = Math.hypot(b[0] - a[0], b[1] - a[1]), n = Math.max(1, Math.round(L / step));
@@ -260,11 +469,12 @@ export function buildTraffic({ streets, unit }) {
const x = a[0] + (b[0] - a[0]) * t / n, z = a[1] + (b[1] - a[1]) * t / n;
pts.push([x, z]);
ok.push(kind === 'boat' ? streets.navigable(x, z) : streets.drivable(x, z));
+ room.push(kind === 'boat' ? Infinity : streets.clearance(x, z));
}
}
const good = ok.filter(Boolean).length;
if (good < 3) return;
- routes.push({ ...r, kind, pts, ok, step: null, cum: null, good });
+ routes.push({ ...r, kind, pts, ok, room, step: null, cum: null, good });
};
streets.lanes.forEach(r => prep(r, 'car'));
streets.boats.forEach(r => prep(r, 'boat'));
@@ -299,9 +509,9 @@ export function buildTraffic({ streets, unit }) {
const remap = new Map(used.map((ri, k) => [ri, k]));
const kept = used.map(ri => {
const r = routes[ri], n = r.pts.length;
- const xy = new Float32Array(n * 2), cum = new Float32Array(r.cum), ok = new Uint8Array(n);
+ const xy = new Float32Array(n * 2), cum = new Float32Array(r.cum), ok = new Uint8Array(n), room = new Float32Array(r.room);
r.pts.forEach(([x, z], k) => { xy[k * 2] = x; xy[k * 2 + 1] = z; ok[k] = r.ok[k] ? 1 : 0; });
- return { kind: r.kind, born: r.born, L: r.L, n, xy, cum, ok };
+ return { kind: r.kind, born: r.born, L: r.L, n, xy, cum, ok, room };
});
for (const v of vehicles) v.ri = remap.get(v.ri);
routes.length = 0;
@@ -333,7 +543,7 @@ export function buildTraffic({ streets, unit }) {
let lo = 0, hi = r.cum.length - 1;
while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (r.cum[mid] <= s) lo = mid; else hi = mid; }
const nx = (lo + 1) % r.n;
- if (!r.ok[lo] || !r.ok[nx]) { mesh.setMatrixAt(k, hidden); return; }
+ if (!r.ok[lo] || !r.ok[nx] || r.room[lo] < v.len / 2 || r.room[nx] < v.len / 2) { mesh.setMatrixAt(k, hidden); return; }
const ax = r.xy[lo * 2], az = r.xy[lo * 2 + 1], bx = r.xy[nx * 2], bz = r.xy[nx * 2 + 1];
const t = (s - r.cum[lo]) / Math.max(1e-6, r.cum[lo + 1] - r.cum[lo]);
pos.set(ax + (bx - ax) * t, v.type === 'boat' ? 0 : baseY, az + (bz - az) * t);
diff --git a/web/studio.js b/web/studio.js
index a4736bc..5999627 100644
--- a/web/studio.js
+++ b/web/studio.js
@@ -270,7 +270,7 @@ export function buildStudio(ctx) {
// only what the street shader needs: copying the whole object would keep the routing closures (and the big field arrays they hold) alive
// a campus has footpaths, not roads: paved stone, no centre line
const pathC = layout?.paths ? new THREE.Color(layout.paths === 'dirt' ? S.dirt : S.plaza) : null;
- const street = streets && { texture: streets.texture, min: streets.min, size: streets.size, maxHalf: streets.maxHalf, asphalt: pathC || new THREE.Color(S.road), grass: new THREE.Color(S.land), mark: pathC || new THREE.Color('#e0d7b8') };
+ const street = streets && { texture: streets.texture, along: streets.alongTexture, dash: streets.dash, dashTurn: streets.dashTurn, texel: streets.texel, min: streets.min, size: streets.size, maxHalf: streets.maxHalf, asphalt: pathC || new THREE.Color(S.road), grass: new THREE.Color(S.land), mark: pathC || new THREE.Color('#e0d7b8') };
if (S.pixel && layout) addGroundDetail(groundMat, layout.ground === 'water' ? 'water' : 'street', { shared, street });
const ground = new THREE.Mesh(new THREE.PlaneGeometry(SIZE * 14, SIZE * 14).rotateX(-Math.PI / 2), groundMat);
ground.receiveShadow = true;
@@ -294,7 +294,7 @@ export function buildStudio(ctx) {
// the field's lookup tables were only needed to plan routes; the GPU keeps its own copy of the texture
const trees = S.pixel && layout ? timed('trees', () => buildTrees({ layout, B, streets, unit: layout.unit, plateStep, shared })) : null;
if (trees) scene.add(trees);
- if (streets) { streets.drivable = streets.navigable = streets.bornAt = null; streets.curbs = null; streets.lanes = streets.boats = null; streets.texture.onUpdate = t => { t.image.data = null; }; }
+ if (streets) { streets.drivable = streets.navigable = streets.clearance = streets.bornAt = null; streets.curbs = null; streets.lanes = streets.boats = null; streets.texture.onUpdate = streets.alongTexture.onUpdate = t => { t.image.data = null; }; }
const roadY = layout?.groundIsWater ? plateStep * 0.8 + 0.05 : 0.05;
// ---- district plinths (classic treemap only)
@@ -356,7 +356,7 @@ export function buildStudio(ctx) {
transformed *= step(0.001, grow);`;
const decl = `attribute vec4 aInfo; attribute float aDied, aHeat, aFocus; uniform float uTimeline;`;
mat.onBeforeCompile = sh => {
- Object.assign(sh.uniforms, { uTimeline: shared.uTimeline, uTime: shared.uTime, uFocus: shared.uFocus, uHover: shared.uHover,
+ Object.assign(sh.uniforms, { uTimeline: shared.uTimeline, uTime: shared.uTime, uFocus: shared.uFocus, uHover: shared.uHover, uLit: shared.uLit,
uWin: { value: unit / 7 }, uWinColor: { value: new THREE.Color(S.windowColor || '#ffffff') }, uWindows: { value: S.windows },
uAccent: { value: accent } });
sh.vertexShader = sh.vertexShader
@@ -371,11 +371,13 @@ export function buildStudio(ctx) {
vInfo = aInfo; vHeat = aHeat; vFocus = aFocus; vId = float(gl_InstanceID);`);
sh.fragmentShader = sh.fragmentShader
.replace('#include
', `#include
- uniform float uTimeline, uTime, uFocus, uHover, uWin, uWindows; uniform vec3 uWinColor, uAccent;
+ uniform float uTimeline, uTime, uFocus, uHover, uLit, uWin, uWindows; uniform vec3 uWinColor, uAccent;
varying vec3 vWP, vObj, vSz, vON; varying vec4 vInfo; varying float vHeat, vFocus, vId;
float hash2(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }`)
.replace('#include ', `#include
- if (uFocus >= 0.0) diffuseColor.rgb *= mix(0.35, 1.0, vFocus);
+ // one person's buildings lit: the rest fade to pale ghosts (darkened, they'd read as dark buildings)
+ float lum = dot(diffuseColor.rgb, vec3(0.299, 0.587, 0.114));
+ if (uFocus >= 0.0) diffuseColor.rgb = uLit > 0.5 ? mix(mix(mix(diffuseColor.rgb, vec3(lum), 0.8), vec3(0.76, 0.75, 0.73), 0.4), mix(vec3(lum), diffuseColor.rgb, 1.3) * 1.08, vFocus) : diffuseColor.rgb * mix(0.35, 1.0, vFocus);
if (abs(vId - uHover) < 0.5) diffuseColor.rgb = mix(diffuseColor.rgb, uAccent, 0.35);
diffuseColor.rgb = mix(diffuseColor.rgb, uAccent, vHeat * 0.6);`)
.replace('#include ', `#include
diff --git a/web/surfaces.js b/web/surfaces.js
index a2dabde..aca07ff 100644
--- a/web/surfaces.js
+++ b/web/surfaces.js
@@ -113,7 +113,7 @@ const GROUND = {
vec2 g = fract(c);
diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * 0.86, max(step(g.x, 0.12), step(g.y, 0.12)) * sFade(c));`,
// the open ground: asphalt only where streets are (near blocks, from a distance field), a dashed
- // centre line found as the ridge of that field, grass everywhere else
+ // centre line where the street's two blocks are equally far, grass everywhere else
street: /* glsl */`
vec2 suv = (vSurfWP.xz - uStreetMin) / uStreetSize;
vec4 st = texture2D(tStreet, suv);
@@ -124,15 +124,15 @@ const GROUND = {
// (on the same clock as the block rising beside it, so no road appears before its land)
if (inside > 0.5 && D > 0.5 && D <= uMaxHalf && st.g * 0.97 - ${LAND_LEAD.toFixed(3)} + 0.012 <= uTimeline) {
col = uAsphalt * (1.0 + (sHash(floor(vSurfWP.xz / P(1.5))) - 0.5) * 0.08);
- // across-street direction (towards the nearest block); the centre line is where D peaks across it
- float a = st.b * 3.14159265;
- vec2 n = vec2(cos(a), sin(a));
- float du = uPx * 0.9 / uStreetSize;
- float D1 = texture2D(tStreet, suv + n * du).r * 255.0, D2 = texture2D(tStreet, suv - n * du).r * 255.0;
- float ridge = step(D1, D + 0.02) * step(D2, D + 0.02) * step(1.5, D);
- vec2 along = vec2(-n.y, n.x);
- float dash = step(0.55, fract(dot(vSurfWP.xz, along) / P(8.0)));
- col = mix(col, uMark, ridge * dash);
+ // the centre line: a pixel wide (wider with the street, close up), dashed every 8 pixels or every
+ // dash, whichever is longer; how far along the street we are comes as an angle over uDashTurn dashes
+ float off = abs(st.b * 255.0 - 128.0) / 32.0 * uTexel;
+ if (st.a > 0.5 && off < max(P(1.0), uDash * 0.125) * 0.5) {
+ vec2 cs = texture2D(tAlong, suv).rg * 2.0 - 1.0;
+ float turn = atan(cs.y, cs.x) / 6.28318531;
+ float dashes = uDashTurn / min(max(P(8.0), uDash) / uDash, uDashTurn);
+ col = mix(col, uMark, step(0.55, fract(turn * dashes)));
+ }
}
diffuseColor.rgb = col;`,
};
@@ -165,9 +165,10 @@ export function addGroundDetail(material, kind, opts) {
const s = opts.street;
inject(material, {
...opts, withPart: false, fragment: GROUND.street, key: 'street',
- decl: '\nuniform sampler2D tStreet; uniform vec2 uStreetMin; uniform float uStreetSize, uMaxHalf; uniform vec3 uAsphalt, uGrass, uMark;',
+ decl: '\nuniform sampler2D tStreet, tAlong; uniform vec2 uStreetMin; uniform float uStreetSize, uMaxHalf, uTexel, uDash, uDashTurn; uniform vec3 uAsphalt, uGrass, uMark;',
uniforms: {
- tStreet: { value: s.texture }, uStreetMin: { value: s.min }, uStreetSize: { value: s.size },
+ tStreet: { value: s.texture }, tAlong: { value: s.along }, uStreetMin: { value: s.min }, uStreetSize: { value: s.size },
+ uTexel: { value: s.texel }, uDash: { value: s.dash }, uDashTurn: { value: s.dashTurn },
uMaxHalf: { value: s.maxHalf }, uAsphalt: { value: s.asphalt }, uGrass: { value: s.grass }, uMark: { value: s.mark },
},
});
diff --git a/web/trees.js b/web/trees.js
index 8b2ff2e..2e50b2c 100644
--- a/web/trees.js
+++ b/web/trees.js
@@ -140,6 +140,7 @@ export function buildTrees({ layout, B, streets, unit, plateStep, shared }) {
if (c.half < unit * 0.22) continue;
const pts = c.pts;
for (let k = 0; k < pts.length; k++) {
+ if (c.bare[k]) continue;
const a = pts[k], b = pts[(k + 1) % pts.length];
const L = Math.hypot(b[0] - a[0], b[1] - a[1]);
for (let t = spacing * 0.6; t < L - spacing * 0.6; t += spacing) {