| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073 |
- /**
- * page/lab.js —— 实验室 · STAGE 工程台(单屏不滚)。
- * 渲染全部交给 core/stage/STAGE.js:
- * - 八款产品各自的专属建模(手表壳犄角 / 录音豆背夹 / 圆屏螺纹底盖 / 胸针别针 / 墨水屏支架 / 翻盖铰链 / 颈环扫掠 / 戒指充电舱)
- * - 爆炸(ex 向量)· 剖视(ghost 半透明)· 尺寸标注(addDim)· PBR 材质 · 单件隔离(solo)
- * - 结构件 14 类库(拖动落位、贴内壁、环形阵列)· STL/OBJ 整件与分件导出 · 截图 · 需求单
- * 视口上方浮着视图条(爆炸 / 剖视 / 标注 / 视角 / 材质 / 氛围灯),下方三档吸附坞:形体 / 结构件 / BOM / 导出。
- * 离开页面时销毁 STAGE 场景(Babylon 只在本页初始化)。
- */
- import { html } from 'lit';
- import '../wc/ph-bom.js';
- import { PhPage } from '../lib/base.js';
- import { loadProduct } from '../services/products.js';
- import { linkHref, currentPath } from '../utils/router.js';
- import { labStyle } from './styles/lab-style.js';
- import { applyCss } from '../lib/css.js';
- import { lsGet, lsSet } from '../utils/storage.js';
- import { moduleUrl, APP_BASE } from '../config.js';
- import { PROC_RULES, PROC_KEYS, resolveProc, reserveUids, validate, paramSchema, arrayRing } from '../core/geometry/parts.js';
- /* ---------------- Babylon / STAGE 懒加载 ---------------- */
- let babylonPromise = null;
- function ensureBabylon() {
- if (window.BABYLON) return Promise.resolve(window.BABYLON);
- if (babylonPromise) return babylonPromise;
- babylonPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = new URL(APP_BASE + 'vendor/babylon/babylon.js', document.baseURI).href;
- s.async = true;
- s.onload = () => {
- const b = window.BABYLON;
- if (b) resolve(b);
- else reject(new Error('Babylon 全局未就绪'));
- };
- s.onerror = () => reject(new Error('Babylon 脚本加载失败'));
- document.head.appendChild(s);
- });
- return babylonPromise;
- }
- let envPromise = null;
- /** 环境反射贴图:本地 cubemap(vendor/babylon/env/studio.env),先取回再初始化场景,避免首帧无反射 */
- function ensureEnv() {
- if (envPromise) return envPromise;
- const url = new URL(APP_BASE + 'vendor/babylon/env/studio.env', document.baseURI).href;
- envPromise = fetch(url).then((r) => (r.ok ? r.arrayBuffer() : null))
- .then((buf) => (buf ? { data: new Uint8Array(buf), size: 512 } : null))
- .catch(() => null);
- return envPromise;
- }
- /* ---------------- 产品 id → STAGE 项目 ---------------- */
- const STAGE_OF = {
- 'watch-case': 'silicone',
- 'recorder-bean': 'recorder',
- 'round-screen': 'round',
- 'ai-pin': 'ai-pin',
- 'eink-tag': 'eink-tag',
- 'pocket-ai': 'pocket-ai',
- 'bone-headset': 'bone-headset',
- 'smart-ring': 'smart-ring',
- };
- /** 数据契约的 shape.defaults 键 → 各 STAGE 文脉参数键(只映射有意义的键) */
- const PARAM_MAP = {
- silicone: { dTop: 'w', dBottom: 'w', height: 'h', wall: 't', cornerR: 'r' },
- recorder: { dTop: 'D', dBottom: 'D', height: 'H', wall: 't', domeR: 'dm' },
- round: { dTop: 'D', dBottom: 'D', height: 'H', wall: 't', domeR: 'rimR', recessR: 'dep', recessDepth: 'dep', screenD: 'sd', chamferC: 'cham' },
- 'ai-pin': { dTop: 'D', dBottom: 'D', height: 'H', wall: 't', recessDepth: 'dep', screenD: 'sd', chamferC: 'ch' },
- 'eink-tag': { height: 'H', wall: 't', cornerR: 'r', length: 'L', screenH: 'W', recessDepth: 'dep', chamferC: 'ch' },
- 'pocket-ai': { height: 'baseH', wall: 't', cornerR: 'r', length: 'L', screenH: 'W', recessDepth: 'dep', chamferC: 'ch' },
- 'bone-headset': { ringD: 'neck', ringBandW: 'modH', length: 'modL', wall: 'tubeR' },
- 'smart-ring': { ringD: 'ringD', ringBandW: 'bandW', height: 'H', dTop: 'dockD' },
- };
- /** 数据契约参数键 → STAGE 参数键(反向:用于从产品 JSON 带出初始值) */
- function stageParamsFromShape(dataType, defaults, projectId) {
- const F = { height: 'H', wall: 't', cornerR: 'r', domeR: 'dm', recessDepth: 'dep', chamferC: 'ch' };
- const out = {};
- const set = (k, v) => { if (v != null && Number.isFinite(Number(v))) out[k] = Number(v); };
- if (dataType === 'watch') { set('w', defaults.screenD); set('d', defaults.screenD + 6.5); }
- if (dataType === 'ring') { set('ringD', defaults.ringD); set('bandW', defaults.ringBandW); set('H', defaults.height); }
- for (const [k, v] of Object.entries(F)) if (defaults[k] != null) set(v, defaults[k]);
- if (dataType === 'rect') { set('L', defaults.length); set('W', defaults.dTop); }
- if (projectId === 'round' || projectId === 'ai-pin' || projectId === 'recorder' || projectId === 'silicone') {
- set('D', defaults.dTop); set('w', defaults.dTop);
- if (defaults.screenD) set(projectId === 'round' ? 'sd' : 'sd', defaults.screenD);
- }
- if (projectId === 'bone-headset') { set('neck', defaults.ringD); set('modH', defaults.ringBandW); }
- if (projectId === 'pocket-ai') { set('lidH', Math.round(defaults.height * 0.4 * 10) / 10); }
- return out;
- }
- const DOCK = { peek: 0.2, half: 0.46, full: 0.72 };
- const SNAP_STEPS = [0.5, 1, 5];
- const UNDO_MAX = 40;
- const VIEWS = [['front', '前'], ['side', '侧'], ['top', '顶'], ['iso', '45°'], ['low', '仰']];
- const buzz = (ms = 8) => { try { navigator.vibrate?.(ms); } catch { /* 忽略 */ } };
- const fmt = (v, d = 1) => (Math.round((Number(v) || 0) * 10 ** d) / 10 ** d).toFixed(d);
- const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
- /** 14 类形体的简图(24×24 SVG 片段,只描边,跟随文字色) */
- export function primIcon(type) {
- const S = 'fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"';
- switch (type) {
- case 'box': return `<rect x="4" y="7" width="13" height="10" ${S}/><path d="M4 7l4-3h13v10l-4 3M17 7l4-3M17 17l4-3" ${S}/>`;
- case 'cyl': return `<ellipse cx="12" cy="6" rx="6" ry="2.6" ${S}/><path d="M6 6v11c0 1.4 2.7 2.6 6 2.6s6-1.2 6-2.6V6" ${S}/>`;
- case 'rib': return `<path d="M5 19V8h3v11M11 19V8h3v11M17 19V8h2" ${S}/>`;
- case 'pocket': return `<rect x="3" y="4" width="18" height="16" rx="2" ${S}/><rect x="7" y="8" width="10" height="8" rx="1" ${S} stroke-dasharray="2 1.5"/>`;
- case 'hole': return `<circle cx="12" cy="12" r="7" ${S} stroke-dasharray="2.5 1.8"/><circle cx="12" cy="12" r="3" ${S}/>`;
- case 'boss2': case 'boss25': case 'boss3': return `<ellipse cx="12" cy="5" rx="5" ry="2" ${S}/><path d="M7 5v13c0 1.1 2.2 2 5 2s5-.9 5-2V5" ${S}/><ellipse cx="12" cy="5" rx="2" ry="1" ${S}/><path d="M10 9v11M14 9v11" ${S} stroke-dasharray="1.5 1.5"/>`;
- case 'thru25': return `<rect x="3" y="3" width="18" height="18" rx="2" ${S}/><circle cx="12" cy="12" r="3.2" ${S}/><path d="M12 4v4M12 16v4M4 12h4M16 12h4" ${S}/>`;
- case 'pin3': return `<path d="M12 2v3" ${S}/><ellipse cx="12" cy="7" rx="3" ry="1.4" ${S}/><path d="M9 7v11c0 .9 1.3 1.6 3 1.6s3-.7 3-1.6V7" ${S}/>`;
- case 'pad4': return `<rect x="4" y="5" width="16" height="14" rx="2" ${S}/>${[[7, 8], [17, 8], [7, 16], [17, 16]].map(([x, y]) => `<circle cx="${x}" cy="${y}" r="1.9" ${S}/>`).join('')}`;
- case 'wall': return `<rect x="3" y="5" width="18" height="14" rx="2" ${S}/><path d="M12 5v14M3 12h6M15 12h6" ${S}/>`;
- case 'tray': return `<rect x="4" y="4" width="16" height="16" rx="2" ${S}/><rect x="7" y="7" width="10" height="10" rx="1" ${S}/><path d="M12 7v-3M9 4h6" ${S}/>`;
- case 'clip': return `<path d="M6 20V8c0-2 .8-3 2-3s2 1 2 3v8" ${S}/><path d="M10 10h5V5" ${S}/>`;
- default: return `<rect x="5" y="5" width="14" height="14" rx="3" ${S}/>`;
- }
- }
- class PhLab extends PhPage {
- constructor() {
- super();
- this.styles = []; // 本页样式由 lab-style.js 注入(vendor lit-html 不解析 css``)
- this.p = null;
- this.error = null;
- this.tab = 'shape';
- this.dock = 'half';
- this.params = {};
- this.parts = [];
- this.cust = []; // STAGE 结构件(spec:{uid,type,x,y,z,...})
- this.selectedPart = null; // STAGE 零件 id(单件隔离)
- this.selUid = null; // 结构件 uid(编辑面板)
- this.pendingSel = null;
- this.picker = false;
- this.snapStep = 1;
- this.undoStack = [];
- this.redoStack = [];
- this.stage = null;
- this.material = '';
- this.explode = 0;
- this.dims = true;
- this.cutaway = false;
- this.glow = false;
- this.view = 'iso';
- this.status = '';
- this.rk = 'injection';
- this.stats = null;
- this.title = '实验室 · Pocket Hardware Lab · FmodeCode';
- }
- createRenderRoot() {
- applyCss(this, ...labStyle);
- return this;
- }
- setup() {
- const m = currentPath().match(/^\/lab\/([^/?#]+)/);
- this.id = m ? decodeURIComponent(m[1]) : '';
- return this._load();
- }
- async _load() {
- this.p = await loadProduct(this.id);
- STAGE_MOD = await import(moduleUrl('core/stage/STAGE.js'));
- window.__STAGE_MOD = STAGE_MOD; // 调试 / 验收:从控制台或自动化脚本直接调用 STAGE API
- this.stageId = STAGE_OF[this.p.id] || 'silicone';
- const saved = lsGet('lab:' + this.p.id);
- const defaults = this.p.shape?.defaults || {};
- const stageDefaults = stageParamsFromShape(this.p.shape?.type, defaults, this.stageId);
- const P = this.stageProject();
- const base = {};
- for (const x of P.params) base[x.k] = x.def;
- this.params = { ...base, ...stageDefaults, ...(saved?.stageParams || {}), ...(saved?.params || {}) };
- this.cust = (saved?.cust || []).filter((x) => x && x.type);
- reserveUids(this.cust.map((x) => ({ uid: x.uid })));
- this.material = saved?.material && P.materials.includes(saved.material) ? saved.material : P.materials[0];
- this.explode = saved?.explode ?? 0;
- this.dims = saved?.dims !== false;
- this.cutaway = !!saved?.cutaway;
- this.glow = !!saved?.glow;
- this.view = saved?.view || 'iso';
- this.rk = saved?.rk || this._defaultRk();
- this.dock = saved?.dock || 'half';
- this.title = `${this.p.name} · 实验室 · Pocket Hardware Lab`;
- this.requestUpdate();
- await this.updateComplete;
- if (!this.isConnected) return;
- await this._mount3d();
- }
- _defaultRk() {
- return resolveProc((this.p.processes || [])[0]?.id || 'injection');
- }
- stageProject() {
- if (!this._sp) this._sp = STAGE_MOD.PROJECTS[this.stageId];
- return this._sp;
- }
- async _mount3d() {
- const canvas = this.querySelector('canvas');
- if (!canvas) return;
- try {
- window.__LAB_STEP = 'babylon';
- window.__LAB_STAGE = this.stage;
- const BAB = await ensureBabylon();
- /* vendor 里是 UMD 包:Node 下默认挂在 module.exports,浏览器里是 window.BABYLON。
- 若挂在别处(或只导出了子集),把 window.BABYLON 指向完整导出,STAGE 只认这个全局 */
- const wb = window.BABYLON;
- const full = (wb && wb.getClassName && wb.Engine) ? wb : (BAB && BAB.default && BAB.default.Engine ? BAB.default : BAB);
- if (full && full.Engine && window.BABYLON !== full) window.BABYLON = full;
- window.__LAB_STEP = 'import';
- if (!this.isConnected) return;
- window.__LAB_STEP = 'env';
- const env = await ensureEnv();
- window.__LAB_STEP = 'init';
- const STAGE = STAGE_MOD.STAGE;
- this.stage = STAGE;
- if (env) STAGE.setEnv(env);
- STAGE.init(canvas, this.querySelector('.stage'));
- STAGE.onSelect((partId, mesh) => {
- if (partId && partId.charAt(0) === 'c') {
- const uid = Number(String(partId).slice(1));
- this._selectCustom(uid);
- } else if (partId) {
- this._solopart(partId);
- } else if (this.selectedPart) {
- this._solopart(null);
- }
- });
- STAGE.onDrag((spec) => {
- this.cust = this.cust.map((x) => (x.uid === spec.uid ? { ...x, x: spec.x, z: spec.z } : x));
- this._saveSoon();
- if (this.selUid === spec.uid) this.requestUpdate();
- });
- STAGE.setCustom(this.stageId, this.cust);
- STAGE.load(this.stageId, this.params, this.material, this.explode);
- STAGE.setDims(this.dims);
- if (this.glow) STAGE.setGlow(true);
- if (this.cutaway) STAGE.setCutaway(true);
- STAGE.setView(this.view);
- this._setDockPx(this.dock, 0);
- this._statsLoop();
- this._watchViewport();
- if (this.pendingSel) { const s = this.pendingSel; this.pendingSel = null; this._solopart(s); }
- this.requestUpdate();
- } catch (e) {
- console.warn(e);
- window.__LAB_ERR = String(e && (e.stack || e.message) || e);
- this.error = e;
- }
- }
- disconnectedCallback() {
- super.disconnectedCallback();
- if (this._statT) clearInterval(this._statT);
- if (this._keysBound) removeEventListener('keydown', this._onKey);
- this._keysBound = false;
- this._unwatchViewport?.();
- clearTimeout(this._saveT);
- try { this.stage?.dispose?.(); } catch { /* 已销毁则忽略 */ }
- this.stage = null;
- }
- _statsLoop() {
- const tick = () => {
- if (!this.isConnected || !this.stage) return;
- const ids = this.stage.partIds();
- const idCount = new Set(ids.map((x) => x.id)).size;
- const el = this.querySelector('.live');
- if (el) el.textContent = `${idCount} 零件 · ${ids.length - idCount} 重复件`;
- };
- tick();
- this._statT = setInterval(tick, 1200);
- }
- /* ---------------- 撤销 / 重做 / 持久化 ---------------- */
- _snapshot() {
- return JSON.stringify({ params: this.params, cust: this.cust, material: this.material, explode: this.explode, dims: this.dims, cutaway: this.cutaway, glow: this.glow, view: this.view });
- }
- _pushUndo() {
- const snap = this._snapshot();
- if (this.undoStack[this.undoStack.length - 1] === snap) return;
- this.undoStack.push(snap);
- if (this.undoStack.length > UNDO_MAX) this.undoStack.shift();
- this.redoStack = [];
- this._syncHistoryBtns();
- }
- _restore(snap) {
- const s = JSON.parse(snap);
- this.params = s.params;
- this.cust = s.cust;
- this.material = s.material;
- this.explode = s.explode;
- this.dims = s.dims;
- this.cutaway = s.cutaway;
- this.glow = s.glow;
- this.view = s.view;
- const STAGE = this.stage;
- if (STAGE) {
- STAGE.setCustom(this.stageId, this.cust);
- STAGE.load(this.stageId, this.params, this.material, this.explode);
- STAGE.setDims(this.dims);
- STAGE.setGlow(this.glow);
- STAGE.setCutaway(this.cutaway);
- STAGE.setView(this.view);
- }
- this.selectedPart = null;
- this.selUid = null;
- this.requestUpdate();
- this._saveSoon();
- }
- undo() {
- const snap = this.undoStack.pop();
- if (!snap) return;
- this.redoStack.push(this._snapshot());
- this._restore(snap);
- this._syncHistoryBtns();
- buzz(8);
- }
- redo() {
- const snap = this.redoStack.pop();
- if (!snap) return;
- this.undoStack.push(this._snapshot());
- this._restore(snap);
- this._syncHistoryBtns();
- buzz(8);
- }
- _syncHistoryBtns() {
- const u = this.querySelector('.hist .undo'), r = this.querySelector('.hist .redo');
- if (u) u.disabled = !this.undoStack.length;
- if (r) r.disabled = !this.redoStack.length;
- }
- _saveSoon() {
- clearTimeout(this._saveT);
- this._saveT = setTimeout(() => {
- lsSet('lab:' + this.p.id, {
- params: this.params, stageParams: this.params, cust: this.cust, material: this.material,
- explode: this.explode, dims: this.dims, cutaway: this.cutaway, glow: this.glow, view: this.view, rk: this.rk, dock: this.dock, v: 4,
- });
- }, 260);
- }
- _bindKeys() {
- if (this._keysBound) return;
- this._keysBound = true;
- this._onKey = (e) => {
- if (!this.isConnected) return;
- const tag = (e.target?.tagName || '').toLowerCase();
- const typing = tag === 'input' || tag === 'textarea';
- if ((e.ctrlKey || e.metaKey) && (e.key === 'z' || e.key === 'Z')) {
- if (typing) return;
- e.preventDefault();
- if (e.shiftKey) this.redo(); else this.undo();
- } else if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || e.key === 'Y')) {
- e.preventDefault();
- this.redo();
- } else if (e.key === 'Escape') {
- if (this.picker) { this.picker = false; this.requestUpdate(); }
- else if (this.selectedPart) this._solopart(null);
- else if (this.selUid) this._selectCustom(null);
- }
- };
- addEventListener('keydown', this._onKey);
- }
- /* ---------------- 形体参数 ---------------- */
- _setParam(k, value, commit = true) {
- const v = Number(value);
- if (!Number.isFinite(v) || this.params[k] === v) return;
- if (commit) this._pushUndo();
- this.params = { ...this.params, [k]: v };
- this.stage?.setParams(this.params);
- this.requestUpdate();
- this._saveSoon();
- }
- _resetAll() {
- this._pushUndo();
- const base = {};
- for (const x of this.stageProject().params) base[x.k] = x.def;
- this.params = base;
- this.stage?.setParams(this.params);
- this.requestUpdate();
- this._saveSoon();
- }
- /* ---------------- 视口控件:材质 / 爆炸 / 剖视 / 标注 / 视角 / 氛围灯 ---------------- */
- _setMaterial(k) {
- if (k === this.material) return;
- this._pushUndo();
- this.material = k;
- this.stage?.setMaterial(k);
- this.requestUpdate();
- this._saveSoon();
- buzz(6);
- }
- _setExplode(v, commit = true) {
- const n = Math.max(0, Math.min(1, Number(v) || 0));
- if (commit && n !== this.explode) this._pushUndo();
- this.explode = n;
- this.stage?.setExplode(n);
- this._syncRangePct('.xrow .explode');
- this._saveSoon();
- }
- _toggleCutaway() {
- this._pushUndo();
- this.cutaway = !this.cutaway;
- this.stage?.setCutaway(this.cutaway);
- this.requestUpdate();
- this._saveSoon();
- }
- _toggleDims() {
- this.dims = !this.dims;
- this.stage?.setDims(this.dims);
- this.requestUpdate();
- this._saveSoon();
- }
- _toggleGlow() {
- this.glow = !this.glow;
- this.stage?.setGlow(this.glow);
- this.requestUpdate();
- this._saveSoon();
- }
- _setView(v) {
- this.view = v;
- this.stage?.setView(v);
- this.requestUpdate();
- this._saveSoon();
- }
- /** 爆炸滑块的即时显示(拖 range 时不走重建,只更新读数) */
- _syncRangePct(sel) {
- const el = this.querySelector(sel);
- if (!el) return;
- const out = el.parentElement?.querySelector('.xpct');
- if (out) out.textContent = Math.round(this.explode * 100) + '%';
- }
- /* ---------------- 零件(STAGE 专属结构) ---------------- */
- get partRows() {
- const proj = this.stageProject();
- const live = this.stage ? this.stage.partIds() : [];
- const count = new Map();
- for (const x of live) count.set(x.id, (count.get(x.id) || 0) + 1);
- const rows = (proj.parts || []).map((pt) => ({ ...pt, cnt: count.get(pt.id) || 0, custom: false }));
- const PRIMS = this.stage?.PRIMS || {};
- for (const s of this.cust) {
- rows.push({ id: 'c' + s.uid, uid: s.uid, n: (PRIMS[s.type] || {}).n || '结构件', q: '1', mat: '随主材质', proc: '自定义结构', tol: '±0.1', cnt: count.get('c' + s.uid) || 0, custom: true });
- }
- return rows;
- }
- _solopart(partId) {
- this.selectedPart = partId || null;
- this.selUid = null;
- this.stage?.setSolo(this.selectedPart);
- if (this.selectedPart) this.pendingSel = this.pendingSel; // 保持状态
- this.requestUpdate();
- buzz(6);
- }
- /** 点零件:进入隔离 → 相机聚焦 → 高亮;再点取消 */
- _togglePart(row) {
- if (row.custom) {
- this._selectCustom(row.uid);
- return;
- }
- if (this.selectedPart === row.id) { this._solopart(null); return; }
- this.tab = 'parts';
- const partId = row.id;
- if (this.stage) {
- this._solopart(partId);
- this.stage.highlight(partId);
- } else this.pendingSel = partId;
- }
- /* ---------------- 结构件:选中 / 编辑 ---------------- */
- get sel() { return this.cust.find((p) => p.uid === this.selUid) || null; }
- _shellDim() {
- return this.stage?._cav ? this.stage._cav() : null;
- }
- /** 工艺校验用的落位包络(结构件坐标是 STAGE 坐标:壳中心为原点、Y 向上) */
- _validationShell() {
- const c = this.stage?._cav?.() || { kind: 'cyl', r: 20, h: 10 };
- const h = Math.max(4, (this.params.H || this.params.h || this.params.height || 10));
- return { kind: c.kind, r: c.r, w: c.w, d: c.d, h, wall: this.params.t || this.params.wall || 1.5 };
- }
- get checks() {
- const parts = this.cust.map((s) => ({ uid: s.uid, type: s.type, params: { ...s }, at: { x: s.x, y: s.y, z: s.z }, rotY: s.rot || 0, visible: true, label: '' }));
- try { return validate(parts, this._validationShell(), this.rk); } catch { return []; }
- }
- /** 结构件 Y=0 是壳底;换算成 STAGE 坐标(壳中心为原点) */
- _y0() {
- const H = Number(this.params.H || this.params.h) || 0;
- return this.params.D ? -H / 2 : this.params.d ? -H / 2 : this.params.L ? -H / 2 : 0;
- }
- _spawnAt() {
- const c = this.stage?._cav?.() || { kind: 'cyl', r: 20 };
- const n = this.cust.length;
- if (c.kind === 'cyl') {
- const r = Math.max(0, c.r * 0.5);
- const a = n * 0.7;
- return { x: Math.round(r * Math.cos(a) * 2) / 2, z: Math.round(-r * Math.sin(a) * 2) / 2 };
- }
- return { x: 0, z: Math.max(0, Math.round(((c.d || 20) / 2 - 8) * 2) / 2) };
- }
- _selectCustom(uid) {
- if (uid == null) {
- this.selUid = null;
- this.stage?.setSolo(this.selectedPart);
- this.requestUpdate();
- return;
- }
- this.selUid = uid;
- this.selectedPart = 'c' + uid;
- this.tab = 'parts';
- if (this.dock === 'peek') this._setDockPx('half', 300);
- this.stage?.setSolo('c' + uid);
- this.stage?.highlight('c' + uid);
- this.stage?.focusPart('c' + uid);
- this.requestUpdate();
- }
- exitEdit() {
- this.selUid = null;
- this.selectedPart = null;
- this.stage?.setSolo(null);
- this.requestUpdate();
- }
- _addCustom(type) {
- this._pushUndo();
- const spec = this.stage.addCustom(type, { ...this._spawnAt(), y: this._y0() + 0.5, snap: this.snapStep });
- this.cust = [...this.cust, spec];
- this.picker = false;
- this.tab = 'parts';
- if (this.dock === 'peek') this._setDockPx('half', 300);
- this._selectCustom(spec.uid);
- this._saveSoon();
- buzz(8);
- }
- _updateCustom(uid, patch, commit = true) {
- if (commit) this._pushUndo();
- this.stage.updateCustom(uid, patch);
- this.cust = this.cust.map((x) => (x.uid === uid ? { ...x, ...patch } : x));
- this.requestUpdate();
- this._saveSoon();
- }
- _deleteCustom(uid) {
- this._pushUndo();
- this.stage.removeCustom(uid);
- this.cust = this.cust.filter((x) => x.uid !== uid);
- if (this.selUid === uid) this.exitEdit();
- this.requestUpdate();
- this._saveSoon();
- buzz(8);
- }
- _ring(uid, n) {
- const spec = this.cust.find((x) => x.uid === uid);
- if (!spec) return;
- this._pushUndo();
- const c = this.stage?._cav?.() || { r: 20 };
- const r = Math.hypot(spec.x || 0, spec.z || 0) || Math.max(6, (c.r || 20) * 0.55);
- const ring = arrayRing({ uid: spec.uid, type: spec.type, params: { ...spec }, at: { x: spec.x, y: spec.y, z: spec.z }, rotY: spec.rot || 0, label: '' }, n, r);
- const fresh = ring.map((p, i) => ({
- uid: spec.uid + 0.001 * (i + 1), type: spec.type, x: p.at.x, y: p.at.y, z: p.at.z,
- rot: Math.round(p.rotY || 0), w: spec.w, h: spec.h, dd: spec.dd, dia: spec.dia, hd: spec.hd, snap: spec.snap,
- }));
- for (const s of fresh) this.stage.addCustom(s.type, s);
- this.cust = [...this.cust, ...fresh];
- this.requestUpdate();
- this._saveSoon();
- buzz(8);
- }
- _tool(uid, kind) {
- const spec = this.cust.find((x) => x.uid === uid);
- if (!spec) return;
- const c = this.stage?._cav?.() || { kind: 'cyl', r: 20 };
- let patch = null;
- if (kind === 'center') patch = { x: 0, z: 0 };
- else if (kind === 'wall') {
- const w = spec.w || spec.dia || 4, d = spec.dd || spec.dia || 4;
- if (c.kind === 'cyl') {
- const rr = Math.max(0, (c.r || 20) - Math.max(w, d) / 2 - 0.5);
- patch = { x: Math.round(rr * 10) / 10, z: 0 };
- } else {
- patch = { x: 0, z: Math.round(((c.d || 20) / 2 - d / 2 - 0.5) * 10) / 10 };
- }
- } else if (kind === 'top') patch = { y: Math.round((this._y0() + (this._validationShell().h || 10) - (spec.h || 1)) * 10) / 10 };
- else if (kind === 'bottom') patch = { y: this._y0() };
- if (patch) this._updateCustom(uid, patch);
- }
- _snapStepChange(v) {
- this.snapStep = Number(v);
- const spec = this.sel;
- if (spec) this._updateCustom(spec.uid, { snap: this.snapStep }, false);
- this.requestUpdate();
- }
- /* ---------------- 坞:三档吸附 ---------------- */
- _setDockPx(name, animateMs = 300) {
- this.dock = name;
- const el = this.querySelector('.dock');
- if (!el) return;
- const h = Math.round(innerHeight * DOCK[name]);
- el.style.transitionDuration = `${animateMs}ms`;
- const px = name === 'peek' ? Math.max(56, h) : h;
- el.style.height = `${px}px`;
- this.style.setProperty('--dock-h', `${px}px`);
- if (name === 'peek') el.classList.add('min');
- else el.classList.remove('min');
- this._saveSoon();
- }
- _bindHead() {
- const head = this.querySelector('.dock-head');
- if (!head || head._bound) return;
- head._bound = true;
- let dragging = false, startY = 0, h0 = 0, moved = false;
- head.addEventListener('pointerdown', (e) => {
- if (e.target.closest('button, input')) return;
- dragging = true; moved = false;
- startY = e.clientY;
- const el = this.querySelector('.dock');
- h0 = el.getBoundingClientRect().height;
- el.style.transitionDuration = '0ms';
- head.setPointerCapture?.(e.pointerId);
- });
- head.addEventListener('pointermove', (e) => {
- if (!dragging) return;
- const dy = startY - e.clientY;
- if (Math.abs(dy) > 4) moved = true;
- const h = Math.max(56, Math.min(innerHeight * 0.86, h0 + dy));
- this.querySelector('.dock').style.height = `${h}px`;
- this.style.setProperty('--dock-h', `${Math.round(h)}px`);
- });
- const end = () => {
- if (!dragging) return;
- dragging = false;
- const h = this.querySelector('.dock').getBoundingClientRect().height;
- if (!moved) { this._setDockPx(this.dock === 'peek' ? 'half' : 'peek', 300); return; }
- let best = 'half', bd = Infinity;
- for (const [k, r] of Object.entries(DOCK)) { const d = Math.abs(h - innerHeight * r); if (d < bd) { bd = d; best = k; } }
- this._setDockPx(best, 300);
- };
- head.addEventListener('pointerup', end);
- head.addEventListener('pointercancel', end);
- }
- _watchViewport() {
- const vv = window.visualViewport;
- if (!vv) return;
- const onVv = () => {
- const kb = Math.max(0, innerHeight - vv.height - vv.offsetTop);
- this.style.setProperty('--kb', `${Math.round(kb)}px`);
- this.style.setProperty('--dock-max', `${Math.round(vv.height)}px`);
- };
- vv.addEventListener('resize', onVv);
- vv.addEventListener('scroll', onVv);
- onVv();
- this._unwatchViewport = () => { vv.removeEventListener('resize', onVv); vv.removeEventListener('scroll', onVv); };
- }
- /* ---------------- 导出 ---------------- */
- _download(name, data, type) {
- const blob = data instanceof Blob ? data : new Blob([data], { type });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = name;
- document.body.appendChild(a);
- a.click();
- a.remove();
- setTimeout(() => URL.revokeObjectURL(url), 1500);
- this.status = '已导出 ' + name;
- this.requestUpdate();
- return url;
- }
- _exportMesh(kind, partId = null) {
- if (!this.stage) return;
- const base = `${this.p.id}-${this.stageId}`;
- const r = kind === 'stl'
- ? (partId ? this.stage.exportSTLPart(partId + '-' + base, partId) : this.stage.exportSTL(base))
- : (partId ? this.stage.exportOBJPart(partId + '-' + base, partId) : this.stage.exportOBJ(base));
- if (!r || !r.text) { this.status = '没有可导出的网格'; this.requestUpdate(); return; }
- this._download(`${base}${partId ? '-' + partId : ''}.${r.ext}`, r.text, kind === 'stl' ? 'model/stl' : 'model/obj');
- }
- async _exportPartMesh(kind) {
- if (!this.stage) return;
- const rows = this.partRows.filter((x) => x.cnt > 0 && !x.custom);
- for (const row of rows) {
- const r = kind === 'stl' ? this.stage.exportSTLPart(`${this.p.id}-${row.id}`, row.id) : this.stage.exportOBJPart(`${this.p.id}-${row.id}`, row.id);
- if (!r || !r.text) continue;
- this._download(`${this.p.id}-${row.id}.${r.ext}`, r.text, kind === 'stl' ? 'model/stl' : 'model/obj');
- await new Promise((res) => setTimeout(res, 120));
- }
- }
- _exportPng() {
- if (!this.stage) return;
- const data = this.stage.snapshot();
- if (!data) { this.status = '截图失败(当前渲染后端不支持)'; this.requestUpdate(); return; }
- const a = document.createElement('a');
- a.href = data;
- a.download = `${this.p.id}-${this.selectedPart || 'view'}.png`;
- document.body.appendChild(a); a.click(); a.remove();
- this.status = '已导出 ' + a.download;
- this.requestUpdate();
- }
- _exportBomCsv() {
- const rows = [['序号', '分组', '名称', '规格', '供应商', '单价', '数量', '小计']];
- for (const r of this.p.bom?.rows || []) rows.push([r.seq, r.group || '', r.name, r.spec || '', r.supplier || '', r.price, r.qty, r.subtotal]);
- rows.push(['', '', '合计', '', '', '', '', this.p.bom?.bomTotal ?? '']);
- const csv = '' + rows.map((r) => r.map((v) => `"${String(v ?? '').replace(/"/g, '""')}"`).join(',')).join('\n');
- this._download(`${this.p.id}-bom.csv`, csv, 'text/csv;charset=utf-8');
- }
- _exportJson() {
- this._download(`${this.p.id}-engineering.json`, JSON.stringify({
- app: 'Pocket Hardware Lab', version: 'v4', generator: 'FmodeCode', exportedAt: new Date().toISOString(), unit: 'mm',
- id: this.p.id, stage: this.stageId, params: this.params, material: this.material,
- explode: this.explode, dims: this.dims, cust: this.cust, process: this.rk, parts: this.stage?.partIds() || [],
- }, null, 2), 'application/json');
- }
- /** 生产需求单(Markdown):参数快照 + 材质 + 公差 + 装配 + 结构件坐标 + 报价回填 */
- specMarkdown() {
- const p = this.p, proj = this.stageProject(), L = [];
- const date = new Date().toISOString().slice(0, 10);
- const matName = STAGE_MOD?.MATERIALS?.[this.material]?.name || this.material;
- L.push(`# 生产需求单 · ${p.name}`, '');
- L.push(`- 型号:${p.latin || p.name}(${p.id})`);
- L.push(`- 日期:${date};单位 mm / °;工艺:${PROC_RULES[this.rk]?.name || this.rk}`);
- L.push(`- 外观材质:${matName}(${this.material});参考:${proj.ref || '—'}`);
- L.push('- 本单由 Pocket Hardware Lab 实验室按当前 3D 参数快照自动生成(FmodeCode)', '');
- L.push('## 1. 参数快照', '', '| 参数 | 键 | 数值 |', '| --- | --- | --- |');
- for (const x of proj.params) L.push(`| ${x.n} | ${x.k} | ${fmt(this.params[x.k], 2)} |`);
- L.push('', '## 2. 零件清单(专属结构)', '', '| 零件 | 数量 | 材质 | 工艺 | 公差 |', '| --- | --- | --- | --- | --- |');
- for (const pt of proj.parts || []) L.push(`| ${pt.n} | ${pt.q} | ${pt.mat} | ${pt.proc} | ${pt.tol} |`);
- for (const s of this.cust) L.push(`| 结构件 #${s.uid}(${s.type}) | 1 | 随主材质 | 自定义 | ±0.1 |`);
- const tol = [...(proj.tolerance || []), ...(p.parts || []).filter((x) => x.tolerance).map((x) => [x.name, x.tolerance])];
- L.push('', '## 3. 公差与验收', '', '| 部位 | 公差 |', '| --- | --- |');
- for (const [a, b] of tol) L.push(`| ${esc(a)} | ${esc(b)} |`);
- L.push('| 整机外形 | ±0.10 |', '| 首件 | 三坐标 / 影像仪报告 + 实配照片 |', '');
- L.push('## 4. 装配顺序', '');
- (proj.steps || []).forEach((s, i) => L.push(`${i + 1}. **${s.n}**:${s.d}`));
- L.push('', '## 5. 结构件坐标表(壳中心为原点;X 右 / Y 上 / Z 前)', '');
- if (!this.cust.length) L.push('- 暂无自定义结构件(按主体参数推定)。');
- else {
- L.push('| uid | 类型 | X | Y | Z | 绕 Y | 尺寸 |', '| --- | --- | --- | --- | --- | --- | --- |');
- for (const s of this.cust) L.push(`| ${s.uid} | ${s.type} | ${fmt(s.x, 2)} | ${fmt(s.y, 2)} | ${fmt(s.z, 2)} | ${fmt(s.rot || 0, 1)}° | ${fmt(s.w ?? s.dia, 2)}×${fmt(s.h, 2)}×${fmt(s.dd ?? s.dia, 2)} |`);
- }
- L.push('', `## 6. 工艺校验(${PROC_RULES[this.rk]?.name || this.rk})`, '');
- const checks = this.checks;
- if (!checks.length) L.push('- 自定义结构件全部通过。');
- for (const c of checks) L.push(`- [${c.level === 'error' ? ' ' : 'x'}] ${c.level === 'error' ? '待改' : '提醒'}:${c.msg}`);
- L.push('', '## 7. 供应商报价回填表', '', '| 项目 | 供应商填写 |', '| --- | --- |');
- for (const x of ['模具费(含试模 / 改模)', '单品单价(含税 / 不含税)', '最小起订量 MOQ', '打样费及抵扣规则', '交期(打样 / 大货)', '模具归属', '表面处理 / 色号', '有效期']) L.push(`| ${x} | |`);
- L.push('', '---', '生产需求单由 Pocket Hardware Lab · FmodeCode 生成;价格口径见产品页,不构成报价承诺。');
- return L.join('\n');
- }
- _exportSpec() {
- this._download(`${this.p.id}-生产需求单.md`, this.specMarkdown(), 'text/markdown;charset=utf-8');
- }
- /* ---------------- 渲染 ---------------- */
- render() {
- if (this.error) return html`<ph-error .error=${this.error}></ph-error>`;
- if (!this.p) return html`<div style="padding:96px;text-align:center;color:var(--ink-3)">载入产品…</div>`;
- const p = this.p;
- const proj = this.stageProject();
- const errs = this.checks.filter((c) => c.level === 'error').length;
- const warns = this.checks.length - errs;
- return html`
- <div class="lab">
- <div class="bar">
- <span><a data-link href=${linkHref(`/p/${p.id}`)}>← 详情</a></span>
- <span class="t">${p.name} · 实验室</span>
- <span class="live"></span>
- <button class="reset" @click=${() => { this.stage?.frame(); this._setView('iso'); }}>适应视图</button>
- </div>
- <div class="stage" style=${`bottom:${this.dock === 'peek' ? 56 : `calc(${DOCK[this.dock] * 100}dvh)`}`}>
- <canvas aria-label="3D 产品结构:单指旋转,双指缩放,点零件隔离,双击复位"></canvas>
- <div class="xbar" role="toolbar" aria-label="视图工具">
- <div class="xrow">
- <span class="xl">爆炸</span>
- <input type="range" class="explode" min="0" max="1" step="0.01" .value=${String(this.explode)}
- @input=${(e) => this._setExplode(e.target.value, false)} @change=${() => this._pushUndo()}
- aria-label="爆炸程度 0 到 100%" />
- <span class="xpct">${Math.round(this.explode * 100)}%</span>
- <button class=${this.cutaway ? 'on' : ''} @click=${() => this._toggleCutaway()} title="剖视 / 透视">剖视</button>
- <button class=${this.dims ? 'on' : ''} @click=${() => this._toggleDims()} title="尺寸标注">标注</button>
- <button class=${this.glow ? 'on' : ''} @click=${() => this._toggleGlow()} title="氛围灯">氛围</button>
- </div>
- <div class="xrow">
- <span class="xl">视角</span>
- <div class="seg" role="group" aria-label="视角">
- ${VIEWS.map(([k, label]) => html`<button class=${this.view === k ? 'on' : ''} @click=${() => this._setView(k)}>${label}</button>`)}
- </div>
- <span class="xl mat-l">材质</span>
- <div class="mats" role="group" aria-label="材质">
- ${(proj.materials || []).map((k) => {
- const m = STAGE_MOD?.MATERIALS?.[k] || {};
- return html`<button class=${this.material === k ? 'on' : ''} title=${m.name || k} aria-label=${m.name || k} @click=${() => this._setMaterial(k)}>
- <i style=${`background:${m.swatch || m.albedo || '#ccc'}`}></i>
- </button>`;
- })}
- </div>
- </div>
- </div>
- <div class="hint">${this.selectedPart ? `隔离:${this._partName(this.selectedPart)} · 再点取消` : '点零件隔离 · 拖动结构件落位 · 双击复位'}</div>
- </div>
- <section class="dock ${this.dock}" data-dock=${this.dock}>
- <div class="dock-head" title="拖动调高度 · 点击档位切换">
- <div class="grab" aria-hidden="true"></div>
- <div class="head-row">
- <button class="tab" @click=${() => this._setDockPx(this.dock === 'peek' ? 'half' : 'peek', 300)} aria-label="切换面板高度">${this.tab === 'shape' ? '形体参数' : this.tab === 'parts' ? '零件' : this.tab === 'bom' ? 'BOM' : '导出'}</button>
- <span class="count">${this.cust.length ? `结构件 ${this.cust.length}` : ''}</span>
- ${errs ? html`<span class="badge err">${errs} 错误</span>` : ''}
- ${warns ? html`<span class="badge warn">${warns} 提醒</span>` : ''}
- <span class="grow"></span>
- <span class="hist">
- <button class="undo" title="撤销 ⌘Z" ?disabled=${!this.undoStack.length} @click=${() => this.undo()}>↺</button>
- <button class="redo" title="重做 ⇧⌘Z" ?disabled=${!this.redoStack.length} @click=${() => this.redo()}>↻</button>
- </span>
- <button class="fold" aria-label=${this.dock === 'peek' ? '展开面板' : '收起面板'} @click=${() => this._setDockPx(this.dock === 'peek' ? 'half' : 'peek', 300)}>${this.dock === 'peek' ? '⌃' : '⌄'}</button>
- </div>
- </div>
- <div class="tabs">
- ${[['shape', '形体'], ['parts', '零件 · 结构'], ['bom', 'BOM'], ['export', '导出']].map(([k, label]) => html`
- <button class=${this.tab === k ? 'on' : ''} @click=${() => { this.tab = k; if (this.dock === 'peek') this._setDockPx('half', 300); this.requestUpdate(); }}>${label}</button>`)}
- </div>
- <div class="body">
- ${this.tab === 'shape' ? this._shapeTab() : ''}
- ${this.tab === 'parts' ? (this.sel ? this._editTab() : this._partsTab()) : ''}
- ${this.tab === 'bom' ? html`<ph-bom .bom=${p.bom}></ph-bom>` : ''}
- ${this.tab === 'export' ? this._exportTab() : ''}
- </div>
- ${this.picker ? this._pickerOverlay() : ''}
- </section>
- </div>`;
- }
- updated() {
- this._bindHead();
- this._syncHistoryBtns();
- }
- _partName(id) {
- const row = this.partRows.find((r) => r.id === id);
- if (row) return row.n;
- if (STAGE_MOD) return STAGE_MOD.PROJECTS[this.stageId]?.parts?.find((x) => x.id === id)?.n || id;
- return id;
- }
- _shapeTab() {
- const proj = this.stageProject();
- const groups = [...new Set(proj.params.map((x) => x.group))];
- return html`
- <div class="proc-row">
- <span>工艺规则</span>
- <select @change=${(e) => { this.rk = resolveProc(e.target.value); this.requestUpdate(); this._saveSoon(); }} aria-label="工艺规则">
- ${PROC_KEYS.map((k) => html`<option value=${k} ?selected=${this.rk === k}>${PROC_RULES[k].name}</option>`)}
- </select>
- <small>${proj.parts?.length || 0} 个专属零件 · 参考 ${esc(proj.ref || '')}</small>
- </div>
- <p class="muted">${esc(proj.summary || '')}</p>
- ${groups.map((g) => html`
- <div class="pgroup"><div class="glabel">${g}</div>
- <div class="grid">
- ${proj.params.filter((x) => x.group === g).map((x) => {
- const v = this.params[x.k];
- return html`<div class="ctl">
- <label for="s-${x.k}"><span>${x.n}</span><small>${x.k}</small></label>
- <input type="range" id="s-${x.k}" min=${x.min} max=${x.max} step=${x.step} .value=${String(v)}
- @input=${(e) => this._setParam(x.k, e.target.value, false)} @change=${() => this._pushUndo()}
- aria-label=${x.n} />
- <input type="number" min=${x.min} max=${x.max} step=${x.step} .value=${String(v)}
- @change=${(e) => this._setParam(x.k, e.target.value)} aria-label=${x.n + ' 数值'} />
- </div>`;
- })}
- </div>
- </div>`)}
- <div style="margin-top:18px"><button class="btn ghost sm" @click=${() => this._resetAll()}>恢复默认参数</button></div>`;
- }
- _partsTab() {
- const rows = this.partRows;
- return html`
- <p class="muted">点零件:隔离 + 相机聚焦 + 高亮;再点一次取消。结构件可直接在视口里拖动落位。</p>
- <div class="list">
- ${rows.map((row) => html`
- <div class="row ${!row.custom && this.selectedPart === row.id ? 'on' : ''} ${row.custom && this.selUid === row.uid ? 'on' : ''}"
- @click=${() => this._togglePart(row)} role="button" tabindex="0"
- @keydown=${(e) => { if (e.key === 'Enter') this._togglePart(row); }}>
- <span class="ic" aria-hidden="true">${row.custom ? '+' : '◇'}</span>
- <span class="meta">
- <b>${row.n}</b>
- <small>${row.custom ? `结构件 #${row.uid} · ${row.proc}` : `${esc(row.proc)} · ${esc(row.tol)}`}${row.cnt > 1 ? ` · ×${row.cnt}` : ''}</small>
- </span>
- ${row.custom ? html`<button class="del" aria-label="删除" @click=${(e) => { e.stopPropagation(); this._deleteCustom(row.uid); }}>×</button>` : html`<span class="cnt">${row.cnt > 1 ? row.cnt : ''}</span>`}
- </div>`)}
- </div>
- <div class="add-row">
- <button class="btn sm" @click=${() => { this.picker = true; this.requestUpdate(); }}>+ 添加结构件</button>
- ${this.p.features?.length ? html`<button class="btn ghost sm" @click=${() => this._applyFeatures()}>应用推荐结构(${this.p.features.length})</button>` : ''}
- </div>
- ${this.checks.length ? html`<ul class="issues">${this.checks.slice(0, 6).map((c) => html`<li class=${c.level}>${c.msg}</li>`)}</ul>` : ''}`;
- }
- _applyFeatures() {
- const feats = this.p.features || [];
- if (!feats.length) return;
- this._pushUndo();
- const map = { 'screw-pillar': 'boss25', boss: 'boss25', standoff: 'boss2', rib: 'rib', snap: 'clip', pocket: 'pocket', tray: 'tray', wall: 'wall' };
- for (const f of feats) {
- const type = map[f.type] || 'box';
- const spec = this.stage.addCustom(type, { x: Number(f.at?.x) || 0, y: this._y0() + (Number(f.at?.y) || 0) * 0.3, z: Number(f.at?.z) || 0 });
- this.cust = [...this.cust, spec];
- }
- this.status = `已应用 ${feats.length} 个推荐结构件`;
- this.requestUpdate();
- this._saveSoon();
- }
- _editTab() {
- const s = this.sel;
- if (!s) return '';
- const prim = this.stage?.PRIMS?.[s.type] || {};
- const schema = (() => { try { return paramSchema(s.type); } catch { return []; } })();
- const maxY = Math.max(2, this._y0() + this._validationShell().h + 4);
- const xzMax = Math.max(10, Math.round((this.stage?._cav?.()?.r || 30) + 10));
- const issues = this.checks.filter((c) => c.partUid === s.uid);
- return html`
- <div class="edit-head">
- <button class="back" @click=${() => this.exitEdit()}>← 全部</button>
- <b>${prim.n || s.type} #${s.uid}</b>
- <span class="grow"></span>
- <span class="snap">吸附
- ${SNAP_STEPS.map((v) => html`<button class=${this.snapStep === v ? 'on' : ''} @click=${() => this._snapStepChange(v)}>${v}</button>`)}
- <i>mm</i>
- </span>
- </div>
- <div class="grid dense">
- ${[['x', 'X', -xzMax, xzMax], ['y', 'Y(壳底为 0)', Math.min(-2, this._y0()), maxY], ['z', 'Z', -xzMax, xzMax]].map(([k, lb, lo, hi]) => html`
- <div class="ctl">
- <label><span>${lb}</span><small>${k}</small></label>
- <input type="range" min=${lo} max=${hi} step=${this.snapStep} .value=${String(s[k] ?? 0)}
- @input=${(e) => this._updateCustom(s.uid, { [k]: Number(e.target.value) }, false)} @change=${() => this._pushUndo()} />
- <input type="number" min=${lo} max=${hi} step=${this.snapStep} .value=${String(s[k] ?? 0)}
- @change=${(e) => this._updateCustom(s.uid, { [k]: Number(e.target.value) })} />
- </div>`)}
- ${schema.map((f) => html`
- <div class="ctl">
- <label><span>${f.label}${f.unit || ''}</span><small>${f.key}</small></label>
- <input type="range" min=${f.min} max=${f.max} step=${f.step} .value=${String(s[f.key] ?? f.def)}
- @input=${(e) => this._updateCustom(s.uid, { [f.key]: Number(e.target.value) }, false)} @change=${() => this._pushUndo()} />
- <input type="number" min=${f.min} max=${f.max} step=${f.step} .value=${String(s[f.key] ?? f.def)}
- @change=${(e) => this._updateCustom(s.uid, { [f.key]: Number(e.target.value) })} />
- </div>`)}
- <div class="ctl">
- <label><span>绕 Y 旋转</span><small>rot</small></label>
- <input type="range" min="0" max="360" step="1" .value=${String(s.rot || 0)}
- @input=${(e) => this._updateCustom(s.uid, { rot: Number(e.target.value) }, false)} @change=${() => this._pushUndo()} />
- <input type="number" min="0" max="360" step="1" .value=${String(s.rot || 0)}
- @change=${(e) => this._updateCustom(s.uid, { rot: Number(e.target.value) })} />
- </div>
- </div>
- <div class="tools">
- <button @click=${() => this._tool(s.uid, 'center')}>居中</button>
- <button @click=${() => this._tool(s.uid, 'wall')}>贴内壁</button>
- <button @click=${() => this._tool(s.uid, 'top')}>贴顶</button>
- <button @click=${() => this._tool(s.uid, 'bottom')}>贴底</button>
- <span class="sep"></span>
- ${[4, 6, 8].map((n) => html`<button @click=${() => this._ring(s.uid, n)}>环形 ×${n}</button>`)}
- <button class="danger" @click=${() => this._deleteCustom(s.uid)}>删除</button>
- </div>
- ${issues.length ? html`<ul class="issues">${issues.map((c) => html`<li class=${c.level}>${c.msg}</li>`)}</ul>` : ''}`;
- }
- _pickerOverlay() {
- const PRIMS = this.stage?.PRIMS || {};
- const groups = {};
- for (const k of Object.keys(PRIMS)) (PRIMS[k].tag = PRIMS[k].tag || '基础', groups[PRIMS[k].tag] = groups[PRIMS[k].tag] || []).push(k);
- return html`
- <div class="picker" role="dialog" aria-label="选择结构件类型">
- <div class="picker-head"><b>添加结构件</b><span class="muted">14 类标准形体</span><span class="grow"></span><button class="x" aria-label="关闭" @click=${() => { this.picker = false; this.requestUpdate(); }}>×</button></div>
- ${Object.entries(groups).map(([g, list]) => html`
- <div class="pgroup"><div class="glabel">${g}</div>
- <div class="pgrid2">
- ${list.map((k) => html`<button class="pcell" data-type=${k} @click=${() => this._addCustom(k)}>
- <span class="ic big" .innerHTML=${primIcon(k)}></span><b>${PRIMS[k].n}</b>
- </button>`)}
- </div>
- </div>`)}
- </div>`;
- }
- _exportTab() {
- const sel = this.selectedPart;
- return html`<div class="export">
- <div class="exgrid">
- <div class="ex">
- <b>整件 STL</b><small>全部可见壳体 + 结构件,ASCII STL,单位 mm</small>
- <button class="btn sm" @click=${() => this._exportMesh('stl')}>下载整件</button>
- </div>
- <div class="ex">
- <b>整件 OBJ</b><small>带零件分组 o 名称,可进渲染器 / 切片前检查</small>
- <button class="btn ghost sm" @click=${() => this._exportMesh('obj')}>下载整件</button>
- </div>
- <div class="ex">
- <b>分件 STL</b><small>${sel ? `当前隔离:${this._partName(sel)}` : '每个零件一个文件'}</small>
- <button class="btn ghost sm" @click=${() => (sel && !sel.startsWith('c') ? this._exportMesh('stl', sel) : this._exportPartMesh('stl'))}>${sel && !sel.startsWith('c') ? '下载该件' : '逐件下载'}</button>
- </div>
- <div class="ex">
- <b>分件 OBJ</b><small>同上,OBJ 分组格式</small>
- <button class="btn ghost sm" @click=${() => (sel && !sel.startsWith('c') ? this._exportMesh('obj', sel) : this._exportPartMesh('obj'))}>${sel && !sel.startsWith('c') ? '下载该件' : '逐件下载'}</button>
- </div>
- <div class="ex">
- <b>截图 PNG</b><small>当前 3D 视角,含爆炸 / 剖视 / 标注状态</small>
- <button class="btn ghost sm" @click=${() => this._exportPng()}>保存截图</button>
- </div>
- <div class="ex">
- <b>生产需求单</b><small>参数 / 零件 / 公差 / 装配 / 结构件坐标 / 报价回填</small>
- <button class="btn ghost sm" @click=${() => this._exportSpec()}>下载 .md</button>
- </div>
- <div class="ex">
- <b>BOM CSV</b><small>物料清单,Excel 可直接打开</small>
- <button class="btn ghost sm" @click=${() => this._exportBomCsv()}>下载 CSV</button>
- </div>
- <div class="ex">
- <b>工程 JSON</b><small>参数 + 材质 + 结构件 + 零件清单,可复现</small>
- <button class="btn ghost sm" @click=${() => this._exportJson()}>下载 JSON</button>
- </div>
- </div>
- <p class="muted">文件名前缀 ${this.p.id};STL 单位 mm,Y 轴向上,壳中心为原点。剖视 / 爆炸状态下导出的仍是装配位置。</p>
- ${this.status ? html`<span class="status">${this.status}</span>` : ''}
- </div>`;
- }
- }
- let STAGE_MOD = null;
- customElements.define('ph-lab', PhLab);
- export function labPage() {
- return new PhLab();
- }
|