From f5652d63d9f2770c51c454cd968644fed77e0131 Mon Sep 17 00:00:00 2001 From: kim Date: Sat, 10 Oct 2026 11:43:38 +0900 Subject: [PATCH] =?UTF-8?q?feat(stl-cad):=203=EB=A9=B4=EB=8F=84=EB=A5=BC?= =?UTF-8?q?=20=EB=8F=84=EB=A9=B4=20=EC=8B=9C=ED=8A=B8=EB=A1=9C=20=EC=97=85?= =?UTF-8?q?=EA=B7=B8=EB=A0=88=EC=9D=B4=EB=93=9C=20=E2=80=94=20=EC=A0=80?= =?UTF-8?q?=EB=A9=B4=EB=8F=84=C2=B7=EB=8B=A8=EB=A9=B4=20A-A=C2=B7=EA=B5=AC?= =?UTF-8?q?=EB=A9=8D=20=EC=B9=98=EC=88=98=ED=91=9C=C2=B7=EB=86=92=EC=9D=B4?= =?UTF-8?q?=20=EB=A0=88=EB=B2=A8=C2=B7=EC=88=A8=EC=9D=80=EC=84=A0=C2=B7?= =?UTF-8?q?=EC=9B=90=EC=A0=90=C2=B7A4=201:1=20=ED=85=9C=ED=94=8C=EB=A6=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 삼각형 직접 z-버퍼 투영(scripts/stl_drawing.py), 실패/초대형 모델은 옛 OpenSCAD 합성으로 폴백. 우측면도 좌우 방향을 +X에서 본 정확한 방향으로 정정. Co-Authored-By: Claude Sonnet 5.5 --- scripts/stl_drawing.py | 537 ++++++++++++++++++++++++++++++++++++ src/tools/stl-cad.ts | 14 +- src/tools/stl-three-view.ts | 67 ++++- 3 files changed, 610 insertions(+), 8 deletions(-) create mode 100644 scripts/stl_drawing.py diff --git a/scripts/stl_drawing.py b/scripts/stl_drawing.py new file mode 100644 index 0000000..7404be8 --- /dev/null +++ b/scripts/stl_drawing.py @@ -0,0 +1,537 @@ +#!/usr/bin/env python3 +"""STL -> 제작용 도면 시트(제3각법) v2. + +stl-three-view.ts가 호출한다(job.json 경로 = argv[1]). 옛 방식(OpenSCAD 실루엣 합성)과 달리 삼각형을 +직접 z-버퍼로 투영해서 단차(높이별 음영/윤곽), 저면도, 단면도(A-A), 사각 창/구멍 치수, 숨은선(점선), +원점·높이 레벨 표기, 치수표를 만든다. 삼각형이 너무 많으면(>MAX_TRI) ok:false로 돌려 옛 렌더러로 폴백한다. + +job: {stl, out, title, circles:{top,front,right:[{u,v,dia,diaMax?,taper?}]}, template_out?} +출력(마지막 줄 JSON): {ok, dims, holes:[...], levels, section:{y}, template, sheet} +""" +import sys, json, math +import numpy as np +import cv2 +from PIL import Image, ImageDraw, ImageFont +from scipy import ndimage + +MAX_TRI = 120000 +SS = 2 # 슈퍼샘플링 배수 + + +def load_stl(path): + data = open(path, 'rb').read() + n = int.from_bytes(data[80:84], 'little') if len(data) >= 84 else 0 + if len(data) == 84 + 50 * n and n > 0: + dt = np.dtype([('n', ' 1e-6)[0] + for i in idx: + x = X[i]; y = Y[i]; w = Wd[i] + x0 = max(int(math.floor(x.min())), 0); x1 = min(int(math.ceil(x.max())) + 1, Wpx) + y0 = max(int(math.floor(y.min())), 0); y1 = min(int(math.ceil(y.max())) + 1, Hpx) + if x1 <= x0 or y1 <= y0: + continue + gx, gy = np.meshgrid(np.arange(x0, x1) + 0.5, np.arange(y0, y1) + 0.5) + d = (x[1] - x[0]) * (y[2] - y[0]) - (x[2] - x[0]) * (y[1] - y[0]) + l1 = ((x[1] - gx) * (y[2] - gy) - (x[2] - gx) * (y[1] - gy)) / d + l2 = ((x[2] - gx) * (y[0] - gy) - (x[0] - gx) * (y[2] - gy)) / d + l3 = 1.0 - l1 - l2 + eps = -1e-3 + m = (l1 >= eps) & (l2 >= eps) & (l3 >= eps) + if not m.any(): + continue + z = (l1 * w[0] + l2 * w[1] + l3 * w[2]).astype(np.float32) + sub = zb[y0:y1, x0:x1] + if keep_max: + upd = m & (z > sub) + else: + upd = m & (z < sub) + sub[upd] = z[upd] + zb[np.isinf(zb)] = np.nan + return zb + + +def font(sz): + for fp in ('/usr/share/fonts/truetype/nanum/NanumSquareRoundB.ttf', + '/usr/share/fonts/truetype/nanum/NanumBarunGothic.ttf', + '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf'): + try: + return ImageFont.truetype(fp, sz) + except Exception: + pass + return ImageFont.load_default() + + +def fmt(n): + r = round(float(n), 1) + if abs(r) < 0.05: + r = 0.0 + return str(int(r)) if r == int(r) else ('%.1f' % r) + + +def shade(D, wmin, wmax, edge_thr): + """깊이맵 -> RGB(높이 음영 + 단차 윤곽선 + 외곽선). SS 해상도 그대로 돌려준다.""" + mask = ~np.isnan(D) + t = np.zeros(D.shape, np.float32) + if wmax - wmin > 1e-6: + t = np.where(mask, (D - wmin) / (wmax - wmin), 0).astype(np.float32) + lo = np.array([236, 238, 242], np.float32); hi = np.array([196, 160, 52], np.float32) + rgb = (lo[None, None, :] * (1 - t[..., None]) + hi[None, None, :] * t[..., None]) + rgb[~mask] = 255 + Df = np.where(mask, D, wmin - 1e3).astype(np.float32) + gx = np.abs(np.diff(Df, axis=1, prepend=Df[:, :1])) + gy = np.abs(np.diff(Df, axis=0, prepend=Df[:1, :])) + edge = ((gx > edge_thr) | (gy > edge_thr)) & True + # 외곽(마스크 경계)도 선으로 + mk = mask.astype(np.uint8) + er = cv2.erode(mk, np.ones((3, 3), np.uint8)) + edge |= (mk > 0) & (er == 0) + edge = cv2.dilate(edge.astype(np.uint8), np.ones((3, 3), np.uint8)) > 0 + rgb[edge] = (28, 28, 28) + return np.clip(rgb, 0, 255).astype(np.uint8), mask + + +def levels_of(D, tol=0.15): + v = D[~np.isnan(D)] + if v.size == 0: + return [] + r = np.round(v, 1) + vals, cnt = np.unique(r, return_counts=True) + keep = [(float(a), int(c)) for a, c in zip(vals, cnt) if c >= 0.01 * v.size] + out = [] + for a, c in sorted(keep): + if out and abs(a - out[-1]) < tol: + continue + out.append(a) + return out + + +def section_y(P, y0, umin, zmax, s, Wpx, Hpx): + """평면 y=y0 단면(x-z)을 SS 해상도로 채워서(해칭) 돌려준다. 윤곽선 선분도 반환.""" + d = P[:, :, 1] - y0 + segs = [] + for a, b in ((0, 1), (1, 2), (2, 0)): + da = d[:, a]; db = d[:, b] + cross = (da * db) < 0 + t = np.where(cross, da / np.where(da - db == 0, 1, da - db), 0) + pts = P[:, a, :] + t[:, None] * (P[:, b, :] - P[:, a, :]) + segs.append((cross, pts[:, 0], pts[:, 2])) + n = P.shape[0] + cnt = sum(c.astype(int) for c, _, _ in segs) + sel = np.nonzero(cnt == 2)[0] + seg_list = [] + for i in sel: + p = [(sx[i], sz[i]) for c, sx, sz in segs if c[i]] + seg_list.append((p[0][0], p[0][1], p[1][0], p[1][1])) + S = np.array(seg_list, dtype=np.float64).reshape(-1, 4) + fill = np.zeros((Hpx, Wpx), np.uint8) + if S.shape[0] == 0: + return fill, S + cols = []; zs = [] + for x1, z1, x2, z2 in S: + if abs(x2 - x1) < 1e-9: + continue + c0 = int(math.ceil((min(x1, x2) - umin) * s - 0.5)); c1 = int(math.floor((max(x1, x2) - umin) * s - 0.5)) + if c1 < c0: + continue + c = np.arange(c0, c1 + 1) + xx = umin + (c + 0.5) / s + z = z1 + (xx - x1) / (x2 - x1) * (z2 - z1) + cols.append(c); zs.append(z) + if not cols: + return fill, S + cols = np.concatenate(cols); zs = np.concatenate(zs) + order = np.lexsort((zs, cols)) + cols = cols[order]; zs = zs[order] + bounds = np.nonzero(np.diff(cols))[0] + 1 + for cc, zz in zip(np.split(cols, bounds), np.split(zs, bounds)): + c = int(cc[0]) + if c < 0 or c >= Wpx: + continue + k = len(zz) - (len(zz) % 2) + for j in range(0, k, 2): + r0 = int(round((zmax - zz[j + 1]) * s)); r1 = int(round((zmax - zz[j]) * s)) + r0 = max(r0, 0); r1 = min(r1, Hpx) + if r1 > r0: + fill[r0:r1, c] = 1 + return fill, S + + +def main(): + job = json.load(open(sys.argv[1])) + P = load_stl(job['stl']) + n = P.shape[0] + if n == 0: + print(json.dumps({'ok': False, 'error': 'empty mesh'})); return + if n > MAX_TRI: + print(json.dumps({'ok': False, 'error': 'too many triangles: %d' % n})); return + mn = P.reshape(-1, 3).min(axis=0); mx = P.reshape(-1, 3).max(axis=0) + W, D, H = [float(mx[i] - mn[i]) for i in range(3)] + if min(W, D, H) <= 0: + print(json.dumps({'ok': False, 'error': 'flat mesh'})); return + + # ── 시트 레이아웃/축척 ── + ML, MR, G, CAP, DIMH = 150, 40, 70, 34, 56 + COLB_MIN = 360 + SW = min((1600 - ML - MR - G - COLB_MIN) / W, (1600 - ML - MR - G) / (W + D)) + SH = (2500 - 4 * (CAP + DIMH) - 150) / (2 * D + 2 * H) + S = max(0.5, min(SW, SH, 14.0)) + s = S * SS + wpx = int(math.ceil(W * s)) + 2; dpx = int(math.ceil(D * s)) + 2; hpx = int(math.ceil(H * s)) + 2 + + # ── 래스터 ── + top_max = raster(P, 0, 1, 2, 1, 1, 1, mn[0], mx[1], s, wpx, dpx, True) + top_min = raster(P, 0, 1, 2, 1, 1, 1, mn[0], mx[1], s, wpx, dpx, False) + front = raster(P, 0, 2, 1, 1, 1, -1, mn[0], mx[2], s, wpx, hpx, True) + right = raster(P, 1, 2, 0, 1, 1, 1, mn[1], mx[2], s, dpx, hpx, True) + + # ── 구멍(평면도에서 둘러싸인 빈 영역) ── + mask_top = ~np.isnan(top_max) + lab, nl = ndimage.label(~mask_top) + holes = [] + border = set(np.unique(np.concatenate([lab[0, :], lab[-1, :], lab[:, 0], lab[:, -1]])).tolist()) + for k in range(1, nl + 1): + if k in border: + continue + ys, xs = np.nonzero(lab == k) + if xs.size == 0: + continue + bw = (xs.max() - xs.min() + 1) / s; bh = (ys.max() - ys.min() + 1) / s + if bw * bh < 4.0: + continue + fillr = xs.size / s / s / (bw * bh) + asp = bw / bh if bh else 0 + circle = 0.93 <= asp <= 1.07 and 0.72 <= fillr <= 0.84 + cx = mn[0] + (xs.min() + xs.max() + 1) / 2 / s + cy = mx[1] - (ys.min() + ys.max() + 1) / 2 / s + # 구멍 둘레의 윗면·아랫면 높이 → 점선 범위 + hm = (lab == k).astype(np.uint8) + ring = (cv2.dilate(hm, np.ones((7, 7), np.uint8)) > 0) & mask_top + ztop = float(np.nanmax(top_max[ring])) if ring.any() else mx[2] + zbot = float(np.nanmin(top_min[ring])) if ring.any() else mn[2] + holes.append({'kind': 'circle' if circle else 'rect', 'w': bw, 'h': bh, 'dia': (bw + bh) / 2, + 'cx': cx, 'cy': cy, 'x0': cx - bw / 2, 'x1': cx + bw / 2, 'y0': cy - bh / 2, 'y1': cy + bh / 2, + 'ztop': ztop, 'zbot': zbot, 'area': bw * bh}) + holes.sort(key=lambda h: -h['area']) + holes = holes[:16] + + # ── 단면 위치: 가장 큰 구멍 중심 y, 없으면 bbox 가운데 ── + sy = holes[0]['cy'] if holes else (mn[1] + mx[1]) / 2 + sy = min(max(sy, mn[1] + 1e-3 * D + 0.01), mx[1] - 1e-3 * D - 0.01) + 1e-4 * D + fill, segs = section_y(P, sy, mn[0], mx[2], s, wpx, hpx) + + # ── 높이 레벨 ── + lv_top = levels_of(top_max); lv_bot = levels_of(top_min) + lv = sorted(set([round(a, 1) for a in lv_top + lv_bot])) + # 가까운 값 병합 + levels = [] + for a in lv: + if not levels or a - levels[-1] > 0.15: + levels.append(a) + bottom_flat = len(lv_bot) <= 1 + + # ── 각 뷰 이미지(SS -> 최종) ── + thr = max(0.2, H * 0.01) + def to_img(rgb): + im = Image.fromarray(rgb) + return im.resize((max(2, int(round(rgb.shape[1] / SS))), max(2, int(round(rgb.shape[0] / SS)))), Image.LANCZOS) + + rgb_top, _ = shade(top_max, mn[2], mx[2], thr) + rgb_front, _ = shade(front, -mx[1], -mn[1], max(0.2, D * 0.01)) + rgb_right, _ = shade(right, mn[0], mx[0], max(0.2, W * 0.01)) + bot_w = np.where(np.isnan(top_min), np.nan, -top_min).astype(np.float32) + rgb_bot, _ = shade(np.flipud(bot_w), -mx[2], -mn[2], thr) + + # 단면 이미지: 해칭 + sec = np.full(fill.shape + (3,), 255, np.uint8) + yy, xx = np.mgrid[0:fill.shape[0], 0:fill.shape[1]] + hatch = ((xx + yy) % int(round(8 * SS)) < SS) & (fill > 0) + sec[fill > 0] = (246, 244, 236) + sec[hatch] = (150, 140, 90) + for x1, z1, x2, z2 in segs: + p1 = (int(round((x1 - mn[0]) * s)), int(round((mx[2] - z1) * s))) + p2 = (int(round((x2 - mn[0]) * s)), int(round((mx[2] - z2) * s))) + cv2.line(sec, p1, p2, (28, 28, 28), SS + 1, cv2.LINE_AA) + + I_top, I_front, I_right, I_bot, I_sec = map(to_img, (rgb_top, rgb_front, rgb_right, rgb_bot, sec)) + tw, th = I_top.size; fw, fh = I_front.size; rw, rh = I_right.size; sw_, sh_ = I_sec.size + + # ── 시트 배치 ── + colA_w = tw + colB_w = max(rw, COLB_MIN) + sheet_w = int(ML + colA_w + G + colB_w + MR) + y = 20 + y_top = y + CAP; y = y_top + th + DIMH + y_front = y + CAP; y = y_front + fh + DIMH + show_bot = not bottom_flat + y_bot = y + CAP + if show_bot: + y = y_bot + th + DIMH + y_sec = y + CAP; y = y_sec + sh_ + DIMH + sheet_h = int(y + 100) + sheet = Image.new('RGB', (sheet_w, sheet_h), 'white') + ax = ML + bx = ML + colA_w + G + sheet.paste(I_top, (ax, y_top)) + sheet.paste(I_front, (ax, y_front)) + rx = bx + (colB_w - rw) // 2 + sheet.paste(I_right, (rx, y_front)) + if show_bot: + sheet.paste(I_bot, (ax, y_bot)) + sheet.paste(I_sec, (ax, y_sec)) + + dr = ImageDraw.Draw(sheet) + LINE = (34, 34, 34); TEXT = (20, 20, 20); CAPC = (110, 110, 110); BLUE = (0, 84, 166); RED = (200, 30, 30) + f_dim = font(20); f_cap = font(15); f_title = font(22); f_small = font(16); f_tab = font(16) + + def arrow(x, yy_, dx, dy, col=LINE): + L = 9 + if dx: + dr.polygon([(x, yy_), (x - dx * L, yy_ + 4), (x - dx * L, yy_ - 4)], fill=col) + else: + dr.polygon([(x, yy_), (x + 4, yy_ - dy * L), (x - 4, yy_ - dy * L)], fill=col) + + def hdim(x0, x1, yy_, label, col=LINE): + dr.line([(x0, yy_), (x1, yy_)], fill=col, width=2) + arrow(x0, yy_, 1, 0, col); arrow(x1, yy_, -1, 0, col) + bb = dr.textbbox((0, 0), label, font=f_dim) + dr.text(((x0 + x1) / 2 - (bb[2] - bb[0]) / 2, yy_ - bb[3] - 8), label, fill=TEXT, font=f_dim) + + def vdim(x, y0_, y1_, label): + dr.line([(x, y0_), (x, y1_)], fill=LINE, width=2) + arrow(x, y0_, 0, 1); arrow(x, y1_, 0, -1) + bb = dr.textbbox((0, 0), label, font=f_dim) + tmp = Image.new('RGB', (bb[2] - bb[0] + 6, bb[3] - bb[1] + 6), 'white') + ImageDraw.Draw(tmp).text((3 - bb[0], 3 - bb[1]), label, fill=TEXT, font=f_dim) + tmp = tmp.rotate(90, expand=True) + sheet.paste(tmp, (int(x - tmp.width - 8), int((y0_ + y1_) / 2 - tmp.height / 2))) + + def ext(x, y0_, y1_): + dr.line([(x, y0_), (x, y1_)], fill=(150, 150, 150), width=1) + + def hext(yy_, x0, x1): + dr.line([(x0, yy_), (x1, yy_)], fill=(150, 150, 150), width=1) + + def dashed(p0, p1, col=(90, 90, 90), dash=9, gap=5, width=1): + x0, y0_ = p0; x1, y1_ = p1 + L = math.hypot(x1 - x0, y1_ - y0_) + if L < 1: + return + ux, uy = (x1 - x0) / L, (y1_ - y0_) / L + t = 0.0 + while t < L: + e = min(t + dash, L) + dr.line([(x0 + ux * t, y0_ + uy * t), (x0 + ux * e, y0_ + uy * e)], fill=col, width=width) + t += dash + gap + + def label_box(cx, cy, text, col=BLUE, f=None): + f = f or f_small + bb = dr.textbbox((0, 0), text, font=f) + w_, h_ = bb[2] - bb[0], bb[3] - bb[1] + x0 = cx - w_ / 2 - 4; y0_ = cy - h_ / 2 - 3 + dr.rectangle([x0, y0_, x0 + w_ + 8, y0_ + h_ + 6], fill=(255, 255, 255)) + dr.text((x0 + 4 - bb[0], y0_ + 3 - bb[1]), text, fill=col, font=f) + + # 좌표 변환(mm -> 시트 px) + def P_top(x, yv): return (ax + (x - mn[0]) * S, y_top + (mx[1] - yv) * S) + def P_front(x, z): return (ax + (x - mn[0]) * S, y_front + (mx[2] - z) * S) + def P_right(yv, z): return (rx + (yv - mn[1]) * S, y_front + (mx[2] - z) * S) + def P_bot(x, yv): return (ax + (x - mn[0]) * S, y_bot + (yv - mn[1]) * S) + def P_sec(x, z): return (ax + (x - mn[0]) * S, y_sec + (mx[2] - z) * S) + + # 캡션 + def caption(cx, yy_, text): + bb = dr.textbbox((0, 0), text, font=f_cap) + dr.text((cx - (bb[2] - bb[0]) / 2, yy_), text, fill=CAPC, font=f_cap) + caption(ax + tw / 2, y_top - 24, '평면도(위에서)') + caption(ax + fw / 2, y_front - 24, '정면도(-Y에서)') + caption(rx + rw / 2, y_front - 24, '우측면도(+X에서)') + if show_bot: + caption(ax + tw / 2, y_bot - 24, '저면도(아래에서)') + caption(ax + sw_ / 2, y_sec - 24, '단면 A-A (평면도의 절단선, +Y 방향을 봄)') + + # 외곽 치수 + y_w = int(y_front + fh + 30) + ext(ax, y_front + fh, y_w + 6); ext(ax + fw, y_front + fh, y_w + 6) + hdim(ax, ax + fw, y_w, fmt(W)) + y_d = int(y_front + rh + 30) + ext(rx, y_front + rh, y_d + 6); ext(rx + rw, y_front + rh, y_d + 6) + hdim(rx, rx + rw, y_d, fmt(D)) + x_h = ax - 62 + hext(y_front, x_h - 6, ax); hext(y_front + fh, x_h - 6, ax) + vdim(x_h, y_front, y_front + fh, fmt(H)) + + # 높이 레벨(정면도 왼쪽 눈금) + last_y = -1e9 + for z in sorted(levels, reverse=True): + py = y_front + (mx[2] - (z + 0.0 - mn[2] + mn[2])) * S + py = y_front + (mx[2] - z) * S + if abs(py - last_y) < 17: + continue + last_y = py + dr.line([(ax - 10, py), (ax, py)], fill=BLUE, width=1) + t = 'z' + fmt(z) + bb = dr.textbbox((0, 0), t, font=f_small) + dr.text((ax - 14 - (bb[2] - bb[0]), py - (bb[3] - bb[1]) / 2 - 2), t, fill=BLUE, font=f_small) + + # 원점 표시(O) + def origin(p): + x_, y_ = p + dr.line([(x_ - 9, y_), (x_ + 9, y_)], fill=RED, width=2); dr.line([(x_, y_ - 9), (x_, y_ + 9)], fill=RED, width=2) + dr.text((x_ + 6, y_ + 3), 'O', fill=RED, font=f_small) + if mn[0] - 5 <= 0 <= mx[0] + 5 and mn[1] - 5 <= 0 <= mx[1] + 5: + origin(P_top(0, 0)) + if mn[0] - 5 <= 0 <= mx[0] + 5 and mn[2] - 5 <= 0 <= mx[2] + 5: + origin(P_front(0, 0)) + if mn[1] - 5 <= 0 <= mx[1] + 5 and mn[2] - 5 <= 0 <= mx[2] + 5: + origin(P_right(0, 0)) + + # 숨은선(점선): 구멍 벽을 정면도/우측면도에 + for h in holes: + for xv in (h['x0'], h['x1']): + dashed(P_front(xv, h['zbot']), P_front(xv, h['ztop'])) + for yv in (h['y0'], h['y1']): + dashed(P_right(yv, h['zbot']), P_right(yv, h['ztop'])) + + # 평면도 구멍 번호/치수 — 큰 구멍은 왼쪽 위 모서리 안쪽에, 작은 구멍(슬롯)은 번호만 위쪽 바깥에 + for i, h in enumerate(holes, 1): + l_, t_ = P_top(h['x0'], h['y1']) + w_px = h['w'] * S; h_px = h['h'] * S + if h['kind'] == 'circle': + txt = '%d: Ø%s' % (i, fmt(h['dia'])) + else: + txt = '%d: %sx%s' % (i, fmt(h['w']), fmt(h['h'])) + bb = dr.textbbox((0, 0), txt, font=f_small) + tw_, th_ = bb[2] - bb[0] + 12, bb[3] - bb[1] + 10 + if w_px > tw_ + 40 and h_px > th_ + 12: + label_box(l_ + tw_ / 2 + 6, t_ + th_ / 2 + 6, txt) + else: + label_box(l_ + w_px / 2, t_ - 14, str(i)) + + # 단면 절단선(평면도) + syc = sy - 1e-4 * D + p0 = P_top(mn[0] - 4, syc); p1 = P_top(mx[0] + 4, syc) + dashed(p0, p1, col=RED, dash=16, gap=5, width=2) + for px_ in (p0[0], p1[0]): + arrow(px_, p0[1] - 14, 0, 1, RED) + dr.line([(px_, p0[1]), (px_, p0[1] - 5)], fill=RED, width=2) + dr.text((p0[0] - 18, p0[1] - 34), 'A', fill=RED, font=f_dim) + dr.text((p1[0] + 6, p0[1] - 34), 'A', fill=RED, font=f_dim) + + # TS가 넘긴 원 지름(단면 기반: 보스·옆구멍 포함) + circ = job.get('circles') or {} + def circ_draw(items, mapper, vw, vh, limit, skip_pts=()): + shown = 0 + for c in items: + if shown >= limit: + break + dmax = c.get('diaMax') or c['dia'] + if dmax >= 0.97 * min(vw, vh) and not c.get('taper'): + continue + if any(abs(c['u'] - ux) < 1.0 and abs(c['v'] - uv) < 1.0 for ux, uv in skip_pts): + continue + cx_, cy_ = mapper(c['u'], c['v']) + t = ('Ø%s~%s' % (fmt(c['dia']), fmt(c['diaMax']))) if c.get('taper') else 'Ø' + fmt(c['dia']) + label_box(cx_, cy_, t, BLUE, f_small) + shown += 1 + top_hole_pts = [(h['cx'], h['cy']) for h in holes] + circ_draw(circ.get('top', []), P_top, W, D, 8, top_hole_pts) + circ_draw(circ.get('front', []), P_front, W, H, 6) + circ_draw(circ.get('right', []), P_right, D, H, 6) + + # 단면도 치수: 가운데 렌즈 같은 구멍의 x 범위 + for i, h in enumerate(holes, 1): + if h['y0'] - 1e-6 <= syc <= h['y1'] + 1e-6: + xa, za = P_sec(h['x0'], mx[2]); xb, _ = P_sec(h['x1'], mx[2]) + hdim(xa, xb, y_sec + sh_ + 26, '%d: %s' % (i, fmt(h['x1'] - h['x0'])), BLUE) + + # ── 치수표(오른쪽 열 상단) ── + ty = y_top + dr.text((bx, ty), '치수표 (단위 mm)', fill=TEXT, font=f_dim); ty += 34 + rows = ['원점 O = 모델 좌표 (0,0,0)', '위치: O 기준 [왼쪽·아래 모서리 기준]'] + for r in rows: + dr.text((bx, ty), r, fill=CAPC, font=f_tab); ty += 22 + ty += 6 + if levels: + dr.text((bx, ty), '높이 레벨: ' + ' / '.join(fmt(z) for z in levels), fill=BLUE, font=f_tab); ty += 26 + for i, h in enumerate(holes, 1): + if ty > y_front - 30: + dr.text((bx, ty), '… 외 %d개' % (len(holes) - i + 1), fill=CAPC, font=f_tab); break + kind = 'Ø%s 구멍' % fmt(h['dia']) if h['kind'] == 'circle' else '%sx%s 창/구멍' % (fmt(h['w']), fmt(h['h'])) + dr.text((bx, ty), '%d %s' % (i, kind), fill=TEXT, font=f_tab); ty += 21 + dr.text((bx + 24, ty), '중심 (%s, %s) [%s, %s]' % (fmt(h['cx']), fmt(h['cy']), fmt(h['cx'] - mn[0]), fmt(h['cy'] - mn[1])), + fill=CAPC, font=f_tab); ty += 24 + if not holes: + dr.text((bx, ty), '관통 구멍/창 없음', fill=CAPC, font=f_tab) + + # 제목란 + div_y = sheet_h - 84 + dr.line([(ML - 60, div_y), (sheet_w - MR, div_y)], fill=(170, 170, 170), width=1) + dr.text((ML - 60, div_y + 12), job.get('title', ''), fill=TEXT, font=f_title) + sub = '가로 %s × 깊이 %s × 높이 %s mm · 제3각법 · 축척 %.1f px/mm · 점선=숨은선(구멍 벽) · O=원점' % (fmt(W), fmt(D), fmt(H), S) + dr.text((ML - 60, div_y + 46), sub, fill=(90, 90, 90), font=f_cap) + + sheet.save(job['out']) + + # ── 1:1 인쇄용 템플릿(A4, 300dpi, 평면도) ── + template = None + if job.get('template_out'): + if W <= 277 and D <= 190: + s1 = 300 / 25.4 + tw1 = int(math.ceil(W * s1)) + 2; th1 = int(math.ceil(D * s1)) + 2 + z1 = raster(P, 0, 1, 2, 1, 1, 1, mn[0], mx[1], s1, tw1, th1, True) + m1 = (~np.isnan(z1)).astype(np.uint8) + pw, ph = int(297 / 25.4 * 300), int(210 / 25.4 * 300) + page = np.full((ph, pw, 3), 255, np.uint8) + ox, oy = (pw - tw1) // 2, (ph - th1) // 2 + reg = page[oy:oy + th1, ox:ox + tw1] + reg[m1 > 0] = (232, 232, 232) + er = cv2.erode(m1, np.ones((3, 3), np.uint8)) + reg[(m1 > 0) & (er == 0)] = (0, 0, 0) + pimg = Image.fromarray(page); pd = ImageDraw.Draw(pimg) + ff = font(34) + if mn[0] - 5 <= 0 <= mx[0] + 5 and mn[1] - 5 <= 0 <= mx[1] + 5: + ox_ = ox + (0 - mn[0]) * s1; oy_ = oy + (mx[1] - 0) * s1 + pd.line([(ox_ - 40, oy_), (ox_ + 40, oy_)], fill=(200, 30, 30), width=3) + pd.line([(ox_, oy_ - 40), (ox_, oy_ + 40)], fill=(200, 30, 30), width=3) + bar_x, bar_y = 60, ph - 90 + pd.line([(bar_x, bar_y), (bar_x + 50 * s1, bar_y)], fill=(0, 0, 0), width=6) + for k in range(0, 51, 10): + pd.line([(bar_x + k * s1, bar_y - 14), (bar_x + k * s1, bar_y + 14)], fill=(0, 0, 0), width=4) + pd.text((bar_x, bar_y + 24), '50 mm — 인쇄 배율 100%(실제 크기)로 인쇄해 이 막대가 50 mm인지 확인', fill=(0, 0, 0), font=ff) + pd.text((60, 40), '1:1 평면도 — ' + job.get('title', ''), fill=(0, 0, 0), font=ff) + pimg.save(job['template_out'], dpi=(300, 300)) + template = job['template_out'] + else: + template = 'skipped: part larger than A4' + + print(json.dumps({ + 'ok': True, 'dims': {'w': W, 'd': D, 'h': H}, 'scale': S, 'sheet': [sheet_w, sheet_h], + 'levels': levels, 'section_y': syc, 'bottom_view': show_bot, 'template': template, + 'holes': [{'kind': h['kind'], 'w': h['w'], 'h': h['h'], 'dia': h['dia'], 'cx': h['cx'], 'cy': h['cy'], + 'z0': h['zbot'], 'z1': h['ztop']} for h in holes], + 'origin': [0, 0, 0], 'bbox_min': mn.tolist(), + })) + + +if __name__ == '__main__': + try: + main() + except Exception as e: # TS가 옛 렌더러로 폴백한다 + import traceback + print(json.dumps({'ok': False, 'error': '%s: %s' % (type(e).__name__, e), 'tb': traceback.format_exc()[-600:]})) diff --git a/src/tools/stl-cad.ts b/src/tools/stl-cad.ts index 1c206f9..ed8a0ac 100644 --- a/src/tools/stl-cad.ts +++ b/src/tools/stl-cad.ts @@ -214,7 +214,7 @@ export const stlCadTool = { type: 'object', required: ['action'], properties: { - action: { type: 'string', enum: ['info', 'render', 'three_view', 'add_hole', 'cut', 'boolean', 'transform', 'merge'], description: 'merge: 여러 STL(stl_paths)을 한 파일로 합침(output_path 필수) — 삼각형을 그대로 이어붙여서 닫히지 않은(non-manifold) 메시도 OK, OpenSCAD 합집합보다 안전. layout=grid(기본)면 각 부품을 바닥(z=0)에 붙여 베드(bed_x×bed_y, 기본 260×260, gap 5mm) 안에 배치하고 넘치면 output_path_2.stl…로 판을 나눔. layout=keep이면 현재 위치 그대로 합침(조립체 확인용). info: 치수/바운딩박스/체적/밀폐(manifold)여부/삼각형수 조회(stl_path). render: 지정한 각도로 PNG 미리보기 생성(stl_path, 모델이 직접 봄). three_view: 제작용 3면도(정면/평면/우측면, 외곽 치수선 표기)를 흰 도면 시트 PNG로 생성(stl_path). add_hole: 지정 좌표에 원통형 구멍 뚫어 새 STL로 저장(stl_path). cut: 박스 모양으로 깎아냄(stl_path). boolean: 다른 STL과 합/차/교집합(stl_path + second_path). transform: 크기변경/회전/거울/이동(stl_path, output_path 생략 시 제자리 덮어씀).' }, + action: { type: 'string', enum: ['info', 'render', 'three_view', 'add_hole', 'cut', 'boolean', 'transform', 'merge'], description: 'merge: 여러 STL(stl_paths)을 한 파일로 합침(output_path 필수) — 삼각형을 그대로 이어붙여서 닫히지 않은(non-manifold) 메시도 OK, OpenSCAD 합집합보다 안전. layout=grid(기본)면 각 부품을 바닥(z=0)에 붙여 베드(bed_x×bed_y, 기본 260×260, gap 5mm) 안에 배치하고 넘치면 output_path_2.stl…로 판을 나눔. layout=keep이면 현재 위치 그대로 합침(조립체 확인용). info: 치수/바운딩박스/체적/밀폐(manifold)여부/삼각형수 조회(stl_path). render: 지정한 각도로 PNG 미리보기 생성(stl_path, 모델이 직접 봄). three_view: 제작용 도면 시트 PNG 생성(stl_path) — 평면·정면·우측면·저면(밑에 단차가 있을 때)·단면 A-A, 외곽 치수·구멍 지름/사각 창 치수·위치 치수표, 높이 레벨, 숨은선(점선), 원점 O. print_1to1=true면 A4 300dpi 1:1 평면도 템플릿도 만든다(출력물 대조용). add_hole: 지정 좌표에 원통형 구멍 뚫어 새 STL로 저장(stl_path). cut: 박스 모양으로 깎아냄(stl_path). boolean: 다른 STL과 합/차/교집합(stl_path + second_path). transform: 크기변경/회전/거울/이동(stl_path, output_path 생략 시 제자리 덮어씀).' }, stl_path: { type: 'string', description: '(info/render/add_hole/cut/boolean 필수) 워크스페이스 기준 상대경로의 바이너리 STL 파일(예: "print3d/esp32_camera/esp32_top.stl"). ASCII STL은 지원 안 함.' }, stl_paths: { type: 'array', items: { type: 'string' }, description: '(info/transform 선택) 여러 STL을 한 번에 처리할 때 stl_path 대신 경로 배열. transform은 각 파일을 제자리 덮어쓴다(output_path 불가). 결과는 파일별로 나열된다.' }, layout: { type: 'string', enum: ['grid', 'keep'], description: '(merge, 선택) grid=베드에 자동 배치(기본), keep=위치 유지' }, @@ -243,6 +243,7 @@ export const stlCadTool = { dx: { type: 'number', description: '(transform, 선택) X 이동(mm)' }, dy: { type: 'number', description: '(transform, 선택) Y 이동(mm)' }, dz: { type: 'number', description: '(transform, 선택) Z 이동(mm)' }, + print_1to1: { type: 'boolean', description: '(three_view, 선택) true면 A4 300dpi 1:1 평면도 템플릿 PNG도 만든다 — 100%로 인쇄해 출력물을 올려 대조' }, align_bottom: { type: 'boolean', description: '(transform, 선택) 기본 true — 변환 후 바닥을 z=0에 붙인다(모든 STL 기본 규칙). false로 주면 끈다. 이것만 단독으로 주면(true) 이동 없이 바닥 정렬만 한다' }, output_path: { type: 'string', description: '(add_hole/cut/boolean 필수, transform 선택) 결과 STL을 저장할 워크스페이스 기준 상대경로(.stl로 끝나야 함). transform에서 생략하면 stl_path 파일을 제자리 덮어쓴다.' }, }, @@ -374,12 +375,13 @@ export const stlCadTool = { // 제작용 3면도(외곽 치수선 포함) — "C안"(2026-09-25). 도면은 사진/ 폴더로. const pngPath = previewPngPath(workspacePath, stlPath, `three_${Date.now()}`); fs.mkdirSync(path.dirname(pngPath), { recursive: true }); - const r = await renderThreeView(stlPath, pngPath); + const r = await renderThreeView(stlPath, pngPath, { template: args?.print_1to1 === true }); if (!r.ok) return { success: false, error: `3면도 생성 실패: ${r.error}` }; - return { - success: true, - stdout: `3면도 생성 완료 — 가로 ${fmtMm(r.dims.w)} × 깊이 ${fmtMm(r.dims.d)} × 높이 ${fmtMm(r.dims.h)} mm (외곽 기준, ${r.seconds}초)\n\n${buildImageMarkdown(pngPath, workspacePath)}`, - }; + let out = `도면 생성 완료 — 가로 ${fmtMm(r.dims.w)} × 깊이 ${fmtMm(r.dims.d)} × 높이 ${fmtMm(r.dims.h)} mm (외곽 기준, ${r.seconds}초)`; + if (r.summary) out += `\n${r.summary}`; + out += `\n\n${buildImageMarkdown(pngPath, workspacePath)}`; + if (r.templatePath) out += `\n\nA4 1:1 인쇄용 평면도(배율 100%로 인쇄):\n${buildImageMarkdown(r.templatePath, workspacePath)}`; + return { success: true, stdout: out }; } if (action === 'transform') { diff --git a/src/tools/stl-three-view.ts b/src/tools/stl-three-view.ts index 0c4dfb0..8f5b8ea 100644 --- a/src/tools/stl-three-view.ts +++ b/src/tools/stl-three-view.ts @@ -256,17 +256,80 @@ export interface ThreeViewResult { outPath: string; dims: ThreeViewDims; seconds: number; + /** v2 도면에서만: 검출된 구멍·높이 레벨·단면 위치 등 텍스트 요약(모델이 읽을 수 있게). */ + summary?: string; + /** v2 도면에서만: A4 1:1 인쇄용 평면도 PNG 경로. */ + templatePath?: string; } // 조립 렌더와 같은 이유(CPU·tmp 충돌 방지)로 동시 실행 하나로 직렬화. let chain: Promise = Promise.resolve(); -export function renderThreeView(stlPath: string, outPngPath: string): Promise { - const run = chain.then(() => doRender(stlPath, outPngPath)); +export function renderThreeView(stlPath: string, outPngPath: string, opts: { template?: boolean } = {}): Promise { + const run = chain.then(async () => { + // v2(삼각형 직접 투영: 저면도·단면·치수표·점선·1:1 템플릿). 실패하면 옛 OpenSCAD 합성으로 폴백. + const v2 = await renderV2(stlPath, outPngPath, !!opts.template); + if (v2.ok) return v2; + console.warn('[stl-three-view] v2 실패 → 옛 렌더러로 폴백:', v2.error); + return doRender(stlPath, outPngPath); + }); chain = run.catch(() => undefined); return run; } +const V2_SCRIPT = path.resolve(__dirname, '..', '..', 'scripts', 'stl_drawing.py'); + +async function renderV2(stlPath: string, outPngPath: string, withTemplate: boolean): Promise { + const t0 = Date.now(); + if (!fs.existsSync(V2_SCRIPT)) return { ok: false, error: 'stl_drawing.py 없음' }; + let circles: Record = { top: [], front: [], right: [] }; + try { + const tri = readStlTriangles(stlPath); + circles = { top: detectCircles(tri, 'z'), front: detectCircles(tri, 'y'), right: detectCircles(tri, 'x') }; + } catch { /* 지름 표기 생략 */ } + fs.mkdirSync(path.dirname(outPngPath), { recursive: true }); + const tmpJob = outPngPath.replace(/\.png$/i, `_job_${Date.now()}.json`); + const templatePath = withTemplate ? outPngPath.replace(/\.png$/i, '_1to1.png') : undefined; + fs.writeFileSync(tmpJob, JSON.stringify({ + stl: stlPath, out: outPngPath, circles, template_out: templatePath, + title: `도면 — ${path.basename(stlPath)}`, + })); + try { + const res: any = await new Promise((resolve) => { + const proc = spawn('python3', ['-I', V2_SCRIPT, tmpJob], { stdio: ['ignore', 'pipe', 'pipe'] }); + let out = '', err = ''; + proc.stdout?.on('data', (d: Buffer) => { out += d.toString('utf8'); if (out.length > 20000) out = out.slice(-20000); }); + proc.stderr?.on('data', (d: Buffer) => { err += d.toString('utf8'); if (err.length > 3000) err = err.slice(-3000); }); + const timer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* noop */ } }, 90_000); + proc.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, error: String(e.message || e) }); }); + proc.on('close', () => { + clearTimeout(timer); + try { resolve(JSON.parse(out.trim().split('\n').pop() || '{}')); } + catch { resolve({ ok: false, error: err.split('\n').filter(Boolean).slice(-3).join(' ') || '출력 파싱 실패' }); } + }); + }); + if (!res.ok) return { ok: false, error: String(res.error || 'v2 실패') }; + if (!fs.existsSync(outPngPath) || fs.statSync(outPngPath).size < 100) return { ok: false, error: 'v2 도면 파일 비정상' }; + const f = (n: number) => fmtMm(n); + const lines: string[] = []; + if (Array.isArray(res.levels) && res.levels.length) lines.push(`높이 레벨(z): ${res.levels.map((z: number) => f(z)).join(' / ')} mm`); + (res.holes || []).forEach((h: any, i: number) => { + const kind = h.kind === 'circle' ? `Ø${f(h.dia)} 구멍` : `${f(h.w)}×${f(h.h)} 창/구멍`; + lines.push(`${i + 1}. ${kind} — 중심 (x ${f(h.cx)}, y ${f(h.cy)}), z ${f(h.z0)}~${f(h.z1)}`); + }); + if (typeof res.section_y === 'number') lines.push(`단면 A-A: y=${f(res.section_y)} 평면(+Y를 봄)`); + lines.push('좌표 원점 O = 모델 좌표 (0,0,0)'); + const tpl = typeof res.template === 'string' && res.template.startsWith('/') ? res.template : undefined; + if (withTemplate && !tpl && res.template) lines.push(`1:1 템플릿: ${res.template}`); + return { + ok: true, outPath: outPngPath, dims: { w: res.dims.w, d: res.dims.d, h: res.dims.h }, + seconds: Math.round((Date.now() - t0) / 100) / 10, summary: lines.join('\n'), templatePath: tpl, + }; + } finally { + try { fs.rmSync(tmpJob, { force: true }); } catch { /* noop */ } + } +} + async function doRender(stlPath: string, outPngPath: string): Promise { const t0 = Date.now(); let dims: ThreeViewDims;