EcoSphere Nusantara — Lab Ekologi AR, VR & GenAI
tailwind.config = {
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
display: ['Plus Jakarta Sans', 'sans-serif'],
},
colors: {
emerald: {
850: '#064e3b',
950: '#022c22',
}
}
}
}
}
body {
background-color: #f0f7f4;
color: #0f172a;
overflow-x: hidden;
}
/* Custom scrollbar */
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: #e2e8f0; }
::-webkit-scrollbar-thumb { background: #059669; border-radius: 9999px; }
/* Animasi pulsing hotspot */
@keyframes pulse-ring {
0% { transform: scale(0.8); opacity: 0.8; }
100% { transform: scale(2.2); opacity: 0; }
}
.hotspot-pulse::before {
content: '';
position: absolute;
inset: -4px;
border-radius: 9999px;
border: 2px solid #059669;
animation: pulse-ring 1.8s cubic-bezier(0.215, 0.61, 0.355, 1) infinite;
}
/* Light Glassmorphism panel dengan kontras tinggi */
.glass-panel {
background: rgba(255, 255, 255, 0.92);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid #cbd5e1;
box-shadow: 0 4px 20px -2px rgba(15, 23, 42, 0.06);
}
/* Dark HUD khusus di atas kanvas 3D agar teks tetap tajam */
.hud-overlay {
background: rgba(15, 23, 42, 0.84);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.18);
color: #f8fafc;
}
/* Canvas container */
#vr-canvas-container, #ar-canvas-container {
position: relative;
width: 100%;
height: 100%;
min-height: 360px;
}
#vr-canvas-container canvas, #ar-canvas-container canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
/* Mode Fullscreen AR Smartphone */
.ar-fullscreen-active {
position: fixed !important;
inset: 0 !important;
width: 100vw !important;
height: 100vh !important;
z-index: 60 !important;
border-radius: 0 !important;
}
Mata Kuliah Ekologi • Program Studi Pendidikan Biologi
Kearifan Lokal: Subak & Talun
Media Pembelajaran Interaktif Berbasis Virtual Reality, Augmented Reality & Generative AI
Misi Kognitif:
0/4 Selesai
⏱️
00:00
/ 20:00
🔇
🎓
Identitas Mahasiswa
Pendidikan Biologi — Ekologi
🌐 VR Jelajah Ekosistem
📱 AR Instrumen Ekologi
🧠 GenAI Mentor Analisis
Mode 1: Virtual Reality (3D Interactive Environment)
Ekosistem Sungai & Kearifan Lokal "Lubuk Larangan / Subak"
Putar kamera dengan mouse/sentuhan. Ubah parameter lingkungan untuk mengamati dampak ekologis secara langsung.
🌊 1. Pencemaran & Sungai
🌱 2. Kebun Smart Farming
Indeks Kesehatan Ekosistem
🏛️
Prinsip Tri Hita Karana & Subak
Pembagian air hulu-hilir berbasis musyawarah menjaga debit & mencegah eutrofikasi limbah domestik.
🎛️ Panel Manipulasi Ekosistem (Uji Keputusan Mahasiswa)
Geser layar untuk rotasi 360° • Scroll/Pinch untuk Zoom
1. Limbah Nitrat/Fosfat
15 mg/L
Picu eutrofikasi & blooming alga
2. Filter Riparian & Bambu
Aktif (80%)
Fitoremediasi lokal tepi sungai
3. Aturan Adat Lubuk Larangan
🛡️ Zona Konservasi: AKTIF
1. Irigasi Tetes IoT (Subak)
Optimal (65%)
Sensor kelembapan tanah otomatis
2. Pupuk Organik vs Kimia
85% Organik
Jaga mikrobioma & cacing tanah
3. Sistem Polikultur Talun
🌿 Tumpang Sari: AKTIF
Oksigen Terlarut (DO)
Ideal bagi ikan endemik
pH & Kekeruhan
Jernih (12 NTU)
Indeks Biodiversitas (H')
Keanekaragaman Tinggi
Emisi Karbon / Jejak
Penyerap Karbon (Sink)
Mode 2: Web-Augmented Reality (3D Smartphone & Desktop)
Inspeksi AR Instrumen Pencemaran & Smart Farming
Putar objek 3D dengan jari/mouse (geser untuk rotasi 360°, cubit untuk zoom), atau aktifkan kamera smartphone untuk menampilkan instrumen AR di lingkungan nyata.
📷 Kamera AR Smartphone
📲 Tampilkan AR Layar Penuh
🧪
Multiparameter DO & pH Sensor
Uji Pencemaran Air
📡
Node Sensor NPK & Kelembapan
Smart Farming IoT
🎋
Biofilter Bambu & Zeolit + Secchi Disk
Kearifan Lokal & Kekeruhan
🚁
Drone Pemantau NDVI Tanaman
Presisi Ekologi Lahan
AR 3D: SENTUH & PUTAR 360°
✕ Tutup Layar Penuh
👁️ Sembunyikan Deskripsi
🔄 Reset
🔍 Bedah Komponen
Referensi Alat Asli
DO & pH Meter Probe
Probe kabel + unit LCD digital DO/pH
Geser untuk putar 360° • Cubit/Scroll untuk zoom • Klik bagian 3D untuk cek detail
Multiparameter DO & pH Sensor
Deteksi Pencemaran Air
▲ Kecilkan / Sembunyikan
Mengukur kadar oksigen terlarut (DO), pH, dan TDS secara real-time untuk mendeteksi pencemaran organik akibat limbah rumah tangga atau pupuk berlebih.
👆 Klik Bagian 3D Alat / Pilih Komponen (3 Bagian):
Bagian terpilih: 1/3
💡 Integrasi Lokal: Ditempatkan di hulu dan hilir saluran Subak.
⚡ Uji Pengukuran Alat
📄 Deskripsi & 3 Bagian Alat AR disembunyikan agar tampilan 3D lebih luas.
▼ Tampilkan Deskripsi
Mode 3: Generative AI (Gemini 3 Flash)
Mentor Analisis Ekologi & Generator Studi Kasus
Tuliskan hipotesis, pendapat, atau pertanyaan analisis Anda, atau hasilkan variasi studi kasus lapangan secara otomatis.
✨ Buat Variasi Studi Kasus Otomatis
📌 Skenario Studi Kasus Aktif
Eutrofikasi & Smart Farming
Sebuah desa pertanian di hulu sungai mengalami ledakan pertumbuhan alga (blooming) akibat limpasan pupuk NPK konvensional. Jika masyarakat menerapkan sistem irigasi Subak berbasis sensor kelembapan tanah (Smart Farming) dan menanam bambu riparian di sempadan sungai, bagaimana dinamika rantai makanan dan kadar Oksigen Terlarut (DO) berubah dalam 6 bulan ke depan?
✍️ Tuliskan Pendapat, Hipotesis, atau Pertanyaan Analisis Anda:
💡 Contoh Argumen Eutrofikasi
🌾 Perspektif Kearifan Lokal
🚀 Analisis dengan Gemini AI
Umpan Balik Multi-Perspektif Gemini AI
Kedalaman Analisis: Evaluasi AI
Sikap & Kesadaran Ekologis
🌱 Refleksi Environmental Awareness (Kesadaran Lingkungan)
Belum Diisi
Setelah menjelajahi simulasi pencemaran sungai, teknologi Smart Farming, dan nilai kearifan lokal, tuliskan refleksi kesadaran lingkungan Anda serta komitmen aksi nyata sebagai calon pendidik Biologi:
Laporan mencakup identitas, durasi belajar, progres misi, refleksi, & skor evaluasi tes.
📋 Salin Laporan
✉️ Kirim Hasil ke Email Mahasiswa
🧭 Alur Eksplorasi (15–20 Menit)
Sintesis C4–C6
⬜
1. Simulasi VR Pencemaran (5 Menit)
Ubah parameter limbah nitrat & aktifkan filter riparian bambu untuk melihat perubahan DO & biodiversitas.
⬜
2. Jelajah VR Smart Farming (5 Menit)
Beralih ke kebun Smart Farming, atur irigasi IoT Subak & sistem polikultur Talun.
⬜
3. Inspeksi AR Instrumen (4 Menit)
Buka tab AR, putar model 3D di smartphone/desktop, dan lakukan bedah komponen / uji pengukuran.
⬜
4. Sintesis Kritis GenAI (5 Menit)
Tulis argumen analisis pada tab GenAI dan dapatkan perspektif multi-disiplin dari Gemini.
🌾
Kearifan Lokal Nusantara dalam Simulasi
Kearifan lokal bukan sekadar hiasan teks, melainkan variabel mekanisme yang mengubah dinamika ekosistem di dalam simulasi 3D:
1. Lubuk Larangan (Sumatra / Bengkulu)
Zona larangan tangkap berbasis adat yang menjaga populasi ikan pemakan alga & kestabilan jaring-jaring makanan sungai.
2. Sistem Subak & Polikultur Talun
Distribusi air hulu-hilir berbasis musyawarah & tanaman berlapis yang menahan erosi serta meningkatkan serapan karbon.
🎯 Evaluasi Tes Singkat (HOTS)
Skor: 0/4
Soal 1 dari 4
Smart Farming & Siklus Hara
1. Mengapa kombinasi sensor kelembapan tanah (Smart Farming) dengan sistem polikultur Talun efektif mencegah pencemaran sungai di hilir?
A. Mencegah irigasi berlebih sehingga mengurangi pencucian (leaching) nitrat ke badan air.
B. Meningkatkan suhu air sungai agar bakteri pengurai bekerja lebih cepat.
C. Menghilangkan kebutuhan fotosintesis pada tanaman budidaya di lahan kering.
// --- 1. STATE MANAGEMENT ---
const appState = {
mode: 'vr',
vrScene: 'pollution', // 'pollution' | 'smartfarm'
adatRuleActive: true,
polycultureActive: true,
arModel: 'do_meter',
arExploded: false,
arCameraActive: false,
arFullscreen: false,
arAutoRotate: true,
arDescVisible: true,
audioEnabled: false,
secondsElapsed: 0,
missions: { m1: false, m2: false, m3: false, m4: false },
arInspectedCount: new Set(['do_meter']),
quizIndex: 0,
quizScore: 0,
quizAnsweredCount: 0,
quizResultsLog: []
};
const apiKey = ""; // Otomatis disediakan saat runtime
// --- 2. TOAST NOTIFICATION (PENGGANTI ALERT) ---
function showToast(title, message, type = 'info') {
const container = document.getElementById('toast-container');
const colors = {
info: 'border-emerald-500 bg-white text-emerald-900 shadow-lg',
warn: 'border-amber-500 bg-white text-amber-900 shadow-lg',
error: 'border-rose-500 bg-white text-rose-900 shadow-lg'
};
const toast = document.createElement('div');
toast.className = `pointer-events-auto border-l-4 ${colors[type] || colors.info} p-3 rounded-xl transition-all duration-300 transform translate-y-2 opacity-0`;
toast.innerHTML = `
${title}
${message}
`;
container.appendChild(toast);
requestAnimationFrame(() => {
toast.classList.remove('translate-y-2', 'opacity-0');
});
setTimeout(() => {
toast.classList.add('opacity-0', 'translate-y-2');
setTimeout(() => toast.remove(), 300);
}, 4000);
}
// --- 3. MISSION PROGRESS & TIMER (15-20 MENIT) ---
function completeMission(missionKey, label) {
if (!appState.missions[missionKey]) {
appState.missions[missionKey] = true;
document.getElementById(`${missionKey}-icon`).textContent = '✅';
const card = document.getElementById(`mission-${missionKey.replace('m', '')}`);
card.classList.remove('border-slate-200', 'bg-slate-50');
card.classList.add('border-emerald-400', 'bg-emerald-50');
const doneCount = Object.values(appState.missions).filter(Boolean).length;
document.getElementById('mission-progress-text').textContent = `${doneCount}/4 Selesai`;
playToneEffect('success');
showToast('Misi Kognitif Tercapai!', label, 'info');
}
}
setInterval(() => {
appState.secondsElapsed++;
const mins = String(Math.floor(appState.secondsElapsed / 60)).padStart(2, '0');
const secs = String(appState.secondsElapsed % 60).padStart(2, '0');
document.getElementById('session-timer').textContent = `${mins}:${secs}`;
}, 1000);
// --- 4. TONE.JS AMBIENT & INTERACTION AUDIO ---
let melodySynth = null;
let bassSynth = null;
let melodyLoop = null;
let bassLoop = null;
async function toggleAudio() {
try {
if (!appState.audioEnabled) {
await Tone.start();
// Instrumen melodi ceria bergaya marimba/kalimba (attack cepat, decay renyah)
melodySynth = new Tone.PolySynth(Tone.Synth, {
oscillator: { type: 'triangle' },
envelope: { attack: 0.015, decay: 0.22, sustain: 0.15, release: 0.35 }
}).toDestination();
melodySynth.volume.value = -15;
// Bass lembut untuk memberi ritme ceria & hangat
bassSynth = new Tone.Synth({
oscillator: { type: 'sine' },
envelope: { attack: 0.02, decay: 0.3, sustain: 0.2, release: 0.4 }
}).toDestination();
bassSynth.volume.value = -16;
// Pola melodi pendidikan yang ceria & optimis (C Major / Pentatonic upbeat)
const cheerfulNotes = [
'C5', 'E5', 'G5', 'A5',
'G5', 'E5', 'D5', 'E5',
'F5', 'A5', 'C6', 'A5',
'G5', 'E5', 'G5', 'D5'
];
const bassNotes = [
'C3', 'G3', 'F3', 'G3'
];
Tone.Transport.bpm.value = 112;
let step = 0;
let barStep = 0;
melodyLoop = new Tone.Loop((time) => {
const note = cheerfulNotes[step % cheerfulNotes.length];
melodySynth.triggerAttackRelease(note, '8n', time);
step++;
}, '8n').start(0);
bassLoop = new Tone.Loop((time) => {
const bNote = bassNotes[barStep % bassNotes.length];
bassSynth.triggerAttackRelease(bNote, '2n', time);
barStep++;
}, '2n').start(0);
Tone.Transport.start();
appState.audioEnabled = true;
document.getElementById('audio-icon').textContent = '🎵';
showToast('Musik Pendidikan Ceria Aktif', 'Melodi ceria bernuansa marimba & efek interaksi diaktifkan.');
} else {
Tone.Transport.stop();
Tone.Transport.position = 0;
if (melodyLoop) {
melodyLoop.stop();
melodyLoop.dispose();
melodyLoop = null;
}
if (bassLoop) {
bassLoop.stop();
bassLoop.dispose();
bassLoop = null;
}
if (melodySynth) {
melodySynth.dispose();
melodySynth = null;
}
if (bassSynth) {
bassSynth.dispose();
bassSynth = null;
}
appState.audioEnabled = false;
document.getElementById('audio-icon').textContent = '🔇';
}
} catch (e) {
console.warn('Audio init error:', e);
}
}
function playToneEffect(type) {
if (!appState.audioEnabled) return;
const synth = new Tone.Synth({
oscillator: { type: 'triangle' },
envelope: { attack: 0.01, decay: 0.12, sustain: 0.05, release: 0.15 }
}).toDestination();
synth.volume.value = -13;
if (type === 'success') {
synth.triggerAttackRelease('C6', '16n');
setTimeout(() => synth.triggerAttackRelease('E6', '16n'), 90);
setTimeout(() => { synth.dispose(); }, 350);
} else {
synth.triggerAttackRelease('G5', '32n');
setTimeout(() => { synth.dispose(); }, 250);
}
}
// --- 5. NAVIGATION SWITCHER ---
function switchMode(mode) {
appState.mode = mode;
['vr', 'ar', 'genai'].forEach(m => {
const view = document.getElementById(`view-${m}`);
const tab = document.getElementById(`tab-${m}`);
if (m === mode) {
view.classList.remove('hidden');
view.classList.add('flex');
tab.classList.add('bg-emerald-600', 'text-white', 'shadow-sm');
tab.classList.remove('text-slate-600');
} else {
view.classList.add('hidden');
view.classList.remove('flex');
tab.classList.remove('bg-emerald-600', 'text-white', 'shadow-sm');
tab.classList.add('text-slate-600');
}
});
if (mode === 'vr') {
setTimeout(resizeVRCanvas, 50);
}
if (mode === 'ar') {
setTimeout(resizeARCanvas, 50);
if (appState.arInspectedCount.size >= 2) {
completeMission('m3', 'Anda telah mengeksplorasi instrumen ekologi berbasis Augmented Reality.');
}
}
playToneEffect('click');
}
// --- 6. THREE.JS VR ENVIRONMENT (PENCEMARAN & SMART FARMING) ---
let vrScene, vrCamera, vrRenderer, vrGroup;
let riverMesh, algaeGroup, fishGroup, riparianGroup, farmCropsGroup, sprinklerParticles;
let isDraggingVR = false, prevMouseVR = { x: 0, y: 0 };
let vrCameraAngle = { theta: 0.6, phi: 0.95, radius: 16 };
function initVR() {
const container = document.getElementById('vr-canvas-container');
if (!container || typeof THREE === 'undefined') return;
vrScene = new THREE.Scene();
vrScene.background = new THREE.Color(0x091d16);
vrScene.fog = new THREE.FogExp2(0x091d16, 0.025);
const width = Math.max(container.clientWidth, 320);
const height = Math.max(container.clientHeight, 360);
vrCamera = new THREE.PerspectiveCamera(50, width / height, 0.1, 100);
updateVRCameraPosition();
vrRenderer = new THREE.WebGLRenderer({ antialias: true });
vrRenderer.setSize(width, height, false);
vrRenderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
container.innerHTML = '';
container.appendChild(vrRenderer.domElement);
// Pencahayaan
const ambientLight = new THREE.AmbientLight(0xffffff, 0.65);
vrScene.add(ambientLight);
const dirLight = new THREE.DirectionalLight(0xfff5e4, 0.9);
dirLight.position.set(10, 18, 10);
vrScene.add(dirLight);
vrGroup = new THREE.Group();
vrScene.add(vrGroup);
buildPollutionScene();
setupVRControls(container);
}
function updateVRCameraPosition() {
if (!vrCamera) return;
vrCamera.position.x = vrCameraAngle.radius * Math.sin(vrCameraAngle.phi) * Math.cos(vrCameraAngle.theta);
vrCamera.position.y = Math.max(2.5, vrCameraAngle.radius * Math.cos(vrCameraAngle.phi));
vrCamera.position.z = vrCameraAngle.radius * Math.sin(vrCameraAngle.phi) * Math.sin(vrCameraAngle.theta);
vrCamera.lookAt(0, 0.5, 0);
}
function setupVRControls(dom) {
dom.addEventListener('mousedown', (e) => { isDraggingVR = true; prevMouseVR = { x: e.clientX, y: e.clientY }; });
window.addEventListener('mouseup', () => { isDraggingVR = false; });
window.addEventListener('mousemove', (e) => {
if (!isDraggingVR) return;
const dx = e.clientX - prevMouseVR.x;
const dy = e.clientY - prevMouseVR.y;
vrCameraAngle.theta -= dx * 0.008;
vrCameraAngle.phi = Math.max(0.35, Math.min(1.35, vrCameraAngle.phi - dy * 0.008));
updateVRCameraPosition();
prevMouseVR = { x: e.clientX, y: e.clientY };
});
// Touch support
dom.addEventListener('touchstart', (e) => {
if (e.touches.length === 1) {
isDraggingVR = true;
prevMouseVR = { x: e.touches[0].clientX, y: e.touches[0].clientY };
}
}, { passive: true });
dom.addEventListener('touchend', () => { isDraggingVR = false; });
dom.addEventListener('touchmove', (e) => {
if (!isDraggingVR || e.touches.length !== 1) return;
const dx = e.touches[0].clientX - prevMouseVR.x;
const dy = e.touches[0].clientY - prevMouseVR.y;
vrCameraAngle.theta -= dx * 0.01;
vrCameraAngle.phi = Math.max(0.35, Math.min(1.35, vrCameraAngle.phi - dy * 0.01));
updateVRCameraPosition();
prevMouseVR = { x: e.touches[0].clientX, y: e.touches[0].clientY };
}, { passive: true });
dom.addEventListener('wheel', (e) => {
e.preventDefault();
vrCameraAngle.radius = Math.max(9, Math.min(26, vrCameraAngle.radius + e.deltaY * 0.01));
updateVRCameraPosition();
}, { passive: false });
}
function clearVRGroup() {
while (vrGroup.children.length > 0) {
vrGroup.remove(vrGroup.children[0]);
}
riverMesh = null;
algaeGroup = null;
fishGroup = null;
riparianGroup = null;
farmCropsGroup = null;
sprinklerParticles = null;
}
function buildPollutionScene() {
clearVRGroup();
// Dasar lahan & tebing sungai
const ground = new THREE.Mesh(
new THREE.BoxGeometry(24, 0.8, 18),
new THREE.MeshStandardMaterial({ color: 0x1e3a2f, roughness: 0.9 })
);
ground.position.set(0, -0.5, 0);
vrGroup.add(ground);
// Aliran sungai
riverMesh = new THREE.Mesh(
new THREE.BoxGeometry(6.5, 0.35, 18.2),
new THREE.MeshStandardMaterial({ color: 0x0ea5e9, roughness: 0.25, metalness: 0.1 })
);
riverMesh.position.set(0, -0.1, 0);
vrGroup.add(riverMesh);
// Vegetasi riparian (bambu & semak penyaring) di sisi kiri & kanan sungai
riparianGroup = new THREE.Group();
const bambooGeo = new THREE.CylinderGeometry(0.14, 0.18, 3.6, 10);
const bambooMat = new THREE.MeshStandardMaterial({ color: 0x65a30d });
for (let i = 0; i < 16; i++) {
const zPos = -7.2 + i * 0.96;
const side = i % 2 === 0 ? -4.3 : 4.3;
const stalk = new THREE.Mesh(bambooGeo, bambooMat);
stalk.position.set(side + (Math.random() - 0.5) * 0.6, 1.6, zPos);
stalk.rotation.z = side < 0 ? -0.06 : 0.06;
riparianGroup.add(stalk);
}
vrGroup.add(riparianGroup);
// Kelompok alga (blooming indikator pencemaran nutrien)
algaeGroup = new THREE.Group();
const algaeGeo = new THREE.SphereGeometry(0.32, 10, 10);
const algaeMat = new THREE.MeshStandardMaterial({ color: 0x84cc16, roughness: 0.6 });
for (let i = 0; i < 20; i++) {
const patch = new THREE.Mesh(algaeGeo, algaeMat);
patch.scale.set(1.5, 0.25, 1.5);
patch.position.set(
(Math.random() - 0.5) * 4.6,
0.12,
-6.5 + i * 0.68
);
algaeGroup.add(patch);
}
vrGroup.add(algaeGroup);
// Biota ikan sungai
fishGroup = new THREE.Group();
const fishGeo = new THREE.ConeGeometry(0.18, 0.65, 8);
fishGeo.rotateX(Math.PI / 2);
const fishMat = new THREE.MeshStandardMaterial({ color: 0xf59e0b });
for (let i = 0; i < 10; i++) {
const fish = new THREE.Mesh(fishGeo, fishMat);
fish.position.set((Math.random() - 0.5) * 3.6, 0.25, -6 + i * 1.3);
fishGroup.add(fish);
}
vrGroup.add(fishGroup);
updatePollutionSim(false);
}
function buildSmartFarmScene() {
clearVRGroup();
// Lahan pertanian & bedengan Smart Farming
const soil = new THREE.Mesh(
new THREE.BoxGeometry(22, 0.8, 16),
new THREE.MeshStandardMaterial({ color: 0x3f2e21, roughness: 0.95 })
);
soil.position.set(0, -0.5, 0);
vrGroup.add(soil);
// Saluran irigasi Subak
const canal = new THREE.Mesh(
new THREE.BoxGeometry(22, 0.25, 1.4),
new THREE.MeshStandardMaterial({ color: 0x0284c7, roughness: 0.2 })
);
canal.position.set(0, -0.05, -6.2);
vrGroup.add(canal);
// Tanaman budidaya & polikultur Talun
farmCropsGroup = new THREE.Group();
const cropMat = new THREE.MeshStandardMaterial({ color: 0x16a34a });
const treeMat = new THREE.MeshStandardMaterial({ color: 0x15803d });
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 7; col++) {
const x = -7.5 + col * 2.5;
const z = -3.2 + row * 2.1;
const crop = new THREE.Mesh(new THREE.ConeGeometry(0.45, 1.1, 8), cropMat);
crop.position.set(x, 0.5, z);
farmCropsGroup.add(crop);
if (appState.polycultureActive && (row === 0 || row === 3) && col % 2 === 0) {
const canopy = new THREE.Mesh(new THREE.DodecahedronGeometry(0.95), treeMat);
canopy.position.set(x, 1.6, z + (row === 0 ? -1.1 : 1.1));
farmCropsGroup.add(canopy);
}
}
}
vrGroup.add(farmCropsGroup);
// Partikel tetesan irigasi presisi
sprinklerParticles = new THREE.Group();
const dropGeo = new THREE.SphereGeometry(0.06, 6, 6);
const dropMat = new THREE.MeshBasicMaterial({ color: 0x38bdf8 });
for (let i = 0; i < 36; i++) {
const drop = new THREE.Mesh(dropGeo, dropMat);
drop.position.set(
(Math.random() - 0.5) * 14,
0.5 + Math.random() * 1.7,
-3.5 + Math.random() * 7
);
sprinklerParticles.add(drop);
}
vrGroup.add(sprinklerParticles);
updateSmartFarmSim(false);
}
function setVRScene(sceneKey) {
appState.vrScene = sceneKey;
const btnPol = document.getElementById('btn-scene-pollution');
const btnFarm = document.getElementById('btn-scene-smartfarm');
const ctrlPol = document.getElementById('controls-pollution');
const ctrlFarm = document.getElementById('controls-smartfarm');
const titleEl = document.getElementById('vr-scene-title');
const subEl = document.getElementById('vr-scene-subtitle');
const lwTitle = document.getElementById('lw-title');
const lwDesc = document.getElementById('lw-desc');
if (sceneKey === 'pollution') {
btnPol.className = 'flex-1 sm:flex-initial px-3 py-2 rounded-xl text-xs font-bold bg-emerald-600 text-white shadow-sm transition-all';
btnFarm.className = 'flex-1 sm:flex-initial px-3 py-2 rounded-xl text-xs font-bold bg-slate-100 text-slate-700 hover:bg-slate-200 border border-slate-300 transition-all';
ctrlPol.classList.remove('hidden');
ctrlPol.classList.add('grid');
ctrlFarm.classList.add('hidden');
ctrlFarm.classList.remove('grid');
titleEl.textContent = 'Ekosistem Sungai & Kearifan Lokal "Lubuk Larangan / Subak"';
subEl.textContent = 'Putar kamera dengan mouse/sentuhan. Ubah parameter lingkungan untuk mengamati dampak ekologis secara langsung.';
lwTitle.textContent = 'Prinsip Tri Hita Karana & Lubuk Larangan';
lwDesc.textContent = 'Perlindungan zona sungai berbasis adat serta vegetasi riparian menjaga kadar DO & mencegah eutrofikasi.';
buildPollutionScene();
} else {
btnFarm.className = 'flex-1 sm:flex-initial px-3 py-2 rounded-xl text-xs font-bold bg-emerald-600 text-white shadow-sm transition-all';
btnPol.className = 'flex-1 sm:flex-initial px-3 py-2 rounded-xl text-xs font-bold bg-slate-100 text-slate-700 hover:bg-slate-200 border border-slate-300 transition-all';
ctrlFarm.classList.remove('hidden');
ctrlFarm.classList.add('grid');
ctrlPol.classList.add('hidden');
ctrlPol.classList.remove('grid');
titleEl.textContent = 'Kebun Smart Farming & Sistem Polikultur Talun / Subak';
subEl.textContent = 'Atur irigasi presisi IoT, komposisi pupuk organik, dan sistem polikultur Talun untuk mengoptimalkan kesehatan lahan.';
lwTitle.textContent = 'Sistem Subak & Agroforestri Talun';
lwDesc.textContent = 'Sinergi irigasi terukur dan tanaman berlapis menahan erosi, menekan limpasan nitrat, serta menyerap karbon.';
buildSmartFarmScene();
}
playToneEffect('click');
}
// --- 7. THREE.JS & WEB-AR INSTRUMENT VIEWER (DENGAN KONTROL SENTUH SMARTPHONE & KLIK BAGIAN 3D) ---
let arScene, arCamera, arRenderer, arModelGroup;
let isDraggingAR = false, prevTouchAR = { x: 0, y: 0 }, initialPinchDistAR = null;
let pointerDownPosAR = { x: 0, y: 0 };
const arRaycaster = new THREE.Raycaster();
const arPointerNDC = new THREE.Vector2();
let activePartIndex = 0;
const arCatalog = {
do_meter: {
title: 'Multiparameter DO & pH Sensor',
badge: 'Deteksi Pencemaran Air',
cornerName: 'DO & pH Meter + Probe Kabel',
cornerSpec: 'Unit LCD digital (mg/L & pH) dengan probe kabel celup',
cornerSvg: `
`,
desc: 'Instrumen elektrokimia untuk mengukur Dissolved Oxygen (DO), pH, dan suhu air. Penurunan DO di bawah 4 mg/L menandakan dekomposisi limbah organik masif.',
local: '💡 Integrasi Lokal: Dipasang di titik masuk & keluar sistem irigasi Subak untuk audit kualitas air bersama.',
reading: 'Hasil Uji AR: DO = 7.6 mg/L | pH = 7.2 | Status: Perairan Sehat (Kelas I)',
parts: [
{
name: '1. Unit Kontrol & Layar LCD',
shortName: '1. Kontrol & LCD',
desc: 'Menampilkan angka DO (mg/L), pH, dan suhu air secara langsung di lapangan serta menyimpan log data pengamatan kualitas air sungai.'
},
{
name: '2. Membran Elektroda DO/pH',
shortName: '2. Elektroda DO/pH',
desc: 'Sensor sensitif yang merespons difusi oksigen terlarut dan aktivitas ion hidrogen (H+) untuk mendeteksi indikasi eutrofikasi atau limbah asam/basa.'
},
{
name: '3. Probe Celup & Kabel Konektor',
shortName: '3. Probe & Kabel',
desc: 'Batang probe kedap air dan kabel penghubung yang menjaga posisi sensor tetap stabil saat dicelupkan ke arus sungai atau saluran irigasi Subak.'
}
]
},
soil_iot: {
title: 'Node Sensor NPK & Kelembapan Tanah IoT',
badge: 'Smart Farming Presisi',
cornerName: 'Node Sensor Kelembapan Tanah',
cornerSpec: 'Dual-probe garpu tanah + modul komparator & kabel',
cornerSvg: `
`,
desc: 'Sensor tanam bertenaga surya yang membaca kadar Nitrogen (N), Fosfor (P), Kalium (K), dan kadar air tanah secara real-time, lalu mengirim sinyal ke katup irigasi tetes otomatis.',
local: '💡 Integrasi Lokal: Mencegah pemborosan air dan limpasan pupuk kimia ke sungai desa.',
reading: 'Hasil Uji AR: Kelembapan = 64% | N: 42 ppm | P: 18 ppm | Rekomendasi: Tunda pemupukan.',
parts: [
{
name: '1. Modul Pengolah & Panel Surya',
shortName: '1. Modul & Surya',
desc: 'Mengolah sinyal sensor tanah dan menyuplai daya agar pemantauan lahan pertanian berjalan konsisten tanpa pemborosan air dan pupuk.'
},
{
name: '2. Konektor & Jalur Kabel Sinyal',
shortName: '2. Kabel & Konektor',
desc: 'Menghubungkan probe pembacaan tanah ke modul pemroses secara stabil di area perakaran tanaman.'
},
{
name: '3. Probe Garpu Kelembapan & NPK',
shortName: '3. Probe Tanah',
desc: 'Ditanamkan ke dalam tanah untuk mengukur konduktivitas kelembapan dan ketersediaan hara di zona akar.'
}
]
},
biofilter: {
title: 'Reaktor Biofilter Bambu & Zeolit Lokal dengan Secchi Disk',
badge: 'Kearifan Lokal & Kekeruhan',
cornerName: 'Secchi Disk + Biofilter Bambu',
cornerSpec: 'Cakram hitam-putih bertali + reaktor bambu & zeolit',
cornerSvg: `
`,
desc: 'Menggabungkan reaktor biofilter bambu, arang aktif/biochar, dan batu zeolit untuk menyaring limbah organik, dilengkapi Secchi Disk hitam-putih bertali untuk mengukur transparansi/kekeruhan air (transparansi Secchi).',
local: '💡 Integrasi Lokal: Memanfaatkan bambu lokal, media zeolit, serta pengamatan transparansi air berbasis kearifan lokal.',
reading: 'Hasil Uji AR: Kedalaman Secchi Disk = 68 cm (Air Relatif Jernih) | Efisiensi Biofilter = 83%.',
parts: [
{
name: '1. Secchi Disk Hitam-Putih & Tali Ukur',
shortName: '1. Secchi Disk & Tali',
desc: 'Cakram bercorak kuadran hitam-putih dengan tali berskala yang diturunkan ke air untuk menentukan batas transparansi visual dan tingkat kekeruhan perairan.'
},
{
name: '2. Reaktor Tabung Bambu & Media Zeolit',
shortName: '2. Bambu & Zeolit',
desc: 'Wadah bambu lokal dan lapisan zeolit berpori yang mengikat ion amonium, kekeruhan, serta polutan terlarut sebelum air dialirkan.'
},
{
name: '3. Biochar & Zona Filtrasi Biologis',
shortName: '3. Biochar & Filtrasi',
desc: 'Lapisan karbon aktif/biochar yang menjadi tempat kolonisasi mikroba pengurai untuk menurunkan beban organik dan menstabilkan kualitas air.'
}
]
},
agri_drone: {
title: 'Drone Pemantau Indeks Vegetasi (NDVI)',
badge: 'Pemetaan Ekologi Lahan',
cornerName: 'Drone Pemantau NDVI Lahan',
cornerSpec: 'Quadcopter multispektral + peta indeks vegetasi (NDVI)',
cornerSvg: `
`,
desc: 'Wahana tanpa awak dengan kamera multispektral untuk memetakan kesehatan klorofil tanaman (NDVI), mendeteksi stres vegetasi lebih awal, dan memetakan tutupan kanopi agroforestri.',
local: '💡 Integrasi Lokal: Memetakan keseimbangan zona hutan lindung (Talun) dan lahan budidaya.',
reading: 'Hasil Uji AR: Skor NDVI Rata-rata = 0.78 (Kanopi Sehat & Serapan Karbon Tinggi).',
parts: [
{
name: '1. Badan Utama & Sistem Kendali',
shortName: '1. Badan & Kendali',
desc: 'Menampung flight controller, navigasi GPS, dan baterai untuk menyusuri jalur pemetaan lahan pertanian maupun agroforestri Talun.'
},
{
name: '2. Sensor Kamera Multispektral',
shortName: '2. Kamera NDVI',
desc: 'Merekam pantulan cahaya tampak dan inframerah dekat (NIR) untuk menghitung indeks vegetasi (NDVI) serta mendeteksi stres tanaman.'
},
{
name: '3. Rotor Propulsi & Rangka Quadcopter',
shortName: '3. Rotor & Rangka',
desc: 'Menghasilkan gaya angkat dan manuver stabil di udara saat memotret kanopi tanaman pada berbagai ketinggian.'
}
]
}
};
function updateARCornerReference(modelKey) {
const info = arCatalog[modelKey];
if (!info) return;
const svgBox = document.getElementById('ar-corner-svg-box');
const nameEl = document.getElementById('ar-corner-ref-name');
const specEl = document.getElementById('ar-corner-ref-spec');
if (svgBox && info.cornerSvg) svgBox.innerHTML = info.cornerSvg;
if (nameEl) nameEl.textContent = info.cornerName || info.title;
if (specEl) specEl.textContent = info.cornerSpec || '';
}
function selectARPart(partIdx, showFeedback = false) {
const catalogItem = arCatalog[appState.arModel];
if (!catalogItem || !catalogItem.parts[partIdx]) return;
if (!appState.arDescVisible) {
toggleARDescPanel(true);
}
activePartIndex = partIdx;
const part = catalogItem.parts[partIdx];
document.getElementById('ar-selected-part-label').textContent = `Bagian terpilih: ${partIdx + 1}/${catalogItem.parts.length}`;
document.getElementById('ar-part-title').textContent = part.name;
document.getElementById('ar-part-desc').textContent = part.desc;
// Highlight tombol bagian yang aktif
const buttons = document.querySelectorAll('#ar-parts-buttons button');
buttons.forEach((btn, idx) => {
if (idx === partIdx) {
btn.className = 'text-left px-2.5 py-2 rounded-xl bg-cyan-600 text-white text-xs font-bold shadow-sm transition-all';
} else {
btn.className = 'text-left px-2.5 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 border border-slate-300 text-xs font-semibold transition-all';
}
});
// Highlight mesh 3D yang sesuai pada model AR
if (arModelGroup) {
arModelGroup.children.forEach((mesh) => {
if (mesh.userData && typeof mesh.userData.partIndex === 'number') {
const isSelected = mesh.userData.partIndex === partIdx;
if (mesh.material && mesh.material.emissive) {
mesh.material.emissive.setHex(isSelected ? 0x0ea5e9 : 0x000000);
mesh.material.emissiveIntensity = isSelected ? 0.35 : 0;
}
}
});
}
if (showFeedback) {
playToneEffect('click');
showToast(part.name, part.desc, 'info');
}
}
function renderARPartButtons(modelKey) {
const catalogItem = arCatalog[modelKey];
const container = document.getElementById('ar-parts-buttons');
if (!catalogItem || !container) return;
container.innerHTML = catalogItem.parts.map((part, idx) => `
${part.shortName}
`).join('');
selectARPart(0, false);
}
function handleARObjectClick(clientX, clientY) {
const container = document.getElementById('ar-canvas-container');
if (!container || !arCamera || !arModelGroup) return;
const rect = container.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return;
arPointerNDC.x = ((clientX - rect.left) / rect.width) * 2 - 1;
arPointerNDC.y = -((clientY - rect.top) / rect.height) * 2 + 1;
arRaycaster.setFromCamera(arPointerNDC, arCamera);
const hits = arRaycaster.intersectObjects(arModelGroup.children, true);
if (hits.length > 0) {
const hitObj = hits[0].object;
const partIdx = (hitObj.userData && typeof hitObj.userData.partIndex === 'number')
? hitObj.userData.partIndex
: (activePartIndex + 1) % 3;
selectARPart(partIdx, true);
}
}
function initAR() {
const container = document.getElementById('ar-canvas-container');
if (!container || typeof THREE === 'undefined') return;
arScene = new THREE.Scene();
const width = Math.max(container.clientWidth, 320);
const height = Math.max(container.clientHeight, 360);
arCamera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100);
arCamera.position.set(0, 1.2, 5.2);
arCamera.lookAt(0, 0, 0);
arRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
arRenderer.setSize(width, height, false);
arRenderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
container.innerHTML = '';
container.appendChild(arRenderer.domElement);
const light1 = new THREE.AmbientLight(0xffffff, 0.9);
const light2 = new THREE.DirectionalLight(0x38bdf8, 1.3);
light2.position.set(5, 8, 5);
arScene.add(light1, light2);
arModelGroup = new THREE.Group();
arScene.add(arModelGroup);
buildAR3DObject('do_meter');
renderARPartButtons('do_meter');
setupARControls(container);
}
function setupARControls(dom) {
// Mouse drag untuk rotasi objek AR 360° & klik untuk memilih bagian 3D
dom.addEventListener('mousedown', (e) => {
isDraggingAR = true;
appState.arAutoRotate = false;
prevTouchAR = { x: e.clientX, y: e.clientY };
pointerDownPosAR = { x: e.clientX, y: e.clientY };
});
window.addEventListener('mouseup', (e) => {
if (isDraggingAR) {
const distMoved = Math.hypot(e.clientX - pointerDownPosAR.x, e.clientY - pointerDownPosAR.y);
if (distMoved {
if (!isDraggingAR || !arModelGroup) return;
const dx = e.clientX - prevTouchAR.x;
const dy = e.clientY - prevTouchAR.y;
arModelGroup.rotation.y += dx * 0.012;
arModelGroup.rotation.x = Math.max(-1.2, Math.min(1.2, arModelGroup.rotation.x + dy * 0.012));
prevTouchAR = { x: e.clientX, y: e.clientY };
});
// Mouse wheel zoom
dom.addEventListener('wheel', (e) => {
e.preventDefault();
if (!arModelGroup) return;
const nextScale = Math.max(0.5, Math.min(2.5, arModelGroup.scale.x - e.deltaY * 0.001));
arModelGroup.scale.setScalar(nextScale);
}, { passive: false });
// Touch Smartphone: 1 Jari untuk Putar 360° / Tap Bagian, 2 Jari (Pinch) untuk Perbesar/Perkecil
dom.addEventListener('touchstart', (e) => {
appState.arAutoRotate = false;
if (e.touches.length === 1) {
isDraggingAR = true;
prevTouchAR = { x: e.touches[0].clientX, y: e.touches[0].clientY };
pointerDownPosAR = { x: e.touches[0].clientX, y: e.touches[0].clientY };
} else if (e.touches.length === 2) {
isDraggingAR = false;
const dx = e.touches[0].clientX - e.touches[1].clientX;
const dy = e.touches[0].clientY - e.touches[1].clientY;
initialPinchDistAR = Math.hypot(dx, dy);
}
}, { passive: true });
dom.addEventListener('touchend', (e) => {
if (isDraggingAR && e.changedTouches.length > 0) {
const touch = e.changedTouches[0];
const distMoved = Math.hypot(touch.clientX - pointerDownPosAR.x, touch.clientY - pointerDownPosAR.y);
if (distMoved {
if (!arModelGroup) return;
if (e.touches.length === 1 && isDraggingAR) {
const dx = e.touches[0].clientX - prevTouchAR.x;
const dy = e.touches[0].clientY - prevTouchAR.y;
arModelGroup.rotation.y += dx * 0.015;
arModelGroup.rotation.x = Math.max(-1.2, Math.min(1.2, arModelGroup.rotation.x + dy * 0.015));
prevTouchAR = { x: e.touches[0].clientX, y: e.touches[0].clientY };
} else if (e.touches.length === 2 && initialPinchDistAR) {
const dx = e.touches[0].clientX - e.touches[1].clientX;
const dy = e.touches[0].clientY - e.touches[1].clientY;
const currentDist = Math.hypot(dx, dy);
const scaleFactor = currentDist / initialPinchDistAR;
const nextScale = Math.max(0.5, Math.min(2.6, arModelGroup.scale.x * scaleFactor));
arModelGroup.scale.setScalar(nextScale);
initialPinchDistAR = currentDist;
}
}, { passive: true });
}
function resetARTransform() {
if (!arModelGroup) return;
arModelGroup.rotation.set(0, 0, 0);
arModelGroup.scale.setScalar(1);
appState.arAutoRotate = true;
playToneEffect('click');
}
function toggleARDescPanel(forceShow = null) {
appState.arDescVisible = typeof forceShow === 'boolean' ? forceShow : !appState.arDescVisible;
const panel = document.getElementById('ar-desc-panel');
const collapsedBar = document.getElementById('ar-desc-collapsed-bar');
const topBtn = document.getElementById('btn-toggle-ar-desc');
if (appState.arDescVisible) {
panel.classList.remove('hidden');
panel.classList.add('flex');
collapsedBar.classList.add('hidden');
if (topBtn) topBtn.textContent = '👁️ Sembunyikan Deskripsi';
} else {
panel.classList.add('hidden');
panel.classList.remove('flex');
collapsedBar.classList.remove('hidden');
if (topBtn) topBtn.textContent = '👁️ Tampilkan Deskripsi';
}
setTimeout(resizeARCanvas, 50);
playToneEffect('click');
}
function toggleARFullscreen() {
const wrapper = document.getElementById('ar-viewport-wrapper');
const exitBtn = document.getElementById('btn-exit-ar-fs');
appState.arFullscreen = !appState.arFullscreen;
if (appState.arFullscreen) {
wrapper.classList.add('ar-fullscreen-active');
exitBtn.classList.remove('hidden');
if (!appState.arCameraActive) {
toggleARCamera();
}
showToast('Mode AR Smartphone Aktif', 'Geser 1 jari untuk memutar objek 3D, cubit 2 jari untuk zoom.');
} else {
wrapper.classList.remove('ar-fullscreen-active');
exitBtn.classList.add('hidden');
}
setTimeout(resizeARCanvas, 60);
}
// Logika Kalkulasi Ekologi Skenario 1: Pencemaran Lingkungan
function updatePollutionSim(trackMission = true) {
const waste = parseInt(document.getElementById('slider-waste').value);
const riparian = parseInt(document.getElementById('slider-riparian').value);
document.getElementById('val-waste').textContent = `${waste} mg/L`;
document.getElementById('val-riparian').textContent = `${riparian}%`;
// Kearifan lokal & fitoremediasi mengurangi dampak pencemaran efektif
const riparianReduction = riparian * 0.55;
const adatBonus = appState.adatRuleActive ? 14 : 0;
const effectivePollution = Math.max(0, Math.min(100, waste - riparianReduction - (appState.adatRuleActive ? 8 : 0)));
const health = Math.max(10, Math.min(100, Math.round(92 - effectivePollution * 0.75 + adatBonus)));
// Visualisasi 3D pada Sungai
if (riverMesh) {
const polRatio = effectivePollution / 100;
const cleanColor = new THREE.Color(0x0ea5e9);
const pollutedColor = new THREE.Color(0x4d7c0f);
riverMesh.material.color.copy(cleanColor).lerp(pollutedColor, polRatio);
}
if (riparianGroup) {
const visibleBamboos = Math.round((riparian / 100) * riparianGroup.children.length);
riparianGroup.children.forEach((b, idx) => b.visible = idx a.visible = idx f.visible = idx = 6 ? 'Sehat untuk biota air' : 'Hipoksia! Risiko ikan mati';
document.getElementById('metric-2-label').textContent = 'Derajat Keasaman (pH)';
document.getElementById('metric-2-val').textContent = `${phVal} pH`;
document.getElementById('metric-2-status').textContent = health > 60 ? 'Netral & Jernih' : 'Keruh & Eutrofik';
document.getElementById('metric-3-label').textContent = "Indeks Biodiversitas (H')";
document.getElementById('metric-3-val').textContent = biodiv;
document.getElementById('metric-3-status').textContent = biodiv > 2.5 ? 'Ekosistem Stabil' : 'Didominasi Alga';
document.getElementById('metric-4-label').textContent = 'Daya Serap Fitoremediasi';
document.getElementById('metric-4-val').textContent = `${Math.round(riparian * 0.85)}%`;
document.getElementById('metric-4-status').textContent = 'Filtrasi akar bambu';
if (trackMission) {
completeMission('m1', 'Anda telah menguji parameter pencemaran sungai & fitoremediasi riparian.');
}
}
function toggleAdatRule() {
appState.adatRuleActive = !appState.adatRuleActive;
const btn = document.getElementById('btn-adat-rule');
if (appState.adatRuleActive) {
btn.textContent = '🛡️ Zona Konservasi: AKTIF';
btn.className = 'mt-1.5 w-full py-1.5 px-2 rounded-lg text-xs font-bold bg-amber-500/20 text-amber-300 border border-amber-500/40 transition-all';
} else {
btn.textContent = '⚠️ Zona Konservasi: NONAKTIF';
btn.className = 'mt-1.5 w-full py-1.5 px-2 rounded-lg text-xs font-bold bg-rose-500/20 text-rose-300 border border-rose-500/40 transition-all';
}
updatePollutionSim(true);
playToneEffect('click');
}
// Logika Kalkulasi Ekologi Skenario 2: Smart Farming
function updateSmartFarmSim(trackMission = true) {
const irrigation = parseInt(document.getElementById('slider-irrigation').value);
const organic = parseInt(document.getElementById('slider-fertilizer').value);
document.getElementById('val-irrigation').textContent = `${irrigation}%`;
document.getElementById('val-fertilizer').textContent = `${organic}% Organik`;
// Optimal irigasi di sekitar 60-70%
const waterPenalty = Math.abs(65 - irrigation) * 0.6;
const health = Math.max(20, Math.min(100, Math.round(50 + organic * 0.4 + (appState.polycultureActive ? 15 : 0) - waterPenalty)));
if (sprinklerParticles) {
sprinklerParticles.visible = irrigation > 25;
sprinklerParticles.scale.setScalar(0.5 + (irrigation / 100) * 0.8);
}
updateHealthHUD(health);
const soilMoisture = Math.min(95, Math.round(irrigation * 0.95));
const nitrateRunoff = Math.max(2, Math.round((100 - organic) * 0.6 + (irrigation > 75 ? (irrigation - 75) * 0.8 : 0)));
const biodiv = (1.2 + (organic / 100) * 1.6 + (appState.polycultureActive ? 0.9 : 0)).toFixed(2);
const carbonSink = (-0.4 - (organic / 100) * 0.8 - (appState.polycultureActive ? 0.7 : 0)).toFixed(1);
document.getElementById('metric-1-label').textContent = 'Kelembapan Tanah IoT';
document.getElementById('metric-1-val').textContent = `${soilMoisture}%`;
document.getElementById('metric-1-status').textContent = (soilMoisture >= 55 && soilMoisture <= 75) ? 'Presisi Optimal' : 'Perlu Kalibrasi Debit';
document.getElementById('metric-2-label').textContent = 'Limpasan Nitrat ke Sungai';
document.getElementById('metric-2-val').textContent = `${nitrateRunoff} ppm`;
document.getElementById('metric-2-status').textContent = nitrateRunoff = 70) {
bar.className = 'h-full bg-emerald-400 transition-all duration-500';
val.textContent = `${health}% (Lestari)`;
val.className = 'text-xs font-bold text-emerald-300';
} else if (health >= 45) {
bar.className = 'h-full bg-amber-400 transition-all duration-500';
val.textContent = `${health}% (Waspada)`;
val.className = 'text-xs font-bold text-amber-300';
} else {
bar.className = 'h-full bg-rose-500 transition-all duration-500';
val.textContent = `${health}% (Tercemar)`;
val.className = 'text-xs font-bold text-rose-400';
}
}
function buildAR3DObject(type) {
while (arModelGroup.children.length > 0) arModelGroup.remove(arModelGroup.children[0]);
appState.arExploded = false;
if (type === 'do_meter') {
const body = new THREE.Mesh(new THREE.BoxGeometry(1.1, 1.8, 0.4), new THREE.MeshStandardMaterial({ color: 0x0f172a, metalness: 0.5 }));
body.userData.partIndex = 0;
const screen = new THREE.Mesh(new THREE.PlaneGeometry(0.85, 0.7), new THREE.MeshBasicMaterial({ color: 0x10b981 }));
screen.position.set(0, 0.35, 0.21);
screen.userData.partIndex = 0;
const probe = new THREE.Mesh(new THREE.CylinderGeometry(0.12, 0.12, 1.6, 16), new THREE.MeshStandardMaterial({ color: 0x38bdf8, metalness: 0.8 }));
probe.position.set(0, -1.5, 0);
probe.userData.partIndex = 1;
const tipGuard = new THREE.Mesh(new THREE.CylinderGeometry(0.18, 0.18, 0.45, 16, 1, true), new THREE.MeshStandardMaterial({ color: 0x94a3b8, metalness: 0.85, side: THREE.DoubleSide }));
tipGuard.position.set(0, -2.15, 0);
tipGuard.userData.partIndex = 2;
arModelGroup.add(body, screen, probe, tipGuard);
} else if (type === 'soil_iot') {
const solar = new THREE.Mesh(new THREE.BoxGeometry(1.6, 0.1, 1.2), new THREE.MeshStandardMaterial({ color: 0x1d4ed8, metalness: 0.7 }));
solar.position.set(0, 1.1, 0);
solar.rotation.x = 0.3;
solar.userData.partIndex = 0;
const hub = new THREE.Mesh(new THREE.CylinderGeometry(0.4, 0.4, 1.2, 16), new THREE.MeshStandardMaterial({ color: 0xf8fafc }));
hub.userData.partIndex = 1;
const spike1 = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.02, 1.4, 12), new THREE.MeshStandardMaterial({ color: 0x94a3b8, metalness: 0.9 }));
spike1.position.set(-0.2, -1.2, 0);
spike1.userData.partIndex = 2;
const spike2 = spike1.clone();
spike2.position.set(0.2, -1.2, 0);
spike2.userData.partIndex = 2;
arModelGroup.add(solar, hub, spike1, spike2);
} else if (type === 'biofilter') {
// Reaktor Biofilter Bambu & Zeolit + Secchi Disk hitam-putih bertali
const bambooReactor = new THREE.Mesh(new THREE.CylinderGeometry(0.85, 0.85, 2.0, 20, 1, true), new THREE.MeshStandardMaterial({ color: 0x65a30d, transparent: true, opacity: 0.55, side: THREE.DoubleSide }));
bambooReactor.position.set(-0.65, 0.1, 0);
bambooReactor.userData.partIndex = 1;
const zeoliteLayer = new THREE.Mesh(new THREE.CylinderGeometry(0.78, 0.78, 0.55, 20), new THREE.MeshStandardMaterial({ color: 0xd97706 }));
zeoliteLayer.position.set(-0.65, -0.35, 0);
zeoliteLayer.userData.partIndex = 1;
const biocharLayer = new THREE.Mesh(new THREE.CylinderGeometry(0.78, 0.78, 0.55, 20), new THREE.MeshStandardMaterial({ color: 0x1e293b }));
biocharLayer.position.set(-0.65, -0.9, 0);
biocharLayer.userData.partIndex = 2;
// Secchi Disk di sisi kanan (cakram putih + kuadran hitam + tali pengukur)
const secchiWhite = new THREE.Mesh(new THREE.CylinderGeometry(0.75, 0.75, 0.08, 28), new THREE.MeshStandardMaterial({ color: 0xf8fafc, roughness: 0.35 }));
secchiWhite.position.set(0.95, -0.45, 0.25);
secchiWhite.rotation.x = 0.45;
secchiWhite.userData.partIndex = 0;
const secchiBlack1 = new THREE.Mesh(new THREE.CylinderGeometry(0.755, 0.755, 0.09, 16, 1, false, 0, Math.PI / 2), new THREE.MeshStandardMaterial({ color: 0x0f172a }));
secchiBlack1.position.set(0.95, -0.45, 0.25);
secchiBlack1.rotation.x = 0.45;
secchiBlack1.userData.partIndex = 0;
const secchiBlack2 = new THREE.Mesh(new THREE.CylinderGeometry(0.755, 0.755, 0.09, 16, 1, false, Math.PI, Math.PI / 2), new THREE.MeshStandardMaterial({ color: 0x0f172a }));
secchiBlack2.position.set(0.95, -0.45, 0.25);
secchiBlack2.rotation.x = 0.45;
secchiBlack2.userData.partIndex = 0;
const secchiRope = new THREE.Mesh(new THREE.CylinderGeometry(0.025, 0.025, 1.8, 8), new THREE.MeshStandardMaterial({ color: 0xe2e8f0 }));
secchiRope.position.set(0.95, 0.4, 0.25);
secchiRope.userData.partIndex = 0;
arModelGroup.add(bambooReactor, zeoliteLayer, biocharLayer, secchiWhite, secchiBlack1, secchiBlack2, secchiRope);
} else if (type === 'agri_drone') {
const core = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.35, 1.2), new THREE.MeshStandardMaterial({ color: 0xf59e0b }));
core.userData.partIndex = 0;
const cam = new THREE.Mesh(new THREE.SphereGeometry(0.28, 16, 16), new THREE.MeshStandardMaterial({ color: 0x0284c7 }));
cam.position.set(0, -0.3, 0.3);
cam.userData.partIndex = 1;
arModelGroup.add(core, cam);
const positions = [[-1.1, 0.2, -1.1], [1.1, 0.2, -1.1], [-1.1, 0.2, 1.1], [1.1, 0.2, 1.1]];
positions.forEach(pos => {
const rotor = new THREE.Mesh(new THREE.CylinderGeometry(0.65, 0.65, 0.05, 16), new THREE.MeshStandardMaterial({ color: 0x38bdf8, transparent: true, opacity: 0.7 }));
rotor.position.set(...pos);
rotor.userData.partIndex = 2;
arModelGroup.add(rotor);
});
}
}
function selectARModel(key) {
appState.arModel = key;
appState.arInspectedCount.add(key);
document.querySelectorAll('.ar-model-btn').forEach(btn => {
btn.className = 'ar-model-btn p-3 rounded-xl glass-panel border border-slate-300 hover:border-emerald-500 text-left transition-all';
});
const activeBtn = document.getElementById(`ar-btn-${key}`);
activeBtn.className = 'ar-model-btn p-3 rounded-xl bg-emerald-50 border-2 border-emerald-600 text-left shadow-sm transition-all';
const info = arCatalog[key];
document.getElementById('ar-detail-title').textContent = info.title;
document.getElementById('ar-detail-badge').textContent = info.badge;
document.getElementById('ar-detail-desc').textContent = info.desc;
document.getElementById('ar-detail-local').textContent = info.local;
updateARCornerReference(key);
buildAR3DObject(key);
renderARPartButtons(key);
playToneEffect('click');
if (appState.arInspectedCount.size >= 2) {
completeMission('m3', 'Anda telah menginspeksi berbagai instrumen ekologi pada mode AR.');
}
}
function explodeARModel() {
appState.arExploded = !appState.arExploded;
arModelGroup.children.forEach((child, index) => {
const offset = (index - (arModelGroup.children.length - 1) / 2) * (appState.arExploded ? 0.65 : 0);
child.position.y += appState.arExploded ? offset : -offset;
});
playToneEffect('click');
showToast(appState.arExploded ? 'Mode Bedah Komponen Aktif' : 'Komponen Dirakit Kembali', 'Amati struktur internal sensor & material biofilter.');
}
function simulateARReading() {
const info = arCatalog[appState.arModel];
playToneEffect('success');
showToast(info.title, info.reading, 'info');
completeMission('m3', 'Anda telah melakukan simulasi pengukuran instrumen pada mode AR.');
}
let arVideoStream = null;
async function toggleARCamera() {
const videoEl = document.getElementById('ar-video-feed');
const studioBg = document.getElementById('ar-studio-bg');
const statusText = document.getElementById('ar-status-text');
const btnCam = document.getElementById('btn-ar-camera');
if (!appState.arCameraActive) {
try {
arVideoStream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: { ideal: 'environment' } },
audio: false
});
videoEl.srcObject = arVideoStream;
await videoEl.play();
videoEl.classList.remove('hidden');
studioBg.classList.add('hidden');
statusText.textContent = 'LIVE CAMERA AR SMARTPHONE';
btnCam.textContent = '⏹️ Matikan Kamera AR';
appState.arCameraActive = true;
showToast('Kamera AR Aktif', 'Arahkan kamera smartphone ke meja/lantai dan putar objek 3D dengan jari.');
} catch (err) {
showToast('Mode Studio 3D Aktif', 'Izin kamera tidak tersedia di peramban ini, objek 3D tetap dapat diputar penuh.', 'warn');
}
} else {
if (arVideoStream) {
arVideoStream.getTracks().forEach(t => t.stop());
}
videoEl.classList.add('hidden');
studioBg.classList.remove('hidden');
statusText.textContent = 'SENTUH & PUTAR 360°';
btnCam.textContent = '📷 Kamera AR Smartphone';
appState.arCameraActive = false;
}
}
// --- 8. GENERATIVE AI (GEMINI API) & FALLBACK SIMULATOR ---
function fillPromptSuggestion(type) {
const input = document.getElementById('student-analysis-input');
if (type === 'dampak') {
input.value = "Menurut analisis saya, jika sensor kelembapan tanah Smart Farming mengurangi limpasan pupuk nitrat hingga 60% dan dikombinasikan dengan biofilter bambu riparian, maka blooming alga akan berhenti, dekomposisi aerob menurun, dan kadar Oksigen Terlarut (DO) akan kembali pulih di atas 6.5 mg/L dalam beberapa bulan.";
} else {
input.value = "Bagaimana kearifan lokal Lubuk Larangan dan sistem irigasi Subak dapat diintegrasikan secara berkelanjutan dengan teknologi sensor IoT modern tanpa menghilangkan peran musyawarah masyarakat adat dalam menjaga ekosistem sungai?";
}
}
async function generateDynamicCaseStudy() {
const btn = document.getElementById('btn-gen-case');
const caseBox = document.getElementById('active-case-study');
const badge = document.getElementById('case-topic-badge');
btn.disabled = true;
btn.textContent = '⏳ Menyusun Studi Kasus...';
const fallbackCases = [
{
topic: "Smart Farming & Siklus Nitrogen",
text: "Sebuah kawasan agrowisata dataran tinggi mengalami penurunan kesuburan tanah dan pencemaran sumur warga akibat pemupukan urea berlebih. Jika kelompok tani beralih ke sistem polikultur Talun yang dipadukan dengan Node Sensor NPK IoT dan pupuk organik cair, analisis bagaimana perubahan keanekaragaman mikrobioma tanah serta kualitas air tanahnya!"
},
{
topic: "Konservasi Sungai & Biofilter",
text: "Limbah organik dari pasar tradisional dan lahan pertanian di sekitar daerah aliran sungai (DAS) menyebabkan kadar DO turun menjadi 3.1 mg/L. Rancang strategi pemulihan yang menggabungkan aturan adat Lubuk Larangan, reaktor biofilter bambu-zeolit, dan pemantauan berkala menggunakan sensor Multiparameter DO!"
}
];
try {
if (!apiKey) throw new Error('No API Key provided, using rich ecological generator');
const prompt = "Buat 1 studi kasus singkat (3-4 kalimat) untuk mahasiswa Pendidikan Biologi mata kuliah Ekologi yang menggabungkan topik Pencemaran Lingkungan atau Smart Farming dengan kearifan lokal Indonesia (Subak, Talun, atau Lubuk Larangan). Bahasa Indonesia akademis.";
const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=${apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ contents: [{ parts: [{ text: prompt }] }] })
});
const data = await res.json();
const generatedText = data.candidates?.[0]?.content?.parts?.[0]?.text;
if (generatedText) {
caseBox.textContent = generatedText.trim();
badge.textContent = 'Studi Kasus Baru (Gemini AI)';
} else {
throw new Error('Empty response');
}
} catch (e) {
const pick = fallbackCases[Math.floor(Math.random() * fallbackCases.length)];
caseBox.textContent = pick.text;
badge.textContent = pick.topic;
} finally {
btn.disabled = false;
btn.textContent = '✨ Buat Variasi Studi Kasus Otomatis';
playToneEffect('success');
showToast('Studi Kasus Diperbarui', 'Silakan tuliskan analisis kritis Anda berdasarkan skenario baru.');
}
}
async function analyzeWithGenAI() {
const userText = document.getElementById('student-analysis-input').value.trim();
const caseText = document.getElementById('active-case-study').textContent.trim();
if (!userText) {
showToast('Input Masih Kosong', 'Tuliskan pendapat, hipotesis, atau pertanyaan analisis Anda terlebih dahulu.', 'warn');
return;
}
const btn = document.getElementById('btn-submit-ai');
const respContainer = document.getElementById('ai-response-container');
const respBody = document.getElementById('ai-response-body');
btn.disabled = true;
btn.innerHTML = '
⏳ Menganalisis Argumen... ';
try {
if (!apiKey) throw new Error('Using built-in multi-perspective ecological analyzer');
const systemPrompt = `Anda adalah Dosen & Mentor Ekologi untuk mahasiswa Pendidikan Biologi. Berikan evaluasi multi-perspektif atas argumen mahasiswa berikut berdasarkan studi kasus: "${caseText}". Format jawaban dalam 3 poin singkat (HTML
dengan ): 1. Perspektif Ekolog (analisis siklus materi/energi & DO/biodiversitas), 2. Perspektif Agronom Smart Farming (efisiensi teknologi presisi), 3. Perspektif Kearifan Lokal Nusantara (relevansi Subak/Talun/Lubuk Larangan), serta 1 pertanyaan reflektif lanjutan.`;
const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=${apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: `Argumen Mahasiswa: ${userText}` }] }],
systemInstruction: { parts: [{ text: systemPrompt }] }
})
});
const data = await res.json();
const aiText = data.candidates?.[0]?.content?.parts?.[0]?.text;
if (aiText) {
respBody.innerHTML = aiText.replace(/\*\*(.*?)\*\*/g, '$1 ').replace(/\n/g, ' ');
} else {
throw new Error('Empty AI text');
}
} catch (e) {
respBody.innerHTML = `
1. Perspektif Ekolog (Dinamika Perairan & Siklus Hara): Analisis Anda menunjukkan pemahaman yang kuat mengenai hubungan sebab-akibat antara beban nutrien (N dan P) dengan dinamika Oksigen Terlarut (DO). Menekan laju eutrofikasi akan memulihkan rantai makanan perairan dari produsen hingga konsumen puncak.
2. Perspektif Agronom Smart Farming: Pemanfaatan sensor kelembapan dan NPK berbasis IoT memastikan pemberian input sesuai kebutuhan fisiologis tanaman (presisi), sehingga meminimalkan pencucian hara (leaching) ke badan air.
3. Perspektif Kearifan Lokal Nusantara: Sinergi teknologi sensor dengan kelembagaan adat seperti Subak dan Lubuk Larangan memperkuat pengawasan sosial sehingga keberlanjutan ekosistem terjaga secara kolektif.
💡 Pertanyaan Reflektif Lanjutan: Jika terjadi anomali curah hujan ekstrem akibat perubahan iklim, bagaimana penyesuaian ambang batas sensor irigasi dan zona penyangga riparian harus dimodifikasi?
`;
} finally {
respContainer.classList.remove('hidden');
respContainer.classList.add('flex');
btn.disabled = false;
btn.innerHTML = '🚀 Analisis dengan Gemini AI ';
completeMission('m4', 'Anda telah menyelesaikan sintesis kritis bersama Gemini AI.');
}
}
// --- 9. QUICK HOTS QUIZ & EMAIL REPORT ---
const quizBank = [
{
topic: "Smart Farming & Siklus Hara",
q: "1. Mengapa kombinasi sensor kelembapan tanah (Smart Farming) dengan sistem polikultur Talun efektif mencegah pencemaran sungai di hilir?",
opts: [
"A. Mencegah irigasi berlebih sehingga mengurangi pencucian (leaching) nitrat ke badan air.",
"B. Meningkatkan suhu air sungai agar bakteri pengurai bekerja lebih cepat.",
"C. Menghilangkan kebutuhan fotosintesis pada tanaman budidaya di lahan kering."
],
correct: 0
},
{
topic: "Pencemaran Air & Eutrofikasi",
q: "2. Dalam ekosistem sungai yang mengalami eutrofikasi akibat limbah pupuk, apa penyebab utama kematian ikan secara massal?",
opts: [
"A. Ikan keracunan cahaya matahari yang terpantul oleh permukaan alga hijau.",
"B. Penurunan drastis Oksigen Terlarut (DO) akibat aktivitas bakteri aerob yang menguraikan alga mati.",
"C. Kenaikan pH air menjadi sangat basa akibat respirasi ikan."
],
correct: 1
},
{
topic: "Kearifan Lokal & Konservasi",
q: "3. Bagaimana peran kearifan lokal 'Lubuk Larangan' dan vegetasi riparian bambu dalam menjaga kestabilan ekosistem sungai?",
opts: [
"A. Mempercepat aliran air sungai sehingga sedimen langsung terbawa ke laut.",
"B. Menyediakan zona perlindungan trofik bagi ikan pemakan alga sekaligus fitoremediasi alami penyerap polutan.",
"C. Menggantikan seluruh fungsi dekomposer mikroba di dasar perairan."
],
correct: 1
},
{
topic: "Instrumen Ekologi & Analisis Data",
q: "4. Jika hasil pembacaan sensor AR menunjukkan DO = 2.8 mg/L dan kadar nitrat tinggi di hilir pertanian, tindakan sintesis paling tepat adalah...",
opts: [
"A. Menambah dosis pupuk urea agar tanaman lebih cepat menyerap air.",
"B. Mengkalibrasi ulang irigasi presisi IoT, mengaktifkan biofilter bambu-zeolit, dan mengurangi input pupuk kimia.",
"C. Memasukkan spesies ikan predator asing ke dalam sungai."
],
correct: 1
}
];
function renderQuizQuestion(idx) {
const item = quizBank[idx];
document.getElementById('quiz-number-label').textContent = `Soal ${idx + 1} dari ${quizBank.length}`;
document.getElementById('quiz-topic-label').textContent = item.topic;
document.getElementById('quiz-question').textContent = item.q;
const optsContainer = document.getElementById('quiz-options');
optsContainer.innerHTML = item.opts.map((opt, optIdx) => `
${opt}
`).join('');
}
function answerQuiz(qIdx, isCorrect) {
if (appState.quizAnsweredCount = quizBank.length) {
const quizBox = document.getElementById('quick-quiz-box');
quizBox.innerHTML = `
Evaluasi Tes Singkat Selesai!
Anda menjawab benar ${appState.quizScore} dari ${quizBank.length} soal analisis ekologi.
🔄 Ulangi Tes
✉️ Kirim ke Email
`;
} else {
appState.quizIndex = (qIdx + 1) % quizBank.length;
renderQuizQuestion(appState.quizIndex);
}
}
function resetQuiz() {
appState.quizIndex = 0;
appState.quizScore = 0;
appState.quizAnsweredCount = 0;
appState.quizResultsLog = [];
document.getElementById('quiz-score-badge').textContent = `Skor: 0/${quizBank.length}`;
const quizBox = document.getElementById('quick-quiz-box');
quizBox.innerHTML = `
Soal 1 dari 4
Smart Farming & Siklus Hara
`;
renderQuizQuestion(0);
}
function updateReflectionStatus() {
const val = document.getElementById('reflection-input').value.trim();
const badge = document.getElementById('reflection-status-badge');
if (val.length >= 20) {
badge.textContent = 'Refleksi Tercatat ✓';
badge.className = 'text-[11px] px-2.5 py-0.5 rounded-full bg-teal-100 text-teal-800 border border-teal-300 font-bold';
} else {
badge.textContent = 'Minimal 20 karakter';
badge.className = 'text-[11px] px-2.5 py-0.5 rounded-full bg-slate-100 text-slate-600 border border-slate-300 font-medium';
}
}
function buildStudentReportText() {
const nama = document.getElementById('student-name').value.trim() || '(Belum diisi)';
const nim = document.getElementById('student-nim').value.trim() || '(Belum diisi)';
const email = document.getElementById('student-email').value.trim() || '(Belum diisi)';
const reflection = document.getElementById('reflection-input').value.trim() || '(Belum menuliskan refleksi)';
const aiOpinion = document.getElementById('student-analysis-input').value.trim() || '(Belum menuliskan analisis GenAI)';
const doneMissions = Object.values(appState.missions).filter(Boolean).length;
const scorePercent = Math.round((appState.quizScore / quizBank.length) * 100);
const timerText = document.getElementById('session-timer').textContent;
return `LAPORAN HASIL PEMBELAJARAN INTERAKTIF EKOLOGI
Program Studi Pendidikan Biologi — Mata Kuliah Ekologi
Media: EcoSphere Nusantara (VR, Web-AR & Generative AI)
============================================================
A. IDENTITAS MAHASISWA
- Nama Mahasiswa : ${nama}
- NIM : ${nim}
- Email : ${email}
- Durasi Belajar : ${timerText} menit
B. CAPAIAN EKSPLORASI & EVALUASI TES SINGKAT
- Misi Kognitif VR/AR/GenAI : ${doneMissions} dari 4 Misi Selesai
- Skor Evaluasi Tes Singkat : ${scorePercent}/100 (${appState.quizScore} benar dari ${quizBank.length} soal)
- Rincian Jawaban Tes : ${appState.quizResultsLog.length > 0 ? appState.quizResultsLog.join(', ') : 'Belum mengerjakan tes'}
C. ANALISIS KRITIS EKOLOGI (SINTESIS GEN-AI)
"${aiOpinion}"
D. REFLEKSI ENVIRONMENTAL AWARENESS (KESADARAN LINGKUNGAN)
"${reflection}"
============================================================
Dikirim dari Aplikasi Pembelajaran Ekologi EcoSphere Nusantara.`;
}
function copyReportToClipboard() {
const reportText = buildStudentReportText();
const tempArea = document.createElement('textarea');
tempArea.value = reportText;
document.body.appendChild(tempArea);
tempArea.select();
document.execCommand('copy');
document.body.removeChild(tempArea);
playToneEffect('success');
showToast('Laporan Disalin!', 'Seluruh hasil evaluasi dan refleksi siap ditempel (paste).', 'info');
}
function sendResultsToEmail() {
const nama = document.getElementById('student-name').value.trim();
const nim = document.getElementById('student-nim').value.trim();
const email = document.getElementById('student-email').value.trim();
if (!nama || !nim || !email) {
showToast('Lengkapi Identitas Mahasiswa', 'Mohon isi Nama, NIM, dan alamat Email Mahasiswa pada bagian atas halaman terlebih dahulu.', 'warn');
document.getElementById('student-name').focus();
return;
}
const subject = encodeURIComponent(`Hasil Belajar & Evaluasi Ekologi - ${nama} (${nim})`);
const body = encodeURIComponent(buildStudentReportText());
playToneEffect('success');
showToast('Membuka Klien Email...', `Mengirim rekap hasil belajar & evaluasi ke ${email}.`, 'info');
window.location.href = `mailto:${encodeURIComponent(email)}?subject=${subject}&body=${body}`;
}
// --- 10. ANIMATION LOOP & RESPONSIVE RESIZE ---
function animate() {
requestAnimationFrame(animate);
// Animasi VR
if (vrRenderer && vrScene && vrCamera && appState.mode === 'vr') {
if (fishGroup && appState.vrScene === 'pollution') {
fishGroup.children.forEach((fish, i) => {
fish.position.z += 0.025;
if (fish.position.z > 7) fish.position.z = -7;
fish.position.x += Math.sin(Date.now() * 0.003 + i) * 0.005;
});
}
if (sprinklerParticles && appState.vrScene === 'smartfarm' && sprinklerParticles.visible) {
sprinklerParticles.children.forEach(drop => {
drop.position.y -= 0.03;
if (drop.position.y {
resizeVRCanvas();
resizeARCanvas();
});
function boot3DScenes() {
if (typeof THREE === 'undefined') {
setTimeout(boot3DScenes, 150);
return;
}
if (!vrRenderer) initVR();
if (!arRenderer) initAR();
resizeVRCanvas();
resizeARCanvas();
}
if (document.readyState === 'complete') {
boot3DScenes();
animate();
} else {
window.addEventListener('load', function () {
boot3DScenes();
setTimeout(() => {
resizeVRCanvas();
resizeARCanvas();
}, 120);
animate();
});
}