// Solar Permit Check: checks a rooftop solar layout the way a permit reviewer looks at it. // All geometry is local metres: x = east, y = north. A roof face is a plane with a downhill azimuth (the way water runs // off, 0 = north, clockwise) and a pitch. A module is a rectangle lying in that plane, given by its centre, its long-side // bearing seen from above and its orientation. Everything runs here in the browser; nothing is sent anywhere. 'use strict'; (() => { const $ = s => document.querySelector(s), $$ = s => [...document.querySelectorAll(s)]; const R = Math.PI / 180, SVGNS = 'http://www.w3.org/2000/svg'; const COMPASS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']; const compass = az => COMPASS[Math.round(((az % 360) + 360) % 360 / 45) % 8]; const angDiff = (a, b) => { const d = Math.abs(((a - b) % 360 + 540) % 360 - 180); return d; }; const fmt = (v, d = 1) => Number.isFinite(v) ? v.toFixed(d) : '—'; const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); // ---------- 2D geometry ---------- const dot = (a, b) => a[0] * b[0] + a[1] * b[1]; const sub = (a, b) => [a[0] - b[0], a[1] - b[1]]; function pointInPoly(p, poly) { let ins = false; for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const a = poly[i], b = poly[j]; if ((a[1] > p[1]) !== (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0]) ins = !ins; } return ins; } function segDist(p, a, b) { const ab = sub(b, a), t = Math.max(0, Math.min(1, dot(sub(p, a), ab) / (dot(ab, ab) || 1))); return Math.hypot(p[0] - a[0] - t * ab[0], p[1] - a[1] - t * ab[1]); } function cross(o, a, b) { return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); } function segCross(a, b, c, d) { const d1 = cross(c, d, a), d2 = cross(c, d, b), d3 = cross(a, b, c), d4 = cross(a, b, d); return ((d1 > 1e-9 && d2 < -1e-9) || (d1 < -1e-9 && d2 > 1e-9)) && ((d3 > 1e-9 && d4 < -1e-9) || (d3 < -1e-9 && d4 > 1e-9)); } const edges = P => P.map((p, i) => [p, P[(i + 1) % P.length]]); // Do two convex polygons overlap (more than touching)? Separating-axis test. function convexOverlap(P, Q, tol = 1e-4) { for (const poly of [P, Q]) for (const [a, b] of edges(poly)) { const n = [a[1] - b[1], b[0] - a[0]], L = Math.hypot(n[0], n[1]) || 1; const pr = X => X.map(p => dot(p, n) / L); const p = pr(P), q = pr(Q); if (Math.max(...p) <= Math.min(...q) + tol || Math.max(...q) <= Math.min(...p) + tol) return false; } return true; } // Shortest distance between two polygons that do not cross (0 if they cross or one holds a vertex of the other). function polyDist(P, Q) { for (const [a, b] of edges(P)) for (const [c, d] of edges(Q)) if (segCross(a, b, c, d)) return 0; let m = Infinity; for (const p of P) for (const [a, b] of edges(Q)) m = Math.min(m, segDist(p, a, b)); for (const q of Q) for (const [a, b] of edges(P)) m = Math.min(m, segDist(q, a, b)); return m; } function centroid(P) { let a = 0, x = 0, y = 0; for (const [p, q] of edges(P)) { const c = p[0] * q[1] - q[0] * p[1]; a += c; x += (p[0] + q[0]) * c; y += (p[1] + q[1]) * c; } return a ? [x / (3 * a), y / (3 * a)] : P[0]; } // ---------- roof geometry ---------- const unit = az => [Math.sin(az * R), Math.cos(az * R)]; function frame(face) { const d = unit(face.az), a = unit(face.az + 90), p = face.pitch * R; return { d, a, p, toPlane: v => [dot(v, d) / Math.cos(p), dot(v, a)] }; } // Four plan corners of a module, plus how far its long side sits from square (the slope or the eave), in degrees. function corners(m, face, L, W) { const { d, a, p } = frame(face); const S = [d[0] * Math.cos(p), d[1] * Math.cos(p), -Math.sin(p)], A = [a[0], a[1], 0]; const dl = (m.bearing - face.az) * R; const th = Math.atan2(Math.sin(dl) * Math.cos(p), Math.cos(dl)); // in-plane angle of the long side from the fall line const U = S.map((s, i) => Math.cos(th) * s + Math.sin(th) * A[i]); const V = S.map((s, i) => -Math.sin(th) * s + Math.cos(th) * A[i]); const c = [m.e, m.n, m.h]; const pts = [[1, 1], [1, -1], [-1, -1], [-1, 1]].map(([u, v]) => [c[0] + u * L / 2 * U[0] + v * W / 2 * V[0], c[1] + u * L / 2 * U[1] + v * W / 2 * V[1]]); const deg = Math.abs(th / R) % 90; return { pts, skew: Math.min(deg, 90 - deg) }; } // ---------- state ---------- const st = { demo: 0, lay: 'draft', own: null, sel: null, focus: null }; const num = (sel, lo, hi, dflt) => { const v = +$(sel).value; return Number.isFinite(v) && $(sel).value !== '' ? Math.min(hi, Math.max(lo, v)) : dflt; }; const cfg = () => ({ edge: num('#sEdge', 0, 200, 25) / 100, gap: num('#sGap', 0, 50, 5) / 100, vent: num('#sVent', 0, 3, 0.35), sq: num('#sSq', 0, 45, 2), street: ((num('#sStreet', -720, 720, 180) % 360) + 360) % 360, city: num('#sCity', 0, 1e5, 0), yield: num('#sYield', 0, 2000, 0), L: num('#sL', 300, 3000, 2382) / 1000, W: num('#sW', 200, 2000, 1134) / 1000, watt: num('#sWatt', 1, 1000, 620) }); function current() { if (st.demo === 'own') return st.own; const D = DEMOS[st.demo]; return { name: D.name, faces: D.faces, vents: D.vents, mods: D.layouts[st.lay].map(([id, face, o, b, e, n, h]) => ({ id, face, o, bearing: b, e, n, h })) }; } // ---------- the checks ---------- function analyse(roof, c) { const faces = Object.fromEntries(roof.faces.map(f => [f.id, f])); const mods = roof.mods.map(m => ({ ...m, flags: {}, notes: [] })); const unknown = mods.filter(m => !faces[m.face]); for (const m of mods) { const f = faces[m.face]; if (!f) continue; const g = corners(m, f, c.L, c.W); m.pts = g.pts; m.skew = g.skew; const fr = frame(f); m.plane = m.pts.map(fr.toPlane); m.fr = fr; } const ok = mods.filter(m => m.pts); const res = { checks: [], mods, faces, unknown }; const add = (id, title, level, text, ids = []) => res.checks.push({ id, title, level, text, ids }); // 1. counts const kw = ok.length * c.watt / 1000; add('count', 'Modules and power', 'info', `${ok.length} modules × ${c.watt} W = ${fmt(kw, 2)} kW DC on ${new Set(ok.map(m => m.face)).size} roof face${new Set(ok.map(m => m.face)).size === 1 ? '' : 's'}.` + (unknown.length ? ` ${unknown.length} module(s) name a face that does not exist: ${unknown.map(m => m.id).join(', ')}.` : ''), unknown.map(m => m.id)); if (unknown.length) res.checks[0].level = 'bad'; // 2. overlaps (any two modules, seen from above) const ov = []; const near = (a, b) => Math.hypot(a.e - b.e, a.n - b.n) < c.L + 0.6; for (let i = 0; i < ok.length; i++) for (let j = i + 1; j < ok.length; j++) if (near(ok[i], ok[j]) && convexOverlap(ok[i].pts, ok[j].pts)) ov.push([ok[i], ok[j]]); ov.forEach(([a, b]) => { a.flags.overlap = b.flags.overlap = 'bad'; a.notes.push('overlaps ' + b.id); b.notes.push('overlaps ' + a.id); }); add('overlap', 'No overlaps', ov.length ? 'bad' : 'ok', ov.length ? `${ov.length} pair(s) overlap: ${ov.slice(0, 6).map(([a, b]) => a.id + '–' + b.id).join(', ')}${ov.length > 6 ? '…' : ''}.` : 'No two modules share roof.', [...new Set(ov.flat().map(m => m.id))]); // 3. edge clearance, measured on the sloped roof surface const edgeBad = []; let tight = Infinity; for (const m of ok) { const f = faces[m.face], F = f.outline.map(m.fr.toPlane); const inside = m.plane.every(p => pointInPoly(p, F)) && !F.some(v => pointInPoly(v, m.plane)); const dd = polyDist(m.plane, F); m.edge = inside ? dd : -dd; tight = Math.min(tight, m.edge); if (m.edge < c.edge - 0.002) { edgeBad.push(m); m.flags.edge = 'bad'; m.notes.push(inside ? `${fmt(m.edge * 100)} cm from the edge` : 'sticks out of its face'); } } add('edge', `At least ${fmt(c.edge * 100, 0)} cm inside each roof edge`, edgeBad.length ? 'bad' : 'ok', edgeBad.length ? `${edgeBad.length} module(s) too close to the edge or outside their face. ${tight <= 0 ? 'At least one runs over the edge of its face.' : `Tightest: ${fmt(tight * 100)} cm.`}` : `Every module clears its edge. Tightest: ${fmt(tight * 100)} cm.`, edgeBad.map(m => m.id)); // 4. gaps between modules on the same face const gapBad = []; let minGap = Infinity; for (let i = 0; i < ok.length; i++) for (let j = i + 1; j < ok.length; j++) { const a = ok[i], b = ok[j]; if (a.face !== b.face || !near(a, b)) continue; const g = polyDist(a.plane, b.plane); if (g > 0.5) continue; if (a.flags.overlap && b.flags.overlap && g === 0) continue; minGap = Math.min(minGap, g); if (g < c.gap - 0.003) { gapBad.push(a, b); a.flags.gap = b.flags.gap = 'warn'; a.notes.push(`${fmt(g * 100)} cm to ${b.id}`); b.notes.push(`${fmt(g * 100)} cm to ${a.id}`); } } const gb = [...new Set(gapBad.map(m => m.id))]; add('gap', `Gaps of at least ${fmt(c.gap * 100, 1)} cm`, gb.length ? 'warn' : 'ok', gb.length ? `${gb.length} module(s) sit closer than the rule. Smallest gap: ${fmt(minGap * 100)} cm.` : (Number.isFinite(minGap) ? `Smallest gap: ${fmt(minGap * 100)} cm.` : 'No neighbouring modules.'), gb); // 5. square to the roof const sk = ok.filter(m => m.skew > c.sq + 1e-6); sk.forEach(m => { m.flags.skew = 'bad'; m.notes.push(`${fmt(m.skew)}° off square`); }); add('square', 'Rows square to the roof', sk.length ? 'bad' : 'ok', sk.length ? `${sk.length} module(s) turned ${fmt(Math.max(...sk.map(m => m.skew)), 0)}° off the slope. From the street they read as a crooked array.` : 'Every module runs with the slope or the eave.', sk.map(m => m.id)); // 6. vents and chimneys const vents = roof.vents || []; const vBad = []; res.ventHits = vents.map(() => false); for (const m of ok) vents.forEach((v, k) => { const inside = pointInPoly(v, m.pts), d = inside ? 0 : Math.min(...edges(m.pts).map(([a, b]) => segDist(v, a, b))); m.vent = Math.min(m.vent ?? Infinity, inside ? -1 : d); if (inside || d < c.vent - 0.005) { vBad.push(m); m.flags.vent = 'bad'; res.ventHits[k] = true; m.notes.push(inside ? 'covers a vent' : `${fmt(d, 2)} m from a vent`); } }); add('vents', `Vents clear by ${fmt(c.vent, 2)} m`, !vents.length ? 'info' : vBad.length ? 'bad' : 'ok', !vents.length ? 'No vents marked. Mark plumbing vents and chimneys from a photo, then check on site.' : vBad.length ? `${new Set(vBad.map(m => m.id)).size} module(s) on or too close to ${res.ventHits.filter(Boolean).length} of ${vents.length} vents.` : `All ${vents.length} marked vents stay clear.`, [...new Set(vBad.map(m => m.id))]); // 7. heights sit on each face's plane const spreadBad = []; for (const f of roof.faces) { const ms = ok.filter(m => m.face === f.id && Number.isFinite(m.h)); if (ms.length < 2) continue; const { d, p } = frame(f); const v = ms.map(m => m.h + dot([m.e, m.n], d) * Math.tan(p)); const spread = Math.max(...v) - Math.min(...v); if (spread > 0.05) { spreadBad.push(f.id); ms.forEach(m => { m.flags.height = 'warn'; }); } } add('heights', 'Heights sit on each roof plane', spreadBad.length ? 'warn' : 'ok', spreadBad.length ? `Face(s) ${spreadBad.join(', ')}: module heights do not fit one plane (more than 5 cm off). Check the pitch or the face each module is on.` : 'Every module height fits its face within 5 cm.', ok.filter(m => m.flags.height).map(m => m.id)); // 8. what the street sees const vis = { face: 0, angle: 0, hidden: 0, flat: 0 }; for (const m of ok) { const f = faces[m.face]; m.seen = f.pitch < 2 ? 'flat' : angDiff(f.az, c.street) <= 45 ? 'face' : angDiff(f.az, c.street) <= 100 ? 'angle' : 'hidden'; vis[m.seen]++; } add('street', 'What the street sees', vis.face ? 'warn' : 'info', `${vis.face} face the street, ${vis.angle} are seen at an angle, ${vis.hidden} face away${vis.flat ? `, ${vis.flat} on a flat roof (check the parapet and the setback from the front wall)` : ''}. Say both numbers in the file, not only the first.`, ok.filter(m => m.seen === 'face').map(m => m.id)); // 9. the city's rooftop estimate if (c.city > 0) add('city', 'Against the city estimate', 'info', `${fmt(kw, 2)} kW is ${fmt(kw / c.city * 100, 0)} % of the city's ${fmt(c.city, 1)} kW estimate. At ${fmt(c.yield, 0)} kWh per kW, about ${Math.round(kw * c.yield).toLocaleString('en-US')} kWh a year: a rough upper figure, because faces turned away from the sun make less. The city figure is indicative, not a limit.`); res.kw = kw; res.vis = vis; return res; } // ---------- drawing ---------- const el = (n, a = {}, parent) => { const e = document.createElementNS(SVGNS, n); for (const k in a) e.setAttribute(k, a[k]); if (parent) parent.appendChild(e); return e; }; const PAL = ['#5b9bd5', '#e8a33d', '#8e6bbf', '#3fa98f', '#d9677a', '#8a96a3', '#b5654a', '#6aa84f']; function levelOf(m) { const v = Object.values(m.flags); return v.includes('bad') ? 'bad' : v.includes('warn') ? 'warn' : 'ok'; } function draw(roof, res, c) { const svg = $('#plan'); svg.textContent = ''; const all = roof.faces.flatMap(f => f.outline).concat(res.mods.filter(m => m.pts).flatMap(m => m.pts)); if (!all.length) return; const xs = all.map(p => p[0]), ys = all.map(p => -p[1]); const pad = 2.6, x0 = Math.min(...xs) - pad, x1 = Math.max(...xs) + pad, y0 = Math.min(...ys) - pad, y1 = Math.max(...ys) + pad; svg.setAttribute('viewBox', `${x0} ${y0} ${x1 - x0} ${y1 - y0}`); const sw = Math.max(x1 - x0, y1 - y0) / 400; const P = pts => pts.map(p => `${p[0].toFixed(3)},${(-p[1]).toFixed(3)}`).join(' '); const gF = el('g', {}, svg), gM = el('g', {}, svg), gV = el('g', {}, svg), gT = el('g', { class: 'lbl' }, svg); roof.faces.forEach((f, i) => { el('polygon', { points: P(f.outline), fill: PAL[i % PAL.length], 'fill-opacity': '.16', stroke: PAL[i % PAL.length], 'stroke-width': sw * 2.2, 'stroke-linejoin': 'round' }, gF); const cc = centroid(f.outline), u = unit(f.az), Lr = 0.9; if (f.pitch >= 2) el('line', { x1: cc[0] - u[0] * Lr, y1: -(cc[1] - u[1] * Lr), x2: cc[0] + u[0] * Lr, y2: -(cc[1] + u[1] * Lr), stroke: 'currentColor', 'stroke-opacity': '.45', 'stroke-width': sw * 2, 'marker-end': 'url(#arr)' }, gF); const n = res.mods.filter(m => m.face === f.id && m.pts).length; const t = el('text', { x: cc[0], y: -cc[1] + 1.55, 'font-size': Math.max(0.55, (x1 - x0) / 34), 'text-anchor': 'middle' }, gT); t.textContent = `${f.id} · ${n}`; }); const defs = el('defs', {}, svg); const mk = el('marker', { id: 'arr', viewBox: '0 0 10 10', refX: '5', refY: '5', markerWidth: '4', markerHeight: '4', orient: 'auto-start-reverse' }, defs); el('path', { d: 'M0,0 L10,5 L0,10 z', fill: 'currentColor', 'fill-opacity': '.5' }, mk); for (const m of res.mods) { if (!m.pts) continue; const lv = levelOf(m), foc = st.focus && st.focus.includes(m.id); const p = el('polygon', { points: P(m.pts), class: `mod ${lv}${st.sel === m.id ? ' sel' : ''}${st.focus && !foc ? ' dim' : ''}`, 'stroke-width': sw * (st.sel === m.id ? 4 : 1.6), tabindex: '0', role: 'button', 'aria-label': `Module ${m.id}, face ${m.face}${lv === 'ok' ? '' : ', has a problem'}` }, gM); p.dataset.id = m.id; } (roof.vents || []).forEach((v, k) => { const hit = res.ventHits[k]; el('circle', { cx: v[0], cy: -v[1], r: c.vent, class: 'vhalo' + (hit ? ' hit' : ''), 'stroke-width': sw * 1.4 }, gV); el('circle', { cx: v[0], cy: -v[1], r: 0.16, class: 'vent' + (hit ? ' hit' : '') }, gV); }); // north arrow, street arrow, 5 m scale const fs = Math.max(0.55, (x1 - x0) / 34); const nx = x1 - 1.2, ny = y0 + 1.9; el('line', { x1: nx, y1: ny, x2: nx, y2: ny - 1.3, stroke: 'currentColor', 'stroke-width': sw * 3, 'marker-end': 'url(#arr)' }, gT); el('text', { x: nx, y: ny + fs * 1.1, 'font-size': fs, 'text-anchor': 'middle' }, gT).textContent = 'N'; const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2, su = unit(c.street), rr = Math.min(x1 - x0, y1 - y0) / 2 - 0.9; const sx = cx + su[0] * rr, sy = cy - su[1] * rr; el('line', { x1: cx + su[0] * (rr - 1.6), y1: cy - su[1] * (rr - 1.6), x2: sx, y2: sy, class: 'street', 'stroke-width': sw * 4, 'marker-end': 'url(#arr)' }, gT); el('text', { x: sx - su[0] * 0.4, y: sy + su[1] * 0.4 - fs * 0.7, 'font-size': fs, 'text-anchor': 'middle', class: 'streettxt' }, gT).textContent = 'street'; const bx = x0 + 0.8, by = y1 - 0.8; el('line', { x1: bx, y1: by, x2: bx + 5, y2: by, stroke: 'currentColor', 'stroke-width': sw * 3 }, gT); el('text', { x: bx + 2.5, y: by - fs * 0.5, 'font-size': fs, 'text-anchor': 'middle' }, gT).textContent = '5 m'; } // ---------- panel ---------- let last = null; function render() { const c = cfg(), roof = current(); if (!roof) { $('#checks').textContent = ''; $('#verdict').textContent = 'Paste your roof below and press Check my roof.'; $('#plan').textContent = ''; $('#faceBody').textContent = ''; return; } const res = analyse(roof, c); last = { roof, res, c }; draw(roof, res, c); const bad = res.checks.filter(k => k.level === 'bad'), warn = res.checks.filter(k => k.level === 'warn'); $('#verdict').className = 'verdict ' + (bad.length ? 'bad' : warn.length ? 'warn' : 'ok'); $('#verdict').innerHTML = bad.length ? `Fix ${bad.length} thing${bad.length > 1 ? 's' : ''} before filing. Red modules on the plan show where.` : warn.length ? `Close. ${warn.length} item${warn.length > 1 ? 's' : ''} to look at, nothing blocking.` : `Ready for a reviewer's eyes. Geometry checks pass; now confirm on site.`; $('#checks').innerHTML = res.checks.map(k => `
  • `).join(''); $$('[data-ck]').forEach(b => b.onclick = () => { const k = res.checks.find(x => x.id === b.dataset.ck); if (st.focusId === k.id) { st.focus = null; st.focusId = null; } else { st.focus = k.ids; st.focusId = k.id; } render(); $('#planCard').scrollIntoView({ behavior: 'smooth', block: 'nearest' }); }); $('#faceBody').innerHTML = roof.faces.map(f => { const ms = res.mods.filter(m => m.face === f.id && m.pts); const s = f.pitch < 2 ? 'flat roof' : angDiff(f.az, c.street) <= 45 ? 'faces it' : angDiff(f.az, c.street) <= 100 ? 'at an angle' : 'faces away'; return `${esc(f.id)}${f.name ? ' ' + esc(f.name) : ''}${f.pitch < 2 ? '—' : compass(f.az) + ' ' + Math.round(f.az) + '°'}${fmt(f.pitch, 1)}°${ms.length}${fmt(ms.length * c.watt / 1000, 2)}${s}`; }).join(''); showDetail(); } function showDetail() { const d = $('#detail'), m = last && last.res.mods.find(x => x.id === st.sel); if (!m || !m.pts) { d.hidden = true; $('#planHint').hidden = false; return; } $('#planHint').hidden = true; d.hidden = false; const f = last.res.faces[m.face]; d.innerHTML = `${esc(m.id)} on face ${esc(m.face)} (${f.pitch < 2 ? 'flat' : compass(f.az) + ', ' + fmt(f.pitch, 1) + '°'}) · ${m.o === 'P' ? 'portrait' : 'landscape'} · ${fmt(m.skew, 1)}° off square · ${fmt(m.edge * 100, 1)} cm from the edge${Number.isFinite(m.vent) ? ` · ${m.vent < 0 ? 'covers a vent' : fmt(m.vent, 2) + ' m from the nearest vent'}` : ''}${m.notes.length ? `
    ${esc([...new Set(m.notes)].join(' · '))}` : '
    No problems.'}`; } $('#plan').addEventListener('click', e => { const id = e.target.dataset && e.target.dataset.id; st.sel = id && st.sel !== id ? id : null; render(); }); $('#plan').addEventListener('keydown', e => { if ((e.key === 'Enter' || e.key === ' ') && e.target.dataset.id) { e.preventDefault(); st.sel = e.target.dataset.id; render(); } }); // ---------- choosing a roof ---------- function setDemo(v) { st.demo = v === 'own' ? 'own' : +v; st.sel = null; st.focus = null; st.focusId = null; $$('[data-demo]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.demo === String(v)))); $('#laySeg').hidden = st.demo === 'own'; $('#ownCard').hidden = st.demo !== 'own'; if (st.demo !== 'own') { const D = DEMOS[st.demo]; $('#sStreet').value = D.street; $('#sCity').value = D.cityKw; $('#sYield').value = D.cityYield; $('#blurb').textContent = D.blurb; } else $('#blurb').textContent = 'Your own roof: paste faces, modules and vents below. Nothing leaves this page.'; render(); } function setLay(v) { st.lay = v; st.sel = null; st.focus = null; st.focusId = null; $$('[data-lay]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.lay === v))); render(); } $$('[data-demo]').forEach(b => b.onclick = () => setDemo(b.dataset.demo)); $$('[data-lay]').forEach(b => b.onclick = () => setLay(b.dataset.lay)); $$('.sets input').forEach(i => i.addEventListener('input', () => { if (i.value === '' || !Number.isFinite(+i.value)) return; render(); })); // ---------- your roof ---------- function parseOwn() { const msg = []; let faces; try { faces = JSON.parse($('#inFaces').value); } catch (e) { throw new Error('Roof faces: not valid JSON (' + e.message + ').'); } if (!Array.isArray(faces) || !faces.length) throw new Error('Roof faces: expected a list of faces.'); faces = faces.map((f, i) => { const o = (f.outline || []).map(p => [+p[0], +p[1]]); if (!f.id || o.length < 3 || o.some(p => !p.every(Number.isFinite))) throw new Error(`Roof face ${i + 1}: needs an id and an outline of at least 3 [east, north] points.`); const az = +f.az, pitch = +f.pitch; if (!Number.isFinite(az) || !Number.isFinite(pitch) || pitch < 0 || pitch >= 80) throw new Error(`Roof face ${f.id}: az (0–360) and pitch (0–80°) must be numbers.`); return { id: String(f.id), name: f.name ? String(f.name) : '', az: ((az % 360) + 360) % 360, pitch, outline: o }; }); const lines = $('#inMods').value.trim().split(/\r?\n/).filter(l => l.trim()); if (!lines.length) throw new Error('Modules: paste at least one line.'); const head = lines[0].toLowerCase().split(/[,;\t]/).map(s => s.trim()); const pick = (...names) => head.findIndex(h => names.includes(h)); const hasHead = head.some(h => /[a-z]/.test(h) && !/^-?[\d.]+$/.test(h)) && pick('east', 'centre_east_m', 'center_east_m', 'e', 'x') >= 0; const ix = hasHead ? { id: pick('id', 'panel_id', 'module'), face: pick('face', 'section', 'plane'), o: pick('orientation', 'o'), b: pick('bearing', 'long_axis_bearing_deg'), e: pick('east', 'centre_east_m', 'center_east_m', 'e', 'x'), n: pick('north', 'centre_north_m', 'center_north_m', 'n', 'y'), h: pick('height', 'centre_height_m', 'center_height_m', 'h', 'z') } : { id: 0, face: 1, o: 2, b: 3, e: 4, n: 5, h: 6 }; for (const k of ['face', 'b', 'e', 'n']) if (ix[k] < 0) throw new Error('Modules: missing a column for ' + ({ face: 'face', b: 'bearing', e: 'east', n: 'north' })[k] + '.'); const mods = lines.slice(hasHead ? 1 : 0).map((l, i) => { const c = l.split(/[,;\t]/).map(s => s.trim().replace(/^"|"$/g, '')); const m = { id: ix.id >= 0 && c[ix.id] ? c[ix.id] : 'M' + String(i + 1).padStart(3, '0'), face: c[ix.face], o: /^p/i.test(c[ix.o] || '') ? 'P' : 'L', bearing: +c[ix.b], e: +c[ix.e], n: +c[ix.n], h: ix.h >= 0 ? +c[ix.h] : NaN }; if (![m.bearing, m.e, m.n].every(Number.isFinite)) throw new Error(`Modules, line ${i + (hasHead ? 2 : 1)}: bearing, east and north must be numbers.`); return m; }); if (mods.length > 2000) throw new Error('Modules: more than 2,000 lines. Split the roof.'); const vents = $('#inVents').value.trim() ? $('#inVents').value.trim().split(/\r?\n/).filter(l => l.trim()).map((l, i) => { const v = l.split(/[,;\t ]+/).map(Number); if (v.length < 2 || !v.slice(0, 2).every(Number.isFinite)) throw new Error(`Vents, line ${i + 1}: write east,north.`); return v.slice(0, 2); }) : []; return { name: 'Your roof', faces, mods, vents, msg }; } $('#runOwn').onclick = () => { try { st.own = parseOwn(); st.sel = null; st.focus = null; st.focusId = null; $('#ownMsg').textContent = `Checked ${st.own.mods.length} modules on ${st.own.faces.length} face${st.own.faces.length === 1 ? '' : 's'}.`; $('#ownMsg').className = 'msg ok'; render(); $('#checkCard').scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) { $('#ownMsg').textContent = e.message; $('#ownMsg').className = 'msg err'; } }; $('#fillOwn').onclick = () => { const D = DEMOS[0]; $('#inFaces').value = JSON.stringify(D.faces.map(f => ({ id: f.id, az: f.az, pitch: f.pitch, outline: f.outline })), null, 0).replace(/\},\{/g, '},\n{'); $('#inMods').value = 'id,face,orientation,bearing,east,north,height\n' + D.layouts.draft.map(([id, f, o, b, e, n, h]) => [id, f, o === 'P' ? 'portrait' : 'landscape', b, e, n, h].join(',')).join('\n'); $('#inVents').value = D.vents.map(v => v.join(',')).join('\n'); $('#sStreet').value = D.street; $('#ownMsg').textContent = 'Demo A draft loaded. Edit it, then press Check my roof.'; $('#ownMsg').className = 'msg'; }; $('#fileIn').onchange = async e => { for (const f of e.target.files) { if (f.size > 2e6) { $('#ownMsg').textContent = f.name + ' is over 2 MB.'; continue; } const t = await f.text(); if (/\.json$/i.test(f.name) || /^\s*\[/.test(t)) $('#inFaces').value = t; else if (/east|centre_east|,/.test(t.split('\n')[0]) && t.split('\n').length > 1 && t.split('\n')[0].split(',').length > 3) $('#inMods').value = t; else $('#inVents').value = t; } $('#ownMsg').textContent = 'Files loaded. Press Check my roof.'; $('#ownMsg').className = 'msg'; e.target.value = ''; }; // ---------- report ---------- $('#copyBtn').onclick = async () => { if (!last) return; const { roof, res, c } = last; const t = [`Solar Permit Check: ${roof.name}${st.demo === 'own' ? '' : ' (' + (st.lay === 'draft' ? 'first draft' : 'fixed') + ')'}`, `Rules: edge ${fmt(c.edge * 100, 0)} cm, gap ${fmt(c.gap * 100, 1)} cm, vents ${fmt(c.vent, 2)} m, square within ${fmt(c.sq, 1)}°, street toward ${Math.round(c.street)}°, module ${Math.round(c.L * 1000)} × ${Math.round(c.W * 1000)} mm ${c.watt} W`, '', ...res.checks.map(k => `[${({ ok: 'PASS', bad: 'FIX', warn: 'CHECK', info: 'NOTE' })[k.level]}] ${k.title}: ${k.text}${k.ids.length ? ' (' + k.ids.join(', ') + ')' : ''}`), '', 'By face:', ...roof.faces.map(f => ` ${f.id}${f.name ? ' ' + f.name : ''}: ${res.mods.filter(m => m.face === f.id && m.pts).length} modules, ${f.pitch < 2 ? 'flat' : compass(f.az) + ' ' + fmt(f.pitch, 1) + '°'}`), '', 'Geometry check only: not an electrical, structural or fire-code design. Confirm vents, pitches and edges on site.'].join('\n'); try { await navigator.clipboard.writeText(t); $('#copyMsg').textContent = 'Copied.'; } catch { $('#copyMsg').textContent = 'Copy was blocked. Select the checks and copy by hand.'; } setTimeout(() => { $('#copyMsg').textContent = ''; }, 2500); }; // ---------- guided tour ---------- const TOUR = [ ['#pickBar', 'Pick a roof', 'Two made-up houses come with the tool. Demo A starts on its first draft, the kind of layout a design tool or a quick sketch produces.', () => { setDemo(0); setLay('draft'); }], ['#planCard', 'Read the plan', 'This is the roof from above. Coloured shapes are roof faces with arrows pointing downhill; dark rectangles are modules. Red ones break a rule. Red rings are vents a module covers.', null], ['#checkCard', 'Go through the checks', 'Each line is one thing a reviewer looks for. Tap a line to light up its modules on the plan. Here: overlaps, a crooked street-face array, modules on vents and one face too close to the edge.', () => { st.focus = null; st.focusId = null; render(); }], ['#pickBar', 'See it fixed', 'The Fixed layout keeps every module square, off the vents and inside the edges. The red goes away; what is left is a note to explain the modules the street can see.', () => setLay('fixed')], ['#setCard', 'Use your own rules', 'Set your borough\'s clearances, the way the street lies, the city\'s rooftop estimate and your module size. Every check updates as you type.', null], ['#ownCard', 'Check your own roof', 'Paste your roof faces, module list and vents (or load the files), press Check my roof, then copy the report into your permit notes.', () => setDemo('own')] ]; let ti = 0; function tourShow() { const [sel, title, text, act] = TOUR[ti]; if (act) act(); $$('.lit').forEach(x => x.classList.remove('lit')); const t = $(sel); t.classList.add('lit'); const top = t.getBoundingClientRect().top + scrollY - 10; scrollTo({ top: Math.max(0, top), behavior: 'smooth' }); $('#tStep').textContent = `Step ${ti + 1} of ${TOUR.length}`; $('#tTitle').textContent = title; $('#tText').textContent = text; $('#tBack').disabled = ti === 0; $('#tNext').textContent = ti === TOUR.length - 1 ? 'Done' : 'Next'; } function tourEnd() { $('#tour').hidden = true; $$('.lit').forEach(x => x.classList.remove('lit')); document.body.classList.remove('touring'); } $('#tourBtn').onclick = () => { ti = 0; $('#tour').hidden = false; document.body.classList.add('touring'); tourShow(); $('#tNext').focus(); }; $('#tNext').onclick = () => { if (ti === TOUR.length - 1) { tourEnd(); setDemo(0); setLay('draft'); return; } ti++; tourShow(); }; $('#tBack').onclick = () => { if (ti > 0) { ti--; tourShow(); } }; $('#tClose').onclick = tourEnd; document.addEventListener('keydown', e => { if (e.key === 'Escape' && !$('#tour').hidden) tourEnd(); }); setDemo(0); if (/[?&]tour=1/.test(location.search)) $('#tourBtn').click(); window.__solar = { analyse, cfg, current, DEMOS }; // for tests })();