/** * MuJoCo Cartpole Inverted Pendulum Physics Simulator * Nonlinear Rigid Body Dynamics with Runge-Kutta 4th Order (RK4) Integration * & Multi-Mode State Feedback (PD / LQR) Control */ // ========================================== // 1. 물리 파라미터 (MuJoCo XML 일치 모델) // ========================================== const physicsConfig = { M: 1.0, // 수레 질량 (kg) m: 0.1, // 막대 질량 (kg) L: 1.0, // 막대 전체 길이 (m) l: 0.5, // 회전축에서 질량중심까지 거리 (L/2 = 0.5m) I: (1/12) * 0.1 * (1.0 * 1.0), // 질량중심 기준 막대 관성모멘트 (kg·m²) g: 9.81, // 중력 가속도 (m/s²) bc: 0.1, // 수레 슬라이드 감쇠계수 (damping) (Ns/m) bp: 0.01, // 힌지 회전 감쇠계수 (damping) (Nms/rad) gear: 10.0, // 모터 기어비 (u in [-1, 1] -> Force = gear * u) dt: 0.01, // 적분 스텝 (s) - 100Hz substeps: 4 // 프레임당 서브스텝 수 }; // 시스템 상태: [x, v, theta, omega, u, time] // x: 수레 위치 (m), v: 수레 속도 (m/s) // theta: 막대 각도 (rad) [수직 직립=0, 오른쪽 기울어짐 > 0], omega: 각속도 (rad/s) let state = { x: 0.0, v: 0.0, theta: 0.15, // MuJoCo 코드와 동일하게 초기 0.15 rad (약 8.6도) 기울임 omega: 0.0, u: 0.0, time: 0.0 }; // 제어 설정 let controlSettings = { mode: 'pd', // 'pd', 'lqr', 'none' k_theta: 8.0, k_omega: 1.6, k_x: 0.3, k_v: 0.6 }; let isRunning = true; let isGraphVisible = true; // ========================================== // 2. 비선형 운동방정식 (Nonlinear ODE) // ========================================== function getDerivatives(s, uForce) { const { M, m, l, I, g, bc, bp } = physicsConfig; const x = s.x || 0; const v = s.v || 0; const th = s.theta || 0; const w = s.omega || 0; const sinTh = Math.sin(th); const cosTh = Math.cos(th); // 일반화 질량 행렬 성분: // [ m11 m12 ] [ x_ddot ] = [ f1 ] // [ m21 m22 ] [ th_ddot ] [ f2 ] const m11 = M + m; const m12 = m * l * cosTh; const m21 = m * l * cosTh; const m22 = I + m * l * l; // 우변 일반화 힘 벡터: const f1 = uForce - bc * v + m * l * (w * w) * sinTh; const f2 = m * g * l * sinTh - bp * w; // 판별식 (행렬식) const det = m11 * m22 - m12 * m21; if (Math.abs(det) < 1e-7) { return { dx: v, dv: 0, dtheta: w, domega: 0 }; } // 2x2 역행렬 곱: const x_ddot = (m22 * f1 - m12 * f2) / det; const th_ddot = (-m21 * f1 + m11 * f2) / det; return { dx: v, dv: x_ddot, dtheta: w, domega: th_ddot }; } // 4차 룽게-쿠타 (RK4) 수치 적분기 function rk4Step(s, uForce, dt) { const k1 = getDerivatives(s, uForce); const s2 = { x: s.x + 0.5 * dt * k1.dx, v: s.v + 0.5 * dt * k1.dv, theta: s.theta + 0.5 * dt * k1.dtheta, omega: s.omega + 0.5 * dt * k1.domega }; const k2 = getDerivatives(s2, uForce); const s3 = { x: s.x + 0.5 * dt * k2.dx, v: s.v + 0.5 * dt * k2.dv, theta: s.theta + 0.5 * dt * k2.dtheta, omega: s.omega + 0.5 * dt * k2.domega }; const k3 = getDerivatives(s3, uForce); const s4 = { x: s.x + dt * k3.dx, v: s.v + dt * k3.dv, theta: s.theta + dt * k3.dtheta, omega: s.omega + dt * k3.domega }; const k4 = getDerivatives(s4, uForce); return { x: s.x + (dt / 6) * (k1.dx + 2 * k2.dx + 2 * k3.dx + k4.dx), v: s.v + (dt / 6) * (k1.dv + 2 * k2.dv + 2 * k3.dv + k4.dv), theta: s.theta + (dt / 6) * (k1.dtheta + 2 * k2.dtheta + 2 * k3.dtheta + k4.dtheta), omega: s.omega + (dt / 6) * (k1.domega + 2 * k2.domega + 2 * k3.domega + k4.domega), u: s.u || 0.0, time: (s.time || 0.0) + dt }; } // 제어 입력 계산 function computeControl(s) { if (controlSettings.mode === 'none') { return 0.0; } const th = s.theta || 0; const w = s.omega || 0; const x = s.x || 0; const v = s.v || 0; let u = 0.0; if (controlSettings.mode === 'pd') { // 사용자의 MuJoCo 원본 제어 수식: // np.clip(8 * th + 1.6 * w + 0.3 * x + 0.6 * v, -1, 1) u = controlSettings.k_theta * th + controlSettings.k_omega * w + controlSettings.k_x * x + controlSettings.k_v * v; } else if (controlSettings.mode === 'lqr') { // LQR 상태 피드백 게인 const K_lqr = [1.73, 2.85, 24.8, 6.42]; u = (K_lqr[2] * th + K_lqr[3] * w + K_lqr[0] * x + K_lqr[1] * v) / physicsConfig.gear; } // 액추에이터 포화 (Saturation: [-1, 1]) if (isNaN(u)) u = 0.0; return Math.max(-1.0, Math.min(1.0, u)); } // 전체 역학적 에너지 계산 (E = T + V) function computeTotalEnergy(s) { const { M, m, l, I, g } = physicsConfig; const cosTh = Math.cos(s.theta || 0); const v = s.v || 0; const w = s.omega || 0; // 운동에너지 T const T = 0.5 * (M + m) * v * v + m * l * v * w * cosTh + 0.5 * (I + m * l * l) * w * w; // 위치에너지 V (기준점: 힌지 높이 y=0 일 때 수직 맨 위 l cos(theta)) const V = m * g * l * cosTh; return T + V; } // ========================================== // 3. Three.js 3D 렌더링 씬 구성 (표준 Y-up 좌표계) // ========================================== let scene, camera, renderer, controls; let cartMesh, poleMesh, trackMesh, forceArrowMesh; const railY = 1.35; // 자유 낙하 시 막대가 아래로 처져도 바닥 및 하단 패널에 가리지 않는 넉넉한 높이 const railZ = -0.55; // 화면 뒤쪽으로 이동하여 전면 UI 패널과의 간격 확보 function initThree() { const container = document.getElementById('canvas-container'); const width = container.clientWidth || 800; const height = container.clientHeight || 600; // 1. Scene scene = new THREE.Scene(); scene.background = new THREE.Color(0x0a0e17); scene.fog = new THREE.FogExp2(0x0a0e17, 0.035); // 2. Camera (Y-up 표준 좌표계: 카트폴 전체가 한눈에 들어오는 넉넉한 시야각) camera = new THREE.PerspectiveCamera(46, width / height, 0.1, 100); camera.position.set(0, 2.3, 4.6); // 3. Renderer renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setSize(width, height); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; container.innerHTML = ''; // 기존 캔버스 제거 container.appendChild(renderer.domElement); // 4. OrbitControls controls = new THREE.OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.dampingFactor = 0.05; controls.target.set(0, 1.35, railZ); // 카트폴 중앙 응시 controls.maxPolarAngle = Math.PI / 2 - 0.02; // 바닥 관통 방지 controls.update(); // 5. 조명 const ambientLight = new THREE.AmbientLight(0xffffff, 0.65); scene.add(ambientLight); const mainLight = new THREE.DirectionalLight(0xffffff, 0.9); mainLight.position.set(3, 6, 4); mainLight.castShadow = true; mainLight.shadow.mapSize.width = 2048; mainLight.shadow.mapSize.height = 2048; mainLight.shadow.camera.near = 0.5; mainLight.shadow.camera.far = 15; mainLight.shadow.camera.left = -4; mainLight.shadow.camera.right = 4; mainLight.shadow.camera.top = 4; mainLight.shadow.camera.bottom = -4; scene.add(mainLight); const fillLight = new THREE.PointLight(0x00f0ff, 0.5, 10); fillLight.position.set(-3, 2, 2); scene.add(fillLight); // 6. MuJoCo 스타일 바닥 그리드 및 평면 (XZ 평면) const gridHelper = new THREE.GridHelper(12, 24, 0x00f0ff, 0x1e293b); gridHelper.position.set(0, 0, 0); scene.add(gridHelper); const floorGeo = new THREE.PlaneGeometry(16, 16); const floorMat = new THREE.MeshStandardMaterial({ color: 0x0d121d, roughness: 0.9, metalness: 0.1 }); const floor = new THREE.Mesh(floorGeo, floorMat); floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor); // 7. 가이드 레일 및 메탈 스탠드 기둥 const trackGeo = new THREE.BoxGeometry(5.2, 0.04, 0.04); const trackMat = new THREE.MeshStandardMaterial({ color: 0x64748b, metalness: 0.7, roughness: 0.3 }); trackMesh = new THREE.Mesh(trackGeo, trackMat); trackMesh.position.set(0, railY, railZ); trackMesh.castShadow = true; scene.add(trackMesh); // 레일 받침대 다리 기둥 3개 (좌, 우, 중앙) const legGeo = new THREE.CylinderGeometry(0.035, 0.045, railY, 16); const legMat = new THREE.MeshStandardMaterial({ color: 0x334155, metalness: 0.8, roughness: 0.4 }); [-2.5, 0, 2.5].forEach(posX => { const leg = new THREE.Mesh(legGeo, legMat); leg.position.set(posX, railY / 2, railZ); leg.castShadow = true; scene.add(leg); // 베이스 플레이트 const baseGeo = new THREE.CylinderGeometry(0.12, 0.14, 0.02, 16); const base = new THREE.Mesh(baseGeo, legMat); base.position.set(posX, 0.01, railZ); base.receiveShadow = true; scene.add(base); }); // 레일 양끝 스토퍼 const stopperGeo = new THREE.CylinderGeometry(0.06, 0.06, 0.12, 16); const stopperMat = new THREE.MeshStandardMaterial({ color: 0xef4444 }); const stopperL = new THREE.Mesh(stopperGeo, stopperMat); stopperL.position.set(-2.6, railY, railZ); scene.add(stopperL); const stopperR = stopperL.clone(); stopperR.position.set(2.6, railY, railZ); scene.add(stopperR); // 8. 수레 (Cart: 너비 0.4, 높이 0.16, 깊이 0.24) const cartGeo = new THREE.BoxGeometry(0.4, 0.16, 0.24); const cartMat = new THREE.MeshStandardMaterial({ color: 0xf1f5f9, metalness: 0.4, roughness: 0.25 }); cartMesh = new THREE.Mesh(cartGeo, cartMat); cartMesh.position.set(0, railY, railZ); cartMesh.castShadow = true; cartMesh.receiveShadow = true; scene.add(cartMesh); // 수레 전면 네온 뱃지 const badgeGeo = new THREE.BoxGeometry(0.42, 0.03, 0.02); const badgeMat = new THREE.MeshBasicMaterial({ color: 0x00f0ff }); const badge = new THREE.Mesh(badgeGeo, badgeMat); badge.position.set(0, 0, 0.125); cartMesh.add(badge); // 9. 막대 (Pole: 길이 1.0m, 지름 0.06m) // 수레 힌지 위치: 수레 중심 상단 (Y = 0.08) const poleGroup = new THREE.Group(); poleGroup.position.set(0, 0.08, 0); const poleRadius = 0.03; const poleLength = physicsConfig.L; // 1.0m const cylinderGeo = new THREE.CylinderGeometry(poleRadius, poleRadius, poleLength, 24); const sphereGeo = new THREE.SphereGeometry(poleRadius, 24, 16); const poleMat = new THREE.MeshStandardMaterial({ color: 0xf59e0b, metalness: 0.2, roughness: 0.2, emissive: 0xd97706, emissiveIntensity: 0.2 }); const cylinder = new THREE.Mesh(cylinderGeo, poleMat); cylinder.castShadow = true; cylinder.position.set(0, poleLength / 2, 0); // Y축 위로 세우기 const sphereBottom = new THREE.Mesh(sphereGeo, poleMat); sphereBottom.castShadow = true; const sphereTop = new THREE.Mesh(sphereGeo, poleMat); sphereTop.position.set(0, poleLength, 0); sphereTop.castShadow = true; poleGroup.add(cylinder); poleGroup.add(sphereBottom); poleGroup.add(sphereTop); // 힌지 회전 베어링 축 (Z축 방향) const hingePivotGeo = new THREE.CylinderGeometry(0.04, 0.04, 0.32, 16); const hingePivotMat = new THREE.MeshStandardMaterial({ color: 0x334155, metalness: 0.8 }); const hingePivot = new THREE.Mesh(hingePivotGeo, hingePivotMat); hingePivot.rotation.x = Math.PI / 2; poleGroup.add(hingePivot); cartMesh.add(poleGroup); poleMesh = poleGroup; // 10. 제어력 / 외란 가시화 화살표 const arrowDir = new THREE.Vector3(1, 0, 0); forceArrowMesh = new THREE.ArrowHelper(arrowDir, new THREE.Vector3(0, railY, railZ), 0.5, 0x00f0ff, 0.14, 0.09); scene.add(forceArrowMesh); // 윈도우 리사이즈 리스너 window.addEventListener('resize', onWindowResize); } function onWindowResize() { const container = document.getElementById('canvas-container'); if (!container || !renderer || !camera) return; const width = container.clientWidth; const height = container.clientHeight; if (width === 0 || height === 0) return; camera.aspect = width / height; camera.updateProjectionMatrix(); renderer.setSize(width, height); } // ========================================== // 4. 실시간 오실로스코프 그래프 (Canvas) // ========================================== const historyLength = 240; const historyData = { theta: new Array(historyLength).fill(0), x: new Array(historyLength).fill(0), force: new Array(historyLength).fill(0) }; function updateOscilloscope(theta, x, force) { historyData.theta.shift(); historyData.theta.push(theta || 0); historyData.x.shift(); historyData.x.push(x || 0); historyData.force.shift(); historyData.force.push(force || 0); if (!isGraphVisible) return; const canvas = document.getElementById('oscilloscopeCanvas'); if (!canvas) return; const ctx = canvas.getContext('2d'); const w = canvas.width; const h = canvas.height; ctx.clearRect(0, 0, w, h); // 배경 격자선 ctx.strokeStyle = 'rgba(255, 255, 255, 0.06)'; ctx.lineWidth = 1; ctx.beginPath(); for (let y = 20; y < h; y += 25) { ctx.moveTo(0, y); ctx.lineTo(w, y); } for (let gx = 0; gx < w; gx += 50) { ctx.moveTo(gx, 0); ctx.lineTo(gx, h); } ctx.stroke(); // 중앙 0 기준선 const midY = h / 2; ctx.strokeStyle = 'rgba(255, 255, 255, 0.18)'; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(0, midY); ctx.lineTo(w, midY); ctx.stroke(); ctx.setLineDash([]); // 선 그리기 함수 function drawLine(arr, color, scale) { ctx.strokeStyle = color; ctx.lineWidth = 2; ctx.beginPath(); for (let i = 0; i < arr.length; i++) { const px = (i / (historyLength - 1)) * w; const py = midY - arr[i] * scale; if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); } ctx.stroke(); } // theta (rad): ±1.0 rad 기준 스케일 drawLine(historyData.theta, '#00f0ff', 70); // x (m): ±2.0 m 기준 스케일 drawLine(historyData.x, '#f43f5e', 35); // force (N): ±10 N 기준 스케일 drawLine(historyData.force, '#fbbf24', 5); } // ========================================== // 5. 시뮬레이션 루프 // ========================================== function animate() { requestAnimationFrame(animate); if (isRunning) { const subDt = physicsConfig.dt / physicsConfig.substeps; for (let s = 0; s < physicsConfig.substeps; s++) { const u = computeControl(state); state.u = u; const force = u * physicsConfig.gear; state = rk4Step(state, force, subDt); // 수레 레일 한계 소프트 바운스 (±2.3m) if (Math.abs(state.x) > 2.3) { state.x = Math.sign(state.x) * 2.3; state.v = -state.v * 0.3; // 반발계수 0.3 } } } // Three.js 3D 모델 업데이트 if (cartMesh) { // 1. 수레 위치 (X축 이동, 높이 railY, 깊이 railZ) cartMesh.position.set(state.x, railY, railZ); // 2. 막대 회전각 (Z축 중심 회전) // theta = 0 일 때 수직(+Y), 오른쪽 기울어짐(theta > 0)일 때 시계방향(-Z 회전) if (poleMesh) { poleMesh.rotation.z = -state.theta; } // 3. 힘 화살표 const totalForce = (state.u || 0) * physicsConfig.gear; if (forceArrowMesh) { forceArrowMesh.position.set(state.x, railY, railZ); if (Math.abs(totalForce) > 0.05) { forceArrowMesh.visible = true; forceArrowMesh.setDirection(new THREE.Vector3(Math.sign(totalForce), 0, 0)); forceArrowMesh.setLength(Math.min(1.2, Math.abs(totalForce) * 0.1), 0.1, 0.06); } else { forceArrowMesh.visible = false; } } } // 4. UI 텔레메트리 업데이트 (안전한 기본값 처리) const deg = ((state.theta || 0) * 180 / Math.PI).toFixed(2); const xVal = (state.x || 0).toFixed(2); const omegaVal = (state.omega || 0).toFixed(2); const uVal = (state.u !== undefined ? state.u : 0).toFixed(2); const energyVal = (computeTotalEnergy(state) || 0).toFixed(2); const elTheta = document.getElementById('valTheta'); const elX = document.getElementById('valX'); const elOmega = document.getElementById('valOmega'); const elCtrl = document.getElementById('valCtrl'); const elEnergy = document.getElementById('valEnergy'); if (elTheta) elTheta.textContent = `${deg}°`; if (elX) elX.textContent = `${xVal} m`; if (elOmega) elOmega.textContent = `${omegaVal} rad/s`; if (elCtrl) elCtrl.textContent = `${uVal}`; if (elEnergy) elEnergy.textContent = `${energyVal} J`; // 프로그레스 바 (-45도 ~ +45도 범위) const barTheta = document.getElementById('barTheta'); const barX = document.getElementById('barX'); if (barTheta) { const thetaPct = Math.max(0, Math.min(100, 50 + (state.theta / (Math.PI / 4)) * 50)); barTheta.style.width = `${thetaPct}%`; } if (barX) { const xPct = Math.max(0, Math.min(100, 50 + (state.x / 2.3) * 50)); barX.style.width = `${xPct}%`; } // 오실로스코프 그래프 갱신 const totalForce = (state.u || 0) * physicsConfig.gear; updateOscilloscope(state.theta, state.x, totalForce); if (controls) controls.update(); if (renderer && scene && camera) { renderer.render(scene, camera); } } // ========================================== // 6. UI 이벤트 리스너 바인딩 // ========================================== function setupEvents() { // 재생 / 일시정지 const btnPlayPause = document.getElementById('btnPlayPause'); if (btnPlayPause) { btnPlayPause.addEventListener('click', () => { isRunning = !isRunning; const playIcon = document.getElementById('playIcon'); if (playIcon) playIcon.textContent = isRunning ? '⏸' : '▶'; }); } // 리셋 const btnReset = document.getElementById('btnReset'); if (btnReset) { btnReset.addEventListener('click', () => { state.x = 0.0; state.v = 0.0; state.theta = 0.15; // 0.15 rad state.omega = 0.0; state.u = 0.0; state.time = 0.0; }); } // 외란 인가 (Impulse) const btnPushLeft = document.getElementById('btnPushLeft'); if (btnPushLeft) { btnPushLeft.addEventListener('click', () => { state.v = (state.v || 0) - 1.8; // 수레에 왼쪽 속도 급격 인가 }); } const btnPushRight = document.getElementById('btnPushRight'); if (btnPushRight) { btnPushRight.addEventListener('click', () => { state.v = (state.v || 0) + 1.8; // 수레에 오른쪽 속도 급격 인가 }); } const btnTiltPole = document.getElementById('btnTiltPole'); if (btnTiltPole) { btnTiltPole.addEventListener('click', () => { state.theta = (state.theta || 0) + (Math.random() > 0.5 ? 0.35 : -0.35); // 막대 각도 20도 외란 }); } // 그래프 패널 토글 const btnToggleGraph = document.getElementById('btnToggleGraph'); const graphPanel = document.getElementById('graphPanel'); if (btnToggleGraph && graphPanel) { btnToggleGraph.addEventListener('click', () => { isGraphVisible = !isGraphVisible; if (isGraphVisible) { graphPanel.classList.remove('hidden'); } else { graphPanel.classList.add('hidden'); } }); } // 제어 모드 탭 const modeChips = document.querySelectorAll('.mode-chip'); const formulaDisplay = document.getElementById('formulaDisplay'); modeChips.forEach(chip => { chip.addEventListener('click', () => { modeChips.forEach(c => c.classList.remove('active')); chip.classList.add('active'); controlSettings.mode = chip.dataset.mode; if (!formulaDisplay) return; if (controlSettings.mode === 'pd') { formulaDisplay.innerHTML = `u = clip(8.0·θ + 1.6·ω + 0.3·x + 0.6·v, -1, 1)사람이 짠 규칙: 기울어진 쪽으로 수레를 밀어 복원 토크 유도`; } else if (controlSettings.mode === 'lqr') { formulaDisplay.innerHTML = `u = -K·x = -(1.73·x + 2.85·v + 24.8·θ + 6.42·ω) / gearLQR 최적 제어: Riccati 해 기반 상태 피드백`; } else { formulaDisplay.innerHTML = `u = 0 (제어 끄기)자연 중력 및 관성에 의한 비선형 역진자 자유 낙하`; } }); }); // 슬라이더 바인딩 const setupSlider = (id, displayId, objKey) => { const slider = document.getElementById(id); const display = document.getElementById(displayId); if (!slider || !display) return; slider.addEventListener('input', (e) => { const val = parseFloat(e.target.value); controlSettings[objKey] = val; display.textContent = val.toFixed(1); }); }; setupSlider('gainTheta', 'dispGainTheta', 'k_theta'); setupSlider('gainOmega', 'dispGainOmega', 'k_omega'); setupSlider('gainX', 'dispGainX', 'k_x'); setupSlider('gainV', 'dispGainV', 'k_v'); const gearSlider = document.getElementById('actuatorGear'); const dispGear = document.getElementById('dispGear'); if (gearSlider && dispGear) { gearSlider.addEventListener('input', (e) => { const val = parseFloat(e.target.value); physicsConfig.gear = val; dispGear.textContent = val.toFixed(1); }); } // 모달 창 열기/닫기 const btnOpenReport = document.getElementById('btnOpenReport'); const btnCloseModal = document.getElementById('btnCloseModal'); const reportModal = document.getElementById('reportModal'); if (btnOpenReport && reportModal) { btnOpenReport.addEventListener('click', () => { loadReportContent(); reportModal.classList.add('open'); }); } if (btnCloseModal && reportModal) { btnCloseModal.addEventListener('click', () => { reportModal.classList.remove('open'); }); } if (reportModal) { reportModal.addEventListener('click', (e) => { if (e.target === reportModal) { reportModal.classList.remove('open'); } }); } } // 모달 보고서 내용 렌더링 function loadReportContent() { const contentEl = document.getElementById('modalReportContent'); if (!contentEl) return; contentEl.innerHTML = `

