feat(pcb): ngspice 회로 시뮬레이션 — 부품·넷→SPICE 넷리스트, 동작점/시간 응답/주파수 응답, R·C·L·D·LED·BJT·MOSFET + 555·연산증폭기·78xx 거동 모델, 파형 차트·부품 전류 표
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7f09db757e
commit
371e1fd9ec
4 files changed
+466
-10
No files matched your search
@@ -4,6 +4,7 @@ import { buildDsn, parseSes, validateProject } from '../../tools/pcb/dsn';
|
||||
import { freeroutingStatus, runFreerouting } from '../../tools/pcb/freerouting';
|
||||
import { buildGcode } from '../../tools/pcb/gcode';
|
||||
import { findJumpers, jumperList } from '../../tools/pcb/jumpers';
|
||||
import { simulate, type SimSpec } from '../../tools/pcb/spice';
|
||||
import { footprintsByFilter, kicadFootprint, kicadStatus, loadFpIndex, loadSymIndex, searchFootprints, searchSymbols, symbolDetail } from '../../tools/pcb/kicadlib';
|
||||
import { DEFAULT_RULES, type PcbProject, type Routed } from '../../tools/pcb/types';
|
||||
|
||||
@@ -73,6 +74,25 @@ export function registerPcbRoutes(app: express.Application, requireGatewayAuth:
|
||||
}
|
||||
});
|
||||
|
||||
// 회로 시뮬레이션(ngspice): 프로젝트의 부품·넷 → SPICE 넷리스트 → 동작점/시간 응답/주파수 응답
|
||||
app.post('/api/pcb/simulate', requireGatewayAuth, async (req, res) => {
|
||||
try {
|
||||
const project = normalize(req.body);
|
||||
const rawParts: any[] = Array.isArray(req.body?.project?.parts) ? req.body.project.parts : [];
|
||||
const parts = project.parts.map((p, i) => {
|
||||
const r = rawParts[i] || {};
|
||||
const pn: Record<string, string> = {};
|
||||
if (r.pinNames && typeof r.pinNames === 'object') for (const [k, v] of Object.entries(r.pinNames).slice(0, 200)) pn[String(k).slice(0, 12)] = String(v).slice(0, 24);
|
||||
return { ...p, sym: typeof r.sym === 'string' ? r.sym.slice(0, 120) : undefined, pinNames: pn };
|
||||
});
|
||||
const spec = req.body?.sim as SimSpec;
|
||||
if (!spec || !spec.analysis) { res.status(400).json({ error: '시뮬레이션 설정이 없습니다.' }); return; }
|
||||
res.json(await simulate({ ...project, parts }, spec));
|
||||
} catch (err: any) {
|
||||
res.status(400).json({ error: String(err?.message || err) });
|
||||
}
|
||||
});
|
||||
|
||||
// 밀링 G-code: 프로젝트 + 배선 결과 → 격리/드릴/외곽 파일
|
||||
app.post('/api/pcb/gcode', requireGatewayAuth, (req, res) => {
|
||||
try {
|
||||
|
||||
@@ -191,7 +191,7 @@ setFootprintResolver(kicadFootprint);
|
||||
// ── 심볼 상세 (핀 이름·종류, SPICE 정보) ──────────────────────────────────────────
|
||||
export interface SymbolDetail {
|
||||
id: string; ref: string; value: string; footprint: string; description: string; datasheet: string; filters: string;
|
||||
pins: { n: string; name: string; type: string }[];
|
||||
pins: { n: string; name: string; type: string; unit: number }[];
|
||||
sim: { device?: string; type?: string; pins?: string; params?: string; library?: string; name?: string };
|
||||
}
|
||||
function readSym(lib: string, name: string): Node[] | null {
|
||||
@@ -209,13 +209,15 @@ export function symbolDetail(lib: string, name: string): SymbolDetail | null {
|
||||
const base = ext ? readSym(lib, String(ext)) : null;
|
||||
const holder = base || sym; // 파생 심볼의 핀은 부모에 있다
|
||||
const pins: SymbolDetail['pins'] = [];
|
||||
const walk = (n: Node[]) => {
|
||||
// 서브심볼 이름이 "<심볼>_<유닛>_<스타일>" 이다. 유닛 0 은 공통, 1.. 은 증폭기 하나하나(LM358 등).
|
||||
const walk = (n: Node[], unit: number) => {
|
||||
for (const c of n) if (isList(c)) {
|
||||
if (c[0] === 'pin') pins.push({ type: String(c[1]), name: String(kids(c, 'name')[0]?.[1] ?? ''), n: String(kids(c, 'number')[0]?.[1] ?? '') });
|
||||
else walk(c);
|
||||
if (c[0] === 'pin') pins.push({ type: String(c[1]), name: String(kids(c, 'name')[0]?.[1] ?? ''), n: String(kids(c, 'number')[0]?.[1] ?? ''), unit });
|
||||
else if (c[0] === 'symbol') { const m = String(c[1]).match(/_(\d+)_\d+$/); walk(c, m ? Number(m[1]) : unit); }
|
||||
else walk(c, unit);
|
||||
}
|
||||
};
|
||||
walk(holder);
|
||||
walk(holder, 0);
|
||||
const seen = new Set<string>();
|
||||
const uniq = pins.filter(p => p.n && !seen.has(p.n) && seen.add(p.n)).sort((a, b) => (Number(a.n) || 1e9) - (Number(b.n) || 1e9) || a.n.localeCompare(b.n));
|
||||
const bp: Record<string, string> = {};
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
// PCB 프로젝트 → SPICE 넷리스트 → ngspice(헤드리스) → 파형/동작점.
|
||||
// 사용자 입력은 숫자·정규화한 이름만 넷리스트에 넣는다(.control 의 shell 등 주입 방지: 원문 문자열을 그대로 쓰지 않음).
|
||||
import { spawn } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { placedPads } from './footprints';
|
||||
import type { PcbProject } from './types';
|
||||
import { symbolDetail, type SymbolDetail } from './kicadlib';
|
||||
|
||||
export interface SimSource { type: 'dc' | 'pulse' | 'sin' | 'ac'; pos: string; neg?: string; dc?: number; v1?: number; v2?: number; td?: number; tr?: number; tf?: number; pw?: number; per?: number; off?: number; amp?: number; freq?: number; mag?: number }
|
||||
export interface SimSpec {
|
||||
gnd: string; sources: SimSource[]; probes: string[];
|
||||
analysis: { type: 'op' | 'tran' | 'ac'; stop?: number | string; step?: number | string; fstart?: number; fstop?: number; ppd?: number };
|
||||
}
|
||||
export interface SimPart { ref: string; fp: string; value?: string; sym?: string; pinNames?: Record<string, string> }
|
||||
export interface SimResult {
|
||||
netlist: string; warnings: string[];
|
||||
op?: { nodes: Record<string, number>; sources: Record<string, number>; parts: { ref: string; kind: string; i?: number; p?: number }[] };
|
||||
x?: number[]; xlabel?: string; traces?: { name: string; unit: string; y: number[] }[];
|
||||
}
|
||||
|
||||
// ── 값 파싱 ─────────────────────────────────────────────────────────────────
|
||||
const MULT: Record<string, number> = { t: 1e12, g: 1e9, meg: 1e6, k: 1e3, m: 1e-3, u: 1e-6, n: 1e-9, p: 1e-12, f: 1e-15 };
|
||||
export function parseValue(raw: string | number | undefined): number | null {
|
||||
if (typeof raw === 'number') return Number.isFinite(raw) ? raw : null;
|
||||
let s = String(raw ?? '').trim().replace(/µ/g, 'u').replace(/[Ω\s]/g, '').replace(/ohms?$/i, '');
|
||||
if (!s) return null;
|
||||
const m4 = s.match(/^(\d+)([RrkKMGTmunpf])(\d+)$/); // 4k7, 2R2, 1u5
|
||||
if (m4) s = `${m4[1]}.${m4[3]}${/[Rr]/.test(m4[2]) ? '' : m4[2]}`;
|
||||
const m = s.match(/^([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)(meg|MEG|Meg|[TGMkKmunpf])?([A-Za-z]*)$/);
|
||||
if (!m) return null;
|
||||
let mult = 1;
|
||||
if (m[2]) mult = m[2].toLowerCase() === 'meg' ? 1e6 : m[2] === 'M' ? 1e6 : (MULT[m[2].toLowerCase()] ?? 1);
|
||||
const v = Number(m[1]) * mult;
|
||||
return Number.isFinite(v) ? v : null;
|
||||
}
|
||||
const num = (v: unknown, d: number) => { const n = typeof v === 'number' ? v : parseValue(String(v ?? '')); return n === null || !Number.isFinite(n) ? d : n; };
|
||||
const fmt = (v: number) => (Math.abs(v) >= 1e-3 && Math.abs(v) < 1e6 ? String(Math.round(v * 1e9) / 1e9) : v.toExponential(6));
|
||||
|
||||
// ── 모델 ────────────────────────────────────────────────────────────────────
|
||||
const MODELS = {
|
||||
DGEN: '.model DGEN D(IS=2.52n N=1.752 RS=0.568 CJO=4p M=0.4 TT=20n BV=100)',
|
||||
DLED: '.model DLED D(IS=1e-20 N=1.9 RS=4 CJO=20p)',
|
||||
QNPN: '.model QNPN NPN(IS=6.734f XTI=3 EG=1.11 VAF=74.03 BF=416.4 NE=1.259 ISE=6.734f IKF=66.78m XTB=1.5 BR=.7371 NC=2 ISC=0 IKR=0 RC=1 CJC=3.638p MJC=.3085 VJC=.75 FC=.5 CJE=4.493p MJE=.2593 VJE=.75 TR=239.5n TF=301.2p ITF=.4 VTF=4 XTF=2 RB=10)',
|
||||
QPNP: '.model QPNP PNP(IS=1.41f XTI=3 EG=1.11 VAF=18.7 BF=180.7 NE=1.5 ISE=0 IKF=80m XTB=1.5 BR=4.977 NC=2 ISC=0 IKR=0 RC=2.5 CJC=9.728p MJC=.5776 VJC=.75 FC=.5 CJE=8.063p MJE=.3677 VJE=.75 TR=33.42n TF=179.3p ITF=.4 VTF=4 XTF=6 RB=10)',
|
||||
MN: '.model MN NMOS(LEVEL=1 VTO=2 KP=0.2 LAMBDA=0.01 CGSO=20p CGDO=5p)',
|
||||
MP: '.model MP PMOS(LEVEL=1 VTO=-2 KP=0.1 LAMBDA=0.01 CGSO=20p CGDO=5p)',
|
||||
};
|
||||
// 555/연산증폭기/78xx 는 거동 모델(매끄러운 수식 — 조건문은 전환 순간 시뮬레이션이 멈춘다)
|
||||
const SUBCKTS = {
|
||||
NE555: `.subckt NE555 gnd trig out rst cont thres disch vcc
|
||||
R1 vcc cont 5k
|
||||
R2 cont lo 5k
|
||||
R3 lo gnd 5k
|
||||
Bset set 0 V = 0.5*(1+tanh(500*(v(lo)-v(trig))))
|
||||
Brst rs 0 V = max(0.5*(1+tanh(500*(v(thres)-v(cont)))), 0.5*(1+tanh(500*(v(gnd)+0.7-v(rst)))))
|
||||
Bq q 0 V = (1-v(rs))*(v(set)+(1-v(set))*0.5*(1+tanh(50*(v(qd)-0.5))))
|
||||
Rq q qd 1k
|
||||
Cq qd 0 1p
|
||||
Bout oi gnd V = 0.1 + v(q)*(v(vcc)-v(gnd)-1.8)
|
||||
Ro oi out 20
|
||||
Bdis disch gnd I = 0.5*(1+tanh(50*(0.5-v(q))))*v(disch,gnd)/10
|
||||
.ends NE555`,
|
||||
OPAMP: `.subckt OPAMP inp inn out vcc vee
|
||||
Rin inp inn 1e8
|
||||
Gm 0 n1 inp inn 1m
|
||||
R1 n1 0 100Meg
|
||||
C1 n1 0 159p
|
||||
Bs1 s1 0 V = 0.5*(v(n1)+(v(vee)+0.05)+sqrt((v(n1)-(v(vee)+0.05))*(v(n1)-(v(vee)+0.05))+1e-4))
|
||||
Bs2 oi 0 V = 0.5*(v(s1)+(v(vcc)-1.5)-sqrt((v(s1)-(v(vcc)-1.5))*(v(s1)-(v(vcc)-1.5))+1e-4))
|
||||
Ro oi out 75
|
||||
.ends OPAMP`,
|
||||
REG: `.subckt REG in gnd out PARAMS: vset=5
|
||||
Bo oi gnd V = 0.5*(min(vset, v(in,gnd)-2)+vset-abs(min(vset, v(in,gnd)-2)-vset))
|
||||
Ro oi out 0.05
|
||||
Rq in gnd 1Meg
|
||||
.ends REG`,
|
||||
};
|
||||
// REG: min() 만으로 충분하지만 입력 부족 시 0 이하로 내려가지 않게 아래에서 max 적용
|
||||
SUBCKTS.REG = `.subckt REG in gnd out PARAMS: vset=5
|
||||
Bo oi gnd V = max(0, min(vset, v(in,gnd)-2))
|
||||
Ro oi out 0.05
|
||||
Rq in gnd 1Meg
|
||||
.ends REG`;
|
||||
|
||||
const sane = (s: string) => String(s).replace(/[^A-Za-z0-9_]/g, '_').toLowerCase();
|
||||
const clean = (n: string) => String(n || '').replace(/~\{([^}]*)\}/g, '$1').replace(/[^A-Za-z0-9+\-]/g, '').toUpperCase();
|
||||
const natural = (a: string, b: string) => (Number(a) || 1e9) - (Number(b) || 1e9) || a.localeCompare(b);
|
||||
|
||||
interface Ctx {
|
||||
nodeOf: (ref: string, pad: string) => string;
|
||||
pads: Map<string, string[]>; // ref → 패드 번호(연결 가능한 것만, 정렬)
|
||||
}
|
||||
|
||||
export function buildNetlist(project: PcbProject & { parts: SimPart[] }, spec: SimSpec): { netlist: string; warnings: string[]; nodeNames: Map<string, string>; parts: { ref: string; kind: string; elem?: string; r?: number; n1?: string; n2?: string }[] } {
|
||||
const warnings: string[] = [];
|
||||
const pads = placedPads(project.parts as any);
|
||||
// 넷 → 노드 이름(소문자 정규화, 충돌 시 번호), 접지는 0
|
||||
const nodeNames = new Map<string, string>();
|
||||
const used = new Set<string>();
|
||||
project.nets.forEach((n, i) => {
|
||||
if (n.name === spec.gnd) { nodeNames.set(n.name, '0'); return; }
|
||||
let nm = `n_${sane(n.name)}`; if (used.has(nm)) nm += `_${i}`;
|
||||
used.add(nm); nodeNames.set(n.name, nm);
|
||||
});
|
||||
const padNode = new Map<string, string>();
|
||||
for (const n of project.nets) for (const id of n.pins) padNode.set(id, nodeNames.get(n.name)!);
|
||||
const padList = new Map<string, string[]>();
|
||||
for (const p of pads) { if (p.npth) continue; (padList.get(p.ref) || padList.set(p.ref, []).get(p.ref)!).push(p.n); }
|
||||
for (const l of padList.values()) l.sort(natural);
|
||||
let nc = 0;
|
||||
const nodeOf = (ref: string, pad: string) => padNode.get(`${ref}-${pad}`) || `nc_${sane(ref)}_${sane(pad)}_${nc++}`;
|
||||
const ctx: Ctx = { nodeOf, pads: padList };
|
||||
|
||||
const L: string[] = [];
|
||||
const need = { DGEN: false, DLED: false, QNPN: false, QPNP: false, MN: false, MP: false, NE555: false, OPAMP: false, REG: false };
|
||||
const partInfo: { ref: string; kind: string; elem?: string; r?: number; n1?: string; n2?: string }[] = [];
|
||||
|
||||
for (const part of project.parts) {
|
||||
const ref = part.ref, prefix = ref.replace(/\d+$/, '').toUpperCase(), val = String(part.value ?? '');
|
||||
const sd: SymbolDetail | null = part.sym ? (() => { const [lib, ...r] = part.sym!.split(':'); return symbolDetail(lib, r.join(':')); })() : null;
|
||||
const plist = ctx.pads.get(ref) || [];
|
||||
const pinName = (n: string) => clean(sd ? sd.pins.find(p => p.n === n)?.name || '' : (part.pinNames?.[n] || ''));
|
||||
const padOfName = (...names: string[]) => plist.find(n => names.includes(pinName(n)));
|
||||
const two = (): [string, string] | null => (plist.length >= 2 ? [nodeOf(ref, plist[0]), nodeOf(ref, plist[1])] : null);
|
||||
const tag = `${ref}`;
|
||||
const id = `${sane(ref)}`;
|
||||
const upper = `${sd?.id || ''} ${val}`.toUpperCase();
|
||||
|
||||
if (prefix === 'R' || prefix === 'C' || prefix === 'L') {
|
||||
const v = parseValue(val), t = two();
|
||||
if (!t) { warnings.push(`${tag}: 핀이 2개 미만이라 무시합니다.`); continue; }
|
||||
if (v === null || v <= 0) { warnings.push(`${tag}: 값을 알 수 없습니다("${val.replace(/[^\x20-\x7E가-힣]/g, '')}"). 값 칸에 4.7k, 100n 같은 값을 넣으세요. (이 부품은 빠진 것으로 시뮬레이션됩니다)`); continue; }
|
||||
const el = `${prefix}_${id}`;
|
||||
L.push(`${el} ${t[0]} ${t[1]} ${fmt(v)}`);
|
||||
partInfo.push({ ref, kind: prefix, elem: el, r: prefix === 'R' ? v : undefined, n1: t[0], n2: t[1] });
|
||||
} else if (prefix === 'D') {
|
||||
const kp = padOfName('K', 'C', 'CATHODE') ?? plist[0], ap = padOfName('A', 'ANODE') ?? plist[1];
|
||||
if (!kp || !ap) { warnings.push(`${tag}: 다이오드 핀을 찾지 못했습니다.`); continue; }
|
||||
const led = /LED/.test(`${upper} ${part.fp.toUpperCase()}`);
|
||||
if (/ZENER|\bZ[A-Z]*\d/.test(upper) && !led) warnings.push(`${tag}: 제너 다이오드는 일반 다이오드로 처리됩니다(항복 전압 미반영).`);
|
||||
const el = `D_${id}`; const model = led ? 'DLED' : 'DGEN'; need[model] = true;
|
||||
L.push(`${el} ${nodeOf(ref, ap)} ${nodeOf(ref, kp)} ${model}`);
|
||||
partInfo.push({ ref, kind: led ? 'LED' : 'D', elem: el });
|
||||
} else if (prefix === 'Q') {
|
||||
const isMos = !!(padOfName('G') && padOfName('D') && padOfName('S'));
|
||||
if (isMos) {
|
||||
const pm = /PMOS|P-CH|PCH|IRF9|IRF5\d\d\b|BS250|SI23|FQP\d+P/.test(upper);
|
||||
need[pm ? 'MP' : 'MN'] = true;
|
||||
const d = nodeOf(ref, padOfName('D')!), g = nodeOf(ref, padOfName('G')!), s = nodeOf(ref, padOfName('S')!);
|
||||
L.push(`M_${id} ${d} ${g} ${s} ${s} ${pm ? 'MP' : 'MN'}`);
|
||||
partInfo.push({ ref, kind: pm ? 'PMOS' : 'NMOS' });
|
||||
warnings.push(`${tag}: MOSFET은 일반 모델(VTO=±2V)로 처리됩니다.`);
|
||||
} else {
|
||||
const pnp = /PNP|2N3906|2N2907|BC55[78]|BC32[5-8]|BD140|TIP4\d|MPSA92|2N5401/.test(upper);
|
||||
let e = padOfName('E'), b = padOfName('B'), c = padOfName('C');
|
||||
if (!e || !b || !c) { [e, b, c] = [plist[0], plist[1], plist[2]]; warnings.push(`${tag}: 핀 이름이 없어 1=E, 2=B, 3=C 로 가정합니다. KiCad 심볼(예: 2N3904)로 추가하면 정확합니다.`); }
|
||||
if (!e || !b || !c) { warnings.push(`${tag}: 트랜지스터 핀이 3개가 아닙니다.`); continue; }
|
||||
need[pnp ? 'QPNP' : 'QNPN'] = true;
|
||||
L.push(`Q_${id} ${nodeOf(ref, c)} ${nodeOf(ref, b)} ${nodeOf(ref, e)} ${pnp ? 'QPNP' : 'QNPN'}`);
|
||||
partInfo.push({ ref, kind: pnp ? 'PNP' : 'NPN' });
|
||||
}
|
||||
} else if (prefix === 'U') {
|
||||
if (!sd) { warnings.push(`${tag}: IC는 KiCad 심볼로 추가해야 시뮬레이션할 수 있습니다(핀 이름 필요).`); continue; }
|
||||
const byName = (...names: string[]) => { const p = sd.pins.find(q => names.includes(clean(q.name))); return p ? nodeOf(ref, p.n) : null; };
|
||||
if (/555/.test(upper)) {
|
||||
const ports = [byName('GND'), byName('TRIG', 'TRIGGER'), byName('OUT', 'OUTPUT', 'Q'), byName('RST', 'RESET', 'R'), byName('CONT', 'CTRL', 'CV', 'CVOLT'), byName('THRES', 'THR', 'THRESHOLD'), byName('DISCH', 'DIS', 'DISCHARGE'), byName('VCC', 'V+', 'VDD')];
|
||||
if (ports.some(p => !p)) { warnings.push(`${tag}: 555 핀 이름을 해석하지 못했습니다.`); continue; }
|
||||
need.NE555 = true; L.push(`X_${id} ${ports.join(' ')} NE555`); partInfo.push({ ref, kind: '555' });
|
||||
} else if (/78\d\d|LM78|L78|79\d\d/.test(upper) && !/79\d\d/.test(upper)) {
|
||||
const mv = upper.match(/78(\d\d)/); const vset = mv ? Number(mv[1]) : 5;
|
||||
const pi = byName('IN', 'VI'), pg = byName('GND'), po = byName('OUT', 'VO');
|
||||
if (!pi || !pg || !po) { warnings.push(`${tag}: 레귤레이터 핀을 해석하지 못했습니다.`); continue; }
|
||||
need.REG = true; L.push(`X_${id} ${pi} ${pg} ${po} REG PARAMS: vset=${vset}`); partInfo.push({ ref, kind: `REG${vset}` });
|
||||
} else if (/AMPLIFIER_OPERATIONAL|LM358|LM324|LM2904|TL0[78]|NE553|LM741|UA741|MCP60|OPA\d|LMV\d|TLC27|LF35/.test(upper)) {
|
||||
const vcc = sd.pins.find(p => /^(V\+|VCC|VDD)$/.test(clean(p.name)) && p.type.startsWith('power')), vee = sd.pins.find(p => /^(V-|VEE|VSS|GND)$/.test(clean(p.name)) && p.type.startsWith('power'));
|
||||
const units = [...new Set(sd.pins.filter(p => p.type === 'output').map(p => p.unit))];
|
||||
let k = 0;
|
||||
for (const u of units) {
|
||||
const ups = sd.pins.filter(p => p.unit === u);
|
||||
const o = ups.find(p => p.type === 'output'), ip = ups.find(p => clean(p.name) === '+'), im = ups.find(p => clean(p.name) === '-');
|
||||
if (!o || !ip || !im || !vcc || !vee) { warnings.push(`${tag}: 연산증폭기 핀(+,-,출력,전원)을 해석하지 못했습니다.`); continue; }
|
||||
need.OPAMP = true; L.push(`X_${id}_${++k} ${nodeOf(ref, ip.n)} ${nodeOf(ref, im.n)} ${nodeOf(ref, o.n)} ${nodeOf(ref, vcc.n)} ${nodeOf(ref, vee.n)} OPAMP`);
|
||||
}
|
||||
if (k) { partInfo.push({ ref, kind: `연산증폭기 ×${k}` }); warnings.push(`${tag}: 범용 연산증폭기 모델(GBW 1MHz, 출력 V+ -1.5V)입니다. 정밀한 규격은 반영되지 않습니다.`); }
|
||||
} else warnings.push(`${tag}: 이 IC(${sd.value})는 시뮬레이션 모델이 없습니다(555, 연산증폭기, 78xx만 지원). 회로에서 빠진 것으로 시뮬레이션됩니다.`);
|
||||
} else if (!/^(J|P|H|SW|TP|F|MH)$/.test(prefix)) {
|
||||
warnings.push(`${tag}: 지원하지 않는 부품 종류(${prefix})라서 무시합니다.`);
|
||||
}
|
||||
}
|
||||
|
||||
// 전원/신호원
|
||||
const sourceNames: string[] = [];
|
||||
spec.sources.forEach((s, i) => {
|
||||
const pos = nodeNames.get(s.pos), neg = s.neg ? nodeNames.get(s.neg) : '0';
|
||||
if (!pos || neg === undefined) { warnings.push(`신호원 #${i + 1}: 넷을 찾을 수 없어 무시합니다.`); return; }
|
||||
const nm = `V_src${i + 1}`; sourceNames.push(nm);
|
||||
let body = '';
|
||||
if (s.type === 'dc') body = `DC ${fmt(num(s.dc, 5))}`;
|
||||
else if (s.type === 'ac') body = `DC ${fmt(num(s.dc, 0))} AC ${fmt(num(s.mag, 1))}`;
|
||||
else if (s.type === 'sin') body = `DC ${fmt(num(s.off, 0))} SIN(${fmt(num(s.off, 0))} ${fmt(num(s.amp, 1))} ${fmt(num(s.freq, 1000))}) AC 1`;
|
||||
else body = `PULSE(${fmt(num(s.v1, 0))} ${fmt(num(s.v2, 5))} ${fmt(num(s.td, 0))} ${fmt(num(s.tr, 1e-6))} ${fmt(num(s.tf, 1e-6))} ${fmt(num(s.pw, 5e-4))} ${fmt(num(s.per, 1e-3))})`;
|
||||
L.push(`${nm} ${pos} ${neg} ${body}`);
|
||||
});
|
||||
|
||||
const head = ['* homeclaw PCB 시뮬레이션'];
|
||||
for (const [net, node] of nodeNames) head.push(`* ${node} = ${sane(net)}`);
|
||||
const models: string[] = [];
|
||||
for (const k of ['DGEN', 'DLED', 'QNPN', 'QPNP', 'MN', 'MP'] as const) if (need[k]) models.push(MODELS[k]);
|
||||
for (const k of ['NE555', 'OPAMP', 'REG'] as const) if (need[k]) models.push(SUBCKTS[k]);
|
||||
const netlist = [...head, ...L, ...models, '.options rshunt=1e12 reltol=1e-3'].join('\n') + '\n';
|
||||
return { netlist, warnings, nodeNames, parts: partInfo };
|
||||
}
|
||||
|
||||
// ── 실행 ────────────────────────────────────────────────────────────────────
|
||||
let busy = false;
|
||||
function runNgspice(cir: string, dir: string, timeoutMs: number): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn('ngspice', ['-b', cir], { cwd: dir, env: { ...process.env, HOME: dir } });
|
||||
let out = '';
|
||||
const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new Error(`시뮬레이션 시간 초과(${timeoutMs / 1000}초). 해석 시간을 줄이거나 시간 간격을 키우세요.`)); }, timeoutMs);
|
||||
child.stdout.on('data', d => { out += d; if (out.length > 4e6) child.kill('SIGKILL'); });
|
||||
child.stderr.on('data', d => { out += d; });
|
||||
child.on('error', e => { clearTimeout(timer); reject(new Error(e.message.includes('ENOENT') ? 'ngspice 가 설치되어 있지 않습니다.' : e.message)); });
|
||||
child.on('close', () => { clearTimeout(timer); resolve(out); });
|
||||
});
|
||||
}
|
||||
|
||||
export async function simulate(project: PcbProject & { parts: SimPart[] }, spec: SimSpec): Promise<SimResult> {
|
||||
const nets = new Set(project.nets.map(n => n.name));
|
||||
if (!nets.has(spec.gnd)) throw new Error('접지(GND) 넷을 고르세요.');
|
||||
if (!spec.sources?.length) throw new Error('전원이나 신호원을 하나 이상 추가하세요.');
|
||||
const probes = (spec.probes || []).filter(p => nets.has(p) && p !== spec.gnd).slice(0, 10);
|
||||
if (!probes.length && spec.analysis.type !== 'op') throw new Error('관찰할 넷(프로브)을 하나 이상 고르세요.');
|
||||
const a = spec.analysis;
|
||||
const b = buildNetlist(project, spec);
|
||||
const probeNodes = probes.map(p => b.nodeNames.get(p)!);
|
||||
const allNodes = [...b.nodeNames.entries()].filter(([n]) => n !== spec.gnd).map(([, v]) => v);
|
||||
|
||||
const ctl: string[] = ['.control', 'set noaskquit', 'set units=degrees', 'set wr_vecnames=false'];
|
||||
if (a.type === 'op') {
|
||||
ctl.push('op', ...allNodes.map(n => `print v(${n})`));
|
||||
b.parts.filter(p => p.kind === 'D' || p.kind === 'LED').forEach(p => ctl.push(`print @${p.elem!.toLowerCase()}[id]`));
|
||||
spec.sources.forEach((_, i) => ctl.push(`print i(v_src${i + 1})`));
|
||||
} else if (a.type === 'tran') {
|
||||
const stop = num(a.stop, 0.01), step = num(a.step, stop / 1000);
|
||||
if (!(stop > 0) || !(step > 0) || stop / step > 200000) throw new Error('해석 시간/간격이 올바르지 않습니다(점 20만 개 이하).');
|
||||
ctl.push(`tran ${fmt(step)} ${fmt(stop)} uic`, `wrdata out.txt ${probeNodes.map(n => `v(${n})`).join(' ')}`);
|
||||
} else {
|
||||
const f1 = num(a.fstart, 10), f2 = num(a.fstop, 1e6), ppd = Math.min(Math.max(Math.round(num(a.ppd, 20)), 2), 100);
|
||||
if (!(f1 > 0) || !(f2 > f1) || Math.log10(f2 / f1) > 9) throw new Error('주파수 범위가 올바르지 않습니다.');
|
||||
if (!spec.sources.some(s => s.type === 'ac' || s.type === 'sin')) throw new Error('AC 해석에는 "AC" 또는 "사인" 신호원이 필요합니다.');
|
||||
ctl.push(`ac dec ${ppd} ${fmt(f1)} ${fmt(f2)}`, `wrdata out.txt ${probeNodes.map(n => `vdb(${n}) ph(v(${n}))`).join(' ')}`);
|
||||
}
|
||||
ctl.push('.endc');
|
||||
const cir = b.netlist + (a.type === 'tran' ? '' : '') + ctl.join('\n') + '\n.end\n';
|
||||
|
||||
if (busy) throw new Error('다른 시뮬레이션이 진행 중입니다. 잠시 후 다시 시도하세요.');
|
||||
busy = true;
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pcb-sim-'));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, 'c.cir'), cir);
|
||||
const log = await runNgspice('c.cir', dir, 40_000);
|
||||
const errs = log.split('\n').filter(l => /^Error|no such|singular matrix|Too many iterations|timestep too small/i.test(l)).slice(0, 4);
|
||||
const res: SimResult = { netlist: b.netlist, warnings: b.warnings };
|
||||
if (a.type === 'op') {
|
||||
const nodes: Record<string, number> = {}, sources: Record<string, number> = {};
|
||||
const nodeToNet = new Map([...b.nodeNames.entries()].map(([k, v]) => [v, k]));
|
||||
for (const m of log.matchAll(/^v\((\S+)\)\s*=\s*(\S+)/gm)) { const net = nodeToNet.get(m[1]); if (net) nodes[net] = Number(m[2]); }
|
||||
spec.sources.forEach((_, i) => { const m = log.match(new RegExp(`^i\\(v_src${i + 1}\\)\\s*=\\s*(\\S+)`, 'mi')); if (m) sources[`전원/신호원 ${i + 1}`] = Number(m[1]); });
|
||||
if (!Object.keys(nodes).length) throw new Error(errs.join(' / ') || 'ngspice 결과를 읽지 못했습니다(회로가 수렴하지 않았을 수 있습니다).');
|
||||
const nv = (node: string) => (node === '0' ? 0 : nodes[nodeToNet.get(node)!] ?? NaN);
|
||||
const parts: NonNullable<SimResult['op']>['parts'] = [];
|
||||
for (const p of b.parts) {
|
||||
if (p.kind === 'R' && p.r && p.n1 && p.n2) { const i = (nv(p.n1) - nv(p.n2)) / p.r; parts.push({ ref: p.ref, kind: 'R', i, p: i * i * p.r }); }
|
||||
else if ((p.kind === 'D' || p.kind === 'LED') && p.elem) { const m = log.match(new RegExp(`^@${p.elem.toLowerCase()}\\[id\\]\\s*=\\s*(\\S+)`, 'mi')); if (m) parts.push({ ref: p.ref, kind: p.kind, i: Number(m[1]) }); }
|
||||
}
|
||||
res.op = { nodes, sources, parts };
|
||||
} else {
|
||||
const file = path.join(dir, 'out.txt');
|
||||
if (!fs.existsSync(file)) throw new Error(errs.join(' / ') || 'ngspice 가 결과를 만들지 못했습니다(회로가 수렴하지 않았을 수 있습니다).');
|
||||
const rows = fs.readFileSync(file, 'utf8').split('\n').map(l => l.trim().split(/\s+/).map(Number)).filter(r => r.length > 1 && r.every(Number.isFinite));
|
||||
if (!rows.length) throw new Error(errs.join(' / ') || '결과가 비어 있습니다.');
|
||||
const stride = Math.max(1, Math.ceil(rows.length / 2500));
|
||||
const pick = rows.filter((_, i) => i % stride === 0 || i === rows.length - 1);
|
||||
res.x = pick.map(r => r[0]);
|
||||
res.xlabel = a.type === 'tran' ? '시간 (s)' : '주파수 (Hz)';
|
||||
res.traces = [];
|
||||
if (a.type === 'tran') probes.forEach((p, k) => res.traces!.push({ name: p, unit: 'V', y: pick.map(r => r[1 + k * 2]) }));
|
||||
else probes.forEach((p, k) => { res.traces!.push({ name: `${p} 이득`, unit: 'dB', y: pick.map(r => r[1 + k * 4]) }); res.traces!.push({ name: `${p} 위상`, unit: '°', y: pick.map(r => r[3 + k * 4]) }); });
|
||||
if (errs.length) res.warnings.push(...errs.map(e => `ngspice: ${e}`));
|
||||
}
|
||||
return res;
|
||||
} finally { busy = false; fs.rmSync(dir, { recursive: true, force: true }); }
|
||||
}
|
||||
+143
-5
@@ -44,6 +44,19 @@ canvas{position:absolute;inset:0;width:100%;height:100%;display:block;touch-acti
|
||||
.dl a{display:block;margin:3px 0;color:var(--brand2);text-decoration:none;font-size:12.5px}
|
||||
details{margin-bottom:6px}summary{cursor:pointer;font-weight:700;font-size:12.5px;padding:4px 0}
|
||||
.note{font-size:11px;color:var(--muted);line-height:1.5;margin-top:4px}
|
||||
#simpane{display:none;flex-direction:column;border-top:2px solid var(--brand);background:var(--panel);height:300px;min-height:140px}
|
||||
#simhead{display:flex;align-items:center;gap:8px;padding:5px 10px;background:var(--panel2);font-size:12px}
|
||||
#simhead b{flex:1}
|
||||
#simbody{flex:1;display:flex;min-height:0}
|
||||
#simchart{flex:1;position:relative;min-width:0}
|
||||
#sc{position:absolute;inset:0;width:100%;height:100%;background:var(--panel)}
|
||||
#simside{width:300px;overflow-y:auto;padding:8px 10px;font-size:12px;border-left:1px solid var(--line)}
|
||||
#simside table{width:100%;border-collapse:collapse}#simside td{padding:2px 4px;border-bottom:1px solid var(--line)}
|
||||
#simside td:last-child{text-align:right;font-variant-numeric:tabular-nums}
|
||||
#simside pre{white-space:pre-wrap;font-size:10.5px;color:var(--muted);max-height:180px;overflow:auto}
|
||||
.srow{display:grid;grid-template-columns:1fr 1fr;gap:4px;background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:6px;margin-bottom:6px}
|
||||
.srow .full{grid-column:1/3}.srow label{font-size:10.5px;color:var(--muted)}
|
||||
.pchk{display:inline-flex;align-items:center;gap:3px;margin:2px 8px 2px 0;font-size:12px}.pchk input{width:auto}
|
||||
@media (max-width:1000px){
|
||||
body{height:auto;overflow:auto}
|
||||
.wrap{display:block}
|
||||
@@ -87,6 +100,10 @@ details{margin-bottom:6px}summary{cursor:pointer;font-weight:700;font-size:12.5p
|
||||
<button class="btn" onclick="fitView()">⤢ 맞춤</button>
|
||||
</div>
|
||||
<div id="cv"><canvas id="c"></canvas></div>
|
||||
<div id="simpane">
|
||||
<div id="simhead"><b id="simtitle">시뮬레이션 결과</b><button class="btn" onclick="$('simpane').style.display='none';resize()">닫기 ✕</button></div>
|
||||
<div id="simbody"><div id="simchart"><canvas id="sc"></canvas></div><div id="simside"></div></div>
|
||||
</div>
|
||||
<div id="bar" style="border-top:1px solid var(--line);border-bottom:0"><span id="hint">부품을 왼쪽에서 눌러 추가 → 끌어서 배치 → 🔗 핀 연결 모드에서 핀을 차례로 클릭해 연결 → 오른쪽에서 자동 배선</span></div>
|
||||
</section>
|
||||
|
||||
@@ -135,6 +152,21 @@ details{margin-bottom:6px}summary{cursor:pointer;font-weight:700;font-size:12.5p
|
||||
<div class="note">V비트라면 "가공 폭"은 깊이에서의 유효 폭입니다. 최소 간격은 가공 폭 이상이어야 배선 사이가 분리됩니다.</div>
|
||||
</details>
|
||||
|
||||
<details><summary>회로 시뮬레이션 (ngspice)</summary>
|
||||
<label style="font-size:11px;color:var(--muted)">접지(0V) 넷</label><select id="s_gnd" onchange="simChanged()"></select>
|
||||
<h3>전원 · 신호원</h3>
|
||||
<div id="s_src"></div>
|
||||
<button class="btn" onclick="addSrc()">+ 추가</button>
|
||||
<h3>해석</h3>
|
||||
<select id="s_an" onchange="simChanged()"><option value="op">동작점 (DC 전압·전류)</option><option value="tran">시간 응답 (파형)</option><option value="ac">주파수 응답 (AC)</option></select>
|
||||
<div id="s_anp" class="grid2" style="margin-top:6px"></div>
|
||||
<h3>관찰할 넷</h3>
|
||||
<div id="s_probes"></div>
|
||||
<button class="btn pri" id="sbtn" style="width:100%;margin-top:8px" onclick="doSim()">▶ 시뮬레이션</button>
|
||||
<div id="s_msg" class="note"></div>
|
||||
<div class="note">저항·커패시터·코일은 <b>값</b> 칸(4.7k, 100n)이 필요합니다. 트랜지스터·IC는 KiCad 심볼로 추가하세요. IC는 555, 연산증폭기, 78xx만 지원합니다.</div>
|
||||
</details>
|
||||
|
||||
<details open><summary>G-code</summary>
|
||||
<button class="btn pri" id="gbtn" style="width:100%" onclick="doGcode()">⚙ G-code 생성 · 미리보기</button>
|
||||
<div id="res"></div>
|
||||
@@ -178,7 +210,7 @@ function loadSample(){
|
||||
function save(){try{localStorage.setItem('pcb-project',JSON.stringify(P));}catch(e){}}
|
||||
function changed(keepRoute){
|
||||
if(!keepRoute){ routed=null; gres=null; $('rres').textContent=''; $('res').innerHTML=''; $('dl').innerHTML=''; }
|
||||
save(); renderNets(); updSel(); draw();
|
||||
save(); renderNets(); updSel(); draw(); if(typeof renderSim==='function') renderSim();
|
||||
}
|
||||
|
||||
// ───────────── 기하 ─────────────
|
||||
@@ -361,13 +393,14 @@ function refPrefix(lib,hint){
|
||||
const l=lib.toLowerCase();
|
||||
return /resistor/.test(l)?'R':/capacitor/.test(l)?'C':/led|diode/.test(l)?'D':/connector|pinheader|terminal/.test(l)?'J':/inductor/.test(l)?'L':/mounting/.test(l)?'H':/transistor|to_/.test(l)?'Q':'U';
|
||||
}
|
||||
async function addKicadPart({fp,ref,value,pins,lib}){
|
||||
async function addKicadPart({fp,ref,value,pins,lib,sym}){
|
||||
try{
|
||||
const d=await api('/api/pcb/kicad/footprint?id='+encodeURIComponent(fp));
|
||||
FPM[fp]=d.footprint; P.fps=P.fps||{}; P.fps[fp]=d.footprint;
|
||||
const pre=refPrefix(lib||'',ref); let n=1; while(P.parts.some(p=>p.ref===pre+n)) n++;
|
||||
const b=d.footprint.body;
|
||||
const part={ref:pre+n,fp,x:snapV(P.board.w/2-(b.x0+b.x1)/2),y:snapV(P.board.h/2-(b.y0+b.y1)/2),rot:0,value:value||''};
|
||||
if(sym) part.sym=sym;
|
||||
if(pins){part.pinNames={};for(const q of pins){const nm=clean(q.name);if(nm)part.pinNames[q.n]=nm;}
|
||||
const have=new Set(d.footprint.pads.map(x=>x.n)), miss=pins.map(q=>q.n).filter(x=>!have.has(x));
|
||||
if(miss.length) $('hint').innerHTML=`<span class="warn">⚠ ${esc(part.ref)}: 심볼 핀 ${esc(miss.join(','))} 번이 풋프린트에 없습니다. 풋프린트를 확인하세요.</span>`;}
|
||||
@@ -380,7 +413,7 @@ async function addKSym(i){
|
||||
try{
|
||||
const d=await api('/api/pcb/kicad/symbol?id='+encodeURIComponent(e.lib+':'+e.name));
|
||||
const s=d.symbol;
|
||||
if(s.footprint){$('kpick').innerHTML='';addKicadPart({fp:'kicad:'+s.footprint,ref:s.ref,value:s.value,pins:s.pins,lib:e.lib});return;}
|
||||
if(s.footprint){$('kpick').innerHTML='';addKicadPart({fp:'kicad:'+s.footprint,ref:s.ref,value:s.value,pins:s.pins,lib:e.lib,sym:s.id});return;}
|
||||
pickCtx={sym:s};kPickList=d.candidates;
|
||||
$('kpick').innerHTML=`<div class="note" style="margin:8px 0 3px">⚠ <b>${esc(s.value)}</b> 는 기본 풋프린트가 없습니다. 하나 고르세요 (${s.pins.length}핀):</div><input id="kpq" placeholder="풋프린트 검색 (0805, DIP-8, TO-92…)" oninput="kPickSearch()"><div class="lib" id="kplist"></div>`;
|
||||
renderPick();
|
||||
@@ -389,7 +422,7 @@ async function addKSym(i){
|
||||
function renderPick(){$('kplist').innerHTML=kPickList.slice(0,40).map((e,i)=>`<button onclick="pickFp(${i})">${esc(e.name)}<span class="sub">${esc(e.lib)} · ${e.pads}패드${e.smd?' · SMD':''}</span></button>`).join('')||'<div class="note">결과 없음</div>';}
|
||||
let kpT=null;
|
||||
function kPickSearch(){clearTimeout(kpT);kpT=setTimeout(async()=>{const q=$('kpq').value.trim();if(q.length<2)return;try{kPickList=(await api('/api/pcb/kicad/search?kind=fp&q='+encodeURIComponent(q))).results;renderPick();}catch(e){}},250);}
|
||||
function pickFp(i){const e=kPickList[i],s=pickCtx.sym;$('kpick').innerHTML='';addKicadPart({fp:`kicad:${e.lib}:${e.name}`,ref:s.ref,value:s.value,pins:s.pins,lib:e.lib});}
|
||||
function pickFp(i){const e=kPickList[i],s=pickCtx.sym;$('kpick').innerHTML='';addKicadPart({fp:`kicad:${e.lib}:${e.name}`,ref:s.ref,value:s.value,pins:s.pins,lib:e.lib,sym:s.id});}
|
||||
function setVal(v){const p=P.parts.find(x=>x.ref===sel);if(!p)return;p.value=v.trim();changed(true);}
|
||||
function pinLabel(id){const k=id.lastIndexOf('-'),p=P.parts.find(x=>x.ref===id.slice(0,k)),nm=p&&p.pinNames?p.pinNames[id.slice(k+1)]:'';return nm?`${id}·${nm}`:id;}
|
||||
async function registerFps(){
|
||||
@@ -460,6 +493,111 @@ function loadFile(inp){
|
||||
rd.readAsText(f);inp.value='';
|
||||
}
|
||||
|
||||
|
||||
// ───────────── 회로 시뮬레이션 ─────────────
|
||||
const SRC_DEF={dc:{dc:'5'},pulse:{v1:'0',v2:'5',per:'1m',pw:'0.5m'},sin:{off:'0',amp:'1',freq:'1k'},ac:{dc:'0',mag:'1'}};
|
||||
const SRC_FIELDS={dc:[['dc','전압 V']],pulse:[['v1','낮음 V'],['v2','높음 V'],['per','주기 s'],['pw','폭 s']],sin:[['off','오프셋 V'],['amp','진폭 V'],['freq','주파수 Hz']],ac:[['dc','DC V'],['mag','크기']]};
|
||||
function ensureSim(){
|
||||
P.sim=P.sim||{gnd:'',sources:[],analysis:{type:'op',stop:'10m',step:'',fstart:'10',fstop:'100k',ppd:'20'},probes:[]};
|
||||
const names=P.nets.map(n=>n.name);
|
||||
if(!names.includes(P.sim.gnd)) P.sim.gnd=names.find(n=>/^(gnd|0|vss)$/i.test(n))||names[0]||'';
|
||||
P.sim.sources=P.sim.sources.filter(s=>names.includes(s.pos));
|
||||
P.sim.probes=P.sim.probes.filter(n=>names.includes(n)&&n!==P.sim.gnd);
|
||||
}
|
||||
function simChanged(){
|
||||
ensureSim();
|
||||
P.sim.gnd=$('s_gnd').value||P.sim.gnd; P.sim.analysis.type=$('s_an').value;
|
||||
for(const k of ['stop','step','fstart','fstop','ppd']){const el=$('sa_'+k);if(el)P.sim.analysis[k]=el.value;}
|
||||
P.sim.probes=[...document.querySelectorAll('#s_probes input:checked')].map(x=>x.value);
|
||||
save(); renderSim();
|
||||
}
|
||||
function addSrc(){ensureSim();const pos=P.nets.map(n=>n.name).find(n=>n!==P.sim.gnd&&/vcc|vdd|5v|3v3|in|vin/i.test(n))||P.nets.map(n=>n.name).find(n=>n!==P.sim.gnd)||'';if(!pos){$('s_msg').innerHTML='<span class="bad">먼저 연결(넷)을 만드세요.</span>';return;}P.sim.sources.push({type:P.sim.sources.length?'sin':'dc',pos,...(P.sim.sources.length?SRC_DEF.sin:SRC_DEF.dc)});save();renderSim();}
|
||||
function rmSrc(i){P.sim.sources.splice(i,1);save();renderSim();}
|
||||
function setSrc(i,k,v){const s=P.sim.sources[i];if(k==='type'){P.sim.sources[i]={type:v,pos:s.pos,...SRC_DEF[v]};save();renderSim();return;}s[k]=v;save();}
|
||||
function renderSim(){
|
||||
if(!P) return; ensureSim();
|
||||
const names=P.nets.map(n=>n.name), opt=(sel,list)=>list.map(n=>`<option ${n===sel?'selected':''} value="${esc(n)}">${esc(n)}</option>`).join('');
|
||||
$('s_gnd').innerHTML=opt(P.sim.gnd,names);
|
||||
$('s_src').innerHTML=P.sim.sources.map((s,i)=>`<div class="srow">
|
||||
<div><label>종류</label><select onchange="setSrc(${i},'type',this.value)">${[['dc','DC 전원'],['pulse','펄스'],['sin','사인'],['ac','AC(주파수 해석용)']].map(([v,l])=>`<option value="${v}" ${s.type===v?'selected':''}>${l}</option>`).join('')}</select></div>
|
||||
<div><label>(+) 넷</label><select onchange="setSrc(${i},'pos',this.value)">${opt(s.pos,names)}</select></div>
|
||||
${SRC_FIELDS[s.type].map(([k,l])=>`<div><label>${l}</label><input value="${esc(s[k]??'')}" onchange="setSrc(${i},'${k}',this.value)"></div>`).join('')}
|
||||
<div class="full"><button class="btn" style="padding:2px 8px;font-size:11px" onclick="rmSrc(${i})">삭제</button> <span class="note">(−)는 접지</span></div></div>`).join('')||'<div class="note">전원이나 신호원을 추가하세요.</div>';
|
||||
$('s_an').value=P.sim.analysis.type;
|
||||
const a=P.sim.analysis,f=(k,l,ph)=>`<div><label>${l}</label><input id="sa_${k}" value="${esc(a[k]??'')}" placeholder="${ph||''}" onchange="simChanged()"></div>`;
|
||||
$('s_anp').innerHTML=a.type==='tran'?f('stop','총 시간 (예: 10m)')+f('step','시간 간격','자동'):a.type==='ac'?f('fstart','시작 Hz')+f('fstop','끝 Hz')+f('ppd','10배당 점 수'):'';
|
||||
$('s_probes').innerHTML=names.filter(n=>n!==P.sim.gnd).map(n=>`<label class="pchk"><input type="checkbox" value="${esc(n)}" ${P.sim.probes.includes(n)?'checked':''} onchange="simChanged()">${esc(n)}</label>`).join('')||'<span class="note">넷 없음</span>';
|
||||
}
|
||||
async function doSim(){
|
||||
ensureSim(); const a=P.sim.analysis, b=$('sbtn');
|
||||
if(!P.sim.probes.length&&a.type!=='op'){P.sim.probes=P.nets.map(n=>n.name).filter(n=>n!==P.sim.gnd).slice(0,4);renderSim();}
|
||||
const step=a.step&&String(a.step).trim()?a.step:undefined;
|
||||
b.disabled=true;$('s_msg').textContent='ngspice 실행 중…';
|
||||
try{
|
||||
const d=await api('/api/pcb/simulate',{project:P,sim:{gnd:P.sim.gnd,sources:P.sim.sources,probes:P.sim.probes,analysis:{type:a.type,stop:a.stop,step,fstart:a.fstart,fstop:a.fstop,ppd:a.ppd}}});
|
||||
$('s_msg').innerHTML='<span class="ok">✔ 완료</span>'+(d.warnings.length?` · 경고 ${d.warnings.length}건`:'');
|
||||
showSim(d,a.type);
|
||||
}catch(e){$('s_msg').innerHTML=`<span class="bad">${esc(e.message)}</span>`;}
|
||||
finally{b.disabled=false;}
|
||||
}
|
||||
const SI=[[1e9,'G'],[1e6,'M'],[1e3,'k'],[1,''],[1e-3,'m'],[1e-6,'µ'],[1e-9,'n'],[1e-12,'p']];
|
||||
function fmtSI(v,unit=''){if(!isFinite(v))return '–';if(v===0)return '0'+unit;const av=Math.abs(v);for(const [m,p] of SI){if(av>=m*0.9995)return (+(v/m).toPrecision(4))+p+unit;}return v.toExponential(2)+unit;}
|
||||
let simRes=null,simHover=null;
|
||||
function showSim(d,type){
|
||||
simRes={...d,type};
|
||||
$('simpane').style.display='flex'; $('simtitle').textContent='시뮬레이션 결과 — '+({op:'동작점',tran:'시간 응답',ac:'주파수 응답'}[type]);
|
||||
let h='';
|
||||
if(d.warnings.length) h+=d.warnings.map(w=>`<div class="warn" style="margin-bottom:3px">⚠ ${esc(w)}</div>`).join('');
|
||||
if(d.op){
|
||||
h+='<b>노드 전압</b><table>'+Object.entries(d.op.nodes).map(([n,v])=>`<tr><td>${esc(n)}</td><td>${fmtSI(v,'V')}</td></tr>`).join('')+'</table>';
|
||||
if(d.op.parts.length) h+='<b style="display:block;margin-top:8px">부품 전류</b><table>'+d.op.parts.map(p=>`<tr><td>${esc(p.ref)} <span style="color:var(--muted)">${p.kind}</span></td><td>${fmtSI(p.i,'A')}${p.p!==undefined?` · ${fmtSI(p.p,'W')}`:''}</td></tr>`).join('')+'</table>';
|
||||
if(Object.keys(d.op.sources).length) h+='<b style="display:block;margin-top:8px">전원 전류</b><table>'+Object.entries(d.op.sources).map(([n,v])=>`<tr><td>${esc(n)}</td><td>${fmtSI(v,'A')}</td></tr>`).join('')+'</table>';
|
||||
}
|
||||
h+=`<details style="margin-top:8px"><summary>SPICE 넷리스트</summary><pre>${esc(d.netlist)}</pre></details>`;
|
||||
$('simside').innerHTML=h;
|
||||
$('simchart').style.display=d.op?'none':'block';
|
||||
$('simside').style.width=d.op?'100%':'300px';
|
||||
resize(); if(!d.op) requestAnimationFrame(()=>drawChart());
|
||||
}
|
||||
const COLORS=['#4fc3f7','#ffb74d','#81c784','#ba68c8','#e57373','#fff176','#4db6ac','#f06292','#a1887f','#90a4ae'];
|
||||
function niceStep(range,n){const raw=range/n,mag=Math.pow(10,Math.floor(Math.log10(raw))),r=raw/mag;return (r<1.5?1:r<3?2:r<7?5:10)*mag;}
|
||||
function drawChart(){
|
||||
const d=simRes; if(!d||!d.x) return;
|
||||
const cv2=$('sc'),c=cv2.getContext('2d'),r=cv2.getBoundingClientRect(),dp=window.devicePixelRatio||1;
|
||||
if(!r.width) return; cv2.width=Math.round(r.width*dp);cv2.height=Math.round(r.height*dp);c.setTransform(dp,0,0,dp,0,0);
|
||||
const fg=getComputedStyle(document.body).color,muted='#94a3b8',grid='rgba(148,163,184,.22)';
|
||||
const ac=d.type==='ac', panels=ac?[d.traces.filter(t=>t.unit==='dB'),d.traces.filter(t=>t.unit==='°')]:[d.traces];
|
||||
const W=r.width,H=r.height,L=58,R=12,T=24,B=30,gap=ac?16:0,ph=(H-T-B-gap)/panels.length;
|
||||
const x0=d.x[0],x1=d.x[d.x.length-1];
|
||||
const X=v=>L+(ac?(Math.log10(v)-Math.log10(x0))/(Math.log10(x1)-Math.log10(x0)):(v-x0)/(x1-x0||1))*(W-L-R);
|
||||
c.font='11px sans-serif';
|
||||
panels.forEach((tr,pi)=>{
|
||||
const top=T+pi*(ph+gap);
|
||||
let lo=Infinity,hi=-Infinity; tr.forEach(t=>t.y.forEach(v=>{if(isFinite(v)){lo=Math.min(lo,v);hi=Math.max(hi,v);}}));
|
||||
if(!isFinite(lo)){lo=0;hi=1;} if(hi-lo<1e-9){lo-=0.5;hi+=0.5;} const pad=(hi-lo)*0.06;lo-=pad;hi+=pad;
|
||||
const Y=v=>top+ph-(v-lo)/(hi-lo)*ph, st=niceStep(hi-lo,5);
|
||||
c.strokeStyle=grid;c.fillStyle=muted;c.lineWidth=1;c.textAlign='right';
|
||||
for(let v=Math.ceil(lo/st)*st;v<=hi;v+=st){c.beginPath();c.moveTo(L,Y(v));c.lineTo(W-R,Y(v));c.stroke();c.fillText(fmtSI(v),L-5,Y(v)+4);}
|
||||
c.strokeStyle=muted;c.strokeRect(L,top,W-L-R,ph);
|
||||
c.fillStyle=muted;c.save();c.translate(12,top+ph/2);c.rotate(-Math.PI/2);c.textAlign='center';c.fillText(tr[0]?tr[0].unit:'',0,0);c.restore();
|
||||
tr.forEach(t=>{const col=COLORS[d.traces.indexOf(t)%COLORS.length];c.strokeStyle=col;c.lineWidth=1.6;c.beginPath();let on=false;t.y.forEach((v,i)=>{if(!isFinite(v)){on=false;return;}const px=X(d.x[i]),py=Y(v);on?c.lineTo(px,py):c.moveTo(px,py);on=true;});c.stroke();});
|
||||
if(simHover!==null){const i=simHover;c.strokeStyle='rgba(255,255,255,.5)';c.beginPath();c.moveTo(X(d.x[i]),top);c.lineTo(X(d.x[i]),top+ph);c.stroke();}
|
||||
});
|
||||
c.fillStyle=muted;c.textAlign='center';
|
||||
if(ac){for(let e=Math.ceil(Math.log10(x0));e<=Math.floor(Math.log10(x1));e++){const v=Math.pow(10,e);c.fillText(fmtSI(v,'Hz'),X(v),H-14);c.strokeStyle=grid;c.beginPath();c.moveTo(X(v),T);c.lineTo(X(v),H-B);c.stroke();}}
|
||||
else{const st=niceStep(x1-x0,6);for(let v=Math.ceil(x0/st)*st;v<=x1;v+=st)c.fillText(fmtSI(v,'s'),X(v),H-14);}
|
||||
let lx=L; d.traces.forEach((t,i)=>{c.fillStyle=COLORS[i%COLORS.length];c.fillRect(lx,8,10,3);c.fillStyle=fg;c.textAlign='left';const hv=simHover!==null?` ${fmtSI(t.y[simHover],t.unit)}`:'';const txt=t.name+hv;c.fillText(txt,lx+14,13);lx+=c.measureText(txt).width+30;});
|
||||
if(simHover!==null){c.fillStyle=muted;c.textAlign='right';c.fillText((ac?'f=':'t=')+fmtSI(d.x[simHover],ac?'Hz':'s'),W-R,13);}
|
||||
}
|
||||
$('sc').addEventListener('mousemove',e=>{
|
||||
const d=simRes;if(!d||!d.x)return;const r=$('sc').getBoundingClientRect(),L=58,R=12,fx=(e.clientX-r.left-L)/(r.width-L-R);
|
||||
if(fx<0||fx>1){simHover=null;drawChart();return;}
|
||||
const x0=d.x[0],x1=d.x[d.x.length-1],tv=d.type==='ac'?Math.pow(10,Math.log10(x0)+fx*(Math.log10(x1)-Math.log10(x0))):x0+fx*(x1-x0);
|
||||
let lo=0,hi=d.x.length-1;while(hi-lo>1){const m=(lo+hi)>>1;if(d.x[m]<tv)lo=m;else hi=m;} simHover=(tv-d.x[lo]<d.x[hi]-tv)?lo:hi; drawChart();
|
||||
});
|
||||
$('sc').addEventListener('mouseleave',()=>{simHover=null;drawChart();});
|
||||
new ResizeObserver(()=>drawChart()).observe($('simchart'));
|
||||
|
||||
// ───────────── 시작 ─────────────
|
||||
(async function init(){
|
||||
try{FP=(await api('/api/pcb/footprints')).footprints;FPM=Object.fromEntries(FP.map(f=>[f.id,f]));}catch(e){$('lib').innerHTML=`<div class="note bad">${esc(e.message)}</div>`;}
|
||||
@@ -468,7 +606,7 @@ function loadFile(inp){
|
||||
if(saved&&saved.board&&saved.parts){P={board:saved.board,parts:saved.parts,nets:saved.nets||[],fps:saved.fps||{},rules:{...DEF_RULES,...(saved.rules||{})},mill:{...DEF_MILL,...(saved.mill||{})}};syncUI();renderNets();updSel();registerFps();}
|
||||
else newProject(false);
|
||||
try{const k=await api('/api/pcb/kicad/status');$('kst').innerHTML=k.installed?`<span class="ok">● ${k.footprints.toLocaleString()} 풋프린트 · ${k.symbols.toLocaleString()} 심볼</span>`:'<span class="bad">미설치</span>';}catch(e){}
|
||||
renderLib();setMode('select');resize();fitView();
|
||||
renderLib();setMode('select');renderSim();resize();fitView();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
Reference in new issue
Block a user