/** * box3d.js — Three.js 盒子 3D 渲染(多实例工厂版) * - 从刀版 panels 自动构建铰链折叠 * - 外侧 / 内侧独立贴图 * - 10 种动效(折叠展开 / 自转 / 掉落 / 由远到近……) * - 重置视角、2K/3K/4K 高清截图、透明背景 */ (function () { const THREE = window.THREE; if (!THREE) return; function fontStack(key) { const fonts = window.PL && window.PL.data && window.PL.data.fonts; return (fonts && fonts[key] && fonts[key].stack) || '"PingFang SC", "Helvetica Neue", sans-serif'; } function panelBox(p) { if (p.poly) { const xs = p.poly.map(function (pt) { return pt[0]; }); const ys = p.poly.map(function (pt) { return pt[1]; }); const x = Math.min.apply(null, xs); const y = Math.min.apply(null, ys); return { x: x, y: y, w: Math.max.apply(null, xs) - x, h: Math.max.apply(null, ys) - y }; } return { x: p.x, y: p.y, w: p.w, h: p.h }; } function boxCenter(b) { return { x: b.x + b.w / 2, y: b.y + b.h / 2 }; } function planeGeometry(b, poly, holes) { if (!poly && (!holes || !holes.length)) return new THREE.PlaneGeometry(b.w, b.h); const shape = new THREE.Shape(); if (poly) { poly.forEach(function (pt, i) { const x = pt[0] - b.x - b.w / 2; const y = -(pt[1] - b.y - b.h / 2); if (i === 0) shape.moveTo(x, y); else shape.lineTo(x, y); }); shape.closePath(); } else { shape.moveTo(-b.w / 2, -b.h / 2); shape.lineTo(b.w / 2, -b.h / 2); shape.lineTo(b.w / 2, b.h / 2); shape.lineTo(-b.w / 2, b.h / 2); shape.closePath(); } (holes || []).forEach(function (ho) { const path = new THREE.Path(); path.absarc(ho.x - b.x - b.w / 2, -(ho.y - b.y - b.h / 2), ho.r, 0, Math.PI * 2, true); shape.holes.push(path); }); const geom = new THREE.ShapeGeometry(shape); const pos = geom.attributes.position; const uv = geom.attributes.uv; for (let i = 0; i < pos.count; i += 1) { uv.setXY(i, (pos.getX(i) + b.w / 2) / Math.max(0.001, b.w), (pos.getY(i) + b.h / 2) / Math.max(0.001, b.h)); } uv.needsUpdate = true; return geom; } // 卡牌等刚性面:在贴图平面上按刀版孔位真实开孔(局部坐标,y 向上) function rigidPlaneGeometry(w, h, holes) { if (!holes || !holes.length) return new THREE.PlaneGeometry(w, h); const shape = new THREE.Shape(); shape.moveTo(-w / 2, -h / 2); shape.lineTo(w / 2, -h / 2); shape.lineTo(w / 2, h / 2); shape.lineTo(-w / 2, h / 2); shape.closePath(); holes.forEach(function (ho) { const path = new THREE.Path(); path.absarc(ho.x, ho.y, ho.r, 0, Math.PI * 2, true); shape.holes.push(path); }); const geom = new THREE.ShapeGeometry(shape); const pos = geom.attributes.position; const uv = geom.attributes.uv; for (let i = 0; i < pos.count; i += 1) { uv.setXY(i, (pos.getX(i) + w / 2) / Math.max(0.001, w), (pos.getY(i) + h / 2) / Math.max(0.001, h)); } uv.needsUpdate = true; return geom; } const FOLD_PARTS = { carton: 1, rsc: 1, mailbox: 1, tuck: 1, straight: 1, autobottom: 1, mailer: 1, drawer: 1, bag: 1, sleeve: 1 }; function panelLayer(p) { if (p.kind === 'glue') return -0.6; if (p.kind === 'lip') return -0.9; if (p.kind === 'dust') return -0.35; if (p.kind === 'tuck') return -0.28; if (p.kind === 'flap') return -0.12; return 0; } function isBodyKind(k) { return !(k === 'glue' || k === 'flap' || k === 'dust' || k === 'tuck' || k === 'lip'); } function canHinge(a, b) { const ka = a.kind || 'body'; const kb = b.kind || 'body'; if (isBodyKind(ka) !== isBodyKind(kb)) return true; if (isBodyKind(ka) && isBodyKind(kb)) return true; return (ka === 'tuck' && kb === 'flap') || (ka === 'flap' && kb === 'tuck'); } function panelEdges(p) { const b = panelBox(p); const pts = p.poly || [[b.x, b.y], [b.x + b.w, b.y], [b.x + b.w, b.y + b.h], [b.x, b.y + b.h]]; const out = []; for (let i = 0; i < pts.length; i += 1) { const a = pts[i]; const c = pts[(i + 1) % pts.length]; if (Math.abs(a[0] - c[0]) < 0.05) out.push({ axis: 'v', c: a[0], lo: Math.min(a[1], c[1]), hi: Math.max(a[1], c[1]) }); else if (Math.abs(a[1] - c[1]) < 0.05) out.push({ axis: 'h', c: a[1], lo: Math.min(a[0], c[0]), hi: Math.max(a[0], c[0]) }); } return out; } function sharedEdge(a, b) { let best = null; panelEdges(a).forEach(function (ea) { panelEdges(b).forEach(function (eb) { if (ea.axis !== eb.axis || Math.abs(ea.c - eb.c) > 0.6) return; const lo = Math.max(ea.lo, eb.lo); const hi = Math.min(ea.hi, eb.hi); const len = hi - lo; if (len <= 2) return; if (!best || len > best.len) best = { axis: ea.axis, c: ea.c, lo: lo, hi: hi, len: len }; }); }); return best; } function buildAdjacency(panels, boxes) { const adj = panels.map(function () { return []; }); for (let i = 0; i < panels.length; i += 1) { for (let j = i + 1; j < panels.length; j += 1) { if (!canHinge(panels[i], panels[j])) continue; const edge = sharedEdge(panels[i], panels[j]); if (!edge) continue; const ca = boxCenter(boxes[i]); const cb = boxCenter(boxes[j]); let n; if (edge.axis === 'v') n = { x: cb.x >= ca.x ? 1 : -1, y: 0 }; else n = { x: 0, y: cb.y >= ca.y ? 1 : -1 }; const mk = function (s) { return edge.axis === 'v' ? { axis: 'v', x: edge.c, y0: edge.lo, y1: edge.hi, n: { x: n.x * s, y: n.y * s } } : { axis: 'h', x0: edge.lo, x1: edge.hi, y: edge.c, n: { x: n.x * s, y: n.y * s } }; }; adj[i].push({ j: j, edge: mk(1), overlap: edge.len }); adj[j].push({ j: i, edge: mk(-1), overlap: edge.len }); } } return adj; } function hingePoint(edge) { if (edge.axis === 'v') return { x: edge.x, y: (edge.y0 + edge.y1) / 2 }; return { x: (edge.x0 + edge.x1) / 2, y: edge.y }; } function rootIndexFor(indices, panels, boxes, prefer) { let best = -1, bestScore = -Infinity; indices.forEach(function (idx) { const b = boxes[idx]; const face = panels[idx].face; const score = (face === prefer ? 1e9 : 0) + (face ? 1e6 : 0) + b.w * b.h; if (score > bestScore) { bestScore = score; best = idx; } }); return best; } /* ================= 实例工厂 ================= */ function create(el, opts) { opts = opts || {}; let renderer = null, scene = null, camera = null, root = null, canvas = null; let meshes = [], hinges = [], components = []; const orbit = { theta: -0.55, phi: 1.08, zoom: 1 }; const orbitHome = { theta: -0.55, phi: 1.08, zoom: 1 }; let autoRotate = false; let onFacePick = opts.onFacePick || null; let drag = null, moved = false, raf = null; let foldT = 0; let showLines = true; let state = null, material = null; let disposeFns = []; renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true }); renderer.setPixelRatio(opts.mini ? 1 : Math.min(window.devicePixelRatio || 1, 2)); renderer.outputEncoding = THREE.sRGBEncoding; renderer.setClearColor(0x000000, 0); canvas = renderer.domElement; canvas.className = 'box3d-canvas'; canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;display:block;z-index:2;touch-action:none;cursor:grab;'; el.appendChild(canvas); el.classList.add('three-active'); scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(32, 1, 1, 60000); scene.add(new THREE.AmbientLight(0xffffff, 0.82)); const key = new THREE.DirectionalLight(0xffffff, 0.8); key.position.set(-350, 600, 800); scene.add(key); const fill = new THREE.DirectionalLight(0xffffff, 0.34); fill.position.set(600, -260, -500); scene.add(fill); const rim = new THREE.DirectionalLight(0xffffff, 0.22); rim.position.set(-500, -200, -700); scene.add(rim); function resize() { const w = Math.max(1, el.clientWidth); const hh = Math.max(1, el.clientHeight); renderer.setSize(w, hh, false); camera.aspect = w / hh; camera.updateProjectionMatrix(); } resize(); if (window.ResizeObserver) { const ro = new ResizeObserver(resize); ro.observe(el); disposeFns.push(function () { ro.disconnect(); }); } /* ---- 贴图 ---- */ function drawFaceArt(ctx, cw, ch, data, px2mm) { const items = (data && data.items) || []; items.forEach(function (it) { if (it.hidden) return; if (it.type === 'text') { const px = it.size * px2mm; const lines = String(it.text || '').split('\n'); const lh = (it.lineHeight || 1.25) * px; ctx.save(); ctx.fillStyle = it.color || '#17140f'; ctx.textAlign = it.align === 'center' ? 'center' : it.align === 'right' ? 'right' : 'left'; ctx.textBaseline = 'middle'; ctx.font = (it.italic ? 'italic ' : '') + (it.weight || 400) + ' ' + px + 'px ' + fontStack(it.font); const x = (it.x / 100) * cw; const y = (it.y / 100) * ch; lines.forEach(function (line, i) { ctx.fillText(line, x, y + (i - (lines.length - 1) / 2) * lh); }); ctx.restore(); } else if ((it.type === 'image' || it.type === 'asset') && it.src) { const img = getCachedImage(it.src, function () { refreshTextures(); }); if (img) { const iw = ((it.w == null ? 70 : it.w) / 100) * cw; const ix = ((it.x == null ? 50 : it.x) / 100) * cw; const iy = ((it.y == null ? 50 : it.y) / 100) * ch; try { ctx.drawImage(img, ix - iw / 2, iy - (iw * (img.height / Math.max(1, img.width))) / 2, iw, iw * (img.height / Math.max(1, img.width))); } catch (e) {} } } else if (it.type === 'barcode' && it.src) { const img = getCachedImage(it.src, function () { refreshTextures(); }); if (img) { const iw = ((it.w || 40) / 100) * cw; const ix = (it.x / 100) * cw; const iy = (it.y / 100) * ch; try { ctx.drawImage(img, ix - iw / 2, iy - iw * 0.42, iw, iw * 0.84); } catch (e) {} } } }); // 兼容旧数据 (data && data.texts || []).forEach(function (t) { const px = t.size * px2mm; const lines = String(t.text || '').split('\n'); const lh = (t.lineHeight || 1.25) * px; ctx.save(); ctx.fillStyle = t.color || '#17140f'; ctx.textAlign = t.align === 'center' ? 'center' : t.align === 'right' ? 'right' : 'left'; ctx.textBaseline = 'middle'; ctx.font = (t.italic ? 'italic ' : '') + (t.weight || 400) + ' ' + px + 'px ' + fontStack(t.font); const x = (t.x / 100) * cw; const y = (t.y / 100) * ch; lines.forEach(function (line, i) { ctx.fillText(line, x, y + (i - (lines.length - 1) / 2) * lh); }); ctx.restore(); }); } /* ---- 面纹理缓存:几何不变时仅重绘画布内容(needsUpdate),避免整场景重建 ---- */ const faceTexCache = {}; // side|face -> { canvas, ctx, texture, cw, ch } const imgCache = new Map(); // src -> HTMLImageElement(避免重复解码) function getCachedImage(src, onReady) { if (imgCache.has(src)) { const img = imgCache.get(src); if (img.complete && img.naturalWidth) return img; return null; } const img = new Image(); img.onload = function () { if (onReady) onReady(); }; img.src = src; imgCache.set(src, img); return null; } function drawFaceTo(entry, face, fillOnly) { const sideData = (state.faces[state.side || 'outer'] || {}); const data = sideData[face] || {}; const ctx = entry.ctx; const cw = entry.cw, ch = entry.ch; const size = { w: entry.sizeW, h: entry.sizeH }; ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = data.color || material.paper || '#fbf7ee'; ctx.fillRect(0, 0, cw, ch); if (data.texture) { const tex = getCachedImage(data.texture, function () { refreshTextures(); }); if (tex) { const scale = Math.max(cw / 220, ch / 220); for (let tx = 0; tx < cw; tx += 220 * scale) for (let ty = 0; ty < ch; ty += 220 * scale) { ctx.drawImage(tex, tx, ty, 220 * scale, 220 * scale); } } } // 结构副面(如扣底/平口箱的补位摇盖)只刷底色与纹理,不重复印图案 if (!fillOnly) drawFaceArt(ctx, cw, ch, data, cw / Math.max(1, size.w)); } function getFaceTexture(face, size, fillOnly) { const key = (state.side || 'outer') + '|' + face + (fillOnly ? '|fill' : ''); let entry = faceTexCache[key]; if (!entry) { const cw = opts.mini ? 360 : 760; const ch = Math.max(160, Math.round(cw * size.h / Math.max(1, size.w))); const c = document.createElement('canvas'); c.width = cw; c.height = ch; const texture = new THREE.CanvasTexture(c); texture.encoding = THREE.sRGBEncoding; texture.anisotropy = renderer.capabilities.getMaxAnisotropy(); entry = { canvas: c, ctx: c.getContext('2d'), texture: texture, cw: cw, ch: ch, sizeW: size.w, sizeH: size.h }; faceTexCache[key] = entry; } return entry; } function refreshTextures() { const prefix = (state.side || 'outer') + '|'; // 清理另一侧的缓存(内外侧切换后不再使用) Object.keys(faceTexCache).forEach(function (k) { if (k.indexOf(prefix) !== 0) { faceTexCache[k].texture.dispose(); delete faceTexCache[k]; } }); meshes.forEach(function (mesh) { const face = mesh.userData.face || mesh.userData.paint; if (!face || !mesh.material) return; const entry = getFaceTexture(face, mesh.userData.faceSize || { w: 1, h: 1 }, mesh.userData.fillOnly); drawFaceTo(entry, face, mesh.userData.fillOnly); entry.texture.needsUpdate = true; if (mesh.material.map !== entry.texture) { mesh.material.map = entry.texture; mesh.material.needsUpdate = true; } }); } function makeMaterial(face, size, inner, fillOnly) { const entry = getFaceTexture(face, size, fillOnly); drawFaceTo(entry, face, fillOnly); entry.texture.needsUpdate = true; return new THREE.MeshStandardMaterial({ map: entry.texture, color: 0xffffff, roughness: 0.8, metalness: 0.02, side: THREE.DoubleSide }); } function cardboardMaterial() { const sideData = (state.faces[state.side || 'outer'] || {}); const plain = sideData._plain || {}; return new THREE.MeshStandardMaterial({ color: new THREE.Color(plain.color || material.paper || '#fbf7ee'), roughness: 0.86, metalness: 0.02, side: THREE.DoubleSide }); } function makePanelMesh(p, box) { const geom = planeGeometry(box, p.poly, p.holes); const face = p.face || p.paint || null; const fillOnly = !p.face && !!p.paint; const mat = face ? makeMaterial(face, { w: box.w, h: box.h }, state.side === 'inner', fillOnly) : cardboardMaterial(); const mesh = new THREE.Mesh(geom, mat); mesh.position.z = panelLayer(p); mesh.userData.face = p.face || null; mesh.userData.paint = p.paint || null; mesh.userData.fillOnly = fillOnly; mesh.userData.faceSize = face ? { w: box.w, h: box.h } : null; mesh.add(new THREE.LineSegments( new THREE.EdgesGeometry(geom), new THREE.LineBasicMaterial({ color: 0x17140f, transparent: true, opacity: 0.24 }) )); meshes.push(mesh); return mesh; } function clearRoot() { if (root) { root.traverse(function (o) { if (o.geometry) o.geometry.dispose(); if (o.material) o.material.dispose(); }); scene.remove(root); } // 纹理缓存随几何一起释放(key 含 side,重建后按需重建) Object.keys(faceTexCache).forEach(function (k) { faceTexCache[k].texture.dispose(); delete faceTexCache[k]; }); root = new THREE.Group(); scene.add(root); meshes = []; hinges = []; components = []; } function buildComponent(indices, panels, boxes, adj, prefer) { const start = rootIndexFor(indices, panels, boxes, prefer); if (start < 0) return null; const comp = new THREE.Group(); const rootGroup = new THREE.Group(); comp.add(rootGroup); const rootBox = boxes[start]; const rootMesh = makePanelMesh(panels[start], rootBox); rootMesh.userData.kind = panels[start].kind; rootGroup.add(rootMesh); const infos = new Map(); infos.set(start, { group: rootGroup, origin: boxCenter(rootBox) }); const visited = new Set([start]); const best = new Map(); const addLinks = function (pi) { adj[pi].forEach(function (link) { if (visited.has(link.j)) return; const cur = best.get(link.j); if (!cur || link.overlap > cur.overlap) best.set(link.j, { from: pi, link: link }); }); }; addLinks(start); while (visited.size < indices.length) { let pick = -1, pickW = -1; best.forEach(function (v, k) { if (visited.has(k)) return; if (v.link.overlap > pickW) { pickW = v.link.overlap; pick = k; } }); if (pick < 0) break; const chosen = best.get(pick); const parent = infos.get(chosen.from); const link = chosen.link; const hinge = hingePoint(link.edge); const cb = boxes[pick]; const pivot = new THREE.Group(); pivot.position.set(hinge.x - parent.origin.x, -(hinge.y - parent.origin.y), 0); const n3 = new THREE.Vector3(link.edge.n.x, -link.edge.n.y, 0); if (n3.lengthSq() < 0.5) n3.set(0, 1, 0); n3.normalize(); const axis = new THREE.Vector3(0, 0, 1).cross(n3).normalize(); pivot.userData.axis = axis; pivot.userData.angle = Math.PI / 2; hinges.push(pivot); parent.group.add(pivot); const cc = boxCenter(cb); const mesh = makePanelMesh(panels[pick], cb); mesh.position.x = cc.x - hinge.x; mesh.position.y = -(cc.y - hinge.y); mesh.userData.kind = panels[pick].kind; pivot.add(mesh); infos.set(pick, { group: pivot, origin: hinge }); visited.add(pick); best.delete(pick); addLinks(pick); } return { group: comp, root: start }; } function buildFromDieline(panels) { const boxes = panels.map(panelBox); const adj = buildAdjacency(panels, boxes); const seen = new Set(); const groups = []; for (let i = 0; i < panels.length; i += 1) { if (seen.has(i)) continue; const stack = [i]; const indices = []; seen.add(i); while (stack.length) { const cur = stack.pop(); indices.push(cur); adj[cur].forEach(function (link) { if (seen.has(link.j)) return; seen.add(link.j); stack.push(link.j); }); } groups.push(indices); } const prefer = 'front'; const built = []; groups.forEach(function (indices) { const comp = buildComponent(indices, panels, boxes, adj, prefer); if (comp) built.push(comp); }); if (!built.length) return false; const main = built[0]; const mainOrigin = boxCenter(boxes[main.root]); built.forEach(function (c) { const center = boxCenter(boxes[c.root]); c.home = new THREE.Vector3(center.x - mainOrigin.x, -(center.y - mainOrigin.y), 0); c.assembled = new THREE.Vector3(0, 0, 0); c.assembledScale = 1; c.isMain = c === main; if (!c.isMain) { c.assembled.set(0, 0, -2); c.assembledScale = 0.94; } c.group.position.copy(c.home); root.add(c.group); components.push(c); }); root.userData.mainOrigin = { x: mainOrigin.x, y: mainOrigin.y }; return true; } function buildRigid(panels) { const t = material.thickness || 0; const W = state.w + t * 2; // 卡牌为单张纸片,厚度取材质厚度,不沿用盒体的深度 const D = state.structure === 'card' ? t * 2 : state.d + t * 2; const H = state.h + t * 2; const inner = state.side === 'inner'; // 卡牌刀版在正面定义挂孔,3D 正反面同步开孔 const cardFront = (panels || []).find(function (p) { return p.face === 'front' && p.holes && p.holes.length; }); const cardBox = cardFront ? panelBox(cardFront) : null; const defs = [ { face: 'front', w: W, h: H, pos: [0, 0, D / 2], rot: [0, 0, 0] }, { face: 'back', w: W, h: H, pos: [0, 0, -D / 2], rot: [0, Math.PI, 0] }, { face: 'right', w: D, h: H, pos: [W / 2, 0, 0], rot: [0, Math.PI / 2, 0] }, { face: 'left', w: D, h: H, pos: [-W / 2, 0, 0], rot: [0, -Math.PI / 2, 0] }, { face: 'top', w: W, h: D, pos: [0, H / 2, 0], rot: [-Math.PI / 2, 0, 0] }, { face: 'bottom', w: W, h: D, pos: [0, -H / 2, 0], rot: [Math.PI / 2, 0, 0] } ]; defs.forEach(function (def) { const holes = cardBox && (def.face === 'front' || def.face === 'back') ? cardFront.holes.map(function (ho) { return { x: ho.x - (cardBox.x + cardBox.w / 2), y: def.h / 2 - (ho.y - cardBox.y), r: ho.r }; }) : null; const geom = rigidPlaneGeometry(def.w, def.h, holes); const mat = makeMaterial(def.face, { w: def.w, h: def.h }, inner); const mesh = new THREE.Mesh(geom, mat); mesh.position.set(def.pos[0], def.pos[1], def.pos[2]); mesh.rotation.set(def.rot[0], def.rot[1], def.rot[2]); mesh.userData.face = def.face; mesh.userData.faceSize = { w: def.w, h: def.h }; root.add(mesh); meshes.push(mesh); mesh.add(new THREE.LineSegments( new THREE.EdgesGeometry(geom), new THREE.LineBasicMaterial({ color: 0x17140f, transparent: true, opacity: 0.22 }) )); }); } /* ---- 动效引擎 ---- */ const anim = { id: null, t0: 0, dur: 0, onEnd: null }; const animState = { theta: 0, phi: 0, zoom: 1, dx: 0, dy: 0, dz: 0, fold: null }; const EASE = { io: function (t) { return t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2; }, out: function (t) { return 1 - Math.pow(1 - t, 3); }, bounce: function (t) { const n1 = 7.5625, d1 = 2.75; if (t < 1 / d1) return n1 * t * t; if (t < 2 / d1) return n1 * (t -= 1.5 / d1) * t + 0.75; if (t < 2.5 / d1) return n1 * (t -= 2.25 / d1) * t + 0.9375; return n1 * (t -= 2.625 / d1) * t + 0.984375; } }; const ANIM_TICKS = { fold: function (p) { animState.fold = p < 0.5 ? EASE.io(p * 2) : 1 - EASE.io((p - 0.5) * 2); }, spinFlat: function (p) { animState.phi = 0.18; animState.theta = EASE.io(p) * Math.PI * 2; }, spinTop: function (p) { animState.phi = -1.05; animState.theta = EASE.io(p) * Math.PI * 2; }, dropSpin: function (p) { const k = EASE.out(Math.min(1, p / 0.55)); animState.dy = (1 - k) * 260; animState.theta = (1 - k) * Math.PI * 2.2; animState.dz = (1 - k) * -80; }, zoomIn: function (p) { animState.zoom = 0.35 + EASE.io(p) * 0.75; animState.phi = 0.12; }, dropZoom: function (p) { if (p < 0.375) { const k = EASE.out(p / 0.375); animState.dy = (1 - k) * 300; animState.theta = (1 - k) * Math.PI * 2.4; } else { const k = EASE.io((p - 0.375) / 0.625); animState.zoom = 1 + k * 1.1; animState.phi = 0.1 + k * 0.2; } }, zoomDetail: function (p) { animState.zoom = 0.4 + EASE.io(p) * 1.2; animState.theta = -0.3 * (1 - p); animState.phi = 0.25 - p * 0.12; }, fromLeft: function (p) { const k = EASE.out(p); animState.dx = (1 - k) * -220; animState.theta = (1 - k) * -Math.PI * 1.5; animState.phi = 0.3; }, curveIn: function (p) { const k = EASE.io(p); animState.dz = (1 - k) * -400; animState.dx = Math.sin(p * Math.PI) * -120 * (1 - p); animState.dy = Math.sin(p * Math.PI) * 90; animState.theta = (1 - k) * -0.9; }, foldBounce: function (p) { animState.fold = EASE.io(Math.min(1, p / 0.7)); if (p > 0.7) animState.dy = -(1 - EASE.bounce((p - 0.7) / 0.3)) * 14; } }; function tickAnim(now) { if (!anim.id) return false; const p = Math.min(1, (now - anim.t0) / (anim.dur * 1000)); Object.assign(animState, { theta: 0, phi: 0, zoom: 1, dx: 0, dy: 0, dz: 0, fold: null }); if (anim.custom) anim.custom(p); else ANIM_TICKS[anim.id](p); if (p >= 1) { const end = anim.onEnd; const wasCustom = anim.custom; anim.id = null; anim.custom = null; if (wasCustom) stopAudioHeart(); if (end) end(); } return true; } function applyCamera() { if (!camera || !root) return; root.updateMatrixWorld(true); const bbox = new THREE.Box3().setFromObject(root); if (bbox.isEmpty()) return; const center = bbox.getCenter(new THREE.Vector3()); const size = bbox.getSize(new THREE.Vector3()); const maxDim = Math.max(size.x, size.y, size.z, 1); const zoom = orbit.zoom * animState.zoom; const r = maxDim * 2.85 / Math.max(0.3, zoom); const phi = Math.max(0.15, Math.min(Math.PI - 0.15, orbit.phi + animState.phi)); const theta = orbit.theta + animState.theta; const x = r * Math.sin(phi) * Math.sin(theta); const y = r * Math.cos(phi); const z = r * Math.sin(phi) * Math.cos(theta); camera.position.set(center.x + x + animState.dx, center.y + y + animState.dy, center.z + z + animState.dz); camera.lookAt(center.x + animState.dx * 0.2, center.y - maxDim * (opts.mini ? 0.02 : 0.05), center.z); } function applyFold(t) { foldT = Math.max(0, Math.min(1, Number(t) || 0)); hinges.forEach(function (g) { g.setRotationFromAxisAngle(g.userData.axis, g.userData.angle * (1 - foldT)); }); // 盒体闭合时插舌应插入盒内,简化折纸模型无法表达穿插,直接隐藏 const showTuck = foldT > 0.35; meshes.forEach(function (m) { if (m.userData.kind === 'tuck') m.visible = showTuck; }); components.forEach(function (c) { if (c.isMain) return; c.group.position.lerpVectors(c.assembled, c.home, foldT); const s = c.assembledScale + (1 - c.assembledScale) * foldT; c.group.scale.set(s, s, s); }); } function applyLines() { if (!root) return; root.traverse(function (o) { if (o.isLineSegments) o.visible = showLines; }); } /* ---- 交互 ---- */ function bindPointer() { canvas.addEventListener('pointerdown', function (e) { if (e.button !== 0) return; if (opts.mini && opts.onInteract) opts.onInteract(); // 按下即接管(停掉 CSS 自动播放) drag = { x: e.clientX, y: e.clientY, theta: orbit.theta, phi: orbit.phi }; moved = false; canvas.style.cursor = 'grabbing'; canvas.setPointerCapture(e.pointerId); }); canvas.addEventListener('pointermove', function (e) { if (!drag) return; const dx = e.clientX - drag.x; const dy = e.clientY - drag.y; if (Math.abs(dx) + Math.abs(dy) > 3) moved = true; orbit.theta = drag.theta - dx * 0.008; orbit.phi = Math.max(0.25, Math.min(Math.PI - 0.25, drag.phi - dy * 0.006)); if (opts.mini && autoRotate && moved && opts.onInteract) { autoRotate = false; opts.onInteract(); } applyCamera(); flush(); // 交互即时渲染:拖拽旋转不依赖 rAF 节奏 }); canvas.addEventListener('pointerup', function (e) { if (!drag) return; const wasMoved = moved; drag = null; canvas.style.cursor = 'grab'; try { canvas.releasePointerCapture(e.pointerId); } catch (err) {} if (wasMoved || !onFacePick) return; const rect = canvas.getBoundingClientRect(); const px = ((e.clientX - rect.left) / rect.width) * 2 - 1; const py = -((e.clientY - rect.top) / rect.height) * 2 + 1; const rc = new THREE.Raycaster(); rc.setFromCamera(new THREE.Vector2(px, py), camera); const hits = rc.intersectObjects(meshes, false); if (hits.length && hits[0].object.userData.face) onFacePick(hits[0].object.userData.face); }); canvas.addEventListener('pointercancel', function () { drag = null; canvas.style.cursor = 'grab'; }); canvas.addEventListener('wheel', function (e) { e.preventDefault(); e.stopPropagation(); orbit.zoom = Math.max(0.4, Math.min(3.2, orbit.zoom * (e.deltaY > 0 ? 0.92 : 1.08))); applyCamera(); flush(); }, { passive: false }); } bindPointer(); let lastFrameAt = performance.now(); // 虚拟时钟:页面时钟可能被节流冻结(rAF 停、setInterval 降频、performance.now 冻结), // 由 Web Worker 心跳(Worker 定时器不受页面可见性节流)持续推进,保证自动播放匀速循环。 let vNow = performance.now(); let lastVTick = vNow; const AUTO_SPEED = 0.28; // 约 22 秒一圈 function tickCore() { const dt = Math.min(0.12, Math.max(0, vNow - lastVTick)) / 1000; lastVTick = vNow; try { const hasAnim = tickAnim(vNow); if (!anim.id && audioDriving) stopAudioHeart(); if (autoRotate && !anim.id) orbit.theta += AUTO_SPEED * dt; if (animState.fold != null) applyFold(animState.fold); applyCamera(); if (renderer && scene && camera) renderer.render(scene, camera); } catch (e) { // 单帧异常不终止渲染循环 } } let framesSinceRaf = 0; // worker 心跳消息计数,rAF 有效帧清零 let lastRafNow = 0; /* 音频线程心跳:AudioContext 回调独立于页面渲染节流,动画播放期提供 ~46fps 稳定帧 */ let audioCtx = null, audioNode = null, audioDriving = false, lastAudioT = null; function startAudioHeart() { try { const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; if (!audioCtx) { audioCtx = new AC(); audioNode = audioCtx.createScriptProcessor(2048, 1, 1); audioNode.onaudioprocess = function () { if (!audioDriving || !anim.id) return; // 用音频硬件时钟精确推进(单调、不受页面渲染节流影响) const t = audioCtx.currentTime; if (lastAudioT != null) vNow += Math.max(0, Math.min(200, (t - lastAudioT) * 1000)); lastAudioT = t; tickCore(); }; const gain = audioCtx.createGain(); gain.gain.value = 0; // 完全静音,仅用心跳 audioNode.connect(gain); gain.connect(audioCtx.destination); } lastAudioT = null; // 同步判定当前状态;suspended 时异步 resume,成功后回调自动生效 audioDriving = audioCtx.state === 'running'; if (audioCtx.state === 'suspended') { audioCtx.resume().then(function () { audioDriving = audioCtx.state === 'running'; }).catch(function () { audioDriving = false; }); } } catch (e) { audioDriving = false; } } function stopAudioHeart() { audioDriving = false; lastAudioT = null; } let lastWall = Date.now(); function animate() { raf = requestAnimationFrame(animate); const now = performance.now(); const rafDt = lastRafNow ? now - lastRafNow : 16.7; lastRafNow = now; const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id; // 虚拟时钟推进源互斥:动画音频心跳运行时由音频帧推进,rAF 帧仅重渲染 if (audioActive) { framesSinceRaf = 0; try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {} return; } // 墙钟流逝(Date.now 不受渲染节流冻结影响):空闲期掉帧也能补齐进度 const wallNow = Date.now(); const wallDt = Math.min(5000, Math.max(0, wallNow - lastWall)); lastWall = wallNow; let step; if (rafDt >= 1 && rafDt < 100) step = rafDt; // rAF 时钟正常:按帧间隔 else if (wallDt > 0) step = wallDt; // 渲染被节流:按墙钟补齐真实流逝 else step = 16.7; // 兜底 vNow += step; framesSinceRaf = 0; tickCore(); } // 心跳自愈:rAF 停止(页面不可见/被节流)时由 Worker 定时器以 12fps 兜底驱动。 // 判据用消息计数而非页面时钟——节流环境下页面 performance.now 可能冻结。 try { const heartCode = 'setInterval(function(){postMessage(1)},83);'; const heartUrl = URL.createObjectURL(new Blob([heartCode], { type: 'application/javascript' })); const heart = new Worker(heartUrl); heart.onmessage = function () { framesSinceRaf += 1; const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id; // rAF 停止时由 worker 帧接管;音频心跳实际运行时让位(避免双重计时) if ((framesSinceRaf > 3 || anim.id) && !audioActive) { vNow += 83; tickCore(); } }; if (typeof window !== 'undefined') window.__workerOk = (window.__workerOk || 0) + 1; } catch (e) { if (typeof window !== 'undefined') window.__workerFail = (window.__workerFail || 0) + 1; setInterval(function () { framesSinceRaf += 1; const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id; if ((framesSinceRaf > 3 || anim.id) && !audioActive) { vNow += 83; tickCore(); } }, 84); } /* ---- 对外 API ---- */ let lastGeomSig = ''; function render(nextState, nextMaterial, panels) { resize(); state = nextState; material = nextMaterial; // 结构签名:盒型/尺寸/内外侧/面数/孔位变化才重建几何;否则仅刷新面纹理(增量,避免卡顿) const holeSig = (panels || []).map(function (p) { return (p.holes || []).map(function (h) { return h.x.toFixed(2) + ',' + h.y.toFixed(2) + ',' + h.r; }).join(';'); }).join('|'); const sig = [state.structure, state.w, state.d, state.h, state.side, panels ? panels.length : 0, holeSig].join('|'); if (sig !== lastGeomSig) { lastGeomSig = sig; clearRoot(); const hasParts = panels && panels.length && FOLD_PARTS[state.structure]; if (hasParts) buildFromDieline(panels); if (!meshes.length) buildRigid(panels); applyFold(foldT); applyLines(); } refreshTextures(); applyCamera(); // 状态变化立即上屏(不依赖下一帧) try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {} } function flush() { try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {} } return { render: render, _dbg: { get scene() { return scene; }, get camera() { return camera; }, get renderer() { return renderer; }, get meshes() { return meshes; }, get hinges() { return hinges; }, get root() { return root; }, get orbit() { return orbit; }, get autoFlag() { return autoRotate; } }, setFold: function (t) { applyFold(t); flush(); }, setAutoRotate: function (v) { autoRotate = !!v; }, isAutoRotate: function () { return !!autoRotate; }, setZoom: function (z) { orbit.zoom = Math.max(0.4, Math.min(3.2, Number(z) || 1)); applyCamera(); flush(); }, setLines: function (v) { showLines = v !== false; applyLines(); flush(); }, // 自动转向指定面:2D 选中面时让 3D 视角同步 focusFace: function (face) { const target = { front: [0, Math.PI / 2], back: [Math.PI, Math.PI / 2], right: [Math.PI / 2, Math.PI / 2], left: [-Math.PI / 2, Math.PI / 2], top: [0, 0.32], bottom: [0, Math.PI - 0.32] }[face]; if (!target) return; const fromT = orbit.theta, fromP = orbit.phi; let toT = target[0]; while (toT - fromT > Math.PI) toT -= Math.PI * 2; while (toT - fromT < -Math.PI) toT += Math.PI * 2; const dur = 420, t0 = performance.now(); function step(now) { const p = Math.min(1, (now - t0) / dur); const e = p < 0.5 ? 2 * p * p : 1 - Math.pow(-2 * p + 2, 2) / 2; orbit.theta = fromT + (toT - fromT) * e; orbit.phi = fromP + (target[1] - fromP) * e; applyCamera(); flush(); if (p < 1) requestAnimationFrame(step); } requestAnimationFrame(step); }, resetView: function () { orbit.theta = orbitHome.theta; orbit.phi = orbitHome.phi; orbit.zoom = orbitHome.zoom; anim.id = null; applyCamera(); flush(); }, playAnim: function (id, dur, onEnd) { const def = (window.PL.boxlib && window.PL.boxlib.ANIMS.find(function (a) { return a.id === id; })) || { dur: 4 }; anim.id = id; anim.custom = null; anim.dur = dur || def.dur; anim.t0 = vNow; // 与 tickAnim 同一虚拟时钟,步进连续(页面时钟可能冻结不可用) anim.onEnd = onEnd || null; startAudioHeart(); }, // 通用补间(音频线程心跳驱动,冻结环境流畅):onUpdate 接收 0~1 进度 tween: function (dur, onUpdate, onDone) { anim.id = '__tween'; anim.custom = onUpdate; anim.dur = dur; anim.t0 = vNow; anim.onEnd = onDone || null; startAudioHeart(); }, stopAnim: function () { anim.id = null; anim.custom = null; stopAudioHeart(); }, animating: function () { return !!anim.id; }, snapshot: function (w, h2, transparent) { const keepW = el.clientWidth, keepH = el.clientHeight, keepZoom = orbit.zoom; if (w && h2) { renderer.setPixelRatio(1); renderer.setSize(w, h2, false); camera.aspect = w / h2; camera.updateProjectionMatrix(); } renderer.render(scene, camera); let url; if (transparent) { // 用离屏合成保留透明通道 const src = canvas; const c = document.createElement('canvas'); c.width = src.width; c.height = src.height; const ctx = c.getContext('2d'); ctx.drawImage(src, 0, 0); url = c.toDataURL('image/png'); } else { url = canvas.toDataURL('image/png'); } if (w && h2) { renderer.setPixelRatio(opts.mini ? 1 : Math.min(window.devicePixelRatio || 1, 2)); renderer.setSize(keepW, keepH, false); camera.aspect = keepW / keepH; camera.updateProjectionMatrix(); } return url; }, dispose: function () { cancelAnimationFrame(raf); disposeFns.forEach(function (f) { f(); }); clearRoot(); renderer.dispose(); if (canvas.parentNode) canvas.parentNode.removeChild(canvas); }, ready: function () { return !!renderer; } }; } window.PL = window.PL || {}; window.PL.box3d = { create: create }; })();