1. 개요 및 연구 목적

카트폴(Cart-Pole, Inverted Pendulum on a Cart) 시스템은 대표적인 비선형(Nonlinear), 저구동(Underactuated), 본질적 불안정(Inherently Unstable) 동역학 시스템입니다. 모터는 수레(Cart)의 수평 병진 운동만을 직접 구동할 수 있으며, 회전 조인트로 연결된 막대(Pole)는 액추에이터가 직접 토크를 주지 않는 저구동 자유도를 가집니다. 본 시뮬레이터는 MuJoCo 물리 엔진의 XML 규격과 동일한 역학 파라미터를 기반으로 고정밀 RK4 적분기를 통해 구축되었으며, 사람이 직관으로 설계한 PD 피드백 제어 법칙의 물리적 유효성을 분석합니다.

2. 라그랑주 역학(Lagrangian Mechanics)을 통한 운동방정식 유도

일반화 좌표계로 수레 위치 $x$와 막대의 연직 기준 회전각 $\theta$를 설정합니다.

[시스템 운동방정식]
(M + m)ẍ + (ml cosθ)θ̈ = F - b_cẋ + ml θ̇² sinθ
(ml cosθ)ẍ + (I + ml²)θ̈ = mgl sinθ - b_p θ̇
    

여기서 $M=1.0\\text{kg}$은 수레 질량, $m=0.1\\text{kg}$은 막대 질량, $l=0.5\\text{m}$은 무게중심까지 거리, $b_c, b_p$는 각각 수레 슬라이드 및 힌지 마찰 감쇠계수입니다.

