# -*- coding: utf-8 -*- """ simplify-stl.py —— 简化过大的 STL 网格 (窗口内 3D 预览用, 纯 numpy 顶点聚类, 零额外依赖) 用途: 屏幕预览不需要几十 MB 的精细网格; 本脚本把 mesh\\ 里 > 阈值的 STL 按网格边长 (GRID_MM) 做顶点聚类, 体积缩小 3~10 倍, 外形基本不变。 用法: python simplify-stl.py (处理 mesh\\ 下所有 > 5MB 的 .stl, 就地覆盖) """ import os import re import struct import numpy as np BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MESH_DIR = os.path.join(BASE, 'catalog', 'mesh') SIZE_MIN = 2 * 1024 * 1024 # 只处理 2MB 以上的网格 (控制窗口内渲染内存) GRID_MM = 0.75 # 聚类网格边长 (mm): 越大越简 (0.5~1.0 预览合适) def read_stl(path): """自动识别二进制/ASCII STL, 返回 (N,3,3) 三角顶点数组""" with open(path, 'rb') as f: head = f.read(5) if head[:5] == b'solid': # ASCII STL: 正则抽出所有 vertex 行 with open(path, 'r', errors='ignore') as f: txt = f.read() arr = np.array(re.findall(r'vertex\s+([-\deE+.]+)\s+([-\deE+.]+)\s+([-\deE+.]+)', txt), dtype=np.float32) return arr.reshape(-1, 3, 3) with open(path, 'rb') as f: f.read(80) (n,) = struct.unpack(' 1e-12 else np.array([0.0, 0.0, 1.0]) f.write(struct.pack('<12f', nrm[0], nrm[1], nrm[2], p0[0], p0[1], p0[2], p1[0], p1[1], p1[2], p2[0], p2[1], p2[2])) f.write(struct.pack('