main.js entry 155.3 KB
Copy main.js
SimKit.define({
title: "Car audio lab",
dt: 2e-5, speed: 0.05, height: 720,
params: {},
_F: [100, 1000, 5000],
_PR: [0.5, 0.35, 0.2],
_FONT: "'MS Sans Serif',Tahoma,Verdana,system-ui,sans-serif",
_MONO: "'Lucida Console','Courier New',monospace",
_L: { ws: { x: 0, y: 0, w: 1, h: 1 }, pn: { x: 0, y: 0, w: 1, h: 1 }, k: 1, port: false },
_TABS: [["Power", "Power"], ["Heads", "Head units"], ["Wiring", "Wiring"], ["Amps", "Amps"], ["Spkrs", "Speakers"], ["Tools", "Tools"]],
_roots: [110, 87.31, 130.81, 98],
_arps: [[440, 523.25, 659.25], [349.23, 440, 523.25], [523.25, 659.25, 783.99], [392, 493.88, 587.33]],
_bells: [2637, 2793, 3136, 2349],
_C: null,
_EX: ["Empty", "Basic", "ISO + sub", "Faulty", "Series + EQ lab"],
_SAVEKEY: "caraudio.save.v1",
_SL: 16384,
// ---- Win95 palette ----
_C95: {
face: "#c0c0c0", light: "#ffffff", shadow: "#808080", dark: "#000000",
title: "#000080", titleT: "#ffffff", field: "#ffffff", fieldD: "#808080",
text: "#000000", dim: "#808080", hot: "#000080", hotT: "#ffffff",
ok: "#008000", warn: "#808000", bad: "#800000", bevelHi: "#dfdfdf"
},
_ASTAR_MAX: 300,
_LOD_WIRES: 250,
_ui0() { return { preset: 2, ign: 1, eng: 0, snd: 0, Vcc: 13.8 }; },
// ================================================================ WIN95 WIDGETS
_raised(g, x, y, w, h, fill) {
const P = this._C95;
g.save();
g.fillStyle = fill || P.face; g.fillRect(x, y, w, h);
g.fillStyle = P.light; g.fillRect(x, y, w, 1); g.fillRect(x, y, 1, h);
g.fillStyle = P.shadow; g.fillRect(x, y + h - 1, w, 1); g.fillRect(x + w - 1, y, 1, h);
g.fillStyle = P.dark; g.fillRect(x + 1, y + h - 2, w - 2, 1); g.fillRect(x + w - 2, y + 1, 1, h - 2);
g.restore();
},
_sunken(g, x, y, w, h, fill) {
const P = this._C95;
g.save();
g.fillStyle = fill || P.field; g.fillRect(x, y, w, h);
g.fillStyle = P.shadow; g.fillRect(x, y, w, 1); g.fillRect(x, y, 1, h);
g.fillStyle = P.dark; g.fillRect(x + 1, y + 1, w - 2, 1); g.fillRect(x + 1, y + 1, 1, h - 2);
g.fillStyle = P.light; g.fillRect(x, y + h - 1, w, 1); g.fillRect(x + w - 1, y, 1, h);
g.restore();
},
_btn95(g, x, y, w, h, label, active, sz, mono) {
const P = this._C95;
if (active) this._sunken(g, x, y, w, h, P.face);
else this._raised(g, x, y, w, h, P.face);
g.save();
g.font = (mono ? this._MONO : this._FONT);
g.font = (sz || 11) + "px " + g.font;
g.fillStyle = P.text; g.textAlign = "center"; g.textBaseline = "middle";
g.fillText(label, x + w / 2 + (active ? 1 : 0), y + h / 2 + (active ? 1 : 0));
g.restore();
},
_field95(g, x, y, w, h, label, sz) {
const P = this._C95;
this._sunken(g, x, y, w, h, P.field);
g.save();
g.font = (sz || 11) + "px " + this._MONO;
g.fillStyle = P.text; g.textAlign = "center"; g.textBaseline = "middle";
g.fillText(label, x + w / 2, y + h / 2);
g.restore();
},
_title95(g, x, y, w, h, text, sz) {
const P = this._C95;
g.save();
g.fillStyle = P.title; g.fillRect(x, y, w, h);
g.font = "bold " + (sz || 12) + "px " + this._FONT;
g.fillStyle = P.titleT; g.textAlign = "left"; g.textBaseline = "middle";
g.fillText(text, x + 6, y + h / 2);
g.restore();
},
_chip95(g, x, y, w, h, text, color, sz) {
const P = this._C95;
this._sunken(g, x, y, w, h, P.face);
g.save();
g.fillStyle = color; g.beginPath(); g.arc(x + 8, y + h / 2, 4, 0, 6.2832); g.fill();
g.font = (sz || 10) + "px " + this._FONT; g.fillStyle = P.text;
g.textAlign = "left"; g.textBaseline = "middle";
g.fillText(text, x + 16, y + h / 2);
g.restore();
},
// ================================================================ CABLE SYSTEM HELPERS
_bump(S) { S.ver = (S.ver || 0) + 1; S.rsig = null; },
_hash(str) { let h = 0; for (let i = 0; i < str.length; i++) h = (h * 31 + str.charCodeAt(i)) | 0; return h < 0 ? -h : h; },
_bbox(r) {
let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;
for (const p of r) { if (p[0] < x0) x0 = p[0]; if (p[0] > x1) x1 = p[0]; if (p[1] < y0) y0 = p[1]; if (p[1] > y1) y1 = p[1]; }
return [x0, y0, x1, y1];
},
_segHitsRect(ax, ay, bx, by, r) {
const [x0, y0, x1, y1] = r;
if (ay === by) {
if (ay < y0 || ay > y1) return false;
const lo = Math.min(ax, bx), hi = Math.max(ax, bx);
return hi > x0 && lo < x1;
}
if (ax === bx) {
if (ax < x0 || ax > x1) return false;
const lo = Math.min(ay, by), hi = Math.max(ay, by);
return hi > y0 && lo < y1;
}
return false;
},
_routeHitsAny(route, rects) {
for (let i = 0; i + 1 < route.length; i++) {
const a = route[i], b = route[i + 1];
for (const r of rects) if (this._segHitsRect(a[0], a[1], b[0], b[1], r)) return true;
}
return false;
},
_obstacleRects(S) {
const C = this._cat(), out = [];
for (const p of S.parts) {
const d = C[p.t];
out.push([p.x - 6, p.y - 6, p.x + d.w + 6, p.y + d.h + 6]);
}
return out;
},
_routeAround(ax, ay, bx, by, h, obs, S) {
const X0 = 178, Y0 = 30, X1 = 1822, Y1 = 1154;
const xs = new Set(), ys = new Set();
xs.add(this._snap((ax + bx) / 2)); ys.add(this._snap((ay + by) / 2));
for (const r of obs) { xs.add(r[0] - 10); xs.add(r[2] + 10); ys.add(r[1] - 10); ys.add(r[3] + 10); }
const xc = [...xs].filter(v => v > X0 + 4 && v < X1 - 4);
const yc = [...ys].filter(v => v > Y0 + 4 && v < Y1 - 4);
const mxm = (ax + bx) / 2, mym = (ay + by) / 2;
xc.sort((p, q) => Math.abs(p - mxm) - Math.abs(q - mxm));
yc.sort((p, q) => Math.abs(p - mym) - Math.abs(q - mym));
const lane = ((h % 9) - 4) * 10;
for (const my of yc) {
const r = this._elbow([[ax, ay], [ax, my + lane * 0.1], [bx, my + lane * 0.1], [bx, by]]);
if (!this._routeHitsAny(r, obs)) return r;
}
for (const mx of xc) {
const r = this._elbow([[ax, ay], [mx + lane * 0.1, ay], [mx + lane * 0.1, by], [bx, by]]);
if (!this._routeHitsAny(r, obs)) return r;
}
for (const my of yc) for (const mx of xc) {
const r = this._elbow([[ax, ay], [mx, ay], [mx, my], [bx, my], [bx, by]]);
if (!this._routeHitsAny(r, obs)) return r;
}
if (Math.abs(bx - ax) >= Math.abs(by - ay)) {
const mx = this._snap((ax + bx) / 2) + lane;
return this._elbow([[ax, ay], [mx, ay], [mx, by], [bx, by]]);
}
const my = this._snap((ay + by) / 2) + lane;
return this._elbow([[ax, ay], [ax, my], [bx, my], [bx, by]]);
},
_fastRoute(a, b, h, S) {
const ax = a.x, ay = a.y, bx = b.x, by = b.y;
const lane = ((h % 9) - 4) * 10;
const straight = (ax === bx || ay === by) ? [[ax, ay], [bx, by]] : null;
if (S) {
const obs = this._obstacleRects(S);
if (straight && !this._routeHitsAny(straight, obs)) return straight;
if (straight) return this._routeAround(ax, ay, bx, by, h, obs, S);
const tries = [];
if (Math.abs(bx - ax) >= Math.abs(by - ay)) {
const mx0 = this._snap((ax + bx) / 2) + lane;
tries.push(this._elbow([[ax, ay], [mx0, ay], [mx0, by], [bx, by]]));
const my0 = this._snap((ay + by) / 2) + lane;
tries.push(this._elbow([[ax, ay], [ax, my0], [bx, my0], [bx, by]]));
for (let k = 1; k <= 4; k++) {
const mx1 = this._snap((ax + bx) / 2) + ((h + k * 7) % 9 - 4) * 10;
tries.push(this._elbow([[ax, ay], [mx1, ay], [mx1, by], [bx, by]]));
}
} else {
const my0 = this._snap((ay + by) / 2) + lane;
tries.push(this._elbow([[ax, ay], [ax, my0], [bx, my0], [bx, by]]));
const mx0 = this._snap((ax + bx) / 2) + lane;
tries.push(this._elbow([[ax, ay], [mx0, ay], [mx0, by], [bx, by]]));
for (let k = 1; k <= 4; k++) {
const my1 = this._snap((ay + by) / 2) + ((h + k * 7) % 9 - 4) * 10;
tries.push(this._elbow([[ax, ay], [ax, my1], [bx, my1], [bx, by]]));
}
}
for (const r of tries) if (!this._routeHitsAny(r, obs)) return r;
return this._routeAround(ax, ay, bx, by, h, obs, S);
}
if (straight) return straight;
if (Math.abs(bx - ax) >= Math.abs(by - ay)) {
const mx = this._snap((ax + bx) / 2) + lane;
return this._elbow([[ax, ay], [mx, ay], [mx, by], [bx, by]]);
}
const my = this._snap((ay + by) / 2) + lane;
return this._elbow([[ax, ay], [ax, my], [bx, my], [bx, by]]);
},
_dragRoutes(S) {
const W = S.wires, id = S.drag.id;
let full = false;
if (S.rt.length !== W.length || !S.rbb || S.rbb.length !== W.length) { S.rt = new Array(W.length).fill(null); S.rbb = new Array(W.length).fill(null); full = true; }
for (let i = 0; i < W.length; i++) {
const w = W[i], a = S.tm[w.a], b = S.tm[w.b];
if (!a || !b) { S.rt[i] = null; S.rbb[i] = null; continue; }
if (full || a.p.id === id || b.p.id === id) { const r = this._fastRoute(a, b, this._hash(w.a + ">" + w.b), S); S.rt[i] = r; S.rbb[i] = this._bbox(r); }
}
},
// ================================================================ CATALOG
_cat() {
if (this._C) return this._C;
const Y = "#f2c40c", O = "#f28c0c", B = "#2f7be8", Wh = "#f4f4f4", Bk = "#161616", R = "#e02424";
const T = (n, x, y, k, lab, pos, tip, o) => Object.assign({ n, x: Math.round(x / 10) * 10, y: Math.round(y / 10) * 10, k, lab: lab || "", pos: pos || "", tip: tip || lab || n }, o || {});
const PR = (k, l, min, max, step, v, u, fmt, vals) => ({ k, l, min, max, step, v, u: u || "", fmt, vals });
const ONOFF = ["OFF", "ON"];
const pinset = (pre, n, x, y, vis) => {
const a = [];
for (let i = 1; i <= n; i++) {
const v = vis && vis[i];
a.push(v ? T(pre + i, v[0], v[1], v[2], v[3], "v", v[4], { col: v[5] }) : T(pre + i, x, y, "pin", "", "", "ISO pin " + pre + i, { h: 1 }));
}
return a;
};
const KD = {
tw: { resp: [0.05, 0.3, 1], lim: [0.02, 0.2, 1] },
wf: { resp: [1, 1, 0.3], lim: [1, 1, 1] },
sw: { resp: [1, 0.1, 0], lim: [1, 0.3, 0.05] },
cx: { resp: [0.8, 1, 0.8], lim: [0.6, 1, 0.9] }
};
const C = {};
C.bat = { kind: "bat", cat: "Power", name: "Battery", ab: "BAT", w: 60, h: 80, spec: "series: voltages add up",
props: [PR("v", "Voltage", 0, 12, 1, 0, "", ["Car (toolbar)", "1.5 V", "3 V", "6 V", "9 V", "12 V"], [0, 1.5, 3, 6, 9, 12])],
tm: [T("pos", 30, 0, "pwr", "+", "r", "Battery positive (+)"), T("neg", 30, 80, "gnd", "\u2212", "r", "Battery negative (\u2212)")] };
C.gnd = { kind: "gnd", cat: "Power", name: "Chassis ground lug", ab: "GND", w: 40, h: 40, spec: "surface + cable decide the noise",
props: [PR("surf", "Surface", 0, 2, 1, 0, "", ["Bare metal", "Painted", "Rusty"], [0, 1, 2]), PR("cab", "Ground cable", 0, 2, 1, 0, "", ["Thick 4 AWG", "Medium 10 AWG", "Thin 18 AWG"], [0, 1, 2])],
tm: [T("g", 20, 0, "gnd", "", "", "Chassis ground lug (bare metal, tied to battery \u2212)")] };
C.fuse = { kind: "fuse", cat: "Power", name: "Fuse", ab: "F", w: 100, h: 40, spec: "",
props: [PR("amps", "Rating", 1, 60, 1, 10, " A", null, [1, 2, 3, 5, 7.5, 10, 15, 20, 25, 30, 40, 60])],
tm: [T("a", 0, 20, "ter", "", "", "Fuse terminal A"), T("b", 100, 20, "ter", "", "", "Fuse terminal B")] };
C.mainfuse = { kind: "fuse", cat: "Power", name: "Main fuse (at battery)", ab: "MF", w: 100, h: 40, spec: "30-300 A, next to the battery",
props: [PR("amps", "Rating", 30, 300, 10, 100, " A", null, [30, 40, 60, 80, 100, 150, 200, 250, 300])],
tm: [T("a", 0, 20, "ter", "", "", "Main fuse terminal A (battery side)"), T("b", 100, 20, "ter", "", "", "Main fuse terminal B (to the car)")] };
C.sw = { kind: "sw", cat: "Power", name: "Ignition key switch", ab: "KEY", w: 80, h: 40, props: [], spec: "follows the Key button",
tm: [T("a", 0, 20, "ter", "", "", "Ignition terminal A"), T("b", 80, 20, "ter", "", "", "Ignition terminal B")] };
C.nfilt = { kind: "fuse", nf: true, cat: "Power", name: "12V noise filter (in-line)", ab: "NF", w: 100, h: 40, spec: "cuts alternator whine downstream",
props: [PR("db", "Attenuation", 6, 30, 6, 12, " dB", null, [6, 12, 20, 30])],
tm: [T("a", 0, 20, "ter", "", "", "Noise filter IN (from battery / fuse)"), T("b", 100, 20, "ter", "", "", "Noise filter OUT (to the device)")] };
C.relay = { kind: "relay", cat: "Power", name: "Relay SPST 12V", ab: "RLY", w: 100, h: 70, props: [], spec: "closes COM-NO when coil \u2265 9 V",
tm: [T("cp", 0, 20, "pwr", "C+", "r", "Relay coil + (needs 9 V or more across the coil)"), T("cm", 0, 50, "gnd", "C\u2212", "r", "Relay coil \u2212 (to ground)"),
T("com", 100, 20, "ter", "COM", "l", "Relay common contact"), T("no", 100, 50, "ter", "NO", "l", "Relay normally-open contact (joins COM when the coil is on)")] };
C.diode = { kind: "diode", cat: "Power", name: "Power diode", ab: "D", w: 80, h: 40, props: [], spec: "passes current anode \u2192 cathode only",
tm: [T("a", 0, 20, "ter", "A", "u", "Diode anode"), T("k", 80, 20, "ter", "K", "u", "Diode cathode")] };
C.bigcap = { kind: "bigcap", cat: "Power", name: "Power capacitor (stiffening)", ab: "CAP", w: 80, h: 60, spec: "smooths 12V, cuts whine",
props: [PR("F", "Capacitance", 0.1, 1, 0.1, 0.5, " F", null, [0.1, 0.5, 1])],
tm: [T("pos", 20, 0, "pwr", "+", "u", "Capacitor + (join it to the amp 12V line)"), T("neg", 60, 0, "gnd", "\u2212", "u", "Capacitor \u2212 (to chassis ground)")] };
const head = o => {
const w = o.iso ? 220 : 280, h = 130, tm = [], outs = [], pre = [];
let hp;
if (o.iso) {
tm.push(T("mA", 60, h, "mateA", "ISO A", "v", "ISO connector A (power). Wire it to a harness or adapter plug of the same type", { mate: { pre: "A", n: 8 } }));
tm.push(T("mB", 140, h, "mateB", "ISO B", "v", "ISO connector B (speakers). Wire it to a harness or adapter plug of the same type", { mate: { pre: "B", n: 8 } }));
tm.push(...pinset("A", 8, 60, h), ...pinset("B", 8, 140, h));
hp = { mem: "A4", acc: "A7", gnd: "A8", rem: "A5", ant: "A5" };
[["B5", "B6"], ["B3", "B4"], ["B7", "B8"], ["B1", "B2"]].forEach(q => outs.push({ p: q[0], m: q[1] }));
} else {
const nm = ["fl.p", "fl.m", "fr.p", "fr.m", "rl.p", "rl.m", "rr.p", "rr.m", "mem", "acc", "gnd", "rem", "ant"];
const lb = ["FL+", "FL\u2212", "FR+", "FR\u2212", "RL+", "RL\u2212", "RR+", "RR\u2212", "MEM", "ACC", "GND", "REM", "ANT"];
const kk = ["spk", "spk", "spk", "spk", "spk", "spk", "spk", "spk", "pwr", "pwr", "gnd", "rem", "pwr"];
const chc = ["#f4f4f4", "#8a8a8a", "#2eaa4a", "#8e44ad"];
const cl = [0, 1, 2, 3, 4, 5, 6, 7].map(i => ({ c: chc[i >> 1], s: i % 2 ? Bk : null })).concat([{ c: Y }, { c: O }, { c: Bk }, { c: B, s: Wh }, { c: B }]);
const tp = ["Speaker out FL +", "Speaker out FL \u2212", "Speaker out FR +", "Speaker out FR \u2212", "Speaker out RL +", "Speaker out RL \u2212", "Speaker out RR +", "Speaker out RR \u2212",
"Memory input (yellow, constant 12V via fuse)", "Accessory input (orange, switched 12V via key + fuse)", "Ground (black)", "Remote output (blue/white, 12V when on)", "Power antenna 12V output (blue)"];
nm.forEach((n, i) => tm.push(T(n, 10 + i * 20, h, kk[i], lb[i], "v", tp[i], { col: cl[i] })));
hp = { mem: "mem", acc: "acc", gnd: "gnd", rem: "rem", ant: "ant" };
[["fl.p", "fl.m"], ["fr.p", "fr.m"], ["rl.p", "rl.m"], ["rr.p", "rr.m"]].forEach(q => outs.push({ p: q[0], m: q[1] }));
}
tm.push(T("antin", w - 20, 0, "rf", "ANT", "u", "Antenna input (coax)"));
const PN = ["FL", "FR", "RL", "RR", "SL", "SR"];
for (let i = 0; i < (o.pairs || 0) * 2; i++) {
const n = "pre" + PN[i];
tm.push(T(n, 20 + i * 20, 0, i % 2 ? "rcaR" : "rcaL", PN[i], "u", "Pre-out " + PN[i] + " (line level, " + o.preV + " V)" + (i >= 4 ? " with low-pass" : "")));
pre.push({ t: n, sub: i >= 4 });
}
const props = [PR("vol", "Volume", 0, 1, 0.05, 0.6, "", v => Math.round(v * 100) + "%")];
if (o.cd) props.push(PR("src", "Source", 0, 1, 1, 0, "", ["CD", "Radio"], [0, 1]));
if (o.pairs >= 3) props.push(PR("fc", "Sub pre-out LPF", 40, 400, 10, 100, " Hz"));
if (o.eq) props.push(PR("bass", "Bass EQ", -10, 10, 1, 0, " dB"), PR("treb", "Treble EQ", -10, 10, 1, 0, " dB"));
props.push(PR("bal", "Balance L/R", -10, 10, 1, 0, "", v => v === 0 ? "Center" : (v < 0 ? "Left " : "Right ") + Math.abs(v)));
props.push(PR("fad", "Fader front/rear", -10, 10, 1, 0, "", v => v === 0 ? "Center" : (v < 0 ? "Rear " : "Front ") + Math.abs(v)));
props.push(PR("loud", "Loudness", 0, 1, 1, 0, "", ["Off", "On"], [0, 1]));
props.push(PR("hpf", "Speaker high-pass", 0, 120, 20, 0, "", v => v ? v + " Hz" : "Off", [0, 60, 80, 120]));
if (o.pairs) props.push(PR("plv", "Pre-out level", 0.5, 1, 0.05, 1, "", v => Math.round(v * 100) + "%"));
if (o.pairs >= 3) props.push(PR("sub", "Sub pre-out level", -10, 10, 1, 0, " dB"));
return { kind: "head", cat: "Head units", name: o.name, ab: "HU", w, h, tm, hp, outs, pre, min: 3, rms: o.rms, preV: o.preV || 0, remMA: o.remMA, cd: !!o.cd, radio: !o.cd, iso: !!o.iso, props,
spec: "4\u00d7" + o.rms + "W RMS \u00b7 " + (o.pairs ? o.pairs + " pre-out pair(s) " + o.preV + "V" : "no pre-out") + " \u00b7 REM " + o.remMA + "mA" };
};
C.head_basic = head({ name: "Head unit BASIC 4x20W (loose wires)", rms: 20, cd: true, remMA: 300, pairs: 0 });
C.head_pre = head({ name: "Head unit PRE-OUT 4x50W (loose wires)", rms: 50, cd: true, remMA: 300, pairs: 3, preV: 4, eq: true });
C.head_radio = head({ name: "Head unit RADIO 4x20W (ISO)", rms: 20, iso: true, remMA: 300, pairs: 1, preV: 2 });
C.head_mid = head({ name: "Head unit MID 4x50W (ISO)", rms: 50, cd: true, iso: true, remMA: 300, pairs: 3, preV: 4, eq: true });
C.head_top = head({ name: "Head unit TOP 4x60W (ISO)", rms: 60, cd: true, iso: true, remMA: 500, pairs: 3, preV: 5, eq: true });
const hv = [];
hv[4] = [20, 70, "pwr", "MEM", "Harness A4: constant 12V (yellow)", { c: Y }];
hv[5] = [40, 70, "rem", "REM", "Harness A5: remote/antenna (blue)", { c: B, s: Wh }];
hv[7] = [60, 70, "pwr", "ACC", "Harness A7: switched 12V (red)", { c: R }];
hv[8] = [80, 70, "gnd", "GND", "Harness A8: ground (black)", { c: Bk }];
const sc = { 1: "#8e44ad", 2: "#8e44ad", 3: "#8a8a8a", 4: "#8a8a8a", 5: "#f4f4f4", 6: "#f4f4f4", 7: "#2eaa4a", 8: "#2eaa4a" };
const sn = { 1: "RR", 2: "RR", 3: "FR", 4: "FR", 5: "FL", 6: "FL", 7: "RL", 8: "RL" };
const bv = [];
for (let i = 1; i <= 8; i++) bv[i] = [110 + (i - 1) * 20, 70, "spk", sn[i] + (i % 2 ? "+" : "\u2212"), "Harness B" + i + ": " + sn[i] + (i % 2 ? " +" : " \u2212"), { c: sc[i], s: i % 2 ? null : Bk }];
C.iso_harness = { kind: "pass", cat: "Wiring", name: "ISO car harness (loose wires)", ab: "HRN", w: 280, h: 70, props: [], spec: "",
tm: [T("mA", 50, 0, "mateA", "ISO A", "u", "Harness plug A. Mates with head unit ISO A", { mate: { pre: "A", n: 8 } }),
T("mB", 190, 0, "mateB", "ISO B", "u", "Harness plug B. Mates with head unit ISO B", { mate: { pre: "B", n: 8 } }),
...pinset("A", 8, 50, 0, hv), ...pinset("B", 8, 190, 0, bv)] };
const ad = [], ints = [];
ad.push(T("pA", 20, 0, "mateA", "A", "u", "Adapter plug A (to head unit)", { mate: { pre: "pA", n: 8 } }), T("pB", 70, 0, "mateB", "B", "u", "Adapter plug B (to head unit)", { mate: { pre: "pB", n: 8 } }),
T("qA", 20, 60, "mateA", "A", "d", "Adapter socket A (to car harness)", { mate: { pre: "qA", n: 8 } }), T("qB", 70, 60, "mateB", "B", "d", "Adapter socket B (to car harness)", { mate: { pre: "qB", n: 8 } }));
ad.push(...pinset("pA", 8, 20, 0), ...pinset("pB", 8, 70, 0), ...pinset("qA", 8, 20, 60), ...pinset("qB", 8, 70, 60));
for (let i = 1; i <= 8; i++) { ints.push(["pA" + i, "qA" + (i === 4 ? 7 : i === 7 ? 4 : i)]); ints.push(["pB" + i, "qB" + i]); }
C.iso_adapter = { kind: "pass", cat: "Wiring", name: "ISO adapter (A4/A7 swapped)", ab: "ADP", w: 100, h: 60, props: [], spec: "swaps MEM and ACC", tm: ad, int: ints };
C.isol = { kind: "filt", iso: true, cat: "Wiring", name: "Ground loop isolator (RCA)", ab: "ISO", w: 140, h: 70, spec: "breaks the RCA ground loop, no power", props: [],
tm: [T("inL", 0, 20, "rcaL", "L", "r", "Isolator input L"), T("inR", 0, 50, "rcaR", "R", "r", "Isolator input R"),
T("outL", 140, 20, "rcaL", "L", "l", "Isolator output L"), T("outR", 140, 50, "rcaR", "R", "l", "Isolator output R")] };
C.ant = { kind: "ant", cat: "Wiring", name: "Active antenna", ab: "ANT", w: 120, h: 60, props: [], spec: "12V, 300mA",
tm: [T("sig", 30, 60, "rf", "RF", "u", "Antenna signal output (coax)"), T("pwr", 60, 60, "pwr", "12V", "u", "Antenna amplifier 12V+ (from head ANT/REM output)"), T("gnd", 90, 60, "gnd", "GND", "u", "Antenna ground")] };
const two = (kind, name, ab, pr, spec) => ({ kind, cat: "Wiring", name, ab, w: 80, h: 40, props: [pr], spec, tm: [T("a", 0, 20, "cap", "", "", name + " terminal A"), T("b", 80, 20, "cap", "", "", name + " terminal B")] });
C.cap = two("cap", "Capacitor (high-pass)", "C", PR("uF", "Capacitance", 1, 100, 1, 10, " \u00b5F", null, [1, 2.2, 4.7, 10, 22, 47, 100]), "series, for tweeters");
C.coil = two("coil", "Coil (low-pass)", "L", PR("mH", "Inductance", 0.1, 5, 0.1, 1, " mH", null, [0.1, 0.2, 0.5, 1, 2, 3.3]), "series, for woofers/subs");
C.distblock = { kind: "pass", cat: "Wiring", name: "Distribution block (1 in, 4 out)", ab: "DST", w: 80, h: 80, props: [], spec: "joins IN with O1..O4",
tm: [T("in", 0, 40, "ter", "IN", "r", "Distribution block input"), T("o1", 80, 10, "ter", "O1", "l", "Output 1"), T("o2", 80, 30, "ter", "O2", "l", "Output 2"), T("o3", 80, 50, "ter", "O3", "l", "Output 3"), T("o4", 80, 70, "ter", "O4", "l", "Output 4")],
int: [["in", "o1"], ["in", "o2"], ["in", "o3"], ["in", "o4"]] };
const xo = (name, ab, outs, props, spec) => {
const h = outs.length === 2 ? 80 : 90, tm = [T("in", 0, 40, "rcaL", "IN", "r", "Crossover input (line level, mono)")];
outs.forEach((s, i) => tm.push(T("out" + s, 140, (outs.length === 2 ? [30, 50] : [30, 50, 70])[i], s === "H" ? "rcaR" : "rcaL", s, "l", "Crossover output " + ({ L: "LOW", M: "MID", H: "HIGH" })[s])));
tm.push(T("pwr", 50, 0, "pwr", "12V", "u", "Crossover 12V+ (fused)"), T("gnd", 90, 0, "gnd", "GND", "u", "Crossover ground"));
return { kind: "filt", xo: outs, cat: "Wiring", name, ab, w: 140, h, spec, props, tm };
};
const ORD = PR("order", "Slope", 6, 24, 6, 12, " dB/oct", null, [6, 12, 24]);
C.xover2 = xo("Active crossover 2-way", "X2", ["L", "H"], [PR("fc", "Crossover freq", 60, 5000, 10, 150, " Hz", null, [60, 80, 100, 150, 200, 300, 500, 1000, 2000, 3000, 5000]), ORD], "mono in: LOW + HIGH out, 12V");
C.xover3 = xo("Active crossover 3-way", "X3", ["L", "M", "H"], [PR("fcL", "Low / mid freq", 60, 500, 10, 150, " Hz", null, [60, 80, 100, 150, 200, 300, 500]), PR("fcH", "Mid / high freq", 1000, 5000, 10, 3000, " Hz", null, [1000, 2000, 3000, 5000]), ORD], "mono in: LOW + MID + HIGH out, 12V");
const amp = o => {
const w = o.w, h = o.h || 120, tm = [], chs = [];
o.ins.forEach((nm, i) => tm.push(T("i" + (i + 1), 0, 30 + i * 20, i % 2 ? "rcaR" : "rcaL", nm, "r", "Low-level input " + nm)));
tm.push(T("rem", w * 0.3, 0, "rem", "REM", "u", "Remote turn-on (from head REM)", { col: { c: B, s: Wh } }),
T("vcc", w * 0.55, 0, "pwr", "12V", "u", "12V+ (thick wire, fuse at battery)"), T("gnd", w * 0.8, 0, "gnd", "GND", "u", "Ground (short, bare metal)"));
for (let k = 1; k <= o.n; k++) {
const bx = 20 + (k - 1) * (w - 40) / o.n;
tm.push(T("p" + k, bx, h, "spk", "+", "d", "Output " + k + " +"), T("m" + k, bx + 20, h, "spk", "\u2212", "d", "Output " + k + " \u2212"));
chs.push({ ins: o.map ? o.map[k - 1] : ["i" + k], p: "p" + k, m: "m" + k });
}
const props = [PR("gain", "Gain (sensitivity)", 0.2, 2, 0.1, 1, "\u00d7")];
if (o.lpf) props.push(PR("fc", "Low-pass", 40, 400, 10, 100, " Hz"), PR("sub", "Subsonic filter", 0, 40, 10, 0, "", v => v ? v + " Hz" : "Off", [0, 20, 30, 40]));
else props.push(PR("xo", "Crossover", 0, 2, 1, 0, "", ["Full range", "High-pass", "Low-pass"], [0, 1, 2]), PR("xf", "Crossover freq", 40, 400, 10, 80, " Hz"));
props.push(PR("bass", "Bass boost", 0, 12, 1, 0, " dB"), PR("rca", "RCA cable", 0, 1, 1, 0, "", ["Basic", "Shielded"], [0, 1]),
PR("lift", "Ground lift", 0, 1, 1, 0, "", ["Off", "On"], [0, 1]), PR("gate", "Noise gate", 0, 1, 1, 0, "", ["Off", "On"], [0, 1]));
return { kind: "amp", cat: "Amps", name: o.name, ab: "AMP", w, h, tm, chs, rms: o.rms, zmin: o.zmin, swing: o.swing, lpf: !!o.lpf, props,
spec: o.n + "\u00d7" + o.rms + "W RMS \u00b7 \u2265" + o.zmin + "\u03a9" };
};
C.amp2 = amp({ name: "Amp 2ch 2x150W", w: 220, n: 2, ins: ["L", "R"], rms: 150, zmin: 2, swing: 1.8 });
C.amp4 = amp({ name: "Amp 4ch 4x75W", w: 260, h: 130, n: 4, ins: ["L1", "R1", "L2", "R2"], rms: 75, zmin: 2, swing: 1.4 });
C.amp1 = amp({ name: "Sub amp mono 500W + LPF", w: 200, n: 1, ins: ["L", "R"], map: [["i1", "i2"]], rms: 500, zmin: 1, swing: 2, lpf: true });
C.filter = { kind: "filt", cat: "Amps", name: "Stereo crossover filter (LPF/HPF)", ab: "LPF", w: 140, h: 80, spec: "2ch, 12V",
props: [PR("mode", "Mode", 0, 1, 1, 0, "", ["Low-pass", "High-pass"], [0, 1]), PR("fc", "Cutoff", 40, 400, 10, 150, " Hz"), PR("slope", "Slope", 6, 24, 6, 12, " dB/oct", null, [6, 12, 24])],
tm: [T("inL", 0, 30, "rcaL", "L", "r", "Filter input L"), T("inR", 0, 50, "rcaR", "R", "r", "Filter input R"),
T("outL", 140, 30, "rcaL", "L", "l", "Filter output L"), T("outR", 140, 50, "rcaR", "R", "l", "Filter output R"),
T("pwr", 50, 0, "pwr", "12V", "u", "Filter 12V+ (fused)"), T("gnd", 90, 0, "gnd", "GND", "u", "Filter ground")] };
C.eq = { kind: "filt", eq: true, cat: "Amps", name: "Equalizer 3-band (line level)", ab: "EQ", w: 140, h: 80, spec: "2ch, 12V, \u00b112 dB; inputs add up",
props: [PR("bass", "Bass 100 Hz", -12, 12, 1, 0, " dB"), PR("mid", "Mid 1 kHz", -12, 12, 1, 0, " dB"), PR("treb", "Treble 5 kHz", -12, 12, 1, 0, " dB")],
tm: C.filter.tm.map(t => Object.assign({}, t)) };
C.linedrv = { kind: "filt", ld: true, cat: "Amps", name: "Line driver (2ch, line level)", ab: "LD", w: 140, h: 80, spec: "2ch, 12V, boosts the RCA level",
props: [PR("gain", "Gain", 0, 12, 1, 12, " dB")],
tm: C.filter.tm.map(t => Object.assign({}, t)) };
const spk = (name, ab, z, p, sz, kd) => ({ kind: "spk", cat: "Speakers", name, ab, w: 80, h: 60, z, p, sz, kd: KD[kd], props: [], spec: z + "\u03a9 \u00b7 " + p + "W RMS",
tm: [T("p", 0, 20, "spk", "+", "r", name + " +"), T("m", 0, 40, "spk", "\u2212", "r", name + " \u2212")] });
C.tw = spk("Tweeter 4\u03a9 20W", "TW", 4, 20, 0.7, "tw");
C.wf65 = spk("Woofer 6.5in 4\u03a9 50W", "WF", 4, 50, 1, "wf");
C.wf8 = spk("Woofer 6.5in 8\u03a9 50W", "WF", 8, 50, 1, "wf");
C.coax = spk("Coaxial 6x9 4\u03a9 40W", "CX", 4, 40, 1, "cx");
C.sub4 = spk("Subwoofer 12in 4\u03a9 150W", "SUB", 4, 150, 1.15, "sw");
C.sub2 = spk("Subwoofer 12in 2\u03a9 300W", "SUB", 2, 300, 1.15, "sw");
C.dmm = { kind: "dmm", cat: "Tools", name: "Multimeter", ab: "DMM", w: 130, h: 100, spec: "",
props: [PR("mode", "Mode", 0, 3, 1, 0, "", ["DC V", "AC V", "Continuity", "Ohms"], [0, 1, 2, 3])],
tm: [T("red", 40, 100, "pwr", "", "", "Multimeter red probe", { col: { c: R } }), T("black", 90, 100, "gnd", "", "", "Multimeter black probe", { col: { c: Bk } })] };
C.scope = { kind: "scope", cat: "Tools", name: "Oscilloscope 2ch", ab: "SCP", w: 160, h: 90, spec: "reading shown in Meters tab",
props: [
PR("ch1", "CH1", 0, 1, 1, 1, "", ONOFF, [0, 1]),
PR("ch2", "CH2", 0, 1, 1, 1, "", ONOFF, [0, 1]),
PR("v1", "CH1 V/div", 0.5, 20, 0.5, 5, " V", null, [0.5, 1, 2, 5, 10, 20]),
PR("v2", "CH2 V/div", 0.5, 20, 0.5, 5, " V", null, [0.5, 1, 2, 5, 10, 20]),
PR("tb", "Time/div", 0.5, 20, 0.5, 2, " ms", null, [0.5, 1, 2, 5, 10, 20]),
PR("trig", "Mode", 0, 3, 1, 0, "", ["Auto", "Normal", "Single", "Roll"], [0, 1, 2, 3]),
PR("edge", "Edge", 0, 1, 1, 0, "", ["Rising", "Falling"], [0, 1]),
PR("lvl", "Trig level", -10, 10, 0.5, 0, " V"),
PR("src", "Trig src", 0, 1, 1, 0, "", ["CH1", "CH2"], [0, 1]),
PR("cp1", "CH1 coupling", 0, 1, 1, 0, "", ["DC", "AC"], [0, 1]),
PR("cp2", "CH2 coupling", 0, 1, 1, 0, "", ["DC", "AC"], [0, 1])
],
tm: [T("c1", 30, 90, "rcaL", "CH1", "u", "Scope channel 1 probe", { col: { c: "#d8d800" } }), T("c2", 80, 90, "rcaL", "CH2", "u", "Scope channel 2 probe", { col: { c: "#00b8b8" } }), T("gnd", 130, 90, "gnd", "GND", "u", "Scope ground clip")] };
C.gen = { kind: "gen", cat: "Tools", name: "Tone generator", ab: "GEN", w: 120, h: 80, spec: "",
props: [PR("on", "Output", 0, 1, 1, 1, "", ONOFF, [0, 1]), PR("band", "Frequency", 0, 2, 1, 1, "", ["100 Hz", "1 kHz", "5 kHz"], [0, 1, 2]), PR("amp", "Level", 0.1, 5, 0.1, 1, " V")],
tm: [T("outL", 120, 30, "rcaL", "L", "l", "Generator output L"), T("outR", 120, 50, "rcaR", "R", "l", "Generator output R")] };
C.probe = { kind: "probe", cat: "Tools", name: "Voltage probe (1 contact)", ab: "PRB", w: 80, h: 50, props: [], spec: "reads voltage vs battery \u2212",
tm: [T("t", 40, 50, "pwr", "", "", "Probe tip: shows the voltage at this point (vs battery \u2212)", { col: { c: R } })] };
C.ctest = { kind: "ctest", cat: "Tools", name: "Cable tester", ab: "CT", w: 80, h: 50, props: [], spec: "OK / OPEN / SHORT",
tm: [T("a", 0, 30, "ter", "", "", "Tester lead A"), T("b", 80, 30, "ter", "", "", "Tester lead B")] };
for (const id in C) { const d = C[id]; d.tm.forEach(t => { t.ex = t.y === 0 ? 3 : t.y === d.h ? 1 : t.x === 0 ? 2 : t.x === d.w ? 0 : -1; }); }
this._C = C;
return C;
},
// ================================================================ PRESETS
_preset(n) {
const p = [], w = [];
const A = (id, t, x, y, pr) => p.push({ id, t, x, y, pr });
const W = (a, b) => w.push({ a, b, r: null });
if (n === 1) {
A("bat", "bat", 190, 420); A("g1", "gnd", 330, 470); A("f1", "fuse", 290, 330, { amps: 10 }); A("f2", "fuse", 290, 390, { amps: 5 });
A("sw", "sw", 430, 330); A("hu", "head_basic", 430, 60);
A("wfl", "wf65", 800, 40); A("wfr", "wf65", 800, 110); A("twl", "tw", 800, 180); A("twr", "tw", 800, 250);
A("c1", "cap", 690, 230); A("c2", "cap", 690, 290);
[["bat.pos", "f1.a"], ["f1.b", "sw.a"], ["sw.b", "hu.acc"], ["bat.pos", "f2.a"], ["f2.b", "hu.mem"], ["hu.gnd", "g1.g"], ["bat.neg", "g1.g"],
["hu.fl.p", "wfl.p"], ["hu.fl.m", "wfl.m"], ["hu.fr.p", "wfr.p"], ["hu.fr.m", "wfr.m"],
["hu.rl.p", "c1.a"], ["c1.b", "twl.p"], ["hu.rl.m", "twl.m"], ["hu.rr.p", "c2.a"], ["c2.b", "twr.p"], ["hu.rr.m", "twr.m"]].forEach(q => W(q[0], q[1]));
} else if (n === 4) {
A("bat1", "bat", 190, 320, { v: 12 }); A("bat2", "bat", 190, 200, { v: 12 }); A("g1", "gnd", 330, 440);
A("dmm", "dmm", 330, 200); A("f1", "fuse", 330, 360, { amps: 10 });
A("gen", "gen", 520, 260); A("eq1", "eq", 700, 200); A("eq2", "eq", 700, 330); A("scp", "scope", 900, 260);
[["bat1.pos", "bat2.neg"], ["bat1.neg", "g1.g"], ["dmm.red", "bat2.pos"], ["dmm.black", "bat1.neg"],
["bat1.pos", "f1.a"], ["f1.b", "eq1.pwr"], ["f1.b", "eq2.pwr"], ["eq1.gnd", "g1.g"], ["eq2.gnd", "g1.g"],
["gen.outL", "eq1.inL"], ["gen.outR", "eq1.inR"], ["gen.outL", "eq2.inL"], ["gen.outR", "eq2.inR"],
["eq1.outL", "scp.c1"], ["eq2.outL", "scp.c2"], ["scp.gnd", "g1.g"]].forEach(q => W(q[0], q[1]));
} else if (n >= 2) {
A("bat", "bat", 190, 420); A("g1", "gnd", 700, 160); A("g2", "gnd", 800, 340, { surf: n === 3 ? 1 : 0, cab: n === 3 ? 2 : 0 });
A("f1", "fuse", 290, 330, { amps: 10 }); A("f2", "fuse", 290, 380, { amps: 5 }); A("f3", "fuse", 290, 430, { amps: n === 3 ? 2 : 30 });
A("sw", "sw", 430, 330); A("hu", "head_mid", 330, 60); A("hn", "iso_harness", 300, 235); A("an", "ant", 610, 60);
A("ap", "amp1", 580, 330);
A("wfl", "wf65", 800, 30); A("wfr", n === 3 ? "tw" : "wf65", 800, 100); A("cxl", "coax", 800, 170); A("cxr", "coax", 800, 240); A("sub", "sub4", 810, 400);
[["bat.pos", "f1.a"], ["f1.b", "sw.a"], ["sw.b", "hn.A7"], ["bat.pos", "f2.a"], ["f2.b", "hn.A4"], ["bat.pos", "f3.a"], ["f3.b", "ap.vcc"],
["hn.A8", "g1.g"], ["hn.A5", "ap.rem"], ["hn.A5", "an.pwr"], ["an.gnd", "g1.g"], ["ap.gnd", n === 3 ? "g2.g" : "g1.g"], ["bat.neg", "g2.g"],
["hu.mA", "hn.mA"], ["hu.mB", "hn.mB"], ["hu.antin", "an.sig"],
["hn.B5", "wfl.p"], ["hn.B6", "wfl.m"], ["hn.B3", "wfr.p"], ["hn.B4", "wfr.m"], ["hn.B7", "cxl.p"], ["hn.B8", "cxl.m"], ["hn.B1", "cxr.p"], ["hn.B2", "cxr.m"],
["hu.preSL", "ap.i1"], ["hu.preSR", "ap.i2"], ["ap.p1", "sub.p"], ["ap.m1", "sub.m"]].filter(q => !(n === 3 && q[0] === "bat.neg")).forEach(q => W(q[0], q[1]));
}
return { p, w };
},
_lbl(S, d) { S.lc = S.lc || {}; S.lc[d.ab] = (S.lc[d.ab] || 0) + 1; return d.ab + S.lc[d.ab]; },
_mk(S, t, x, y, id, pr) {
const d = this._cat()[t], q = { id: id || (t + "_" + (++S.cnt)), t, x, y, pr: {}, lb: this._lbl(S, d) };
d.props.forEach(p => { q.pr[p.k] = p.v; });
if (pr) Object.assign(q.pr, pr);
return q;
},
_ssig(S) { return S.parts.map(p => p.t + p.x + "," + p.y + JSON.stringify(p.pr)).join(";") + "|" + S.wires.map(w => w.a + ">" + w.b).join(","); },
_load(S, n) {
const pr = this._preset(n);
S.lc = {}; S.cnt = 100;
S.parts = pr.p.map(o => this._mk(S, o.t, o.x, o.y, o.id, o.pr));
S.wires = pr.w;
S.fh = {}; S.fb = {}; S.sh = {}; S.sb = {};
S.pend = null; S.pts = []; S.sel = null; S.tool = null; S.dirty = true; S.nethl = null;
S.ver = (S.ver || 0) + 1;
S.rsig = null;
S.fitReq = true;
S.lsig = this._ssig(S); S.cfm = -1; S.cfmT = 0;
S.scFrozen = false; S.scSnap = null;
if (S._rtCache) S._rtCache.clear();
},
_pick(S, i) {
if (this._ssig(S) !== S.lsig && S.cfm !== i) { S.cfm = i; S.cfmT = 300; return; }
this._pushUndo(S);
S.ui.preset = i; S.lp = i; this._load(S, i);
this._log(S, "Loaded example: " + this._EX[i], "g");
},
_repair(S) { S.fh = {}; S.fb = {}; S.sh = {}; S.sb = {}; this._log(S, "Repair: fuses and speakers replaced", "g"); },
// ================================================================ UNDO / REDO / SAVE / LOG
_snapshot(S) {
return JSON.stringify({
parts: S.parts.map(p => ({ id: p.id, t: p.t, x: p.x, y: p.y, pr: p.pr, lb: p.lb })),
wires: S.wires.map(w => ({ a: w.a, b: w.b, r: w.r })),
cnt: S.cnt, lc: S.lc
});
},
_pushUndo(S) {
S.undo.push(this._snapshot(S));
if (S.undo.length > 100) S.undo.shift();
S.redo.length = 0;
},
_restore(S, json) {
const C = this._cat(), o = typeof json === "string" ? JSON.parse(json) : json;
const parts = [];
for (const q of (o.parts || [])) {
const d = C[q.t]; if (!d) continue;
const pr = Object.assign({}, q.pr || {});
d.props.forEach(p => { if (pr[p.k] === undefined) pr[p.k] = p.v; });
parts.push({ id: q.id, t: q.t, x: q.x, y: q.y, pr, lb: q.lb || this._lbl(S, d) });
}
const ids = new Set(parts.map(p => p.id));
const owner = s => s.slice(0, Math.max(0, s.indexOf(".")));
S.parts = parts;
S.wires = (o.wires || []).filter(w => ids.has(owner(w.a)) && ids.has(owner(w.b))).map(w => ({ a: w.a, b: w.b, r: w.r || null }));
S.cnt = o.cnt || S.cnt; S.lc = o.lc || S.lc;
S.pend = null; S.pts = []; S.nethl = null; S.drag = null;
if (!ids.has(S.sel)) S.sel = null;
S.dirty = true; this._bump(S);
if (S._rtCache) S._rtCache.clear();
},
_undoAct(S) {
if (!S.undo.length) { this._say(S, "Nothing to undo."); return; }
S.redo.push(this._snapshot(S));
this._restore(S, S.undo.pop());
},
_redoAct(S) {
if (!S.redo.length) { this._say(S, "Nothing to redo."); return; }
S.undo.push(this._snapshot(S));
this._restore(S, S.redo.pop());
},
_save(S) {
try {
const o = JSON.parse(this._snapshot(S));
o.ui = S.ui; o.ts = Date.now();
localStorage.setItem(this._SAVEKEY, JSON.stringify(o));
this._say(S, "Saved: " + S.parts.length + " parts, " + S.wires.length + " wires.");
} catch (e) { this._say(S, "Save failed: browser storage is not available here."); }
},
_loadSave(S) {
let raw = null;
try { raw = localStorage.getItem(this._SAVEKEY); } catch (e) { this._say(S, "Load failed: browser storage is not available here."); return; }
if (!raw) { this._say(S, "No saved circuit found."); return; }
try {
const o = JSON.parse(raw);
this._pushUndo(S);
this._restore(S, o);
if (o.ui) for (const k in S.ui) if (k !== "snd" && k !== "preset" && o.ui[k] !== undefined) S.ui[k] = o.ui[k];
S.fh = {}; S.fb = {}; S.sh = {}; S.sb = {};
S.lsig = this._ssig(S); S.fitReq = true; S.scFrozen = false; S.scSnap = null;
this._say(S, "Loaded saved circuit (" + S.parts.length + " parts).");
this._log(S, "Loaded saved circuit", "g");
} catch (e) { this._say(S, "Load failed: the save is damaged."); }
},
_png(S) {
try {
const a = document.createElement("a");
a.href = S.bound.toDataURL("image/png"); a.download = "car-audio-lab.png";
document.body.appendChild(a); a.click(); a.remove();
this._say(S, "PNG exported.");
} catch (e) { this._say(S, "PNG export failed."); }
},
_log(S, msg, kind) {
if (!S.log) return;
S.log.push({ t: S.tt || 0, msg, kind: kind || "" });
if (S.log.length > 200) S.log.shift();
},
_events(S) {
const N = S.net;
for (const st of N.heads.concat(N.amps)) {
const id = st.p.id, on = !!st.on, pv = S.onPrev[id];
if (pv !== undefined && pv !== on) this._log(S, st.p.lb + (on ? " turned ON" : " turned OFF"), on ? "g" : "y");
S.onPrev[id] = on;
}
},
// ================================================================ INIT / LAYOUT
init(P, S) {
S.ui = this._ui0();
S.parts = []; S.wires = []; S.lp = -1; S.cnt = 100; S.lc = {};
S.pend = null; S.pts = []; S.mx = -1e3; S.my = -1e3; S.sel = null; S.tool = null; S.tab = 0; S.drag = null; S.moved = false;
S.sig = ""; S.net = null; S.tl = null; S.tm = {}; S.ti = {}; S.dirty = true;
S.rt = []; S.rsig = null; S.hw = -1; S.fr = 0; S.btn = []; S.btnPrev = []; S.msg = ""; S.mt = 0;
S.fh = {}; S.fb = {}; S.sh = {}; S.sb = {}; S.fi = {};
S.pw = {}; S.zl = {}; S.prot = {}; S.clip = {}; S.spp = {}; S.sv = {}; S.sa = {}; S.ca = {}; S.nsig = {};
S.r1 = new Float32Array(this._SL); S.r2 = new Float32Array(this._SL); S.rtm = new Float64Array(this._SL); S.ri = 0; S.sc = { c1: 0, c2: 0 };
S.scCur1 = 0.25; S.scCur2 = 0.75; S.scDrag = 0; S.scRect = null; S.scFrozen = false; S.scSnap = null; S.scSig = "";
S.W = 900; S.H = 700; S.s = 1; S.ox = 0; S.oy = 0; S.rad = 0;
S.au = null; S.auErr = false; S.sndOn = false; S.lsnd = S.ui.snd;
S.nl = {}; S.xt = {}; S.psc = 0; S.pscr = null; S.gqk = ""; S.z = 1; S.vx = 0; S.vy = 0; S.ptab = 0; S.cat = 0; S.fitReq = true; S.port = null; S.pan = null; S.wx = -1e3; S.wy = -1e3; S.gq = {}; S.nz = {}; S.sg = {}; S.sn = {}; S.phw = 0;
S.help = false; S.cfm = -1; S.cfmT = 0; S.lsig = "";
S._A = {}; S._A2 = {}; S._ns = {}; S._nz = {}; S._mixA = [0, 0, 0]; S._mixA2 = [0, 0, 0];
S.ver = 0; S.rv = 0; S.rbb = []; S.rpend = 0; S.deg = {}; S.flg = {}; S.hwk = ""; S.hwa = -1;
S.undo = []; S.redo = []; S.log = []; S.tt = 0; S.paused = false; S.stepN = 0;
S.rly = {}; S.dio = {}; S.protPrev = {}; S.onPrev = {}; S.nethl = null; S.mm = null; S.dragU = false;
},
_cl(v, a, b) { return v < a ? a : v > b ? b : v; },
_w(S, x, y) { const r = this._L.ws; return [176 + (x - r.x) / S.z + S.vx, 28 + (y - r.y) / S.z + S.vy]; },
_clampView(S) {
const r = this._L.ws, vw = r.w / S.z, vh = r.h / S.z;
S.vx = this._cl(S.vx, -400, Math.max(-400, 1650 - vw + 80)); S.vy = this._cl(S.vy, -400, Math.max(-400, 1130 - vh + 80));
},
_zoom(S, f, cx, cy) {
const r = this._L.ws;
if (cx === undefined) { cx = r.x + r.w / 2; cy = r.y + r.h / 2; }
const w = this._w(S, cx, cy), z = this._cl(S.z * f, 0.25, 2.5);
S.vx = w[0] - 176 - (cx - r.x) / z; S.vy = w[1] - 28 - (cy - r.y) / z; S.z = z; this._clampView(S);
},
_fit(S) {
const r = this._L.ws;
if (!S.parts.length) { S.z = 1; S.vx = 0; S.vy = 0; return; }
const C = this._cat(); let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;
for (const p of S.parts) { const d = C[p.t]; x0 = Math.min(x0, p.x - 30); y0 = Math.min(y0, p.y - 40); x1 = Math.max(x1, p.x + d.w + 30); y1 = Math.max(y1, p.y + d.h + 60); }
const z = this._cl(Math.min(r.w / (x1 - x0), (r.h - 40) / (y1 - y0)), 0.25, 1.6);
S.z = z; S.vx = x0 - 176 - (r.w / z - (x1 - x0)) / 2; S.vy = y0 - 28 - ((r.h - 40) / z - (y1 - y0)) / 2; this._clampView(S);
},
_snap(v) { return Math.round(v / 10) * 10; },
_inWs(x, y) { const r = this._L.ws; return x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h; },
_lay(S) {
const C = this._cat(), tl = [], tm = {}, ix = {};
for (const p of S.parts) {
const d = C[p.t];
for (const t of d.tm) {
const o = { id: p.id + "." + t.n, x: p.x + t.x, y: p.y + t.y, d: t, p, k: t.k, lab: t.lab, pos: t.pos, tip: p.lb + ": " + t.tip, hid: !!t.h, ex: t.ex };
ix[o.id] = tl.length; tl.push(o); tm[o.id] = o;
}
}
S.tl = tl; S.tm = tm; S.ti = ix;
},
_tick(P, S) {
if (S.lp !== P.preset) { S.lp = P.preset; this._load(S, P.preset | 0); }
if (S.dirty || !S.tl) { this._lay(S); S.dirty = false; }
let fb = "", sb = "", bv = "";
for (const k in S.fb) if (S.fb[k]) fb += k + ",";
for (const k in S.sb) if (S.sb[k]) sb += k + ",";
for (const p of S.parts) if (p.t === "bat") bv += p.pr.v + ",";
const sig = S.ver + "|" + fb + "|" + sb + "|" + (P.ign >= 0.5 ? 1 : 0) + "|" + P.Vcc + "|" + bv;
if (sig !== S.sig || !S.net) { S.sig = sig; S.net = this._solve(P, S); this._afterSolve(S); }
},
_afterSolve(S) {
const N = S.net, deg = {}, W = S.wires;
for (const w of W) { deg[w.a] = 1; deg[w.b] = 1; }
S.deg = deg;
N.wcol = new Array(W.length); N.ncb = false; N.badWire = null;
const au = k => k === "rcaL" || k === "rcaR" || k === "spk" || k === "rf", pw = k => k === "pwr" || k === "gnd" || k === "rem";
for (let i = 0; i < W.length; i++) {
const a = S.tm[W[i].a], b = S.tm[W[i].b];
if (!a || !b) continue;
if ((au(a.k) && pw(b.k)) || (au(b.k) && pw(a.k))) { N.badWire = { a, b }; break; }
}
},
// ================================================================ SOLVER
// Обгортка: реле та діоди залежать від потенціалів, тому розв'язуємо кілька разів,
// поки стан реле/діодів не стабілізується.
_solve(P, S) {
const C = this._cat();
const hasR = S.parts.some(p => C[p.t].kind === "relay"), hasD = S.parts.some(p => C[p.t].kind === "diode");
if (!hasR && !hasD) { S.rly = {}; S.dio = {}; return this._solveR(P, S, {}, {}); }
const prev = S.rly || {};
let rl = {}, dl = {}, N = null, settled = false;
for (const k in prev) rl[k] = prev[k];
for (let it = 0; it < 3 && !settled; it++) {
dl = hasD ? this._solveR(P, S, rl, {}).dio : {};
N = this._solveR(P, S, rl, dl);
const nr = {}; settled = true;
for (const p of S.parts) if (C[p.t].kind === "relay") { nr[p.id] = !!N.rcl[p.id]; if (nr[p.id] !== !!rl[p.id]) settled = false; }
rl = nr;
}
if (!settled) N = this._solveR(P, S, rl, dl);
for (const p of S.parts) if (C[p.t].kind === "relay" && prev[p.id] !== undefined && !!prev[p.id] !== !!rl[p.id]) this._log(S, p.lb + (rl[p.id] ? " clicked: contacts CLOSED" : " released: contacts OPEN"), "y");
S.rly = rl; S.dio = dl;
return N;
},
_solveR(P, S, rl, dl) {
const C = this._cat(), tl = S.tl, ix = S.ti, n = tl.length, parts = S.parts;
const mk = () => { const p = new Array(n); for (let i = 0; i < n; i++) p[i] = i; return p; };
const dcp = mk(), aup = mk();
const fd = (p, i) => { while (p[i] !== i) { p[i] = p[p[i]]; i = p[i]; } return i; };
const un = (p, a, b) => { if (ix[a] === undefined || ix[b] === undefined) return; a = fd(p, ix[a]); b = fd(p, ix[b]); if (a !== b) p[a] = b; };
const both = (a, b) => { un(dcp, a, b); un(aup, a, b); };
for (const w of S.wires) {
const ta = S.tm[w.a], tb = S.tm[w.b];
if (!ta || !tb) continue;
if (ta.d.mate && tb.d.mate) for (let i = 1; i <= ta.d.mate.n; i++) both(ta.p.id + "." + ta.d.mate.pre + i, tb.p.id + "." + tb.d.mate.pre + i);
both(w.a, w.b);
}
const of = k => parts.filter(p => C[p.t].kind === k);
for (const p of parts) { const d = C[p.t]; if (d.int) for (const q of d.int) both(p.id + "." + q[0], p.id + "." + q[1]); }
for (const p of parts) {
const k = C[p.t].kind;
if (k === "relay" && rl[p.id]) un(dcp, p.id + ".com", p.id + ".no");
else if (k === "diode" && dl[p.id]) un(dcp, p.id + ".a", p.id + ".k");
}
const bats = of("bat"), bat = bats[0];
if (P.ign >= 0.5) of("sw").forEach(p => un(dcp, p.id + ".a", p.id + ".b"));
if (bat) of("gnd").forEach(p => un(dcp, p.id + ".g", bat.id + ".neg"));
const nd = id => ix[id] === undefined ? -2 : fd(dcp, ix[id]);
const na = id => ix[id] === undefined ? -2 : fd(aup, ix[id]);
const bvOf = p => p.pr.v > 0 ? p.pr.v : P.Vcc;
const bpos = bats.map(b => nd(b.id + ".pos")), bneg = bats.map(b => nd(b.id + ".neg"));
const hot = bat ? bpos[0] : -1, gnd = bat ? bneg[0] : -3;
const fz = of("fuse").map(p => ({ id: p.id, p, a: nd(p.id + ".a"), b: nd(p.id + ".b"), ok: !S.fb[p.id] }));
const energize = roots => {
const en = new Set(roots.filter(x => x >= 0)), par = new Map();
let ch = true;
while (ch) {
ch = false;
for (const f of fz) {
if (!f.ok) continue;
if (en.has(f.a) && !en.has(f.b)) { en.add(f.b); par.set(f.b, { id: f.id, from: f.a }); ch = true; }
else if (en.has(f.b) && !en.has(f.a)) { en.add(f.a); par.set(f.a, { id: f.id, from: f.b }); ch = true; }
}
}
return { en, par };
};
const potentials = extra => {
const adj = new Map(), add = (a, b, v) => {
if (a < 0 || b < 0) return;
if (!adj.has(a)) adj.set(a, []); if (!adj.has(b)) adj.set(b, []);
adj.get(a).push([b, v]); adj.get(b).push([a, -v]);
};
bats.forEach((b, i) => add(bneg[i], bpos[i], bvOf(b)));
for (const f of fz) if (f.ok) add(f.a, f.b, 0);
for (const e of extra) add(e[0], e[1], e[2]);
const pot = new Map(); let conflict = false, cid = 0;
const seeds = bat ? [bneg[0]].concat(bneg) : [];
for (const s of seeds) {
if (s < 0 || pot.has(s)) continue;
const c = cid++; pot.set(s, { v: 0, c }); const q = [s];
while (q.length) {
const u = q.pop(), pu = pot.get(u);
for (const e of (adj.get(u) || [])) {
const v = pu.v + e[1], pw = pot.get(e[0]);
if (!pw) { pot.set(e[0], { v, c }); q.push(e[0]); } else if (Math.abs(pw.v - v) > 0.05) conflict = true;
}
}
}
return { pot, conflict };
};
const P1 = potentials([]);
const inRef = (PP, r) => { const o = PP.pot.get(r); return o && o.c === 0 ? o : null; };
const vref = (PP, r) => { const o = inRef(PP, r); return o ? o.v : 0; };
const roots1 = [];
bpos.forEach(x => { if (x >= 0 && inRef(P1, x) && roots1.indexOf(x) < 0) roots1.push(x); });
const E1 = energize(roots1);
const direct = !!bat && (bats.some((b, i) => bpos[i] === bneg[i]) || bpos.indexOf(gnd) >= 0);
const short = !!bat && (direct || P1.conflict || E1.en.has(gnd));
const pok = (E, PP, id) => !!bat && !short && E.en.has(nd(id)) && vref(PP, nd(id)) > 1;
const gok = id => gnd !== -3 && nd(id) === gnd;
const by = {}, heads = [], amps = [], filts = [], gens = [], ants = of("ant"), loads = [], bigcaps = of("bigcap");
for (const p of of("head")) {
const D = C[p.t], t = k => p.id + "." + D.hp[k];
const hp = { mem: pok(E1, P1, t("mem")), acc: pok(E1, P1, t("acc")), gnd: gok(t("gnd")) };
const vm = vref(P1, nd(t("mem"))), va = vref(P1, nd(t("acc"))), vs = Math.min(vm, va), vhi = Math.max(vm, va);
const pw = hp.mem && hp.acc && hp.gnd, vbad = pw ? (vs < 8 ? 1 : vhi > 18 ? 2 : 0) : 0;
const H = { p, d: D, hp, vs, vhi, vbad, on: pw && !vbad, t };
heads.push(H); by[p.id] = H;
}
const roots = roots1.slice(), extra = [];
for (const H of heads) if (H.on) [nd(H.t("rem")), nd(H.t("ant"))].forEach(x => { if (x >= 0 && x !== gnd) { roots.push(x); extra.push([gnd, x, H.vs]); } });
const P2 = potentials(extra);
const E = energize(roots);
const pk = id => pok(E, P2, id);
const vd = (r1, r2) => {
const a = P2.pot.get(r1), b = P2.pot.get(r2);
if (!a || !b || a.c !== b.c) return 0;
if (a.c === 0 && short) return 0;
return a.v - b.v;
};
// стан реле (котушка >= 9 V) та діодів (анод вище катода, коли діоди розімкнені)
const rcl = {}, dio = {};
for (const p of of("relay")) rcl[p.id] = Math.abs(vd(nd(p.id + ".cp"), nd(p.id + ".cm"))) >= 9;
for (const p of of("diode")) {
const pa = P2.pot.get(nd(p.id + ".a")), pc = P2.pot.get(nd(p.id + ".k"));
dio[p.id] = !short && !!pa && pa.c === 0 && pa.v > 1 && (!pc || (pc.c === 0 && pa.v > pc.v + 0.05));
}
for (const H of heads) {
H.ant = ants.find(a => na(H.p.id + ".antin") === na(a.id + ".sig")) || null;
H.antPow = !!H.ant && pk(H.ant.id + ".pwr"); H.antGnd = !!H.ant && gok(H.ant.id + ".gnd");
H.antOk = H.on && !!H.ant && H.antPow && H.antGnd;
loads.push({ t: H.t("mem"), key: H.p.id + ":m", type: "hm", p: H.p }, { t: H.t("acc"), key: H.p.id + ":a", type: "ha", p: H.p });
}
for (const p of of("amp")) {
const ap = { vcc: pk(p.id + ".vcc"), rem: pk(p.id + ".rem"), gnd: gok(p.id + ".gnd") };
const vs = vref(P2, nd(p.id + ".vcc")), pw = ap.vcc && ap.rem && ap.gnd, vbad = pw ? (vs < 8 ? 1 : vs > 18 ? 2 : 0) : 0;
const A = { p, d: C[p.t], ap, vs, vbad, on: pw && !vbad, fromRem: false };
for (const H of heads) { const x = nd(p.id + ".vcc"); if (x === nd(H.t("rem")) && roots1.indexOf(x) < 0) A.fromRem = true; }
amps.push(A); by[p.id] = A;
loads.push({ t: p.id + ".vcc", key: p.id + ":v", type: "av", p });
}
for (const p of of("filt")) {
const iso = !!C[p.t].iso;
const fp = iso ? { pwr: true, gnd: true } : { pwr: pk(p.id + ".pwr"), gnd: gok(p.id + ".gnd") };
const vs = iso ? 12 : vref(P2, nd(p.id + ".pwr")), pw = fp.pwr && fp.gnd, vbad = (!iso && pw) ? (vs < 8 ? 1 : vs > 18 ? 2 : 0) : 0;
const F = { p, fp, vs, vbad, on: pw && !vbad };
filts.push(F); by[p.id] = F;
if (!iso) loads.push({ t: p.id + ".pwr", key: p.id + ":f", type: "fl", p });
}
for (const p of of("gen")) { const g = { p }; gens.push(g); by[p.id] = g; }
const fl = {}, sf = {}, unfused = [];
const fzi = {}; fz.forEach(f => { fzi[f.id] = f; });
const cdb = c => c.pr.F >= 1 ? 14 : c.pr.F >= 0.5 ? 10 : 6;
for (const L of loads) {
let x = nd(L.t); L.nfdb = 0; L.fuse = false;
if (!E.en.has(x)) continue;
const x0 = x;
for (const cp of bigcaps) if (nd(cp.id + ".pos") === x0 && gok(cp.id + ".neg")) L.nfdb = Math.max(L.nfdb, cdb(cp));
while (E.par.has(x)) {
const q = E.par.get(x), f = fzi[q.id];
if (C[f.p.t].nf) L.nfdb = Math.max(L.nfdb, f.p.pr.db); else L.fuse = true;
(fl[q.id] = fl[q.id] || []).push(L.key); x = q.from;
}
if (!L.fuse && pk(L.t)) unfused.push(L);
const st = by[L.p.id]; if (st) st.nfdb = Math.max(st.nfdb || 0, L.nfdb);
}
if (!direct && E.en.has(gnd)) { let x = gnd; while (E.par.has(x)) { const q = E.par.get(x); sf[q.id] = true; x = q.from; } }
const conn = (a, b) => {
if (a === b) return true;
const seen = new Set([a]); let ch = true;
while (ch) {
ch = false;
for (const f of fz) {
if (!f.ok) continue;
if (seen.has(f.a) && !seen.has(f.b)) { seen.add(f.b); ch = true; }
else if (seen.has(f.b) && !seen.has(f.a)) { seen.add(f.a); ch = true; }
}
}
return seen.has(b);
};
const spk = of("spk").map(p => {
const a = nd(p.id + ".p"), b = nd(p.id + ".m");
return { p, X: na(p.id + ".p"), Y: na(p.id + ".m"), dc: Math.abs(vd(a, b)) > 1 };
});
const el = parts.filter(p => C[p.t].kind === "cap" || C[p.t].kind === "coil").map(p => ({ p, kind: C[p.t].kind, a: na(p.id + ".a"), b: na(p.id + ".b") }));
const reach = (f, t) => {
if (f === t) return [];
for (let i = 0; i < el.length; i++) {
const c = el[i];
for (const [a, b] of [[c.a, c.b], [c.b, c.a]]) {
if (a !== f) continue;
if (b === t) return [i];
for (let j = 0; j < el.length; j++) {
if (j === i) continue;
const d = el[j];
if ((d.a === b && d.b === t) || (d.b === b && d.a === t)) return [i, j];
}
}
}
return null;
};
const chs = [], keysOf = {}, keyRoots = [], spkNets = new Set();
const reg = (id, key) => { const r = na(id); if (r < 0) return; (keysOf[r] = keysOf[r] || []).push(key); keyRoots.push([r, key]); };
for (const H of heads) {
H.d.outs.forEach((o, i) => {
const c = { key: H.p.id + "/" + i, kind: "head", ci: i, h: H, own: H.p.id, p: na(H.p.id + "." + o.p), m: na(H.p.id + "." + o.m), min: H.d.min, sp: [] };
c.short = c.p === c.m; chs.push(c); spkNets.add(c.p);
});
H.d.pre.forEach((o, i) => reg(H.p.id + "." + o.t, "pre:" + H.p.id + ":" + i));
}
for (const g of gens) { reg(g.p.id + ".outL", "gen:" + g.p.id + ":L"); reg(g.p.id + ".outR", "gen:" + g.p.id + ":R"); }
for (const F of filts) {
const xs = C[F.p.t].xo;
if (xs) xs.forEach(s => reg(F.p.id + ".out" + s, "fo:" + F.p.id + ":" + s));
else { reg(F.p.id + ".outL", "fo:" + F.p.id + ":L"); reg(F.p.id + ".outR", "fo:" + F.p.id + ":R"); }
}
const inKeys = (id, self) => {
const ks = (keysOf[na(id)] || []).filter(k => !self || k.indexOf("fo:" + self + ":") !== 0);
return ks.length ? ks : null;
};
for (const F of filts) {
if (C[F.p.t].xo) F.kI = inKeys(F.p.id + ".in", F.p.id);
else { F.kL = inKeys(F.p.id + ".inL", F.p.id); F.kR = inKeys(F.p.id + ".inR", F.p.id); }
}
for (const A of amps) {
A.d.chs.forEach((o, i) => {
const c = { key: A.p.id + "/" + i, kind: "amp", am: A, own: A.p.id, p: na(A.p.id + "." + o.p), m: na(A.p.id + "." + o.m), min: A.d.zmin, sp: [] };
c.short = c.p === c.m;
c.ins = o.ins.map(t => inKeys(A.p.id + "." + t, null));
c.insFromSpk = o.ins.some(t => spkNets.has(na(A.p.id + "." + t)));
chs.push(c);
});
A.insSpk = chs.some(c => c.am === A && c.insFromSpk);
}
for (const s of spk) {
if (s.X === s.Y) continue;
for (const c of chs) {
if (c.short) continue;
let a = reach(s.X, c.p), b = reach(s.Y, c.m), pol = 1;
if (!a || !b) { a = reach(s.X, c.m); b = reach(s.Y, c.p); pol = -1; }
if (a && b) { c.sp.push({ s: s.p, X: s.X, el: a.concat(b), pol, h: [1, 1, 1] }); break; }
}
}
const origin = (ks, iso, d) => {
if (!ks || d > 4) return null;
for (const k of ks) {
if (k.indexOf("pre:") === 0) return { H: by[k.split(":")[1]], iso };
if (k.indexOf("fo:") === 0) {
const F = by[k.split(":")[1]]; if (!F) continue;
const ik = C[F.p.t].xo ? F.kI : (k.slice(-1) === "L" ? F.kL : F.kR);
const o = origin(ik, iso || !!C[F.p.t].iso, d + 1);
if (o) return o;
}
}
return null;
};
for (const A of amps) {
A.loop = false;
for (const c of chs) if (c.am === A) for (const k of c.ins) {
const o = origin(k, false, 0);
if (o && o.H && o.H.on && A.on && !o.iso && na(A.p.id + ".gnd") !== na(o.H.t("gnd"))) A.loop = true;
}
}
const vsys = Math.max(0, ...bpos.map(x => x >= 0 ? vref(P2, x) : 0));
return { nd, na, hot, gnd, E, short, direct, conflict: P1.conflict, bats, vd, vsys, heads, amps, filts, gens, ants, by, loads, fl, sf, unfused, conn, spk, el, chs, keyRoots, rcl, dio,
scope: of("scope")[0] || null, dmm: of("dmm")[0] || null };
},
// ================================================================ SIMULATION
step(dt, P, S, t) {
P = S.ui;
this._tick(P, S);
if (S.paused) { if (S.stepN > 0) S.stepN--; else return; }
S.tt = (S.tt || 0) + dt; t = S.tt;
this._events(S);
const N = S.net, F = this._F, PR = this._PR, TP = 6.2831853, C = this._cat();
const sn = [Math.sin(TP * F[0] * t), Math.sin(TP * F[1] * t), Math.sin(TP * F[2] * t)];
const A = S._A, A2 = S._A2, ns = S._ns, nz = S._nz;
for (const k in A) delete A[k]; for (const k in A2) delete A2[k]; for (const k in ns) delete ns[k]; for (const k in nz) delete nz[k];
const eng = P.eng >= 0.5;
S.phw = (S.phw || 0) + TP * (500 + 300 * Math.sin(t * 0.7)) * dt;
const swh = Math.sin(S.phw), shu = Math.sin(TP * 50 * t), db = v => Math.pow(10, v / 20);
const gqv = id => (S.gq && S.gq[id] !== undefined) ? S.gq[id] : 0.1;
const lpf = (f, fc) => 1 / Math.sqrt(1 + (f / fc) * (f / fc));
const hpf = (f, fc) => 1 / Math.sqrt(1 + (fc / f) * (fc / f));
const flt = (f, pr) => { const e = pr.slope === 24 ? 8 : pr.slope === 12 ? 4 : 2; return 1 / Math.sqrt(1 + Math.pow(pr.mode === 1 ? pr.fc / f : f / pr.fc, e)); };
const xog = (d, pr, side, f) => {
const e = pr.order === 24 ? 8 : pr.order === 12 ? 4 : 2;
const lp = fc => 1 / Math.sqrt(1 + Math.pow(f / fc, e)), hp = fc => 1 / Math.sqrt(1 + Math.pow(fc / f, e));
if (d.xo.length === 2) return side === "L" ? lp(pr.fc) : hp(pr.fc);
return side === "L" ? lp(pr.fcL) : side === "M" ? hp(pr.fcL) * lp(pr.fcH) : hp(pr.fcH);
};
const mixK = (ks, M, out) => { out[0] = 0; out[1] = 0; out[2] = 0; if (ks) for (const k of ks) { const x = M[k]; if (x) { out[0] += x[0]; out[1] += x[1]; out[2] += x[2]; } } return out; };
for (const s of N.spk) if (s.dc && !S.sb[s.p.id]) { S.sb[s.p.id] = true; this._log(S, s.p.lb + " burnt by DC voltage", "r"); }
S.rad = 0; let rs = false;
for (const H of N.heads) {
const pr = H.p.pr, D = H.d;
H.rad = !H.on ? 0 : ((D.radio || pr.src >= 0.5) ? (H.antOk ? 1 : 2) : 0);
if (H.on && !rs) { S.rad = H.rad; rs = true; }
const m = D.preV * 0.75 * pr.vol * (pr.plv || 1); H.eg = [db(pr.bass || 0), 1, db(pr.treb || 0)];
{
const bal = pr.bal || 0, fad = pr.fad || 0, ldv = pr.loud ? 1 - pr.vol : 0;
H.gc = [0, 1, 2, 3].map(i => (i % 2 === 0 ? (bal > 0 ? 1 - bal / 10 : 1) : (bal < 0 ? 1 + bal / 10 : 1)) * (i < 2 ? (fad < 0 ? 1 + fad / 10 : 1) : (fad > 0 ? 1 - fad / 10 : 1)));
H.lg = [1 + ldv * 0.8, 1, 1 + ldv * 0.4];
H.hp = [0, 1, 2].map(b => pr.hpf ? hpf(F[b], pr.hpf) : 1);
}
D.pre.forEach((o, i) => {
const a = [0, 0, 0];
if (H.on) for (let b = 0; b < 3; b++) a[b] = m * PR[b] * H.eg[b] * H.lg[b] * (o.sub ? lpf(F[b], pr.fc) * db(pr.sub || 0) : H.gc[i]);
A["pre:" + H.p.id + ":" + i] = a; A2["pre:" + H.p.id + ":" + i] = [0, 0, 0];
});
}
for (const g of N.gens) {
const a = [0, 0, 0];
if (g.p.pr.on) a[g.p.pr.band] = g.p.pr.amp;
A["gen:" + g.p.id + ":L"] = [0, 0, 0]; A["gen:" + g.p.id + ":R"] = [0, 0, 0]; A2["gen:" + g.p.id + ":L"] = a; A2["gen:" + g.p.id + ":R"] = a;
}
const passes = Math.max(1, Math.min(N.filts.length, 6));
const mxa = S._mixA, mxa2 = S._mixA2;
for (let pass = 0; pass < passes; pass++) for (const f of N.filts) {
const fdf = C[f.p.t];
if (fdf.xo) {
const x = mixK(f.kI, A, mxa), x2 = mixK(f.kI, A2, mxa2);
for (const side of fdf.xo) {
const a = [0, 0, 0], a2 = [0, 0, 0];
if (f.on) for (let b = 0; b < 3; b++) { const gf = xog(fdf, f.p.pr, side, F[b]); a[b] = x[b] * gf; a2[b] = x2[b] * gf; }
A["fo:" + f.p.id + ":" + side] = a; A2["fo:" + f.p.id + ":" + side] = a2;
}
continue;
}
for (const side of ["L", "R"]) {
const k = side === "L" ? f.kL : f.kR, a = [0, 0, 0], a2 = [0, 0, 0];
const x = mixK(k, A, mxa), x2 = mixK(k, A2, mxa2);
if (f.on) for (let b = 0; b < 3; b++) {
const gf = fdf.iso ? 1 : fdf.ld ? db(f.p.pr.gain) : fdf.eq ? db(b === 0 ? f.p.pr.bass : b === 1 ? f.p.pr.mid : f.p.pr.treb) : flt(F[b], f.p.pr);
a[b] = x[b] * gf; a2[b] = x2[b] * gf;
}
A["fo:" + f.p.id + ":" + side] = a; A2["fo:" + f.p.id + ":" + side] = a2;
}
}
for (const kr of N.keyRoots) {
const x = A[kr[1]], y = A2[kr[1]];
if (!x || !y) continue;
const o = ns[kr[0]] || (ns[kr[0]] = [0, 0, 0]);
for (let b = 0; b < 3; b++) o[b] += x[b] + y[b];
}
const pwOwn = {};
for (const c of N.chs) {
let a = [0, 0, 0], a2 = [0, 0, 0], on = false, Vc = c.kind === "head" ? c.h.vs : 0, nW = 0, nH = 0, nS = 0;
if (c.kind === "head") {
if (c.h.on) { on = true; for (let b = 0; b < 3; b++) a[b] = PR[b] * c.h.p.pr.vol * c.h.vs * c.h.eg[b] * c.h.gc[c.ci] * c.h.lg[b] * c.h.hp[b]; nW = eng ? 0.25 * gqv(c.own) * Math.pow(10, -(c.h.nfdb || 0) / 20) : 0; nS = 0.005; }
} else {
const am = c.am, Va = am.d.swing * am.vs; Vc = Va;
if (am.on) {
on = true;
for (const ks of c.ins) {
if (!ks) continue;
const x = mixK(ks, A, mxa), x2 = mixK(ks, A2, mxa2);
for (let b = 0; b < 3; b++) { a[b] += x[b] / c.ins.length * Va / 2 * am.p.pr.gain; a2[b] += x2[b] / c.ins.length * Va / 2 * am.p.pr.gain; }
}
const pr = am.p.pr;
for (let b = 0; b < 3; b++) {
let h = 1;
if (am.d.lpf) h *= lpf(F[b], pr.fc);
if (pr.xo === 1) h *= hpf(F[b], pr.xf); else if (pr.xo === 2) h *= lpf(F[b], pr.xf);
if (pr.sub) h *= hpf(F[b], pr.sub);
if (b === 0) h *= db(pr.bass || 0);
a[b] *= h; a2[b] *= h;
}
const sg = a[0] + a[1] + a[2] + a2[0] + a2[1] + a2[2];
const gate = (pr.gate && sg < 0.05) ? 0.05 : 1, shd = pr.rca ? 0.15 : 1, pwf = Math.pow(10, -(am.nfdb || 0) / 20);
nW = eng ? (1.5 * gqv(c.own) * pr.gain + 1.2 * ((S.xt && S.xt[c.own]) || 0) * pr.gain * shd) * pwf * gate : 0;
nH = (am.loop && !pr.lift) ? 0.25 * pr.gain * gate : 0;
nS = 0.04 * pr.gain * (pr.rca ? 0.5 : 1) * gate;
}
}
const G = [0, 0, 0];
for (const e of c.sp) {
if (S.sb[e.s.id]) continue;
const d = C[e.s.t];
let ce = 0, Ls = 0;
for (const i of e.el) { const q = N.el[i]; if (q.kind === "cap") ce += 1 / (q.p.pr.uF * 1e-6); else Ls += q.p.pr.mH * 1e-3; }
const fH = ce > 0 ? ce / (TP * d.z) : 0, fL = Ls > 0 ? d.z / (TP * Ls) : 0;
for (let b = 0; b < 3; b++) {
let h = 1;
if (fH > 0) h *= 1 / Math.sqrt(1 + (fH / F[b]) * (fH / F[b]));
if (fL > 0) h *= 1 / Math.sqrt(1 + (F[b] / fL) * (F[b] / fL));
e.h[b] = h; G[b] += h * h / d.z;
}
}
let num = 0, den = 0;
for (let b = 0; b < 3; b++) { num += PR[b] * PR[b]; den += PR[b] * PR[b] * G[b]; }
const Z = den > 0 ? num / den : Infinity;
const prot = on && (c.short || Z < c.min);
if (prot !== !!S.protPrev[c.key]) {
S.protPrev[c.key] = prot;
const nm = c.kind === "head" ? c.h.p.lb : c.am.p.lb;
this._log(S, nm + (prot ? " entered PROTECT (load too low / shorted)" : " left PROTECT"), prot ? "r" : "g");
}
S.prot[c.key] = prot; S.zl[c.key] = c.short ? 0 : Z;
if (prot) { a = [0, 0, 0]; a2 = [0, 0, 0]; nW = nH = nS = 0; }
S.nl[c.own] = nW + nH + nS;
let sm = a[0] + a[1] + a[2] + a2[0] + a2[1] + a2[2];
if (sm > Vc) { const kf = Vc / sm; a = a.map(v => v * kf); a2 = a2.map(v => v * kf); sm = Vc; S.clip[c.key] = 1500; }
const tt = [a[0] + a2[0], a[1] + a2[1], a[2] + a2[2]];
if (S.clip[c.key] > 0) S.clip[c.key]--;
S.ca[c.key] = tt; ns[c.p] = tt; nz[c.p] = [nW, nH];
let Pt = 0;
for (let b = 0; b < 3; b++) Pt += tt[b] * tt[b] / 2 * G[b];
S.pw[c.key] = (S.pw[c.key] || 0) + (Pt - (S.pw[c.key] || 0)) * 0.002;
pwOwn[c.own] = (pwOwn[c.own] || 0) + S.pw[c.key];
for (const e of c.sp) {
const sp = e.s, d = C[sp.t];
if (S.sb[sp.id]) continue;
let m = 0, pw = 0, v = 0;
const ac = [0, 0, 0], ag = [0, 0, 0], kr = d.kd.resp, q2 = Math.sqrt(2 * d.z) * 6;
for (let b = 0; b < 3; b++) {
const vb = tt[b] * e.h[b], pb = vb * vb / 2 / d.z;
pw += pb; m += pb / (d.p * d.kd.lim[b]); v += vb * sn[b];
ac[b] = kr[b] * Math.abs(a[b] * e.h[b]) / q2;
ag[b] = kr[b] * Math.abs(a2[b] * e.h[b]) / q2;
}
ns[e.X] = [tt[0] * e.h[0], tt[1] * e.h[1], tt[2] * e.h[2]]; nz[e.X] = [nW * e.h[1], nH * e.h[0]];
S.sn[sp.id] = [Math.max(kr[1], 0.4) * Math.abs(nW * e.h[1]) / q2, kr[0] * Math.abs(nH * e.h[0]) / q2, kr[2] * Math.abs(nS * e.h[2]) / q2];
S.sa[sp.id] = ac; S.sg[sp.id] = ag; S.sv[sp.id] = e.pol * v; sp._d = 1;
S.spp[sp.id] = (S.spp[sp.id] || 0) + (pw - (S.spp[sp.id] || 0)) * 0.002;
const h = S.sh[sp.id] || 0;
S.sh[sp.id] = m > 1.2 ? h + dt * (m - 1.2) * 30 : Math.max(0, h - dt * 2);
if (S.sh[sp.id] >= 1) { S.sb[sp.id] = true; this._log(S, sp.lb + " burnt: overloaded", "r"); }
}
}
const driven = {};
for (const c of N.chs) for (const e of c.sp) if (!S.sb[e.s.id]) driven[e.s.id] = 1;
for (const s of N.spk) {
const id = s.p.id;
if (!driven[id]) { S.sv[id] = 0; S.sa[id] = null; S.sg[id] = null; S.sn[id] = null; S.spp[id] = (S.spp[id] || 0) * 0.998; S.sh[id] = Math.max(0, (S.sh[id] || 0) - dt * 2); }
}
S.nsig = ns; S.nz = nz;
const cur = {};
for (const L of N.loads) {
const st = N.by[L.p.id];
if (L.type === "hm") cur[L.key] = st.hp.mem ? 0.1 : 0;
else if (L.type === "ha") cur[L.key] = st.on ? 0.7 + (pwOwn[L.p.id] || 0) / (st.vs * 0.4) : 0;
else if (L.type === "av") cur[L.key] = st.on ? 1.2 + (pwOwn[L.p.id] || 0) / (st.vs * 0.5) : 0;
else cur[L.key] = st.on ? 0.15 : 0;
}
for (const p of S.parts) {
if (C[p.t].kind !== "fuse") continue;
const id = p.id;
if (C[p.t].nf) { let I0 = 0; for (const k of (N.fl[id] || [])) I0 += cur[k] || 0; S.fi[id] = I0; continue; }
if (S.fb[id]) { S.fi[id] = 0; continue; }
let I = N.sf[id] ? 250 : 0;
for (const k of (N.fl[id] || [])) I += cur[k] || 0;
S.fi[id] = I;
const r = I / p.pr.amps;
if (r > 1) S.fh[id] = (S.fh[id] || 0) + dt * (r * r - 1) * 30;
else S.fh[id] = Math.max(0, (S.fh[id] || 0) - dt * 2);
if (S.fh[id] >= 1) { S.fb[id] = true; this._log(S, p.lb + " BLOWN (" + I.toFixed(1) + " A through " + p.pr.amps + " A)", "r"); }
}
if (N.scope) {
const sp = N.scope, id = sp.id, g0 = id + ".gnd", pr = sp.pr;
const acv = tid => {
const a = ns[N.na(tid)], z = nz[N.na(tid)];
return (a ? a[0] * sn[0] + a[1] * sn[1] + a[2] * sn[2] : 0) + (z ? z[0] * swh + z[1] * shu : 0);
};
const dcv = tid => N.vd(N.nd(tid), N.nd(g0));
const v1 = pr.ch1 ? dcv(id + ".c1") + acv(id + ".c1") - acv(g0) : 0, v2 = pr.ch2 ? dcv(id + ".c2") + acv(id + ".c2") - acv(g0) : 0;
if (!(pr.trig === 2 && S.scFrozen)) {
const L = S.r1.length, i = S.ri % L;
S.r1[i] = v1; S.r2[i] = v2; S.rtm[i] = t; S.ri++;
}
S.sc = { c1: v1, c2: v2 };
}
},
// ================================================================ GROUND / CROSSTALK
_gq(S) {
if (S.rpend > 0 && S.gqk !== "") return;
const N = S.net, C = this._cat(), tm = S.tm;
let pk = "";
for (const p of S.parts) { const q = p.pr; if (q.surf !== undefined || q.cab !== undefined || q.rca !== undefined) pk += (q.surf || 0) + "," + (q.cab || 0) + "," + (q.rca || 0) + ";"; }
const key = S.rv + "|" + S.sig + "|" + pk;
if (key === S.gqk) return;
S.gqk = key;
const plen = r => { let l = 0; for (let k = 0; k + 1 < r.length; k++) l += Math.abs(r[k + 1][0] - r[k][0]) + Math.abs(r[k + 1][1] - r[k][1]); return l; };
const adj = {}, add = (a, b, w) => { (adj[a] = adj[a] || []).push([b, w]); (adj[b] = adj[b] || []).push([a, w]); };
S.wires.forEach((w, i) => {
const a = tm[w.a], b = tm[w.b]; if (!a || !b) return;
const len = S.rt[i] ? plen(S.rt[i]) : Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
if (a.d.mate && b.d.mate) for (let j = 1; j <= a.d.mate.n; j++) add(a.p.id + "." + a.d.mate.pre + j, b.p.id + "." + b.d.mate.pre + j, len);
add(w.a, w.b, len);
});
for (const p of S.parts) { const d = C[p.t]; if (d.int) for (const q of d.int) add(p.id + "." + q[0], p.id + "." + q[1], 0); }
const RES = [0.02, 0.08, 0.25], SF = [0.02, 0.5, 1.5], targets = [], isT = new Set();
const bat = S.parts.find(p => C[p.t].kind === "bat");
if (bat) targets.push([bat.id + ".neg", 0.02, 0.02]);
for (const p of S.parts) if (C[p.t].kind === "gnd") targets.push([p.id + ".g", SF[p.pr.surf || 0], RES[p.pr.cab || 0]]);
targets.forEach(t => isT.add(t[0]));
const hpush = (h, x) => { let i = h.length; h.push(x); while (i > 0) { const p = (i - 1) >> 1; if (h[p][0] <= x[0]) break; h[i] = h[p]; i = p; } h[i] = x; };
const hpop = h => {
const top = h[0], last = h.pop();
if (h.length) { let i = 0; const n = h.length; for (;;) { let c = 2 * i + 1; if (c >= n) break; if (c + 1 < n && h[c + 1][0] < h[c][0]) c++; if (h[c][0] >= last[0]) break; h[i] = h[c]; i = c; } h[i] = last; }
return top;
};
const one = src => {
const dist = new Map([[src, 0]]), done = new Set(), hp = [[0, src]];
while (hp.length) {
const top = hpop(hp), du = top[0], u = top[1];
if (done.has(u)) continue;
done.add(u);
if (isT.has(u) && u !== src) continue;
const es = adj[u]; if (!es) continue;
for (const e of es) { const v = du + e[1], old = dist.get(e[0]); if (old === undefined || v < old) { dist.set(e[0], v); hpush(hp, [v, e[0]]); } }
}
let best = 2;
for (const t of targets) { const d = dist.get(t[0]); if (d !== undefined) best = Math.min(best, t[1] + d / 100 * t[2]); }
return best;
};
const o = {};
for (const H of N.heads) o[H.p.id] = one(H.t("gnd"));
for (const A of N.amps) o[A.p.id] = one(A.p.id + ".gnd");
for (const F of N.filts) if (!C[F.p.t].iso) o[F.p.id] = one(F.p.id + ".gnd");
S.gq = o;
const PW = { pwr: 1, gnd: 1, rem: 1, ter: 1 };
const sigW = [], pwrW = [];
S.wires.forEach((w, i) => {
const a = tm[w.a], b = tm[w.b];
if (!a || !b || !S.rt[i] || (a.d.mate && b.d.mate)) return;
if (/^rca/.test(a.k) && /^rca/.test(b.k)) sigW.push(i); else if (PW[a.k] && PW[b.k]) pwrW.push(i);
});
const walk = (r, fn) => {
for (let k = 0; k + 1 < r.length; k++) {
const a = r[k], b = r[k + 1], n = Math.max(Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1])) / 10, sx = Math.sign(b[0] - a[0]), sy = Math.sign(b[1] - a[1]);
for (let s = 0; s <= n; s++) fn(Math.round((a[0] + sx * s * 10) / 10), Math.round((a[1] + sy * s * 10) / 10));
}
};
const pg = new Uint8Array(65536);
for (const i of pwrW) walk(S.rt[i], (cx, cy) => { if (cx >= 0 && cx < 256 && cy >= 0 && cy < 256) pg[cx * 256 + cy] = 1; });
const prox = r => {
let tot = 0;
walk(r, (cx, cy) => {
let w = 0;
for (let dx = -2; dx <= 2 && w < 1; dx++) for (let dy = -2; dy <= 2; dy++) {
const x = cx + dx, y = cy + dy;
if (x < 0 || y < 0 || x > 255 || y > 255 || !pg[x * 256 + y]) continue;
w = Math.max(w, Math.max(Math.abs(dx), Math.abs(dy)) <= 1 ? 1 : 0.6);
if (w === 1) break;
}
tot += 10 * w;
});
return tot;
};
const xw = {}, xt = {};
for (const A of N.amps) {
const roots = new Set(A.d.chs.flatMap(c => c.ins).map(t => N.na(A.p.id + "." + t)));
let t = 0;
for (const i of sigW) if (roots.has(N.na(S.wires[i].a))) { if (xw[i] === undefined) xw[i] = prox(S.rt[i]); t += xw[i]; }
xt[A.p.id] = t / 100;
}
S.xt = xt;
},
// ================================================================ ROUTING
_routeAll(S) {
const tm = S.tm, W = S.wires, nW = W.length;
const out = new Array(nW), bbs = new Array(nW), todo = [], live = new Set();
const cache = S._rtCache || (S._rtCache = new Map());
const useA = nW <= this._ASTAR_MAX;
const sigOf = (w, a, b) => a.p.x + "," + a.p.y + "|" + b.p.x + "," + b.p.y + "|" + (w.r && w.r.length ? w.r.map(pt => pt[0] + ":" + pt[1]).join(";") : "");
for (let i = 0; i < nW; i++) {
const w = W[i], a = tm[w.a], b = tm[w.b];
if (!a || !b) { out[i] = null; bbs[i] = null; continue; }
const key = w.a + ">" + w.b; live.add(key);
const sig = sigOf(w, a, b); let e = cache.get(key);
if (!e || e.sig !== sig) {
let route, fin = true;
if (w.r && w.r.length) route = this._elbow([[a.x, a.y]].concat(w.r, [[b.x, b.y]]));
else { route = this._fastRoute(a, b, this._hash(key), S); fin = !useA; }
e = { sig, route, bb: this._bbox(route), fin };
cache.set(key, e);
if (!fin) todo.push(i);
} else if (!e.fin && useA) todo.push(i);
out[i] = e.route; bbs[i] = e.bb;
}
if (cache.size > live.size) for (const k of cache.keys()) if (!live.has(k)) cache.delete(k);
const pend = todo.length ? this._astarPass(S, todo, out, bbs, cache) : 0;
S.rt = out; S.rbb = bbs; S.rpend = pend; S.rv = (S.rv || 0) + 1;
S.rsig = pend ? null : "ok";
},
_astarPass(S, todo, out, bbs, cache) {
const G = 10, Cc = 183, R = 117, N = Cc * R, tm = S.tm, C = this._cat(), W = S.wires, NT = S.net;
const rg = this._rg || (this._rg = { base: new Float32Array(N), oH: new Int32Array(N), oV: new Int32Array(N), kH: new Int8Array(N), kV: new Int8Array(N) });
const base = rg.base, oH = rg.oH, oV = rg.oV, kH = rg.kH, kV = rg.kV;
base.fill(0); oH.fill(0); oV.fill(0); kH.fill(0); kV.fill(0);
const rb = (this._rb && this._rb.n === N) ? this._rb : (this._rb = { n: N, g: new Float32Array(N * 5), p: new Int32Array(N * 5), s: new Int32Array(N * 5), id: 0, hf: [], hs: [] });
const rect = (x0, y0, x1, y1, c) => {
for (let j = Math.max(0, Math.ceil(y0 / G)); j <= Math.min(R - 1, Math.floor(y1 / G)); j++)
for (let i = Math.max(0, Math.ceil(x0 / G)); i <= Math.min(Cc - 1, Math.floor(x1 / G)); i++) base[j * Cc + i] += c;
};
rect(0, 0, 170, 1170, 60); rect(0, 0, 1830, 24, 60);
for (const p of S.parts) { const d = C[p.t]; rect(p.x - 10, p.y - 10, p.x + d.w + 10, p.y + d.h + 10, 3); rect(p.x + 10, p.y + 10, p.x + d.w - 10, p.y + d.h - 10, 40); }
for (const t of S.tl) {
if (t.hid) continue;
const cx = Math.round(t.x / G), cy = Math.round(t.y / G);
if (cx < 0 || cy < 0 || cx >= Cc || cy >= R) continue;
base[cy * Cc + cx] += 40;
const pen = (dx, dy) => { const i = cx + dx, j = cy + dy; if (i >= 0 && i < Cc && j >= 0 && j < R) base[j * Cc + i] += 6; };
if (t.pos === "r") pen(1, 0); else if (t.pos === "l") pen(-1, 0);
else if (t.pos === "u") pen(0, -1); else if (t.pos === "d") pen(0, 1);
else if (t.pos === "v") for (let k = 1; k <= 4; k++) pen(0, -k);
}
const AU = { rcaL: 1, rcaR: 1, spk: 1, rf: 1, cap: 1 };
const clsOf = w => { const a = tm[w.a], b = tm[w.b]; if (a.d.mate && b.d.mate) return 3; return (AU[a.k] || AU[b.k]) ? 2 : 1; };
const rankOf = w => {
const a = tm[w.a], b = tm[w.b];
if (a.d.mate && b.d.mate) return 0;
if (/^rca|^rf$/.test(a.k) || /^rca|^rf$/.test(b.k)) return 3;
if (a.k === "spk" || b.k === "spk" || a.k === "cap" || b.k === "cap") return 2;
return 1;
};
const nidOf = w => NT.na(w.a) + 3;
const mark = (pts, nid, cls) => {
for (let i = 0; i + 1 < pts.length; i++) {
const a = pts[i], b = pts[i + 1], hz = a[1] === b[1];
const len = Math.round(Math.max(Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1])) / G);
const sx = Math.sign(b[0] - a[0]), sy = Math.sign(b[1] - a[1]);
for (let k = 0; k <= len; k++) {
const c = Math.round((a[1] + sy * k * G) / G) * Cc + Math.round((a[0] + sx * k * G) / G);
if (c >= 0 && c < N) { if (hz) { oH[c] = nid; kH[c] = cls; } else { oV[c] = nid; kV[c] = cls; } }
}
}
};
const skip = new Set(todo);
for (let i = 0; i < W.length; i++) if (out[i] && !skip.has(i)) mark(out[i], nidOf(W[i]), clsOf(W[i]));
const DX = [1, 0, -1, 0], DY = [0, 1, 0, -1];
const ast = (ta, tb, nid, cls) => {
const a = [ta.x, ta.y], b = [tb.x, tb.y];
const s = Math.round(a[1] / G) * Cc + Math.round(a[0] / G), t = Math.round(b[1] / G) * Cc + Math.round(b[0] / G);
const tx = t % Cc, ty = (t / Cc) | 0;
const sex = ta.ex === undefined ? -1 : ta.ex, tex = tb.ex === undefined ? -1 : tb.ex;
const gS = rb.g, par = rb.p, gen = rb.s, cur = ++rb.id;
const hf = rb.hf, hs = rb.hs; hf.length = 0; hs.length = 0;
const push = (f, st) => {
let i = hf.length; hf.push(f); hs.push(st);
while (i > 0) { const p = (i - 1) >> 1; if (hf[p] <= f) break; hf[i] = hf[p]; hs[i] = hs[p]; i = p; }
hf[i] = f; hs[i] = st;
};
const pop = () => {
const rs = hs[0], lf = hf.pop(), ls = hs.pop(), n = hf.length;
if (n > 0) {
let i = 0;
for (;;) {
let c = 2 * i + 1;
if (c >= n) break;
if (c + 1 < n && hf[c + 1] < hf[c]) c++;
if (hf[c] >= lf) break;
hf[i] = hf[c]; hs[i] = hs[c]; i = c;
}
hf[i] = lf; hs[i] = ls;
}
return rs;
};
const s0 = s * 5 + 4;
gen[s0] = cur; gS[s0] = 0; par[s0] = -1; push(0, s0);
let end = -1, exp = 0;
while (hf.length) {
if (++exp > 30000) break;
const st = pop(), cell = (st / 5) | 0, d = st % 5;
if (cell === t) { end = st; break; }
const gc = gS[st], cx = cell % Cc, cy = (cell / Cc) | 0;
for (let nd = 0; nd < 4; nd++) {
if (d < 4 && nd === ((d + 2) & 3)) continue;
const nx = cx + DX[nd], ny = cy + DY[nd];
if (nx < 0 || ny < 0 || nx >= Cc || ny >= R) continue;
const nc = ny * Cc + nx, hzm = !(nd & 1);
let c = 1;
if (nc !== t) c += base[nc];
const same = hzm ? oH[nc] : oV[nc], cross = hzm ? oV[nc] : oH[nc];
if (same) c += same === nid ? -0.5 : 14;
if (cross && cross !== nid) c += 2;
for (let sg = -1; sg <= 1; sg += 2) {
const mx = hzm ? nx : nx + sg, my = hzm ? ny + sg : ny;
if (mx < 0 || my < 0 || mx >= Cc || my >= R) continue;
const m = my * Cc + mx, o = hzm ? oH[m] : oV[m];
if (o && o !== nid) c += ((hzm ? kH[m] : kV[m]) === cls) ? 3 : 9;
}
if (d < 4 && d !== nd) c += 5;
if (d === 4 && sex >= 0 && nd !== sex) c += 8;
if (nc === t && tex >= 0 && nd !== ((tex + 2) & 3)) c += 8;
const ns = nc * 5 + nd, ng = gc + c;
if (gen[ns] !== cur || ng < gS[ns]) { gen[ns] = cur; gS[ns] = ng; par[ns] = st; push(ng + 0.5 * (Math.abs(nx - tx) + Math.abs(ny - ty)), ns); }
}
}
if (end < 0) {
const obs = this._obstacleRects(S);
return this._routeAround(a[0], a[1], b[0], b[1], this._hash(ta.id + ">" + tb.id), obs, S);
}
const cells = [];
for (let st = end; st >= 0; st = par[st]) cells.push((st / 5) | 0);
cells.reverse();
const xy = c => [(c % Cc) * G, ((c / Cc) | 0) * G];
const pts = [xy(cells[0])];
for (let i = 1; i < cells.length - 1; i++) if (cells[i + 1] - cells[i] !== cells[i] - cells[i - 1]) pts.push(xy(cells[i]));
pts.push(xy(cells[cells.length - 1]));
return pts;
};
const dist = i => { const w = W[i], a = tm[w.a], b = tm[w.b]; return Math.abs(a.x - b.x) + Math.abs(a.y - b.y); };
todo.sort((i, j) => (rankOf(W[i]) - rankOf(W[j])) || (dist(i) - dist(j)));
const now = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
const t0 = now();
for (let q = 0; q < todo.length; q++) {
if (q > 0 && now() - t0 > 10) return todo.length - q;
const i = todo[q], w = W[i], nid = nidOf(w), cls = clsOf(w);
const r = ast(tm[w.a], tm[w.b], nid, cls), e = cache.get(w.a + ">" + w.b);
if (e) { e.route = r; e.bb = this._bbox(r); e.fin = true; out[i] = r; bbs[i] = e.bb; }
mark(r, nid, cls);
}
return 0;
},
_wireAt(S, x, y) {
if (!S.rt || S.rt.length !== S.wires.length || typeof x !== "number") return -1;
const m = 6 / S.z, bb = S.rbb;
for (let i = S.rt.length - 1; i >= 0; i--) {
const p = S.rt[i];
if (!p) continue;
const b = bb && bb[i];
if (b && (x < b[0] - m || x > b[2] + m || y < b[1] - m || y > b[3] + m)) continue;
for (let k = 0; k + 1 < p.length; k++) if (this._segDist(x, y, p[k], p[k + 1]) < m) return i;
}
return -1;
},
_wcol(S, w, a, b, i) {
const N = S.net;
if (i !== undefined && N.wcol && N.wcol[i]) return N.wcol[i];
const r = this._wcol0(S, w, a, b);
if (i !== undefined && N.wcol) N.wcol[i] = r;
return r;
},
_wcol0(S, w, a, b) {
const N = S.net, ca = this._tcol(a), cb = this._tcol(b);
if (ca && ca.sp) return ca;
if (cb && cb.sp) return cb;
if (!N.ncb) {
N.ncb = true; N.nc = {};
for (const t of S.tl) {
if (t.hid) continue;
const c = this._tcol(t);
if (!c) continue;
const r = N.na(t.id), nc = N.nc[r] || (N.nc[r] = { sp: null, kind: null });
if (c.sp) { if (!nc.sp) nc.sp = c; } else if (!nc.kind) nc.kind = c;
}
}
const nc = N.nc[N.na(w.a)] || { sp: null, kind: null };
if (nc.sp) return nc.sp;
if (ca || cb) return ca || cb;
if (nc.kind) return nc.kind;
return { c: N.nd(w.a) === N.gnd ? "#161616" : "#e02424" };
},
_wstyle(P, S, w, i) {
const N = S.net, a = S.tm[w.a], b = S.tm[w.b], F = S.flg || {};
if (a.d.mate && b.d.mate) return { mate: true };
const au = k => k === "rcaL" || k === "rcaR" || k === "spk" || k === "rf";
const pw = k => k === "pwr" || k === "gnd" || k === "rem";
const A = au(a.k), B = au(b.k);
const err = (A && pw(b.k)) || (B && pw(a.k));
const lvl = k => (k === "rcaL" || k === "rcaR") ? 1 : k === "spk" ? 2 : 0;
const mismatch = lvl(a.k) && lvl(b.k) && lvl(a.k) !== lvl(b.k);
const sp = this._wcol(S, w, a, b, i), r = N.nd(w.a);
let live = false, short = false;
if (A || B) {
const x = S.nsig[N.na(w.a)];
live = !!x && (x[0] + x[1] + x[2]) > 0.05;
if (a.k === "rf" || b.k === "rf") live = S.rad === 1 && !!F.antOk;
} else if (N.short && (r === N.gnd || N.E.en.has(r))) short = true;
else if (r === N.gnd) live = !!(F.headOn || F.ampOn);
else live = N.E.en.has(r);
return { c: sp.c, s: sp.s || null, err, live, short, mismatch };
},
_drawWires(g, S, P, x0, y0, x1, y1) {
const W = S.wires, rt = S.rt, bb = S.rbb, vis = [], N = S.net;
for (let i = 0; i < W.length; i++) {
if (!rt[i]) continue;
const b = bb[i];
if (b && (b[2] < x0 || b[0] > x1 || b[3] < y0 || b[1] > y1)) continue;
vis.push(i);
}
// підсвічування ланцюга (net) вибраного дроту
if (S.nethl) {
const root = N.nd(S.nethl);
if (root >= 0) {
g.save(); g.lineJoin = "round"; g.lineCap = "round";
g.strokeStyle = "rgba(255,210,0,0.65)"; g.lineWidth = Math.max(9, 8 / S.z);
g.beginPath();
for (const i of vis) {
if (N.nd(W[i].a) !== root) continue;
const r = rt[i]; g.moveTo(r[0][0], r[0][1]); for (let k = 1; k < r.length; k++) g.lineTo(r[k][0], r[k][1]);
}
g.stroke(); g.restore();
}
}
if (vis.length <= this._LOD_WIRES && S.z >= 0.35) {
for (const i of vis) this._wire(g, rt[i], this._wstyle(P, S, W[i], i), S.fr, i === S.hw);
return;
}
const lw = Math.max(1.8, 1.3 / S.z), groups = new Map();
g.save(); g.lineJoin = "round"; g.lineCap = "round";
g.beginPath();
for (const i of vis) { const r = rt[i]; g.moveTo(r[0][0], r[0][1]); for (let k = 1; k < r.length; k++) g.lineTo(r[k][0], r[k][1]); }
g.strokeStyle = "rgba(70,70,70,0.75)"; g.lineWidth = lw + 1.6; g.stroke();
for (const i of vis) {
const st = this._wstyle(P, S, W[i], i);
const c = st.mate ? "#9a9a9a" : st.err ? "#ff2020" : st.short ? "#ff2828" : st.mismatch ? "#ffaa00" : st.c;
let a = groups.get(c); if (!a) groups.set(c, a = []);
a.push(i);
}
for (const [c, a] of groups) {
g.beginPath();
for (const i of a) { const r = rt[i]; g.moveTo(r[0][0], r[0][1]); for (let k = 1; k < r.length; k++) g.lineTo(r[k][0], r[k][1]); }
g.strokeStyle = c; g.lineWidth = lw; g.stroke();
}
g.restore();
if (S.hw >= 0 && rt[S.hw]) this._wire(g, rt[S.hw], this._wstyle(P, S, W[S.hw], S.hw), S.fr, true);
},
// ================================================================ INTERACTION
_hit(S, x, y) {
if (!S.tl || typeof x !== "number") return null;
const rr = 13 * (this._L.k || 1) / S.z; let best = null, bd = Math.max(30, rr * rr);
for (const t of S.tl) {
if (t.hid) continue;
const d = (t.x - x) * (t.x - x) + (t.y - y) * (t.y - y);
if (d < bd) { bd = d; best = t; }
}
return best;
},
_partAt(S, x, y) {
const C = this._cat();
for (let i = S.parts.length - 1; i >= 0; i--) {
const p = S.parts[i], d = C[p.t];
if (x >= p.x && x <= p.x + d.w && y >= p.y && y <= p.y + d.h) return p;
}
return null;
},
_say(S, m) { S.msg = m; S.mt = 360; },
_delPart(S, p) {
this._pushUndo(S);
S.parts = S.parts.filter(q => q !== p);
S.wires = S.wires.filter(w => w.a.indexOf(p.id + ".") !== 0 && w.b.indexOf(p.id + ".") !== 0);
delete S.fb[p.id]; delete S.sb[p.id]; delete S.fh[p.id]; delete S.sh[p.id];
if (S.sel === p.id) S.sel = null;
S.dirty = true; this._bump(S);
},
_down(S, x, y) {
const pn = this._L.pn;
if (S.ptab === 1 && x >= pn.x && x <= pn.x + pn.w && y >= pn.y && y <= pn.y + pn.h) { S.pscr = { y, sc: S.psc || 0 }; S.moved = false; return; }
if (S.ptab === 2 && S.scRect && x >= pn.x && x <= pn.x + pn.w) {
const r = S.scRect;
if (y >= r.y - 6 && y <= r.y + r.h + 6) {
const d1 = Math.abs(x - (r.x + S.scCur1 * r.w)), d2 = Math.abs(x - (r.x + S.scCur2 * r.w));
if (Math.min(d1, d2) < 12) { S.scDrag = d1 <= d2 ? 1 : 2; S.moved = false; return; }
}
}
if (S.mm && x >= S.mm.x && x <= S.mm.x + S.mm.w && y >= S.mm.y && y <= S.mm.y + S.mm.h) return;
if (!this._inWs(x, y)) return;
const sx = x, sy = y, w = this._w(S, x, y);
x = w[0]; y = w[1]; S.moved = false;
if (S.tool || S.pend) return;
if (this._hit(S, x, y)) return;
const p = this._partAt(S, x, y);
if (p) { S.sel = p.id; S.ptab = 1; S.psc = 0; S.drag = { id: p.id, dx: x - p.x, dy: y - p.y }; S.dragU = false; }
else S.pan = { sx, sy, vx: S.vx, vy: S.vy };
},
_move(S, x, y) {
const p = S.parts.find(q => q.id === S.drag.id), d = p && this._cat()[p.t];
if (!p) return;
const nx = this._cl(this._snap(x - S.drag.dx), 178, 1822 - d.w), ny = this._cl(this._snap(y - S.drag.dy), 30, 1154 - d.h);
if (nx !== p.x || ny !== p.y) {
if (!S.dragU) { S.dragU = true; this._pushUndo(S); }
p.x = nx; p.y = ny; S.moved = true; S.dirty = true;
}
},
_click(S, x, y) {
if (S.moved) { S.moved = false; return; }
for (let i = S.btn.length - 1; i >= 0; i--) {
const b = S.btn[i];
if (x >= b.x && x <= b.x + b.w && y >= b.y && y <= b.y + b.h) { b.fn(x, y); return; }
}
if (!this._inWs(x, y)) return;
{ const w = this._w(S, x, y); x = w[0]; y = w[1]; }
const h = this._hit(S, x, y);
if (S.tool && !h && !S.pend) {
const d = this._cat()[S.tool];
const px = this._cl(this._snap(x - d.w / 2), 178, 1822 - d.w), py = this._cl(this._snap(y - d.h / 2), 30, 1154 - d.h);
this._pushUndo(S);
const q = this._mk(S, S.tool, px, py);
S.parts.push(q); S.sel = q.id; S.dirty = true; this._bump(S);
return;
}
if (!S.pend) {
if (h) { S.pend = h.id; S.pts = []; return; }
const wi = this._wireAt(S, x, y);
if (wi >= 0) {
S.nethl = S.wires[wi].a;
const root = S.net.nd(S.nethl);
let cnt = 0; for (const w of S.wires) if (S.net.nd(w.a) === root) cnt++;
this._say(S, "Net highlighted: " + cnt + " wire(s) share this connection. Click empty space to clear.");
return;
}
S.nethl = null;
const p = this._partAt(S, x, y);
if (p) { S.sel = p.id; return; }
S.sel = null;
return;
}
if (h) {
if (S.pend === h.id) { S.pend = null; S.pts = []; return; }
const ta = S.tm[S.pend], tb = h;
const ma = !!ta.d.mate, mb = !!tb.d.mate;
if (ma !== mb || (ma && ta.k !== tb.k)) { this._say(S, "Connector terminals only mate with the same connector type (ISO A with ISO A, ISO B with ISO B)."); S.pend = null; S.pts = []; return; }
const a = S.pend, b = h.id, route = S.pts.length ? S.pts.map(p => p.slice()) : null;
this._pushUndo(S);
const ex = S.wires.find(w => (w.a === a && w.b === b) || (w.a === b && w.b === a));
if (ex) ex.r = ex.a === a ? route : (route ? route.slice().reverse() : null);
else S.wires.push({ a, b, r: route });
S.pend = null; S.pts = []; this._bump(S);
return;
}
const gx = this._cl(this._snap(x), 178, 1822), gy = this._cl(this._snap(y), 30, 1154);
const last = S.pts[S.pts.length - 1];
if (!last || last[0] !== gx || last[1] !== gy) S.pts.push([gx, gy]);
},
_ctx(S, x, y) {
if (S.tool) { S.tool = null; return; }
if (S.pend) { if (S.pts.length) S.pts.pop(); else S.pend = null; return; }
if (!this._inWs(x, y)) return;
{ const w = this._w(S, x, y); x = w[0]; y = w[1]; }
const h = this._hit(S, x, y);
if (h) { this._pushUndo(S); S.wires = S.wires.filter(w => w.a !== h.id && w.b !== h.id); this._bump(S); return; }
const i = this._wireAt(S, x, y);
if (i >= 0) { this._pushUndo(S); S.wires.splice(i, 1); this._bump(S); return; }
const p = this._partAt(S, x, y);
if (p) this._delPart(S, p);
},
_bind(g, S) {
const cv = g.canvas;
if (!cv || S.bound === cv) return;
S.bound = cv;
const pos = e => {
const r = cv.getBoundingClientRect();
const px = (e.clientX - r.left) * (S.W / r.width), py = (e.clientY - r.top) * (S.H / r.height);
return [(px - S.ox) / S.s, (py - S.oy) / S.s];
};
const upd = p => { S.mx = p[0]; S.my = p[1]; const w = this._w(S, p[0], p[1]); S.wx = w[0]; S.wy = w[1]; };
const mv = p => {
upd(p);
if (S.drag) this._move(S, S.wx, S.wy);
else if (S.scDrag) { const r = S.scRect; if (r) { S["scCur" + S.scDrag] = this._cl((p[0] - r.x) / r.w, 0, 1); S.moved = true; } }
else if (S.pscr) { const dy = p[1] - S.pscr.y; if (Math.abs(dy) > 6) S.moved = true; S.psc = S.pscr.sc - dy; }
else if (S.pan) {
const dx = p[0] - S.pan.sx, dy = p[1] - S.pan.sy;
if (Math.abs(dx) + Math.abs(dy) > 3) S.moved = true;
S.vx = S.pan.vx - dx / S.z; S.vy = S.pan.vy - dy / S.z; this._clampView(S);
}
};
cv.addEventListener("mousemove", e => mv(pos(e)));
cv.addEventListener("wheel", e => {
const p = pos(e), pn = this._L.pn;
if (S.ptab === 1 && p[0] >= pn.x && p[0] <= pn.x + pn.w && p[1] >= pn.y && p[1] <= pn.y + pn.h) { e.preventDefault(); S.psc = (S.psc || 0) + e.deltaY * 0.5; return; }
if (!this._inWs(p[0], p[1])) return; e.preventDefault(); this._zoom(S, e.deltaY < 0 ? 1.15 : 1 / 1.15, p[0], p[1]); }, { passive: false });
cv.addEventListener("mouseleave", () => { S.mx = -1e3; S.my = -1e3; S.pan = null; S.pscr = null; S.scDrag = 0; if (S.drag) { S.drag = null; S.rsig = null; } });
cv.addEventListener("mousedown", e => { if (e.button !== 0) return; const p = pos(e); this._down(S, p[0], p[1]); });
cv.addEventListener("mouseup", () => { S.pan = null; S.pscr = null; S.scDrag = 0; if (S.drag) { S.drag = null; S.rsig = null; } });
cv.addEventListener("click", e => { const p = pos(e); this._click(S, p[0], p[1]); });
cv.addEventListener("contextmenu", e => { e.preventDefault(); const p = pos(e); this._ctx(S, p[0], p[1]); });
if (typeof document !== "undefined" && !S.kb) {
S.kb = e => {
if (!(e.ctrlKey || e.metaKey)) return;
const k = (e.key || "").toLowerCase();
if (k === "z" && !e.shiftKey) { e.preventDefault(); this._undoAct(S); }
else if (k === "y" || (k === "z" && e.shiftKey)) { e.preventDefault(); this._redoAct(S); }
};
document.addEventListener("keydown", S.kb);
}
const td = e => Math.hypot(e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY);
cv.addEventListener("touchstart", e => {
e.preventDefault();
clearTimeout(S.lpT);
if (e.touches.length >= 2) { S.pinch = { d: td(e), z: S.z }; S.drag = null; S.pan = null; S.tap = null; S.scDrag = 0; return; }
const p = pos(e.touches[0]); upd(p);
S.tap = { x: p[0], y: p[1], mv: 0, lp: false };
this._down(S, p[0], p[1]);
S.lpT = setTimeout(() => { if (S.tap && !S.tap.mv && !S.moved) { S.tap.lp = true; this._ctx(S, S.tap.x, S.tap.y); } }, 650);
}, { passive: false });
cv.addEventListener("touchmove", e => {
e.preventDefault();
if (e.touches.length >= 2 && S.pinch) {
const r = cv.getBoundingClientRect();
const mx = ((e.touches[0].clientX + e.touches[1].clientX) / 2 - r.left) * (S.W / r.width), my = ((e.touches[0].clientY + e.touches[1].clientY) / 2 - r.top) * (S.H / r.height);
this._zoom(S, td(e) / S.pinch.d * S.pinch.z / S.z, (mx - S.ox) / S.s, (my - S.oy) / S.s);
return;
}
const p = pos(e.touches[0]);
if (S.tap && Math.abs(p[0] - S.tap.x) + Math.abs(p[1] - S.tap.y) > 8) { S.tap.mv = 1; clearTimeout(S.lpT); }
mv(p);
}, { passive: false });
cv.addEventListener("touchend", e => {
e.preventDefault(); clearTimeout(S.lpT);
if (e.touches.length === 0) {
const t = S.tap, wasMoved = S.moved;
S.pinch = null; S.drag = null; S.pan = null; S.pscr = null; S.scDrag = 0; S.rsig = null; S.tap = null;
S.moved = false;
if (t && !t.mv && !t.lp && !wasMoved) this._click(S, t.x, t.y);
S.mx = -1e3; S.my = -1e3;
}
}, { passive: false });
},
_chg(p, pd, dir) {
if (pd.vals) {
let i = pd.vals.indexOf(p.pr[pd.k]); if (i < 0) i = 0;
p.pr[pd.k] = pd.vals[this._cl(i + dir, 0, pd.vals.length - 1)];
} else p.pr[pd.k] = Math.round(this._cl(p.pr[pd.k] + dir * pd.step, pd.min, pd.max) * 1000) / 1000;
},
_fv(pd, v) {
if (Array.isArray(pd.fmt)) return pd.fmt[pd.vals ? pd.vals.indexOf(v) : v];
if (typeof pd.fmt === "function") return pd.fmt(v);
return (typeof v === "number" ? +v.toFixed(2) : v) + pd.u;
},
// ================================================================ DRAW PRIMITIVES
_rr(g, x, y, w, h, r, fill, stroke, lw) {
g.save(); g.beginPath();
g.moveTo(x + r, y); g.lineTo(x + w - r, y); g.quadraticCurveTo(x + w, y, x + w, y + r);
g.lineTo(x + w, y + h - r); g.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
g.lineTo(x + r, y + h); g.quadraticCurveTo(x, y + h, x, y + h - r);
g.lineTo(x, y + r); g.quadraticCurveTo(x, y, x + r, y); g.closePath();
if (fill) { g.fillStyle = fill; g.fill(); }
if (stroke) { g.strokeStyle = stroke; g.lineWidth = lw || 1; g.stroke(); }
g.restore();
},
_bv(g, x, y, w, h) {
this._raised(g, x + 1, y + 2, w, h, "#a0a0a0");
this._raised(g, x, y, w, h, this._C95.face);
},
_sk(g, x, y, w, h, fill) { this._sunken(g, x, y, w, h, fill || this._C95.field); },
_bt(S, g, x, y, w, h, label, fn, act, sz, tip) {
this._btn95(g, x, y, w, h, label, act, sz);
S.btn.push({ x, y, w, h, fn, tip });
},
_tx(g, s, x, y, c, sz, al, b) {
g.save(); g.font = (b ? "bold " : "") + sz + "px " + this._FONT; g.fillStyle = c;
g.textAlign = al || "center"; g.textBaseline = "middle"; g.fillText(s, x, y); g.restore();
},
_txM(g, s, x, y, c, sz, al, b) {
g.save(); g.font = (b ? "bold " : "") + sz + "px " + this._MONO; g.fillStyle = c;
g.textAlign = al || "center"; g.textBaseline = "middle"; g.fillText(s, x, y); g.restore();
},
_tv(g, s, x, y, c, sz) {
g.save(); g.translate(x, y); g.rotate(-1.5708);
g.font = sz + "px " + this._FONT; g.fillStyle = c; g.textAlign = "left"; g.textBaseline = "middle";
g.fillText(s, 0, 0); g.restore();
},
_ln(g, x1, y1, x2, y2, c, w) {
g.save(); g.strokeStyle = c; g.lineWidth = w || 1.5; g.lineCap = "round";
g.beginPath(); g.moveTo(x1, y1); g.lineTo(x2, y2); g.stroke(); g.restore();
},
_poly(g, pts, c, closed, fill) {
g.save(); g.strokeStyle = c; g.lineWidth = 1.5; g.lineJoin = "round";
g.beginPath(); g.moveTo(pts[0][0], pts[0][1]);
for (let i = 1; i < pts.length; i++) g.lineTo(pts[i][0], pts[i][1]);
if (closed) g.closePath();
if (fill) { g.fillStyle = fill; g.fill(); }
g.stroke(); g.restore();
},
_circ(g, x, y, r, c, fill) {
g.save(); g.strokeStyle = c; g.lineWidth = 1.5;
g.beginPath(); g.arc(x, y, r, 0, 6.2832);
if (fill) { g.fillStyle = c; g.fill(); }
g.stroke(); g.restore();
},
_arc(g, x, y, r, a1, a2, c) {
g.save(); g.strokeStyle = c; g.lineWidth = 1.5; g.lineCap = "round";
g.beginPath(); g.arc(x, y, r, a1, a2); g.stroke(); g.restore();
},
// ================================================================ CABLE COLOURS
_tcol(t) {
const d = t.d, Wh = "#f4f4f4";
if (d.col) return { c: d.col.c, s: d.col.s || null, sp: true };
switch (t.k) {
case "gnd": return { c: "#161616" };
case "pwr": return { c: "#e02424" };
case "rem": return { c: "#2f7be8", s: Wh };
case "rf": return { c: "#4a4a4a", s: "#bdbdbd" };
case "rcaL": return { c: Wh };
case "rcaR": return { c: "#e02424" };
case "spk":
if (/\+$/.test(t.lab)) return { c: "#e02424" };
if (/[\u2212-]$/.test(t.lab)) return { c: "#161616" };
return null;
}
return null;
},
_wire(g, pts, st, fr, hl) {
if (!pts || pts.length < 2) return;
g.save(); g.lineJoin = "round"; g.lineCap = "round";
const path = () => { g.beginPath(); g.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) g.lineTo(pts[i][0], pts[i][1]); };
if (st.mate) { path(); g.strokeStyle = "#202020"; g.lineWidth = 9; g.stroke(); path(); g.strokeStyle = "#9a9a9a"; g.lineWidth = 6; g.stroke(); if (hl) { path(); g.strokeStyle = "rgba(0,0,128,0.5)"; g.lineWidth = 3; g.stroke(); } g.restore(); return; }
if (st.short) { path(); g.strokeStyle = "rgba(255,40,40,0.45)"; g.lineWidth = 9; g.stroke(); }
if (hl) { path(); g.strokeStyle = "rgba(0,0,128,0.45)"; g.lineWidth = 9; g.stroke(); }
path(); g.strokeStyle = "rgba(90,90,90,0.8)"; g.lineWidth = 5; g.stroke();
path(); g.strokeStyle = st.c; g.lineWidth = 3.2; g.stroke();
if (st.s) { path(); g.setLineDash([5, 5]); g.strokeStyle = st.s; g.lineWidth = 3.2; g.stroke(); g.setLineDash([]); }
if (st.err) { path(); g.setLineDash([4, 6]); g.strokeStyle = "#ff2020"; g.lineWidth = 3.2; g.stroke(); g.setLineDash([]); }
else if (st.mismatch) { path(); g.setLineDash([8, 4]); g.strokeStyle = "#ffaa00"; g.lineWidth = 3.2; g.stroke(); g.setLineDash([]); }
if (st.live) {
path(); g.setLineDash([2, 12]); g.lineDashOffset = -fr * 0.6;
g.strokeStyle = st.c === "#f4f4f4" ? "#2a7be0" : "rgba(255,255,255,0.85)"; g.lineWidth = 1.5; g.stroke(); g.setLineDash([]);
}
g.restore();
},
_hv(S, P, on) { return on ? SimKit.voltColor(P.Vcc, P.Vcc) : "#555"; },
_part(g, p, P, S) {
const N = S.net, d = this._cat()[p.t], x = p.x, y = p.y, w = d.w, h = d.h, k = d.kind, st = N.by[p.id];
const on = !!(st && st.on);
this._bv(g, x, y, w, h);
const small = w < 130;
if (k !== "spk") this._tx(g, small ? p.lb : p.lb + " \u00b7 " + d.name, x + w / 2, y + 12, "#000", 9, "center", true);
const cx = x + w / 2;
if (k === "head") {
this._sk(g, x + 10, y + 22, w - 20, 44, "#1c2b1c");
const rad = st.rad, pr = p.pr, radio = d.radio || pr.src >= 0.5;
this._txM(g, !st.on ? "OFF" : (radio ? (st.antOk ? "RADIO FM 98.4" : "RADIO: NO ANT") : "CD PLAYER"), cx, y + 36, st.on ? (rad === 2 ? "#ffb000" : "#7CFC00") : "#4a5a4a", 11, "center", true);
this._txM(g, st.on ? "VOL " + Math.round(pr.vol * 100) + "%" : (st.vbad === 1 ? "LOW V" : st.vbad === 2 ? "OVER V" : "NO POWER"), cx, y + 52, st.vbad === 2 ? "#ff4040" : "#7CFC00", 9);
const chk = N.chs.filter(c => c.h === st);
if (chk.some(c => S.prot[c.key])) this._tx(g, "PROTECT", x + w - 40, y + 52, "#ff4040", 9, "center", true);
else if (chk.some(c => S.clip[c.key] > 0)) this._tx(g, "CLIP", x + w - 40, y + 52, "#ff4040", 9, "center", true);
this._tx(g, d.spec, cx, y + 76, "#404040", 8);
this._tx(g, st.on ? "(" + (d.iso ? "ISO plug" : "loose wires") + ")" : (d.iso ? "ISO plug" : "loose wires"), cx, y + 88, "#707070", 8);
} else if (k === "amp") {
this._circ(g, x + 36, y + 26, 4, on ? "#00c000" : "#800000", true);
this._tx(g, on ? "ON" : (st.vbad ? (st.vbad === 1 ? "LOW V" : "OVER V") : "OFF"), x + 50, y + 26, "#000", 9, "left", true);
const own = N.chs.filter(c => c.am === st);
own.forEach((c, i) => {
const col = S.prot[c.key] ? "#c00000" : (S.clip[c.key] > 0 ? "#c00000" : "#000");
const txt = "CH" + (i + 1) + " " + (S.pw[c.key] || 0).toFixed(1) + " W" + (S.prot[c.key] ? " PROT" : S.clip[c.key] > 0 ? " CLIP" : "");
this._txM(g, txt, x + 36, y + 42 + i * 11, col, 8, "left");
});
this._tx(g, "gain \u00d7" + p.pr.gain.toFixed(1) + (d.lpf ? " LPF " + p.pr.fc + " Hz" : ""), cx + 20, y + h - 10, "#404040", 8);
this._tx(g, d.spec, cx + 20, y + h - 22, "#707070", 8);
} else if (k === "filt") {
this._circ(g, x + 20, y + 28, 4, on ? "#00c000" : "#800000", true);
if (d.eq) { this._txM(g, "B " + p.pr.bass + " M " + p.pr.mid + " T " + p.pr.treb + " dB", cx, y + 46, "#000", 9); this._tx(g, "3-band EQ", cx, y + 60, "#707070", 8); }
else if (d.iso) { this._tx(g, "RCA isolator", cx, y + 40, "#000", 9); this._tx(g, "no hum from ground loops", cx, y + 54, "#707070", 8); }
else if (d.ld) { this._txM(g, "+" + p.pr.gain + " dB", cx, y + 46, "#000", 9); this._tx(g, "line driver", cx, y + 60, "#707070", 8); }
else if (d.xo) {
this._txM(g, d.xo.length === 2 ? p.pr.fc + " Hz \u00b7 " + p.pr.order + " dB/oct" : p.pr.fcL + " / " + p.pr.fcH + " Hz", cx, y + 46, "#000", 9);
this._tx(g, d.xo.length === 2 ? "2-way crossover" : "3-way crossover \u00b7 " + p.pr.order + " dB/oct", cx, y + 60, "#707070", 8);
}
else { this._txM(g, p.pr.fc + " Hz \u00b7 " + p.pr.slope + " dB/oct", cx, y + 46, "#000", 9); this._tx(g, p.pr.mode === 1 ? "high-pass" : "low-pass", cx, y + 60, "#707070", 8); }
} else if (k === "spk") {
const id = p.id, burnt = !!S.sb[id], z = d.sz;
const vis = burnt ? 0 : this._cl(Math.sqrt((S.spp[id] || 0) / (d.p * 0.1)), 0, 1);
const col = burnt ? "#d03030" : (vis < 0.03 ? "#444" : SimKit.voltColor(vis * P.Vcc, P.Vcc));
const defl = burnt ? 0 : this._cl((S.sv[id] || 0) * 0.3, -4, 4), cy = y + 30;
this._tx(g, p.lb, x + 40, y + 8, "#000", 9, "center", true);
this._poly(g, [[x + 12, cy - 10], [x + 24, cy - 10], [x + 24, cy + 10], [x + 12, cy + 10]], col, true, "#e0e0e0");
this._poly(g, [[x + 24, cy - 8], [x + 24 + 14 * z + defl, cy - 22 * z * 0.95], [x + 24 + 14 * z + defl, cy + 22 * z * 0.95], [x + 24, cy + 8]], col, true, "#d0d0d0");
this._ln(g, x, y + 20, x + 12, y + 20, "#444"); this._ln(g, x, y + 40, x + 12, y + 40, "#444");
if (!burnt && vis >= 0.03) for (const r of [8, 14]) this._arc(g, x + 38 + 14 * z, cy, r, -0.7, 0.7, col);
if (burnt) { this._ln(g, x + 30, cy - 14, x + 56, cy + 14, "#d03030", 3); this._ln(g, x + 30, cy + 14, x + 56, cy - 14, "#d03030", 3); }
this._tx(g, d.spec, x + 40, y + h + 8, burnt ? "#d03030" : "#000", 8);
this._txM(g, burnt ? "BURNT" : (S.spp[id] || 0).toFixed(1) + " W", x + 40, y + h + 18, burnt ? "#d03030" : "#404040", 8, "center", burnt);
} else if (k === "fuse") {
const bl = !!S.fb[p.id], col = bl ? "#d03030" : this._hv(S, P, N.E.en.has(N.nd(p.id + ".a")) && !N.short);
this._ln(g, x, y + 20, x + 25, y + 20, col); this._ln(g, x + 75, y + 20, x + 100, y + 20, col);
this._poly(g, [[x + 25, y + 14], [x + 75, y + 14], [x + 75, y + 26], [x + 25, y + 26]], col, true, "#e8e8e8");
if (bl) { this._ln(g, x + 38, y + 17, x + 62, y + 23, col); this._ln(g, x + 38, y + 23, x + 62, y + 17, col); }
else this._ln(g, x + 28, y + 20, x + 72, y + 20, col, 1);
this._tx(g, bl ? "BLOWN" : (d.nf ? "filter -" + p.pr.db + " dB" : p.pr.amps + " A"), cx, y + 33, bl ? "#d03030" : "#000", 9, "center", bl);
if (!bl) this._txM(g, (S.fi[p.id] || 0).toFixed(1) + " A now", cx, y + 5, "#404040", 8);
} else if (k === "sw") {
const o = P.ign >= 0.5;
this._ln(g, x, y + 20, x + 20, y + 20, "#444"); this._ln(g, x + 60, y + 20, x + 80, y + 20, "#444");
this._circ(g, x + 20, y + 20, 2.5, "#444", true); this._circ(g, x + 60, y + 20, 2.5, "#444", true);
if (o) this._ln(g, x + 20, y + 20, x + 60, y + 20, "#000", 2.5); else this._ln(g, x + 20, y + 20, x + 56, y + 6, "#000", 2.5);
this._tx(g, o ? "ON" : "OFF", cx, y + 33, o ? "#006000" : "#800000", 9, "center", true);
} else if (k === "relay") {
const cl = !!(S.rly && S.rly[p.id]);
this._ln(g, x, y + 20, x + 14, y + 20, "#444"); this._ln(g, x, y + 50, x + 14, y + 50, "#444");
this._poly(g, [[x + 14, y + 20], [x + 34, y + 20], [x + 34, y + 50], [x + 14, y + 50]], cl ? "#006000" : "#000", true, cl ? "#c0ffc0" : "#e8e8e8");
this._ln(g, x + 100, y + 20, x + 70, y + 20, "#444"); this._ln(g, x + 100, y + 50, x + 70, y + 50, "#444");
this._circ(g, x + 70, y + 20, 2.5, "#444", true); this._circ(g, x + 70, y + 50, 2.5, "#444", true);
if (cl) this._ln(g, x + 70, y + 20, x + 70, y + 50, "#000", 2.5); else this._ln(g, x + 70, y + 20, x + 58, y + 44, "#000", 2.5);
this._tx(g, cl ? "CLOSED" : "OPEN", x + 50, y + 62, cl ? "#006000" : "#800000", 9, "center", true);
} else if (k === "diode") {
const cd = !!(S.dio && S.dio[p.id]);
this._ln(g, x, y + 20, x + 30, y + 20, "#444"); this._ln(g, x + 50, y + 20, x + 80, y + 20, "#444");
this._poly(g, [[x + 30, y + 8], [x + 30, y + 32], [x + 50, y + 20]], "#000", true, cd ? "#80e080" : "#e8e8e8");
this._ln(g, x + 50, y + 8, x + 50, y + 32, "#000", 2.5);
} else if (k === "bigcap") {
const pe = N.E.en.has(N.nd(p.id + ".pos")) && !N.short && N.gnd !== -3, ch = pe ? this._cl(N.vsys / 16, 0, 1) : 0;
this._ln(g, x + 20, y, x + 20, y + 14, "#444"); this._ln(g, x + 60, y, x + 60, y + 14, "#444");
this._sk(g, x + 10, y + 14, 60, 34, "#e8e8e8");
g.save(); g.fillStyle = "#6ab86a"; g.fillRect(x + 12, y + 46 - 30 * ch, 56, 30 * ch); g.restore();
this._txM(g, p.pr.F + " F", cx, y + 26, "#000", 9, "center", true);
this._txM(g, pe ? N.vsys.toFixed(1) + " V" : "0.0 V", cx, y + 56, "#000", 8);
} else if (k === "bat") {
const vb = p.pr.v > 0 ? p.pr.v : P.Vcc;
this._ln(g, x + 30, y + 14, x + 30, y + 34, "#000"); this._ln(g, x + 12, y + 34, x + 48, y + 34, "#000", 3); this._ln(g, x + 20, y + 40, x + 40, y + 40, "#000", 3);
this._ln(g, x + 12, y + 46, x + 48, y + 46, "#000", 3); this._ln(g, x + 20, y + 52, x + 40, y + 52, "#000", 3); this._ln(g, x + 30, y + 52, x + 30, y + 66, "#000");
this._txM(g, vb.toFixed(1) + " V", cx, y + 74, "#000", 9, "center", true);
this._tx(g, "+", x + 46, y + 22, "#c00000", 11, "center", true);
} else if (k === "gnd") {
this._ln(g, x + 20, y + 4, x + 20, y + 14, "#000"); this._ln(g, x + 8, y + 14, x + 32, y + 14, "#000"); this._ln(g, x + 12, y + 20, x + 28, y + 20, "#000"); this._ln(g, x + 16, y + 26, x + 24, y + 26, "#000");
this._tx(g, "CHASSIS", x + 20, y + 35, "#505050", 7);
} else if (k === "cap") {
this._ln(g, x, y + 20, x + 36, y + 20, "#444"); this._ln(g, x + 36, y + 10, x + 36, y + 30, "#000", 2.5); this._ln(g, x + 44, y + 10, x + 44, y + 30, "#000", 2.5); this._ln(g, x + 44, y + 20, x + 80, y + 20, "#444");
this._txM(g, p.pr.uF + " \u00b5F", cx, y + 6, "#000", 8, "center", false);
this._tx(g, p.lb, cx, y + 35, "#000", 8, "center", true);
} else if (k === "coil") {
this._ln(g, x, y + 20, x + 22, y + 20, "#444"); this._ln(g, x + 58, y + 20, x + 80, y + 20, "#444");
for (let i = 0; i < 3; i++) this._arc(g, x + 28 + i * 12, y + 20, 6, Math.PI, 0, "#000");
this._txM(g, p.pr.mH + " mH", cx, y + 6, "#000", 8, "center", false);
this._tx(g, p.lb, cx, y + 35, "#000", 8, "center", true);
} else if (k === "ant") {
const hOK = N.heads.some(H => H.ant === p && H.antOk);
this._ln(g, x + 60, y + 20, x + 80, y + 6, "#000", 2); this._circ(g, x + 80, y + 6, 2.5, "#000", true);
this._tx(g, hOK ? "SIGNAL OK" : "NO SIGNAL", cx, y + 34, hOK ? "#006000" : "#707070", 8, "center", true);
} else if (k === "gen") {
this._txM(g, p.pr.on ? ["100 Hz", "1 kHz", "5 kHz"][p.pr.band] + " " + p.pr.amp.toFixed(1) + "V" : "OFF", cx, y + 40, "#000", 9);
this._tx(g, "sine", cx, y + 54, "#707070", 8);
} else if (k === "dmm") {
const r = this._dmm(P, S, p);
this._sk(g, x + 10, y + 22, w - 20, 36, "#a8b8a0");
this._txM(g, r.t, cx, y + 40, "#101810", 12, "center", true);
this._txM(g, ["DC V", "AC V", "CONT", "OHMS"][p.pr.mode], cx, y + 68, "#000", 8);
this._tx(g, "RED", x + 40, y + 84, "#c00000", 8, "center", true); this._tx(g, "BLACK", x + 90, y + 84, "#000", 8, "center", true);
} else if (k === "probe") {
const id = p.id + ".t", v = N.vd(N.nd(id), N.gnd), ac = this._acRms(S, id);
this._sk(g, x + 8, y + 18, w - 16, 22, "#a8b8a0");
this._txM(g, (v < -0.005 ? "-" : "") + Math.abs(v).toFixed(2) + " V" + (ac > 0.01 ? " ~" + ac.toFixed(2) : ""), cx, y + 29, "#101810", 9, "center", true);
} else if (k === "ctest") {
const a = N.nd(p.id + ".a"), b = N.nd(p.id + ".b"), con = N.conn(a, b);
const t = con ? (N.short ? "SHORT" : "OK") : "OPEN", col = con ? (N.short ? "#c00000" : "#006000") : "#707070";
this._sk(g, x + 14, y + 20, w - 28, 22, "#a8b8a0");
this._txM(g, t, cx, y + 31, col, 11, "center", true);
} else if (k === "scope") {
this._sk(g, x + 10, y + 22, w - 20, 40, "#001a00");
for (let i = 1; i < 4; i++) this._ln(g, x + 10 + i * (w - 20) / 4, y + 22, x + 10 + i * (w - 20) / 4, y + 62, "#064a06", 1);
this._ln(g, x + 10, y + 42, x + w - 10, y + 42, "#064a06", 1);
this._tx(g, "SCOPE", cx, y + 76, "#404040", 8);
} else if (k === "pass") {
this._tx(g, d.spec, cx, y + h / 2 + 2, "#404040", 8);
}
if (S.sel === p.id) {
g.save(); g.setLineDash([4, 3]); g.strokeStyle = "#000080"; g.lineWidth = 2; g.strokeRect(x - 4, y - 4, w + 8, h + 8); g.restore();
}
},
_acRms(S, tid) {
const N = S.net, a = S.nsig && S.nsig[N.na(tid)], z = S.nz && S.nz[N.na(tid)];
return Math.sqrt((a ? (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]) / 2 : 0) + (z ? (z[0] * z[0] + z[1] * z[1]) / 2 : 0));
},
_dmm(P, S, p) {
const N = S.net, r = p.id + ".red", b = p.id + ".black", mode = p.pr.mode;
const ac = id => this._acRms(S, id);
if (mode === 0) { const v = N.vd(N.nd(r), N.nd(b)); return { t: (v < -0.005 ? "-" : "") + Math.abs(v).toFixed(2) + " V" }; }
if (mode === 1) return { t: Math.abs(ac(r) - ac(b)).toFixed(2) + " V~" };
const con = N.conn(N.nd(r), N.nd(b));
if (mode === 2) return { t: con ? "BEEP 0.1\u03a9" : "OPEN" };
if (con) return { t: "0.1 \u03a9" };
for (const s of N.spk) {
const a = N.na(r), c = N.na(b);
if ((a === s.X && c === s.Y) || (a === s.Y && c === s.X)) return { t: (this._cat()[s.p.t].z * 0.85).toFixed(1) + " \u03a9" };
}
return { t: "OL" };
},
// ================================================================ OSCILLOSCOPE
// Знаходить вікно відображення: {i0, n, trig, ok, wait}
_scopeFind(sp, S) {
const pr = sp.pr, L = S.r1.length, hd = S.ri, n = Math.min(L - 20, Math.round(pr.tb * 500));
const sig = [pr.trig, pr.edge, pr.lvl, pr.src, pr.v1, pr.v2, pr.tb, pr.cp1, pr.cp2, pr.ch1, pr.ch2].join("|");
if (S.scSig !== sig) { S.scSig = sig; S.scFrozen = false; S.scSnap = null; }
if (pr.trig !== 2 && S.scFrozen) { S.scFrozen = false; S.scSnap = null; }
if (S.scFrozen && S.scSnap) return S.scSnap;
if (hd < n + 2) return { i0: 0, n, trig: false, ok: false, wait: true };
if (pr.trig === 3) return { i0: hd - n, n, trig: false, ok: true };
const arr = pr.src ? S.r2 : S.r1, ac = pr.src ? pr.cp2 : pr.cp1, v = k => arr[((k % L) + L) % L];
let off = 0;
if (ac) { let s = 0; for (let k = hd - n; k < hd; k++) s += v(k); off = s / n; }
const lv = pr.lvl + off, kmin = Math.max(1, hd - L + 2);
let found = -1;
for (let k = hd - n; k >= kmin; k--) {
const a = v(k - 1), b = v(k);
if (pr.edge ? (a >= lv && b < lv) : (a < lv && b >= lv)) { found = k; break; }
}
if (found >= 0) {
const r = { i0: found, n, trig: true, ok: true };
if (pr.trig === 2) { S.scFrozen = true; S.scSnap = r; }
return r;
}
if (pr.trig === 0) return { i0: hd - n, n, trig: false, ok: true };
return { i0: 0, n, trig: false, ok: false, wait: true };
},
// Vpp / Vrms / Vavg (для AC зв'язку середнє віднімається)
_scopeMeasure(arr, S, i0, n, ac) {
const L = arr.length; let mn = 1e9, mx = -1e9, s = 0;
for (let k = i0; k < i0 + n; k++) { const x = arr[k % L]; if (x < mn) mn = x; if (x > mx) mx = x; s += x; }
const mean = s / n; let q = 0;
const o = ac ? mean : 0;
for (let k = i0; k < i0 + n; k++) { const x = arr[k % L] - o; q += x * x; }
return { mn, mx, vpp: mx - mn, avg: ac ? 0 : mean, mean, rms: Math.sqrt(q / n) };
},
// частота через перетини середини розмаху (з гістерезисом)
_scopeFreq(arr, S, i0, n) {
const L = arr.length; let mn = 1e9, mx = -1e9;
for (let k = i0; k < i0 + n; k++) { const x = arr[k % L]; if (x < mn) mn = x; if (x > mx) mx = x; }
const vpp = mx - mn;
if (vpp < 0.02) return { f: 0, T: 0 };
const mid = (mn + mx) / 2, hy = vpp * 0.05;
let armed = false, first = -1, last = -1, cnt = 0;
for (let k = i0; k < i0 + n; k++) {
const x = arr[k % L];
if (x < mid - hy) armed = true;
else if (armed && x > mid + hy) { armed = false; if (first < 0) first = k; last = k; cnt++; }
}
if (cnt < 2) return { f: 0, T: 0 };
const T = (S.rtm[last % L] - S.rtm[first % L]) / (cnt - 1);
return T > 0 ? { f: 1 / T, T } : { f: 0, T: 0 };
},
_drawScope(g, S, x, y, w, h, sp) {
const pr = sp.pr, L = S.r1.length;
this._sk(g, x, y, w, h, "#001a00");
const dx = w / 10, dy = h / 8, cy = y + h / 2;
for (let i = 1; i < 10; i++) this._ln(g, x + i * dx, y, x + i * dx, y + h, i === 5 ? "#0a6a0a" : "#064a06", 1);
for (let j = 1; j < 8; j++) this._ln(g, x, y + j * dy, x + w, y + j * dy, j === 4 ? "#0a6a0a" : "#064a06", 1);
this._txM(g, pr.tb + " ms/div", x + w - 4, y + h - 8, "#4ac84a", 8, "right");
if (pr.ch1) this._txM(g, "1: " + pr.v1 + " V/div" + (pr.cp1 ? " AC" : ""), x + 4, y + h - 8, "#d8d800", 8, "left");
if (pr.ch2) this._txM(g, "2: " + pr.v2 + " V/div" + (pr.cp2 ? " AC" : ""), x + 4, y + h - 18, "#00b8b8", 8, "left");
const F = this._scopeFind(sp, S), res = { F, m1: null, m2: null, f1: null, f2: null, cur: null };
if (F.ok) {
const chs = [[1, S.r1, "#ffff00", pr.ch1, pr.v1, pr.cp1], [2, S.r2, "#00ffff", pr.ch2, pr.v2, pr.cp2]];
for (const [id, arr, col, en, vd, ac] of chs) {
if (!en) continue;
const m = this._scopeMeasure(arr, S, F.i0, F.n, ac), off = ac ? m.mean : 0;
res["m" + id] = m; res["f" + id] = this._scopeFreq(arr, S, F.i0, F.n);
g.save(); g.beginPath(); g.rect(x, y, w, h); g.clip();
g.strokeStyle = col; g.lineWidth = 1.2; g.beginPath();
for (let px = 0; px <= w; px++) {
const k = F.i0 + Math.floor(px / w * F.n);
if (k >= F.i0 + F.n) break;
const yy = cy - (arr[k % L] - off) / vd * dy;
if (px === 0) g.moveTo(x + px, yy); else g.lineTo(x + px, yy);
}
g.stroke(); g.restore();
}
// курсори
const c1 = S.scCur1, c2 = S.scCur2;
const val = (arr, c, ac, m) => arr[(F.i0 + Math.min(F.n - 1, Math.floor(c * F.n))) % L] - (ac ? m.mean : 0);
res.cur = { dt: (c2 - c1) * 10 * pr.tb };
if (res.m1) res.cur.d1 = val(S.r1, c2, pr.cp1, res.m1) - val(S.r1, c1, pr.cp1, res.m1);
if (res.m2) res.cur.d2 = val(S.r2, c2, pr.cp2, res.m2) - val(S.r2, c1, pr.cp2, res.m2);
} else {
this._txM(g, F.wait && pr.trig === 2 ? "SINGLE: ARMED, WAITING FOR TRIGGER" : (pr.trig === 1 ? "NORMAL: NO TRIGGER" : "COLLECTING..."), x + w / 2, cy, "#4ac84a", 9, "center", true);
}
// рівень тригера
if (pr.trig !== 3) {
const ty = cy - pr.lvl / (pr.src ? pr.v2 : pr.v1) * dy;
if (ty > y && ty < y + h) { g.save(); g.fillStyle = "#ff8040"; g.beginPath(); g.moveTo(x, ty - 4); g.lineTo(x + 7, ty); g.lineTo(x, ty + 4); g.closePath(); g.fill(); g.restore(); }
}
// курсори (лінії)
for (const [i, c] of [[1, S.scCur1], [2, S.scCur2]]) {
const cxp = x + c * w;
g.save(); g.setLineDash([3, 3]); g.strokeStyle = "#ffffff"; g.lineWidth = 1;
g.beginPath(); g.moveTo(cxp, y); g.lineTo(cxp, y + h); g.stroke(); g.setLineDash([]); g.restore();
this._txM(g, String(i), cxp + 6, y + 18, "#ffffff", 8, "center", true);
}
// смуга Trigger
g.save(); g.fillStyle = F.trig ? "#00b000" : "#2a2a2a"; g.fillRect(x + 1, y + 1, w - 2, 9); g.restore();
this._txM(g, F.trig ? "TRIGGER" : ["AUTO", "NORMAL", "SINGLE", "ROLL"][pr.trig], x + w / 2, y + 6, F.trig ? "#ffffff" : "#8a8a8a", 7, "center", true);
if (S.scFrozen) this._txM(g, "HOLD", x + w - 4, y + 18, "#ff8040", 8, "right", true);
return res;
},
// ================================================================ DIAGNOSTICS
_diag(P, S) {
const N = S.net, o = [], R = "#800000", Y = "#808000", G = "#008000";
if (!S.parts.length) return [["Empty workbench: choose a part in the toolbox, then click the workspace.", "#000"]];
const C = this._cat();
if (!N.bats.length) o.push(["No battery on the workbench (Power tab).", Y]);
if (N.direct) o.push(["CATASTROPHIC SHORT: battery + is wired directly to ground!", R]);
else {
const f = Object.keys(N.sf).filter(k => N.sf[k]).map(k => S.parts.find(p => p.id === k).lb);
if (f.length) o.push(["Short to ground through " + f.join(", ") + " - fuse will blow", R]);
else if (N.short) o.push(["Battery loop: sources conflict (wrong series/parallel wiring, or batteries of different voltage in parallel)", R]);
}
for (const p of S.parts) {
if (S.fb[p.id]) o.push([p.lb + " BLOWN - fix the fault, then press Repair", R]);
if (S.sb[p.id]) {
const s = N.spk.find(q => q.p === p), d = C[p.t];
o.push([p.lb + (s && s.dc ? ": BURNT by DC voltage across the speaker" : d.kd === undefined ? "" : (p.t === "tw" ? ": BURNT - bass/too much power reached the tweeter" : ": BURNT - overloaded (" + d.z + "\u03a9 " + d.p + "W)")), R]);
}
}
for (const c of N.chs) if (S.prot[c.key]) { const nm = c.kind === "head" ? c.h.p.lb : c.am.p.lb; o.push([nm + " in PROTECT - " + (c.short ? "output shorted" : "load " + S.zl[c.key].toFixed(1) + "\u03a9 < " + c.min + "\u03a9"), R]); }
if (!N.short) {
for (const H of N.heads) if (!H.on) {
if (!H.hp.mem) o.push([H.p.lb + " OFF: MEM (yellow) needs constant 12V via a fuse", Y]);
else if (!H.hp.acc) o.push([H.p.lb + " OFF: ACC (orange/red) needs switched 12V (key + fuse)", Y]);
else if (!H.hp.gnd) o.push([H.p.lb + " OFF: GND not connected to chassis", Y]);
else if (H.vbad) o.push([H.p.lb + (H.vbad === 1 ? " OFF: supply too low (" + H.vs.toFixed(1) + " V, needs 8-18 V)" : " OFF: OVERVOLTAGE " + H.vhi.toFixed(1) + " V (max 18 V) - protection"), H.vbad === 2 ? R : Y]);
}
for (const A of N.amps) if (!A.on) {
if (!A.ap.vcc) o.push([A.p.lb + " OFF: 12V+ needs a thick fused wire from the battery", Y]);
else if (!A.ap.rem) o.push([A.p.lb + " OFF: REM needs 12V from the head unit REM (blue)", Y]);
else if (!A.ap.gnd) o.push([A.p.lb + " OFF: GND not connected to chassis", Y]);
else if (A.vbad) o.push([A.p.lb + (A.vbad === 1 ? " OFF: supply too low (" + A.vs.toFixed(1) + " V, needs 8-18 V)" : " OFF: OVERVOLTAGE " + A.vs.toFixed(1) + " V (max 18 V) - protection"), A.vbad === 2 ? R : Y]);
}
for (const F of N.filts) if (!F.on) o.push([F.p.lb + (F.vbad ? (F.vbad === 1 ? " OFF: supply too low (" + F.vs.toFixed(1) + " V)" : " OFF: OVERVOLTAGE " + F.vs.toFixed(1) + " V (max 18 V)") : " OFF: needs fused 12V and ground"), F.vbad === 2 ? R : Y]);
}
for (const L of N.unfused) o.push(["WARNING: " + L.p.lb + " power input is UNFUSED - add a fuse at the battery", Y]);
for (const A of N.amps) {
if (A.on && A.fromRem) o.push([A.p.lb + ": 12V+ fed from head REM (only ~300mA) - use a fused battery wire", R]);
if (A.insSpk) o.push([A.p.lb + ": input connected to a speaker output - use PRE OUT (RCA)", Y]);
if (A.on) for (const c of N.chs) if (c.am === A && !c.ins.some(k => k)) o.push([A.p.lb + " CH" + (A.d.chs.length > 1 ? (N.chs.filter(q => q.am === A).indexOf(c) + 1) : "") + ": no signal on its input", Y]);
if (A.on && N.chs.filter(c => c.am === A).every(c => !c.sp.length)) o.push([A.p.lb + ": no speakers connected", Y]);
}
for (const H of N.heads) {
if (H.on && ((H.d.radio || H.p.pr.src >= 0.5)) && !H.antOk) {
if (!H.ant) o.push([H.p.lb + " radio: connect ANT IN to an antenna RF output", Y]);
else if (!H.antPow) o.push([H.p.lb + " radio: antenna needs 12V from head ANT/REM", Y]);
else if (!H.antGnd) o.push([H.p.lb + " radio: antenna GND not connected", Y]);
}
if (H.on && N.chs.filter(c => c.h === H).every(c => !c.sp.length) && !H.d.pre.length) o.push([H.p.lb + ": no speakers connected", Y]);
}
for (const c of N.chs) for (const e of c.sp) {
if (e.s.t === "tw" && !e.el.some(i => N.el[i].kind === "cap")) o.push([e.s.lb + ": tweeter without series capacitor - bass will destroy it", Y]);
if (e.pol < 0) o.push([e.s.lb + ": polarity reversed (+ and \u2212 swapped)", Y]);
}
if (N.badWire) o.push(["Wire " + N.badWire.a.p.lb + "-" + N.badWire.b.p.lb + ": audio terminal wired to power/ground", R]);
const gqs = S.gq || {}, xts = S.xt || {};
if (P.eng >= 0.5) for (const A of N.amps) if (A.on) {
if ((gqs[A.p.id] || 0) > 0.4) o.push([A.p.lb + ": weak ground adds whine - bare metal, thicker cable, shorter run", Y]);
if ((xts[A.p.id] || 0) > 0.5 && !A.p.pr.rca) o.push([A.p.lb + ": signal cable runs beside a power cable - move it away or use shielded RCA", Y]);
}
for (const A of N.amps) if (A.on && A.loop && !A.p.pr.lift) o.push([A.p.lb + ": ground loop hum - ground at one point, use Ground lift or an isolator", Y]);
for (const A of N.amps) if (A.on && A.p.pr.gain > 1.5 && !A.p.pr.gate) o.push([A.p.lb + ": high gain adds hiss - lower the gain or turn on the noise gate", Y]);
if (!o.length) { const n = N.spk.filter(s => (S.spp[s.p.id] || 0) > 0.01).length; o.push(["System OK - " + n + " speaker(s) playing", G]); }
return o;
},
// ================================================================ TOOLBAR / PANEL (Win95)
_tbItems(S, P, kt) {
const U = S.ui, it = [], W = l => Math.max(44, l.length * 6.6 + 20) * kt;
const B = (label, fn, act, tip, w) => it.push({ label, fn, act, tip, w: w || W(label) });
it.push({ title: "Car Audio Lab", w: 104 * kt });
it.push({ cap: "Example:", w: 52 * kt });
this._EX.forEach((n, i) => B(S.cfm === i ? "Discard changes?" : n, () => this._pick(S, i), U.preset === i && S.cfm !== i,
S.cfm === i ? "Click again to throw away your changes and load this example" : "Load the example circuit: " + n));
it.push({ gap: 10 * kt });
B("Undo", () => this._undoAct(S), false, "Undo the last change (Ctrl+Z)");
B("Redo", () => this._redoAct(S), false, "Redo (Ctrl+Y or Ctrl+Shift+Z)");
B("Repair", () => this._repair(S), false, "Replace blown fuses and burnt speakers");
it.push({ gap: 10 * kt });
B("Save", () => this._save(S), false, "Save this circuit in the browser");
B("Load", () => this._loadSave(S), false, "Load the circuit saved in the browser");
B("PNG", () => this._png(S), false, "Export the current view as a PNG image");
it.push({ gap: 10 * kt });
B(S.paused ? "\u25B6 Play" : "|| Pause", () => { S.paused = !S.paused; }, S.paused, "Pause or resume the simulation");
B(">| Step", () => { S.paused = true; S.stepN = 500; }, false, "Advance the simulation by 10 ms (pauses first)");
it.push({ gap: 10 * kt });
B("Key: " + (U.ign >= 0.5 ? "ON" : "OFF"), () => { U.ign = U.ign >= 0.5 ? 0 : 1; }, U.ign >= 0.5, "Ignition key. ON gives switched 12 V to the ACC wire through the key switch");
B("Engine: " + (U.eng >= 0.5 ? "RUNNING" : "OFF"), () => { U.eng = U.eng >= 0.5 ? 0 : 1; }, U.eng >= 0.5, "Engine running adds alternator whine. OFF = silent electrics");
B("\u2212", () => { U.Vcc = Math.max(9, Math.round((U.Vcc - 0.5) * 10) / 10); }, false, "Lower the car battery voltage (batteries set to 'Car' follow this)", 30 * kt);
it.push({ cap: "Car battery " + U.Vcc.toFixed(1) + " V", w: 100 * kt });
B("+", () => { U.Vcc = Math.min(15, Math.round((U.Vcc + 0.5) * 10) / 10); }, false, "Raise the car battery voltage", 30 * kt);
it.push({ gap: 10 * kt });
B(S.sndOn ? "\u266a Sound ON" : "\u266a Sound OFF", () => this._toggleSnd(S), S.sndOn, "Turn the audio output on or off");
B("?", () => { S.help = !S.help; }, S.help, "How to use this lab", 30 * kt);
return it;
},
_tbFlow(it, VW, kt) {
const rh = 26 * kt, gp = 4, pad = 6; let x = pad, y = 6;
for (const o of it) {
if (o.gap) { if (x > pad) x += o.gap; continue; }
if (x + o.w > VW - pad && x > pad) { x = pad; y += rh + gp; }
o.x = x; o.y = y; o.h = rh; x += o.w + gp;
}
return { h: Math.round(y + rh + 6) };
},
_help(S, g, ws, k) {
const lines = [
"1. Add parts tab: tap a part, then tap the workspace to place it.",
"2. Wire: tap a terminal (a dot), then another terminal. Tap empty space in between to add a bend.",
"3. Move: drag a part. Tap a part to change its settings in the Settings tab.",
"4. Remove: right-click or long-press a wire, a terminal or a part.",
"5. Cable colours: red = +12 V, black = ground, blue/white = remote, white/red = RCA left/right, speaker wires use the channel colour.",
"6. Batteries in series add up: connect + of one to \u2212 of the next, then measure the two free ends.",
"7. Several equalizers/filters can share one source, and several outputs on one wire are mixed.",
"8. Top bar: pick an example, Undo/Redo (Ctrl+Z / Ctrl+Y), Save/Load, PNG, Pause/Step, Key, Engine, battery voltage, Sound.",
"9. Tap a wire to highlight everything on the same net. The mini-map (bottom right) jumps the view.",
"10. Meters tab: oscilloscope with trigger modes and two cursors (drag the white lines). Log tab: event history."
];
const w = Math.min(ws.w - 24, 540), fs = 10.5 * k, lh = 15 * k, mc = Math.floor((w - 28) / (fs * 0.56));
const wrapped = lines.map(l => this._wrap(l, mc));
const n = wrapped.reduce((a, l) => a + l.length, 0), h = (n + 3) * lh + wrapped.length * 6 + 24;
const x = ws.x + (ws.w - w) / 2, y = ws.y + 12;
this._raised(g, x, y, w, h, this._C95.face);
this._title95(g, x, y, w, 20 * k, "How to use the lab", 12 * k);
let yy = y + 20 * k + lh + 6;
wrapped.forEach(l => { l.forEach((t, j) => this._tx(g, t, x + 14, yy + j * lh, "#000", fs, "left")); yy += l.length * lh + 6; });
this._tx(g, "Tap anywhere to close", x + 14, y + h - 12, "#404040", 10 * k, "left");
S.btn.push({ x: ws.x, y: ws.y, w: ws.w, h: ws.h, fn: () => { S.help = false; } });
},
_btnTip(S) {
for (let i = S.btnPrev.length - 1; i >= 0; i--) {
const b = S.btnPrev[i];
if (b.tip && S.mx >= b.x && S.mx <= b.x + b.w && S.my >= b.y && S.my <= b.y + b.h) return b.tip;
}
return "";
},
_cut(s, w, fs) { const m = Math.max(4, Math.floor(w / (fs * 0.56))); return s.length > m ? s.slice(0, m - 1) + "\u2026" : s; },
_wrap(s, n) {
const out = []; let cur = "";
for (const w of s.split(" ")) {
if ((cur + " " + w).trim().length > n && cur) { out.push(cur); cur = w; } else cur = (cur + " " + w).trim();
}
if (cur) out.push(cur);
return out;
},
_panel(g, S, P, N, C, pn, k, dg) {
const port = this._L.port, Pc = this._C95;
S.scRect = null;
this._raised(g, pn.x, pn.y, pn.w, pn.h, Pc.face);
const bad = dg.some(d => d[1] === Pc.bad), okS = dg.length === 1 && (dg[0][1] === Pc.ok || dg[0][1] === "#000");
const names = ["Add parts", "Settings", "Meters", "Problems", "Log"], tw = (pn.w - 8) / 5, th = Math.round(26 * k);
names.forEach((n, i) => {
const x = pn.x + 4 + i * tw, act = S.ptab === i;
this._btn95(g, x, pn.y + 4, tw - 2, th, n, act, 10.5 * k);
S.btn.push({ x, y: pn.y + 4, w: tw - 2, h: th, fn: () => { S.ptab = i; } });
if (i === 3 && !okS) { g.fillStyle = bad ? "#c00000" : "#808000"; g.beginPath(); g.arc(x + tw - 12, pn.y + 11, 4, 0, 6.2832); g.fill(); }
});
const cx0 = pn.x + 10, cw = pn.w - 20, y0 = pn.y + 4 + th + 10, bottom = pn.y + pn.h - 10;
const fs = 11 * k;
if (S.ptab === 0) {
const cols = 3, chw = (cw - (cols - 1) * 4) / cols, chh = 24 * k;
this._TABS.forEach((t, i) => this._bt(S, g, cx0 + (i % cols) * (chw + 4), y0 + Math.floor(i / cols) * (chh + 4), chw, chh, t[0], () => { S.cat = i; }, S.cat === i, 10 * k));
const yy = y0 + 2 * (chh + 4) + 8, c2 = port ? 2 : 1, iw = (cw - (c2 - 1) * 6) / c2, ih = Math.round(40 * k);
let idx = 0;
for (const id in C) {
const d = C[id];
if (d.cat !== this._TABS[S.cat][1]) continue;
const x = cx0 + (idx % c2) * (iw + 6), y = yy + Math.floor(idx / c2) * (ih + 4), act = S.tool === id;
if (act) this._sunken(g, x, y, iw, ih, "#e0e0ff");
else this._sunken(g, x, y, iw, ih, Pc.field);
this._tx(g, this._cut(d.name, iw - 16, fs), x + 8, y + ih * 0.35, "#000", fs, "left", true);
this._tx(g, this._cut(d.spec || "", iw - 16, 9 * k), x + 8, y + ih * 0.72, "#404040", 9 * k, "left");
S.btn.push({ x, y, w: iw, h: ih, fn: () => { S.tool = act ? null : id; S.pend = null; S.pts = []; } });
idx++;
}
this._tx(g, S.tool ? "Now tap the workspace to place it." : "Tap a part, then tap the workspace to place it.", cx0, bottom - 2, "#404040", 10 * k, "left");
} else if (S.ptab === 1) {
const sel = S.parts.find(p => p.id === S.sel);
if (!sel) {
this._tx(g, "No part selected", pn.x + pn.w / 2, y0 + 30 * k, "#404040", 12 * k, "center", true);
this._tx(g, "Tap or drag a part on the workspace", pn.x + pn.w / 2, y0 + 50 * k, "#808080", 11 * k);
return;
}
const d = C[sel.t], st = N.by[sel.id];
this._tx(g, this._cut(sel.lb + " \u00b7 " + d.name, cw, 12 * k), cx0, y0 + 6, "#000", 12 * k, "left", true);
if (d.spec) this._tx(g, this._cut(d.spec, cw, 10 * k), cx0, y0 + 24 * k, "#404040", 10 * k, "left");
if (st && st.on !== undefined) {
const on = st.on;
this._sunken(g, cx0, y0 + 36 * k, 78 * k, 20 * k, on ? "#c0ffc0" : "#ffc0c0");
this._tx(g, on ? "powered" : "no power", cx0 + 39 * k, y0 + 46 * k, on ? "#006000" : "#800000", 10 * k, "center", true);
}
const ry0 = y0 + 66 * k, rh = 34 * k, rb = bottom - 34 * k - 8, mx = Math.max(0, d.props.length * rh - (rb - ry0));
S.pmax = mx; S.psc = this._cl(S.psc || 0, 0, mx);
if (!d.props.length) this._tx(g, "This part has no settings.", cx0, ry0 + 12, "#808080", fs, "left");
d.props.forEach((pd, i) => {
const y = ry0 + i * rh - S.psc;
if (y < ry0 - 1 || y + rh > rb + 1) return;
this._tx(g, pd.l, cx0, y + 15 * k, "#000", fs, "left");
const bw = 26 * k, vx = cx0 + cw * 0.42, vw = cw * 0.58 - 2 * bw - 10;
this._field95(g, vx + bw + 4, y + 2, vw, 24 * k, String(this._fv(pd, sel.pr[pd.k])), fs);
this._bt(S, g, vx, y + 2, bw, 24 * k, "\u2212", () => { this._pushUndo(S); this._chg(sel, pd, -1); }, false, 14 * k);
this._bt(S, g, vx + bw + 8 + vw, y + 2, bw, 24 * k, "+", () => { this._pushUndo(S); this._chg(sel, pd, 1); }, false, 14 * k);
});
if (mx > 0) {
const tr = rb - ry0, th2 = Math.max(24, tr * (tr / (tr + mx)));
this._sunken(g, pn.x + pn.w - 9, ry0, 6, tr, "#808080");
this._raised(g, pn.x + pn.w - 9, ry0 + (tr - th2) * S.psc / mx, 6, th2, "#c0c0c0");
this._tx(g, "scroll for more \u2195", cx0 + cw, y0 + 46 * k, "#808080", 9.5 * k, "right");
}
this._bt(S, g, cx0, bottom - 34 * k, cw, 34 * k, "Delete part", () => this._delPart(S, sel), false, fs);
} else if (S.ptab === 2) {
const lab = (t, y) => this._tx(g, t, cx0, y, "#000", fs, "left", true);
const fV = v => (Math.abs(v) >= 100 ? v.toFixed(0) : Math.abs(v) >= 10 ? v.toFixed(1) : v.toFixed(2));
const fF = f => f <= 0 ? "--" : f >= 1000 ? (f / 1000).toFixed(2) + " kHz" : f.toFixed(f < 100 ? 1 : 0) + " Hz";
lab("Oscilloscope", y0 + 6);
let yy = y0 + 18;
if (N.scope) {
const pr = N.scope.pr, sh = Math.min(cw * 0.5, Math.max(60, bottom - y0 - 250 * k));
const res = this._drawScope(g, S, cx0, y0 + 18, cw, sh, N.scope);
S.scRect = { x: cx0, y: y0 + 18, w: cw, h: sh };
if (pr.trig === 2) this._bt(S, g, cx0 + cw - 66 * k, y0 - 2, 66 * k, 18 * k, "Re-arm", () => { S.scFrozen = false; S.scSnap = null; }, false, 9.5 * k);
yy = y0 + 18 + sh + 12 * k;
const lh = 12.5 * k, fm = 9 * k;
this._txM(g, ["Auto", "Normal", "Single", "Roll"][pr.trig] + " \u00b7 " + (pr.edge ? "Falling" : "Rising") + " \u00b7 CH" + (pr.src + 1) + " \u00b7 " + pr.lvl + " V \u00b7 " + pr.tb + " ms/div", cx0, yy, "#404040", fm, "left");
yy += lh;
for (const id of [1, 2]) {
if (!pr["ch" + id]) continue;
const m = res["m" + id], f = res["f" + id], col = id === 1 ? "#808000" : "#007070";
if (!m) { this._txM(g, "CH" + id + " --", cx0, yy, col, fm, "left", true); yy += lh; continue; }
this._txM(g, "CH" + id + " Vpp " + fV(m.vpp) + " Vrms " + fV(m.rms) + " Vavg " + fV(m.avg), cx0, yy, col, fm, "left", true); yy += lh;
this._txM(g, " f " + fF(f.f) + " T " + (f.T > 0 ? (f.T * 1000).toFixed(2) + " ms" : "--"), cx0, yy, col, fm, "left"); yy += lh;
}
if (res.cur) this._txM(g, "Cursors: dV1 " + (res.cur.d1 !== undefined ? fV(res.cur.d1) : "--") + " dV2 " + (res.cur.d2 !== undefined ? fV(res.cur.d2) : "--") + " V dt " + res.cur.dt.toFixed(2) + " ms", cx0, yy, "#404040", fm, "left");
else this._txM(g, "Cursors: drag the white lines on the screen", cx0, yy, "#808080", fm, "left");
yy += lh;
} else {
const sh = Math.min(cw * 0.5, Math.max(70, bottom - y0 - 130 * k));
this._sk(g, cx0, y0 + 18, cw, sh, "#0b1f14");
this._bt(S, g, cx0 + cw / 2 - 70 * k, y0 + 18 + sh / 2 - 15 * k, 140 * k, 30 * k, "Add oscilloscope", () => { S.ptab = 0; S.cat = 5; S.tool = "scope"; }, false, 10.5 * k);
yy = y0 + 18 + sh + 4 * k;
}
const my = yy + 14 * k;
lab("Multimeter", my);
this._sunken(g, cx0, my + 12, cw, 42 * k, "#a8c0a0");
if (N.dmm) { const r = this._dmm(P, S, N.dmm); this._txM(g, ["DC V", "AC V", "CONT", "OHMS"][N.dmm.pr.mode] + " " + r.t, cx0 + cw / 2, my + 12 + 21 * k, "#001800", 15 * k, "center", true); }
else this._bt(S, g, cx0 + cw / 2 - 70 * k, my + 12 + 6 * k, 140 * k, 30 * k, "Add multimeter", () => { S.ptab = 0; S.cat = 5; S.tool = "dmm"; }, false, 10.5 * k);
} else if (S.ptab === 3) {
this._tx(g, "Key " + (P.ign >= 0.5 ? "ON" : "OFF") + " \u00b7 Supply " + N.vsys.toFixed(1) + " V \u00b7 Heads " + N.heads.filter(h => h.on).length + "/" + N.heads.length + " \u00b7 Amps " + N.amps.filter(a => a.on).length + "/" + N.amps.length, cx0, y0 + 6, "#000", fs, "left", true);
const lg = [["#e02424", "power +12V"], ["#161616", "ground"], ["#2f7be8", "remote / RCA"], ["#ff2020", "wrong wire type"], ["#ffaa00", "level mix-up"]];
const lgh = lg.length * 16 * k + 14, lh = 16 * k, mc = Math.floor((cw - 22) / (fs * 0.56));
const nlv = Object.values(S.nl || {}), nmx = nlv.length ? Math.max(...nlv) : 0;
const ntx = nmx < 0.15 ? "low" : nmx < 0.6 ? "medium" : "high";
this._tx(g, "Noise level: " + ntx, cx0, y0 + 26 * k, nmx < 0.15 ? "#006000" : nmx < 0.6 ? "#808000" : "#800000", fs, "left", true);
let yy = y0 + 48 * k;
const lim = bottom - lgh - 4;
for (let i = 0; i < dg.length; i++) {
const ln = this._wrap(dg[i][0], mc);
if (yy + ln.length * lh > lim) { this._tx(g, "+ " + (dg.length - i) + " more", cx0, yy + 6, "#404040", 10 * k, "left"); break; }
g.fillStyle = dg[i][1] === Pc.bad ? "#c00000" : dg[i][1] === Pc.warn ? "#808000" : "#008000";
g.beginPath(); g.arc(cx0 + 5, yy + 7 * k, 4, 0, 6.2832); g.fill();
ln.forEach((t, j) => this._tx(g, t, cx0 + 16, yy + 7 * k + j * lh, "#000", 10.5 * k, "left"));
yy += ln.length * lh + 6;
}
lg.forEach((l, i) => {
const y = bottom - lgh + 10 + i * lh;
this._ln(g, cx0, y, cx0 + 26, y, l[0], 3.5); this._tx(g, l[1], cx0 + 34, y, "#000", 10 * k, "left");
});
} else {
const lh = 14 * k;
this._tx(g, "Event log (" + S.log.length + ")", cx0, y0 + 6, "#000", fs, "left", true);
this._bt(S, g, cx0 + cw - 60 * k, y0 - 2, 60 * k, 18 * k, "Clear", () => { S.log.length = 0; }, false, 9.5 * k);
const maxL = Math.max(1, Math.floor((bottom - y0 - 26 * k) / lh));
if (!S.log.length) this._tx(g, "No events yet.", cx0, y0 + 30 * k, "#808080", 10.5 * k, "left");
for (let i = 0; i < maxL && i < S.log.length; i++) {
const e = S.log[S.log.length - 1 - i], col = e.kind === "r" ? "#800000" : e.kind === "g" ? "#006000" : e.kind === "y" ? "#707000" : "#000";
this._tx(g, this._cut("[" + e.t.toFixed(2) + "s] " + e.msg, cw, 10 * k), cx0, y0 + 30 * k + i * lh, col, 10 * k, "left");
}
}
},
// ================================================================ MAIN DRAW
draw(g, W, H, P, S) {
P = S.ui;
this._tick(P, S);
const N = S.net, C = this._cat(), Pc = this._C95;
S.W = W; S.H = H; S.fr++;
const port = H > W, k = port ? 1.25 : 1, kt = port ? 1.1 : 1;
let VW, VH;
if (port) { VW = 540; VH = Math.max(800, 540 * H / W); } else { VH = 720; VW = Math.max(900, 720 * W / H); }
const sc = Math.min(W / VW, H / VH);
S.s = sc; S.ox = (W - VW * sc) / 2; S.oy = (H - VH * sc) / 2;
const items = this._tbItems(S, P, kt), tb = this._tbFlow(items, VW, kt).h;
let ws, pn;
if (port) { const ph = Math.round(VH * 0.44); pn = { x: 0, y: VH - ph, w: VW, h: ph }; ws = { x: 0, y: tb, w: VW, h: VH - ph - tb }; }
else { const pw = Math.min(380, Math.round(VW * 0.3)); pn = { x: VW - pw, y: tb, w: pw, h: VH - tb }; ws = { x: 0, y: tb, w: VW - pw, h: VH - tb }; }
this._L = { ws, pn, k, port };
if (S.port !== port) { S.port = port; S.fitReq = true; }
if (S.fitReq) { S.fitReq = false; this._fit(S); }
this._bind(g, S);
this._audio(P, S);
S.btnPrev = S.btn; S.btn = [];
if (S.mt > 0) S.mt--;
if (S.cfmT > 0) { S.cfmT--; if (!S.cfmT) S.cfm = -1; }
if (S.drag) this._dragRoutes(S);
else if (S.rsig === null || S.rt.length !== S.wires.length) this._routeAll(S);
this._gq(S);
const wsw = this._w(S, S.mx, S.my); S.wx = wsw[0]; S.wy = wsw[1];
const hov = this._inWs(S.mx, S.my) ? this._hit(S, S.wx, S.wy) : null;
let wa = -1;
if (!hov && !S.pend && this._inWs(S.mx, S.my)) {
const hk = S.mx + "," + S.my + "," + S.rv + "," + S.z + "," + S.vx + "," + S.vy + "," + S.wires.length;
if (hk !== S.hwk) { S.hwk = hk; S.hwa = this._wireAt(S, S.wx, S.wy); }
wa = S.hwa;
}
S.hw = wa;
S.flg = { antOk: N.heads.some(H => H.antOk), headOn: N.heads.some(H => H.on), ampOn: N.amps.some(q => q.on) };
const dg = this._diag(P, S);
const vx0 = 176 + S.vx, vy0 = 28 + S.vy, vx1 = vx0 + ws.w / S.z, vy1 = vy0 + ws.h / S.z;
g.save();
g.fillStyle = "#008080"; g.fillRect(0, 0, W, H);
g.translate(S.ox, S.oy); g.scale(sc, sc);
// toolbar (Win95)
this._raised(g, 0, 0, VW, tb, Pc.face);
for (const o of items) {
if (o.gap) continue;
if (o.title) this._title95(g, o.x - 4, o.y, o.w + 8, o.h, o.title, 12 * kt);
else if (o.cap) this._tx(g, o.cap, o.x + (o.cap.indexOf("Car") === 0 ? o.w / 2 : 0), o.y + o.h / 2, "#000", 11 * kt, o.cap.indexOf("Car") === 0 ? "center" : "left", o.cap.indexOf("Car") === 0);
else this._bt(S, g, o.x, o.y, o.w, o.h, o.label, o.fn, o.act, 10.5 * kt, o.tip);
}
// workspace
this._sunken(g, ws.x, ws.y, ws.w, ws.h, "#ffffff");
g.save(); g.beginPath(); g.rect(ws.x + 2, ws.y + 2, ws.w - 4, ws.h - 4); g.clip();
g.translate(ws.x, ws.y); g.scale(S.z, S.z); g.translate(-176 - S.vx, -28 - S.vy);
{
const st = S.z < 0.5 ? 40 : 20;
const gx0 = Math.max(180, Math.ceil((176 + S.vx) / st) * st), gx1 = Math.min(1826, 176 + S.vx + ws.w / S.z);
const gy0 = Math.max(40, Math.ceil((28 + S.vy) / st) * st), gy1 = Math.min(1158, 28 + S.vy + ws.h / S.z);
g.fillStyle = "#c0c0c0";
for (let gx = gx0; gx < gx1; gx += st) for (let gy = gy0; gy < gy1; gy += st) g.fillRect(gx - 0.5, gy - 0.5, 1, 1);
g.strokeStyle = "#a0a0a0"; g.lineWidth = 1; g.setLineDash([4, 4]); g.strokeRect(176, 28, 1650, 1130); g.setLineDash([]);
}
for (const p of S.parts) {
const d = C[p.t];
if (p.x > vx1 + 20 || p.x + d.w < vx0 - 20 || p.y > vy1 + 20 || p.y + d.h + 30 < vy0 - 20) continue;
this._part(g, p, P, S);
}
this._drawWires(g, S, P, vx0, vy0, vx1, vy1);
const deg = S.deg || {};
for (const t of S.tl) {
if (t.hid) continue;
if (t.x < vx0 - 20 || t.x > vx1 + 20 || t.y < vy0 - 20 || t.y > vy1 + 20) continue;
const tc = this._tcol(t), cn = deg[t.id];
if (t.k === "mateA" || t.k === "mateB") {
g.save(); g.fillStyle = cn ? "#000" : "#808080"; g.fillRect(t.x - 9, t.y - 5, 18, 10); g.strokeStyle = "#ffffff"; g.lineWidth = 1; g.strokeRect(t.x - 9, t.y - 5, 18, 10); g.restore();
} else if (t.k.indexOf("rca") === 0) {
this._circ(g, t.x, t.y, 6, "#404040", false);
g.save(); g.fillStyle = tc ? tc.c : "#808080"; g.beginPath(); g.arc(t.x, t.y, 3.4, 0, 6.2832); g.fill(); g.restore();
} else {
const r = (t.k === "cap" || t.k === "ter") ? 3.5 : 4.5;
g.save(); g.globalAlpha = cn ? 1 : 0.8; g.fillStyle = tc ? tc.c : "#808080";
g.beginPath(); g.arc(t.x, t.y, r, 0, 6.2832); g.fill(); g.lineWidth = 1; g.strokeStyle = "#000"; g.stroke(); g.restore();
}
if (t.lab) {
if (t.pos === "r") this._tx(g, t.lab, t.x + 9, t.y, "#000", 9, "left");
else if (t.pos === "l") this._tx(g, t.lab, t.x - 9, t.y, "#000", 9, "right");
else if (t.pos === "u") this._tx(g, t.lab, t.x, t.y - 10, "#000", 9);
else if (t.pos === "d") this._tx(g, t.lab, t.x, t.y + 11, "#000", 9);
else if (t.pos === "v") this._tv(g, t.lab, t.x + 3, t.y - 8, "#000", 9);
}
}
if (hov) this._circ(g, hov.x, hov.y, 9, "#000080", false);
if (S.tool && this._inWs(S.mx, S.my) && !S.pend) {
const d = C[S.tool];
g.save(); g.setLineDash([4, 3]); g.strokeStyle = "#000080"; g.lineWidth = 1.5;
g.strokeRect(this._cl(this._snap(S.wx - d.w / 2), 178, 1822 - d.w), this._cl(this._snap(S.wy - d.h / 2), 30, 1154 - d.h), d.w, d.h); g.restore();
}
if (S.pend && S.tm[S.pend]) {
const p = S.tm[S.pend];
this._circ(g, p.x, p.y, 9, "#000080", false);
let endp = null;
if (hov && hov.id !== S.pend) endp = [hov.x, hov.y];
else if (this._inWs(S.mx, S.my)) endp = [this._cl(this._snap(S.wx), 178, 1822), this._cl(this._snap(S.wy), 30, 1154)];
const list = [[p.x, p.y]].concat(S.pts);
if (endp) list.push(endp);
if (list.length > 1) {
const pl = this._elbow(list);
g.save(); g.setLineDash([4, 3]); g.lineJoin = "round"; g.strokeStyle = "#000080"; g.lineWidth = 1.8;
g.beginPath(); g.moveTo(pl[0][0], pl[0][1]);
for (let i = 1; i < pl.length; i++) g.lineTo(pl[i][0], pl[i][1]);
g.stroke(); g.restore();
}
for (const q of S.pts) { g.save(); g.fillStyle = "#000080"; g.fillRect(q[0] - 3, q[1] - 3, 6, 6); g.restore(); }
}
g.restore();
// status bar (Win95)
const sh = 24 * k, sy = ws.y + ws.h - sh;
this._raised(g, ws.x, sy, ws.w, sh, Pc.face);
const btip = this._btnTip(S);
let hint;
if (S.mt > 0) hint = S.msg;
else if (btip) hint = btip;
else if (hov) hint = hov.tip;
else if (S.pend) hint = "Tap empty space for a bend, tap a terminal to finish. Right-click / long-press cancels.";
else if (S.tool) hint = "Tap the workspace to place: " + C[S.tool].name;
else if (S.hw >= 0) hint = "Click: highlight this net. Right-click / long-press removes this wire.";
else hint = "Tap a terminal, then another terminal to wire. Drag parts to move. Long-press deletes. Tap ? for help.";
const bad = dg.some(d => d[1] === Pc.bad), okS = dg.length === 1 && (dg[0][1] === Pc.ok || dg[0][1] === "#000");
const chipT = okS ? "System OK" : dg.length + (bad ? " issue(s)" : " warning(s)"), chipW = (chipT.length * 6.4 + 30) * k;
this._tx(g, this._cut(hint, ws.w - chipW - 22, 10.5 * k), 8, sy + sh / 2, S.mt > 0 ? "#800000" : "#000", 10.5 * k, "left");
this._chip95(g, ws.x + ws.w - chipW - 6, sy + 3, chipW, sh - 6, chipT, okS ? "#008000" : bad ? "#c00000" : "#808000", 10 * k);
S.btn.push({ x: ws.x + ws.w - chipW - 6, y: sy, w: chipW + 6, h: sh, fn: () => { S.ptab = 3; } });
// mini-map
const mw = 130 * k, mh = mw * 1130 / 1650, mx0 = ws.x + ws.w - mw - 8, my0 = sy - mh - 6;
S.mm = { x: mx0, y: my0, w: mw, h: mh };
{
this._sunken(g, mx0, my0, mw, mh, "#ffffff");
const kx = (mw - 4) / 1650, ky = (mh - 4) / 1130, ox = mx0 + 2 - 176 * kx, oy = my0 + 2 - 28 * ky;
g.save(); g.beginPath(); g.rect(mx0 + 2, my0 + 2, mw - 4, mh - 4); g.clip();
for (const p of S.parts) {
const d = C[p.t];
g.fillStyle = S.sel === p.id ? "#000080" : (S.sb[p.id] || S.fb[p.id]) ? "#c00000" : "#808080";
g.fillRect(ox + p.x * kx, oy + p.y * ky, Math.max(2, d.w * kx), Math.max(2, d.h * ky));
}
g.strokeStyle = "#c00000"; g.lineWidth = 1.2;
g.strokeRect(ox + vx0 * kx, oy + vy0 * ky, (vx1 - vx0) * kx, (vy1 - vy0) * ky);
g.restore();
S.btn.push({ x: mx0, y: my0, w: mw, h: mh, tip: "Mini-map: click to move the view", fn: (cx, cy) => {
const wx = 176 + (cx - mx0 - 2) / kx, wy = 28 + (cy - my0 - 2) / ky;
S.vx = wx - 176 - ws.w / S.z / 2; S.vy = wy - 28 - ws.h / S.z / 2; this._clampView(S);
} });
}
const zoff = mh + 10;
const bw = 30 * k, bx = ws.x + ws.w - bw - 8;
this._bt(S, g, bx, sy - 3 * bw - 18 - zoff, bw, bw, "+", () => this._zoom(S, 1.25), false, 14 * k);
this._bt(S, g, bx, sy - 2 * bw - 12 - zoff, bw, bw, "\u2212", () => this._zoom(S, 1 / 1.25), false, 14 * k);
this._bt(S, g, bx, sy - bw - 6 - zoff, bw, bw, "Fit", () => this._fit(S), false, 10 * k);
this._txM(g, Math.round(S.z * 100) + "%", bx + bw / 2, sy - 3 * bw - 26 - zoff, "#000", 10 * k, "center", true);
if (S.rpend > 0) this._tx(g, "routing " + S.rpend + " cable(s)\u2026", ws.x + ws.w / 2, ws.y + 14, "#404040", 10 * k, "center");
if (S.paused) this._tx(g, "PAUSED", ws.x + 12, ws.y + 14, "#c00000", 11 * k, "left", true);
if (!S.parts.length) {
this._tx(g, "Empty workbench", ws.x + ws.w / 2, ws.y + ws.h / 2 - 12 * k, "#808080", 15 * k, "center", true);
this._tx(g, "Open the Add parts tab, pick a part, then tap here.", ws.x + ws.w / 2, ws.y + ws.h / 2 + 10 * k, "#808080", 11 * k);
}
this._panel(g, S, P, N, C, pn, k, dg);
if (S.help) this._help(S, g, ws, k);
g.restore();
},
// ================================================================ SOUND
_audioInit(S) {
if (S.au || S.auErr) return;
const AC = typeof window !== "undefined" && (window.AudioContext || window.webkitAudioContext);
if (!AC) { S.auErr = true; return; }
let ctx;
try { ctx = new AC(); } catch (e) { S.auErr = true; return; }
const mixAll = ctx.createGain(), sh = ctx.createWaveShaper();
const comp = ctx.createDynamicsCompressor(), master = ctx.createGain();
const mkc = f => { const c = new Float32Array(1024); for (let i = 0; i < 1024; i++) c[i] = f(i / 511.5 - 1); return c; };
const soft = mkc(x => Math.tanh(x * 1.1)), hard = mkc(x => Math.max(-1, Math.min(1, x * 5)));
sh.curve = soft;
mixAll.connect(sh); sh.connect(comp); comp.connect(master); master.connect(ctx.destination);
master.gain.value = 0;
const bus = [0, 1, 2].map(() => ctx.createGain());
const nb = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate);
const d = nb.getChannelData(0);
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
const tb = [100, 1000, 5000].map(f => { const o = ctx.createOscillator(); o.type = "sine"; o.frequency.value = f; const gg = ctx.createGain(); gg.gain.value = 0.5; o.connect(gg); o.start(); return gg; });
const nzb = [0, 1, 2].map(() => ctx.createGain());
const wo = ctx.createOscillator(); wo.type = "sawtooth"; wo.frequency.value = 600; wo.connect(nzb[0]); wo.start();
const ho = ctx.createOscillator(); ho.type = "sine"; ho.frequency.value = 50; ho.connect(nzb[1]); ho.start();
const hs = ctx.createBufferSource(); hs.buffer = nb; hs.loop = true;
const hf = ctx.createBiquadFilter(); hf.type = "highpass"; hf.frequency.value = 3000; hs.connect(hf); hf.connect(nzb[2]); hs.start();
const au = { ctx, master, sh, soft, hard, hardOn: false, bus, mixAll, sp: {}, st: {}, sn: {}, tb, nzb, wo, nb, n: 0, rad: 0, next: ctx.currentTime + 0.1 };
S.au = au;
au.timer = setInterval(() => this._seq(S), 40);
const res = () => { if (S.sndOn && ctx.state === "suspended") ctx.resume().catch(() => {}); };
document.addEventListener("pointerdown", res);
document.addEventListener("keydown", res);
res();
},
_spkG(au, id, pan) {
if (au.sp[id]) return au.sp[id];
const ctx = au.ctx, mix = ctx.createGain();
const g = au.bus.map(b => { const x = ctx.createGain(); x.gain.value = 0; b.connect(x); x.connect(mix); return x; });
if (ctx.createStereoPanner) { const pn = ctx.createStereoPanner(); pn.pan.value = pan; mix.connect(pn); pn.connect(au.mixAll); }
else mix.connect(au.mixAll);
au.st[id] = au.tb.map(b => { const x = ctx.createGain(); x.gain.value = 0; b.connect(x); x.connect(mix); return x; });
au.sn[id] = au.nzb.map(b => { const x = ctx.createGain(); x.gain.value = 0; b.connect(x); x.connect(mix); return x; });
au.sp[id] = g;
return g;
},
_toggleSnd(S) {
S.ui.snd = S.ui.snd >= 0.5 ? 0 : 1;
S.lsnd = S.ui.snd; S.sndOn = S.ui.snd >= 0.5;
if (S.sndOn) { this._audioInit(S); if (S.au && S.au.ctx.state === "suspended") S.au.ctx.resume().catch(() => {}); }
},
_seq(S) {
const au = S.au;
if (!au) return;
const ctx = au.ctx;
if (!S.sndOn || S.paused || ctx.state !== "running") { au.next = Math.max(au.next, ctx.currentTime + 0.05); return; }
const spd = 60 / 112 / 4;
if (au.next < ctx.currentTime) au.next = ctx.currentTime + 0.05;
while (au.next < ctx.currentTime + 0.15) { this._note(au, au.n, au.next); au.n++; au.next += spd; }
},
_note(au, n, t) {
const ctx = au.ctx, st = n % 16, bar = (n >> 4) % 4;
const env = (bus, peak, a, d) => {
const g = ctx.createGain();
g.gain.setValueAtTime(0.0001, t);
g.gain.exponentialRampToValueAtTime(peak, t + a);
g.gain.exponentialRampToValueAtTime(0.0001, t + a + d);
g.connect(au.bus[bus]);
return g;
};
const osc = (type, f, dest, len) => { const o = ctx.createOscillator(); o.type = type; o.frequency.setValueAtTime(f, t); o.connect(dest); o.start(t); o.stop(t + len); return o; };
const noise = (ftype, f, q, dest, len) => {
const s = ctx.createBufferSource(); s.buffer = au.nb;
const fl = ctx.createBiquadFilter(); fl.type = ftype; fl.frequency.value = f; fl.Q.value = q;
s.connect(fl); fl.connect(dest); s.start(t); s.stop(t + len);
};
if (au.rad === 2) { [120, 1200, 6000].forEach((f, b) => noise("bandpass", f, 0.5, env(b, 0.35, 0.005, 0.12), 0.2)); return; }
if (st % 4 === 0 || st === 10) {
const o = ctx.createOscillator(); o.type = "sine";
o.frequency.setValueAtTime(130, t); o.frequency.exponentialRampToValueAtTime(42, t + 0.12);
o.connect(env(0, 1, 0.003, 0.3)); o.start(t); o.stop(t + 0.4);
}
if (st === 0 || st === 3 || st === 6 || st === 8 || st === 11 || st === 14) {
const f = this._roots[bar] * ((st === 6 || st === 14) ? 2 : 1);
const lp = ctx.createBiquadFilter(); lp.type = "lowpass"; lp.frequency.value = 220; lp.Q.value = 3;
lp.connect(env(0, 0.55, 0.01, 0.22)); osc("sawtooth", f, lp, 0.3);
}
if (st % 2 === 0) {
const f = this._arps[bar][[0, 1, 2, 1, 0, 2, 1, 2][(st >> 1) % 8]];
const bp = ctx.createBiquadFilter(); bp.type = "bandpass"; bp.frequency.value = 1100; bp.Q.value = 0.8;
bp.connect(env(1, 0.3, 0.005, 0.2)); osc("sawtooth", f, bp, 0.3);
}
if (st === 4 || st === 12) noise("bandpass", 1800, 0.8, env(1, 0.5, 0.002, 0.12), 0.2);
noise("highpass", 6500, 0.7, env(2, st % 2 ? 0.35 : 0.15, 0.002, st === 6 ? 0.18 : (st % 2 ? 0.05 : 0.03)), 0.25);
if (st === 0 || st === 8) osc("sine", this._bells[bar], env(2, 0.12, 0.005, 0.9), 1.1);
if (au.rad === 1) noise("highpass", 3000, 0.5, env(2, 0.05, 0.005, 0.12), 0.2);
},
_audio(P, S) {
if (S.lsnd !== P.snd) { S.lsnd = P.snd; S.sndOn = P.snd >= 0.5; }
if (S.sndOn && !S.au) this._audioInit(S);
const au = S.au;
if (!au) return;
const ctx = au.ctx, t = ctx.currentTime, C = this._cat();
if (S.sndOn && ctx.state === "suspended") ctx.resume().catch(() => {});
au.master.gain.setTargetAtTime(S.sndOn && !S.paused ? 0.5 : 0, t, 0.05);
au.rad = S.rad;
if (!S.sndOn) return;
const live = {};
au.wo.frequency.setTargetAtTime(500 + 300 * Math.sin(t * 0.7), t, 0.05);
for (const p of S.parts) {
if (C[p.t].kind !== "spk") continue;
live[p.id] = 1;
const a = S.sa[p.id], g = this._spkG(au, p.id, this._cl((p.x + 40 - 536) / 360, -1, 1));
const tg = au.st[p.id], ng = au.sn[p.id], ag = S.sg[p.id], an = S.sn[p.id];
for (let b = 0; b < 3; b++) {
const v = a ? (a[b] || 0) : 0; g[b].gain.setTargetAtTime(isFinite(v) ? v : 0, t, 0.04);
const w = ag ? (ag[b] || 0) : 0; tg[b].gain.setTargetAtTime(isFinite(w) ? w : 0, t, 0.04);
const q = an ? (an[b] || 0) * 6 : 0; ng[b].gain.setTargetAtTime(isFinite(q) ? q : 0, t, 0.04);
}
}
for (const id in au.sp) if (!live[id]) [au.sp[id], au.st[id], au.sn[id]].forEach(arr => arr.forEach(x => x.gain.setTargetAtTime(0, t, 0.04)));
let hard = false;
for (const k in S.clip) if (S.clip[k] > 0) hard = true;
if (hard !== au.hardOn) { au.hardOn = hard; au.sh.curve = hard ? au.hard : au.soft; }
},
_elbow(list) {
const out = [list[0].slice()];
let pd = null;
for (let i = 1; i < list.length; i++) {
const p = out[out.length - 1], q = list[i];
if (p[0] === q[0] && p[1] === q[1]) continue;
if (p[0] === q[0]) { out.push(q.slice()); pd = "v"; }
else if (p[1] === q[1]) { out.push(q.slice()); pd = "h"; }
else { const hf = pd !== "h"; out.push(hf ? [q[0], p[1]] : [p[0], q[1]]); out.push(q.slice()); pd = hf ? "v" : "h"; }
}
if (out.length < 3) return out;
const r = [out[0]];
for (let i = 1; i < out.length - 1; i++) {
const a = r[r.length - 1], b = out[i], c = out[i + 1];
if ((a[0] === b[0] && b[0] === c[0]) || (a[1] === b[1] && b[1] === c[1])) continue;
r.push(b);
}
r.push(out[out.length - 1]);
return r;
},
_segDist(px, py, a, b) {
const dx = b[0] - a[0], dy = b[1] - a[1], l2 = dx * dx + dy * dy;
let t = l2 ? ((px - a[0]) * dx + (py - a[1]) * dy) / l2 : 0;
t = t < 0 ? 0 : t > 1 ? 1 : t;
const qx = a[0] + t * dx, qy = a[1] + t * dy;
return Math.sqrt((px - qx) * (px - qx) + (py - qy) * (py - qy));
},
scope: {
span: P => 0.03, unit: "V",
traces: [
{ label: "CH1", color: "#d8d800", get: S => S.sc ? S.sc.c1 : 0 },
{ label: "CH2", color: "#00b8b8", get: S => S.sc ? S.sc.c2 : 0 }
]
}
});