3. "기울어진 쪽으로 민다"의 물리적 직관과 관성력 역학

막대가 오른쪽으로 $\theta > 0$ 기울어졌을 때, 중력 $mg$에 의한 토크 $\\tau_g = mgl\\sin\\theta$는 막대를 시계 방향(더 넘어지는 방향)으로 가속시킵니다. 이를 상쇄하기 위해 수레를 오른쪽($\\ddot{x} > 0$)으로 급가속하면, 가속 좌표계(비관성계)에서 막대의 질량중심은 왼쪽 방향으로 관성력(Fictitious Force) $F_{inertial} = -m\\ddot{x}$를 받게 됩니다. 이 관성력이 힌지 축에 대해 형성하는 역토크 $\\tau_{inertial} = -m\\ddot{x} l \\cos\\theta$가 중력 토크를 제압하여 막대를 연직 방향($\\theta \\to 0$)으로 일으켜 세웁니다.

4. 상태 피드백 제어 규칙 분석

코드에 정의된 제어 법칙은 다음과 같습니다:

u = clip(8·θ + 1.6·θ̇ + 0.3·x + 0.6·ẋ, -1, 1),   Force F = u × gear (gear=10)

5. 선형화 및 LQR 최적 제어기와의 비교

수직 평형점 $(\\theta \\approx 0, \\dot{\\theta} \\approx 0)$ 근방에서 테일러 전개 소각 근사($\\sin\\theta \\approx \\theta, \\cos\\theta \\approx 1$)를 취하면 상태공간 선형 모델 $\\dot{\\mathbf{x}} = A\\mathbf{x} + B u$를 얻습니다. 인간이 경험적으로 조율한 규칙 기반 게인은 이 선형 시스템의 모든 폐루프 극점(Closed-Loop Poles)을 좌반평면(LHP, Stable Region)에 안정적으로 배치하고 있음을 수학적으로 입증할 수 있습니다.

`; } // ========================================== // 7. 진입점 초기화 // ========================================== window.addEventListener('DOMContentLoaded', () => { initThree(); setupEvents(); animate(); });