feat(pcb): PCB 제작 앱 — 부품 배치·핀 연결 에디터, Freerouting 헤드리스 자동배선(DSN/SES), 격리 가공·드릴·외곽 밀링 G-code 생성(clipper-lib), 창작 메뉴에 추가

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-10-04 10:47:34 +09:00
1 parent 6f211da4c2
commit 8c4d60f5a2
13 files changed
+1039

No files matched your search

+3
View File
@@ -182,3 +182,6 @@ voicepack_ko/
/*key*.txt
/*token*.txt
/*secret*.txt
# --- 외부 도구 바이너리(Freerouting jar 등, scripts/install-freerouting.sh 로 설치) ---
.smallclaw/tools/
+6
View File
@@ -16,6 +16,7 @@
"avr8js": "^0.21.0",
"better-sqlite3": "^12.9.0",
"chromadb": "^3.5.0",
"clipper-lib": "^6.4.2",
"commander": "^14.0.3",
"cors": "^2.8.6",
"croner": "^10.0.1",
@@ -1289,6 +1290,11 @@
"node": ">= 10"
}
},
"node_modules/clipper-lib": {
"version": "6.4.2",
"resolved": "https://registry.npmjs.org/clipper-lib/-/clipper-lib-6.4.2.tgz",
"integrity": "sha512-knglhjQX5ihNj/XCIs6zCHrTemdvHY3LPZP9XB2nq2/3igyYMFueFXtfp84baJvEE+f8pO1ZS4UVeEgmLnAprQ=="
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+1
View File
@@ -44,6 +44,7 @@
"avr8js": "^0.21.0",
"better-sqlite3": "^12.9.0",
"chromadb": "^3.5.0",
"clipper-lib": "^6.4.2",
"commander": "^14.0.3",
"cors": "^2.8.6",
"croner": "^10.0.1",
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
# PCB 앱의 자동배선기(Freerouting)를 .smallclaw/tools/freerouting/ 에 설치한다.
# 사용: scripts/install-freerouting.sh [버전] (기본 2.4.1, Java 21+ 필요)
set -euo pipefail
VER="${1:-2.4.1}"
DIR="$(cd "$(dirname "$0")/.." && pwd)/.smallclaw/tools/freerouting"
mkdir -p "$DIR"
curl -fL -o "$DIR/freerouting-$VER.jar" "https://github.com/freerouting/freerouting/releases/download/v$VER/freerouting-$VER.jar"
ln -sf "freerouting-$VER.jar" "$DIR/freerouting.jar"
echo "installed: $DIR/freerouting-$VER.jar"
+62
View File
@@ -0,0 +1,62 @@
import express from 'express';
import { FOOTPRINTS } from '../../tools/pcb/footprints';
import { buildDsn, parseSes, validateProject } from '../../tools/pcb/dsn';
import { freeroutingStatus, runFreerouting } from '../../tools/pcb/freerouting';
import { buildGcode } from '../../tools/pcb/gcode';
import { DEFAULT_RULES, type PcbProject, type Routed } from '../../tools/pcb/types';
function normalize(raw: any): PcbProject {
const p = raw?.project ?? raw ?? {};
return {
board: { w: Number(p.board?.w), h: Number(p.board?.h) },
parts: Array.isArray(p.parts) ? p.parts.slice(0, 400).map((x: any) => ({ ref: String(x.ref), fp: String(x.fp), x: Number(x.x), y: Number(x.y), rot: Number(x.rot) || 0, value: x.value ? String(x.value) : undefined })) : [],
nets: Array.isArray(p.nets) ? p.nets.slice(0, 600).map((n: any) => ({ name: String(n.name), pins: Array.isArray(n.pins) ? n.pins.map(String) : [] })) : [],
rules: { ...DEFAULT_RULES, ...(p.rules || {}), layers: p.rules?.layers === 2 ? 2 : 1, copper: p.rules?.copper === 'F.Cu' ? 'F.Cu' : 'B.Cu' },
mill: p.mill,
};
}
export function registerPcbRoutes(app: express.Application, requireGatewayAuth: express.RequestHandler): void {
app.get('/api/pcb/status', requireGatewayAuth, (_req, res) => {
res.json(freeroutingStatus());
});
app.get('/api/pcb/footprints', requireGatewayAuth, (_req, res) => {
res.json({ footprints: FOOTPRINTS });
});
// 자동 배선: 프로젝트 → DSN → Freerouting → SES → 트레이스
app.post('/api/pcb/route', requireGatewayAuth, async (req, res) => {
try {
const project = normalize(req.body);
const errors = validateProject(project);
if (errors.length) { res.status(400).json({ error: errors[0], errors }); return; }
const run = await runFreerouting(buildDsn(project), {
maxPasses: Number(req.body?.maxPasses) || 30,
timeoutSec: Number(req.body?.timeoutSec) || 120,
});
const routed = parseSes(run.ses, project);
res.json({ ...routed, stats: { unrouted: run.unrouted, violations: run.violations, seconds: run.seconds }, log: run.log });
} catch (err: any) {
res.status(500).json({ error: String(err?.message || err) });
}
});
// 밀링 G-code: 프로젝트 + 배선 결과 → 격리/드릴/외곽 파일
app.post('/api/pcb/gcode', requireGatewayAuth, (req, res) => {
try {
const project = normalize(req.body);
const errors = validateProject(project);
if (errors.length) { res.status(400).json({ error: errors[0], errors }); return; }
const rr = req.body?.routed || {};
const routed: Routed = {
traces: Array.isArray(rr.traces) ? rr.traces : [],
vias: Array.isArray(rr.vias) ? rr.vias : [],
};
if (!routed.traces.length) { res.status(400).json({ error: '배선 결과가 없습니다. 먼저 자동 배선을 실행하세요.' }); return; }
res.json(buildGcode(project, routed));
} catch (err: any) {
res.status(500).json({ error: String(err?.message || err) });
}
});
}
+2
View File
@@ -92,6 +92,7 @@ import { registerUserRoutes } from './routes/routes-users';
import { registerDetectiveRoutes } from './routes/routes-detective';
import { registerPptxRoutes } from './routes/routes-pptx';
import { registerDentalJournalRoutes } from './routes/routes-dental-journals';
import { registerPcbRoutes } from './routes/routes-pcb';
import { registerVoiceRoutes } from './routes/routes-voice';
import { registerVoiceRealtimeRoutes, attachVoiceRealtimeWsProxy } from './routes/routes-voice-realtime';
import { registerMusicRoutes } from './routes/routes-music';
@@ -3062,6 +3063,7 @@ app.get('/api/files/{*filePath}', (req: express.Request, res: express.Response)
registerPptxRoutes(app, getSessionUser, requireGatewayAuth, imageSearch);
registerDentalJournalRoutes(app, requireGatewayAuth);
registerPcbRoutes(app, requireGatewayAuth);
+152
View File
@@ -0,0 +1,152 @@
// 프로젝트 → Specctra DSN(Freerouting 입력), SES(Freerouting 출력) → 트레이스.
// 단위: DSN 은 um(정수), 에디터는 mm. DSN 은 y 가 위로 증가하므로 y 를 뒤집는다.
// 회전은 DSN 에 맡기지 않고 부품 인스턴스마다 이미 회전된 핀 좌표로 image 를 만든다(회전 의미 불일치 방지).
import { FOOTPRINT_MAP, placedPads } from './footprints';
import type { PcbProject, Routed, Trace, Via } from './types';
const um = (mm: number) => Math.round(mm * 1000);
const safe = (s: string) => String(s).replace(/[^A-Za-z0-9_+\-.]/g, '_');
export function validateProject(p: PcbProject): string[] {
const errs: string[] = [];
if (!(p.board?.w > 5 && p.board?.h > 5)) errs.push('보드 크기가 너무 작습니다.');
const refs = new Set<string>();
for (const part of p.parts) {
if (!FOOTPRINT_MAP.has(part.fp)) errs.push(`알 수 없는 풋프린트: ${part.fp} (${part.ref})`);
if (refs.has(part.ref)) errs.push(`부품 번호 중복: ${part.ref}`);
refs.add(part.ref);
}
const pads = placedPads(p.parts);
const padIds = new Set(pads.map(x => x.id));
const margin = 0.5;
for (const pad of pads) {
if (pad.x - pad.w / 2 < margin || pad.y - pad.h / 2 < margin || pad.x + pad.w / 2 > p.board.w - margin || pad.y + pad.h / 2 > p.board.h - margin) {
errs.push(`${pad.id} 패드가 보드 가장자리(${margin}mm)에 너무 가깝거나 밖에 있습니다.`);
}
}
for (const n of p.nets) for (const pin of n.pins) if (!padIds.has(pin)) errs.push(`넷 ${n.name}: 존재하지 않는 핀 ${pin}`);
if (p.rules.layers === 1 && p.rules.copper === 'B.Cu' && pads.some(x => x.smd)) errs.push('아랫면(B.Cu) 단면 보드에는 SMD 부품을 쓸 수 없습니다. 윗면(F.Cu)을 고르거나 SMD를 빼세요.');
if (p.nets.filter(n => n.pins.length >= 2).length === 0) errs.push('2핀 이상 연결된 넷이 없습니다.');
return errs;
}
export function layerNames(p: PcbProject): string[] {
return p.rules.layers === 2 ? ['F.Cu', 'B.Cu'] : [p.rules.copper];
}
export function buildDsn(p: PcbProject): string {
const layers = layerNames(p);
const pads = placedPads(p.parts);
const L: string[] = [];
L.push('(pcb homeclaw.dsn');
L.push(' (parser (string_quote ") (space_in_quoted_tokens on) (host_cad "homeclaw") (host_version "1"))');
L.push(' (resolution um 10)');
L.push(' (unit um)');
L.push(' (structure');
layers.forEach((l, i) => L.push(` (layer ${l} (type signal) (property (index ${i})))`));
const W = um(p.board.w), H = um(p.board.h);
L.push(` (boundary (path pcb 0 0 0 0 ${-H} ${W} ${-H} ${W} 0 0 0))`);
const viaName = `Via[0-1]_${um(p.rules.viaDia)}:${um(p.rules.viaDrill)}_um`;
// 단면 보드에도 비아 정의가 필요하다(없으면 Freerouting 이 viaRule null NPE 로 배선을 시작도 못 함).
L.push(` (via "${viaName}")`);
L.push(` (rule (width ${um(p.rules.trace)}) (clearance ${um(p.rules.clearance)}) (clearance ${um(p.rules.clearance)} (type default_smd)))`);
L.push(' )');
// placement + library(image/padstack)
const padstacks = new Map<string, string>(); // key → 정의
const psName = (pad: typeof pads[number]) => {
const key = `${pad.shape}_${um(pad.w)}x${um(pad.h)}${pad.smd ? '_smd' : ''}`;
if (!padstacks.has(key)) {
const onLayers = pad.smd ? ['F.Cu'].filter(l => layers.includes(l)) : layers;
const shapes = onLayers.map(l => {
if (pad.shape === 'circle' || Math.abs(pad.w - pad.h) < 1e-6 && pad.shape !== 'rect') return ` (shape (circle ${l} ${um(pad.w)} 0 0))`;
if (pad.shape === 'oval') {
const horiz = pad.w >= pad.h, len = Math.abs(pad.w - pad.h) / 2, wd = Math.min(pad.w, pad.h);
return horiz ? ` (shape (path ${l} ${um(wd)} ${-um(len)} 0 ${um(len)} 0))` : ` (shape (path ${l} ${um(wd)} 0 ${-um(len)} 0 ${um(len)}))`;
}
return ` (shape (rect ${l} ${-um(pad.w / 2)} ${-um(pad.h / 2)} ${um(pad.w / 2)} ${um(pad.h / 2)}))`;
});
padstacks.set(key, ` (padstack ${key}\n${shapes.join('\n')}\n (attach off)\n )`);
}
return key;
};
L.push(' (placement');
for (const part of p.parts) L.push(` (component IMG_${safe(part.ref)} (place ${safe(part.ref)} ${um(part.x)} ${-um(part.y)} front 0))`);
L.push(' )');
L.push(' (library');
for (const part of p.parts) {
L.push(` (image IMG_${safe(part.ref)}`);
for (const pad of pads.filter(x => x.ref === part.ref)) {
L.push(` (pin ${psName(pad)} ${safe(pad.n)} ${um(pad.x - part.x)} ${-um(pad.y - part.y)})`);
}
L.push(' )');
}
for (const def of padstacks.values()) L.push(def);
{
const shapes = layers.map(l => ` (shape (circle ${l} ${um(p.rules.viaDia)} 0 0))`).join('\n');
L.push(` (padstack "${viaName}"\n${shapes}\n (attach off)\n )`);
}
L.push(' )');
// network
L.push(' (network');
const nets = p.nets.filter(n => n.pins.length >= 2);
const netName = new Map<string, string>();
nets.forEach((n, i) => netName.set(n.name, safe(n.name) || `N${i}`));
for (const n of nets) {
const pins = n.pins.map(id => { const k = id.lastIndexOf('-'); return `${safe(id.slice(0, k))}-${safe(id.slice(k + 1))}`; });
L.push(` (net ${netName.get(n.name)} (pins ${pins.join(' ')}))`);
}
const via = ` (circuit (use_via "${viaName}"))`;
L.push(` (class default ${nets.map(n => netName.get(n.name)).join(' ')}${via} (rule (width ${um(p.rules.trace)}) (clearance ${um(p.rules.clearance)})))`);
L.push(' )');
L.push(' (wiring)');
L.push(')');
return L.join('\n') + '\n';
}
// ── SES 파서 ─────────────────────────────────────────────────────────────────
type Node = string | Node[];
function parseSexp(src: string): Node {
const tok = src.match(/"[^"]*"|\(|\)|[^\s()]+/g) || [];
let i = 0;
const read = (): Node => {
const t = tok[i++];
if (t === '(') { const arr: Node[] = []; while (i < tok.length && tok[i] !== ')') arr.push(read()); i++; return arr; }
return t.startsWith('"') ? t.slice(1, -1) : t;
};
return read();
}
const head = (n: Node) => (Array.isArray(n) && typeof n[0] === 'string' ? n[0] : '');
export function parseSes(ses: string, p: PcbProject): Routed {
const root = parseSexp(ses) as Node[];
const routes = root.find(n => head(n) === 'routes') as Node[] | undefined;
if (!routes) throw new Error('SES 에 routes 가 없습니다.');
const res = routes.find(n => head(n) === 'resolution') as string[] | undefined;
const perUm = res ? Number(res[2]) : 10; // "resolution um 10" → 10 단위 = 1um
const toMm = (v: string) => Number(v) / perUm / 1000;
const traces: Trace[] = [], vias: Via[] = [];
const netOut = routes.find(n => head(n) === 'network_out') as Node[] | undefined;
for (const net of (netOut || []).filter(n => head(n) === 'net') as Node[][]) {
const name = String(net[1]);
for (const item of net.slice(2)) {
if (head(item) === 'wire') {
const path = (item as Node[]).find(n => head(n) === 'path') as string[] | undefined;
if (!path) continue;
const coords = path.slice(3).map(Number);
const pts: [number, number][] = [];
for (let k = 0; k + 1 < coords.length; k += 2) pts.push([coords[k] / perUm / 1000, -coords[k + 1] / perUm / 1000]);
traces.push({ net: name, layer: path[1], w: toMm(path[2]), pts });
} else if (head(item) === 'via') {
const v = item as string[];
vias.push({ net: name, x: toMm(v[2]), y: -toMm(v[3]) });
}
}
}
// 원래 이름으로 되돌리기(safe() 로 바뀐 경우 대비)
const back = new Map(p.nets.map(n => [safe(n.name), n.name]));
traces.forEach(t => { t.net = back.get(t.net) || t.net; });
vias.forEach(v => { v.net = back.get(v.net) || v.net; });
return { traces, vias };
}
+107
View File
@@ -0,0 +1,107 @@
// PCB 앱 풋프린트 라이브러리 + 부품 배치 좌표 변환.
// 좌표계: mm, 에디터 좌표(원점 좌상단, y 아래로 증가). 풋프린트 원점은 1번 핀(또는 중심).
// rot 은 시계 방향(화면 기준) 0/90/180/270. 클라이언트 JS(pcb-app.html)에 같은 변환이 있으니 함께 고칠 것.
export interface Pad { n: string; x: number; y: number; w: number; h: number; shape: 'circle' | 'rect' | 'oval'; drill: number }
export interface Footprint {
id: string; name: string; group: string; smd: boolean;
pads: Pad[];
body: { x0: number; y0: number; x1: number; y1: number }; // 실크/외곽선 그리기용
}
export interface PartInst { ref: string; fp: string; x: number; y: number; rot: number; value?: string }
export interface PlacedPad { ref: string; n: string; id: string; x: number; y: number; w: number; h: number; shape: Pad['shape']; drill: number; smd: boolean }
const round = (v: number) => Math.round(v * 1000) / 1000;
function tht(n: string | number, x: number, y: number, d: number, drill: number, first = false): Pad {
return { n: String(n), x: round(x), y: round(y), w: d, h: d, shape: first ? 'rect' : 'circle', drill };
}
function smd(n: string | number, x: number, y: number, w: number, h: number): Pad {
return { n: String(n), x: round(x), y: round(y), w, h, shape: 'rect', drill: 0 };
}
function bodyOf(pads: Pad[], pad = 0.8) {
const xs = pads.flatMap(p => [p.x - p.w / 2, p.x + p.w / 2]);
const ys = pads.flatMap(p => [p.y - p.h / 2, p.y + p.h / 2]);
return { x0: round(Math.min(...xs) - pad / 2), y0: round(Math.min(...ys) - pad / 2), x1: round(Math.max(...xs) + pad / 2), y1: round(Math.max(...ys) + pad / 2) };
}
function fp(id: string, name: string, group: string, pads: Pad[], isSmd = false, body?: Footprint['body']): Footprint {
return { id, name, group, smd: isSmd, pads, body: body ?? bodyOf(pads) };
}
export function buildFootprints(): Footprint[] {
const list: Footprint[] = [];
// 핀헤더 1xN, 2xN (2.54mm)
for (let n = 2; n <= 10; n++) {
const pads = Array.from({ length: n }, (_, i) => tht(i + 1, 0, i * 2.54, 1.8, 1.0, i === 0));
list.push(fp(`HDR-1x${n}`, `핀헤더 1x${n}`, '커넥터', pads));
}
for (const n of [3, 4, 5, 8]) {
const pads: Pad[] = [];
for (let r = 0; r < n; r++) for (let c = 0; c < 2; c++) pads.push(tht(r * 2 + c + 1, c * 2.54, r * 2.54, 1.8, 1.0, r === 0 && c === 0));
list.push(fp(`HDR-2x${n}`, `핀헤더 2x${n}`, '커넥터', pads));
}
list.push(fp('TERM-2P', '스크류 터미널 2P (5.08)', '커넥터', [tht(1, 0, 0, 2.4, 1.3, true), tht(2, 5.08, 0, 2.4, 1.3)]));
list.push(fp('TERM-3P', '스크류 터미널 3P (5.08)', '커넥터', [tht(1, 0, 0, 2.4, 1.3, true), tht(2, 5.08, 0, 2.4, 1.3), tht(3, 10.16, 0, 2.4, 1.3)]));
// DIP (행 간격 7.62)
for (const n of [8, 14, 16, 18, 20, 28]) {
const half = n / 2, pads: Pad[] = [];
for (let i = 0; i < half; i++) pads.push(tht(i + 1, 0, i * 2.54, 1.6, 0.9, i === 0));
for (let i = 0; i < half; i++) pads.push(tht(half + i + 1, 7.62, (half - 1 - i) * 2.54, 1.6, 0.9));
list.push(fp(`DIP-${n}`, `DIP-${n}`, 'IC', pads, false, { x0: 0.9, y0: -1.3, x1: 6.7, y1: (half - 1) * 2.54 + 1.3 }));
}
// 축방향 저항/다이오드
for (const p of [7.62, 10.16, 12.7]) {
list.push(fp(`RES-AX-${p}`, `저항 축형 ${p}mm`, '수동소자', [tht(1, 0, 0, 1.8, 0.9), tht(2, p, 0, 1.8, 0.9)]));
}
list.push(fp('DIODE-AX-10.16', '다이오드 축형 10.16mm', '수동소자', [tht(1, 0, 0, 1.8, 0.9, true), tht(2, 10.16, 0, 1.8, 0.9)]));
for (const p of [2.54, 5.08, 7.62]) {
list.push(fp(`CAP-RAD-${p}`, `커패시터 방사형 ${p}mm`, '수동소자', [tht(1, 0, 0, 1.8, 0.9, true), tht(2, p, 0, 1.8, 0.9)]));
}
list.push(fp('LED-5MM', 'LED 5mm', '수동소자', [tht(1, 0, 0, 1.8, 0.9, true), tht(2, 2.54, 0, 1.8, 0.9)]));
list.push(fp('TO-92', 'TO-92 (3핀)', '트랜지스터', [tht(1, 0, 0, 1.6, 0.9, true), tht(2, 2.54, 0, 1.6, 0.9), tht(3, 5.08, 0, 1.6, 0.9)]));
list.push(fp('TO-220', 'TO-220 (3핀)', '트랜지스터', [tht(1, 0, 0, 2.2, 1.1, true), tht(2, 2.54, 0, 2.2, 1.1), tht(3, 5.08, 0, 2.2, 1.1)]));
// SMD
list.push(fp('R-0805', '0805 (SMD)', 'SMD', [smd(1, 0, 0, 1.0, 1.4), smd(2, 1.9, 0, 1.0, 1.4)], true));
list.push(fp('R-1206', '1206 (SMD)', 'SMD', [smd(1, 0, 0, 1.2, 1.8), smd(2, 3.0, 0, 1.2, 1.8)], true));
{
const pads: Pad[] = [];
for (let i = 0; i < 4; i++) pads.push(smd(i + 1, 0, i * 1.27, 1.6, 0.6));
for (let i = 0; i < 4; i++) pads.push(smd(5 + i, 5.4, (3 - i) * 1.27, 1.6, 0.6));
list.push(fp('SOIC-8', 'SOIC-8 (SMD)', 'SMD', pads, true, { x0: 1.0, y0: -0.9, x1: 4.4, y1: 4.7 }));
}
list.push(fp('MOUNT-3.2', '고정 구멍 Ø3.2', '기타', [{ n: '1', x: 0, y: 0, w: 6, h: 6, shape: 'circle', drill: 3.2 }]));
return list;
}
export const FOOTPRINTS: Footprint[] = buildFootprints();
export const FOOTPRINT_MAP: Map<string, Footprint> = new Map(FOOTPRINTS.map(f => [f.id, f]));
/** 회전(시계 방향, y-아래 좌표계). rot 은 90의 배수로 정규화. */
export function rotPoint(x: number, y: number, rot: number): [number, number] {
const r = ((Math.round(rot / 90) * 90) % 360 + 360) % 360;
switch (r) {
case 90: return [-y, x];
case 180: return [-x, -y];
case 270: return [y, -x];
default: return [x, y];
}
}
export function placedPads(parts: PartInst[]): PlacedPad[] {
const out: PlacedPad[] = [];
for (const part of parts) {
const f = FOOTPRINT_MAP.get(part.fp);
if (!f) continue;
const r = ((Math.round(part.rot / 90) * 90) % 360 + 360) % 360;
const swap = r === 90 || r === 270;
for (const p of f.pads) {
const [dx, dy] = rotPoint(p.x, p.y, part.rot);
out.push({
ref: part.ref, n: p.n, id: `${part.ref}-${p.n}`,
x: round(part.x + dx), y: round(part.y + dy),
w: swap ? p.h : p.w, h: swap ? p.w : p.h, shape: p.shape, drill: p.drill, smd: f.smd,
});
}
}
return out;
}
+65
View File
@@ -0,0 +1,65 @@
// Freerouting(Java) 헤드리스 실행기 — DSN 을 받아 SES 와 배선 통계를 돌려준다.
import { spawn, spawnSync } from 'child_process';
import fs from 'fs';
import os from 'os';
import path from 'path';
const JAR = process.env.FREEROUTING_JAR || path.resolve(__dirname, '../../../.smallclaw/tools/freerouting/freerouting.jar');
export function freeroutingStatus(): { installed: boolean; jar: string; java: string | null } {
let java: string | null = null;
try {
const r = spawnSync('java', ['-version'], { encoding: 'utf8', timeout: 5000 });
const m = String(r.stderr || r.stdout || '').match(/version "([^"]+)"/);
java = m ? m[1] : null;
} catch { /* java 없음 */ }
return { installed: fs.existsSync(JAR), jar: JAR, java };
}
let busy = false;
export interface RouteRun { ses: string; unrouted: number; violations: number; seconds: number; log: string }
export async function runFreerouting(dsn: string, opts: { maxPasses?: number; timeoutSec?: number } = {}): Promise<RouteRun> {
const st = freeroutingStatus();
if (!st.installed) throw new Error('Freerouting 이 설치되어 있지 않습니다. scripts/install-freerouting.sh 를 실행하세요.');
if (!st.java) throw new Error('Java 를 찾을 수 없습니다(Java 21 이상 필요).');
if (busy) throw new Error('다른 자동 배선이 진행 중입니다. 잠시 후 다시 시도하세요.');
busy = true;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pcb-route-'));
const t0 = Date.now();
try {
const inFile = path.join(dir, 'board.dsn'), outFile = path.join(dir, 'board.ses');
fs.writeFileSync(inFile, dsn);
const passes = Math.min(Math.max(opts.maxPasses ?? 30, 1), 100);
const timeoutMs = Math.min(Math.max(opts.timeoutSec ?? 120, 10), 600) * 1000;
const args = ['-Djava.awt.headless=true', '-Xmx1g', '-jar', JAR, '-de', inFile, '-do', outFile, '-mp', String(passes), '-mt', '2'];
// HOME 을 임시 폴더로 돌려 사용자 홈에 freerouting.json/로그가 생기지 않게 한다.
const env = { ...process.env, HOME: dir, XDG_CONFIG_HOME: dir, XDG_STATE_HOME: dir, XDG_DATA_HOME: dir };
let log = '';
await new Promise<void>((resolve, reject) => {
const child = spawn('java', args, { cwd: dir, env });
const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new Error(`자동 배선 시간 초과(${timeoutMs / 1000}초) — 보드를 단순화하거나 패스 수를 줄여 보세요.`)); }, timeoutMs);
child.stdout.on('data', d => { log += d; });
child.stderr.on('data', d => { log += d; });
child.on('error', e => { clearTimeout(timer); reject(e); });
child.on('close', () => { clearTimeout(timer); resolve(); });
});
if (!fs.existsSync(outFile)) {
const tail = log.split('\n').filter(Boolean).slice(-4).join(' | ').slice(0, 400);
throw new Error(`Freerouting 이 결과를 만들지 못했습니다: ${tail}`);
}
const all = [...log.matchAll(/\((\d+) unrouted and (\d+) violations\)/g)];
const last = all[all.length - 1];
return {
ses: fs.readFileSync(outFile, 'utf8'),
unrouted: last ? Number(last[1]) : -1,
violations: last ? Number(last[2]) : -1,
seconds: Math.round((Date.now() - t0) / 100) / 10,
log: log.split('\n').filter(l => /INFO|WARN|ERROR/.test(l)).slice(-12).join('\n'),
};
} finally {
busy = false;
fs.rmSync(dir, { recursive: true, force: true });
}
}
+196
View File
@@ -0,0 +1,196 @@
// 배선 결과 → PCB 밀링 G-code (격리 가공 / 드릴 / 외곽 컷). 도형 연산은 clipper-lib(정수 µm).
// 좌표: 입력은 에디터 mm(좌상단 원점, y 아래로). G-code 는 보드 좌하단 원점, y 위로 → gy = H - y.
// 아랫면 가공(mirror)이면 gx = W - x (보드를 좌우로 뒤집어 동박면을 위로 놓고 깎는다).
import { placedPads } from './footprints';
import type { MillSettings, PcbProject, Routed } from './types';
import { DEFAULT_MILL } from './types';
import { layerNames } from './dsn';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const ClipperLib: any = require('clipper-lib');
const S = 1000; // mm → µm
type IP = { X: number; Y: number };
const ip = (x: number, y: number): IP => ({ X: Math.round(x * S), Y: Math.round(y * S) });
function circlePoly(cx: number, cy: number, d: number): IP[] {
const n = Math.max(16, Math.min(48, Math.round(d * 12)));
return Array.from({ length: n }, (_, i) => ip(cx + (d / 2) * Math.cos((2 * Math.PI * i) / n), cy + (d / 2) * Math.sin((2 * Math.PI * i) / n)));
}
function rectPoly(cx: number, cy: number, w: number, h: number): IP[] {
return [ip(cx - w / 2, cy - h / 2), ip(cx + w / 2, cy - h / 2), ip(cx + w / 2, cy + h / 2), ip(cx - w / 2, cy + h / 2)];
}
function offsetOpen(path: IP[], delta: number): IP[][] {
const co = new ClipperLib.ClipperOffset(2, 0.004 * S);
co.AddPath(path, ClipperLib.JoinType.jtRound, ClipperLib.EndType.etOpenRound);
const out: IP[][] = [];
co.Execute(out, delta * S);
return out;
}
function union(polys: IP[][]): IP[][] {
const c = new ClipperLib.Clipper();
c.AddPaths(polys, ClipperLib.PolyType.ptSubject, true);
const out: IP[][] = [];
c.Execute(ClipperLib.ClipType.ctUnion, out, ClipperLib.PolyFillType.pftNonZero, ClipperLib.PolyFillType.pftNonZero);
return out;
}
function offsetClosed(polys: IP[][], delta: number): IP[][] {
const co = new ClipperLib.ClipperOffset(2, 0.004 * S);
co.AddPaths(polys, ClipperLib.JoinType.jtRound, ClipperLib.EndType.etClosedPolygon);
const out: IP[][] = [];
co.Execute(out, delta * S);
return out;
}
/** 닫힌 윤곽선들(선)을 사각형 영역으로 잘라낸다(보드 밖으로 나가는 가공 제거). */
function clipLinesToRect(loops: IP[][], x0: number, y0: number, x1: number, y1: number): IP[][] {
const c = new ClipperLib.Clipper();
c.AddPaths(loops.map(l => [...l, l[0]]), ClipperLib.PolyType.ptSubject, false);
c.AddPath([ip(x0, y0), ip(x1, y0), ip(x1, y1), ip(x0, y1)], ClipperLib.PolyType.ptClip, true);
const tree = new ClipperLib.PolyTree();
c.Execute(ClipperLib.ClipType.ctIntersection, tree, ClipperLib.PolyFillType.pftNonZero, ClipperLib.PolyFillType.pftNonZero);
return ClipperLib.Clipper.OpenPathsFromPolyTree(tree) as IP[][];
}
type Pt = [number, number];
const toMm = (p: IP): Pt => [p.X / S, p.Y / S];
/** 한 층의 동박(패드+비아+트레이스) 합집합. */
function copperUnion(p: PcbProject, routed: Routed, layer: string): IP[][] {
const polys: IP[][] = [];
for (const pad of placedPads(p.parts)) {
if (pad.smd && layer !== 'F.Cu') continue;
if (pad.shape === 'circle') polys.push(circlePoly(pad.x, pad.y, pad.w));
else if (pad.shape === 'oval') polys.push(...offsetOpen([ip(pad.x - Math.max(0, pad.w - pad.h) / 2, pad.y), ip(pad.x + Math.max(0, pad.w - pad.h) / 2, pad.y)], Math.min(pad.w, pad.h) / 2));
else polys.push(rectPoly(pad.x, pad.y, pad.w, pad.h));
}
for (const v of routed.vias) polys.push(circlePoly(v.x, v.y, p.rules.viaDia));
for (const t of routed.traces) {
if (t.layer !== layer || t.pts.length < 2) continue;
polys.push(...offsetOpen(t.pts.map(([x, y]) => ip(x, y)), t.w / 2));
}
return union(polys);
}
/** 가장 가까운 경로 순서로 재배열(이동 거리 단축). */
function orderPaths(paths: IP[][]): IP[][] {
const left = paths.filter(pp => pp.length >= 2);
const out: IP[][] = [];
let cur: IP = { X: 0, Y: 0 };
while (left.length) {
let bi = 0, bd = Infinity;
left.forEach((pp, i) => { const d = (pp[0].X - cur.X) ** 2 + (pp[0].Y - cur.Y) ** 2; if (d < bd) { bd = d; bi = i; } });
const [pp] = left.splice(bi, 1);
out.push(pp);
cur = pp[pp.length - 1];
}
return out;
}
export interface GcodeResult {
files: Record<string, string>;
preview: { isolation: Record<string, Pt[][]>; drills: { x: number; y: number; d: number }[]; outline: Pt[] };
stats: { holes: number; drillSizes: number[]; isolationLengthMm: number; estMinutes: number };
warnings: string[];
}
export function buildGcode(p: PcbProject, routed: Routed): GcodeResult {
const m: MillSettings = { ...DEFAULT_MILL, ...(p.mill || {}) };
const W = p.board.w, H = p.board.h;
const warnings: string[] = [];
const layers = layerNames(p);
if (p.rules.clearance < m.toolDia - 1e-9) warnings.push(`최소 간격(${p.rules.clearance}mm)이 가공 폭(${m.toolDia}mm)보다 좁아 일부 배선 사이가 완전히 분리되지 않을 수 있습니다.`);
if (p.rules.trace < m.toolDia) warnings.push(`배선 폭(${p.rules.trace}mm)이 가공 폭(${m.toolDia}mm)보다 가늘어 박리 위험이 있습니다.`);
const mirrorFor = (layer: string) => (p.rules.layers === 2 ? layer === 'B.Cu' : m.mirror && layer === 'B.Cu');
const mirrorOthers = p.rules.layers === 1 && m.mirror && p.rules.copper === 'B.Cu';
const f = (v: number) => (Math.round(v * 1000) / 1000).toString();
const tx = (x: number, mir: boolean) => f(mir ? W - x : x);
const ty = (y: number) => f(H - y);
const head = (title: string) => [
`(${title} — homeclaw PCB)`,
`(board ${W} x ${H} mm, 단위 mm, 원점 = 보드 좌하단${mirrorOthers ? ', 좌우 반전(아랫면 가공)' : ''})`,
'G21 G90 G17 G94',
m.rpm > 0 ? `M3 S${m.rpm}` : '(스핀들 수동)',
`G0 Z${f(m.safeZ)}`,
];
const tail = ['M5', `G0 Z${f(m.safeZ)}`, 'G0 X0 Y0', 'M2'];
const files: Record<string, string> = {};
const isolation: Record<string, Pt[][]> = {};
let isoLen = 0, plunges = 0;
for (const layer of layers) {
const u = copperUnion(p, routed, layer);
const step = Math.max(m.toolDia * (1 - Math.min(Math.max(m.overlap, 0), 0.9)), 0.02);
let loops: IP[][] = [];
for (let i = 0; i < Math.max(1, Math.round(m.passes)); i++) loops.push(...offsetClosed(u, m.toolDia / 2 + i * step));
// 보드 밖으로 나가는 부분은 제거(가장자리 0.1mm 안쪽까지만 가공)
const clipped = orderPaths(clipLinesToRect(loops, 0.1, 0.1, W - 0.1, H - 0.1));
const mir = mirrorFor(layer);
const L = head(`${layer} 격리 가공 (${m.passes}패스, Ø${m.toolDia}mm)`);
isolation[layer] = clipped.map(pp => pp.map(toMm));
for (const pp of clipped) {
const pts = pp.map(toMm);
L.push(`G0 X${tx(pts[0][0], mir)} Y${ty(pts[0][1])}`);
L.push(`G1 Z${f(m.cutZ)} F${f(m.plunge)}`);
plunges++;
for (let k = 1; k < pts.length; k++) {
L.push(`G1 X${tx(pts[k][0], mir)} Y${ty(pts[k][1])} F${f(m.feed)}`);
isoLen += Math.hypot(pts[k][0] - pts[k - 1][0], pts[k][1] - pts[k - 1][1]);
}
L.push(`G0 Z${f(m.safeZ)}`);
}
L.push(...tail);
files[`copper-${layer === 'F.Cu' ? 'top' : 'bottom'}.nc`] = L.join('\n') + '\n';
}
// 드릴
const holes: { x: number; y: number; d: number }[] = [];
for (const pad of placedPads(p.parts)) if (pad.drill > 0) holes.push({ x: pad.x, y: pad.y, d: pad.drill });
if (p.rules.layers === 2) for (const v of routed.vias) holes.push({ x: v.x, y: v.y, d: p.rules.viaDrill });
const sizes = [...new Set(holes.map(h => Math.round(h.d * 100) / 100))].sort((a, b) => a - b);
{
const L = head('드릴');
for (const sz of sizes) {
L.push(`G0 Z${f(m.safeZ)}`, 'M5', `(공구 교체: Ø${sz}mm 드릴)`, 'M0', m.rpm > 0 ? `M3 S${m.rpm}` : '');
let pts = holes.filter(h => Math.round(h.d * 100) / 100 === sz).map(h => [ip(h.x, h.y)]);
for (const pp of orderPaths(pts.map(a => [a[0], a[0]]))) {
const [x, y] = toMm(pp[0]);
L.push(`G0 X${tx(x, mirrorOthers)} Y${ty(y)}`, `G1 Z${f(m.drillZ)} F${f(m.plunge)}`, `G0 Z${f(m.safeZ)}`);
}
}
L.push(...tail);
files['drill.nc'] = L.filter(Boolean).join('\n') + '\n';
}
// 외곽 컷 (공구 중심은 보드 바깥으로 반지름만큼 오프셋)
const outline: Pt[] = (() => {
const r = offsetClosed([[ip(0, 0), ip(W, 0), ip(W, H), ip(0, H)]], m.outlineDia / 2)[0] || [];
return r.map(toMm);
})();
{
const L = head(`외곽 컷 (Ø${m.outlineDia}mm)`);
const depthN = Math.max(1, Math.ceil(Math.abs(m.outlineZ) / Math.max(m.outlineStep, 0.1)));
L.push(`G0 X${tx(outline[0][0], mirrorOthers)} Y${ty(outline[0][1])}`);
for (let i = 1; i <= depthN; i++) {
const z = (m.outlineZ * i) / depthN;
L.push(`G1 Z${f(z)} F${f(m.plunge)}`);
for (let k = 1; k < outline.length; k++) L.push(`G1 X${tx(outline[k][0], mirrorOthers)} Y${ty(outline[k][1])} F${f(m.feed)}`);
L.push(`G1 X${tx(outline[0][0], mirrorOthers)} Y${ty(outline[0][1])} F${f(m.feed)}`);
}
L.push(...tail);
files['outline.nc'] = L.join('\n') + '\n';
}
if (p.rules.layers === 2) warnings.push('양면 보드: 아랫면 파일은 좌우 반전되어 있습니다. 뒤집어 가공할 때 기준 모서리(원점)를 맞춰 정렬하세요.');
warnings.push('외곽 컷에는 고정 탭이 없습니다. 양면테이프 등으로 기판을 고정하세요.');
return {
files,
preview: { isolation, drills: holes, outline },
stats: {
holes: holes.length, drillSizes: sizes, isolationLengthMm: Math.round(isoLen),
estMinutes: Math.round(((isoLen / Math.max(m.feed, 1)) + plunges * 0.02 + holes.length * 0.03) * 10) / 10,
},
warnings,
};
}
+37
View File
@@ -0,0 +1,37 @@
import type { PartInst } from './footprints';
export interface NetDef { name: string; pins: string[] } // pins: "R1-1" 형식
export interface PcbRules {
trace: number; // 배선 폭 mm
clearance: number; // 최소 간격 mm
layers: 1 | 2;
copper: 'F.Cu' | 'B.Cu'; // layers===1 일 때 쓰는 동박면
viaDia: number; viaDrill: number;
}
export interface MillSettings {
toolDia: number; // 격리 가공 유효 절삭폭 mm (V비트면 깊이에서의 폭)
passes: number; // 격리 패스 수
overlap: number; // 패스 간 겹침 0~0.9
cutZ: number; // 격리 깊이 (음수)
safeZ: number;
feed: number; plunge: number; rpm: number;
drillZ: number; // 드릴 깊이 (음수, 기판 두께 + 여유)
outlineDia: number; outlineZ: number; outlineStep: number;
mirror: boolean; // 아랫면 가공: 좌우 반전
}
export interface PcbProject {
board: { w: number; h: number };
parts: PartInst[];
nets: NetDef[];
rules: PcbRules;
mill?: MillSettings;
}
export interface Trace { net: string; layer: string; w: number; pts: [number, number][] } // mm, 에디터 좌표
export interface Via { net: string; x: number; y: number }
export interface Routed { traces: Trace[]; vias: Via[] }
export const DEFAULT_RULES: PcbRules = { trace: 0.4, clearance: 0.3, layers: 1, copper: 'B.Cu', viaDia: 0.9, viaDrill: 0.5 };
export const DEFAULT_MILL: MillSettings = {
toolDia: 0.2, passes: 2, overlap: 0.3, cutZ: -0.1, safeZ: 2, feed: 200, plunge: 60, rpm: 10000,
drillZ: -1.8, outlineDia: 1.0, outlineZ: -1.8, outlineStep: 0.6, mirror: true,
};
+1
View File
@@ -69,6 +69,7 @@
<button onclick="window.open('/html/music-app.html','_blank')">🎵 음악</button>
<button onclick="window.open('/html/writer-app.html','_blank')">✍️ 작가</button>
<button onclick="window.open('/html/studio-app.html','_blank')">🎨 스튜디오</button>
<button onclick="window.open('/html/pcb-app.html','_blank')">🔌 PCB</button>
</div>
</div>
<button class="mode-btn" onclick="window.open('/html/pptx-wizard.html','_blank')" title="슬라이드 제작">📊 슬라이드</button>
+397
View File
@@ -0,0 +1,397 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🔌 PCB 제작</title>
<style>
:root{--bg:#0f1117;--panel:#1a1d27;--panel2:#22263a;--line:#2e3250;--text:#e2e8f0;--muted:#94a3b8;--brand:#6366f1;--brand2:#818cf8;--green:#22c55e;--red:#ef4444;--yellow:#f59e0b;--r:10px;--canvas:#0d2a18;}
@media (prefers-color-scheme: light){:root{--bg:#eef1f8;--panel:#fff;--panel2:#f0f3fb;--line:#cdd3e8;--text:#1e2337;--muted:#5a6480;--brand:#4f52cc;--brand2:#4f52cc;--green:#15803d;--red:#dc2626;--yellow:#b45309;}}
*{box-sizing:border-box;margin:0;padding:0}
body{background:var(--bg);color:var(--text);font-family:'Segoe UI',system-ui,sans-serif;font-size:13px;height:100vh;display:flex;flex-direction:column;overflow:hidden}
header{display:flex;align-items:center;gap:8px;padding:8px 12px;background:var(--panel);border-bottom:1px solid var(--line);flex-wrap:wrap}
header h1{font-size:15px;margin-right:6px}
.btn{background:var(--panel2);color:var(--text);border:1px solid var(--line);border-radius:8px;padding:6px 11px;font-size:12.5px;cursor:pointer;white-space:nowrap}
.btn:hover{border-color:var(--brand)}
.btn.pri{background:var(--brand);color:#fff;border-color:var(--brand);font-weight:600}
.btn.on{border-color:var(--brand);color:var(--brand2);background:rgba(99,102,241,.16)}
.btn:disabled{opacity:.5;cursor:default}
#fr{font-size:11.5px;color:var(--muted);margin-left:auto}
.wrap{flex:1;display:grid;grid-template-columns:230px 1fr 320px;min-height:0}
aside{background:var(--panel);overflow-y:auto;padding:10px}
#left{border-right:1px solid var(--line)}#right{border-left:1px solid var(--line)}
h3{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);margin:10px 0 6px}
h3:first-child{margin-top:0}
input,select{background:var(--panel2);border:1px solid var(--line);border-radius:6px;padding:5px 7px;font-size:12.5px;color:var(--text);width:100%}
.lib button{display:block;width:100%;text-align:left;background:none;border:0;border-radius:6px;padding:5px 7px;color:var(--text);font-size:12.5px;cursor:pointer}
.lib button:hover{background:var(--panel2)}
.lib .grp{font-size:10.5px;color:var(--muted);margin:8px 0 2px;font-weight:700}
#center{display:flex;flex-direction:column;min-width:0;min-height:0}
#bar{display:flex;gap:6px;align-items:center;padding:6px 10px;background:var(--panel2);border-bottom:1px solid var(--line);flex-wrap:wrap;min-height:40px}
#bar .sp{flex:1}
#cv{flex:1;min-height:0;position:relative}
canvas{position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:none;background:var(--canvas)}
#hint{font-size:11.5px;color:var(--muted)}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:6px 8px}
.grid2 label{font-size:11px;color:var(--muted);display:block;margin-bottom:2px}
.net{background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:6px;margin-bottom:6px}
.net input{font-weight:600;margin-bottom:4px}
.chip{display:inline-flex;gap:3px;align-items:center;background:rgba(99,102,241,.16);color:var(--brand2);border-radius:10px;padding:1px 3px 1px 7px;font-size:11px;margin:1px 2px 1px 0}
.chip button{background:none;border:0;color:inherit;cursor:pointer;font-size:12px;line-height:1}
#res{font-size:12px;line-height:1.6}
.ok{color:var(--green)}.bad{color:var(--red)}.warn{color:var(--yellow)}
.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}
@media (max-width:1000px){
body{height:auto;overflow:auto}
.wrap{display:block}
#center{height:62vh}
aside{border:0;border-top:1px solid var(--line)}
}
</style>
</head>
<body>
<header>
<h1>🔌 PCB 제작</h1>
<button class="btn" onclick="newProject(true)">새로 만들기</button>
<button class="btn" onclick="loadSample()">예제</button>
<button class="btn" onclick="saveFile()">💾 저장</button>
<button class="btn" onclick="$('file').click()">📂 불러오기</button>
<input type="file" id="file" accept=".json" style="display:none" onchange="loadFile(this)">
<span id="fr">Freerouting 확인 중…</span>
</header>
<div class="wrap">
<aside id="left">
<h3>부품 라이브러리</h3>
<input id="libq" placeholder="검색 (예: DIP, 저항, LED)" oninput="renderLib()">
<div class="lib" id="lib"></div>
</aside>
<section id="center">
<div id="bar">
<button class="btn on" id="m-select" onclick="setMode('select')" title="V">↖ 선택·이동</button>
<button class="btn" id="m-connect" onclick="setMode('connect')" title="C">🔗 핀 연결</button>
<span id="selinfo" style="font-size:12px;color:var(--muted)"></span>
<button class="btn" onclick="rotateSel()" title="R">⟳ 회전</button>
<button class="btn" onclick="deleteSel()" title="Delete">🗑 삭제</button>
<span class="sp"></span>
<label style="font-size:11px;color:var(--muted)">격자</label>
<select id="snap" style="width:76px" onchange="draw()"><option value="0.5">0.5mm</option><option value="1.27">1.27mm</option><option value="2.54" selected>2.54mm</option><option value="0.1">0.1mm</option></select>
<button class="btn" onclick="fitView()">⤢ 맞춤</button>
</div>
<div id="cv"><canvas id="c"></canvas></div>
<div id="bar" style="border-top:1px solid var(--line);border-bottom:0"><span id="hint">부품을 왼쪽에서 눌러 추가 → 끌어서 배치 → 🔗 핀 연결 모드에서 핀을 차례로 클릭해 연결 → 오른쪽에서 자동 배선</span></div>
</section>
<aside id="right">
<details open><summary>보드 · 규칙</summary>
<div class="grid2">
<div><label>가로 mm</label><input type="number" id="bw" min="10" step="1" onchange="applySettings()"></div>
<div><label>세로 mm</label><input type="number" id="bh" min="10" step="1" onchange="applySettings()"></div>
<div style="grid-column:1/3"><label>동박 구성</label>
<select id="lay" onchange="applySettings()"><option value="1B">단면 — 아랫면(B.Cu), 부품은 윗면</option><option value="1F">단면 — 윗면(F.Cu), SMD 가능</option><option value="2">양면</option></select></div>
<div><label>배선 폭 mm</label><input type="number" id="tw" step="0.05" min="0.1" onchange="applySettings()"></div>
<div><label>최소 간격 mm</label><input type="number" id="cl" step="0.05" min="0.1" onchange="applySettings()"></div>
<div><label>비아 지름 mm</label><input type="number" id="vd" step="0.1" onchange="applySettings()"></div>
<div><label>비아 드릴 mm</label><input type="number" id="vh" step="0.1" onchange="applySettings()"></div>
</div>
</details>
<details open><summary>연결(넷)</summary>
<div id="nets"></div>
<div class="note">🔗 핀 연결 모드에서 핀 A → 핀 B를 클릭하면 이어집니다. 계속 클릭하면 같은 넷에 추가됩니다. Esc로 끊기.</div>
</details>
<details open><summary>자동 배선 (Freerouting)</summary>
<div class="grid2"><div><label>최대 패스</label><input type="number" id="passes" value="30" min="1" max="100"></div><div><label>제한 시간(초)</label><input type="number" id="tmo" value="120" min="10" max="600"></div></div>
<button class="btn pri" id="rbtn" style="width:100%;margin-top:8px" onclick="doRoute()">🧭 자동 배선</button>
<div id="rres" class="note"></div>
</details>
<details><summary>밀링 설정</summary>
<div class="grid2">
<div><label>가공 폭(절삭폭) mm</label><input type="number" id="m_toolDia" step="0.05" onchange="applyMill()"></div>
<div><label>격리 패스 수</label><input type="number" id="m_passes" step="1" min="1" max="6" onchange="applyMill()"></div>
<div><label>패스 겹침 0~0.9</label><input type="number" id="m_overlap" step="0.1" onchange="applyMill()"></div>
<div><label>격리 깊이 Z mm</label><input type="number" id="m_cutZ" step="0.01" onchange="applyMill()"></div>
<div><label>이송 mm/min</label><input type="number" id="m_feed" onchange="applyMill()"></div>
<div><label>하강 mm/min</label><input type="number" id="m_plunge" onchange="applyMill()"></div>
<div><label>안전 높이 Z</label><input type="number" id="m_safeZ" step="0.5" onchange="applyMill()"></div>
<div><label>스핀들 rpm (0=수동)</label><input type="number" id="m_rpm" step="1000" onchange="applyMill()"></div>
<div><label>드릴 깊이 Z</label><input type="number" id="m_drillZ" step="0.1" onchange="applyMill()"></div>
<div><label>외곽 비트 Ø mm</label><input type="number" id="m_outlineDia" step="0.1" onchange="applyMill()"></div>
<div><label>외곽 깊이 Z</label><input type="number" id="m_outlineZ" step="0.1" onchange="applyMill()"></div>
<div><label>외곽 단차 mm</label><input type="number" id="m_outlineStep" step="0.1" onchange="applyMill()"></div>
<div style="grid-column:1/3"><label><input type="checkbox" id="m_mirror" style="width:auto" onchange="applyMill()"> 아랫면 단면: 좌우 반전(뒤집어서 가공)</label></div>
</div>
<div class="note">V비트라면 "가공 폭"은 깊이에서의 유효 폭입니다. 최소 간격은 가공 폭 이상이어야 배선 사이가 분리됩니다.</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>
<div class="dl" id="dl"></div>
</details>
</aside>
</div>
<script>
const $=id=>document.getElementById(id);
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
function authH(extra){let t='';try{t=sessionStorage.getItem('smallclaw_token')||localStorage.getItem('smallclaw_token')||'';}catch(e){}const h={...(extra||{})};if(t)h['Authorization']='Bearer '+t;return h;}
async function api(url,body){
const r=await fetch(url,{method:body?'POST':'GET',credentials:'include',headers:authH(body?{'Content-Type':'application/json'}:{}),body:body?JSON.stringify(body):undefined});
const d=await r.json().catch(()=>({}));
if(!r.ok) throw new Error(d.error||('서버 오류 '+r.status));
return d;
}
// ───────────── 모델 ─────────────
const DEF_RULES={trace:0.4,clearance:0.3,layers:1,copper:'B.Cu',viaDia:0.9,viaDrill:0.5};
const DEF_MILL={toolDia:0.2,passes:2,overlap:0.3,cutZ:-0.1,safeZ:2,feed:200,plunge:60,rpm:10000,drillZ:-1.8,outlineDia:1.0,outlineZ:-1.8,outlineStep:0.6,mirror:true};
let FP=[],FPM={};
let P=null, routed=null, gres=null;
let view={s:12,ox:30,oy:30}, mode='select', sel=null, pending=null, drag=null, pan=null, hover=null;
const PREFIX={RES:'R',CAP:'C',LED:'D',DIODE:'D',DIP:'U',SOIC:'U',HDR:'J',TERM:'J',TO:'Q',R:'R',MOUNT:'H'};
function newProject(ask){
if(ask && P && P.parts.length && !confirm('현재 작업을 지우고 새로 만들까요?')) return;
P={board:{w:50,h:35},parts:[],nets:[],rules:{...DEF_RULES},mill:{...DEF_MILL}};
routed=null; gres=null; sel=null; pending=null; fitView(); syncUI(); changed(true);
}
function loadSample(){
if(P&&P.parts.length&&!confirm('현재 작업을 예제로 바꿀까요?')) return;
P={board:{w:40,h:30},parts:[
{ref:'J1',fp:'HDR-1x4',x:7.62,y:7.62,rot:0},{ref:'J2',fp:'HDR-1x4',x:30.48,y:7.62,rot:0},{ref:'R1',fp:'RES-AX-7.62',x:15.24,y:22.86,rot:0}],
nets:[{name:'A',pins:['J1-1','J2-1']},{name:'B',pins:['J1-2','J2-2']},{name:'C',pins:['J1-3','R1-1']},{name:'D',pins:['J2-3','R1-2']}],
rules:{...DEF_RULES},mill:{...DEF_MILL}};
routed=null;gres=null;sel=null;pending=null;fitView();syncUI();changed(true);
}
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();
}
// ───────────── 기하 ─────────────
function rotPoint(x,y,rot){const r=((Math.round(rot/90)*90)%360+360)%360;return r===90?[-y,x]:r===180?[-x,-y]:r===270?[y,-x]:[x,y];}
function padsOf(part){
const f=FPM[part.fp]; if(!f) return [];
const r=((Math.round(part.rot/90)*90)%360+360)%360, swap=r===90||r===270;
return f.pads.map(p=>{const [dx,dy]=rotPoint(p.x,p.y,part.rot);return {id:part.ref+'-'+p.n,ref:part.ref,n:p.n,x:part.x+dx,y:part.y+dy,w:swap?p.h:p.w,h:swap?p.w:p.h,shape:p.shape,drill:p.drill,smd:f.smd};});
}
function allPads(){return P.parts.flatMap(padsOf);}
function bboxOf(part){
const f=FPM[part.fp]; if(!f) return null; const b=f.body;
const c=[[b.x0,b.y0],[b.x1,b.y0],[b.x1,b.y1],[b.x0,b.y1]].map(([x,y])=>rotPoint(x,y,part.rot));
const xs=c.map(q=>q[0]+part.x), ys=c.map(q=>q[1]+part.y);
return {x0:Math.min(...xs),y0:Math.min(...ys),x1:Math.max(...xs),y1:Math.max(...ys)};
}
const snapV=v=>{const g=parseFloat($('snap').value)||0.5;return Math.round(v/g)*g;};
const sx=x=>x*view.s+view.ox, sy=y=>y*view.s+view.oy;
const wx=x=>(x-view.ox)/view.s, wy=y=>(y-view.oy)/view.s;
function netOfPin(id){return P.nets.findIndex(n=>n.pins.includes(id));}
function mst(pts){ // Prim — 넷의 에어와이어
if(pts.length<2) return []; const used=[0], edges=[], rest=pts.map((_,i)=>i).slice(1);
while(rest.length){let bi=-1,bj=-1,bd=Infinity;for(const i of used)for(const j of rest){const d=(pts[i].x-pts[j].x)**2+(pts[i].y-pts[j].y)**2;if(d<bd){bd=d;bi=i;bj=j;}}edges.push([pts[bi],pts[bj]]);used.push(bj);rest.splice(rest.indexOf(bj),1);}
return edges;
}
// ───────────── 그리기 ─────────────
const cv=$('c'), ctx=cv.getContext('2d');
function resize(){const r=cv.getBoundingClientRect(),d=window.devicePixelRatio||1;cv.width=Math.round(r.width*d);cv.height=Math.round(r.height*d);ctx.setTransform(d,0,0,d,0,0);draw();}
new ResizeObserver(resize).observe($('cv'));
function fitView(){const r=cv.getBoundingClientRect();if(!P||!r.width)return;const m=30;view.s=Math.max(2,Math.min((r.width-2*m)/P.board.w,(r.height-2*m)/P.board.h));view.ox=(r.width-P.board.w*view.s)/2;view.oy=(r.height-P.board.h*view.s)/2;draw();}
const LC={'F.Cu':'#ef5350','B.Cu':'#42a5f5'};
function copperColor(layer){return P.rules.layers===1?'#c9843f':(LC[layer]||'#c9843f');}
function draw(){
if(!P||!ctx) return;
const r=cv.getBoundingClientRect(); ctx.clearRect(0,0,r.width,r.height);
const W=P.board.w,H=P.board.h;
ctx.fillStyle='#10351f'; ctx.fillRect(sx(0),sy(0),W*view.s,H*view.s);
ctx.strokeStyle='#e8f5e9'; ctx.lineWidth=1.5; ctx.strokeRect(sx(0),sy(0),W*view.s,H*view.s);
const g=parseFloat($('snap').value)||2.54;
if(g*view.s>=7){ctx.fillStyle='rgba(255,255,255,.13)';for(let x=0;x<=W+1e-6;x+=g)for(let y=0;y<=H+1e-6;y+=g)ctx.fillRect(sx(x)-.5,sy(y)-.5,1.2,1.2);}
// 가공 미리보기
if(gres){
ctx.lineWidth=1;ctx.strokeStyle='#ffd54a';
for(const layer of Object.keys(gres.preview.isolation)) for(const loop of gres.preview.isolation[layer]){ctx.beginPath();loop.forEach((q,i)=>i?ctx.lineTo(sx(q[0]),sy(q[1])):ctx.moveTo(sx(q[0]),sy(q[1])));ctx.stroke();}
ctx.strokeStyle='#ff6b6b';ctx.setLineDash([6,4]);ctx.beginPath();gres.preview.outline.forEach((q,i)=>i?ctx.lineTo(sx(q[0]),sy(q[1])):ctx.moveTo(sx(q[0]),sy(q[1])));ctx.closePath();ctx.stroke();ctx.setLineDash([]);
}
// 트레이스·비아
if(routed){
for(const t of routed.traces){ctx.strokeStyle=copperColor(t.layer);ctx.globalAlpha=.85;ctx.lineWidth=Math.max(1.5,t.w*view.s);ctx.lineCap='round';ctx.lineJoin='round';ctx.beginPath();t.pts.forEach((q,i)=>i?ctx.lineTo(sx(q[0]),sy(q[1])):ctx.moveTo(sx(q[0]),sy(q[1])));ctx.stroke();}
ctx.globalAlpha=1;
for(const v of routed.vias){ctx.fillStyle='#cfd8dc';ctx.beginPath();ctx.arc(sx(v.x),sy(v.y),P.rules.viaDia/2*view.s,0,7);ctx.fill();ctx.fillStyle='#000';ctx.beginPath();ctx.arc(sx(v.x),sy(v.y),P.rules.viaDrill/2*view.s,0,7);ctx.fill();}
}
// 부품
for(const part of P.parts){
const b=bboxOf(part); if(!b) continue;
const isSel=sel===part.ref;
ctx.strokeStyle=isSel?'#fff176':'rgba(255,255,255,.55)'; ctx.lineWidth=isSel?2:1;
ctx.strokeRect(sx(b.x0),sy(b.y0),(b.x1-b.x0)*view.s,(b.y1-b.y0)*view.s);
ctx.fillStyle=isSel?'#fff176':'rgba(255,255,255,.8)'; ctx.font='11px sans-serif'; ctx.fillText(part.ref,sx(b.x0)+2,sy(b.y0)-3);
for(const pad of padsOf(part)){
const net=netOfPin(pad.id)>=0, cx=sx(pad.x), cy=sy(pad.y), w=pad.w*view.s, h=pad.h*view.s;
ctx.fillStyle=pending===pad.id?'#fff176':(net?'#e0a458':'#b0b7c3');
if(pad.shape==='circle'){ctx.beginPath();ctx.arc(cx,cy,w/2,0,7);ctx.fill();}else ctx.fillRect(cx-w/2,cy-h/2,w,h);
if(pad.drill>0){ctx.fillStyle='#10351f';ctx.beginPath();ctx.arc(cx,cy,pad.drill/2*view.s,0,7);ctx.fill();}
if(hover===pad.id){ctx.strokeStyle='#fff';ctx.lineWidth=1.5;ctx.strokeRect(cx-w/2-2,cy-h/2-2,w+4,h+4);}
}
}
// 에어와이어(미배선 연결 안내)
const pm=Object.fromEntries(allPads().map(p=>[p.id,p]));
ctx.lineWidth=1;ctx.strokeStyle='rgba(255,255,255,.55)';ctx.setLineDash([3,3]);
if(!routed) for(const n of P.nets){for(const [a,b] of mst(n.pins.map(i=>pm[i]).filter(Boolean))){ctx.beginPath();ctx.moveTo(sx(a.x),sy(a.y));ctx.lineTo(sx(b.x),sy(b.y));ctx.stroke();}}
ctx.setLineDash([]);
if(gres){ctx.fillStyle='#000';ctx.strokeStyle='#fff';for(const h of gres.preview.drills){ctx.beginPath();ctx.arc(sx(h.x),sy(h.y),Math.max(1.5,h.d/2*view.s),0,7);ctx.fill();}}
}
// ───────────── 입력 ─────────────
function pos(e){const r=cv.getBoundingClientRect();return {x:e.clientX-r.left,y:e.clientY-r.top};}
function hitPad(mx,my){
let best=null,bd=Infinity;
for(const p of allPads()){const dx=Math.abs(mx-p.x),dy=Math.abs(my-p.y);const rx=Math.max(p.w,1.6)/2+0.3,ry=Math.max(p.h,1.6)/2+0.3;if(dx<=rx&&dy<=ry){const d=dx*dx+dy*dy;if(d<bd){bd=d;best=p;}}}
return best;
}
function hitPart(mx,my){for(let i=P.parts.length-1;i>=0;i--){const b=bboxOf(P.parts[i]);if(b&&mx>=b.x0&&mx<=b.x1&&my>=b.y0&&my<=b.y1)return P.parts[i];}return null;}
cv.addEventListener('contextmenu',e=>e.preventDefault());
cv.addEventListener('pointerdown',e=>{
cv.setPointerCapture(e.pointerId); const q=pos(e), mx=wx(q.x), my=wy(q.y);
if(e.button===1||e.button===2||e.shiftKey||e.altKey){pan={x:q.x,y:q.y,ox:view.ox,oy:view.oy};return;}
if(mode==='connect'){
const p=hitPad(mx,my);
if(!p){pending=null;draw();return;}
if(pending&&pending!==p.id) connect(pending,p.id);
pending=p.id; draw(); return;
}
const part=hitPart(mx,my);
if(part){sel=part.ref;drag={part,dx:mx-part.x,dy:my-part.y,moved:false};}
else{sel=null;pan={x:q.x,y:q.y,ox:view.ox,oy:view.oy};}
updSel();draw();
});
cv.addEventListener('pointermove',e=>{
const q=pos(e);
if(pan){view.ox=pan.ox+q.x-pan.x;view.oy=pan.oy+q.y-pan.y;draw();return;}
if(drag){drag.part.x=snapV(wx(q.x)-drag.dx);drag.part.y=snapV(wy(q.y)-drag.dy);drag.moved=true;draw();return;}
if(mode==='connect'){const p=hitPad(wx(q.x),wy(q.y));const h=p?p.id:null;if(h!==hover){hover=h;draw();}}
});
cv.addEventListener('pointerup',()=>{ if(drag&&drag.moved) changed(); drag=null; pan=null; });
cv.addEventListener('wheel',e=>{e.preventDefault();const q=pos(e),f=e.deltaY<0?1.15:1/1.15,ns=Math.min(80,Math.max(2,view.s*f));view.ox=q.x-(q.x-view.ox)*(ns/view.s);view.oy=q.y-(q.y-view.oy)*(ns/view.s);view.s=ns;draw();},{passive:false});
window.addEventListener('keydown',e=>{
if(/INPUT|SELECT|TEXTAREA/.test(document.activeElement.tagName)) return;
const k=e.key.toLowerCase();
if(k==='r') rotateSel(); else if(k==='delete'||k==='backspace') deleteSel();
else if(k==='c') setMode('connect'); else if(k==='v') setMode('select');
else if(k==='escape'){pending=null;sel=null;updSel();draw();}
else if(sel&&k.startsWith('arrow')){const p=P.parts.find(x=>x.ref===sel),g=parseFloat($('snap').value)||0.5;if(p){if(k==='arrowleft')p.x-=g;if(k==='arrowright')p.x+=g;if(k==='arrowup')p.y-=g;if(k==='arrowdown')p.y+=g;changed();e.preventDefault();}}
});
function setMode(m){mode=m;pending=null;hover=null;$('m-select').classList.toggle('on',m==='select');$('m-connect').classList.toggle('on',m==='connect');cv.style.cursor=m==='connect'?'crosshair':'default';draw();}
// ───────────── 편집 ─────────────
function addPart(fpId){
const f=FPM[fpId]; if(!f) return;
const pre=PREFIX[fpId.split('-')[0]]||'X'; let n=1; while(P.parts.some(p=>p.ref===pre+n)) n++;
const b=f.body; const part={ref:pre+n,fp:fpId,x:snapV(P.board.w/2-(b.x0+b.x1)/2),y:snapV(P.board.h/2-(b.y0+b.y1)/2),rot:0};
P.parts.push(part); sel=part.ref; setMode('select'); changed();
}
function rotateSel(){const p=P.parts.find(x=>x.ref===sel);if(!p)return;p.rot=(p.rot+90)%360;changed();}
function deleteSel(){
if(!sel) return; const ref=sel;
P.parts=P.parts.filter(p=>p.ref!==ref);
P.nets.forEach(n=>n.pins=n.pins.filter(id=>!id.startsWith(ref+'-')));
P.nets=P.nets.filter(n=>n.pins.length>=1); sel=null; changed();
}
function connect(a,b){
const ia=netOfPin(a), ib=netOfPin(b);
if(ia>=0&&ia===ib) return;
if(ia<0&&ib<0){let n=1;while(P.nets.some(x=>x.name==='N'+n))n++;P.nets.push({name:'N'+n,pins:[a,b]});}
else if(ia>=0&&ib<0) P.nets[ia].pins.push(b);
else if(ia<0&&ib>=0) P.nets[ib].pins.push(a);
else{P.nets[ia].pins.push(...P.nets[ib].pins);P.nets.splice(ib,1);}
changed();
}
function renderNets(){
$('nets').innerHTML=P.nets.map((n,i)=>`<div class="net"><input value="${esc(n.name)}" onchange="renameNet(${i},this.value)">${n.pins.map(id=>`<span class="chip">${esc(id)}<button onclick="rmPin(${i},'${esc(id)}')">✕</button></span>`).join('')}<div><button class="btn" style="padding:2px 8px;font-size:11px;margin-top:4px" onclick="rmNet(${i})">넷 삭제</button></div></div>`).join('')||'<div class="note">아직 연결이 없습니다.</div>';
}
function renameNet(i,v){v=v.trim().replace(/[^A-Za-z0-9_+\-]/g,'_');if(!v||P.nets.some((n,j)=>j!==i&&n.name===v)){renderNets();return;}P.nets[i].name=v;changed(true);}
function rmPin(i,id){P.nets[i].pins=P.nets[i].pins.filter(x=>x!==id);if(P.nets[i].pins.length<1)P.nets.splice(i,1);changed();}
function rmNet(i){P.nets.splice(i,1);changed();}
function updSel(){
const p=P.parts.find(x=>x.ref===sel);
$('selinfo').textContent=p?`${p.ref} · ${FPM[p.fp]?FPM[p.fp].name:p.fp} · ${p.rot}°`:'';
}
// ───────────── 라이브러리/설정 UI ─────────────
function renderLib(){
const q=$('libq').value.trim().toLowerCase(); let h='',g='';
for(const f of FP){ if(q&&!(f.name+' '+f.id+' '+f.group).toLowerCase().includes(q)) continue;
if(f.group!==g){g=f.group;h+=`<div class="grp">${esc(g)}</div>`;}
h+=`<button onclick="addPart('${esc(f.id)}')">${esc(f.name)}</button>`; }
$('lib').innerHTML=h||'<div class="note">결과 없음</div>';
}
function syncUI(){
$('bw').value=P.board.w;$('bh').value=P.board.h;
$('lay').value=P.rules.layers===2?'2':(P.rules.copper==='F.Cu'?'1F':'1B');
$('tw').value=P.rules.trace;$('cl').value=P.rules.clearance;$('vd').value=P.rules.viaDia;$('vh').value=P.rules.viaDrill;
for(const k of Object.keys(DEF_MILL)){const el=$('m_'+k);if(!el)continue;if(el.type==='checkbox')el.checked=!!P.mill[k];else el.value=P.mill[k];}
}
function applySettings(){
P.board.w=Math.max(10,+$('bw').value||50);P.board.h=Math.max(10,+$('bh').value||35);
const l=$('lay').value;P.rules.layers=l==='2'?2:1;P.rules.copper=l==='1F'?'F.Cu':'B.Cu';
P.rules.trace=+$('tw').value||0.4;P.rules.clearance=+$('cl').value||0.3;P.rules.viaDia=+$('vd').value||0.9;P.rules.viaDrill=+$('vh').value||0.5;
changed();fitView();
}
function applyMill(){
for(const k of Object.keys(DEF_MILL)){const el=$('m_'+k);if(!el)continue;P.mill[k]=el.type==='checkbox'?el.checked:(+el.value);}
gres=null;$('res').innerHTML='';$('dl').innerHTML='';save();draw();
}
// ───────────── 배선 · G-code ─────────────
async function doRoute(){
const b=$('rbtn');b.disabled=true;$('rres').innerHTML='Freerouting 실행 중… (보드에 따라 수 초~수 분)';
try{
const d=await api('/api/pcb/route',{project:P,maxPasses:+$('passes').value||30,timeoutSec:+$('tmo').value||120});
routed={traces:d.traces,vias:d.vias};gres=null;$('res').innerHTML='';$('dl').innerHTML='';
const un=d.stats.unrouted;
$('rres').innerHTML=un===0?`<span class="ok">✔ 배선 완료</span> · ${d.traces.length}구간 · 비아 ${d.vias.length}개 · ${d.stats.seconds}초`
:`<span class="bad">✖ 미배선 ${un<0?'?':un}건</span> (${d.traces.length}구간 배선됨, ${d.stats.seconds}초)<br>단면 보드는 배선이 교차하면 풀 수 없습니다. 부품을 옮기거나 회전해 교차를 줄이거나, 양면/점퍼를 쓰세요.`;
save();draw();
}catch(e){$('rres').innerHTML=`<span class="bad">${esc(e.message)}</span>`;}
finally{b.disabled=false;}
}
async function doGcode(){
if(!routed){$('res').innerHTML='<span class="bad">먼저 자동 배선을 실행하세요.</span>';return;}
const b=$('gbtn');b.disabled=true;$('res').textContent='생성 중…';
try{
gres=await api('/api/pcb/gcode',{project:P,routed});
const s=gres.stats;
$('res').innerHTML=`구멍 ${s.holes}개(드릴 ${s.drillSizes.join(', ')||'-'}mm) · 격리 경로 ${s.isolationLengthMm}mm · 예상 약 ${s.estMinutes}분`+gres.warnings.map(w=>`<div class="warn">⚠ ${esc(w)}</div>`).join('');
$('dl').innerHTML=Object.keys(gres.files).map(n=>`<a href="#" onclick="dlFile('${esc(n)}');return false">⬇ ${esc(n)}</a>`).join('')+'<div class="note">순서: 격리(copper) → 드릴(공구 교체 시 M0 일시정지) → 외곽. 가공 전 Z 영점·고정을 확인하세요.</div>';
draw();
}catch(e){$('res').innerHTML=`<span class="bad">${esc(e.message)}</span>`;}
finally{b.disabled=false;}
}
function dlFile(n){const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([gres.files[n]],{type:'text/plain'}));a.download=n;a.click();setTimeout(()=>URL.revokeObjectURL(a.href),2000);}
function saveFile(){const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify({project:P,routed},null,1)],{type:'application/json'}));a.download='pcb-project.json';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),2000);}
function loadFile(inp){
const f=inp.files[0];if(!f)return;const rd=new FileReader();
rd.onload=()=>{try{const d=JSON.parse(rd.result);const pr=d.project||d;if(!pr.board||!pr.parts)throw new Error('PCB 프로젝트 파일이 아닙니다.');
P={board:pr.board,parts:pr.parts,nets:pr.nets||[],rules:{...DEF_RULES,...(pr.rules||{})},mill:{...DEF_MILL,...(pr.mill||{})}};
routed=d.routed&&d.routed.traces?d.routed:null;gres=null;sel=null;pending=null;fitView();syncUI();changed(true);}catch(e){alert('불러오기 실패: '+e.message);}};
rd.readAsText(f);inp.value='';
}
// ───────────── 시작 ─────────────
(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>`;}
try{const s=await api('/api/pcb/status');$('fr').innerHTML=s.installed&&s.java?`<span class="ok">● Freerouting 준비됨</span> (Java ${esc(s.java)})`:`<span class="bad">● Freerouting 미설치</span> — scripts/install-freerouting.sh`;}catch(e){$('fr').textContent='';}
let saved=null;try{saved=JSON.parse(localStorage.getItem('pcb-project')||'null');}catch(e){}
if(saved&&saved.board&&saved.parts){P={board:saved.board,parts:saved.parts,nets:saved.nets||[],rules:{...DEF_RULES,...(saved.rules||{})},mill:{...DEF_MILL,...(saved.mill||{})}};syncUI();renderNets();updSel();}
else newProject(false);
renderLib();setMode('select');resize();fitView();
})();
</script>
</body>
</html>