/* ========================================================================== 倫敦塔益智盒 3D 模擬器 - Three.js + Cannon.js 3D 物理與幾何引擎 ========================================================================== */ class Tower3DSimulator { constructor(containerId) { this.container = document.getElementById(containerId); // 基本參數設定 (單位:公分 cm) this.S = 4.00; // 盒子內徑預設 4.00cm (死鎖狀態,供使用者自行探索) this.ballDiameter = 2.00; // 球直徑固定 2.00cm this.r = 1.00; // 球半徑 1.00cm this.holeDiameter = 2.00; // 孔洞直徑 2.00cm this.wallThickness = 0.2; // 盒壁厚度 0.2cm this.currentMode = 1; this.isDiagonalTilted = false; this.isBoxLocked = false; this.isEscaped = false; // 成功脫出狀態旗標 // 1-4-1 旋轉角度 (模式二三中 4 綠球整組繞軸旋轉) this.groupRotationAngle = 0; // 弧度 rad this.mode1Config = '141'; // 模式一預設配置 // Three.js 核心物件 this.scene = null; this.camera = null; this.renderer = null; this.controls = null; this.boxGroup = null; this.spheresGroup = null; this.helpersGroup = null; // Cannon.js 物理世界 (Mode 1) this.world = null; this.sphereBodies = []; this.wallBodies = []; // 6 顆球 Mesh 引用 this.spheres = { m1: null, m2: null, m3: null, m4: null, // 中層 4 球 (綠球) top: null, // 頂球 (Red) bottom: null // 底球 (Blue) }; this.spheresArr = []; // 手動牽引與 Raycaster this.raycaster = new THREE.Raycaster(); this.mouse = new THREE.Vector2(); this.isDragging = false; this.lastMousePos = new THREE.Vector2(); // 動態時序變數 this.animTime = 0; this.init(); } /* ------------------------------------------------------------------ 初始化 Three.js 場景、燈光、Cannon 物理與事件監聽 ------------------------------------------------------------------ */ init() { try { if (!this.container) return; const w = this.container.clientWidth; const h = this.container.clientHeight || 540; // Scene this.scene = new THREE.Scene(); // Camera this.camera = new THREE.PerspectiveCamera(45, w / h, 0.1, 1000); this.camera.position.set(16, 12, 18); // Renderer this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); this.renderer.setSize(w, h); this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; this.container.appendChild(this.renderer.domElement); // OrbitControls this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement); this.controls.enableDamping = true; this.controls.dampingFactor = 0.05; this.controls.target.set(0, 0, 0); // Lights const ambientLight = new THREE.AmbientLight(0xffffff, 0.7); this.scene.add(ambientLight); const dirLight = new THREE.DirectionalLight(0xffffff, 1.2); dirLight.position.set(15, 25, 20); dirLight.castShadow = true; dirLight.shadow.mapSize.width = 2048; dirLight.shadow.mapSize.height = 2048; dirLight.shadow.bias = -0.0001; this.scene.add(dirLight); const pointLight = new THREE.PointLight(0x38bdf8, 0.8, 50); pointLight.position.set(-10, -10, -10); this.scene.add(pointLight); // Group Containers this.boxGroup = new THREE.Group(); this.spheresGroup = new THREE.Group(); this.helpersGroup = new THREE.Group(); this.scene.add(this.boxGroup); this.scene.add(this.spheresGroup); this.scene.add(this.helpersGroup); // Initialize Cannon Physics World (Mode 1) this.initPhysics(); // Build 3D Box & Spheres this.rebuildBox(); this.createSpheres(); // Setup Pointer Events (Mode 2/3 rotation drag) this.setupDragControls(); // Resize handler window.addEventListener('resize', () => this.onWindowResize()); // Start Animation Loop this.animate = this.animate.bind(this); requestAnimationFrame(this.animate); } catch (err) { console.error('[Tower3DSimulator] init error:', err); } } /* ------------------------------------------------------------------ Cannon.js 物理世界初始化 ------------------------------------------------------------------ */ initPhysics() { if (typeof CANNON === 'undefined') return; this.world = new CANNON.World(); this.world.gravity.set(0, -9.81, 0); this.world.broadphase = new CANNON.NaiveBroadphase(); this.world.solver.iterations = 25; this.defaultMaterial = new CANNON.Material("default"); const contactMat = new CANNON.ContactMaterial( this.defaultMaterial, this.defaultMaterial, { friction: 0.3, restitution: 0.05 } ); this.world.addContactMaterial(contactMat); } /* ------------------------------------------------------------------ 建造帶有六個圓形出口孔洞的正方體玻璃盒 ------------------------------------------------------------------ */ rebuildBox() { while (this.boxGroup.children.length > 0) { const child = this.boxGroup.children[0]; if (child.geometry) child.geometry.dispose(); this.boxGroup.remove(child); } const S = this.S; const w = this.wallThickness; const holeR = this.holeDiameter / 2; const outerSize = S + w * 2; const hs = outerSize / 2; const shape = new THREE.Shape(); shape.moveTo(-hs, -hs); shape.lineTo(hs, -hs); shape.lineTo(hs, hs); shape.lineTo(-hs, hs); shape.lineTo(-hs, -hs); const holePath = new THREE.Path(); holePath.absarc(0, 0, holeR, 0, Math.PI * 2, false); shape.holes.push(holePath); const faceGeo = new THREE.ExtrudeGeometry(shape, { depth: w, bevelEnabled: false, curveSegments: 16 }); faceGeo.translate(0, 0, -w / 2); const boxMat = new THREE.MeshPhysicalMaterial({ color: 0x38bdf8, transparent: true, opacity: 0.18, roughness: 0.1, transmission: 0.9, thickness: w, side: THREE.DoubleSide, depthWrite: false }); const edgeMat = new THREE.LineBasicMaterial({ color: 0x38bdf8, transparent: true, opacity: 0.4 }); const ringMat = new THREE.LineBasicMaterial({ color: 0xf97316, linewidth: 2, transparent: true, opacity: 0.8 }); const ringPoints = new THREE.Path().absarc(0, 0, holeR, 0, Math.PI * 2, false).getPoints(24); const ringGeo = new THREE.BufferGeometry().setFromPoints(ringPoints); const offset = S / 2 + w / 2; const transforms = [ { pos: [0, 0, offset], rot: [0, 0, 0] }, { pos: [0, 0, -offset], rot: [0, Math.PI, 0] }, { pos: [-offset, 0, 0], rot: [0, -Math.PI / 2, 0] }, { pos: [offset, 0, 0], rot: [0, Math.PI / 2, 0] }, { pos: [0, offset, 0], rot: [-Math.PI / 2, 0, 0] }, { pos: [0, -offset, 0], rot: [Math.PI / 2, 0, 0] } ]; // 僅計算一次邊緣幾何 (6 面共享,性能提升 6 倍) const sharedEdgesGeo = new THREE.EdgesGeometry(faceGeo); transforms.forEach(t => { const mesh = new THREE.Mesh(faceGeo, boxMat); const edges = new THREE.LineSegments(sharedEdgesGeo, edgeMat); const ringOuter = new THREE.Line(ringGeo, ringMat); ringOuter.position.z = w / 2 + 0.01; const ringInner = new THREE.Line(ringGeo, ringMat); ringInner.position.z = -w / 2 - 0.01; mesh.add(ringOuter); mesh.add(ringInner); mesh.position.set(...t.pos); mesh.rotation.set(...t.rot); edges.position.copy(mesh.position); edges.rotation.copy(mesh.rotation); // 禁止盒面 Raycasting 干擾球體選取 mesh.raycast = () => { }; edges.raycast = () => { }; this.boxGroup.add(mesh); this.boxGroup.add(edges); }); // 僅在物理自由模擬模式 (Mode 1) 下才需要重建 Cannon.js 邊界牆 if (this.currentMode === 1) { this.rebuildPhysicsWalls(); } } /* ------------------------------------------------------------------ Cannon.js 6 面封閉邊界牆 ------------------------------------------------------------------ */ rebuildPhysicsWalls() { if (!this.world) return; this.wallBodies.forEach(body => this.world.remove(body)); this.wallBodies = []; const halfS = this.S / 2; const physW = 10.0; // 極度加厚物理牆壁(10cm)絕對防止高速拖曳時穿模 const halfPhysW = physW / 2; const holeD = this.holeDiameter; // 2.00 // 使用 4 個 CANNON.Box 來組成一面有方形孔洞的牆,避免穿模(Clipping) // 這樣物理引擎會真實計算球體與洞口的實體邊界碰撞 const sideLen = (this.S - holeD) / 2; // CANNON.Box dimensions are half-extents const topShape = new CANNON.Box(new CANNON.Vec3(halfS, sideLen/2, halfPhysW)); const bottomShape = new CANNON.Box(new CANNON.Vec3(halfS, sideLen/2, halfPhysW)); const leftShape = new CANNON.Box(new CANNON.Vec3(sideLen/2, holeD/2, halfPhysW)); const rightShape = new CANNON.Box(new CANNON.Vec3(sideLen/2, holeD/2, halfPhysW)); const wallDefs = [ { pos: [0, -halfS - halfPhysW, 0], rot: [Math.PI/2, 0, 0] }, // 底面 { pos: [0, halfS + halfPhysW, 0], rot: [-Math.PI/2, 0, 0] }, // 頂面 { pos: [-halfS - halfPhysW, 0, 0], rot: [0, Math.PI/2, 0] }, // 左面 { pos: [halfS + halfPhysW, 0, 0], rot: [0, -Math.PI/2, 0] }, // 右面 { pos: [0, 0, -halfS - halfPhysW], rot: [0, 0, 0] }, // 後面 { pos: [0, 0, halfS + halfPhysW], rot: [0, Math.PI, 0] } // 前面 ]; wallDefs.forEach((wd) => { const body = new CANNON.Body({ mass: 0, material: this.defaultMaterial }); // 將 4 塊形狀組合,中央剛好空出一個 holeD x holeD 的洞口 body.addShape(topShape, new CANNON.Vec3(0, halfS - sideLen/2, 0)); body.addShape(bottomShape, new CANNON.Vec3(0, -halfS + sideLen/2, 0)); body.addShape(leftShape, new CANNON.Vec3(-halfS + sideLen/2, 0, 0)); body.addShape(rightShape, new CANNON.Vec3(halfS - sideLen/2, 0, 0)); body.quaternion.setFromEuler(wd.rot[0], wd.rot[1], wd.rot[2], 'XYZ'); body.position.set(...wd.pos); this.world.addBody(body); this.wallBodies.push(body); }); } /* ------------------------------------------------------------------ 創建 6 顆剛體木球 ------------------------------------------------------------------ */ createSpheres() { while (this.spheresGroup.children.length > 0) { this.spheresGroup.remove(this.spheresGroup.children[0]); } this.spheresArr = []; this.sphereBodies = []; const r = this.r; const sphereGeo = new THREE.SphereGeometry(r, 48, 48); const matMid = new THREE.MeshPhysicalMaterial({ color: 0x10b981, roughness: 0.15, clearcoat: 0.8 }); const matTop = new THREE.MeshPhysicalMaterial({ color: 0xf43f5e, roughness: 0.15, clearcoat: 0.8 }); const matBottom = new THREE.MeshPhysicalMaterial({ color: 0x3b82f6, roughness: 0.15, clearcoat: 0.8 }); this.spheres.m1 = new THREE.Mesh(sphereGeo, matMid); this.spheres.m2 = new THREE.Mesh(sphereGeo, matMid.clone()); this.spheres.m3 = new THREE.Mesh(sphereGeo, matMid.clone()); this.spheres.m4 = new THREE.Mesh(sphereGeo, matMid.clone()); this.spheres.top = new THREE.Mesh(sphereGeo, matTop); this.spheres.bottom = new THREE.Mesh(sphereGeo, matBottom); // 陣列順序:[m1, m2, m3, m4, top, bottom] this.spheresArr = [ this.spheres.m1, this.spheres.m2, this.spheres.m3, this.spheres.m4, this.spheres.top, this.spheres.bottom ]; this.spheresArr.forEach((mesh, index) => { mesh.castShadow = true; mesh.receiveShadow = true; mesh.userData = { id: index }; this.spheresGroup.add(mesh); if (this.world) { const body = new CANNON.Body({ mass: 0.05, shape: new CANNON.Sphere(r), material: this.defaultMaterial }); body.linearDamping = 0.4; body.angularDamping = 0.4; body.collisionFilterGroup = 1; body.collisionFilterMask = -1; this.world.addBody(body); this.sphereBodies.push(body); } }); this.resetPositions(); } /* ------------------------------------------------------------------ 重設球體位置 ------------------------------------------------------------------ */ resetPositions() { this.groupRotationAngle = 0; if (this.currentMode === 1) { this.resetMode1Positions(this.mode1Config); } else { this.apply141Alignment(); } } /** * Mode 1: 根據所選配置 (141, 24, 33, 33-staggered) 擺放球體 → 自由落下靠重力 */ resetMode1Positions(config = '141') { const limit = (this.S / 2) - this.r; if (config === '141') { this.groupRotationAngle = 0; this.apply141Alignment(); } else if (config === '24') { const yTop = Math.sqrt(4 - limit * limit) - limit; const positions = [ new THREE.Vector3(-limit, -limit, -limit), new THREE.Vector3(limit, -limit, -limit), new THREE.Vector3(-limit, -limit, limit), new THREE.Vector3(limit, -limit, limit), new THREE.Vector3(0, Math.max(yTop, 0), -limit), new THREE.Vector3(0, Math.max(yTop, 0), limit) ]; this.spheresArr.forEach((mesh, i) => { mesh.position.copy(positions[i]); if (this.sphereBodies[i]) { this.sphereBodies[i].position.set(positions[i].x, positions[i].y, positions[i].z); this.sphereBodies[i].velocity.set(0, 0, 0); this.sphereBodies[i].angularVelocity.set(0, 0, 0); } }); } else if (config === '33') { const yTop = -limit + 2.0; // 有3顆球壓在另外3顆上方 const positions = [ new THREE.Vector3(-limit, -limit, -limit), new THREE.Vector3(limit, -limit, -limit), new THREE.Vector3(0, -limit, limit), new THREE.Vector3(-limit, yTop, -limit), new THREE.Vector3(limit, yTop, -limit), new THREE.Vector3(0, yTop, limit) ]; this.spheresArr.forEach((mesh, i) => { mesh.position.copy(positions[i]); if (this.sphereBodies[i]) { this.sphereBodies[i].position.set(positions[i].x, positions[i].y, positions[i].z); this.sphereBodies[i].velocity.set(0, 0, 0); this.sphereBodies[i].angularVelocity.set(0, 0, 0); } }); } else if (config === '33-staggered') { // 3-3 交錯配置:下層 3 球 (後 2 前 1),上層 3 球旋轉 180° (前 2 後 1) 並自然下沉嵌進凹槽 const r = this.r; const dy = Math.sqrt(Math.max(0, 4 * r * r - limit * limit)); const yTop = Math.min(limit, -limit + dy); const positions = [ new THREE.Vector3(-limit, -limit, -limit), // 下層後左 (綠) new THREE.Vector3(limit, -limit, -limit), // 下層後右 (綠) new THREE.Vector3(0, -limit, limit), // 下層前中 (綠) new THREE.Vector3(limit, yTop, limit), // 上層前右 (綠,與 33 正疊相比旋轉 180°) new THREE.Vector3(-limit, yTop, limit), // 上層前左 (紅) new THREE.Vector3(0, yTop, -limit) // 上層後中 (藍) ]; this.spheresArr.forEach((mesh, i) => { mesh.position.copy(positions[i]); mesh.quaternion.set(0, 0, 0, 1); if (this.sphereBodies[i]) { this.sphereBodies[i].position.set(positions[i].x, positions[i].y, positions[i].z); this.sphereBodies[i].quaternion.set(0, 0, 0, 1); this.sphereBodies[i].velocity.set(0, 0, 0); this.sphereBodies[i].angularVelocity.set(0, 0, 0); } }); this.isEscaped = false; } } /* ------------------------------------------------------------------ 1-4-1 對齊排列 正方體 8 個角 (以俯視圖為準,上面=正Y,左=負X,後=負Z): ┌───────────────────────────────────┐ │ 1號 (左上後) ──── 2號 (右上後) │ ← 頂面 (Y = +limit) │ | | │ │ 4號 (左上前) ──── 3號 (右上前) │ └───────────────────────────────────┘ ┌───────────────────────────────────┐ │ 5號 (左下後) ──── 6號 (右下後) │ ← 底面 (Y = -limit) │ | | │ │ 8號 (左下前) ──── 7號 (右下前) │ └───────────────────────────────────┘ 使用者要求綠球固定在 1, 3, 5, 7 號角落 (四面體的交替頂點) 1號: (-d, +d, -d) → 上左後 3號: (+d, +d, +d) → 上右前 5號: (-d, -d, +d) → 下左前 [修正: 使用者的 5 號是 1 號正下方] 7號: (+d, -d, -d) → 下右後 [使用者重新定義]: 5號是1號正下方 → (-d, -d, -d) 7號是3號正下方 → (+d, -d, +d) 所以 1,3,5,7 = (-d,+d,-d), (+d,+d,+d), (-d,-d,-d), (+d,-d,+d) 這正是正四面體的 4 個頂點!互相距離最遠。 綠球整組繞 Y 軸旋轉時: - 在 XZ 平面上旋轉 (x, z) 分量 - Y 分量保持不變 (±d) - 旋轉後 clamp 到盒界 [-limit, limit] - 中心洞口大小隨旋轉角度變化 - 紅藍球沿 Y 軸沉入,沉入深度由畢氏定理決定 ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ 1-4-1 斜對角排列與剛體旋轉 (嚴格防穿模) 幾何結構定義: - 4 顆綠球固定在正方體的 1, 3, 5, 7 號斜對角角落 (交替頂點,死鎖狀態): 1號: (-limit, +limit, -limit) ← 俯視圖左上後 3號: (+limit, +limit, +limit) ← 俯視圖右上前 5號: (-limit, -limit, -limit) ← 1號正下方 7號: (+limit, -limit, +limit) ← 3號正下方 - 紅球 (頂球) 與 藍球 (底球): 位於與綠球垂直的另一組對角線方向,依剛體球-球接觸約束緊貼於盒內。 - 初始狀態 (θ = 0): 6 顆球深鎖在盒子內部斜對角,絕不穿模、絕非脫出狀態! - 旋轉時: 4 顆綠球在斜對角開始轉動,紅藍球隨之在另一對角線上作動。 ------------------------------------------------------------------ */ apply141Alignment() { const S = this.S; const r = this.r; const limit = Math.max(0, (S / 2) - r); // 球心距盒壁的極限距離 // 4 顆綠球的斜對角角落 (1, 3, 5, 7 號角) const corners = [ { x: -limit, y: limit, z: -limit }, // 1號 (左上後) { x: limit, y: limit, z: limit }, // 3號 (右上前) { x: -limit, y: -limit, z: -limit }, // 5號 (左下後) { x: limit, y: -limit, z: limit } // 7號 (右下前) ]; const theta = this.groupRotationAngle; const cosT = Math.cos(theta); const sinT = Math.sin(theta); // 4 顆綠球在斜對角繞 Y 軸旋轉 XZ 分量 const rotatedCorners = corners.map(c => { let rx = c.x * cosT - c.z * sinT; let ry = c.y; let rz = c.x * sinT + c.z * cosT; // 嚴格限制在盒壁內部,絕對防止穿模 rx = THREE.MathUtils.clamp(rx, -limit, limit); ry = THREE.MathUtils.clamp(ry, -limit, limit); rz = THREE.MathUtils.clamp(rz, -limit, limit); return new THREE.Vector3(rx, ry, rz); }); // 更新 4 顆綠球位置 const greenSpheres = [this.spheres.m1, this.spheres.m2, this.spheres.m3, this.spheres.m4]; greenSpheres.forEach((mesh, i) => { if (!mesh) return; mesh.position.copy(rotatedCorners[i]); if (this.sphereBodies[i]) { this.sphereBodies[i].position.set(rotatedCorners[i].x, rotatedCorners[i].y, rotatedCorners[i].z); this.sphereBodies[i].velocity.set(0, 0, 0); this.sphereBodies[i].angularVelocity.set(0, 0, 0); } }); // 紅藍球在垂直於綠球斜對角的另一條對角線上 (Y=0) const perpX = (cosT + sinT) / Math.SQRT2; const perpZ = (sinT - cosT) / Math.SQRT2; // 二分搜尋最小合法半跨距 a (剛體球球不穿透約束) let aMin = 0; let aMax = limit * Math.SQRT2; for (let iter = 0; iter < 50; iter++) { const aMid = (aMin + aMax) / 2; const redX = aMid * perpX; const redZ = aMid * perpZ; const blueX = -redX; const blueZ = -redZ; let valid = true; // 紅藍剛體距離 >= 2r if (2 * aMid < 2 * r - 0.001) { valid = false; } // 紅球到每顆綠球剛體距離 >= 2r if (valid) { for (const p of rotatedCorners) { const dx = redX - p.x; const dy = 0 - p.y; const dz = redZ - p.z; if (dx * dx + dy * dy + dz * dz < 4 * r * r - 0.001) { valid = false; break; } } } // 藍球到每顆綠球剛體距離 >= 2r if (valid) { for (const p of rotatedCorners) { const dx = blueX - p.x; const dy = 0 - p.y; const dz = blueZ - p.z; if (dx * dx + dy * dy + dz * dz < 4 * r * r - 0.001) { valid = false; break; } } } // 嚴格在盒壁內,不可穿模 if (valid) { if (Math.abs(redX) > limit || Math.abs(redZ) > limit || Math.abs(blueX) > limit || Math.abs(blueZ) > limit) { valid = false; } } if (valid) { aMax = aMid; // 可行,嘗試更緊湊 } else { aMin = aMid; // 不可行,需增大 } } const bestA = aMax; const redPosX = THREE.MathUtils.clamp(bestA * perpX, -limit, limit); const redPosZ = THREE.MathUtils.clamp(bestA * perpZ, -limit, limit); const bluePosX = THREE.MathUtils.clamp(-bestA * perpX, -limit, limit); const bluePosZ = THREE.MathUtils.clamp(-bestA * perpZ, -limit, limit); // 臨界脫出判定:初始 θ=0 必定不可脫出; // 唯有當 S >= 4.10 且順向轉動角度達到臨界角時判定為脫出! const thetaCrit = Math.atan((2 * r) / S); this.isEscaped = (S >= 4.098 && theta >= thetaCrit * 0.88); if (this.spheres.top) { this.spheres.top.position.set(redPosX, 0, redPosZ); if (this.sphereBodies[4]) { this.sphereBodies[4].position.set(redPosX, 0, redPosZ); this.sphereBodies[4].velocity.set(0, 0, 0); } } if (this.spheres.bottom) { this.spheres.bottom.position.set(bluePosX, 0, bluePosZ); if (this.sphereBodies[5]) { this.sphereBodies[5].position.set(bluePosX, 0, bluePosZ); this.sphereBodies[5].velocity.set(0, 0, 0); } } } /* ------------------------------------------------------------------ 切換模式 Mode 1: 靠重力,OrbitControls 完全自由 (旋轉盒身讓球滾動) Mode 2/3: 無重力,盒子僅 XY 軸旋轉,綠球整組轉動 ------------------------------------------------------------------ */ setMode(mode) { this.currentMode = mode; this.isDiagonalTilted = false; this.boxGroup.rotation.set(0, 0, 0); this.spheresGroup.rotation.set(0, 0, 0); this.boxGroup.quaternion.set(0, 0, 0, 1); this.spheresGroup.quaternion.set(0, 0, 0, 1); this.groupRotationAngle = 0; this.isBoxLocked = false; if (mode === 1) { // Mode 1: 無重力, 讓使用者拖曳轉動 if (this.world) this.world.gravity.set(0, 0, 0); this.controls.enabled = true; // 開啟所有旋轉軸 this.controls.minPolarAngle = 0; this.controls.maxPolarAngle = Math.PI; this.controls.minAzimuthAngle = -Infinity; this.controls.maxAzimuthAngle = Infinity; this.resetPositions(); } else { // Mode 2 & 3: 無重力,盒子僅 XY 軸旋轉 if (this.world) this.world.gravity.set(0, 0, 0); // 限制 OrbitControls 僅 XY 旋轉 this.controls.enabled = true; this.apply141Alignment(); } } /* ------------------------------------------------------------------ 導出球體座標狀態 (供 Mode 3 剖面圖隨動渲染使用) ------------------------------------------------------------------ */ getSpherePositions() { return { m1: this.spheres.m1.position.clone(), m2: this.spheres.m2.position.clone(), m3: this.spheres.m3.position.clone(), m4: this.spheres.m4.position.clone(), top: this.spheres.top.position.clone(), bottom: this.spheres.bottom.position.clone() }; } /* ------------------------------------------------------------------ 視角縮放控制 ------------------------------------------------------------------ */ zoomIn() { if (this.camera) this.camera.position.multiplyScalar(0.85); } zoomOut() { if (this.camera) this.camera.position.multiplyScalar(1.18); } resetZoom() { if (!this.camera || !this.controls) return; const startPos = this.camera.position.clone(); const endPos = new THREE.Vector3(16, 12, 18); const startTarget = this.controls.target.clone(); const endTarget = new THREE.Vector3(0, 0, 0); const duration = 750; // 毫秒平滑補間 const startTime = performance.now(); this.controls.enabled = false; // 動畫期間暫時鎖定使用者手動干涉 const animateCamera = (now) => { const elapsed = now - startTime; const progress = Math.min(elapsed / duration, 1.0); // easeInOutCubic 緩動曲線 const ease = progress < 0.5 ? 4 * progress * progress * progress : 1 - Math.pow(-2 * progress + 2, 3) / 2; this.camera.position.lerpVectors(startPos, endPos, ease); this.controls.target.lerpVectors(startTarget, endTarget, ease); if (progress < 1.0) { requestAnimationFrame(animateCamera); } else { this.camera.position.copy(endPos); this.controls.target.copy(endTarget); this.controls.enabled = !this.isBoxLocked; } }; requestAnimationFrame(animateCamera); } /* ------------------------------------------------------------------ 固定 / 解鎖盒子旋轉 (Lock Box Toggle) ------------------------------------------------------------------ */ toggleLockBox() { this.isBoxLocked = !this.isBoxLocked; this.controls.enabled = !this.isBoxLocked; return this.isBoxLocked; } /* ------------------------------------------------------------------ 體對角線傾斜解鎖 Toggle (Mode 2) ------------------------------------------------------------------ */ toggleDiagonalTilt() { if (this.currentMode !== 2) return; this.isDiagonalTilted = !this.isDiagonalTilted; } /* ------------------------------------------------------------------ 動態調校內徑 S (採用 rAF 調度,球體即時跟隨,盒身流暢重構) ------------------------------------------------------------------ */ setInnerSize(S) { this.S = S; // 球體座標向量運算超輕量 (<0.05ms),即時同步保證零延遲視覺反饋 if (this.currentMode === 2 || this.currentMode === 3) { this.apply141Alignment(); } // 盒身 3D 重構採用 rAF 節流,每幀最多執行一次,徹底消除滑鼠拖曳卡頓 if (this.rebuildBoxRaf) cancelAnimationFrame(this.rebuildBoxRaf); this.rebuildBoxRaf = requestAnimationFrame(() => { this.rebuildBox(); this.rebuildBoxRaf = null; }); } /* ------------------------------------------------------------------ 拖曳控制 (Mode 1 抓球 / Mode 2,3 旋轉綠球組) ------------------------------------------------------------------ */ setupDragControls() { const dom = this.renderer.domElement; dom.addEventListener('pointerdown', (e) => { const rect = dom.getBoundingClientRect(); this.mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1; this.mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1; if (this.currentMode === 1) { // 模式一:取消單顆球拖曳,完全依賴 OrbitControls 旋轉視角(模擬旋轉盒子) return; } // Mode 2/3: 在固定盒子時開始拖曳旋轉 if (this.isBoxLocked) { this.isDragging = true; this.controls.enabled = false; this.lastMousePos.set(e.clientX, e.clientY); if (dom.setPointerCapture) { try { dom.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ } } } }); dom.addEventListener('pointermove', (e) => { if (!this.isDragging) return; if (this.currentMode === 1 && this.isBoxLocked) { // 如果是 141,完全走模式二/三的數學運算機制 if (this.mode1Config === '141') { if (this.S <= 4.00) return; this.groupRotationAngle += dx * 0.008; this.apply141Alignment(); return; } // 模式一:固定盒子後,拖曳可以對群體球施加切線速度,模擬整組轉動 const speedX = dy * 5.0; // 降低拖曳力道防止穿模 const speedY = dx * 5.0; const omega = new CANNON.Vec3(speedX, speedY, 0); this.sphereBodies.forEach(body => { const rVec = new CANNON.Vec3(body.position.x, body.position.y, body.position.z); const v = omega.cross(rVec); // 施加速度讓球體隨拖曳旋轉 body.velocity.set(v.x, v.y, v.z); // 為了視覺效果,也可以加一點角速度 body.angularVelocity.set(speedX, speedY, 0); }); return; } if (this.currentMode === 2 || this.currentMode === 3) { const dx = e.clientX - this.lastMousePos.x; this.lastMousePos.set(e.clientX, e.clientY); this.groupRotationAngle += dx * 0.008; // 物理臨界相切角 θ_crit = atan(2r / S) const thetaCrit = Math.atan((2 * this.r) / this.S); // 步驟二:S=4.00cm 允許微幅轉動約 0.08 rad (約 4.6°),轉沒多少撞壁卡死 let maxThetaPos; if (this.S <= 4.00) { maxThetaPos = 0.08; } else if (this.S < 4.098) { const t = (this.S - 4.00) / (4.10 - 4.00); maxThetaPos = 0.08 + t * (thetaCrit * 0.88 - 0.08); } else { maxThetaPos = thetaCrit * 1.35; } // 逆向極限:受封閉頂壁阻擋卡死 const minThetaNeg = -0.08 - Math.min(0.04, Math.max(0, (this.S - 4.00) * 0.4)); if (this.groupRotationAngle > maxThetaPos) { this.groupRotationAngle = maxThetaPos; if (!this.isEscaped && window.showToastMessage) { if (this.S <= 4.00) { window.showToastMessage('⚠️ 空間不足卡死!S=4.00cm 剛體微轉即撞壁'); } else { window.showToastMessage('⚠️ 剛體撞擊孔壁!空間不足未達脫出角度'); } } } if (this.groupRotationAngle < minThetaNeg) { this.groupRotationAngle = minThetaNeg; if (window.showToastMessage) window.showToastMessage('⚠️ 剛體撞擊封閉頂壁!反向無出口通道卡死'); } this.apply141Alignment(); // 觸發全域事件讓 UI 即時更新狀態 if (window.onSimulatorRotationUpdate) { window.onSimulatorRotationUpdate(this.getSpherePositions(), this.groupRotationAngle, this.isEscaped); } } }); const stopDrag = (e) => { if (this.isDragging) { this.isDragging = false; this.draggedSphere = null; if (dom.releasePointerCapture && e && e.pointerId) { try { dom.releasePointerCapture(e.pointerId); } catch (err) { /* ignore */ } } if (!this.isBoxLocked) { this.controls.enabled = true; } } }; dom.addEventListener('pointerup', stopDrag); dom.addEventListener('pointerleave', stopDrag); } /* ------------------------------------------------------------------ 視窗 Resize ------------------------------------------------------------------ */ onWindowResize() { if (!this.container || !this.renderer || !this.camera) return; const w = this.container.clientWidth; const h = this.container.clientHeight || 540; // 防禦性檢查:若容器隱藏 (寬或高為 0),避免寫入 NaN 破壞投影矩陣與畫布 if (w <= 0 || h <= 0) return; this.camera.aspect = w / h; this.camera.updateProjectionMatrix(); this.renderer.setSize(w, h); } /* ------------------------------------------------------------------ 主動畫迴圈 ------------------------------------------------------------------ */ animate() { requestAnimationFrame(this.animate); this.animTime += 0.015; // Mode 1: 物理模擬 (Cannon.js step) if (this.currentMode === 1 && this.world) { this.world.step(1 / 60); this.spheresArr.forEach((mesh, i) => { if (this.sphereBodies[i]) { mesh.position.copy(this.sphereBodies[i].position); mesh.quaternion.copy(this.sphereBodies[i].quaternion); } }); } // Mode 2 體對角線傾斜解鎖旋轉 if (this.currentMode === 2 && this.isDiagonalTilted) { const axis = new THREE.Vector3(1, 1, 1).normalize(); const targetRot = Math.PI / 3; this.boxGroup.quaternion.slerp(new THREE.Quaternion().setFromAxisAngle(axis, targetRot), 0.05); this.spheresGroup.quaternion.slerp(new THREE.Quaternion().setFromAxisAngle(axis, targetRot), 0.05); } else if (this.currentMode === 2 && !this.isDiagonalTilted) { this.boxGroup.quaternion.slerp(new THREE.Quaternion(0, 0, 0, 1), 0.08); this.spheresGroup.quaternion.slerp(new THREE.Quaternion(0, 0, 0, 1), 0.08); } this.controls.update(); this.renderer.render(this.scene, this.camera); } } // 導出全域物件 window.Tower3DSimulator = Tower3DSimulator;