삼각형 직접 z-버퍼 투영(scripts/stl_drawing.py), 실패/초대형 모델은 옛 OpenSCAD 합성으로 폴백. 우측면도 좌우 방향을 +X에서 본 정확한 방향으로 정정. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
538 lines
23 KiB
Python
538 lines
23 KiB
Python
#!/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', '<f4', 3), ('v', '<f4', (3, 3)), ('a', '<u2')])
|
||
arr = np.frombuffer(data, dtype=dt, count=n, offset=84)
|
||
return arr['v'].astype(np.float64)
|
||
import re
|
||
txt = data.decode('utf8', 'ignore')
|
||
v = re.findall(r'vertex\s+(\S+)\s+(\S+)\s+(\S+)', txt)
|
||
a = np.array(v, dtype=np.float64).reshape(-1, 3, 3)
|
||
return a
|
||
|
||
|
||
def raster(P, ui, vi, wi, usgn, vsgn, wsgn, umin, vmax, s, Wpx, Hpx, keep_max=True):
|
||
"""삼각형 P(n,3,3)를 (u,v) 평면에 z-버퍼로 래스터화. 반환: 깊이맵(없으면 nan)."""
|
||
U = usgn * P[:, :, ui]; V = vsgn * P[:, :, vi]; Wd = wsgn * P[:, :, wi]
|
||
X = (U - umin) * s; Y = (vmax - V) * s
|
||
zb = np.full((Hpx, Wpx), -np.inf if keep_max else np.inf, dtype=np.float32)
|
||
# 화면 투영 면적이 0인(옆면) 삼각형은 건너뛴다.
|
||
area2 = (X[:, 1] - X[:, 0]) * (Y[:, 2] - Y[:, 0]) - (X[:, 2] - X[:, 0]) * (Y[:, 1] - Y[:, 0])
|
||
idx = np.nonzero(np.abs(area2) > 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:]}))
|