// HK Site Analysis v3: the diagram series board. // Twelve small diagrams of the same site at the same frame and scale, one topic each, laid out on one board // (A3 landscape, also A2 and PNG), each diagram as its own 1080 x 1080 PNG, each map alone as a plate (for the 3D view), // and sheet 2: the exploded layer axonometric with leader labels. // v3: colour presets (opts.style: paper, mono, vivid, night), round frames (opts.shape: 'circle'), generic raster layers, // three new diagrams drawn by diagrams3.js through the kit K. // Every diagram is drawn only from data the app loaded (see app.js); nothing is invented. // Units: board and tiles in millimetres at A3; each map is a nested SVG with a 0..100 viewBox. // Type: system fonts only (site design standard); the same fonts render in the on-screen SVG and in the canvas exports. const FONT = "'Helvetica Neue', Helvetica, Arial, 'Microsoft JhengHei', 'PingFang TC', 'Noto Sans TC', sans-serif"; const TITLES = { fig: ['Figure-ground', '圖底關係'], hgt: ['Building heights', '建築物高度'], topo: ['Topography', '地形'], sun: ['Winter shadows', '冬至陰影'], sunh: ['Sunlight hours', '日照時數'], wind: ['Prevailing wind', '盛行風'], acc: ['Access and movement', '交通及人流'], walk: ['Walking distance', '步行範圍'], noise: ['Road noise (proxy)', '道路噪音(推算)'], green: ['Green and open space', '綠化及休憩空間'], view: ['Views and openness', '景觀及開揚度'], svf: ['Sky view factor', '天空可視因子'], }; export const KEYS = ['fig', 'hgt', 'topo', 'sun', 'sunh', 'wind', 'acc', 'walk', 'noise', 'green', 'view', 'svf']; const NEW3 = ['sunh', 'walk', 'svf']; export const STYLES = [ { id: 'paper', en: 'Paper', zh: '紙本' }, { id: 'mono', en: 'Line', zh: '線稿' }, { id: 'vivid', en: 'Vivid', zh: '鮮明' }, { id: 'night', en: 'Night', zh: '夜色' }, ]; const H_BRK = [10, 30, 60, 100, 150]; const VZ = 0.5; // heights drawn at half the plan scale (plan-oblique) // ---------- colour presets ---------- // paper = the v2 "style B" values exactly. Every other preset overrides the same tokens. const PAPER = { id: 'paper', dark: false, glow: false, paper: '#fbfaf7', ink: '#1d1c1a', ink2: '#4a4741', muted: '#7a756b', rule: '#d9d3c7', ground: '#f1eee8', road: '#ffffff', roadEdge: '#cfc9bf', bld: '#d9d4ca', hatch: null, site: '#e2483d', white: '#ffffff', halo: '#ffffff', panel: '#ffffff', panelOp: 0.93, onAccent: '#ffffff', eyebrow: '#9c4a2f', warn: '#9c4a2f', card: '#f2efe8', locTile: '#cfc8bb', num: null, figBg: '#ffffff', figBld: '#1d1c1a', hgtBg: '#f4f2ed', hRamp: ['#e6e4f3', '#c6c2e7', '#a29bd5', '#7d73bf', '#5c51a7', '#3b3283'], hShade: [29, 28, 26], hLine: null, topoRamp: [[248, 242, 229], [222, 190, 141], [150, 98, 50]], hillK: 0.38, contour: '#6e4a26', contourHalo: '#f6eedf', topoBld: '#ffffff', topoBldOp: 0.55, sunBg: '#f4f1ea', shadow: '#2f4a86', shadowOp: 0.17, sunBld: '#fdfcf9', sunBldLine: '#cfc6b6', sunText: '#9a6610', windBg: '#f3f2ee', windBld: '#dcd8d0', windText: '#1b6c83', windSummer: '#0f5a70', petalLine: '#ffffff', petalOp: 0.78, accBg: '#f4f2ed', accBld: '#e9e5de', accRoads: { Highway: '#b3ada2', 'Main Road': '#c4beb3', 'Secondary Road': '#d5d0c6', 'Restricted Road': '#e0dcd3', Track: '#e0dcd3', other: '#d3cec5' }, accDark: '#0a4f4b', noiseBg: '#fbfaf8', noiseBands: ['#f8e3ed', '#efb8d2', '#df7dab'], noiseBld: '#ffffff', noiseBldOp: 0.5, noiseBldLine: '#bdb5a8', noiseMinor: '#d9d4cb', noiseMajor: '#9e2a62', greenBg: '#f7f6f2', greenRoad: '#ebe7df', greenBld: '#dedad2', park: '#2f6b2a', greenCols: { wood: '#4f8a45', shrub: '#86b46b', grass: '#b5d58f', urban: '#93c47d', agri: '#d4e3a6' }, viewBg: '#f3f2ee', viewBld: '#d9d5cd', // for the v3 drawers (diagrams3.js): sunlight hours few -> many, sky view factor enclosed -> open, walk bands sunhRamp: ['#3b4a7a', '#6a5f8f', '#a8768a', '#dc9670', '#f2c36b', '#fbe7a6'], svfRamp: ['#2b2d42', '#4d5a7c', '#7d93b2', '#b3c8dc', '#e6eff6'], walk5: '#7a4fb5', walk10: '#b9a0dc', walkRest: '#d6d1c7', acc: { fig: '#1d1c1a', hgt: '#4b44a3', topo: '#a8713a', sun: '#e89a1c', sunh: '#e07b39', wind: '#2a9fc0', acc: '#13867f', walk: '#7a4fb5', noise: '#c43d7e', green: '#4f9a4a', view: '#3a6fd0', svf: '#4f7d99' }, }; // light architectural: black and grey line work, hatched blocks, one red site const MONO = { ...PAPER, id: 'mono', paper: '#ffffff', ink: '#111111', ink2: '#3b3b3b', muted: '#767676', rule: '#cfcfcf', ground: '#f2f2f2', road: '#ffffff', roadEdge: '#bdbdbd', bld: '#d4d4d4', hatch: '#8c8c8c', site: '#e3001b', eyebrow: '#111111', warn: '#111111', card: '#f4f4f4', locTile: '#cfcfcf', num: '#111111', figBg: '#ffffff', figBld: '#111111', hgtBg: '#f6f6f6', hRamp: ['#f1f1f1', '#d9d9d9', '#bdbdbd', '#999999', '#707070', '#444444'], hShade: [0, 0, 0], hLine: '#333333', topoRamp: [[252, 252, 252], [222, 222, 222], [150, 150, 150]], hillK: 0.32, contour: '#2b2b2b', contourHalo: '#ffffff', topoBld: '#ffffff', topoBldOp: 0.6, sunBg: '#f6f6f6', shadow: '#000000', shadowOp: 0.13, sunBld: '#ffffff', sunBldLine: '#9a9a9a', sunText: '#111111', windBg: '#f6f6f6', windBld: '#dddddd', windText: '#111111', windSummer: '#111111', petalLine: '#ffffff', petalOp: 0.5, accBg: '#f6f6f6', accBld: '#e4e4e4', accRoads: { Highway: '#a6a6a6', 'Main Road': '#b8b8b8', 'Secondary Road': '#cccccc', 'Restricted Road': '#dddddd', Track: '#dddddd', other: '#d0d0d0' }, accDark: '#111111', noiseBg: '#ffffff', noiseBands: ['#f0f0f0', '#d9d9d9', '#b9b9b9'], noiseBld: '#ffffff', noiseBldOp: 0.55, noiseBldLine: '#a8a8a8', noiseMinor: '#d6d6d6', noiseMajor: '#111111', greenBg: '#fafafa', greenRoad: '#eeeeee', greenBld: '#dcdcdc', park: '#111111', greenCols: { wood: '#5e5e5e', shrub: '#8a8a8a', grass: '#c2c2c2', urban: '#a6a6a6', agri: '#e0e0e0' }, viewBg: '#f6f6f6', viewBld: '#dadada', sunhRamp: ['#3a3a3a', '#636363', '#8c8c8c', '#b4b4b4', '#d9d9d9', '#f7f7f7'], svfRamp: ['#262626', '#575757', '#8a8a8a', '#bdbdbd', '#efefef'], walk5: '#111111', walk10: '#8a8a8a', walkRest: '#d9d9d9', acc: { fig: '#111111', hgt: '#111111', topo: '#111111', sun: '#111111', sunh: '#111111', wind: '#111111', acc: '#111111', walk: '#111111', noise: '#111111', green: '#111111', view: '#111111', svf: '#111111' }, }; // colourful diagram look: each map sits on a soft colour field of its own accent const VIVID = { ...PAPER, id: 'vivid', paper: '#fbf7ef', ink: '#1b1a2e', ink2: '#3f3d57', muted: '#77748a', rule: '#ddd5c6', ground: '#f4eee2', road: '#ffffff', roadEdge: '#d7cdb9', bld: '#d8cfbe', site: '#ff3b2f', eyebrow: '#ff3b2f', warn: '#c2321f', card: '#f1eadb', locTile: '#d3c8b3', figBg: '#ffe2d3', figBld: '#1f2b5b', hgtBg: '#eef0fb', hRamp: ['#fff1a8', '#ffd166', '#f79d65', '#ef476f', '#b5179e', '#5a189a'], hShade: [30, 20, 60], topoRamp: [[236, 247, 220], [160, 210, 140], [52, 118, 86]], hillK: 0.34, contour: '#1f5136', contourHalo: '#eef7e4', topoBld: '#ffffff', topoBldOp: 0.6, sunBg: '#fff2cf', shadow: '#4b3fa8', shadowOp: 0.2, sunBld: '#ffffff', sunBldLine: '#e7cf96', sunText: '#a24f00', windBg: '#dff3fa', windBld: '#c3e3ee', windText: '#00617f', windSummer: '#023e5a', petalLine: '#ffffff', petalOp: 0.8, accBg: '#e3f5ef', accBld: '#c9e8dd', accRoads: { Highway: '#ffffff', 'Main Road': '#ffffff', 'Secondary Road': '#fbfffd', 'Restricted Road': '#f2fbf8', Track: '#f2fbf8', other: '#f6fcfa' }, accDark: '#004d40', noiseBg: '#fff0f6', noiseBands: ['#ffd3e6', '#ff9cc7', '#ff5c9d'], noiseBld: '#ffffff', noiseBldOp: 0.65, noiseBldLine: '#f0b6cf', noiseMinor: '#ffffff', noiseMajor: '#9c004e', greenBg: '#f1f8e6', greenRoad: '#ffffff', greenBld: '#dcd8cc', park: '#0f5a2c', greenCols: { wood: '#2e8b57', shrub: '#5fbf5a', grass: '#a8e063', urban: '#7bd389', agri: '#e3f59a' }, viewBg: '#e8edff', viewBld: '#c9d4f4', sunhRamp: ['#3d2c8d', '#7b2cbf', '#c9408a', '#ff7b54', '#ffb347', '#ffe66d'], svfRamp: ['#1d2b64', '#2f5fa8', '#3fa7d6', '#8fd3e8', '#e0f7fa'], walk5: '#8e44ec', walk10: '#c9a3ff', walkRest: '#d9d0e6', acc: { fig: '#1f2b5b', hgt: '#7a2fc0', topo: '#2e8b57', sun: '#ff9f1c', sunh: '#ff7a00', wind: '#00a6d6', acc: '#00a087', walk: '#8e44ec', noise: '#e5007a', green: '#3fa34d', view: '#3d5afe', svf: '#1aa3b8' }, }; // dark sheet, light line work, glowing accents const NIGHT = { ...PAPER, id: 'night', dark: true, glow: true, paper: '#0f1217', ink: '#ece9e2', ink2: '#c4c1b9', muted: '#8d8b86', rule: '#2e333b', ground: '#161a21', road: '#2b313b', roadEdge: '#3d4450', bld: '#333a46', site: '#ff5b4d', white: '#ffffff', halo: '#0f1217', panel: '#1b2029', panelOp: 0.95, onAccent: '#0f1217', eyebrow: '#ffb36b', warn: '#ffb36b', card: '#161a21', locTile: '#3a414d', figBg: '#090b0e', figBld: '#e9e5db', hgtBg: '#12161c', hRamp: ['#283057', '#334a92', '#3f6fcf', '#5fa0f0', '#9dd0ff', '#e8f6ff'], hShade: [5, 7, 12], topoRamp: [[24, 28, 35], [78, 68, 54], [205, 158, 96]], hillK: 0.5, contour: '#e0ac6c', contourHalo: '#0f1217', topoBld: '#0f1217', topoBldOp: 0.5, sunBg: '#272c35', shadow: '#04060a', shadowOp: 0.36, sunBld: '#3e4553', sunBldLine: '#5b6475', sunText: '#ffc56b', windBg: '#151a21', windBld: '#2a303a', windText: '#8fe3ff', windSummer: '#d2f6ff', petalLine: '#0f1217', petalOp: 0.8, accBg: '#141820', accBld: '#262c36', accRoads: { Highway: '#4d5562', 'Main Road': '#434a56', 'Secondary Road': '#3a404b', 'Restricted Road': '#323843', Track: '#323843', other: '#363c47' }, accDark: '#a6f7e9', noiseBg: '#12151b', noiseBands: ['#3a1f3f', '#5e2456', '#962f79'], noiseBld: '#0f1217', noiseBldOp: 0.55, noiseBldLine: '#3a414d', noiseMinor: '#2f353f', noiseMajor: '#ff6cb6', greenBg: '#12161b', greenRoad: '#20252d', greenBld: '#2b313b', park: '#bdf7a6', greenCols: { wood: '#2f7d46', shrub: '#4ea35a', grass: '#7cc46a', urban: '#5fb877', agri: '#a0cf6e' }, viewBg: '#151a21', viewBld: '#2c323d', sunhRamp: ['#1c2233', '#3b3566', '#7a4a7e', '#c46a5e', '#f2a94e', '#ffe08a'], svfRamp: ['#0d1017', '#1f3550', '#2f6f8f', '#5fb6c9', '#bff3f5'], walk5: '#c18cff', walk10: '#6f55a8', walkRest: '#30363f', acc: { fig: '#ece9e2', hgt: '#7fa8ff', topo: '#e0ac6c', sun: '#ffb547', sunh: '#ffcf5a', wind: '#4fd1ff', acc: '#2fe0c4', walk: '#c18cff', noise: '#ff4fa3', green: '#6fdc7a', view: '#6ea8ff', svf: '#7fe7ff' }, }; const THEMES = { paper: PAPER, mono: MONO, vivid: VIVID, night: NIGHT }; // board geometry (mm, A3 landscape): 6 x 2 tiles, title band above, key strip and credits below const BW = 420, BH = 297, M = 10, GAP = 5, MW = (BW - 2 * M - 5 * GAP) / 6, TH_CAP = 31, TILE_H = MW + TH_CAP; const GRID_Y = 50, ROW_GAP = 5; const slot = (i) => ({ x: M + (i % 6) * (MW + GAP), y: GRID_Y + Math.floor(i / 6) * (TILE_H + ROW_GAP) }); const STRIP_Y = GRID_Y + 2 * TILE_H + ROW_GAP + 3.5; export function createBoard(L) { const { T, isZh, compass, sunPos, fmtArea, nm, CELL, ROAD } = L; const DG3 = L.diagrams3 || {}; let C = PAPER, SHAPE = 'square', TH = {}; function useTheme(opts = {}) { C = THEMES[opts && opts.style] || PAPER; SHAPE = opts && opts.shape === 'circle' ? 'circle' : 'square'; TH = {}; for (const k of KEYS) { // canonical titles live here; diagrams3.js titles (L.diagrams3[k].en/zh) are overridden so the board and the 3D view agree const tt = TITLES[k]; TH[k] = { c: C.acc[k], en: tt[0], zh: tt[1] }; } return C; } useTheme(); const meas = document.createElement('canvas').getContext('2d'); const tw = (s, size, bold) => { meas.font = `${bold ? 'bold ' : ''}${size * 20}px ${FONT}`; return meas.measureText(s).width / 20; }; function wrap(s, size, width, bold) { const out = []; let cur = ''; const toks = isZh() ? (String(s).match(/[A-Za-z0-9.,:;()°%+\-/·]+\s?|\s|./g) || []) : String(s).split(/(\s+)/); for (const t of toks) { const n = cur + t; if (tw(n.trim(), size, bold) > width && cur.trim()) { out.push(cur.trim()); cur = t.trimStart(); } else cur = n; } if (cur.trim()) out.push(cur.trim()); return isZh() ? kinsoku(out) : out; } // zh: a line never starts with closing punctuation; the mark moves up onto the end of the line before const NO_START = '。,、;:)」』!?》〉】.,.;:)'; function kinsoku(lines) { for (let i = 1; i < lines.length; i++) { let ln = lines[i], mv = ''; while (ln && NO_START.includes(ln[0])) { mv += ln[0]; ln = ln.slice(1).trimStart(); } if (!mv) continue; lines[i - 1] += mv; lines[i] = ln; if (!ln) { lines.splice(i, 1); i--; } } return lines; } const esc = (s) => String(s == null ? '' : s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); const f1 = (v) => (Math.round(v * 10) / 10).toString(), f2 = (v) => (Math.round(v * 100) / 100).toString(); function tx(x, y, s, { size = 2.6, bold = false, weight = null, fill = C.ink, anchor = 'start', halo = null, rot = 0, ls = 0, op = 1, role = null } = {}) { const tr = rot ? ` transform="rotate(${f2(rot)} ${f2(x)} ${f2(y)})"` : ''; const h = halo ? ` stroke="${halo}" stroke-width="${f2(size * 0.3)}" stroke-linejoin="round" paint-order="stroke"` : ''; const wt = weight ? ` font-weight="${weight}"` : bold ? ' font-weight="bold"' : ''; // pin the drawn width to the measured one: at small screen sizes Chromium rounds glyph advances and draws text 10 to 25% // wider than measured, which pushed zh captions into the next tile; exports are near 1:1 so the adjustment there is tiny const str = String(s == null ? '' : s), fit = !ls && str.length > 2 ? ` textLength="${f2(tw(str, size, bold || (weight && weight >= 600)))}" lengthAdjust="spacingAndGlyphs"` : ''; return `${esc(s)}`; } // is a map point inside the drawn frame with margin m (square: the 0..100 box; round: the circle) const inMap = (X, Y, m = 2) => (SHAPE === 'circle' ? Math.hypot(X - 50, Y - 50) <= 50 - m : X >= m && X <= 100 - m && Y >= m && Y <= 100 - m); const gl = () => (C.glow ? ' filter="url(#hsa-glow)"' : ''); const bldFill = () => (C.hatch ? 'url(#hsa-hatch)' : C.bld); // shared definitions: round clip (map units), glow (night), hatch (mono blocks) function defsSVG() { return `` + `` + ``; } // ---------- geometry helpers in map units ---------- function proj(res) { const f = res.f, F = f.E1 - f.E0, U = 100 / F; const X = (E) => 50 + (E - f.cE) * U, Y = (N) => 50 - (N - f.cN) * U; return { F, U, X, Y }; } const sArea = (pts) => { let s = 0; for (let i = 0, n = pts.length; i < n; i++) { const p = pts[i], q = pts[(i + 1) % n]; s += p[0] * q[1] - q[0] * p[1]; } return s / 2; }; // rings in screen coords -> path; outer rings one way round, holes the other, so non-zero fill unions overlaps function ringsPath(list) { const o = []; for (const { pts, hole } of list) { if (pts.length < 3) continue; let p = pts; const a = sArea(p); if ((a > 0) === !!hole) p = p.slice().reverse(); o.push('M' + p.map(([x, y]) => `${f1(x)} ${f1(y)}`).join('L') + 'Z'); } return o.join(''); } function blocksPath(res, blocks, p) { const list = []; for (const b of blocks) { list.push({ pts: b.ring.map(([E, N]) => [p.X(E), p.Y(N)]) }); for (const h of b.holes || []) list.push({ pts: h.map(([E, N]) => [p.X(E), p.Y(N)]), hole: true }); } return ringsPath(list); } const lineD = (pts, p) => 'M' + pts.map(([E, N]) => `${f1(p.X(E))} ${f1(p.Y(N))}`).join('L'); function roadsSVG(res, p, { color = C.road, minW = 0.45, scale = 1, classes = null, op = 1 } = {}) { const runs = res.roadRuns.filter((r) => r.cls !== 'Tunnel' && ROAD[r.cls] && (!classes || classes.includes(r.cls))).sort((a, b) => ROAD[b.cls].rank - ROAD[a.cls].rank); const by = new Map(); for (const r of runs) { const k = r.cls; if (!by.has(k)) by.set(k, []); by.get(k).push(lineD(r.pts, p)); } let o = ''; for (const [cls, ds] of by) { const w = Math.max(minW, ROAD[cls].w * p.U * scale); o += ``; } return o; } const siteD = (res, p) => 'M' + res.R.map(([E, N]) => `${f2(p.X(E))} ${f2(p.Y(N))}`).join('L') + 'Z'; function siteSVG(res, p, { fill = 0.1, dash = false, w = 0.8 } = {}) { return ``; } function baseSVG(res, p, { ground = C.ground, bld = bldFill(), roads = true } = {}) { let o = ``; if (roads) o += roadsSVG(res, p); o += ``; return o; } // north arrow (top right) and a true scale bar (bottom left); in a round frame both sit in the free corners function northScale(res, p, { light = false, north = true, scale = true, round = SHAPE === 'circle' } = {}) { const ink = light ? '#fff' : C.ink, bg = round ? 'none' : light ? 'rgba(0,0,0,0.35)' : C.dark ? 'rgba(15,18,23,0.85)' : 'rgba(255,255,255,0.88)'; let o = ''; if (scale) { const Lm = [10, 20, 25, 50, 100, 200, 250, 500].filter((v) => v <= p.F / (round ? 5 : 4)).pop() || 10, len = Lm * p.U, by = round ? 96.6 : 94; o += ``; if (!round) o += ``; o += ``; o += tx(4, by - 1, '0', { size: 2.3, fill: ink }) + tx(4 + len, by - 1, T([`${Lm} m`, `${Lm} 米`]), { size: 2.3, fill: ink, anchor: 'middle' }); o += ''; } if (north) { o += `${bg !== 'none' ? `` : ''}${tx(0, 8.6, 'N', { size: 2.4, bold: true, fill: ink, anchor: 'middle' })}`; } return o; } // a panel in the middle of a map: says plainly that a layer is missing or empty instead of leaving it blank function noteBox(head, sub, y = 20) { const w = Math.min(84, Math.max(tw(head, 3, true), sub ? tw(sub, 2.4) : 0) + 10); return `` + tx(50, y, head, { size: 3, bold: true, anchor: 'middle', fill: C.ink }) + (sub ? tx(50, y + 5, sub, { size: 2.4, anchor: 'middle', fill: C.muted }) : '') + ''; } const LEGEND_KINDS = ['box', 'ring', 'line', 'dash', 'dot', 'bus', 'mtr', 'lr', 'arrow', 'text', 'ramp']; function kit() { return { C, TH, dark: !!C.dark, glow: !!C.glow, shape: SHAPE, style: C.id, tx, f1, f2, esc, wrap, tw, T, isZh, compass, proj, lineD, sArea, baseSVG, siteSVG, roadsSVG, ringsPath, blocksPath, noteBox, northScale, legendKinds: LEGEND_KINDS, bldFill: bldFill() }; } // ---------- derived numbers and rasters, once per result ---------- function prepare(res) { if (res._b) return res._b; const p = proj(res), F = p.F, R0 = F / 2, [cx, cy] = res.siteC; const B = { p, topoBy: {} }; // coverage inside a circle of radius F/2 round the site, the site itself left out (2 m pixels) const px = 2, n = Math.ceil((2 * R0) / px); const cov = (ringsList) => { const cv = document.createElement('canvas'); cv.width = cv.height = n; const x = cv.getContext('2d'); const tx_ = (E) => (E - (cx - R0)) / px, ty_ = (N) => ((cy + R0) - N) / px; x.fillStyle = '#000'; x.beginPath(); for (const r of ringsList) { r.forEach(([E, N], i) => (i ? x.lineTo(tx_(E), ty_(N)) : x.moveTo(tx_(E), ty_(N)))); x.closePath(); } x.fill('nonzero'); const d = x.getImageData(0, 0, n, n).data; let hit = 0, tot = 0; for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) { const E = cx - R0 + (i + 0.5) * px, N = cy + R0 - (j + 0.5) * px; if (Math.hypot(E - cx, N - cy) > R0 || L.inPoly(E, N, res.R)) continue; tot++; if (d[(j * n + i) * 4 + 3] > 127) hit++; } return tot ? (100 * hit) / tot : 0; }; B.radius = R0; B.built = cov(res.blocks.filter((b) => !b.onSite && Math.hypot(b.c[0] - cx, b.c[1] - cy) < R0 + 200).map((b) => b.ring)); const x = res.extra || {}; if (x.green && !x.green.error) { B.green = cov(x.green.map((g) => g.ring)); const byC = new Map(); for (const g of x.green) byC.set(g.cls, (byC.get(g.cls) || 0) + Math.abs(sArea(g.ring))); B.greenMain = [...byC.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] || null; } // nearest busier road (highway / main road) to the site edge let best = null; for (const r of res.roadRuns) { if (r.cls !== 'Highway' && r.cls !== 'Main Road') continue; for (let i = 0; i < r.pts.length - 1; i++) { const a = r.pts[i], b = r.pts[i + 1]; let d = Infinity; for (const q of res.R) d = Math.min(d, L.segDist(q[0], q[1], a[0], a[1], b[0], b[1])); if (L.inPoly(a[0], a[1], res.R)) d = 0; d = Math.max(0, d - ROAD[r.cls].w / 2); if (!best || d < best.d) best = { d, r }; } } B.busy = best; res._b = B; return B; } // topography colour at t (0..1) in the current preset's ramp const topoCol = (t) => { const [c0, c1, c2] = C.topoRamp; return t < 0.5 ? c0.map((v, m) => v + (c1[m] - v) * t * 2) : c1.map((v, m) => v + (c2[m] - v) * (t - 0.5) * 2); }; const lum = (hex) => { const n = parseInt(hex.slice(1), 16); return (0.2126 * (n >> 16) + 0.7152 * ((n >> 8) & 255) + 0.0722 * (n & 255)) / 255; }; const rgbHex = (c) => '#' + c.map((v) => Math.round(v).toString(16).padStart(2, '0')).join(''); // topography raster per preset: elevation bands in the ramp, multiplied by the hill shade function topoRaster(res, B) { if (B.topoBy[C.id]) return B.topoBy[C.id]; const p = B.p; // bands at the contour interval, but the ramp spans at least 30 m, so a flat site stays pale instead of looking steep const { gnx, gny, gz, hill } = res.grid, iv = res.interval, lo = Math.floor(res.fmin / iv) * iv, span = Math.max(30, res.fmax - lo); const cv = document.createElement('canvas'); cv.width = gnx; cv.height = gny; const xx = cv.getContext('2d'), im = xx.createImageData(gnx, gny); for (let j = 0; j < gny; j++) for (let i = 0; i < gnx; i++) { const k = j * gnx + i, o = ((gny - 1 - j) * gnx + i) * 4, t = Math.min(1, Math.max(0, (Math.floor((gz[k] - lo) / iv) * iv) / span)); const c = topoCol(t), sh = 1 - C.hillK * hill[k]; im.data[o] = c[0] * sh; im.data[o + 1] = c[1] * sh; im.data[o + 2] = c[2] * sh; im.data[o + 3] = 255; } xx.putImageData(im, 0, 0); const { gx0, gy0 } = res.grid; return (B.topoBy[C.id] = { id: 'topo', canvas: cv, url: cv.toDataURL(), x: p.X(gx0 - CELL / 2), y: p.Y(gy0 + (gny - 0.5) * CELL), w: gnx * CELL * p.U, h: gny * CELL * p.U, lo, hi: lo + span }); } const urls = new WeakMap(); const rasterURL = (r) => r.url || urls.get(r.canvas) || (urls.set(r.canvas, r.canvas.toDataURL()), urls.get(r.canvas)); // ---------- the diagrams: each returns map SVG (0..100), legend items, takeaway and optional rasters ---------- const D = {}; // the site is taken as cleared: 'tallest' never counts a block on the site (app.js already leaves them out; filtered again here) const offTall = (res) => (res.tallest || []).filter((t) => !(t.b && t.b.onSite)); function onSiteTop(res) { if (res.tallestOnSite && Number.isFinite(res.tallestOnSite.top)) return res.tallestOnSite.top; let z = null; for (const b of res.frameBlocks || []) if (b.onSite && (z === null || b.zt > z)) z = b.zt; return z; } D.fig = (res, p, B) => { let o = ``; o += ``; o += ``; // the radius the figure is measured in o += ``; return { svg: o, legend: [{ k: 'box', c: C.figBld, t: T(['Buildings', '建築物']) }, { k: 'box', c: C.site, t: T(['Site', '地盤']) }, { k: 'ring', c: C.site, t: T([`${B.radius} m radius`, `半徑 ${B.radius} 米`]) }], take: T([`Within ${B.radius} m of the site, buildings cover ${B.built.toFixed(0)}% of the ground.`, `地盤 ${B.radius} 米範圍內,建築物覆蓋 ${B.built.toFixed(0)}% 地面。`]), }; }; D.hgt = (res, p) => { let o = `` + roadsSVG(res, p); const ramp = C.hRamp, [sr, sg, sb] = C.hShade; const cls = (H) => { let i = 0; while (i < H_BRK.length && H >= H_BRK[i]) i++; return i; }; const mix = (hex, m) => { const n = parseInt(hex.slice(1), 16), r = n >> 16, g = (n >> 8) & 255, b = n & 255, k = 1 - m; return `rgb(${Math.round(r * k + sr * m)},${Math.round(g * k + sg * m)},${Math.round(b * k + sb * m)})`; }; const groups = new Map(); for (const b of res.frameBlocks) { if (b.onSite) continue; const k = b.id; if (!groups.has(k)) groups.set(k, []); groups.get(k).push(b); } const glist = [...groups.values()].map((bs) => ({ bs: bs.sort((a, b) => a.zb - b.zb || b.c[1] - a.c[1]), n: Math.max(...bs.map((b) => b.c[1])) })); glist.sort((a, b) => b.n - a.n); // north first, so nearer (southern) blocks overlap o += ``; for (const g of glist) for (const b of g.bs) { const H = Math.max(0.5, b.H), vb = Math.max(0, b.zb - b.gmin) * p.U * VZ, vt = H * p.U * VZ; const col = ramp[cls(H)], ring = sArea(b.ring) > 0 ? b.ring : b.ring.slice().reverse(); // counter-clockwise in E,N let wa = '', wb = ''; for (let i = 0; i < ring.length; i++) { const a = ring[i], c = ring[(i + 1) % ring.length], dx = c[0] - a[0], dy = c[1] - a[1]; if (dx <= 0) continue; // only walls facing the viewer (south side) const q = `M${f1(p.X(a[0]))} ${f1(p.Y(a[1]) - vb)}L${f1(p.X(c[0]))} ${f1(p.Y(c[1]) - vb)}L${f1(p.X(c[0]))} ${f1(p.Y(c[1]) - vt)}L${f1(p.X(a[0]))} ${f1(p.Y(a[1]) - vt)}Z`; if (dy > 0) wa += q; else wb += q; // outward normal points east / west } if (wa) o += ``; if (wb) o += ``; o += ``; } o += ``; // the three tallest: top level in mPD over the roof for (const t of offTall(res).slice(0, 3)) { const x = p.X(t.b.c[0]), y = p.Y(t.b.c[1]) - t.b.H * p.U * VZ, yb = p.Y(t.b.c[1]); if (x >= 3 && x <= 97 && y >= 6 && y <= 97 && inMap(x, y - 5, 5)) { o += ``; o += tx(x, y - 4.8, `${t.top.toFixed(0)} mPD`, { size: 2.5, bold: true, anchor: 'middle', halo: C.halo, fill: C.ink }); } else if (y < 6 && x >= 6 && x <= 94 && yb > 12 && yb <= 97) { // a tall tower whose roof runs off the top of the map: label it at the top of the part that is drawn let yl = 4.6; while (yl < yb - 4 && !inMap(x, yl - 2, 3)) yl += 1; if (yl < yb - 4) o += tx(x, yl, `${t.top.toFixed(0)} mPD ↑`, { size: 2.5, bold: true, anchor: 'middle', halo: C.halo, fill: C.ink }); } } const hs = res.frameBlocks.filter((b) => !b.onSite).map((b) => b.H).sort((a, b) => a - b), med = hs.length ? hs[Math.floor(hs.length / 2)] : 0; if (!hs.length) o += noteBox(T(['No buildings recorded', '沒有建築物記錄']), T(['in this frame (LandsD)', '此範圍內(地政總署)'])); const estPct = res.inFrame ? (100 * res.est) / res.inFrame : 0; const estTxt = estPct >= 20 ? [` ${res.est} of ${res.inFrame} heights estimated from storeys.`, `${res.inFrame} 座中有 ${res.est} 座按樓層估算高度。`] : ['', '']; const t0 = offTall(res)[0], tn = t0 ? nm(t0.en, t0.tc) || T(['an unnamed block', '一座未命名建築物']) : ''; const zOn = onSiteTop(res), onTxt = zOn !== null ? [` Existing on site up to ${zOn.toFixed(0)} mPD (taken as cleared).`, `地盤現有建築物最高 ${zOn.toFixed(0)} mPD(假設已清空)。`] : ['', '']; return { svg: o, legend: [{ k: 'ramp', cs: ramp, ticks: ['0', ...H_BRK.map(String)], t: T(['height above ground, m', '離地高度(米)']) }], take: t0 ? T([`Tallest nearby: ${tn}, ${t0.top.toFixed(1)} mPD, ${t0.d < 1 ? 'on the site edge' : t0.d.toFixed(0) + ' m ' + compass(t0.br)}.${onTxt[0]} Typical block ${med.toFixed(0)} m.${estTxt[0]} Heights drawn at half scale.`, `附近最高:${tn},${t0.top.toFixed(1)} mPD,${t0.d < 1 ? '緊貼地盤' : `位於${compass(t0.br)}面 ${t0.d.toFixed(0)} 米`}。${onTxt[1]}一般建築體高 ${med.toFixed(0)} 米。${estTxt[1]}高度以一半比例繪畫。`]) : T([`No buildings recorded off the site in the frame.${onTxt[0]}`, `範圍內地盤以外沒有建築物記錄。${onTxt[1]}`]), }; }; D.topo = (res, p, B) => { const tp = topoRaster(res, B); let o = ''; for (const c of res.contours) { o += ``; } o += ``; o += siteSVG(res, p, { fill: 0.08 }); // index contour labels, a few, spread out const placed = []; for (const c of res.contours.filter((c) => c.idx)) { let n = 0; for (let si = Math.floor(c.segs.length / 4); si < c.segs.length && n < 2; si += Math.max(1, Math.floor(c.segs.length / 6))) { const [a, b, cc, dd] = c.segs[si], mx = (p.X(a) + p.X(cc)) / 2, my = (p.Y(b) + p.Y(dd)) / 2; if (mx < 8 || mx > 92 || my < 12 || my > 86 || !inMap(mx, my, 8) || placed.some(([x, y]) => Math.hypot(x - mx, y - my) < 22)) continue; let ang = (Math.atan2(p.Y(dd) - p.Y(b), p.X(cc) - p.X(a)) * 180) / Math.PI; if (ang > 90) ang -= 180; if (ang < -90) ang += 180; o += tx(mx, my + 0.8, String(c.v), { size: 2.2, fill: C.contour, anchor: 'middle', halo: C.contourHalo, rot: ang }); placed.push([mx, my]); n++; } } // fall arrow through the site const fall = res.grad * 100, [sx, sy] = [p.X(res.siteC[0]), p.Y(res.siteC[1])]; if (fall >= 1) { const a = (res.fallDir * Math.PI) / 180, Lr = Math.max(9, Math.min(22, Math.sqrt(res.siteArea) * p.U * 0.9)), ux = Math.sin(a), uy = -Math.cos(a); const x0 = sx - ux * Lr / 2, y0 = sy - uy * Lr / 2, x1 = sx + ux * Lr / 2, y1 = sy + uy * Lr / 2; o += ``; o += ``; o += tx(x1 + ux * 2.5, y1 + uy * 2.5 + 1, `${fall.toFixed(0)}%`, { size: 2.8, bold: true, anchor: 'middle', halo: C.halo, fill: C.ink }); } for (const [E, N, z, isC] of res.spots) { if (isC) continue; const x = p.X(E), y = p.Y(N); o += `` + tx(x + 1.2, y - 0.8, `+${z.toFixed(1)}`, { size: 2.2, halo: C.halo, fill: C.ink }); } return { svg: o, rasters: [tp], legend: [{ k: 'ramp', cs: [0, 0.33, 0.67, 1].map((t) => rgbHex(topoCol(t))), ticks: [`+${tp.lo.toFixed(0)}`, `+${tp.hi.toFixed(0)} mPD`] }, { k: 'line', c: C.contour, w: 0.5, t: T([`contour ${res.interval} m`, `等高線 ${res.interval} 米`]) }], take: T([(res.zmax - res.zmin < 0.05 ? `Ground +${res.zmin.toFixed(1)} mPD. ` : `Ground +${res.zmin.toFixed(1)} to +${res.zmax.toFixed(1)} mPD. `) + (fall < 1 ? 'The site is practically level.' : `The site falls about ${fall.toFixed(0)}% (1 in ${Math.round(100 / fall)}) to the ${compass(res.fallDir)}.`), (res.zmax - res.zmin < 0.05 ? `地面 +${res.zmin.toFixed(1)} mPD。` : `地面 +${res.zmin.toFixed(1)} 至 +${res.zmax.toFixed(1)} mPD。`) + (fall < 1 ? '地盤大致平坦。' : `地盤向${compass(res.fallDir)}傾斜約 ${fall.toFixed(0)}%(1 比 ${Math.round(100 / fall)})。`)]), }; }; D.sun = (res, p) => { let o = `` + roadsSVG(res, p); for (const s of res.sun) { // each hour's shadow; where they overlap the ground stays in shade longer const sub = []; for (const sh of s.paths) { const Rg = sh.ring, n = Rg.length, rings = [Rg.map(([E, N]) => [p.X(E + sh.vb[0]), p.Y(N + sh.vb[1])]), Rg.map(([E, N]) => [p.X(E + sh.vt[0]), p.Y(N + sh.vt[1])])]; for (let i = 0; i < n; i++) { const a = Rg[i], b = Rg[(i + 1) % n]; rings.push([[p.X(a[0] + sh.vb[0]), p.Y(a[1] + sh.vb[1])], [p.X(b[0] + sh.vb[0]), p.Y(b[1] + sh.vb[1])], [p.X(b[0] + sh.vt[0]), p.Y(b[1] + sh.vt[1])], [p.X(a[0] + sh.vt[0]), p.Y(a[1] + sh.vt[1])]]); } for (const rg of rings) if (Math.abs(sArea(rg)) > 0.004) sub.push({ pts: rg }); } o += ``; } o += ``; o += siteSVG(res, p, { fill: 0.12 }); // sun path over the site: polar, horizon circle, 21 Dec bold, 21 Jun dashed const cx = p.X(res.siteC[0]), cy = p.Y(res.siteC[1]), Rr = 35, ac = TH.sun.c; const pr = (alt, az) => { const r = (Rr * (90 - alt)) / 90, a = (az * Math.PI) / 180; return [cx + r * Math.sin(a), cy - r * Math.cos(a)]; }; o += ``; o += ``; const path = (m, d) => { const q = []; for (let h = 5; h <= 19.5; h += 0.1) { const s = sunPos(res.lat, res.lon, h, m, d); if (s.alt > 0) q.push(pr(s.alt, s.az)); } return 'M' + q.map(([x, y]) => `${f2(x)} ${f2(y)}`).join('L'); }; o += ``; o += ``; for (const s of res.sun) { const [x, y] = pr(s.alt, s.az); o += ``; o += `` + tx(x, y + 0.9, String(s.hr).padStart(2, '0'), { size: 2.3, bold: true, fill: C.onAccent, anchor: 'middle' }); } const [jx, jy] = pr(sunPos(res.lat, res.lon, 12, 6, 21).alt, sunPos(res.lat, res.lon, 12, 6, 21).az); o += tx(jx + 2, jy + 4.6, T(['21 Jun', '6月21日']), { size: 2.2, fill: C.sunText, halo: C.halo }); const [dx_, dy_] = pr(sunPos(res.lat, res.lon, 13.2, 12, 21).alt, sunPos(res.lat, res.lon, 13.2, 12, 21).az); o += tx(dx_ + 3.2, dy_ + 4, T(['21 Dec', '12月21日']), { size: 2.2, bold: true, fill: C.sunText, halo: C.halo }); const pc = res.sun.map((s) => s.pct.toFixed(0)), hill = res.sun.filter((s) => s.terrPct >= 10).map((s) => s.hr); const so = Math.min(0.9, C.shadowOp * 2.5); return { svg: o, legend: [{ k: 'box', c: C.shadow, op: C.shadowOp, bg: C.sunBg, t: T(['shadow 09, 12, 15 h', '陰影 9、12、15 時']) }, { k: 'box', c: C.shadow, op: so, bg: C.sunBg, t: T(['in shade longer', '陰影時間較長']) }, { k: 'line', c: ac, w: 1, t: T(['sun path', '太陽軌跡']) }], take: T([`21 Dec: ${pc[0]}% of the site in shade at 9 am, ${pc[1]}% at noon, ${pc[2]}% at 3 pm.` + (hill.length ? ` Hill shadow too at ${hill.map((h) => (h > 12 ? h - 12 + ' pm' : h === 12 ? 'noon' : h + ' am')).join(', ')}.` : ''), `冬至(12 月 21 日):地盤在上午 9 時有 ${pc[0]}% 在陰影中,正午 ${pc[1]}%,下午 3 時 ${pc[2]}%。` + (hill.length ? `${hill.map((h) => h + ' 時').join('、')}亦受山坡遮擋。` : '')]), }; }; D.wind = (res, p) => { const w = res.extra && res.extra.wind; let o = baseSVG(res, p, { ground: C.windBg, bld: C.hatch ? bldFill() : C.windBld }); o += siteSVG(res, p, { fill: 0.12 }); const DIR_EN = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']; const DIR_ZH = ['北', '北北東', '東北', '東北東', '東', '東南東', '東南', '南南東', '南', '南南西', '西南', '西南西', '西', '西北西', '西北', '北北西']; if (!w || w.error) { o += noteBox(T(['No PlanD wind data', '未能載入規劃署風資料']), T(['for this location', '此位置']), 48.5); return { svg: o, legend: [], take: T(['Wind data did not load for this site.', '未能載入此地盤的風資料。']) }; } const cx = p.X(res.siteC[0]), cy = p.Y(res.siteC[1]), r0 = 3, Rm = 38, ac = TH.wind.c; const mx = Math.max(...w.annual, ...w.summer), sc = (v) => r0 + (Rm - r0) * Math.sqrt(v / mx); // area-true petals const petal = (i, v, half = 9.5) => { const a0 = ((i * 22.5 - half) * Math.PI) / 180, a1 = ((i * 22.5 + half) * Math.PI) / 180, r = sc(v), q = []; for (let k = 0; k <= 6; k++) { const a = a0 + ((a1 - a0) * k) / 6; q.push([cx + r * Math.sin(a), cy - r * Math.cos(a)]); } const b0 = [cx + r0 * Math.sin(a1), cy - r0 * Math.cos(a1)], b1 = [cx + r0 * Math.sin(a0), cy - r0 * Math.cos(a0)]; return `M${f2(b1[0])} ${f2(b1[1])}L` + q.map(([x, y]) => `${f2(x)} ${f2(y)}`).join('L') + `L${f2(b0[0])} ${f2(b0[1])}Z`; }; for (const pc of [0.1, 0.2, 0.3]) if (pc <= mx * 1.05) { const r = sc(pc); o += `` + tx(cx + 0.8, cy - r - 0.4, `${pc * 100}%`, { size: 1.9, fill: C.windText, halo: C.halo }); } o += ``; o += ``; o += siteSVG(res, p, { fill: 0, w: 0.7, dash: true }); for (const [i, s] of [[0, 'N'], [4, 'E'], [8, 'S'], [12, 'W']]) { const a = (i * 22.5 * Math.PI) / 180, r = Rm + 3.5; o += tx(cx + r * Math.sin(a), cy - r * Math.cos(a) + 1, isZh() ? DIR_ZH[i] : s, { size: 2.5, bold: true, anchor: 'middle', fill: C.windText, halo: C.halo }); } const ia = w.annual.indexOf(Math.max(...w.annual)), is = w.summer.indexOf(Math.max(...w.summer)), D_ = isZh() ? DIR_ZH : DIR_EN; return { svg: o, legend: [{ k: 'box', c: ac, op: C.petalOp, t: T(['annual', '全年']) }, { k: 'dash', c: C.windSummer, t: T(['summer (Jun-Aug)', '夏季(6 至 8 月)']) }, { k: 'text', t: T([`PlanD model, ${w.level} m level`, `規劃署模擬,${w.level} 米高度`]) }], take: T([`At the model's 200 m level the wind comes most often from the ${D_[ia]} (${(w.annual[ia] * 100).toFixed(0)}% of the year); in summer from the ${D_[is]}. Street-level wind differs.`, `在模擬的 200 米高度,風最常來自${D_[ia]}(全年 ${(w.annual[ia] * 100).toFixed(0)}%),夏季則來自${D_[is]}。街道層面的風會有不同。`]), }; }; // clip a segment to a box (Liang-Barsky); returns the clipped length in metres function clipLen(ax, ay, bx, by, x0, y0, x1, y1) { let t0 = 0, t1 = 1; const dx = bx - ax, dy = by - ay; for (const [pp, q] of [[-dx, ax - x0], [dx, x1 - ax], [-dy, ay - y0], [dy, y1 - ay]]) { if (pp === 0) { if (q < 0) return 0; continue; } const r = q / pp; if (pp < 0) { if (r > t1) return 0; if (r > t0) t0 = r; } else { if (r < t0) return 0; if (r < t1) t1 = r; } } return t1 > t0 ? (t1 - t0) * Math.hypot(dx, dy) : 0; } // distance from a point to the site boundary (0 inside the site) function siteDist(res, E, N) { if (L.inPoly(E, N, res.R)) return 0; let d = Infinity; const R = res.R; for (let i = 0; i < R.length; i++) { const a = R[i], b = R[(i + 1) % R.length]; d = Math.min(d, L.segDist(E, N, a[0], a[1], b[0], b[1])); } return d; } D.acc = (res, p) => { const x = res.extra || {}, ac = TH.acc.c, dk = C.accDark, f = res.f; let o = ``; o += ``; o += roadsSVG(res, p, { color: (c) => C.accRoads[c] || C.accRoads.other, minW: 0.6 }); // pedestrian network (LandsD 3D Pedestrian Network); covered share by length, clipped to the frame let lenCov = 0, lenAll = 0; const gaps = []; if (!x.ped || x.ped.error) gaps.push(['walkways', '行人路']); if (!x.bus || x.bus.error) gaps.push(['bus stops', '巴士站']); if (!x.mtr || x.mtr.error) gaps.push(['MTR', '港鐵']); const sets = { path: [], indoor: [], link: [], vert: [], cross: [] }; if (x.ped && !x.ped.error) { for (const l of x.ped) { let len = 0; for (let i = 0; i < l.pts.length - 1; i++) len += clipLen(l.pts[i][0], l.pts[i][1], l.pts[i + 1][0], l.pts[i + 1][1], f.E0, f.N0, f.E1, f.N1); lenAll += len; if (l.cov) lenCov += len; const d = lineD(l.pts, p); if (l.k === 'cross') sets.cross.push(d); else if (l.indoor) sets.indoor.push(d); else (sets[l.k] || sets.path).push(d); } o += ``; o += ``; o += ``; o += ``; o += ``; } o += siteSVG(res, p, { fill: 0.14 }); // markers first (drawn last, on top); their boxes are kept so the road names keep clear of them let mk = ''; const avoid = []; // [x0, y0, x1, y1] in map units const [sx, sy] = res.siteC; let nBus = 0, busDrawn = 0, mtrDrawn = 0, mtrArrow = 0, lrDrawn = 0; if (x.bus && !x.bus.error) for (const [E, N] of x.bus) { if (siteDist(res, E, N) <= 200) nBus++; // from the site boundary, not the centre const X = p.X(E), Y = p.Y(N); if (!inMap(X, Y, 1.5)) continue; busDrawn++; mk += ``; } // MTR exits (OpenStreetMap); the nearest one gets an arrow from the frame edge when it is outside let mtrTxt = null; if (x.mtr && !x.mtr.error && x.mtr.exits.length) { for (const e of x.mtr.exits) { const X = p.X(e.E), Y = p.Y(e.N); if (!inMap(X, Y, 1.8)) continue; mtrDrawn++; mk += `` + tx(X, Y + 0.85, 'M', { size: 2.3, bold: true, fill: C.onAccent, anchor: 'middle' }); avoid.push([X - 1.6, Y - 1.6, X + 1.6 + (e.ref ? 0.6 + tw(e.ref, 2, true) : 0), Y + 1.6]); if (e.ref) mk += tx(X + 2.2, Y + 0.8, e.ref, { size: 2, bold: true, fill: dk, halo: C.halo }); } // an exit with no station name: the name is dropped, never replaced by the bare word MTR / 港鐵 const n = x.mtr.exits[0], st = n.station && (n.station.en || n.station.zh) ? T([n.station.en || n.station.zh, n.station.zh || n.station.en]) : ''; const X = p.X(n.E), Y = p.Y(n.N); if (!inMap(X, Y, 2)) { const br = Math.atan2(n.E - sx, n.N - sy), ux = Math.sin(br), uy = -Math.cos(br), cx = p.X(sx), cy = p.Y(sy); // in a round frame the arrow stops at the circle; in a square one at the frame edge const t = SHAPE === 'circle' ? Math.max(5, 44 - Math.hypot(cx - 50, cy - 50)) : Math.min(ux > 0 ? (95 - cx) / ux : ux < 0 ? (5 - cx) / ux : Infinity, uy > 0 ? (95 - cy) / uy : uy < 0 ? (5 - cy) / uy : Infinity); const ex = cx + ux * t, ey = cy + uy * t, bx = ex - ux * 9, by = ey - uy * 9; mk += ``; const lab = `${[st, n.ref].filter(Boolean).join(' ') || T(['MTR exit', '港鐵出口'])} · ${Math.round(n.d / 10) * 10} ${T(['m', '米'])}`, wd = tw(lab, 2.2, true); const lx = Math.min(97 - wd, Math.max(3, bx - wd / 2)), ly = Math.min(88, Math.max(9, by + (uy > 0 ? -2.2 : 3.6))); mk += `` + tx(lx, ly, lab, { size: 2.2, bold: true, fill: dk }); avoid.push([lx - 0.8, ly - 2.4, lx + wd + 0.8, ly + 1]); mtrArrow++; // QA r2: an arrow, not the M symbol } const sEn = [n.station && (n.station.en || n.station.zh), n.ref].filter(Boolean).join(' '), sZh = [n.station && (n.station.zh || n.station.en), n.ref].filter(Boolean).join(' '); mtrTxt = [`nearest MTR exit ${Math.round(n.d / 10) * 10} m (${sEn ? sEn + ', ' : ''}straight line)`, `最近港鐵出口 ${Math.round(n.d / 10) * 10} 米(${sZh ? sZh + ',' : ''}直線距離)`]; } else if (x.mtr && !x.mtr.error) mtrTxt = ['no MTR exit within 2 km', '2 公里內沒有港鐵出口']; // Light Rail stops (OpenStreetMap): a ring with LR; named when it is within 1 km let lrTxt = null; if (x.mtr && !x.mtr.error && x.mtr.lr && x.mtr.lr.length) { for (const q of x.mtr.lr) { const X = p.X(q.E), Y = p.Y(q.N); if (!inMap(X, Y, 2)) continue; lrDrawn++; mk += `` + tx(X, Y + 0.65, 'LR', { size: 1.6, bold: true, fill: dk, anchor: 'middle' }); avoid.push([X - 1.9, Y - 1.9, X + 1.9, Y + 1.9]); } const q = x.mtr.lr[0]; if (q.d <= 1000) lrTxt = [`nearest Light Rail stop ${Math.round(q.d / 10) * 10} m (${q.en || q.zh})`, `最近輕鐵站 ${Math.round(q.d / 10) * 10} 米(${q.zh || q.en})`]; } // road names: one per main street, on its best in-frame segment that is long enough and clear of exit labels and other names const hitsBox = (l, wd) => { const a = (l.ang * Math.PI) / 180, ux = Math.cos(a), uy = Math.sin(a), vx = -uy, vy = ux; for (let s = -wd / 2; s <= wd / 2 + 1e-6; s += 0.5) for (const v of [-1.2, 0, 1.2]) { const px_ = l.mx + ux * s + vx * v, py_ = l.my + uy * s + vy * v; for (const [x0, y0, x1, y1] of avoid) if (px_ >= x0 - 0.4 && px_ <= x1 + 0.4 && py_ >= y0 - 0.4 && py_ <= y1 + 0.4) return true; } return false; }; const cands = new Map(); for (const r of res.roadRuns) { if (!['Highway', 'Main Road', 'Secondary Road'].includes(r.cls)) continue; const name = nm(r.en, r.tc); if (!name) continue; for (let i = 0; i < r.pts.length - 1; i++) { const x1 = p.X(r.pts[i][0]), y1 = p.Y(r.pts[i][1]), x2 = p.X(r.pts[i + 1][0]), y2 = p.Y(r.pts[i + 1][1]), len = Math.hypot(x2 - x1, y2 - y1), mx = (x1 + x2) / 2, my = (y1 + y2) / 2; if (mx < 10 || mx > 90 || my < 14 || my > 86 || !inMap(mx, my, 10)) continue; let ang = (Math.atan2(y2 - y1, x2 - x1) * 180) / Math.PI; if (ang > 90) ang -= 180; if (ang < -90) ang += 180; if (!cands.has(name)) cands.set(name, []); cands.get(name).push({ name, len, mx, my, ang, sc: len / ROAD[r.cls].rank }); } } const roads = [...cands.values()].map((cs) => cs.sort((a, b) => b.sc - a.sc)).sort((a, b) => b[0].sc - a[0].sc).slice(0, 5); let names = '', nNames = 0, nSkipped = 0; for (const cs of roads) { const wd = tw(cs[0].name, 2.2); const l = cs.find((c) => wd + 2 <= c.len && !hitsBox(c, wd)); if (!l) { if (cs.some((c) => wd + 2 <= c.len)) nSkipped++; continue; } names += tx(l.mx, l.my + 0.75, l.name, { size: 2.2, fill: C.ink2, anchor: 'middle', halo: C.halo, rot: l.ang, role: 'road' }); nNames++; // the placed name becomes an obstacle for the next names const a = (l.ang * Math.PI) / 180, hx = (Math.abs(Math.cos(a)) * wd) / 2 + Math.abs(Math.sin(a)) * 1.2, hy = (Math.abs(Math.sin(a)) * wd) / 2 + Math.abs(Math.cos(a)) * 1.2; avoid.push([l.mx - hx, l.my - hy, l.mx + hx, l.my + hy]); } o += `${names}` + mk; if (gaps.length) o += noteBox(T([`No ${gaps.map((g) => g[0]).join(', ')} data`, `未能載入${gaps.map((g) => g[1]).join('、')}資料`]), T(['the server did not answer', '伺服器沒有回應'])); // legend: one entry per kind actually drawn, in the colour and line it is drawn with const rc = C.accRoads['Main Road'], lg = [{ k: 'line', c: lum(rc) > 0.9 && !C.dark ? C.roadEdge : rc, w: 1.6, t: T(['roads', '道路']) }]; if (sets.path.length) lg.push({ k: 'line', c: ac, w: 0.5, t: T(['footpaths', '行人路']) }); if (sets.indoor.length) lg.push({ k: 'line', c: ac, w: 0.4, da: '0.7 0.6', op: 0.6, t: T(['indoor walkways', '室內通道']) }); if (sets.cross.length) lg.push({ k: 'line', c: ac, w: 0.8, da: '0.3 0.3', cap: 'butt', t: T(['crossings', '過路處']) }); if (sets.link.length) lg.push({ k: 'line', c: ac, w: 0.9, t: T(['footbridges, subways', '行人天橋、行人隧道']) }); if (sets.vert.length) lg.push({ k: 'line', c: dk, w: 1.1, t: T(['lifts, escalators, stairs, ramps', '升降機、扶手電梯、樓梯、斜道']) }); if (busDrawn) lg.push({ k: 'bus', c: ac, t: T(['bus stop', '巴士站']) }); if (mtrDrawn) lg.push({ k: 'mtr', c: dk, t: T(['MTR exit', '港鐵出口']) }); if (mtrArrow) lg.push({ k: 'arrow', c: dk, t: T(['MTR exit beyond the frame', '範圍以外的港鐵出口']) }); if (lrDrawn) lg.push({ k: 'lr', c: dk, t: T(['Light Rail stop', '輕鐵站']) }); const bits = []; if (x.bus && !x.bus.error) bits.push(nBus ? [`${nBus} bus stop${nBus === 1 ? '' : 's'} within 200 m of the site`, `地盤 200 米內有 ${nBus} 個巴士站`] : ['no bus stop within 200 m of the site', '地盤 200 米內沒有巴士站']); if (mtrTxt) bits.push(mtrTxt); if (lrTxt) bits.push(lrTxt); if (!bits.length) bits.push(['transport data did not load', '未能載入交通資料']); if (lenAll > 0) { const pc = Math.round((100 * lenCov) / lenAll); bits.push([`${pc}% of the mapped walkway length in the frame is covered`, `範圍內已記錄行人通道長度有 ${pc}% 有上蓋`]); } return { svg: o, legend: lg, take: T([bits.map((b) => b[0]).join('; ').replace(/^./, (c) => c.toUpperCase()) + '.', bits.map((b) => b[1]).join(';') + '。']) }; }; D.noise = (res, p, B) => { let o = ``; const busy = res.roadRuns.filter((r) => r.cls === 'Highway' || r.cls === 'Main Road'); const [b100, b50, b25] = C.noiseBands, bands = [[100, b100], [50, b50], [25, b25]]; for (const [d, c] of bands) if (busy.length) o += ``; o += ``; o += roadsSVG(res, p, { color: C.noiseMinor, minW: 0.35, classes: ['Secondary Road', 'Restricted Road', 'Track'] }); o += `` + roadsSVG(res, p, { color: C.noiseMajor, minW: 0.7, scale: 0.5, classes: ['Highway', 'Main Road'] }) + ''; o += siteSVG(res, p, { fill: 0.1 }); const busyIn = busy.some((r) => r.pts.some(([E, N]) => { const X = p.X(E), Y = p.Y(N); return X > -20 && X < 120 && Y > -20 && Y < 120; })); if (res.roadErr) o += noteBox(T(['Road data did not load', '未能載入道路資料']), ''); else if (!busyIn) o += noteBox(T(['No highway or main road', '沒有快速公路或主要道路']), T(['in or near this frame', '此範圍內及附近'])); const b = B.busy, nmr = b ? nm(b.r.en, b.r.tc) || T(['an unnamed road', '一條未命名道路']) : ''; return { svg: o, legend: [{ k: 'box', c: b25, t: T(['under 25 m', '25 米以內']) }, { k: 'box', c: b50, t: T(['25 to 50 m', '25 至 50 米']) }, { k: 'box', c: b100, t: T(['50 to 100 m', '50 至 100 米']) }, { k: 'text', t: T(['from a highway or main road', '距快速公路或主要道路']) }], take: b && b.d <= 200 ? T([`Proxy, not a measurement: the nearest highway or main road, ${nmr}, is ${b.d < 1 ? 'on the site edge' : b.d.toFixed(0) + ' m from the site edge'}.`, `只屬推算,並非量度:最近的快速公路或主要道路為${nmr},${b.d < 1 ? '緊貼地盤' : '距地盤邊界 ' + b.d.toFixed(0) + ' 米'}。`]) : T([`Proxy, not a measurement: no highway or main road within 200 m of the site.`, `只屬推算,並非量度:地盤 200 米內沒有快速公路或主要道路。`]), }; }; const GREEN_N = { wood: ['woodland', '林地'], shrub: ['shrubland', '灌木'], grass: ['grassland', '草地'], urban: ['green urban area', '市區綠化地帶'], agri: ['farmland', '農地'] }; const G_ORDER = ['wood', 'shrub', 'urban', 'grass', 'agri']; D.green = (res, p, B) => { const x = res.extra || {}; let o = `` + roadsSVG(res, p, { color: C.greenRoad }); const seen = new Set(); if (!x.green || x.green.error) o += noteBox(T(['No habitat map data', '未能載入生境地圖資料']), T(['the AFCD server did not answer', '漁護署伺服器沒有回應'])); if (x.green && !x.green.error) { const by = new Map(); for (const g of x.green) { if (!GREEN_N[g.cls]) continue; if (!by.has(g.cls)) by.set(g.cls, []); by.get(g.cls).push({ pts: g.ring.map(([E, N]) => [p.X(E), p.Y(N)]) }); seen.add(g.cls); } for (const k of ['agri', 'grass', 'urban', 'shrub', 'wood']) if (by.has(k)) o += ``; } o += ``; o += siteSVG(res, p, { fill: 0.12 }); let parkTxt = null, parksDrawn = 0; if (x.parks && !x.parks.error) { const [sx, sy] = res.siteC; const ps = x.parks.map((q) => ({ ...q, d: Math.hypot(q.E - sx, q.N - sy) })).sort((a, b) => a.d - b.d); for (const q of ps) { const X = p.X(q.E), Y = p.Y(q.N); if (!inMap(X, Y, 2)) continue; const lab = T([q.en, q.zh]), lw = tw(lab, 2.1, true), right = X + 2 + lw < 97 && inMap(X + 2 + lw, Y, 1.5); parksDrawn++; o += ``; if (right || X - 2 - lw > 3 && inMap(X - 2 - lw, Y, 1.5)) o += tx(right ? X + 2 : X - 2, Y + 0.8, lab, { size: 2.1, fill: C.park, bold: true, halo: C.halo, anchor: right ? 'start' : 'end' }); } if (ps[0] && ps[0].d <= 1000) parkTxt = [`${ps[0].en} is ${Math.round(ps[0].d / 10) * 10} m away`, `${ps[0].zh}相距 ${Math.round(ps[0].d / 10) * 10} 米`]; } const lg = [...seen].sort((a, b) => G_ORDER.indexOf(a) - G_ORDER.indexOf(b)).map((k) => ({ k: 'box', c: C.greenCols[k], t: T(GREEN_N[k]) })); if (parksDrawn) lg.push({ k: 'dot', c: C.park, t: T(['LCSD park', '康文署公園']) }); const g = B.green, main = B.greenMain && GREEN_N[B.greenMain] ? T(GREEN_N[B.greenMain]) : ''; const take = g == null ? T(['Green data did not load.', '未能載入綠化資料。']) : T([`Mapped green covers ${g.toFixed(0)}% of the ground within ${B.radius} m${g >= 1 && main ? `, mostly ${main}` : ''}.` + (parkTxt ? ` ${parkTxt[0]}.` : ''), `地盤 ${B.radius} 米範圍內,已記錄的綠化佔地面 ${g.toFixed(0)}%${g >= 1 && main ? `,主要為${main}` : ''}。` + (parkTxt ? `${parkTxt[1]}。` : '')]); return { svg: o, legend: lg, take }; }; D.view = (res, p) => { const v = res.views, ac = TH.view.c; let o = baseSVG(res, p, { ground: C.viewBg, bld: C.hatch ? bldFill() : C.viewBld }); const cx = p.X(v.x0), cy = p.Y(v.y0); const poly = (iso) => 'M' + Array.from(iso.d, (d, i) => { const a = (i * 2 * Math.PI) / iso.d.length, r = Math.min(d, p.F) * p.U; return `${f2(cx + r * Math.sin(a))} ${f2(cy - r * Math.cos(a))}`; }).join('L') + 'Z'; o += ``; o += ``; o += siteSVG(res, p, { fill: 0, w: 0.7, dash: true }); for (const s of v.open.slice(0, 3)) { // open sectors from 30 m up: arrows out to the frame const a = (s.mid * Math.PI) / 180, ux = Math.sin(a), uy = -Math.cos(a); const t = SHAPE === 'circle' ? Math.max(6, 43 - Math.hypot(cx - 50, cy - 50)) : Math.min(ux > 0 ? (93 - cx) / ux : ux < 0 ? (7 - cx) / ux : Infinity, uy > 0 ? (90 - cy) / uy : uy < 0 ? (10 - cy) / uy : Infinity); const ex = cx + ux * t, ey = cy + uy * t, w2 = Math.min(s.w, 70) / 2, a0 = ((s.mid - w2) * Math.PI) / 180, a1 = ((s.mid + w2) * Math.PI) / 180, rr = t * 0.98; o += ``; o += ``; } o += ``; const dirs = v.open.slice(0, 3).map((s) => compass(s.mid)); const lg = [{ k: 'box', c: ac, op: 0.4, t: T(['seen from street level', '街道層面可見']) }, { k: 'box', c: ac, op: 0.13, t: T(['seen from 30 m up', '離地 30 米可見']) }]; if (v.open.length) lg.push({ k: 'arrow', c: ac, t: T([`clear beyond ${v.openD} m`, `${v.openD} 米外仍開揚`]) }); return { svg: o, legend: lg, take: T([`From the street the view typically reaches ${v.street.med.toFixed(0)} m (median; sky view factor ${v.street.svf.toFixed(2)}). ` + (dirs.length ? `From 30 m up it opens to the ${[...new Set(dirs)].join(', ')}.` : 'Even 30 m up it stays enclosed.'), `在街道層面,一般可見 ${v.street.med.toFixed(0)} 米(中位數;天空可視因子 ${v.street.svf.toFixed(2)})。` + (dirs.length ? `離地 30 米向${[...new Set(dirs)].join('、')}開揚。` : '離地 30 米仍然封閉。')]), }; }; // a diagram that could not be drawn: the plain base map with a note that says why const hasCJK = (s) => /[㐀-鿿]/.test(String(s)); function unavailable(res, p, why) { let reason = ''; if (Array.isArray(why)) reason = T(why); else if (why && (!isZh() || hasCJK(why))) reason = String(why); else reason = T(['the analysis did not run', '分析未能執行']); if (reason.length > 60) reason = reason.slice(0, 57).trimEnd() + '...'; const o = baseSVG(res, p, { ground: C.ground }) + siteSVG(res, p, { fill: 0.12 }) + noteBox(T(['Not available for this site', '此地盤未能提供']), reason, 48.5); return { svg: o, legend: [], take: T(['Not available for this site', '此地盤未能提供此分析']) + (reason ? T([`: ${reason}.`, `:${reason}。`]) : T(['.', '。'])) }; } // one diagram for the current preset, whatever drew it function drawKey(res, key) { const B = prepare(res), p = B.p; let d; if (D[key]) d = D[key](res, p, B); else { const r = res[key], g = DG3[key]; if (!g || typeof g.draw !== 'function') d = unavailable(res, p, ['the analysis is not loaded', '分析尚未載入']); else if (!r) d = unavailable(res, p, ['no result for this site', '此地盤沒有結果']); else if (r.error) d = unavailable(res, p, r.error); else { try { d = g.draw(res, p, B, kit()); } catch (e) { console.warn('diagram ' + key, e); d = null; } if (!d || typeof d.svg !== 'string') d = unavailable(res, p, ['the drawing failed', '繪圖失敗']); } } return { svg: d.svg, legend: d.legend || [], take: d.take || '', rasters: (d.rasters || []).filter((r) => r && r.canvas), ownScale: !!d.ownScale || key === 'walk' }; } // the map of one diagram (0..100 user units): rasters (screen only), drawing, round clip, ring, north and scale function mapBody(res, d, { forExport = false, north = true } = {}) { const p = prepare(res).p, round = SHAPE === 'circle'; const imgs = forExport ? '' : d.rasters.map((r) => ``).join(''); let o; if (round) { const notes = []; const body = d.svg.replace(/[\s\S]*?<\/g>/g, (m) => { notes.push(m); return ''; }); o = `${imgs}${body}${notes.join('')}` + ringSVG(); } else o = imgs + d.svg; if (north) o += northScale(res, p, { scale: !d.ownScale }); return o; } // the round frame: a fine ring with ticks every 30 degrees, north tick heavier function ringSVG() { let o = ``; for (let a = 0; a < 360; a += 30) { const r0 = a === 0 ? 46.6 : 48.2, t = (a * Math.PI) / 180, s = Math.sin(t), c = -Math.cos(t); o += ``; } return o; } // ---------- tile = map + caption ---------- function legendSVG(items, x0, y0, width, sz = 2.05) { let o = '', x = x0, y = y0, rows = 1, rampRow = false; for (const it of items) { const lab = it.t || '', lw = tw(lab, sz); let sw = 4.2; if (it.k === 'ramp') sw = 22; if (x + sw + lw + 1.2 > x0 + width && x > x0) { x = x0; y += rampRow ? 5.2 : 3.7; rows++; rampRow = false; } if (it.bg) o += ``; if (it.k === 'box') o += ``; else if (it.k === 'ring') o += ``; else if (it.k === 'line') { const hw = it.cap === 'butt' ? 0 : Math.min(1, (it.w || 0.5) / 2); o += ``; } else if (it.k === 'dash') o += ``; else if (it.k === 'dot') o += ``; else if (it.k === 'bus') o += ``; else if (it.k === 'mtr') o += `` + tx(x + 1.4, y - 0.15, 'M', { size: 1.9, bold: true, fill: C.onAccent, anchor: 'middle' }); else if (it.k === 'lr') o += `` + tx(x + 1.4, y - 0.35, 'LR', { size: 1.1, bold: true, fill: it.c, anchor: 'middle' }); else if (it.k === 'arrow') o += ``; else if (it.k === 'text') sw = 0; if (it.k === 'ramp') { const cs = it.cs || [], n = Math.max(1, cs.length), seg = 22 / n, ticks = it.ticks || []; cs.forEach((c, i) => { o += ``; }); if (ticks.length === 2) { o += tx(x, y + 1.6, ticks[0], { size: 1.8, fill: C.muted }) + tx(x + 22, y + 1.6, ticks[1], { size: 1.8, fill: C.muted, anchor: 'end' }); } else ticks.forEach((t, i) => { o += tx(x + i * seg, y + 1.6, t, { size: 1.8, fill: C.muted, anchor: i ? 'middle' : 'start' }); }); if (lab) o += tx(x + 23.2, y - 0.3, lab, { size: sz, fill: C.ink2 }); x += 24.4 + (lab ? lw : 0) + 2.4; if (ticks.length) rampRow = true; continue; } o += tx(x + sw, y, lab, { size: sz, fill: it.k === 'text' ? C.muted : C.ink2 }); x += sw + lw + 2.6; } return { o, h: items.length ? y - y0 + (rampRow ? 2.2 : 0.6) : 0 }; } // caption under a map: number + title, the take (as many lines as fit), the legend function captionSVG(d, key, idx, width, maxH) { const th = TH[key], numCol = C.num || (th.c === C.ink ? C.site : th.c), ty = 4.6; let o = tx(0, ty, String(idx + 1).padStart(2, '0'), { size: 3.4, bold: true, fill: numCol }); o += tx(6.2, ty, T([th.en, th.zh]), { size: 3.4, bold: true, fill: C.ink, role: 'title' }); const lg = legendSVG(d.legend, 0, 0, width), lines = wrap(d.take, 2.3, width), LH = 3.0, t0 = ty + 4.4; let n = lines.length; const fits = (k) => t0 + (k - 1) * LH + (lg.h || d.legend.length ? 4.5 + lg.h : 0) <= maxH; while (n > 1 && !fits(n)) n--; for (let i = 0; i < n; i++) { let ln = lines[i]; if (i === n - 1 && n < lines.length) { while (ln.length > 3 && tw(ln + '...', 2.3) > width) ln = ln.slice(0, -1); ln = ln.trimEnd() + '...'; } o += tx(0, t0 + i * LH, ln, { size: 2.3, fill: C.ink2, role: 'take' }); } if (d.legend.length) o += `${lg.o}`; return o; } // a tile on the board: map square (MW) and caption; returns rasters for the exports function tileSVG(res, key, idx, { forExport = false } = {}) { const d = drawKey(res, key); let o = `${mapBody(res, d, { forExport })}`; if (SHAPE !== 'circle') o += ``; o += `${captionSVG(d, key, idx, MW, TH_CAP - 0.6)}`; return { svg: o, take: d.take, rasters: d.rasters }; } // ---------- the board ---------- function locator(res, x, y, w, h) { const idx = L.dtmTiles && L.dtmTiles(); if (!idx) return ''; let e0 = Infinity, e1 = -Infinity, n0 = Infinity, n1 = -Infinity; const ts = []; for (const k of idx) { const [e, n] = k.split('_').map(Number); ts.push([e, n]); e0 = Math.min(e0, e); e1 = Math.max(e1, e); n0 = Math.min(n0, n); n1 = Math.max(n1, n); } if (!ts.length) return ''; const s = Math.min(w / (e1 - e0 + 1), h / (n1 - n0 + 1)), ox = x + (w - (e1 - e0 + 1) * s) / 2, oy = y + (h - (n1 - n0 + 1) * s) / 2; let d = ''; for (const [e, n] of ts) d += `M${f2(ox + (e - e0) * s)} ${f2(oy + (n1 - n) * s)}h${f2(s * 0.86)}v${f2(s * 0.86)}h${f2(-s * 0.86)}Z`; const sx = ox + (res.siteC[0] / 1000 - e0) * s, sy = oy + (n1 + 1 - res.siteC[1] / 1000) * s; return ``; } const okR = (r) => r && !r.error; const NONE = () => T(['none', '沒有']); // title band (y 10 to 45): eyebrow, name, address, coordinates; key facts; locator function titleBand(res, { name = '', address = null, drawn = '' } = {}, eyebrow) { const B = prepare(res), o = []; o.push(tx(M, 15, eyebrow, { size: 2.3, bold: true, fill: C.eyebrow, ls: 0.55 })); const title = name || T(['Site analysis', '地盤分析']); let ty = 26.2; for (const ln of wrap(title, 10.5, 172, true).slice(0, 1)) { o.push(tx(M - 0.5, ty, ln, { size: 10.5, bold: true, fill: C.ink, ls: -0.12 })); ty += 6.6; } if (address) { o.push(tx(M, ty, wrap(T([address.en || address.name || '', address.zh || address.nameZh || '']), 3, 172)[0] || '', { size: 3, fill: C.ink2 })); ty += 4.6; } o.push(tx(M, ty, `HK1980 E ${res.siteC[0].toFixed(0)} N ${res.siteC[1].toFixed(0)} ${res.lat.toFixed(5)} N ${res.lon.toFixed(5)} E ${T(['site', '地盤'])} ${fmtArea(res.siteArea)} ${T(['drawn', '繪製'])} ${drawn}`, { size: 2.1, fill: C.muted, ls: 0.1 })); // facts const x = res.extra || {}, mtr = x.mtr && !x.mtr.error && x.mtr.exits[0], tn0 = offTall(res)[0]; const lr0 = x.mtr && !x.mtr.error && x.mtr.lr && x.mtr.lr[0], useLr = lr0 && lr0.d <= 1000 && (!mtr || lr0.d < mtr.d); const facts = [ [T(['GROUND', '地面']), `+${res.zs.toFixed(0)}`, 'mPD', T([res.grad * 100 >= 1 ? `falls ${(res.grad * 100).toFixed(0)}% ${compass(res.fallDir)}` : 'level', res.grad * 100 >= 1 ? `向${compass(res.fallDir)}傾斜 ${(res.grad * 100).toFixed(0)}%` : '平坦'])], [T(['TALLEST NEARBY', '附近最高']), tn0 ? tn0.top.toFixed(0) : NONE(), tn0 ? 'mPD' : '', tn0 ? (tn0.d < 1 ? T(['on the site edge', '緊貼地盤']) : T([`${tn0.d.toFixed(0)} m ${compass(tn0.br)}`, `${compass(tn0.br)}面 ${tn0.d.toFixed(0)} 米`])) : T(['no building off the site', '地盤以外沒有建築物'])], [T(['NOON SHADE 21 DEC', '冬至正午陰影']), res.sun[1].pct.toFixed(0), '%', T(['of the site', '地盤面積'])], ]; const sh = res.sunh; if (okR(sh) && sh.site && sh.dates) { const id = sh.show || 'mar', dd = sh.dates.find((q) => q.id === id), s = sh.site[id]; if (dd && s && Number.isFinite(s.mean)) facts.push([T([`SUN HOURS ${dd.en}`.toUpperCase(), `${dd.zh}日照`]), s.mean.toFixed(1), T(['h', '小時']), T(['site average', '地盤平均'])]); } facts.push([T(['BUILT COVER', '建築覆蓋']), B.built.toFixed(0), '%', T([`within ${B.radius} m`, `${B.radius} 米內`])]); facts.push(useLr ? [T(['NEAREST LIGHT RAIL', '最近輕鐵站']), String(Math.round(lr0.d / 10) * 10), T(['m', '米']), T([lr0.en || lr0.zh, lr0.zh || lr0.en])] : [T(['NEAREST MTR EXIT', '最近港鐵出口']), mtr ? String(Math.round(mtr.d / 10) * 10) : NONE(), mtr ? T(['m', '米']) : '', mtr ? (mtr.station && (mtr.station.en || mtr.station.zh) ? T([mtr.station.en || mtr.station.zh, mtr.station.zh || mtr.station.en]) : T(['straight line', '直線距離'])) : T(['within 2 km', '2 公里內'])]); for (const f_ of facts) if (!f_[1] || /NaN|undefined|^-$/.test(String(f_[1]))) { f_[1] = NONE(); f_[2] = ''; } const fx0 = 190, fw = (364 - fx0) / facts.length; facts.forEach(([lab, val, unit, sub], i) => { const fx = fx0 + i * fw; o.push(``); o.push(tx(fx + 2.4, 15, wrap(lab, 1.75, fw - 4, true)[0] || '', { size: 1.75, bold: true, fill: C.muted, ls: 0.3 })); o.push(tx(fx + 2.2, 28, val, { size: 8.4, fill: C.ink, ls: -0.2 }) + (unit ? tx(fx + 3.2 + tw(val, 8.4) - 0.2 * val.length, 28, unit, { size: 2.6, fill: C.ink2 }) : '')); o.push(tx(fx + 2.4, 33.4, wrap(String(sub), 2.1, fw - 4)[0] || '', { size: 2.1, fill: C.ink2 })); }); o.push(`` + locator(res, 369.5, 12.5, BW - M - 371, 26.5)); o.push(``); return o; } function footer(o, fy) { o.push(``); let yy = fy; for (const ln of wrap(L.credits(), 1.9, 336)) { o.push(tx(M, yy, ln, { size: 1.9, fill: C.muted })); yy += 2.5; } o.push(tx(BW - M, fy, 'anzonwong.com/lab/hk-site-analysis', { size: 2.1, fill: C.muted, anchor: 'end' })); o.push(tx(BW - M, fy + 3.6, 'AW Design', { size: 2.7, bold: true, anchor: 'end', fill: C.ink, ls: 0.2 })); } // the key strip under the grid: how to read, notes, data by diagram function keyStrip(res, y0) { const p = prepare(res).p, o = []; o.push(``); const hy = y0 + 4, head = (x, s) => tx(x, hy, s, { size: 1.9, bold: true, fill: C.muted, ls: 0.4 }); // how to read o.push(head(M, T(['HOW TO READ', '閱讀說明']))); let y = hy + 4.4; const row = (sym, label) => { o.push(sym(M, y) + tx(M + 7, y, label, { size: 2.1, fill: C.ink2 })); y += 3.7; }; row((x, yy) => ``, T(['The site', '地盤'])); row((x, yy) => ``, T(['Existing buildings (LandsD)', '現有建築物(地政總署)'])); row((x, yy) => ``, T(['Roads (LandsD)', '道路(地政總署)'])); row((x, yy) => ``, T(['Grid north is up in every diagram', '所有圖均以方格北向上'])); // notes const nx = 78, nw = 166; o.push(head(nx, T(['NOTES', '註釋']))); const sh = res.sunh, wk = res.walk; const dd = okR(sh) && sh.dates ? sh.dates.find((q) => q.id === (sh.show || 'mar')) : null; const dEn = dd ? dd.en : '21 Mar', dZh = dd ? dd.zh : '3 月 21 日', spd = okR(wk) && wk.speed ? wk.speed : 80; const notes = T([ `Every diagram shows the same ${p.F} m by ${p.F} m frame round the site, except walking distance (08), which needs a wider one; scale bars are true at A3. ` + `Shadows are for 21 December, the lowest sun of the year. Sunlight hours count the hours of direct sun on open ground on ${dEn}, with buildings and terrain blocking the sun. ` + `Wind is Planning Department modelled data at the 200 m level, not at the street. Walking assumes ${spd} m a minute along mapped footpaths, with 5 and 10 minute bands. ` + `Noise is a distance proxy, not a measurement. Views and the sky view factor treat the site as cleared and ignore trees; a sky view factor of 1 is open sky, 0 is fully enclosed.`, `每幅圖均顯示地盤周邊相同的 ${p.F} 米乘 ${p.F} 米範圍(步行範圍圖需要較大範圍除外);比例尺於 A3 準確。` + `陰影以全年太陽最低的 12 月 21 日計算。日照時數為${dZh}空地上直接日照的小時數,已計建築物及地形遮擋。` + `風資料為規劃署在 200 米高度的模擬數據,並非街道層面。步行以每分鐘 ${spd} 米沿已記錄的行人路計算,顯示 5 及 10 分鐘範圍。` + `噪音只按距離推算,並非量度。景觀及天空可視因子假設地盤已清空,並不計樹木;天空可視因子 1 代表完全開揚,0 代表完全封閉。`]); y = hy + 4.2; for (const ln of wrap(notes, 1.95, nw)) { o.push(tx(nx, y, ln, { size: 1.95, fill: C.ink2 })); y += 2.6; } o.push(tx(nx, y + 0.3, T(['Hobby project, not official, for reference only. Not a substitute for a survey or professional advice.', '個人興趣項目,並非官方資料,只供參考,不能取代測量或專業意見。']), { size: 2, bold: true, fill: C.warn })); // data by diagram const dx = 252; o.push(head(dx, T(['DATA BY DIAGRAM', '各圖資料來源']))); const w = res.extra && res.extra.wind, net = okR(wk) && wk.net === 'road'; const src = [ ['01 02', T(['LandsD buildings, live', '地政總署建築物,即時'])], ['03', T(['LandsD 5 m terrain model', '地政總署 5 米地形模型'])], ['04 05', T(['NOAA sun equations, LandsD', 'NOAA 太陽方程式、地政總署'])], ['06', T([`PlanD site wind data${w && w.cell ? ', cell ' + w.cell : ''}`, `規劃署地盤總體風環境資料${w && w.cell ? ',網格 ' + w.cell : ''}`])], ['07', T(['LandsD paths, TD bus stops, OSM rail', '地政總署行人路、運輸署巴士站、OSM 鐵路'])], ['08', net ? T(['LandsD road centrelines, OSM rail', '地政總署道路中線、OSM 鐵路']) : T(['LandsD 3D pedestrian network, OSM rail', '地政總署三維行人道路網、OSM 鐵路'])], ['09', T(['LandsD road classes', '地政總署道路分類'])], ['10', T(['AFCD habitat map, LCSD parks', '漁護署生境地圖、康文署公園'])], ['11 12', T(['LandsD buildings and terrain', '地政總署建築物及地形'])], ]; const cw = (BW - M - dx) / 3; src.forEach(([n, t], i) => { const cx = dx + Math.floor(i / 3) * cw, cy = hy + 4.2 + (i % 3) * 3.4; o.push(tx(cx, cy, n, { size: 1.9, bold: true, fill: C.ink2 }) + tx(cx + 8, cy, wrap(t, 1.9, cw - 9)[0] || '', { size: 1.9, fill: C.ink2 })); }); return o; } function rootOpen(W, H, units, cls) { return `` + defsSVG(); } function buildBoard(res, opts = {}) { useTheme(opts); const forExport = !!opts.forExport, rasters = []; const o = [rootOpen(BW, BH, 'mm', 'hsa-board')]; if (!forExport) o.push(``); o.push(...titleBand(res, opts, T(['HK SITE ANALYSIS · DIAGRAM SERIES', '香港地盤分析 · 分析圖組']))); KEYS.forEach((k, i) => { const s = slot(i), t = tileSVG(res, k, i, { forExport }); o.push(`${t.svg}`); for (const r of t.rasters) rasters.push({ r, x: s.x, y: s.y, size: MW }); }); o.push(...keyStrip(res, STRIP_Y)); footer(o, 280.5); o.push(''); return { svg: o.join('\n'), rasters, round: SHAPE === 'circle' }; } function boardSVG(res, opts = {}) { return buildBoard(res, opts).svg; } // ---------- rasterise ---------- async function svgToImage(svg, w, h) { const s = svg.replace(/width="[\d.]+(mm|px)?" height="[\d.]+(mm|px)?"/, `width="${w}" height="${h}"`); const url = URL.createObjectURL(new Blob([s], { type: 'image/svg+xml;charset=utf-8' })); try { const img = new Image(); img.decoding = 'sync'; await new Promise((ok, bad) => { img.onload = ok; img.onerror = () => bad(new Error('board image')); img.src = url; }); return img; } finally { setTimeout(() => URL.revokeObjectURL(url), 1000); } } // paint raster layers of one map (map units) under the vector drawing; k = px per mm, (x, y, size) = the map square in mm function paintRasters(cx, list, k, round) { for (const { r, x, y, size } of list) { const mk = size / 100; cx.save(); cx.beginPath(); if (round) cx.arc((x + 50 * mk) * k, (y + 50 * mk) * k, 50 * mk * k, 0, 2 * Math.PI); else cx.rect(x * k, y * k, size * k, size * k); cx.clip(); cx.imageSmoothingEnabled = true; cx.drawImage(r.canvas, (x + r.x * mk) * k, (y + r.y * mk) * k, r.w * mk * k, r.h * mk * k); cx.restore(); } } async function boardCanvas(res, opts = {}, dpi = 200, scale = 1) { const W = Math.round((BW * scale / 25.4) * dpi), H = Math.round((BH * scale / 25.4) * dpi), k = W / BW; const b = buildBoard(res, { ...opts, forExport: true }); const cv = document.createElement('canvas'); cv.width = W; cv.height = H; const x = cv.getContext('2d'); x.fillStyle = C.paper; x.fillRect(0, 0, W, H); paintRasters(x, b.rasters, k, b.round); // rasters first, under the vector drawing x.drawImage(await svgToImage(b.svg, W, H), 0, 0, W, H); return cv; } // single diagram, 1080 x 1080: header, the map large, caption, credits const S1 = 1080, S_MAP = 640, S_X = (S1 - S_MAP) / 2, S_Y = 118, S_SC = 9; function singleSVG(res, key, opts = {}) { useTheme(opts); const forExport = !!opts.forExport, i = KEYS.indexOf(key), d = drawKey(res, key); let o = rootOpen(S1, S1, 'mm', 'hsa-single'); if (!forExport) o += ``; o += tx(S_X, 54, T(['HK SITE ANALYSIS', '香港地盤分析']) + ` · ${String(i + 1).padStart(2, '0')} / ${KEYS.length}`, { size: 17, bold: true, fill: C.eyebrow, ls: 3 }); o += tx(S_X - 2, 94, wrap(opts.name || T(['Site analysis', '地盤分析']), 32, S_MAP, true)[0] || '', { size: 32, bold: true, fill: C.ink, ls: -0.4 }); o += `${mapBody(res, d, { forExport })}`; if (SHAPE !== 'circle') o += ``; const capW = S_MAP / S_SC, capY = S_Y + S_MAP + 6; o += `${captionSVG(d, key, i, capW, (1018 - capY) / S_SC)}`; // credits + the full hobby disclaimer: 2 to 3 lines under the caption, type shrunk only as far as needed (never below 10 px) const cr = T(['Data: Lands Department, TD, AFCD, LCSD, PlanD (HKSAR Government), OpenStreetMap contributors. Hobby project, not official, for reference only. Not a substitute for a survey or professional advice.', '資料:地政總署、運輸署、漁農自然護理署、康文署、規劃署(香港特區政府)、OpenStreetMap 貢獻者。個人興趣項目,並非官方資料,只供參考,不能取代測量或專業意見。']); const crW = S_MAP - 130; let crS = 12, crL = wrap(cr, crS, crW); while (crL.length > 3 && crS > 10) { crS -= 0.5; crL = wrap(cr, crS, crW); } const crLH = crS * 1.3; let yy = 1066 - (crL.length - 1) * crLH; for (const ln of crL) { o += tx(S_X, yy, ln, { size: crS, fill: C.muted, role: 'credit' }); yy += crLH; } o += tx(S1 - S_X, S1 - 36, 'anzonwong.com', { size: 15, bold: true, anchor: 'end', fill: C.ink }); return { svg: o + '', tx0: S_X, ty0: S_Y, sc: S_MAP / MW, rasters: d.rasters, round: SHAPE === 'circle' }; } async function singleCanvas(res, key, opts = {}) { const s = singleSVG(res, key, { ...opts, forExport: true }); const cv = document.createElement('canvas'); cv.width = cv.height = S1; const x = cv.getContext('2d'); x.fillStyle = C.paper; x.fillRect(0, 0, S1, S1); paintRasters(x, s.rasters.map((r) => ({ r, x: S_X, y: S_Y, size: S_MAP })), 1, s.round); x.drawImage(await svgToImage(s.svg, S1, S1), 0, 0, S1, S1); return cv; } // the map of one diagram alone (no caption, north or scale), px x px; transparent outside a round frame async function plateCanvas(res, key, opts = {}, px = 1024) { useTheme(opts); const d = drawKey(res, key), round = SHAPE === 'circle'; const cv = document.createElement('canvas'); cv.width = cv.height = px; const x = cv.getContext('2d'); paintRasters(x, d.rasters.map((r) => ({ r, x: 0, y: 0, size: px })), 1, round); const body = round ? `${d.svg}` : d.svg; const svg = `${defsSVG()}${body}`; x.drawImage(await svgToImage(svg, px, px), 0, 0, px, px); return cv; } // ---------- sheet 2: exploded layers with leader labels ---------- const EX_W = 3307; function explodedSVG(res, opts = {}, ex = {}) { useTheme(opts); const forExport = !!opts.forExport, o = [rootOpen(BW, BH, 'mm', 'hsa-board hsa-exploded')]; if (!forExport) o.push(``); const cvs = ex && ex.canvas, k = cvs ? BW / (cvs.width || EX_W) : BW / EX_W; if (cvs && !forExport) o.push(``); o.push(...titleBand(res, opts, T(['HK SITE ANALYSIS · EXPLODED LAYERS', '香港地盤分析 · 分層爆炸圖']))); if (!cvs) { o.push(`${noteBox(T(['3D view not available', '未能提供 3D 視圖']), T(['this browser cannot draw WebGL', '此瀏覽器未能繪畫 WebGL']), 50)}`); } // labels, right column, in the order of their anchors from top to bottom const LX = 300, LW = BW - M - LX, top = 54, bot = 268; const items = ((ex && ex.anchors) || []).filter((a) => KEYS.includes(a.key) && Number.isFinite(a.x) && Number.isFinite(a.y)) .map((a) => { const d = drawKey(res, a.key), lines = wrap(d.take, 2.3, LW - 7).slice(0, 3); return { a, ax: a.x * k, ay: a.y * k, lines, h: 5.4 + lines.length * 3 + 2 }; }) .sort((p, q) => p.ay - q.ay); let y = top; for (const it of items) { it.y = Math.max(y, Math.min(it.ay - 2, bot)); y = it.y + it.h; } for (let i = items.length - 1, lim = bot; i >= 0; i--) { const it = items[i]; if (it.y + it.h > lim) it.y = lim - it.h; lim = it.y; } for (const it of items) { const key = it.a.key, i = KEYS.indexOf(key), th = TH[key], col = C.num || (th.c === C.ink ? C.site : th.c), ly = it.y + 3.4; let g = ``; g += ``; g += ``; g += tx(LX, ly, String(i + 1).padStart(2, '0'), { size: 3.4, bold: true, fill: col }) + tx(LX + 6.6, ly, T([th.en, th.zh]), { size: 3.4, bold: true, fill: C.ink, role: 'title' }); it.lines.forEach((ln, j) => { g += tx(LX + 6.6, ly + 4.2 + j * 3, ln, { size: 2.3, fill: C.ink2, role: 'take' }); }); o.push(g + ''); } footer(o, 280.5); o.push(''); return o.join('\n'); } function explodedSheetSVG(res, opts = {}, ex = {}) { return explodedSVG(res, opts, ex); } async function explodedSheetCanvas(res, opts = {}, ex = {}, dpi = 200, scale = 1) { const W = Math.round((BW * scale / 25.4) * dpi), H = Math.round((BH * scale / 25.4) * dpi); const svg = explodedSVG(res, { ...opts, forExport: true }, ex); const cv = document.createElement('canvas'); cv.width = W; cv.height = H; const x = cv.getContext('2d'); x.fillStyle = C.paper; x.fillRect(0, 0, W, H); if (ex && ex.canvas) { x.imageSmoothingEnabled = true; x.drawImage(ex.canvas, 0, 0, W, (ex.canvas.height / ex.canvas.width) * W); } x.drawImage(await svgToImage(svg, W, H), 0, 0, W, H); return cv; } // ---------- small APIs for the 3D view and the lead ---------- function theme(opts = {}) { useTheme(opts); return { id: C.id, paper: C.paper, ink: C.ink, ink2: C.ink2, muted: C.muted, rule: C.rule, ground: C.ground, bld: C.bld, road: C.road, site: C.site, accent: { ...C.acc }, dark: !!C.dark, hRamp: C.hRamp.slice(), hBreaks: H_BRK.slice(), shape: SHAPE }; } function titles() { useTheme({ style: C.id, shape: SHAPE }); const o = {}; for (const k of KEYS) o[k] = [TH[k].en, TH[k].zh]; return o; } return { KEYS, STYLES, prepare, boardSVG, boardCanvas, singleSVG, singleCanvas, plateCanvas, explodedSheetSVG, explodedSheetCanvas, theme, titles, kit: (opts) => { useTheme(opts); return kit(); }, BW, BH }; }