// ==UserScript== // @name X66全量脚本 // @namespace x66.tools // @version 1.0.2 // @description X66 标注平台脚本合集。当前模块:尺寸锚定覆盖 —— 平台覆盖尺寸时两端平分,本脚本改成只保留你没动的那一端 // @match http://data-label-lan.gacrnd.com/tool/pc* // @match http://data-label.ruqimobility.com/tool/pc* // @run-at document-idle // @grant none // ==/UserScript== /* ========================================================================== * X66 全量脚本 * 模块化容器:以后新增功能,在 MODULES 里加一项即可,互不干扰。 * 当前模块: * 1. 尺寸锚定覆盖 —— 平台「尺寸覆盖」只改尺寸不动中心,导致两端平分; * 本模块改成单侧锚定,保留你没动的那一端。 * 通用能力: * · 面板/悬浮球可拖动,位置存 localStorage,刷新后自动复原 * ========================================================================== */ (() => { 'use strict'; if (window.__x66Loaded) return; window.__x66Loaded = true; const VERSION = '1.0.2'; const AXES = ['x', 'y', 'z']; const EPS = 1e-7; // 端面「确实没动」的容差:max(绝对 1mm, 尺寸变化的 5%) const END_TOL_ABS = 1e-3; const END_TOL_RATIO = 0.05; const X66 = (window.X66 = window.X66 || {}); X66.version = VERSION; /* ======================== 模块:尺寸锚定覆盖 ======================== */ const LS = { enabled: 'x66.anchor.enabled', keep: 'x66.anchor.keepDelta', mem: 'x66.anchor.memory', flip: 'x66.anchor.flip', pos: 'x66.anchor.pos', // { panel:{left,top}, toggle:{left,top} } }; const state = { enabled: true, keepDelta: false, memory: {}, // trackKey -> 'L' | 'R' flip: {}, // trackKey -> { long:1, short:1 } 方位翻转 baseline: new Map(), // "frameId|uuid" -> {scale,pos} lastSeen: new Map(), votes: new Map(), lastUndo: null, pendingType: null, pollTimer: 0, }; X66.state = state; try { state.enabled = localStorage.getItem(LS.enabled) !== 'false'; state.keepDelta = localStorage.getItem(LS.keep) === 'true'; state.memory = JSON.parse(localStorage.getItem(LS.mem) || '{}') || {}; state.flip = JSON.parse(localStorage.getItem(LS.flip) || '{}') || {}; } catch {} const ed = () => window.editor; /* ---------------- 提示 ---------------- */ let toastEl, toastTimer; function toast(msg, isError) { if (!document.body) return; if (!toastEl) { toastEl = document.createElement('div'); toastEl.style.cssText = 'position:fixed;left:50%;top:64px;transform:translateX(-50%);z-index:2147483647;' + 'max-width:calc(100vw - 40px);padding:9px 15px;border-radius:6px;font:13px/1.55 system-ui,sans-serif;' + 'box-shadow:0 4px 16px #0006;pointer-events:none;white-space:pre-wrap;transition:opacity .18s'; document.body.append(toastEl); } toastEl.style.background = isError ? '#432b30' : '#203a30'; toastEl.style.color = '#edf3fa'; toastEl.style.border = '1px solid ' + (isError ? '#a86060' : '#49886c'); toastEl.style.opacity = '1'; toastEl.textContent = msg; clearTimeout(toastTimer); toastTimer = setTimeout(() => { toastEl.style.opacity = '0'; }, isError ? 5000 : 2400); } /* ---------------- 读平台对象 ---------------- */ function currentFrame() { const e = ed(); if (!e?.state?.frames) return null; return e.state.frames[e.state.frameIndex] || null; } function frameObjects(frameId) { const e = ed(); if (!e?.dataManager) return null; const viaMap = e.dataManager.dataMap?.get?.(String(frameId)); if (Array.isArray(viaMap)) return viaMap; const viaFn = e.dataManager.getFrameObject?.(frameId); return Array.isArray(viaFn) ? viaFn : null; } function selectedBox() { const sel = ed()?.pc?.selection; if (!Array.isArray(sel) || sel.length !== 1) return null; const box = sel[0]; if (!box || box.type !== 'Box3Helper' || !box.uuid) return null; if (!box.scale || !box.position) return null; return box; } const snapshotOf = box => ({ scale: [box.scale.x, box.scale.y, box.scale.z], pos: [box.position.x, box.position.y, box.position.z], }); function baseKey(frame, box) { return String(frame?.id) + '|' + box.uuid; } function trackKeyOf(box) { if (!box) return null; const cls = box.userData?.classType || '?'; const tn = box.userData?.trackName; if (tn === undefined || tn === null || tn === '') return 'uuid#' + box.uuid; return cls + '#' + tn; } /* ---------------- 几何 ---------------- */ function toLocal(box, dWorld) { const V3 = box.position.constructor; const v = new V3(dWorld[0], dWorld[1], dWorld[2]); if (box.quaternion) { const q = box.quaternion.clone(); q.invert(); v.applyQuaternion(q); } return [v.x, v.y, v.z]; } /* ---------------- 核心判据:双端对照 ---------------- */ // dc=中心沿本地轴位移,ds=该轴尺寸变化 // A端(低端) 位移 dA = dc − ds/2 // B端(高端) 位移 dB = dc + ds/2 // 只有「一端≈0、另一端明显动」才下结论;两端都动(平移污染/对称缩放)一律不猜。 // 返回 'L'=保留低端 | 'R'=保留高端 | null=判不出 function judgeEnds(dc, ds, tol) { if (!Number.isFinite(dc) || !Number.isFinite(ds) || Math.abs(ds) < 1e-5) return null; const dA = dc - ds / 2; const dB = dc + ds / 2; const aStill = Math.abs(dA) <= tol; const bStill = Math.abs(dB) <= tol; if (aStill && !bStill) return 'L'; if (bStill && !aStill) return 'R'; return null; } const endTol = ds => Math.max(END_TOL_ABS, Math.abs(ds) * END_TOL_RATIO); /* ---------------- 方位命名(平台正交视图投影) ---------------- * 平台约定(实测确认): * · 点云坐标系是 Z-up,世界 (0,0,1) 为竖直向上 * · 侧视图里,画面右侧 = 车头 * · 后视图里,画面左 = 车左、画面右 = 车右 * 做法:把框长轴两端投影进「侧视图」,投影 x 大的一端是车头; * 把短轴两端投影进「后视图」,投影 x 小的一端是车左。 * 视图从 editor.pc.renderViews 取(axis 字段标记观察轴,相机是正交相机)。 * ------------------------------------------------------------------ */ const orientCache = new Map(); function orthoViews() { const rv = ed()?.pc?.renderViews; if (!Array.isArray(rv)) return []; return rv.filter(v => v && v.axis && v.camera); } function computeOrientation(box) { const V = box.position.constructor; const q = box.quaternion; // 1. 竖直轴:世界 up 反算到本地,取分量最大的轴 const up = new V(0, 0, 1); if (q) up.applyQuaternion(q.clone().invert()); const absUp = [Math.abs(up.x), Math.abs(up.y), Math.abs(up.z)]; const vIdx = absUp.indexOf(Math.max(...absUp)); // 2. 剩下两个水平轴:长的算车长(前后),短的算车宽(左右) const horiz = [0, 1, 2].filter(i => i !== vIdx); const longIdx = box.scale[AXES[horiz[0]]] >= box.scale[AXES[horiz[1]]] ? horiz[0] : horiz[1]; const shortIdx = horiz[0] === longIdx ? horiz[1] : horiz[0]; const dirOf = i => new V(i === 0 ? 1 : 0, i === 1 ? 1 : 0, i === 2 ? 1 : 0).applyQuaternion(q); // 3. 某轴两端在给定视图里的投影:dx 决定左右,len 决定这个视图能否看到这根轴 const measure = (view, idx) => { const d = dirOf(idx); const h = box.scale[AXES[idx]] / 2; const pPlus = box.position.clone().addScaledVector(d, h).project(view.camera); const pMinus = box.position.clone().addScaledVector(d, -h).project(view.camera); if (!Number.isFinite(pPlus.x) || !Number.isFinite(pMinus.x)) return null; return { dx: pPlus.x - pMinus.x, len: Math.hypot(pPlus.x - pMinus.x, pPlus.y - pMinus.y) }; }; let sideDx = null, backDx = null; let sideBest = Infinity, backBest = Infinity; for (const v of orthoViews()) { try { v.camera.updateMatrixWorld(true); } catch { continue; } const L = measure(v, longIdx); const S = measure(v, shortIdx); if (!L || !S) continue; // 侧视图:短轴沿视线(投影最短),长轴横着铺开 if (S.len < sideBest - 1e-6) { sideBest = S.len; sideDx = L.dx; } // 后视图:长轴沿视线(投影最短),短轴横着铺开 if (L.len < backBest - 1e-6) { backBest = L.len; backDx = S.dx; } } return { vIdx, longIdx, shortIdx, upPosIsTop: up.getComponent(vIdx) > 0, longPosIsFront: sideDx === null ? true : sideDx > 0, shortPosIsLeft: backDx === null ? true : backDx < 0, ok: sideDx !== null && backDx !== null, }; } function orientationOf(box) { const key = [ box.quaternion.x, box.quaternion.y, box.quaternion.z, box.quaternion.w, box.scale.x, box.scale.y, box.scale.z, ].map(v => v.toFixed(4)).join(','); const hit = orientCache.get(box.uuid); if (hit && hit.key === key) return hit.val; let val = null; try { val = computeOrientation(box); } catch (err) { console.warn('[X66] 方位计算失败', err); } if (!val) { val = { vIdx: 1, longIdx: 0, shortIdx: 2, upPosIsTop: true, longPosIsFront: true, shortPosIsLeft: true, ok: false }; } if (orientCache.size > 300) orientCache.clear(); orientCache.set(box.uuid, { key, val }); return val; } function axisMeta(box) { const o = orientationOf(box); const f = state.flip[trackKeyOf(box)] || {}; const meta = {}; meta[AXES[o.vIdx]] = { size: '车高', pos: o.upPosIsTop ? '车上' : '车下', neg: o.upPosIsTop ? '车下' : '车上', }; const longFront = f.long ? !o.longPosIsFront : o.longPosIsFront; meta[AXES[o.longIdx]] = { size: '车长', pos: longFront ? '车头' : '车尾', neg: longFront ? '车尾' : '车头', }; const shortLeft = f.short ? !o.shortPosIsLeft : o.shortPosIsLeft; meta[AXES[o.shortIdx]] = { size: '车宽', pos: shortLeft ? '车左' : '车右', neg: shortLeft ? '车右' : '车左', }; return meta; } // anchor 'L' = 保留低端,'R' = 保留高端 const endName = (meta, axis, anchor) => meta[axis][anchor === 'L' ? 'neg' : 'pos']; /* ---------------- 拖拽识别 ---------------- */ function trackStep(key, box) { const cur = snapshotOf(box); const prev = state.lastSeen.get(key); state.lastSeen.set(key, cur); if (!prev) return; const dW = [cur.pos[0] - prev.pos[0], cur.pos[1] - prev.pos[1], cur.pos[2] - prev.pos[2]]; const dL = toLocal(box, dW); let votes = state.votes.get(key); let touched = false; for (let i = 0; i < 3; i++) { const ds = cur.scale[i] - prev.scale[i]; if (Math.abs(ds) < 1e-4) continue; const anchor = judgeEnds(dL[i], ds, endTol(ds)); if (!anchor) continue; if (!votes) votes = { x: 0, y: 0, z: 0 }; votes[AXES[i]] += (anchor === 'R' ? 1 : -1) * Math.abs(ds); touched = true; } if (touched) state.votes.set(key, votes); } function anchorFromVotes(key, axis) { const v = state.votes.get(key)?.[axis] || 0; if (Math.abs(v) < 1e-4) return null; return v > 0 ? 'R' : 'L'; } // 三重降级:端面绝对对照 → 拖拽过程采样 → 本轨迹记忆。两套判据打架时宁可问人。 function anchorFor(key, axis, absAnchor) { const dragAnchor = anchorFromVotes(key, axis); if (absAnchor && dragAnchor && absAnchor !== dragAnchor) { return { anchor: null, conflict: true }; } if (absAnchor) return { anchor: absAnchor, from: 'abs' }; if (dragAnchor) return { anchor: dragAnchor, from: 'drag' }; const remembered = state.memory[trackKeyOf(selectedBox())]; if (remembered) return { anchor: remembered, from: 'memory' }; return { anchor: null }; } function rememberAnchor(trackKey, anchor) { if (!trackKey) return; state.memory[trackKey] = anchor; try { localStorage.setItem(LS.mem, JSON.stringify(state.memory)); } catch {} } /* ---------------- 轮询 ---------------- */ function poll() { try { const frame = currentFrame(); const box = selectedBox(); if (!frame || !box) { refreshPanel(); return; } const key = baseKey(frame, box); if (!state.baseline.has(key)) state.baseline.set(key, snapshotOf(box)); trackStep(key, box); refreshPanel(); } catch (err) { console.warn('[X66] 轮询异常', err); } } function startPolling() { clearInterval(state.pollTimer); state.pollTimer = setInterval(poll, 80); } /* ---------------- 应用 ---------------- */ function applyToBox(tgt, srcBox, ops, useDelta) { const V3 = tgt.position.constructor; let changed = false; for (const op of ops) { const old = tgt.scale[op.axis]; if (!Number.isFinite(old)) continue; const newSize = useDelta ? old + op.ds : srcBox.scale[op.axis]; if (!(newSize > 0) || Math.abs(newSize - old) < EPS) continue; const move = (op.anchor === 'L' ? 1 : -1) * (newSize - old) / 2; const off = new V3(0, 0, 0); off[op.axis] = move; if (tgt.quaternion) off.applyQuaternion(tgt.quaternion); tgt.position.set(tgt.position.x + off.x, tgt.position.y + off.y, tgt.position.z + off.z); tgt.scale[op.axis] = newSize; changed = true; } if (changed) { tgt.updateMatrix?.(); tgt.updateMatrixWorld?.(true); } return changed; } /* ---------------- 准备 ---------------- */ function prepare(type, forcedAnchor) { const e = ed(); if (!e?.state?.frames) return { pass: true }; if (!e.state.loadAll) return { pass: true, why: '全部帧未加载完成' }; if (e.state.config?.frameSuperPosition) return { pass: true, why: '叠帧状态' }; if (e.state.config?.compensationMode) return { pass: true, why: '补偿模式' }; try { if (e.actionManager?.isBlocked?.()) return { pass: true, why: '有操作进行中' }; } catch {} const frame = currentFrame(); const box = selectedBox(); if (!frame || !box) return { pass: true, why: '未单选 3D 框' }; const key = baseKey(frame, box); const snap = state.baseline.get(key); if (!snap) { state.baseline.set(key, snapshotOf(box)); return { pass: true, why: '首次见到该框,已记录基线' }; } const dWabs = [ box.position.x - snap.pos[0], box.position.y - snap.pos[1], box.position.z - snap.pos[2], ]; const dLabs = toLocal(box, dWabs); const ops = []; let conflict = false; for (let i = 0; i < 3; i++) { const ds = box.scale[AXES[i]] - snap.scale[i]; if (Math.abs(ds) < EPS) continue; let anchor; if (forcedAnchor) { anchor = forcedAnchor; } else { const absAnchor = judgeEnds(dLabs[i], ds, endTol(ds)); const decided = anchorFor(key, AXES[i], absAnchor); anchor = decided.anchor; if (decided.conflict) conflict = true; } ops.push({ axis: AXES[i], ds, anchor, known: !!anchor }); } if (!ops.length) return { pass: true, why: '本帧尺寸未变化' }; const unknown = ops.filter(o => !o.known).map(o => o.axis.toUpperCase()); if (unknown.length) { return { pass: true, why: '待确认', needPick: true, conflict, type, key }; } return { pass: false, e, frame, box, key, snap, ops, type, forced: !!forcedAnchor }; } /* ---------------- 执行 ---------------- */ function execute(plan) { const { e, frame: curFrame, box: src, key, snap, ops, type } = plan; const curIndex = e.state.frameIndex; const allFrames = e.state.frames; const targets = type === 'pre' ? allFrames.filter((f, i) => i <= curIndex) : type === 'next' ? allFrames.filter((f, i) => i >= curIndex) : allFrames.slice(); const undo = { srcUuid: src.uuid, srcBaseline: snap, // 执行前的源帧基线,反转时要用它复原 type, anchor: ops[0].anchor, frames: [], }; let done = 0, skipped = 0; const errors = []; for (const frame of targets) { if (frame.id === 'superFrame') continue; const objs = frameObjects(frame.id); if (!Array.isArray(objs)) { skipped++; continue; } const box = objs.find(o => o.uuid === src.uuid && o.type === 'Box3Helper'); if (!box) { skipped++; continue; } if (String(frame.id) === String(curFrame.id)) { done++; continue; } undo.frames.push({ frameId: frame.id, ...snapshotOf(box) }); if (!applyToBox(box, src, ops, state.keepDelta)) continue; try { e.dataManager.updateSaveObject(frame.id, box); done++; } catch (err) { errors.push(String(err?.message || err)); } state.lastSeen.set(baseKey(frame, box), snapshotOf(box)); } state.lastUndo = undo; state.baseline.set(key, snapshotOf(src)); state.lastSeen.set(key, snapshotOf(src)); state.votes.delete(key); try { e.pc?.render?.(); e.updateView?.(); } catch {} try { e.addRecords?.('annotateAction', { key: 'onlyMsg', des: '尺寸覆盖(锚定)' }); } catch {} const meta = axisMeta(src); const keepName = endName(meta, ops[0].axis, ops[0].anchor); const label = type === 'all' ? '全部' : type === 'pre' ? '前帧' : '后帧'; refreshPanel(); if (errors.length) { toast('已覆盖 ' + done + ' 帧,' + errors.length + ' 帧写入失败:' + errors[0], true); } else { toast('尺寸' + label + '覆盖 ' + done + ' 帧 · 保留' + keepName + (skipped ? '\n跳过 ' + skipped + ' 帧' : '')); } } function restoreFrames(u) { const e = ed(); if (!e?.dataManager) return 0; let n = 0; for (const item of u.frames) { const box = frameObjects(item.frameId)?.find(o => o.uuid === u.srcUuid && o.type === 'Box3Helper'); if (!box) continue; box.scale.set(item.scale[0], item.scale[1], item.scale[2]); box.position.set(item.pos[0], item.pos[1], item.pos[2]); box.updateMatrix?.(); try { e.dataManager.updateSaveObject(item.frameId, box); const k = String(item.frameId) + '|' + u.srcUuid; const snap = { scale: item.scale.slice(), pos: item.pos.slice() }; state.baseline.set(k, snap); state.lastSeen.set(k, snap); n++; } catch {} } return n; } function undoLast() { const u = state.lastUndo; if (!u?.frames?.length) { toast('没有可撤销的记录', true); return; } const n = restoreFrames(u); state.lastUndo = null; try { ed()?.pc?.render?.(); ed()?.updateView?.(); } catch {} refreshPanel(); toast('已撤销,还原 ' + n + ' 帧'); } // 反转:先把上次覆盖撤掉、源帧基线复原,再按相反的锚定端重做一次 function reverseLast() { const u = state.lastUndo; if (!u?.srcBaseline) { toast('没有可反转的记录', true); return; } const frame = currentFrame(); const box = selectedBox(); if (!frame || !box || box.uuid !== u.srcUuid) { toast('请先选中同一辆车再反转', true); return; } restoreFrames(u); const key = baseKey(frame, box); state.baseline.set(key, u.srcBaseline); state.lastSeen.set(key, u.srcBaseline); state.votes.clear(); state.lastUndo = null; const plan = prepare(u.type, u.anchor === 'L' ? 'R' : 'L'); if (plan.pass) { toast('反转失败:' + (plan.why || '未知'), true); return; } execute(plan); } function applyWithAnchor(anchor) { // 已经覆盖过一次又改了锚定端 → 先复原再重做 if (state.lastUndo?.srcBaseline) { const u = state.lastUndo; const frame = currentFrame(); const box = selectedBox(); if (frame && box && box.uuid === u.srcUuid) { restoreFrames(u); const key = baseKey(frame, box); state.baseline.set(key, u.srcBaseline); state.lastSeen.set(key, u.srcBaseline); state.votes.clear(); state.lastUndo = null; } } const type = state.pendingType || 'all'; const plan = prepare(type, anchor); if (plan.pass) { toast('没东西可覆盖:' + (plan.why || '未知'), true); return; } try { execute(plan); rememberAnchor(trackKeyOf(plan.box), anchor); state.pendingType = null; refreshPanel(); } catch (err) { console.error('[X66] 执行失败', err); toast('覆盖失败:' + (err?.message || err), true); } } function resetBaseline() { const frame = currentFrame(); const box = selectedBox(); state.baseline.clear(); state.lastSeen.clear(); state.votes.clear(); if (frame && box) { const k = baseKey(frame, box); state.baseline.set(k, snapshotOf(box)); state.lastSeen.set(k, snapshotOf(box)); } refreshPanel(); toast(box ? '基线已重置' : '基线已清除'); } /* ---------------- 拦截平台按钮 ---------------- */ const TYPE_BY_INDEX = ['pre', 'all', 'next']; function onClickCapture(ev) { if (!state.enabled) return; const holder = ev.target?.closest?.('.display-box-size'); if (!holder) return; const iconBox = ev.target.closest('.icon-box'); if (!iconBox) return; const idx = [...holder.querySelectorAll('.icon-box')].indexOf(iconBox); if (idx < 0 || idx > 2) return; let plan; try { plan = prepare(TYPE_BY_INDEX[idx]); } catch (err) { console.warn('[X66] 准备失败,放行原生', err); return; } if (plan.pass) { if (plan.needPick) { ev.preventDefault(); ev.stopPropagation(); ev.stopImmediatePropagation(); state.pendingType = plan.type; openPanel(true); refreshPanel(); toast('判不出该保留哪一端,请在面板上点一下', true); return; } if (plan.why && plan.why !== '未单选 3D 框') console.log('[X66] 放行原生:' + plan.why); return; } ev.preventDefault(); ev.stopPropagation(); ev.stopImmediatePropagation(); try { execute(plan); } catch (err) { console.error('[X66] 执行失败', err); toast('覆盖失败:' + (err?.message || err), true); } } /* ---------------- 面板 ---------------- */ let panelEl, toggleEl; /* ---------------- 拖动 + 位置记忆 ---------------- * 面板和悬浮球都按住就能拖,松手存 localStorage,刷新/下次打开自动回原位。 * 坐标用 left/top(不再用 right/bottom),拖动中与 resize 后都夹在可视区内。 * ------------------------------------------------- */ const posState = { panel: null, toggle: null }; const DEF_TOGGLE = { right: 14, bottom: 150 }; // 与 CSS 默认位一致 const DEF_PANEL = { right: 14, bottom: 186 }; function loadPos() { try { const raw = JSON.parse(localStorage.getItem(LS.pos) || '{}') || {}; for (const k of ['panel', 'toggle']) { const v = raw[k]; if (v && Number.isFinite(v.left) && Number.isFinite(v.top)) posState[k] = { left: v.left, top: v.top }; } } catch {} } function savePos() { try { localStorage.setItem(LS.pos, JSON.stringify(posState)); } catch {} } function clampPos(el, left, top) { const w = el.offsetWidth || 0, h = el.offsetHeight || 0; const maxL = Math.max(0, window.innerWidth - w); const maxT = Math.max(0, window.innerHeight - h); return { left: Math.min(Math.max(0, Math.round(left)), maxL), top: Math.min(Math.max(0, Math.round(top)), maxT), }; } function placeEl(el, left, top) { const p = clampPos(el, left, top); el.style.left = p.left + 'px'; el.style.top = p.top + 'px'; el.style.right = 'auto'; el.style.bottom = 'auto'; return p; } // 没记住过位置 → 按 CSS 原来的右下角默认位算 function defaultPos(el, def) { return { left: window.innerWidth - (el.offsetWidth || 0) - def.right, top: window.innerHeight - (el.offsetHeight || 0) - def.bottom, }; } // 有记忆用记忆,没有用默认;顺便夹回可视区(窗口改小后跑出去会被拉回来) function restorePos(el, key, def) { if (!el || !el.offsetWidth) return; // 还量不到尺寸(面板未展开)就跳过 const p = posState[key] || defaultPos(el, def); const q = placeEl(el, p.left, p.top); if (posState[key]) posState[key] = q; } function makeDraggable(el, handle, key, def) { let down = false, moved = false, sx = 0, sy = 0, ox = 0, oy = 0; const onMove = ev => { if (!down) return; if (ev.buttons === 0) { onUp(); return; } // 在窗口外松手,回来时兜底收尾 const dx = ev.clientX - sx, dy = ev.clientY - sy; if (!moved) { if (Math.abs(dx) < 3 && Math.abs(dy) < 3) return; // 手抖不算拖动,保住单击/双击 moved = true; } placeEl(el, ox + dx, oy + dy); }; const onUp = () => { document.removeEventListener('mousemove', onMove, true); document.removeEventListener('mouseup', onUp, true); if (!down) return; down = false; if (moved) { const r = el.getBoundingClientRect(); posState[key] = clampPos(el, r.left, r.top); savePos(); el.__x66dragEnd = Date.now(); } moved = false; }; handle.addEventListener('mousedown', ev => { if (ev.button !== 0) return; if (ev.target.closest('input,button,select,textarea')) return; // 勾选框/按钮不触发拖动 if (!el.style.left) restorePos(el, key, def); const r = el.getBoundingClientRect(); sx = ev.clientX; sy = ev.clientY; ox = r.left; oy = r.top; down = true; moved = false; ev.preventDefault(); document.addEventListener('mousemove', onMove, true); document.addEventListener('mouseup', onUp, true); }); } function onResize() { restorePos(toggleEl, 'toggle', DEF_TOGGLE); if (panelEl?.dataset.open === '1') restorePos(panelEl, 'panel', DEF_PANEL); } function resetPos() { posState.panel = null; posState.toggle = null; try { localStorage.removeItem(LS.pos); } catch {} restorePos(toggleEl, 'toggle', DEF_TOGGLE); if (panelEl?.dataset.open === '1') restorePos(panelEl, 'panel', DEF_PANEL); toast('面板位置已复位'); } function refreshPanel() { if (!panelEl) return; if (!panelEl.isConnected) { try { document.body.append(panelEl); } catch {} } if (panelEl.dataset.open !== '1') { updateToggleLook(); return; } try { refreshPanelInner(); } catch (err) { console.warn('[X66] 面板刷新异常', err); } } // 当前改动概览:只给标注员看「哪个方位、从多少变到多少」 function changeSummary(box, snap) { const meta = axisMeta(box); const lines = []; let primary = null; for (let i = 0; i < 3; i++) { const ds = box.scale[AXES[i]] - snap.scale[i]; if (Math.abs(ds) < EPS) continue; const m = meta[AXES[i]]; lines.push(m.size + ' ' + snap.scale[i].toFixed(2) + ' → ' + box.scale[AXES[i]].toFixed(2)); if (!primary || Math.abs(ds) > Math.abs(primary.ds)) primary = { axis: AXES[i], ds }; } return { lines, primary, meta }; } function refreshPanelInner() { const frame = currentFrame(); const box = selectedBox(); const infoEl = panelEl.querySelector('.x66-info'); const negBtn = panelEl.querySelector('.x66-keep-neg'); const posBtn = panelEl.querySelector('.x66-keep-pos'); const undoBtn = panelEl.querySelector('.x66-undo'); let summary = null; if (!box) { infoEl.textContent = '未选中框'; } else if (!frame) { infoEl.textContent = '当前帧未就绪'; } else { const snap = state.baseline.get(baseKey(frame, box)); if (!snap) { infoEl.textContent = '就绪'; } else { summary = changeSummary(box, snap); infoEl.textContent = summary.lines.length ? summary.lines.join('\n') : '未改动尺寸'; } } // 按钮文案换成方位词(取改动最大的那根轴) const meta = box ? axisMeta(box) : null; const primaryAxis = summary?.primary?.axis || 'x'; if (meta) { negBtn.textContent = '保留' + meta[primaryAxis].neg; posBtn.textContent = '保留' + meta[primaryAxis].pos; } else { negBtn.textContent = '保留这端'; posBtn.textContent = '保留那端'; } const hasChange = !!summary?.lines.length; const canAct = hasChange || !!state.pendingType || !!state.lastUndo; negBtn.disabled = !canAct; posBtn.disabled = !canAct; undoBtn.disabled = !state.lastUndo; updateToggleLook(); } function buildPanel() { loadPos(); const style = document.createElement('style'); style.textContent = ` .x66-toggle{position:fixed;right:14px;bottom:150px;z-index:2147483646;font:12px system-ui,sans-serif; padding:5px 10px;border-radius:6px;background:#1d4ed8;color:#fff;cursor:pointer;user-select:none; box-shadow:0 2px 10px #0005;border:1px solid #3b82f6} .x66-toggle.x66-off{background:#475569;border-color:#64748b} .x66-toggle.x66-alert{background:#b45309;border-color:#f59e0b} .x66-panel{position:fixed;right:14px;bottom:186px;z-index:2147483646;width:228px; background:#181f2b;color:#e8edf5;border:1px solid #3a4a62;border-radius:10px;padding:11px; font:12px/1.6 system-ui,sans-serif;box-shadow:0 8px 28px #0007;display:none} .x66-panel[data-open="1"]{display:block} .x66-panel .x66-head{display:flex;align-items:center;gap:6px; margin:0 0 8px;font-size:12.5px;font-weight:500;color:#cbd6e6; cursor:move;user-select:none} .x66-panel .x66-grip{color:#64748b;font-size:12px;letter-spacing:-1px;flex:none} .x66-panel .x66-title{flex:1;cursor:move} .x66-panel .x66-head input{margin:0;cursor:pointer;flex:none} .x66-panel .x66-info{padding:7px 9px;background:#202a39;border:1px solid #354155;border-radius:6px; white-space:pre-wrap;color:#bfe0ff;font-family:ui-monospace,monospace;font-size:11.5px;line-height:1.7} .x66-panel .x66-row{display:flex;gap:6px;margin-top:7px} .x66-panel button{flex:1;padding:6px 8px;border-radius:5px;border:1px solid #435570;background:#29374b; color:inherit;font:inherit;cursor:pointer} .x66-panel button:hover:not(:disabled){background:#374c68} .x66-panel button.x66-keep{border-color:#3b82f6;background:#1e3a8a} .x66-panel button.x66-keep:hover:not(:disabled){background:#24479f} .x66-panel button:disabled{opacity:.4;cursor:default} `; document.head.append(style); toggleEl = document.createElement('div'); toggleEl.className = 'x66-toggle'; panelEl = document.createElement('div'); panelEl.className = 'x66-panel'; panelEl.dataset.open = '0'; panelEl.innerHTML = `