box3d.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. /**
  2. * box3d.js — Three.js 盒子 3D 渲染(多实例工厂版)
  3. * - 从刀版 panels 自动构建铰链折叠
  4. * - 外侧 / 内侧独立贴图
  5. * - 10 种动效(折叠展开 / 自转 / 掉落 / 由远到近……)
  6. * - 重置视角、2K/3K/4K 高清截图、透明背景
  7. */
  8. (function () {
  9. const THREE = window.THREE;
  10. if (!THREE) return;
  11. function fontStack(key) {
  12. const fonts = window.PL && window.PL.data && window.PL.data.fonts;
  13. return (fonts && fonts[key] && fonts[key].stack) || '"PingFang SC", "Helvetica Neue", sans-serif';
  14. }
  15. function panelBox(p) {
  16. if (p.poly) {
  17. const xs = p.poly.map(function (pt) { return pt[0]; });
  18. const ys = p.poly.map(function (pt) { return pt[1]; });
  19. const x = Math.min.apply(null, xs);
  20. const y = Math.min.apply(null, ys);
  21. return { x: x, y: y, w: Math.max.apply(null, xs) - x, h: Math.max.apply(null, ys) - y };
  22. }
  23. return { x: p.x, y: p.y, w: p.w, h: p.h };
  24. }
  25. function boxCenter(b) { return { x: b.x + b.w / 2, y: b.y + b.h / 2 }; }
  26. function planeGeometry(b, poly, holes) {
  27. if (!poly && (!holes || !holes.length)) return new THREE.PlaneGeometry(b.w, b.h);
  28. const shape = new THREE.Shape();
  29. if (poly) {
  30. poly.forEach(function (pt, i) {
  31. const x = pt[0] - b.x - b.w / 2;
  32. const y = -(pt[1] - b.y - b.h / 2);
  33. if (i === 0) shape.moveTo(x, y);
  34. else shape.lineTo(x, y);
  35. });
  36. shape.closePath();
  37. } else {
  38. shape.moveTo(-b.w / 2, -b.h / 2);
  39. shape.lineTo(b.w / 2, -b.h / 2);
  40. shape.lineTo(b.w / 2, b.h / 2);
  41. shape.lineTo(-b.w / 2, b.h / 2);
  42. shape.closePath();
  43. }
  44. (holes || []).forEach(function (ho) {
  45. const path = new THREE.Path();
  46. path.absarc(ho.x - b.x - b.w / 2, -(ho.y - b.y - b.h / 2), ho.r, 0, Math.PI * 2, true);
  47. shape.holes.push(path);
  48. });
  49. const geom = new THREE.ShapeGeometry(shape);
  50. const pos = geom.attributes.position;
  51. const uv = geom.attributes.uv;
  52. for (let i = 0; i < pos.count; i += 1) {
  53. 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));
  54. }
  55. uv.needsUpdate = true;
  56. return geom;
  57. }
  58. // 卡牌等刚性面:在贴图平面上按刀版孔位真实开孔(局部坐标,y 向上)
  59. function rigidPlaneGeometry(w, h, holes) {
  60. if (!holes || !holes.length) return new THREE.PlaneGeometry(w, h);
  61. const shape = new THREE.Shape();
  62. shape.moveTo(-w / 2, -h / 2);
  63. shape.lineTo(w / 2, -h / 2);
  64. shape.lineTo(w / 2, h / 2);
  65. shape.lineTo(-w / 2, h / 2);
  66. shape.closePath();
  67. holes.forEach(function (ho) {
  68. const path = new THREE.Path();
  69. path.absarc(ho.x, ho.y, ho.r, 0, Math.PI * 2, true);
  70. shape.holes.push(path);
  71. });
  72. const geom = new THREE.ShapeGeometry(shape);
  73. const pos = geom.attributes.position;
  74. const uv = geom.attributes.uv;
  75. for (let i = 0; i < pos.count; i += 1) {
  76. uv.setXY(i, (pos.getX(i) + w / 2) / Math.max(0.001, w), (pos.getY(i) + h / 2) / Math.max(0.001, h));
  77. }
  78. uv.needsUpdate = true;
  79. return geom;
  80. }
  81. const FOLD_PARTS = { carton: 1, rsc: 1, mailbox: 1, tuck: 1, straight: 1, autobottom: 1, mailer: 1, drawer: 1, bag: 1, sleeve: 1 };
  82. function panelLayer(p) {
  83. if (p.kind === 'glue') return -0.6;
  84. if (p.kind === 'lip') return -0.9;
  85. if (p.kind === 'dust') return -0.35;
  86. if (p.kind === 'tuck') return -0.28;
  87. if (p.kind === 'flap') return -0.12;
  88. return 0;
  89. }
  90. function isBodyKind(k) {
  91. return !(k === 'glue' || k === 'flap' || k === 'dust' || k === 'tuck' || k === 'lip');
  92. }
  93. function canHinge(a, b) {
  94. const ka = a.kind || 'body';
  95. const kb = b.kind || 'body';
  96. if (isBodyKind(ka) !== isBodyKind(kb)) return true;
  97. if (isBodyKind(ka) && isBodyKind(kb)) return true;
  98. return (ka === 'tuck' && kb === 'flap') || (ka === 'flap' && kb === 'tuck');
  99. }
  100. function panelEdges(p) {
  101. const b = panelBox(p);
  102. 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]];
  103. const out = [];
  104. for (let i = 0; i < pts.length; i += 1) {
  105. const a = pts[i];
  106. const c = pts[(i + 1) % pts.length];
  107. 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]) });
  108. 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]) });
  109. }
  110. return out;
  111. }
  112. function sharedEdge(a, b) {
  113. let best = null;
  114. panelEdges(a).forEach(function (ea) {
  115. panelEdges(b).forEach(function (eb) {
  116. if (ea.axis !== eb.axis || Math.abs(ea.c - eb.c) > 0.6) return;
  117. const lo = Math.max(ea.lo, eb.lo);
  118. const hi = Math.min(ea.hi, eb.hi);
  119. const len = hi - lo;
  120. if (len <= 2) return;
  121. if (!best || len > best.len) best = { axis: ea.axis, c: ea.c, lo: lo, hi: hi, len: len };
  122. });
  123. });
  124. return best;
  125. }
  126. function buildAdjacency(panels, boxes) {
  127. const adj = panels.map(function () { return []; });
  128. for (let i = 0; i < panels.length; i += 1) {
  129. for (let j = i + 1; j < panels.length; j += 1) {
  130. if (!canHinge(panels[i], panels[j])) continue;
  131. const edge = sharedEdge(panels[i], panels[j]);
  132. if (!edge) continue;
  133. const ca = boxCenter(boxes[i]);
  134. const cb = boxCenter(boxes[j]);
  135. let n;
  136. if (edge.axis === 'v') n = { x: cb.x >= ca.x ? 1 : -1, y: 0 };
  137. else n = { x: 0, y: cb.y >= ca.y ? 1 : -1 };
  138. const mk = function (s) {
  139. return edge.axis === 'v'
  140. ? { axis: 'v', x: edge.c, y0: edge.lo, y1: edge.hi, n: { x: n.x * s, y: n.y * s } }
  141. : { axis: 'h', x0: edge.lo, x1: edge.hi, y: edge.c, n: { x: n.x * s, y: n.y * s } };
  142. };
  143. adj[i].push({ j: j, edge: mk(1), overlap: edge.len });
  144. adj[j].push({ j: i, edge: mk(-1), overlap: edge.len });
  145. }
  146. }
  147. return adj;
  148. }
  149. function hingePoint(edge) {
  150. if (edge.axis === 'v') return { x: edge.x, y: (edge.y0 + edge.y1) / 2 };
  151. return { x: (edge.x0 + edge.x1) / 2, y: edge.y };
  152. }
  153. function rootIndexFor(indices, panels, boxes, prefer) {
  154. let best = -1, bestScore = -Infinity;
  155. indices.forEach(function (idx) {
  156. const b = boxes[idx];
  157. const face = panels[idx].face;
  158. const score = (face === prefer ? 1e9 : 0) + (face ? 1e6 : 0) + b.w * b.h;
  159. if (score > bestScore) { bestScore = score; best = idx; }
  160. });
  161. return best;
  162. }
  163. /* ================= 实例工厂 ================= */
  164. function create(el, opts) {
  165. opts = opts || {};
  166. let renderer = null, scene = null, camera = null, root = null, canvas = null;
  167. let meshes = [], hinges = [], components = [];
  168. const orbit = { theta: -0.55, phi: 1.08, zoom: 1 };
  169. const orbitHome = { theta: -0.55, phi: 1.08, zoom: 1 };
  170. let autoRotate = false;
  171. let onFacePick = opts.onFacePick || null;
  172. let drag = null, moved = false, raf = null;
  173. let foldT = 0;
  174. let showLines = true;
  175. let state = null, material = null;
  176. let disposeFns = [];
  177. renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
  178. renderer.setPixelRatio(opts.mini ? 1 : Math.min(window.devicePixelRatio || 1, 2));
  179. renderer.outputEncoding = THREE.sRGBEncoding;
  180. renderer.setClearColor(0x000000, 0);
  181. canvas = renderer.domElement;
  182. canvas.className = 'box3d-canvas';
  183. canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;display:block;z-index:2;touch-action:none;cursor:grab;';
  184. el.appendChild(canvas);
  185. el.classList.add('three-active');
  186. scene = new THREE.Scene();
  187. camera = new THREE.PerspectiveCamera(32, 1, 1, 60000);
  188. scene.add(new THREE.AmbientLight(0xffffff, 0.82));
  189. const key = new THREE.DirectionalLight(0xffffff, 0.8);
  190. key.position.set(-350, 600, 800);
  191. scene.add(key);
  192. const fill = new THREE.DirectionalLight(0xffffff, 0.34);
  193. fill.position.set(600, -260, -500);
  194. scene.add(fill);
  195. const rim = new THREE.DirectionalLight(0xffffff, 0.22);
  196. rim.position.set(-500, -200, -700);
  197. scene.add(rim);
  198. function resize() {
  199. const w = Math.max(1, el.clientWidth);
  200. const hh = Math.max(1, el.clientHeight);
  201. renderer.setSize(w, hh, false);
  202. camera.aspect = w / hh;
  203. camera.updateProjectionMatrix();
  204. }
  205. resize();
  206. if (window.ResizeObserver) {
  207. const ro = new ResizeObserver(resize);
  208. ro.observe(el);
  209. disposeFns.push(function () { ro.disconnect(); });
  210. }
  211. /* ---- 贴图 ---- */
  212. function drawFaceArt(ctx, cw, ch, data, px2mm) {
  213. const items = (data && data.items) || [];
  214. items.forEach(function (it) {
  215. if (it.hidden) return;
  216. if (it.type === 'text') {
  217. const px = it.size * px2mm;
  218. const lines = String(it.text || '').split('\n');
  219. const lh = (it.lineHeight || 1.25) * px;
  220. ctx.save();
  221. ctx.fillStyle = it.color || '#17140f';
  222. ctx.textAlign = it.align === 'center' ? 'center' : it.align === 'right' ? 'right' : 'left';
  223. ctx.textBaseline = 'middle';
  224. ctx.font = (it.italic ? 'italic ' : '') + (it.weight || 400) + ' ' + px + 'px ' + fontStack(it.font);
  225. const x = (it.x / 100) * cw;
  226. const y = (it.y / 100) * ch;
  227. lines.forEach(function (line, i) {
  228. ctx.fillText(line, x, y + (i - (lines.length - 1) / 2) * lh);
  229. });
  230. ctx.restore();
  231. } else if ((it.type === 'image' || it.type === 'asset') && it.src) {
  232. const img = getCachedImage(it.src, function () { refreshTextures(); });
  233. if (img) {
  234. const iw = ((it.w == null ? 70 : it.w) / 100) * cw;
  235. const ix = ((it.x == null ? 50 : it.x) / 100) * cw;
  236. const iy = ((it.y == null ? 50 : it.y) / 100) * ch;
  237. 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) {}
  238. }
  239. } else if (it.type === 'barcode' && it.src) {
  240. const img = getCachedImage(it.src, function () { refreshTextures(); });
  241. if (img) {
  242. const iw = ((it.w || 40) / 100) * cw;
  243. const ix = (it.x / 100) * cw;
  244. const iy = (it.y / 100) * ch;
  245. try { ctx.drawImage(img, ix - iw / 2, iy - iw * 0.42, iw, iw * 0.84); } catch (e) {}
  246. }
  247. }
  248. });
  249. // 兼容旧数据
  250. (data && data.texts || []).forEach(function (t) {
  251. const px = t.size * px2mm;
  252. const lines = String(t.text || '').split('\n');
  253. const lh = (t.lineHeight || 1.25) * px;
  254. ctx.save();
  255. ctx.fillStyle = t.color || '#17140f';
  256. ctx.textAlign = t.align === 'center' ? 'center' : t.align === 'right' ? 'right' : 'left';
  257. ctx.textBaseline = 'middle';
  258. ctx.font = (t.italic ? 'italic ' : '') + (t.weight || 400) + ' ' + px + 'px ' + fontStack(t.font);
  259. const x = (t.x / 100) * cw;
  260. const y = (t.y / 100) * ch;
  261. lines.forEach(function (line, i) { ctx.fillText(line, x, y + (i - (lines.length - 1) / 2) * lh); });
  262. ctx.restore();
  263. });
  264. }
  265. /* ---- 面纹理缓存:几何不变时仅重绘画布内容(needsUpdate),避免整场景重建 ---- */
  266. const faceTexCache = {}; // side|face -> { canvas, ctx, texture, cw, ch }
  267. const imgCache = new Map(); // src -> HTMLImageElement(避免重复解码)
  268. function getCachedImage(src, onReady) {
  269. if (imgCache.has(src)) {
  270. const img = imgCache.get(src);
  271. if (img.complete && img.naturalWidth) return img;
  272. return null;
  273. }
  274. const img = new Image();
  275. img.onload = function () { if (onReady) onReady(); };
  276. img.src = src;
  277. imgCache.set(src, img);
  278. return null;
  279. }
  280. function drawFaceTo(entry, face, fillOnly) {
  281. const sideData = (state.faces[state.side || 'outer'] || {});
  282. const data = sideData[face] || {};
  283. const ctx = entry.ctx;
  284. const cw = entry.cw, ch = entry.ch;
  285. const size = { w: entry.sizeW, h: entry.sizeH };
  286. ctx.setTransform(1, 0, 0, 1, 0, 0);
  287. ctx.fillStyle = data.color || material.paper || '#fbf7ee';
  288. ctx.fillRect(0, 0, cw, ch);
  289. if (data.texture) {
  290. const tex = getCachedImage(data.texture, function () { refreshTextures(); });
  291. if (tex) {
  292. const scale = Math.max(cw / 220, ch / 220);
  293. for (let tx = 0; tx < cw; tx += 220 * scale) for (let ty = 0; ty < ch; ty += 220 * scale) {
  294. ctx.drawImage(tex, tx, ty, 220 * scale, 220 * scale);
  295. }
  296. }
  297. }
  298. // 结构副面(如扣底/平口箱的补位摇盖)只刷底色与纹理,不重复印图案
  299. if (!fillOnly) drawFaceArt(ctx, cw, ch, data, cw / Math.max(1, size.w));
  300. }
  301. function getFaceTexture(face, size, fillOnly) {
  302. const key = (state.side || 'outer') + '|' + face + (fillOnly ? '|fill' : '');
  303. let entry = faceTexCache[key];
  304. if (!entry) {
  305. const cw = opts.mini ? 360 : 760;
  306. const ch = Math.max(160, Math.round(cw * size.h / Math.max(1, size.w)));
  307. const c = document.createElement('canvas');
  308. c.width = cw;
  309. c.height = ch;
  310. const texture = new THREE.CanvasTexture(c);
  311. texture.encoding = THREE.sRGBEncoding;
  312. texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
  313. entry = { canvas: c, ctx: c.getContext('2d'), texture: texture, cw: cw, ch: ch, sizeW: size.w, sizeH: size.h };
  314. faceTexCache[key] = entry;
  315. }
  316. return entry;
  317. }
  318. function refreshTextures() {
  319. const prefix = (state.side || 'outer') + '|';
  320. // 清理另一侧的缓存(内外侧切换后不再使用)
  321. Object.keys(faceTexCache).forEach(function (k) {
  322. if (k.indexOf(prefix) !== 0) {
  323. faceTexCache[k].texture.dispose();
  324. delete faceTexCache[k];
  325. }
  326. });
  327. meshes.forEach(function (mesh) {
  328. const face = mesh.userData.face || mesh.userData.paint;
  329. if (!face || !mesh.material) return;
  330. const entry = getFaceTexture(face, mesh.userData.faceSize || { w: 1, h: 1 }, mesh.userData.fillOnly);
  331. drawFaceTo(entry, face, mesh.userData.fillOnly);
  332. entry.texture.needsUpdate = true;
  333. if (mesh.material.map !== entry.texture) {
  334. mesh.material.map = entry.texture;
  335. mesh.material.needsUpdate = true;
  336. }
  337. });
  338. }
  339. function makeMaterial(face, size, inner, fillOnly) {
  340. const entry = getFaceTexture(face, size, fillOnly);
  341. drawFaceTo(entry, face, fillOnly);
  342. entry.texture.needsUpdate = true;
  343. return new THREE.MeshStandardMaterial({
  344. map: entry.texture,
  345. color: 0xffffff,
  346. roughness: 0.8,
  347. metalness: 0.02,
  348. side: THREE.DoubleSide
  349. });
  350. }
  351. function cardboardMaterial() {
  352. const sideData = (state.faces[state.side || 'outer'] || {});
  353. const plain = sideData._plain || {};
  354. return new THREE.MeshStandardMaterial({
  355. color: new THREE.Color(plain.color || material.paper || '#fbf7ee'),
  356. roughness: 0.86,
  357. metalness: 0.02,
  358. side: THREE.DoubleSide
  359. });
  360. }
  361. function makePanelMesh(p, box) {
  362. const geom = planeGeometry(box, p.poly, p.holes);
  363. const face = p.face || p.paint || null;
  364. const fillOnly = !p.face && !!p.paint;
  365. const mat = face ? makeMaterial(face, { w: box.w, h: box.h }, state.side === 'inner', fillOnly) : cardboardMaterial();
  366. const mesh = new THREE.Mesh(geom, mat);
  367. mesh.position.z = panelLayer(p);
  368. mesh.userData.face = p.face || null;
  369. mesh.userData.paint = p.paint || null;
  370. mesh.userData.fillOnly = fillOnly;
  371. mesh.userData.faceSize = face ? { w: box.w, h: box.h } : null;
  372. mesh.add(new THREE.LineSegments(
  373. new THREE.EdgesGeometry(geom),
  374. new THREE.LineBasicMaterial({ color: 0x17140f, transparent: true, opacity: 0.24 })
  375. ));
  376. meshes.push(mesh);
  377. return mesh;
  378. }
  379. function clearRoot() {
  380. if (root) {
  381. root.traverse(function (o) {
  382. if (o.geometry) o.geometry.dispose();
  383. if (o.material) o.material.dispose();
  384. });
  385. scene.remove(root);
  386. }
  387. // 纹理缓存随几何一起释放(key 含 side,重建后按需重建)
  388. Object.keys(faceTexCache).forEach(function (k) {
  389. faceTexCache[k].texture.dispose();
  390. delete faceTexCache[k];
  391. });
  392. root = new THREE.Group();
  393. scene.add(root);
  394. meshes = [];
  395. hinges = [];
  396. components = [];
  397. }
  398. function buildComponent(indices, panels, boxes, adj, prefer) {
  399. const start = rootIndexFor(indices, panels, boxes, prefer);
  400. if (start < 0) return null;
  401. const comp = new THREE.Group();
  402. const rootGroup = new THREE.Group();
  403. comp.add(rootGroup);
  404. const rootBox = boxes[start];
  405. const rootMesh = makePanelMesh(panels[start], rootBox);
  406. rootMesh.userData.kind = panels[start].kind;
  407. rootGroup.add(rootMesh);
  408. const infos = new Map();
  409. infos.set(start, { group: rootGroup, origin: boxCenter(rootBox) });
  410. const visited = new Set([start]);
  411. const best = new Map();
  412. const addLinks = function (pi) {
  413. adj[pi].forEach(function (link) {
  414. if (visited.has(link.j)) return;
  415. const cur = best.get(link.j);
  416. if (!cur || link.overlap > cur.overlap) best.set(link.j, { from: pi, link: link });
  417. });
  418. };
  419. addLinks(start);
  420. while (visited.size < indices.length) {
  421. let pick = -1, pickW = -1;
  422. best.forEach(function (v, k) {
  423. if (visited.has(k)) return;
  424. if (v.link.overlap > pickW) { pickW = v.link.overlap; pick = k; }
  425. });
  426. if (pick < 0) break;
  427. const chosen = best.get(pick);
  428. const parent = infos.get(chosen.from);
  429. const link = chosen.link;
  430. const hinge = hingePoint(link.edge);
  431. const cb = boxes[pick];
  432. const pivot = new THREE.Group();
  433. pivot.position.set(hinge.x - parent.origin.x, -(hinge.y - parent.origin.y), 0);
  434. const n3 = new THREE.Vector3(link.edge.n.x, -link.edge.n.y, 0);
  435. if (n3.lengthSq() < 0.5) n3.set(0, 1, 0);
  436. n3.normalize();
  437. const axis = new THREE.Vector3(0, 0, 1).cross(n3).normalize();
  438. pivot.userData.axis = axis;
  439. pivot.userData.angle = Math.PI / 2;
  440. hinges.push(pivot);
  441. parent.group.add(pivot);
  442. const cc = boxCenter(cb);
  443. const mesh = makePanelMesh(panels[pick], cb);
  444. mesh.position.x = cc.x - hinge.x;
  445. mesh.position.y = -(cc.y - hinge.y);
  446. mesh.userData.kind = panels[pick].kind;
  447. pivot.add(mesh);
  448. infos.set(pick, { group: pivot, origin: hinge });
  449. visited.add(pick);
  450. best.delete(pick);
  451. addLinks(pick);
  452. }
  453. return { group: comp, root: start };
  454. }
  455. function buildFromDieline(panels) {
  456. const boxes = panels.map(panelBox);
  457. const adj = buildAdjacency(panels, boxes);
  458. const seen = new Set();
  459. const groups = [];
  460. for (let i = 0; i < panels.length; i += 1) {
  461. if (seen.has(i)) continue;
  462. const stack = [i];
  463. const indices = [];
  464. seen.add(i);
  465. while (stack.length) {
  466. const cur = stack.pop();
  467. indices.push(cur);
  468. adj[cur].forEach(function (link) {
  469. if (seen.has(link.j)) return;
  470. seen.add(link.j);
  471. stack.push(link.j);
  472. });
  473. }
  474. groups.push(indices);
  475. }
  476. const prefer = 'front';
  477. const built = [];
  478. groups.forEach(function (indices) {
  479. const comp = buildComponent(indices, panels, boxes, adj, prefer);
  480. if (comp) built.push(comp);
  481. });
  482. if (!built.length) return false;
  483. const main = built[0];
  484. const mainOrigin = boxCenter(boxes[main.root]);
  485. built.forEach(function (c) {
  486. const center = boxCenter(boxes[c.root]);
  487. c.home = new THREE.Vector3(center.x - mainOrigin.x, -(center.y - mainOrigin.y), 0);
  488. c.assembled = new THREE.Vector3(0, 0, 0);
  489. c.assembledScale = 1;
  490. c.isMain = c === main;
  491. if (!c.isMain) {
  492. c.assembled.set(0, 0, -2);
  493. c.assembledScale = 0.94;
  494. }
  495. c.group.position.copy(c.home);
  496. root.add(c.group);
  497. components.push(c);
  498. });
  499. root.userData.mainOrigin = { x: mainOrigin.x, y: mainOrigin.y };
  500. return true;
  501. }
  502. function buildRigid(panels) {
  503. const t = material.thickness || 0;
  504. const W = state.w + t * 2;
  505. // 卡牌为单张纸片,厚度取材质厚度,不沿用盒体的深度
  506. const D = state.structure === 'card' ? t * 2 : state.d + t * 2;
  507. const H = state.h + t * 2;
  508. const inner = state.side === 'inner';
  509. // 卡牌刀版在正面定义挂孔,3D 正反面同步开孔
  510. const cardFront = (panels || []).find(function (p) { return p.face === 'front' && p.holes && p.holes.length; });
  511. const cardBox = cardFront ? panelBox(cardFront) : null;
  512. const defs = [
  513. { face: 'front', w: W, h: H, pos: [0, 0, D / 2], rot: [0, 0, 0] },
  514. { face: 'back', w: W, h: H, pos: [0, 0, -D / 2], rot: [0, Math.PI, 0] },
  515. { face: 'right', w: D, h: H, pos: [W / 2, 0, 0], rot: [0, Math.PI / 2, 0] },
  516. { face: 'left', w: D, h: H, pos: [-W / 2, 0, 0], rot: [0, -Math.PI / 2, 0] },
  517. { face: 'top', w: W, h: D, pos: [0, H / 2, 0], rot: [-Math.PI / 2, 0, 0] },
  518. { face: 'bottom', w: W, h: D, pos: [0, -H / 2, 0], rot: [Math.PI / 2, 0, 0] }
  519. ];
  520. defs.forEach(function (def) {
  521. const holes = cardBox && (def.face === 'front' || def.face === 'back')
  522. ? cardFront.holes.map(function (ho) {
  523. return { x: ho.x - (cardBox.x + cardBox.w / 2), y: def.h / 2 - (ho.y - cardBox.y), r: ho.r };
  524. })
  525. : null;
  526. const geom = rigidPlaneGeometry(def.w, def.h, holes);
  527. const mat = makeMaterial(def.face, { w: def.w, h: def.h }, inner);
  528. const mesh = new THREE.Mesh(geom, mat);
  529. mesh.position.set(def.pos[0], def.pos[1], def.pos[2]);
  530. mesh.rotation.set(def.rot[0], def.rot[1], def.rot[2]);
  531. mesh.userData.face = def.face;
  532. mesh.userData.faceSize = { w: def.w, h: def.h };
  533. root.add(mesh);
  534. meshes.push(mesh);
  535. mesh.add(new THREE.LineSegments(
  536. new THREE.EdgesGeometry(geom),
  537. new THREE.LineBasicMaterial({ color: 0x17140f, transparent: true, opacity: 0.22 })
  538. ));
  539. });
  540. }
  541. /* ---- 动效引擎 ---- */
  542. const anim = { id: null, t0: 0, dur: 0, onEnd: null };
  543. const animState = { theta: 0, phi: 0, zoom: 1, dx: 0, dy: 0, dz: 0, fold: null };
  544. const EASE = {
  545. io: function (t) { return t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2; },
  546. out: function (t) { return 1 - Math.pow(1 - t, 3); },
  547. bounce: function (t) {
  548. const n1 = 7.5625, d1 = 2.75;
  549. if (t < 1 / d1) return n1 * t * t;
  550. if (t < 2 / d1) return n1 * (t -= 1.5 / d1) * t + 0.75;
  551. if (t < 2.5 / d1) return n1 * (t -= 2.25 / d1) * t + 0.9375;
  552. return n1 * (t -= 2.625 / d1) * t + 0.984375;
  553. }
  554. };
  555. const ANIM_TICKS = {
  556. fold: function (p) {
  557. animState.fold = p < 0.5 ? EASE.io(p * 2) : 1 - EASE.io((p - 0.5) * 2);
  558. },
  559. spinFlat: function (p) {
  560. animState.phi = 0.18;
  561. animState.theta = EASE.io(p) * Math.PI * 2;
  562. },
  563. spinTop: function (p) {
  564. animState.phi = -1.05;
  565. animState.theta = EASE.io(p) * Math.PI * 2;
  566. },
  567. dropSpin: function (p) {
  568. const k = EASE.out(Math.min(1, p / 0.55));
  569. animState.dy = (1 - k) * 260;
  570. animState.theta = (1 - k) * Math.PI * 2.2;
  571. animState.dz = (1 - k) * -80;
  572. },
  573. zoomIn: function (p) {
  574. animState.zoom = 0.35 + EASE.io(p) * 0.75;
  575. animState.phi = 0.12;
  576. },
  577. dropZoom: function (p) {
  578. if (p < 0.375) {
  579. const k = EASE.out(p / 0.375);
  580. animState.dy = (1 - k) * 300;
  581. animState.theta = (1 - k) * Math.PI * 2.4;
  582. } else {
  583. const k = EASE.io((p - 0.375) / 0.625);
  584. animState.zoom = 1 + k * 1.1;
  585. animState.phi = 0.1 + k * 0.2;
  586. }
  587. },
  588. zoomDetail: function (p) {
  589. animState.zoom = 0.4 + EASE.io(p) * 1.2;
  590. animState.theta = -0.3 * (1 - p);
  591. animState.phi = 0.25 - p * 0.12;
  592. },
  593. fromLeft: function (p) {
  594. const k = EASE.out(p);
  595. animState.dx = (1 - k) * -220;
  596. animState.theta = (1 - k) * -Math.PI * 1.5;
  597. animState.phi = 0.3;
  598. },
  599. curveIn: function (p) {
  600. const k = EASE.io(p);
  601. animState.dz = (1 - k) * -400;
  602. animState.dx = Math.sin(p * Math.PI) * -120 * (1 - p);
  603. animState.dy = Math.sin(p * Math.PI) * 90;
  604. animState.theta = (1 - k) * -0.9;
  605. },
  606. foldBounce: function (p) {
  607. animState.fold = EASE.io(Math.min(1, p / 0.7));
  608. if (p > 0.7) animState.dy = -(1 - EASE.bounce((p - 0.7) / 0.3)) * 14;
  609. }
  610. };
  611. function tickAnim(now) {
  612. if (!anim.id) return false;
  613. const p = Math.min(1, (now - anim.t0) / (anim.dur * 1000));
  614. Object.assign(animState, { theta: 0, phi: 0, zoom: 1, dx: 0, dy: 0, dz: 0, fold: null });
  615. if (anim.custom) anim.custom(p);
  616. else ANIM_TICKS[anim.id](p);
  617. if (p >= 1) {
  618. const end = anim.onEnd;
  619. const wasCustom = anim.custom;
  620. anim.id = null;
  621. anim.custom = null;
  622. if (wasCustom) stopAudioHeart();
  623. if (end) end();
  624. }
  625. return true;
  626. }
  627. function applyCamera() {
  628. if (!camera || !root) return;
  629. root.updateMatrixWorld(true);
  630. const bbox = new THREE.Box3().setFromObject(root);
  631. if (bbox.isEmpty()) return;
  632. const center = bbox.getCenter(new THREE.Vector3());
  633. const size = bbox.getSize(new THREE.Vector3());
  634. const maxDim = Math.max(size.x, size.y, size.z, 1);
  635. const zoom = orbit.zoom * animState.zoom;
  636. const r = maxDim * 2.85 / Math.max(0.3, zoom);
  637. const phi = Math.max(0.15, Math.min(Math.PI - 0.15, orbit.phi + animState.phi));
  638. const theta = orbit.theta + animState.theta;
  639. const x = r * Math.sin(phi) * Math.sin(theta);
  640. const y = r * Math.cos(phi);
  641. const z = r * Math.sin(phi) * Math.cos(theta);
  642. camera.position.set(center.x + x + animState.dx, center.y + y + animState.dy, center.z + z + animState.dz);
  643. camera.lookAt(center.x + animState.dx * 0.2, center.y - maxDim * (opts.mini ? 0.02 : 0.05), center.z);
  644. }
  645. function applyFold(t) {
  646. foldT = Math.max(0, Math.min(1, Number(t) || 0));
  647. hinges.forEach(function (g) {
  648. g.setRotationFromAxisAngle(g.userData.axis, g.userData.angle * (1 - foldT));
  649. });
  650. // 盒体闭合时插舌应插入盒内,简化折纸模型无法表达穿插,直接隐藏
  651. const showTuck = foldT > 0.35;
  652. meshes.forEach(function (m) {
  653. if (m.userData.kind === 'tuck') m.visible = showTuck;
  654. });
  655. components.forEach(function (c) {
  656. if (c.isMain) return;
  657. c.group.position.lerpVectors(c.assembled, c.home, foldT);
  658. const s = c.assembledScale + (1 - c.assembledScale) * foldT;
  659. c.group.scale.set(s, s, s);
  660. });
  661. }
  662. function applyLines() {
  663. if (!root) return;
  664. root.traverse(function (o) { if (o.isLineSegments) o.visible = showLines; });
  665. }
  666. /* ---- 交互 ---- */
  667. function bindPointer() {
  668. canvas.addEventListener('pointerdown', function (e) {
  669. if (e.button !== 0) return;
  670. if (opts.mini && opts.onInteract) opts.onInteract(); // 按下即接管(停掉 CSS 自动播放)
  671. drag = { x: e.clientX, y: e.clientY, theta: orbit.theta, phi: orbit.phi };
  672. moved = false;
  673. canvas.style.cursor = 'grabbing';
  674. canvas.setPointerCapture(e.pointerId);
  675. });
  676. canvas.addEventListener('pointermove', function (e) {
  677. if (!drag) return;
  678. const dx = e.clientX - drag.x;
  679. const dy = e.clientY - drag.y;
  680. if (Math.abs(dx) + Math.abs(dy) > 3) moved = true;
  681. orbit.theta = drag.theta - dx * 0.008;
  682. orbit.phi = Math.max(0.25, Math.min(Math.PI - 0.25, drag.phi - dy * 0.006));
  683. if (opts.mini && autoRotate && moved && opts.onInteract) {
  684. autoRotate = false;
  685. opts.onInteract();
  686. }
  687. applyCamera();
  688. flush(); // 交互即时渲染:拖拽旋转不依赖 rAF 节奏
  689. });
  690. canvas.addEventListener('pointerup', function (e) {
  691. if (!drag) return;
  692. const wasMoved = moved;
  693. drag = null;
  694. canvas.style.cursor = 'grab';
  695. try { canvas.releasePointerCapture(e.pointerId); } catch (err) {}
  696. if (wasMoved || !onFacePick) return;
  697. const rect = canvas.getBoundingClientRect();
  698. const px = ((e.clientX - rect.left) / rect.width) * 2 - 1;
  699. const py = -((e.clientY - rect.top) / rect.height) * 2 + 1;
  700. const rc = new THREE.Raycaster();
  701. rc.setFromCamera(new THREE.Vector2(px, py), camera);
  702. const hits = rc.intersectObjects(meshes, false);
  703. if (hits.length && hits[0].object.userData.face) onFacePick(hits[0].object.userData.face);
  704. });
  705. canvas.addEventListener('pointercancel', function () {
  706. drag = null;
  707. canvas.style.cursor = 'grab';
  708. });
  709. canvas.addEventListener('wheel', function (e) {
  710. e.preventDefault();
  711. e.stopPropagation();
  712. orbit.zoom = Math.max(0.4, Math.min(3.2, orbit.zoom * (e.deltaY > 0 ? 0.92 : 1.08)));
  713. applyCamera();
  714. flush();
  715. }, { passive: false });
  716. }
  717. bindPointer();
  718. let lastFrameAt = performance.now();
  719. // 虚拟时钟:页面时钟可能被节流冻结(rAF 停、setInterval 降频、performance.now 冻结),
  720. // 由 Web Worker 心跳(Worker 定时器不受页面可见性节流)持续推进,保证自动播放匀速循环。
  721. let vNow = performance.now();
  722. let lastVTick = vNow;
  723. const AUTO_SPEED = 0.28; // 约 22 秒一圈
  724. function tickCore() {
  725. const dt = Math.min(0.12, Math.max(0, vNow - lastVTick)) / 1000;
  726. lastVTick = vNow;
  727. try {
  728. const hasAnim = tickAnim(vNow);
  729. if (!anim.id && audioDriving) stopAudioHeart();
  730. if (autoRotate && !anim.id) orbit.theta += AUTO_SPEED * dt;
  731. if (animState.fold != null) applyFold(animState.fold);
  732. applyCamera();
  733. if (renderer && scene && camera) renderer.render(scene, camera);
  734. } catch (e) {
  735. // 单帧异常不终止渲染循环
  736. }
  737. }
  738. let framesSinceRaf = 0; // worker 心跳消息计数,rAF 有效帧清零
  739. let lastRafNow = 0;
  740. /* 音频线程心跳:AudioContext 回调独立于页面渲染节流,动画播放期提供 ~46fps 稳定帧 */
  741. let audioCtx = null, audioNode = null, audioDriving = false, lastAudioT = null;
  742. function startAudioHeart() {
  743. try {
  744. const AC = window.AudioContext || window.webkitAudioContext;
  745. if (!AC) return;
  746. if (!audioCtx) {
  747. audioCtx = new AC();
  748. audioNode = audioCtx.createScriptProcessor(2048, 1, 1);
  749. audioNode.onaudioprocess = function () {
  750. if (!audioDriving || !anim.id) return;
  751. // 用音频硬件时钟精确推进(单调、不受页面渲染节流影响)
  752. const t = audioCtx.currentTime;
  753. if (lastAudioT != null) vNow += Math.max(0, Math.min(200, (t - lastAudioT) * 1000));
  754. lastAudioT = t;
  755. tickCore();
  756. };
  757. const gain = audioCtx.createGain();
  758. gain.gain.value = 0; // 完全静音,仅用心跳
  759. audioNode.connect(gain);
  760. gain.connect(audioCtx.destination);
  761. }
  762. lastAudioT = null;
  763. // 同步判定当前状态;suspended 时异步 resume,成功后回调自动生效
  764. audioDriving = audioCtx.state === 'running';
  765. if (audioCtx.state === 'suspended') {
  766. audioCtx.resume().then(function () {
  767. audioDriving = audioCtx.state === 'running';
  768. }).catch(function () { audioDriving = false; });
  769. }
  770. } catch (e) { audioDriving = false; }
  771. }
  772. function stopAudioHeart() {
  773. audioDriving = false;
  774. lastAudioT = null;
  775. }
  776. let lastWall = Date.now();
  777. function animate() {
  778. raf = requestAnimationFrame(animate);
  779. const now = performance.now();
  780. const rafDt = lastRafNow ? now - lastRafNow : 16.7;
  781. lastRafNow = now;
  782. const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id;
  783. // 虚拟时钟推进源互斥:动画音频心跳运行时由音频帧推进,rAF 帧仅重渲染
  784. if (audioActive) {
  785. framesSinceRaf = 0;
  786. try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {}
  787. return;
  788. }
  789. // 墙钟流逝(Date.now 不受渲染节流冻结影响):空闲期掉帧也能补齐进度
  790. const wallNow = Date.now();
  791. const wallDt = Math.min(5000, Math.max(0, wallNow - lastWall));
  792. lastWall = wallNow;
  793. let step;
  794. if (rafDt >= 1 && rafDt < 100) step = rafDt; // rAF 时钟正常:按帧间隔
  795. else if (wallDt > 0) step = wallDt; // 渲染被节流:按墙钟补齐真实流逝
  796. else step = 16.7; // 兜底
  797. vNow += step;
  798. framesSinceRaf = 0;
  799. tickCore();
  800. }
  801. // 心跳自愈:rAF 停止(页面不可见/被节流)时由 Worker 定时器以 12fps 兜底驱动。
  802. // 判据用消息计数而非页面时钟——节流环境下页面 performance.now 可能冻结。
  803. try {
  804. const heartCode = 'setInterval(function(){postMessage(1)},83);';
  805. const heartUrl = URL.createObjectURL(new Blob([heartCode], { type: 'application/javascript' }));
  806. const heart = new Worker(heartUrl);
  807. heart.onmessage = function () {
  808. framesSinceRaf += 1;
  809. const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id;
  810. // rAF 停止时由 worker 帧接管;音频心跳实际运行时让位(避免双重计时)
  811. if ((framesSinceRaf > 3 || anim.id) && !audioActive) {
  812. vNow += 83;
  813. tickCore();
  814. }
  815. };
  816. if (typeof window !== 'undefined') window.__workerOk = (window.__workerOk || 0) + 1;
  817. } catch (e) {
  818. if (typeof window !== 'undefined') window.__workerFail = (window.__workerFail || 0) + 1;
  819. setInterval(function () {
  820. framesSinceRaf += 1;
  821. const audioActive = audioDriving && audioCtx && audioCtx.state === 'running' && !!anim.id;
  822. if ((framesSinceRaf > 3 || anim.id) && !audioActive) {
  823. vNow += 83;
  824. tickCore();
  825. }
  826. }, 84);
  827. }
  828. /* ---- 对外 API ---- */
  829. let lastGeomSig = '';
  830. function render(nextState, nextMaterial, panels) {
  831. resize();
  832. state = nextState;
  833. material = nextMaterial;
  834. // 结构签名:盒型/尺寸/内外侧/面数/孔位变化才重建几何;否则仅刷新面纹理(增量,避免卡顿)
  835. const holeSig = (panels || []).map(function (p) {
  836. return (p.holes || []).map(function (h) { return h.x.toFixed(2) + ',' + h.y.toFixed(2) + ',' + h.r; }).join(';');
  837. }).join('|');
  838. const sig = [state.structure, state.w, state.d, state.h, state.side, panels ? panels.length : 0, holeSig].join('|');
  839. if (sig !== lastGeomSig) {
  840. lastGeomSig = sig;
  841. clearRoot();
  842. const hasParts = panels && panels.length && FOLD_PARTS[state.structure];
  843. if (hasParts) buildFromDieline(panels);
  844. if (!meshes.length) buildRigid(panels);
  845. applyFold(foldT);
  846. applyLines();
  847. }
  848. refreshTextures();
  849. applyCamera();
  850. // 状态变化立即上屏(不依赖下一帧)
  851. try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {}
  852. }
  853. function flush() {
  854. try { renderer.render(scene, camera); lastFrameAt = performance.now(); } catch (e) {}
  855. }
  856. return {
  857. render: render,
  858. _dbg: {
  859. get scene() { return scene; },
  860. get camera() { return camera; },
  861. get renderer() { return renderer; },
  862. get meshes() { return meshes; },
  863. get hinges() { return hinges; },
  864. get root() { return root; },
  865. get orbit() { return orbit; },
  866. get autoFlag() { return autoRotate; }
  867. },
  868. setFold: function (t) { applyFold(t); flush(); },
  869. setAutoRotate: function (v) { autoRotate = !!v; },
  870. isAutoRotate: function () { return !!autoRotate; },
  871. setZoom: function (z) { orbit.zoom = Math.max(0.4, Math.min(3.2, Number(z) || 1)); applyCamera(); flush(); },
  872. setLines: function (v) { showLines = v !== false; applyLines(); flush(); },
  873. // 自动转向指定面:2D 选中面时让 3D 视角同步
  874. focusFace: function (face) {
  875. const target = {
  876. front: [0, Math.PI / 2], back: [Math.PI, Math.PI / 2],
  877. right: [Math.PI / 2, Math.PI / 2], left: [-Math.PI / 2, Math.PI / 2],
  878. top: [0, 0.32], bottom: [0, Math.PI - 0.32]
  879. }[face];
  880. if (!target) return;
  881. const fromT = orbit.theta, fromP = orbit.phi;
  882. let toT = target[0];
  883. while (toT - fromT > Math.PI) toT -= Math.PI * 2;
  884. while (toT - fromT < -Math.PI) toT += Math.PI * 2;
  885. const dur = 420, t0 = performance.now();
  886. function step(now) {
  887. const p = Math.min(1, (now - t0) / dur);
  888. const e = p < 0.5 ? 2 * p * p : 1 - Math.pow(-2 * p + 2, 2) / 2;
  889. orbit.theta = fromT + (toT - fromT) * e;
  890. orbit.phi = fromP + (target[1] - fromP) * e;
  891. applyCamera();
  892. flush();
  893. if (p < 1) requestAnimationFrame(step);
  894. }
  895. requestAnimationFrame(step);
  896. },
  897. resetView: function () {
  898. orbit.theta = orbitHome.theta;
  899. orbit.phi = orbitHome.phi;
  900. orbit.zoom = orbitHome.zoom;
  901. anim.id = null;
  902. applyCamera();
  903. flush();
  904. },
  905. playAnim: function (id, dur, onEnd) {
  906. const def = (window.PL.boxlib && window.PL.boxlib.ANIMS.find(function (a) { return a.id === id; })) || { dur: 4 };
  907. anim.id = id;
  908. anim.custom = null;
  909. anim.dur = dur || def.dur;
  910. anim.t0 = vNow; // 与 tickAnim 同一虚拟时钟,步进连续(页面时钟可能冻结不可用)
  911. anim.onEnd = onEnd || null;
  912. startAudioHeart();
  913. },
  914. // 通用补间(音频线程心跳驱动,冻结环境流畅):onUpdate 接收 0~1 进度
  915. tween: function (dur, onUpdate, onDone) {
  916. anim.id = '__tween';
  917. anim.custom = onUpdate;
  918. anim.dur = dur;
  919. anim.t0 = vNow;
  920. anim.onEnd = onDone || null;
  921. startAudioHeart();
  922. },
  923. stopAnim: function () { anim.id = null; anim.custom = null; stopAudioHeart(); },
  924. animating: function () { return !!anim.id; },
  925. snapshot: function (w, h2, transparent) {
  926. const keepW = el.clientWidth, keepH = el.clientHeight, keepZoom = orbit.zoom;
  927. if (w && h2) {
  928. renderer.setPixelRatio(1);
  929. renderer.setSize(w, h2, false);
  930. camera.aspect = w / h2;
  931. camera.updateProjectionMatrix();
  932. }
  933. renderer.render(scene, camera);
  934. let url;
  935. if (transparent) {
  936. // 用离屏合成保留透明通道
  937. const src = canvas;
  938. const c = document.createElement('canvas');
  939. c.width = src.width; c.height = src.height;
  940. const ctx = c.getContext('2d');
  941. ctx.drawImage(src, 0, 0);
  942. url = c.toDataURL('image/png');
  943. } else {
  944. url = canvas.toDataURL('image/png');
  945. }
  946. if (w && h2) {
  947. renderer.setPixelRatio(opts.mini ? 1 : Math.min(window.devicePixelRatio || 1, 2));
  948. renderer.setSize(keepW, keepH, false);
  949. camera.aspect = keepW / keepH;
  950. camera.updateProjectionMatrix();
  951. }
  952. return url;
  953. },
  954. dispose: function () {
  955. cancelAnimationFrame(raf);
  956. disposeFns.forEach(function (f) { f(); });
  957. clearRoot();
  958. renderer.dispose();
  959. if (canvas.parentNode) canvas.parentNode.removeChild(canvas);
  960. },
  961. ready: function () { return !!renderer; }
  962. };
  963. }
  964. window.PL = window.PL || {};
  965. window.PL.box3d = { create: create };
  966. })();