Back to the app
The code
Night Courier by Gemini 4 Hydrogen
Exactly as the AI wrote it. Shown as text, so nothing runs on this page.
index.html
works · auto-checked (Checked by an automated pass. Not hand-played yet.)<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<link rel="icon" href="data:,">
<title>Night Courier — Sunset Lake Delivery</title>
<style>
:root {
--glass-bg: rgba(24, 16, 36, 0.62);
--glass-border: rgba(255, 214, 158, 0.28);
--gold: #ffbe5c;
--coral: #ff7b54;
--cream: #fff5e4;
--mint: #6ee7b7;
}
* {
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
user-select: none;
-webkit-user-select: none;
}
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: #1a1426;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
color: var(--cream);
touch-action: none;
}
#gameCanvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: crosshair;
}
/* Subtle mouse reticle */
#mouseReticle {
position: fixed;
width: 34px;
height: 34px;
margin-left: -17px;
margin-top: -17px;
border-radius: 50%;
border: 2px solid rgba(255, 224, 165, 0.72);
box-shadow: 0 0 12px rgba(255, 172, 85, 0.45);
pointer-events: none;
z-index: 8;
opacity: 0;
transition: opacity 0.2s ease;
}
#mouseReticle::after {
content: "";
position: absolute;
left: 50%;
top: 50%;
width: 6px;
height: 6px;
margin: -3px 0 0 -3px;
border-radius: 50%;
background: #ffe0a5;
}
/* Touch drag steering indicator */
#touchIndicator {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 9;
display: none;
}
#touchBase {
position: absolute;
width: 112px;
height: 112px;
margin: -56px 0 0 -56px;
border-radius: 50%;
border: 2px dashed rgba(255, 224, 165, 0.55);
background: radial-gradient(circle, rgba(255, 190, 92, 0.14), rgba(24, 16, 36, 0.22));
}
#touchKnob {
position: absolute;
width: 48px;
height: 48px;
margin: -24px 0 0 -24px;
border-radius: 50%;
background: radial-gradient(circle at 35% 35%, #fff2d6, #ff9d4d);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4), 0 0 14px rgba(255, 175, 85, 0.6);
}
/* Directional offscreen ring compass arrow */
#ringPointer {
position: fixed;
width: 48px;
height: 48px;
margin: -24px 0 0 -24px;
pointer-events: none;
z-index: 10;
display: none;
flex-direction: column;
align-items: center;
justify-content: center;
}
#ringArrowShape {
width: 34px;
height: 34px;
filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.55));
}
#ringDistLabel {
font-size: 11px;
font-weight: 700;
color: #fff3d6;
text-shadow: 0 1px 4px rgba(0, 0, 0, 0.85);
margin-top: -2px;
letter-spacing: 0.3px;
}
/* Top HUD */
.hud-top {
position: fixed;
top: max(12px, env(safe-area-inset-top));
left: max(12px, env(safe-area-inset-left));
right: max(12px, env(safe-area-inset-right));
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
z-index: 20;
pointer-events: none;
}
.hud-group {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
pointer-events: none;
}
.pill {
pointer-events: auto;
display: inline-flex;
align-items: center;
gap: 8px;
background: var(--glass-bg);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border: 1px solid var(--glass-border);
border-radius: 999px;
padding: 8px 14px;
min-height: 44px;
box-shadow: 0 6px 20px rgba(10, 6, 20, 0.35);
font-size: 15px;
font-weight: 700;
letter-spacing: 0.2px;
}
.pill-label {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.8px;
opacity: 0.78;
font-weight: 600;
display: block;
line-height: 1;
margin-bottom: 2px;
}
.pill-value {
font-size: 17px;
line-height: 1.05;
color: #fff7ea;
font-variant-numeric: tabular-nums;
}
.pill.bump {
animation: popBump 0.32s ease;
}
@keyframes popBump {
0% { transform: scale(1); }
45% { transform: scale(1.1); border-color: rgba(255, 210, 120, 0.85); }
100% { transform: scale(1); }
}
/* Daylight / Nightfall progress pill */
.daylight-pill {
min-width: 156px;
flex-direction: column;
align-items: stretch;
gap: 5px;
padding: 8px 14px;
}
.daylight-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
font-size: 12px;
font-weight: 700;
}
.daylight-track {
width: 100%;
height: 7px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.14);
overflow: hidden;
}
.daylight-fill {
height: 100%;
width: 100%;
border-radius: 999px;
background: linear-gradient(90deg, #ffd166, #ff7b54, #c44d8f);
transition: width 0.18s linear;
}
.daylight-pill.urgent {
border-color: rgba(255, 110, 96, 0.75);
animation: pulseUrgent 1.1s ease-in-out infinite;
}
@keyframes pulseUrgent {
0%, 100% { box-shadow: 0 6px 20px rgba(10, 6, 20, 0.35); }
50% { box-shadow: 0 0 22px rgba(255, 100, 90, 0.55); }
}
.icon-btn {
pointer-events: auto;
width: 46px;
height: 46px;
border-radius: 50%;
border: 1px solid var(--glass-border);
background: var(--glass-bg);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
color: var(--cream);
display: inline-flex;
align-items: center;
justify-content: center;
cursor: pointer;
box-shadow: 0 6px 20px rgba(10, 6, 20, 0.35);
transition: transform 0.15s ease, background 0.15s ease;
padding: 0;
}
.icon-btn:active {
transform: scale(0.92);
}
/* Bottom Camera Bar */
.camera-dock {
position: fixed;
bottom: max(14px, env(safe-area-inset-bottom));
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 8px;
padding: 6px;
border-radius: 999px;
background: var(--glass-bg);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid var(--glass-border);
box-shadow: 0 10px 28px rgba(8, 4, 18, 0.48);
z-index: 25;
max-width: calc(100vw - 24px);
}
.cam-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 7px;
min-height: 46px;
padding: 8px 16px;
border-radius: 999px;
border: 1px solid transparent;
background: transparent;
color: rgba(255, 245, 228, 0.86);
font-family: inherit;
font-size: 14px;
font-weight: 700;
cursor: pointer;
white-space: nowrap;
transition: transform 0.14s ease, background 0.2s ease, color 0.2s ease, box-shadow 0.2s ease;
}
.cam-btn:active {
transform: scale(0.94);
}
.cam-btn.active {
background: linear-gradient(135deg, #ffbd59, #ff7e54);
color: #241219;
box-shadow: 0 4px 14px rgba(255, 145, 77, 0.45);
}
.cam-btn svg {
width: 19px;
height: 19px;
flex-shrink: 0;
}
/* Toast & Demo Banner */
#toast {
position: fixed;
top: calc(max(12px, env(safe-area-inset-top)) + 64px);
left: 50%;
transform: translateX(-50%) translateY(-10px);
background: rgba(28, 18, 42, 0.84);
border: 1px solid rgba(255, 214, 140, 0.45);
color: #fff6e5;
padding: 9px 18px;
border-radius: 999px;
font-size: 14px;
font-weight: 700;
z-index: 22;
pointer-events: none;
opacity: 0;
transition: opacity 0.25s ease, transform 0.25s ease;
white-space: nowrap;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
}
#toast.show {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
#demoBanner {
position: fixed;
bottom: calc(max(14px, env(safe-area-inset-bottom)) + 68px);
left: 50%;
transform: translateX(-50%);
background: rgba(24, 16, 38, 0.78);
border: 1px solid rgba(255, 206, 120, 0.5);
color: #ffe7bf;
padding: 8px 16px;
border-radius: 999px;
font-size: 13px;
font-weight: 700;
letter-spacing: 0.3px;
z-index: 21;
pointer-events: none;
display: none;
white-space: nowrap;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
}
/* Modal Overlays (Start & End) */
.overlay {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
z-index: 40;
background: radial-gradient(circle at center, rgba(22, 12, 34, 0.32), rgba(14, 9, 24, 0.68));
transition: opacity 0.3s ease;
}
.overlay.hidden {
opacity: 0;
pointer-events: none;
}
.card {
width: min(440px, 100%);
background: linear-gradient(165deg, rgba(38, 24, 52, 0.92), rgba(22, 15, 36, 0.94));
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255, 208, 138, 0.35);
border-radius: 26px;
padding: 28px 24px 24px;
text-align: center;
box-shadow: 0 24px 60px rgba(5, 2, 15, 0.65);
}
.badge-cat {
display: inline-flex;
align-items: center;
justify-content: center;
width: 64px;
height: 64px;
border-radius: 20px;
background: linear-gradient(135deg, #ffb454, #ff6b4a);
box-shadow: 0 8px 24px rgba(255, 128, 72, 0.4);
margin-bottom: 12px;
}
.card h1 {
margin: 0 0 8px;
font-size: clamp(26px, 5vw, 34px);
line-height: 1.1;
color: #fff6e8;
letter-spacing: -0.4px;
}
.card p {
margin: 0 0 18px;
font-size: 15px;
line-height: 1.48;
color: rgba(255, 239, 217, 0.86);
}
.controls-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-bottom: 20px;
text-align: left;
}
.control-tip {
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 214, 158, 0.16);
border-radius: 14px;
padding: 10px 12px;
font-size: 13px;
line-height: 1.35;
color: rgba(255, 240, 220, 0.88);
}
.control-tip strong {
display: block;
color: var(--gold);
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 3px;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
margin-bottom: 22px;
}
.stat-box {
background: rgba(255, 255, 255, 0.07);
border: 1px solid rgba(255, 214, 158, 0.18);
border-radius: 16px;
padding: 12px 8px;
}
.stat-box .num {
display: block;
font-size: 22px;
font-weight: 800;
color: var(--gold);
font-variant-numeric: tabular-nums;
}
.stat-box .lbl {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.6px;
opacity: 0.78;
}
.primary-btn {
width: 100%;
min-height: 54px;
border: none;
border-radius: 16px;
background: linear-gradient(135deg, #ffc45c, #ff7a4f);
color: #261116;
font-family: inherit;
font-size: 18px;
font-weight: 800;
letter-spacing: 0.3px;
cursor: pointer;
box-shadow: 0 10px 26px rgba(255, 132, 74, 0.45);
transition: transform 0.15s ease, filter 0.15s ease;
}
.primary-btn:active {
transform: scale(0.97);
}
@media (max-width: 560px) {
.pill {
padding: 6px 11px;
min-height: 42px;
gap: 6px;
}
.pill-value { font-size: 15px; }
.daylight-pill { min-width: 122px; padding: 6px 11px; }
.cam-btn { padding: 8px 12px; font-size: 13px; min-height: 44px; gap: 5px; }
.cam-btn svg { width: 17px; height: 17px; }
.controls-grid { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<div id="mouseReticle"></div>
<div id="touchIndicator">
<div id="touchBase"></div>
<div id="touchKnob"></div>
</div>
<div id="ringPointer">
<svg id="ringArrowShape" viewBox="0 0 36 36">
<path d="M18 3 L31 28 L18 22 L5 28 Z" fill="#ffd166" stroke="#2d1724" stroke-width="2.2" stroke-linejoin="round"/>
</svg>
<span id="ringDistLabel">90m</span>
</div>
<!-- Top HUD -->
<div class="hud-top">
<div class="hud-group">
<div class="pill" id="scorePill">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none">
<path d="M21 12c-3-4.5-7.5-6-11-6-2.5 0-4.8 1-6.5 2.5L1 7v10l2.5-1.5C5.2 17 7.5 18 10 18c3.5 0 8-1.5 11-6Z" fill="#ffd166"/>
<circle cx="15.5" cy="11" r="1.4" fill="#2a1622"/>
</svg>
<div>
<span class="pill-label">Score</span>
<span class="pill-value" id="scoreVal">0</span>
</div>
</div>
<div class="pill" id="cratesPill">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none">
<rect x="3" y="4" width="18" height="16" rx="3" fill="#e59f58" stroke="#fff2d8" stroke-width="1.6"/>
<path d="M3 10h18M9 4v16M15 4v16" stroke="#7c4720" stroke-width="1.6"/>
</svg>
<div>
<span class="pill-label">Crates Left</span>
<span class="pill-value" id="cratesVal">8</span>
</div>
</div>
</div>
<div class="hud-group">
<div class="pill daylight-pill" id="daylightPill">
<div class="daylight-row">
<span id="timePhaseLabel">Sunset</span>
<span id="timeLeftVal">1:30</span>
</div>
<div class="daylight-track">
<div class="daylight-fill" id="daylightFill"></div>
</div>
</div>
<button class="icon-btn" id="soundBtn" aria-label="Toggle Sound" title="Toggle Sound">
<svg id="soundOnIcon" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" fill="currentColor" stroke="none"/>
<path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>
<path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>
</svg>
<svg id="soundOffIcon" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="display:none">
<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" fill="currentColor" stroke="none"/>
<line x1="22" y1="9" x2="16" y2="15"/>
<line x1="16" y1="9" x2="22" y2="15"/>
</svg>
</button>
</div>
</div>
<div id="toast"></div>
<div id="demoBanner">Auto-Flight Preview — Touch or click anywhere to fly</div>
<!-- Bottom Camera Switcher -->
<div class="camera-dock" id="cameraDock">
<button class="cam-btn active" data-cam="behind" id="camBehind">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 3l3 7 6 2-6 2-1 5-2-1-2 1-1-5-6-2 6-2 3-7z"/>
</svg>
<span>Behind</span>
</button>
<button class="cam-btn" data-cam="cockpit" id="camCockpit">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round">
<path d="M3 16c0-5 4-9 9-9s9 4 9 9"/>
<path d="M3 16h18"/>
<path d="M12 7v9"/>
<circle cx="8" cy="19" r="1.4" fill="currentColor"/>
<circle cx="16" cy="19" r="1.4" fill="currentColor"/>
</svg>
<span>Cockpit</span>
</button>
<button class="cam-btn" data-cam="above" id="camAbove">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="8"/>
<circle cx="12" cy="12" r="3"/>
<path d="M12 2v3M12 19v3M2 12h3M19 12h3"/>
</svg>
<span>Above</span>
</button>
</div>
<!-- Start Screen -->
<div class="overlay" id="startOverlay">
<div class="card">
<div class="badge-cat">
<svg width="36" height="36" viewBox="0 0 36 36" fill="none">
<path d="M7 11L9 21C9 26.5 13 30 18 30C23 30 27 26.5 27 21L29 11L23 14.5C21.5 13.8 19.8 13.5 18 13.5C16.2 13.5 14.5 13.8 13 14.5L7 11Z" fill="#fff5e4"/>
<circle cx="14" cy="20" r="1.8" fill="#2b1720"/>
<circle cx="22" cy="20" r="1.8" fill="#2b1720"/>
<path d="M16.5 23L18 24.5L19.5 23" stroke="#ff6b4a" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</div>
<h1>Night Courier</h1>
<p>Pilot the little propeller plane over the lake town at sunset. Fly through glowing sky rings to parachute fish crates down to cats waiting on rooftops and docks before night falls!</p>
<div class="controls-grid">
<div class="control-tip">
<strong>Mouse</strong>
Move your pointer to guide the plane smoothly through the rings.
</div>
<div class="control-tip">
<strong>Touch</strong>
Drag one finger anywhere on screen to climb, dive, and turn.
</div>
</div>
<button class="primary-btn" id="startBtn">Take Off</button>
</div>
</div>
<!-- End Screen -->
<div class="overlay hidden" id="endOverlay">
<div class="card">
<div class="badge-cat" id="endBadge">
<svg width="36" height="36" viewBox="0 0 36 36" fill="none">
<path d="M18 5L21.8 12.8L30.4 14L24.2 20L25.7 28.5L18 24.5L10.3 28.5L11.8 20L5.6 14L14.2 12.8L18 5Z" fill="#fff5e4"/>
</svg>
</div>
<h1 id="endTitle">All Crates Delivered!</h1>
<p id="endSubtitle">Every lakeside cat got their sunset fish dinner right on time.</p>
<div class="stats-grid">
<div class="stat-box">
<span class="num" id="endScore">0</span>
<span class="lbl">Score</span>
</div>
<div class="stat-box">
<span class="num" id="endDelivered">8/8</span>
<span class="lbl">Delivered</span>
</div>
<div class="stat-box">
<span class="num" id="endBest">0</span>
<span class="lbl">Best</span>
</div>
</div>
<button class="primary-btn" id="playAgainBtn">Play Again</button>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script>
(function () {
'use strict';
if (typeof THREE === 'undefined') {
document.body.innerHTML = '<div style="padding:32px;color:#fff;font-family:sans-serif;text-align:center;"><h2>3D library failed to load</h2><p>Please check your connection and reload.</p></div>';
return;
}
// =========================================================================
// 1. UTILITIES & SAFE STORAGE
// =========================================================================
const TOTAL_CRATES = 8;
const TOTAL_FLIGHT_SECONDS = 90.0;
const DEMO_LOOP_SECONDS = 20.0;
const RING_HIT_RADIUS = 10.6;
const STORAGE_KEY = 'night_courier_best_v1';
function clamp(v, min, max) {
return v < min ? min : v > max ? max : v;
}
function lerp(a, b, t) {
return a + (b - a) * t;
}
function smoothstep(edge0, edge1, x) {
const t = clamp((x - edge0) / (edge1 - edge0), 0, 1);
return t * t * (3 - 2 * t);
}
function srgbColor(hex) {
return new THREE.Color(hex).convertSRGBToLinear();
}
function readBestScore() {
try {
const v = parseInt(localStorage.getItem(STORAGE_KEY) || '0', 10);
return Number.isFinite(v) ? v : 0;
} catch (e) {
return 0;
}
}
function saveBestScore(score) {
try {
const prev = readBestScore();
if (score > prev) localStorage.setItem(STORAGE_KEY, String(score));
} catch (e) {}
}
// =========================================================================
// 2. PROCEDURAL WEB AUDIO ENGINE
// =========================================================================
class SoundEngine {
constructor() {
this.ctx = null;
this.muted = false;
this.engineOsc = null;
this.engineGain = null;
this.engineFilter = null;
this.started = false;
}
init() {
if (this.started || this.muted) return;
try {
const AudioCtx = window.AudioContext || window.webkitAudioContext;
if (!AudioCtx) return;
this.ctx = new AudioCtx();
if (this.ctx.state === 'suspended') this.ctx.resume();
// Cozy soft propeller purr
const osc = this.ctx.createOscillator();
const sub = this.ctx.createOscillator();
const filter = this.ctx.createBiquadFilter();
const gain = this.ctx.createGain();
osc.type = 'sawtooth';
osc.frequency.value = 54;
sub.type = 'triangle';
sub.frequency.value = 27;
filter.type = 'lowpass';
filter.frequency.value = 180;
filter.Q.value = 1.2;
gain.gain.value = 0.0;
osc.connect(filter);
sub.connect(filter);
filter.connect(gain);
gain.connect(this.ctx.destination);
osc.start();
sub.start();
this.engineOsc = osc;
this.engineSub = sub;
this.engineFilter = filter;
this.engineGain = gain;
this.started = true;
} catch (e) {}
}
setMuted(m) {
this.muted = m;
if (this.engineGain && this.ctx) {
this.engineGain.gain.setTargetAtTime(m ? 0 : 0.032, this.ctx.currentTime, 0.08);
}
if (!m && !this.started) this.init();
}
updateProp(speedNorm, active) {
if (!this.started || !this.ctx || !this.engineGain) return;
if (this.ctx.state === 'suspended') this.ctx.resume().catch(() => {});
const t = this.ctx.currentTime;
const targetVol = (this.muted || !active) ? 0.0 : 0.028 + speedNorm * 0.014;
const baseFreq = 50 + speedNorm * 16;
this.engineGain.gain.setTargetAtTime(targetVol, t, 0.1);
this.engineOsc.frequency.setTargetAtTime(baseFreq, t, 0.08);
this.engineSub.frequency.setTargetAtTime(baseFreq * 0.5, t, 0.08);
this.engineFilter.frequency.setTargetAtTime(165 + speedNorm * 85, t, 0.1);
}
playRingChime(index) {
if (this.muted || !this.ctx) return;
try {
const now = this.ctx.currentTime;
const notes = [523.25, 587.33, 659.25, 783.99, 880.0, 987.77, 1046.5, 1174.66];
const f1 = notes[index % notes.length];
const f2 = f1 * 1.5;
[f1, f2].forEach((freq, i) => {
const osc = this.ctx.createOscillator();
const gain = this.ctx.createGain();
osc.type = 'triangle';
osc.frequency.setValueAtTime(freq, now + i * 0.06);
gain.gain.setValueAtTime(0.001, now + i * 0.06);
gain.gain.exponentialRampToValueAtTime(0.11, now + i * 0.06 + 0.02);
gain.gain.exponentialRampToValueAtTime(0.0001, now + i * 0.06 + 0.48);
osc.connect(gain);
gain.connect(this.ctx.destination);
osc.start(now + i * 0.06);
osc.stop(now + i * 0.06 + 0.5);
});
} catch (e) {}
}
playDeliveryMeow() {
if (this.muted || !this.ctx) return;
try {
const now = this.ctx.currentTime;
// Cute rising-then-falling cat chirp + bell
const osc = this.ctx.createOscillator();
const gain = this.ctx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(620, now);
osc.frequency.exponentialRampToValueAtTime(920, now + 0.09);
osc.frequency.exponentialRampToValueAtTime(710, now + 0.24);
gain.gain.setValueAtTime(0.001, now);
gain.gain.exponentialRampToValueAtTime(0.09, now + 0.03);
gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.28);
osc.connect(gain);
gain.connect(this.ctx.destination);
osc.start(now);
osc.stop(now + 0.3);
const bell = this.ctx.createOscillator();
const bGain = this.ctx.createGain();
bell.type = 'triangle';
bell.frequency.setValueAtTime(1046.5, now + 0.08);
bGain.gain.setValueAtTime(0.001, now + 0.08);
bGain.gain.exponentialRampToValueAtTime(0.07, now + 0.1);
bGain.gain.exponentialRampToValueAtTime(0.0001, now + 0.52);
bell.connect(bGain);
bGain.connect(this.ctx.destination);
bell.start(now + 0.08);
bell.stop(now + 0.55);
} catch (e) {}
}
playFanfare(won) {
if (this.muted || !this.ctx) return;
try {
const now = this.ctx.currentTime;
const seq = won ? [523.25, 659.25, 783.99, 1046.5] : [392.0, 349.23, 329.63, 261.63];
seq.forEach((f, idx) => {
const osc = this.ctx.createOscillator();
const gain = this.ctx.createGain();
osc.type = 'triangle';
const t0 = now + idx * 0.11;
osc.frequency.setValueAtTime(f, t0);
gain.gain.setValueAtTime(0.001, t0);
gain.gain.exponentialRampToValueAtTime(0.11, t0 + 0.03);
gain.gain.exponentialRampToValueAtTime(0.0001, t0 + 0.65);
osc.connect(gain);
gain.connect(this.ctx.destination);
osc.start(t0);
osc.stop(t0 + 0.7);
});
} catch (e) {}
}
}
const sound = new SoundEngine();
// =========================================================================
// 3. PROCEDURAL CANVAS TEXTURES
// =========================================================================
function createCrateTexture() {
const c = document.createElement('canvas');
c.width = 128;
c.height = 128;
const g = c.getContext('2d');
g.fillStyle = '#cf8a49';
g.fillRect(0, 0, 128, 128);
g.fillStyle = '#b47236';
for (let y = 0; y < 128; y += 32) {
g.fillRect(0, y, 128, 3);
}
g.strokeStyle = '#e5a764';
g.lineWidth = 14;
g.strokeRect(7, 7, 114, 114);
// Cute fish emblem
g.fillStyle = '#2d688f';
g.beginPath();
g.ellipse(68, 64, 24, 13, 0, 0, Math.PI * 2);
g.fill();
g.beginPath();
g.moveTo(42, 64);
g.lineTo(28, 52);
g.lineTo(28, 76);
g.closePath();
g.fill();
g.fillStyle = '#fff3d6';
g.beginPath();
g.arc(80, 61, 3, 0, Math.PI * 2);
g.fill();
const tex = new THREE.CanvasTexture(c);
tex.encoding = THREE.sRGBEncoding;
return tex;
}
function createLandingMatTexture() {
const c = document.createElement('canvas');
c.width = 128;
c.height = 128;
const g = c.getContext('2d');
g.clearRect(0, 0, 128, 128);
g.fillStyle = 'rgba(255, 198, 92, 0.92)';
g.beginPath();
g.arc(64, 64, 56, 0, Math.PI * 2);
g.fill();
g.fillStyle = '#402533';
g.beginPath();
g.arc(64, 64, 42, 0, Math.PI * 2);
g.fill();
g.fillStyle = '#ffd166';
g.beginPath();
g.arc(64, 64, 22, 0, Math.PI * 2);
g.fill();
const tex = new THREE.CanvasTexture(c);
tex.encoding = THREE.sRGBEncoding;
return tex;
}
function createGaugeTexture() {
const c = document.createElement('canvas');
c.width = 128;
c.height = 128;
const g = c.getContext('2d');
g.fillStyle = '#1b1626';
g.beginPath();
g.arc(64, 64, 60, 0, Math.PI * 2);
g.fill();
g.strokeStyle = '#e5a764';
g.lineWidth = 5;
g.stroke();
g.strokeStyle = '#fff0d4';
g.lineWidth = 3;
for (let i = 0; i < 12; i++) {
const a = (i / 12) * Math.PI * 2;
g.beginPath();
g.moveTo(64 + Math.cos(a) * 44, 64 + Math.sin(a) * 44);
g.lineTo(64 + Math.cos(a) * 52, 64 + Math.sin(a) * 52);
g.stroke();
}
const tex = new THREE.CanvasTexture(c);
tex.encoding = THREE.sRGBEncoding;
return tex;
}
// =========================================================================
// 4. TERRAIN & LAKE GEOGRAPHY
// =========================================================================
function getLakeRadius(ang) {
return 146 + 18 * Math.sin(ang * 2.0 + 0.4) + 12 * Math.cos(ang * 3.0 - 0.7);
}
function getTerrainHeight(x, z) {
const r = Math.hypot(x, z);
const ang = Math.atan2(z, x);
const lr = getLakeRadius(ang);
const d = r - lr;
// Gentle central island around (12, -8)
const ix = x - 10;
const iz = z + 8;
const ir = Math.hypot(ix, iz);
const islandBump = 12.2 * Math.exp(-(ir * ir) / (27 * 27));
if (d < 0) {
// Smooth lakebed
const depth = -7.5 * smoothstep(0, -34, d);
return depth + islandBump;
}
// Town terrace band: 0 <= d < 58
const terrace = 5.5 * smoothstep(0, 24, d) + 4.0 * smoothstep(24, 64, d);
// Rolling hills outside town
const hillMask = smoothstep(42, 130, d);
const ridgeA = 34 * (0.5 + 0.5 * Math.sin(x * 0.016 + 0.4) * Math.cos(z * 0.015 - 0.3));
const ridgeB = 22 * (0.5 + 0.5 * Math.sin((x + z) * 0.022));
const outerPeak = 46 * smoothstep(140, 320, d);
const smallWaves = 1.4 * Math.sin(x * 0.05) * Math.cos(z * 0.05) * smoothstep(8, 35, d);
return terrace + smallWaves + hillMask * (ridgeA + ridgeB + outerPeak) + islandBump;
}
// =========================================================================
// 5. THREE.JS SCENE, RENDERER & PLANAR WATER REFLECTION SETUP
// =========================================================================
const canvas = document.getElementById('gameCanvas');
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: 'high-performance'
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.shadowMap.autoUpdate = false;
renderer.localClippingEnabled = true;
const scene = new THREE.Scene();
const fog = new THREE.FogExp2(srgbColor('#e68255'), 0.00145);
scene.fog = fog;
const mainCam = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.16, 1600);
const reflCam = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.16, 1600);
const reflClipPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0.08);
let reflTarget = new THREE.WebGLRenderTarget(
Math.max(128, Math.floor(window.innerWidth * 0.45)),
Math.max(128, Math.floor(window.innerHeight * 0.45)),
{ minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat }
);
// Lights
const hemiLight = new THREE.HemisphereLight(srgbColor('#ffd0a3'), srgbColor('#3b4e42'), 0.85);
scene.add(hemiLight);
const sunLight = new THREE.DirectionalLight(srgbColor('#ffc678'), 1.95);
sunLight.position.set(-160, 82, -190);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(1024, 1024);
sunLight.shadow.camera.near = 20;
sunLight.shadow.camera.far = 620;
const sc = 235;
sunLight.shadow.camera.left = -sc;
sunLight.shadow.camera.right = sc;
sunLight.shadow.camera.top = sc;
sunLight.shadow.camera.bottom = -sc;
sunLight.shadow.bias = -0.0006;
scene.add(sunLight);
// =========================================================================
// 6. SKY DOME & WATER REFLECTION SHADERS
// =========================================================================
const skyUniforms = {
uSunDir: { value: new THREE.Vector3(-0.6, 0.25, -0.75).normalize() },
uZenithColor: { value: srgbColor('#3b6099') },
uHorizonColor: { value: srgbColor('#ff8e53') },
uSunGlowColor: { value: srgbColor('#ffd98c') },
uNightFactor: { value: 0.0 },
uTime: { value: 0.0 }
};
const skyMat = new THREE.ShaderMaterial({
uniforms: skyUniforms,
side: THREE.BackSide,
depthWrite: false,
toneMapped: true,
vertexShader: `
varying vec3 vWorldDir;
void main() {
vWorldDir = position;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 uSunDir;
uniform vec3 uZenithColor;
uniform vec3 uHorizonColor;
uniform vec3 uSunGlowColor;
uniform float uNightFactor;
uniform float uTime;
varying vec3 vWorldDir;
float hash3(vec3 p) {
p = fract(p * vec3(443.897, 441.423, 437.195));
p += dot(p, p.yzx + 19.19);
return fract((p.x + p.y) * p.z);
}
void main() {
vec3 dir = normalize(vWorldDir);
float h = clamp(dir.y, 0.0, 1.0);
vec3 col = mix(uHorizonColor, uZenithColor, pow(h, 0.56));
if (dir.y < 0.0) {
col = mix(uHorizonColor, uHorizonColor * 0.45, clamp(-dir.y * 4.0, 0.0, 1.0));
}
// Warm sunset atmospheric bloom + sun disc
vec3 sDir = normalize(uSunDir);
float sunDot = max(dot(dir, sDir), 0.0);
float horizonVis = smoothstep(-0.10, 0.04, dir.y) * (1.0 - smoothstep(0.75, 1.0, uNightFactor));
col += uSunGlowColor * (pow(sunDot, 5.0) * 0.42 + pow(sunDot, 38.0) * 0.72) * (1.0 - uNightFactor * 0.7);
float sunDisc = smoothstep(0.9975, 0.9992, sunDot) * horizonVis;
col += uSunGlowColor * sunDisc * 2.8;
// Subtle stars & moon glow at dusk/night
if (uNightFactor > 0.25 && dir.y > 0.04) {
vec3 grid = floor(dir * 270.0);
float r = hash3(grid);
if (r > 0.9935) {
float twinkle = 0.55 + 0.45 * sin(uTime * 2.6 + r * 90.0);
float starFade = smoothstep(0.25, 0.85, uNightFactor) * smoothstep(0.04, 0.22, dir.y);
col += vec3(0.85, 0.90, 1.0) * twinkle * starFade * 1.1;
}
}
// Soft crescent moon high in east sky
vec3 moonDir = normalize(vec3(0.55, 0.52, 0.65));
float mDot = max(dot(dir, moonDir), 0.0);
float moonHalo = pow(mDot, 28.0) * 0.14 * smoothstep(0.2, 0.9, uNightFactor);
float moonDisc = smoothstep(0.9986, 0.9993, mDot) * smoothstep(0.25, 0.8, uNightFactor);
col += vec3(0.75, 0.84, 1.0) * (moonHalo + moonDisc * 1.4);
gl_FragColor = vec4(col, 1.0);
#include <tonemapping_fragment>
#include <encodings_fragment>
}
`
});
const skyMesh = new THREE.Mesh(new THREE.SphereGeometry(980, 32, 20), skyMat);
skyMesh.renderOrder = -10;
skyMesh.frustumCulled = false;
scene.add(skyMesh);
// Planar Reflection Water Mesh
const reflProjView = new THREE.Matrix4();
const waterUniforms = {
uReflProjView: { value: reflProjView },
uReflectionTex: { value: reflTarget.texture },
uTime: { value: 0.0 },
uSunDir: { value: skyUniforms.uSunDir.value },
uSunColor: { value: srgbColor('#ffd480') },
uWaterBaseColor: { value: srgbColor('#1e4959') },
uFogColor: { value: fog.color },
uFogDensity: { value: fog.density }
};
const waterMat = new THREE.ShaderMaterial({
uniforms: waterUniforms,
toneMapped: true,
vertexShader: `
uniform mat4 uReflProjView;
varying vec3 vWorldPos;
varying vec4 vReflClipPos;
void main() {
vec4 worldPos = modelMatrix * vec4(position, 1.0);
vWorldPos = worldPos.xyz;
vReflClipPos = uReflProjView * worldPos;
gl_Position = projectionMatrix * viewMatrix * worldPos;
}
`,
fragmentShader: `
uniform sampler2D uReflectionTex;
uniform float uTime;
uniform vec3 uSunDir;
uniform vec3 uSunColor;
uniform vec3 uWaterBaseColor;
uniform vec3 uFogColor;
uniform float uFogDensity;
varying vec3 vWorldPos;
varying vec4 vReflClipPos;
void main() {
vec2 p = vWorldPos.xz;
float t = uTime;
// Animated water ripple normal
float w1 = sin(p.x * 0.24 + t * 1.5 + sin(p.y * 0.16 + t * 0.8));
float w2 = cos(p.y * 0.31 - t * 1.3 + cos(p.x * 0.19 - t * 0.6));
float w3 = sin((p.x + p.y) * 0.45 + t * 2.1);
vec2 grad = vec2(
w1 * 0.011 + w3 * 0.007,
w2 * 0.011 - w3 * 0.007
);
vec2 ndc = vReflClipPos.xy / max(vReflClipPos.w, 0.0001);
vec2 reflUV = ndc * 0.5 + 0.5;
vec2 distUV = clamp(reflUV + grad * 1.45, vec2(0.003), vec2(0.997));
vec3 reflCol = texture2D(uReflectionTex, distUV).rgb;
vec3 N = normalize(vec3(grad.x * 4.2, 1.0, grad.y * 4.2));
vec3 V = normalize(cameraPosition - vWorldPos);
float fresnel = mix(0.18, 0.94, pow(1.0 - clamp(dot(N, V), 0.0, 1.0), 3.4));
vec3 col = mix(uWaterBaseColor, reflCol, fresnel);
// Sparkling sun glitter path on lake
vec3 L = normalize(uSunDir);
vec3 R = reflect(-V, N);
float specSharp = pow(max(dot(R, L), 0.0), 170.0) * 2.4;
float specSoft = pow(max(dot(R, L), 0.0), 24.0) * 0.32;
float sunVis = smoothstep(-0.06, 0.08, L.y);
col += uSunColor * (specSharp + specSoft) * sunVis;
// Exponential distance fog matching scene
float dist = length(cameraPosition - vWorldPos);
float fogFactor = 1.0 - exp(-uFogDensity * uFogDensity * dist * dist);
col = mix(col, uFogColor, clamp(fogFactor, 0.0, 1.0));
gl_FragColor = vec4(col, 1.0);
#include <tonemapping_fragment>
#include <encodings_fragment>
}
`
});
const waterGeo = new THREE.CircleGeometry(245, 72);
waterGeo.rotateX(-Math.PI / 2);
const waterMesh = new THREE.Mesh(waterGeo, waterMat);
waterMesh.position.y = 0.0;
waterMesh.receiveShadow = false;
scene.add(waterMesh);
// =========================================================================
// 7. BUILD TERRAIN, HILLS, TREES, CLOUDS & LAKESIDE TOWN
// =========================================================================
function buildTerrain() {
const size = 1080;
const segs = 120;
const geo = new THREE.PlaneGeometry(size, size, segs, segs);
geo.rotateX(-Math.PI / 2);
const pos = geo.attributes.position;
const colors = new Float32Array(pos.count * 3);
const cSand = srgbColor('#d4b180');
const cGrass = srgbColor('#5f8f4e');
const cForest = srgbColor('#3b6a48');
const cRock = srgbColor('#6f687a');
const tmp = new THREE.Color();
for (let i = 0; i < pos.count; i++) {
const x = pos.getX(i);
const z = pos.getZ(i);
const y = getTerrainHeight(x, z);
pos.setY(i, y);
if (y < 1.3) {
tmp.copy(cSand);
} else if (y < 14) {
tmp.copy(cSand).lerp(cGrass, smoothstep(1.3, 4.2, y));
} else if (y < 46) {
tmp.copy(cGrass).lerp(cForest, smoothstep(14, 34, y));
} else {
tmp.copy(cForest).lerp(cRock, smoothstep(46, 84, y));
}
colors[i * 3] = tmp.r;
colors[i * 3 + 1] = tmp.g;
colors[i * 3 + 2] = tmp.b;
}
geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
geo.computeVertexNormals();
const mat = new THREE.MeshLambertMaterial({ vertexColors: true });
const mesh = new THREE.Mesh(geo, mat);
mesh.receiveShadow = true;
mesh.castShadow = false;
scene.add(mesh);
}
buildTerrain();
// Instanced Pine Trees around hillsides & village
function buildTrees() {
const treePositions = [];
let seed = 42;
function rand() {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
}
for (let i = 0; i < 480; i++) {
const ang = rand() * Math.PI * 2;
const lr = getLakeRadius(ang);
const r = lr + 14 + Math.pow(rand(), 1.2) * 210;
const x = Math.cos(ang) * r;
const z = Math.sin(ang) * r;
const y = getTerrainHeight(x, z);
if (y > 2.2 && y < 68) {
treePositions.push({ x, y, z, s: 0.75 + rand() * 0.7 });
}
}
// A couple trees on the central island
for (let i = 0; i < 6; i++) {
const a = (i / 6) * Math.PI * 2 + 0.5;
const x = 10 + Math.cos(a) * 16;
const z = -8 + Math.sin(a) * 16;
const y = getTerrainHeight(x, z);
if (y > 1.8) treePositions.push({ x, y, z, s: 0.85 });
}
const trunkGeo = new THREE.CylinderGeometry(0.45, 0.65, 3.4, 6);
trunkGeo.translate(0, 1.7, 0);
const trunkMat = new THREE.MeshLambertMaterial({ color: srgbColor('#5c3d2e') });
const coneGeo = new THREE.ConeGeometry(2.6, 5.8, 7);
coneGeo.translate(0, 5.2, 0);
const coneMat = new THREE.MeshLambertMaterial({ color: srgbColor('#315d43') });
const coneTopGeo = new THREE.ConeGeometry(1.9, 4.4, 7);
coneTopGeo.translate(0, 7.8, 0);
const trunks = new THREE.InstancedMesh(trunkGeo, trunkMat, treePositions.length);
const cones = new THREE.InstancedMesh(coneGeo, coneMat, treePositions.length);
const tops = new THREE.InstancedMesh(coneTopGeo, coneMat, treePositions.length);
cones.castShadow = true;
tops.castShadow = true;
const dummy = new THREE.Object3D();
treePositions.forEach((p, idx) => {
dummy.position.set(p.x, p.y - 0.3, p.z);
dummy.scale.setScalar(p.s);
dummy.rotation.y = idx * 1.1;
dummy.updateMatrix();
trunks.setMatrixAt(idx, dummy.matrix);
cones.setMatrixAt(idx, dummy.matrix);
tops.setMatrixAt(idx, dummy.matrix);
});
scene.add(trunks, cones, tops);
}
buildTrees();
// Fluffy Sunset Clouds
const clouds = [];
const cloudMat = new THREE.MeshLambertMaterial({
color: srgbColor('#ffe2c9'),
emissive: srgbColor('#6b3b3b'),
emissiveIntensity: 0.25
});
function buildClouds() {
const puffGeo = new THREE.IcosahedronGeometry(1, 1);
for (let i = 0; i < 28; i++) {
const g = new THREE.Group();
const puffs = 4 + (i % 3);
for (let j = 0; j < puffs; j++) {
const m = new THREE.Mesh(puffGeo, cloudMat);
const rx = (j - (puffs - 1) * 0.5) * 8.5;
const ry = (j === 1 || j === 2) ? 2.6 : 0.4;
const rz = ((j * 7) % 3 - 1) * 3.5;
const sc = (j === 1 || j === 2) ? 9.5 : 7.0;
m.position.set(rx, ry, rz);
m.scale.set(sc * 1.35, sc * 0.72, sc * 1.05);
g.add(m);
}
const x = ((i * 97) % 840) - 420;
const z = ((i * 151) % 840) - 420;
const y = 78 + ((i * 29) % 48);
g.position.set(x, y, z);
g.rotation.y = (i * 0.7) % Math.PI;
scene.add(g);
clouds.push({ mesh: g, speed: 1.4 + (i % 5) * 0.45 });
}
}
buildClouds();
// Shared Emissive Materials for Town Windows & Lanterns (brighten as night falls!)
const windowEmissiveMat = new THREE.MeshBasicMaterial({ color: srgbColor('#ffcf75') });
const lanternGlowMat = new THREE.MeshBasicMaterial({ color: srgbColor('#ffe39b') });
const townPointLights = [];
const chimneyOrigins = [];
const sailBoats = [];
const matTex = createLandingMatTexture();
const crateTex = createCrateTexture();
// Helper to create a charming cottage
function createCottage(x, z, rotY, wallHex, roofHex, scale = 1.0) {
const g = new THREE.Group();
const y = getTerrainHeight(x, z);
g.position.set(x, y, z);
g.rotation.y = rotY;
g.scale.setScalar(scale);
// Stone foundation skirt so sloped ground never leaves gap
const skirt = new THREE.Mesh(
new THREE.BoxGeometry(8.4, 5.0, 7.2),
new THREE.MeshLambertMaterial({ color: srgbColor('#6c626d') })
);
skirt.position.y = -1.6;
skirt.receiveShadow = true;
g.add(skirt);
// Walls
const walls = new THREE.Mesh(
new THREE.BoxGeometry(8.0, 5.4, 6.8),
new THREE.MeshLambertMaterial({ color: srgbColor(wallHex) })
);
walls.position.y = 2.7;
walls.castShadow = true;
walls.receiveShadow = true;
g.add(walls);
// Pitched Roof (rotated 4-sided cone/prism look using 2 pitched plates or CylinderGeometry(0,r,h,4))
const roof = new THREE.Mesh(
new THREE.ConeGeometry(6.4, 4.2, 4),
new THREE.MeshLambertMaterial({ color: srgbColor(roofHex) })
);
roof.rotation.y = Math.PI / 4;
roof.scale.set(1.12, 1.0, 0.96);
roof.position.y = 7.4;
roof.castShadow = true;
roof.receiveShadow = true;
g.add(roof);
// Chimney
const chim = new THREE.Mesh(
new THREE.BoxGeometry(1.1, 2.8, 1.1),
new THREE.MeshLambertMaterial({ color: srgbColor('#8c5347') })
);
chim.position.set(2.2, 8.2, 1.1);
g.add(chim);
// Glowing warm windows
const winGeo = new THREE.BoxGeometry(1.3, 1.4, 0.25);
[[-2.1, 3.0, 3.42], [2.1, 3.0, 3.42], [-2.1, 3.0, -3.42], [2.1, 3.0, -3.42]].forEach(([wx, wy, wz]) => {
const w = new THREE.Mesh(winGeo, windowEmissiveMat);
w.position.set(wx, wy, wz);
g.add(w);
});
const sideWinGeo = new THREE.BoxGeometry(0.25, 1.4, 1.3);
[[-4.02, 3.0, 0], [4.02, 3.0, 0]].forEach(([wx, wy, wz]) => {
const w = new THREE.Mesh(sideWinGeo, windowEmissiveMat);
w.position.set(wx, wy, wz);
g.add(w);
});
scene.add(g);
// World position of chimney top for smoke
const chimWorld = new THREE.Vector3(2.2, 9.8, 1.1).multiplyScalar(scale).applyAxisAngle(new THREE.Vector3(0, 1, 0), rotY).add(g.position);
chimneyOrigins.push(chimWorld);
return { group: g, roofTopLocalY: 9.5, scale };
}
// Build non-target decorative cottages + lighthouse + boats
function buildLakeTownDecor() {
const wallPalette = ['#f2dec4', '#f4c8b8', '#e6d8be', '#dfd5e8', '#f5e6cc'];
const roofPalette = ['#b85042', '#7d4e57', '#4a6b7c', '#c96f4b'];
// Scenic village clusters around the shore
const decorAngles = [0.22, 0.55, 1.05, 1.42, 1.88, 2.32, 2.74, 3.25, 3.68, 4.18, 4.65, 5.12, 5.55, 5.95, 0.38, 1.62, 2.95, 4.42, 5.38];
decorAngles.forEach((ang, idx) => {
const offset = 20 + (idx % 3) * 14;
const r = getLakeRadius(ang) + offset;
const x = Math.cos(ang) * r;
const z = Math.sin(ang) * r;
createCottage(
x, z,
-ang + Math.PI * 0.5,
wallPalette[idx % wallPalette.length],
roofPalette[idx % roofPalette.length],
0.9 + (idx % 3) * 0.14
);
});
// Central Island Lighthouse
const lx = 10, lz = -8;
const ly = getTerrainHeight(lx, lz);
const lh = new THREE.Group();
lh.position.set(lx, ly - 0.5, lz);
const tower = new THREE.Mesh(
new THREE.CylinderGeometry(2.3, 3.5, 14, 10),
new THREE.MeshLambertMaterial({ color: srgbColor('#f7efe2') })
);
tower.position.y = 7;
tower.castShadow = true;
lh.add(tower);
const stripe = new THREE.Mesh(
new THREE.CylinderGeometry(2.68, 3.05, 4.2, 10),
new THREE.MeshLambertMaterial({ color: srgbColor('#c84b40') })
);
stripe.position.y = 7.2;
lh.add(stripe);
const lanternRoom = new THREE.Mesh(
new THREE.CylinderGeometry(2.1, 2.1, 2.4, 10),
lanternGlowMat
);
lanternRoom.position.y = 14.9;
lh.add(lanternRoom);
const cap = new THREE.Mesh(
new THREE.ConeGeometry(2.8, 2.4, 10),
new THREE.MeshLambertMaterial({ color: srgbColor('#3b4859') })
);
cap.position.y = 17.2;
lh.add(cap);
const lhLight = new THREE.PointLight(srgbColor('#ffcf70'), 0.8, 70, 1.5);
lhLight.position.set(0, 15, 0);
lh.add(lhLight);
townPointLights.push(lhLight);
scene.add(lh);
// Gentle sailboats on the lake
for (let i = 0; i < 6; i++) {
const bg = new THREE.Group();
const hull = new THREE.Mesh(
new THREE.BoxGeometry(2.6, 1.0, 5.8),
new THREE.MeshLambertMaterial({ color: srgbColor(i % 2 === 0 ? '#a85143' : '#4a6e82') })
);
hull.position.y = 0.25;
bg.add(hull);
const mast = new THREE.Mesh(
new THREE.CylinderGeometry(0.1, 0.12, 6.2, 6),
new THREE.MeshLambertMaterial({ color: srgbColor('#7a5338') })
);
mast.position.y = 3.5;
bg.add(mast);
const sail = new THREE.Mesh(
new THREE.ConeGeometry(2.2, 4.8, 3),
new THREE.MeshLambertMaterial({ color: srgbColor('#fff5e4') })
);
sail.position.set(0, 3.8, 0.2);
sail.scale.set(0.18, 1.0, 1.0);
bg.add(sail);
const ang = (i / 6) * Math.PI * 2 + 0.4;
const rad = 58 + (i % 3) * 22;
bg.position.set(Math.cos(ang) * rad, 0.0, Math.sin(ang) * rad);
bg.rotation.y = ang + Math.PI * 0.5;
scene.add(bg);
sailBoats.push({ group: bg, ang, rad, speed: 0.032 + (i % 2) * 0.015, phase: i * 1.3 });
}
}
buildLakeTownDecor();
// =========================================================================
// 8. WAITING CAT BUILDER & 8 DELIVERY STATIONS (4 ROOFTOPS + 4 DOCKS)
// =========================================================================
function createWaitingCat(furHex, accentHex) {
const g = new THREE.Group();
const furMat = new THREE.MeshLambertMaterial({ color: srgbColor(furHex) });
const accMat = new THREE.MeshLambertMaterial({ color: srgbColor(accentHex) });
const eyeMat = new THREE.MeshBasicMaterial({ color: srgbColor('#1e141c') });
// Body
const body = new THREE.Mesh(new THREE.CylinderGeometry(0.62, 0.78, 1.45, 8), furMat);
body.position.y = 0.72;
body.castShadow = true;
g.add(body);
// Chest patch
const chest = new THREE.Mesh(new THREE.SphereGeometry(0.45, 8, 6), accMat);
chest.position.set(0, 0.82, 0.42);
g.add(chest);
// Head
const head = new THREE.Mesh(new THREE.SphereGeometry(0.65, 10, 8), furMat);
head.position.set(0, 1.82, 0.08);
head.castShadow = true;
g.add(head);
// Ears
const earGeo = new THREE.ConeGeometry(0.24, 0.52, 4);
const earL = new THREE.Mesh(earGeo, furMat);
earL.position.set(-0.38, 2.42, 0.05);
earL.rotation.z = 0.28;
const earR = new THREE.Mesh(earGeo, furMat);
earR.position.set(0.38, 2.42, 0.05);
earR.rotation.z = -0.28;
g.add(earL, earR);
// Eyes & pink nose
const eyeGeo = new THREE.SphereGeometry(0.08, 6, 6);
const eL = new THREE.Mesh(eyeGeo, eyeMat);
eL.position.set(-0.22, 1.88, 0.63);
const eR = new THREE.Mesh(eyeGeo, eyeMat);
eR.position.set(0.22, 1.88, 0.63);
g.add(eL, eR);
// Waving arm
const arm = new THREE.Mesh(new THREE.CylinderGeometry(0.15, 0.14, 0.85, 6), furMat);
arm.position.set(0.68, 1.5, 0.2);
arm.rotation.z = -0.7;
g.add(arm);
// Tail
const tail = new THREE.Mesh(new THREE.CylinderGeometry(0.11, 0.13, 1.1, 6), furMat);
tail.position.set(0, 0.55, -0.68);
tail.rotation.x = -0.7;
g.add(tail);
g.scale.setScalar(1.35);
return { group: g, arm, head };
}
const deliveryStations = [];
const stationCatColors = [
['#36333d', '#f7efe5'], // tuxedo
['#d9cfc1', '#9c6844'], // cream siamese
['#8d949e', '#ebe7e1'], // grey tabby
['#f5efe6', '#de7a3b'], // calico
['#2b2730', '#ffd166'], // black cat
['#c98e5b', '#fff1db'], // caramel
['#e8dfd5', '#6b6570'], // white-grey
['#e39a54', '#fff2dc'] // ginger cousin
];
function buildDeliveryStations() {
// 8 balanced stations around the lake loop (alternating Rooftop & Dock!)
// Station angles arranged in a natural scenic flight circle
const specs = [
{ type: 'rooftop', ang: 0.78, ringH: 27, label: 'Bakery Rooftop' },
{ type: 'dock', ang: 1.56, ringH: 25, label: 'Harbor Dock' },
{ type: 'rooftop', ang: 2.36, ringH: 29, label: 'Bell Inn Roof' },
{ type: 'dock', ang: 3.12, ringH: 24, label: 'West Pier Dock' },
{ type: 'rooftop', ang: 3.92, ringH: 28, label: 'Hillside Cottage' },
{ type: 'dock', ang: 4.72, ringH: 25, label: 'Fisherman Dock' },
{ type: 'rooftop', ang: 5.48, ringH: 29, label: 'Clockhouse Roof' },
{ type: 'dock', ang: 0.02, ringH: 24, label: 'Sunset Pier' }
];
const ringGeo = new THREE.TorusGeometry(7.2, 0.65, 14, 42);
const innerRingGeo = new THREE.TorusGeometry(5.6, 0.18, 8, 36);
const matGeo = new THREE.CircleGeometry(3.8, 24);
matGeo.rotateX(-Math.PI / 2);
specs.forEach((sp, i) => {
const lr = getLakeRadius(sp.ang);
let padPos = new THREE.Vector3();
let ringHeading = sp.ang + Math.PI * 0.5;
if (sp.type === 'rooftop') {
const r = lr + 15;
const x = Math.cos(sp.ang) * r;
const z = Math.sin(sp.ang) * r;
const groundY = getTerrainHeight(x, z);
// Flat-topped cozy inn/bakery rooftop with pitched trim & wide roof terrace
const hg = new THREE.Group();
hg.position.set(x, groundY, z);
hg.rotation.y = -sp.ang + Math.PI * 0.5;
const skirt = new THREE.Mesh(
new THREE.BoxGeometry(12.2, 6, 10.6),
new THREE.MeshLambertMaterial({ color: srgbColor('#695e6a') })
);
skirt.position.y = -2.2;
hg.add(skirt);
const body = new THREE.Mesh(
new THREE.BoxGeometry(11.6, 7.2, 10.0),
new THREE.MeshLambertMaterial({ color: srgbColor('#f3dcc0') })
);
body.position.y = 3.6;
body.castShadow = true;
body.receiveShadow = true;
hg.add(body);
const roofDeck = new THREE.Mesh(
new THREE.BoxGeometry(12.8, 1.1, 11.2),
new THREE.MeshLambertMaterial({ color: srgbColor('#b64c3e') })
);
roofDeck.position.y = 7.7;
roofDeck.castShadow = true;
roofDeck.receiveShadow = true;
hg.add(roofDeck);
// Windows
const wGeo = new THREE.BoxGeometry(1.8, 1.8, 0.28);
[[-3, 4.2, 5.05], [3, 4.2, 5.05], [-3, 4.2, -5.05], [3, 4.2, -5.05]].forEach(([wx, wy, wz]) => {
const wm = new THREE.Mesh(wGeo, windowEmissiveMat);
wm.position.set(wx, wy, wz);
hg.add(wm);
});
// Cozy corner lantern on roof
const lPost = new THREE.Mesh(
new THREE.CylinderGeometry(0.14, 0.14, 2.4, 6),
new THREE.MeshLambertMaterial({ color: srgbColor('#3b2f35') })
);
lPost.position.set(-4.6, 9.2, 4.2);
hg.add(lPost);
const lBulb = new THREE.Mesh(new THREE.SphereGeometry(0.45, 8, 8), lanternGlowMat);
lBulb.position.set(-4.6, 10.4, 4.2);
hg.add(lBulb);
const pl = new THREE.PointLight(srgbColor('#ffbe66'), 0.4, 34, 1.6);
pl.position.set(-4.6, 10.4, 4.2);
hg.add(pl);
townPointLights.push(pl);
scene.add(hg);
padPos.set(x, groundY + 8.32, z);
} else {
// Wooden Pier / Dock jutting out over the lake
const r = lr - 10;
const x = Math.cos(sp.ang) * r;
const z = Math.sin(sp.ang) * r;
const dg = new THREE.Group();
dg.position.set(x, 0, z);
dg.rotation.y = -sp.ang + Math.PI * 0.5;
const woodMat = new THREE.MeshLambertMaterial({ color: srgbColor('#8a5a3a') });
const deck = new THREE.Mesh(new THREE.BoxGeometry(9.6, 0.8, 22.0), woodMat);
deck.position.set(0, 1.7, 3.0);
deck.castShadow = true;
deck.receiveShadow = true;
dg.add(deck);
// Wooden pilings down into lakebed
const postGeo = new THREE.CylinderGeometry(0.38, 0.42, 9.5, 7);
[[-4.0, -5], [4.0, -5], [-4.0, 2], [4.0, 2], [-4.0, 10], [4.0, 10]].forEach(([px, pz]) => {
const post = new THREE.Mesh(postGeo, woodMat);
post.position.set(px, -2.2, pz);
dg.add(post);
});
// Dock lantern post
const lPost = new THREE.Mesh(
new THREE.CylinderGeometry(0.14, 0.14, 3.2, 6),
new THREE.MeshLambertMaterial({ color: srgbColor('#3b2f35') })
);
lPost.position.set(3.8, 3.6, 11.8);
dg.add(lPost);
const lBulb = new THREE.Mesh(new THREE.SphereGeometry(0.48, 8, 8), lanternGlowMat);
lBulb.position.set(3.8, 5.2, 11.8);
dg.add(lBulb);
const pl = new THREE.PointLight(srgbColor('#ffbe66'), 0.45, 36, 1.6);
pl.position.set(3.8, 5.2, 11.8);
dg.add(pl);
townPointLights.push(pl);
scene.add(dg);
padPos.set(x, 2.16, z);
}
// Landing Mat
const matMesh = new THREE.Mesh(
matGeo,
new THREE.MeshBasicMaterial({ map: matTex, transparent: true })
);
matMesh.position.copy(padPos).add(new THREE.Vector3(0, 0.06, 0));
scene.add(matMesh);
// Waiting Cat standing on the edge of the landing mat looking up
const [fur, acc] = stationCatColors[i % stationCatColors.length];
const cat = createWaitingCat(fur, acc);
cat.group.position.set(padPos.x + 2.4, padPos.y, padPos.z + 1.4);
cat.group.lookAt(0, padPos.y + 15, 0);
scene.add(cat.group);
// Glowing Sky Ring directly above landing pad
const ringPos = new THREE.Vector3(padPos.x, Math.max(padPos.y + 18, sp.ringH), padPos.z);
const ringGroup = new THREE.Group();
ringGroup.position.copy(ringPos);
ringGroup.rotation.y = ringHeading;
const outerMat = new THREE.MeshBasicMaterial({ color: srgbColor('#ffcb5c') });
const outerTorus = new THREE.Mesh(ringGeo, outerMat);
ringGroup.add(outerTorus);
const innerMat = new THREE.MeshBasicMaterial({
color: srgbColor('#7cf6ff'),
transparent: true,
opacity: 0.78
});
const innerTorus = new THREE.Mesh(innerRingGeo, innerMat);
ringGroup.add(innerTorus);
// Horizontal overhead guide ring so Above view sees a glowing bullseye too
const topGuide = new THREE.Mesh(
new THREE.RingGeometry(6.8, 7.6, 32),
new THREE.MeshBasicMaterial({
color: srgbColor('#ffe08c'),
side: THREE.DoubleSide,
transparent: true,
opacity: 0.45
})
);
topGuide.rotation.x = Math.PI / 2;
ringGroup.add(topGuide);
// Soft vertical light beam connecting ring to landing pad
const beamH = ringPos.y - padPos.y;
const beam = new THREE.Mesh(
new THREE.CylinderGeometry(1.8, 3.6, beamH, 16, 1, true),
new THREE.MeshBasicMaterial({
color: srgbColor('#ffcf70'),
transparent: true,
opacity: 0.13,
side: THREE.DoubleSide,
depthWrite: false,
blending: THREE.AdditiveBlending
})
);
beam.position.y = -beamH * 0.5;
ringGroup.add(beam);
scene.add(ringGroup);
deliveryStations.push({
id: i,
type: sp.type,
label: sp.label,
padPos,
ringPos,
ringGroup,
outerTorus,
innerTorus,
outerMat,
innerMat,
beam,
cat,
dropped: false,
delivered: false,
happyTimer: 0,
landedCrate: null
});
});
}
buildDeliveryStations();
// =========================================================================
// 9. PROPELLER PLANE, ORANGE CAT PILOT & COCKPIT INTERIOR
// =========================================================================
const planeGroup = new THREE.Group();
scene.add(planeGroup);
const fuselageRearGroup = new THREE.Group();
const exteriorPilotGroup = new THREE.Group();
const cockpitInteriorGroup = new THREE.Group();
planeGroup.add(fuselageRearGroup, exteriorPilotGroup, cockpitInteriorGroup);
let propAssembly = null;
let propBlurDisc = null;
let scarfSegments = [];
let underbellyCrate = null;
let cockpitYoke = null;
let cockpitCompassNeedle = null;
function buildPlane() {
const creamMat = new THREE.MeshLambertMaterial({ color: srgbColor('#fff0d6') });
const redMat = new THREE.MeshLambertMaterial({ color: srgbColor('#e04b3e') });
const darkMat = new THREE.MeshLambertMaterial({ color: srgbColor('#302636') });
const woodMat = new THREE.MeshLambertMaterial({ color: srgbColor('#915832') });
// Nose engine cowling (always visible!)
const cowling = new THREE.Mesh(new THREE.CylinderGeometry(0.88, 1.04, 1.45, 14), redMat);
cowling.rotation.x = Math.PI / 2;
cowling.position.set(0, 0.05, -1.95);
cowling.castShadow = true;
planeGroup.add(cowling);
// Front fuselage body
const frontBody = new THREE.Mesh(new THREE.BoxGeometry(1.75, 1.45, 1.9), creamMat);
frontBody.position.set(0, 0.02, -0.5);
frontBody.castShadow = true;
planeGroup.add(frontBody);
// Rear fuselage & tail (hidden in cockpit camera so nothing clips!)
const rearBody = new THREE.Mesh(new THREE.CylinderGeometry(0.95, 0.35, 3.2, 10), creamMat);
rearBody.rotation.x = Math.PI / 2;
rearBody.position.set(0, 0.05, 1.85);
rearBody.castShadow = true;
fuselageRearGroup.add(rearBody);
const hStab = new THREE.Mesh(new THREE.BoxGeometry(3.4, 0.14, 0.95), redMat);
hStab.position.set(0, 0.18, 3.0);
hStab.castShadow = true;
fuselageRearGroup.add(hStab);
const vFin = new THREE.Mesh(new THREE.BoxGeometry(0.18, 1.35, 1.05), redMat);
vFin.position.set(0, 0.8, 3.05);
vFin.castShadow = true;
fuselageRearGroup.add(vFin);
// Main Wings (always visible, including out the cockpit sides!)
const wing = new THREE.Mesh(new THREE.BoxGeometry(9.2, 0.22, 1.65), creamMat);
wing.position.set(0, 0.18, -0.45);
wing.castShadow = true;
planeGroup.add(wing);
const wingStripeL = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.24, 1.68), redMat);
wingStripeL.position.set(-3.2, 0.18, -0.45);
const wingStripeR = wingStripeL.clone();
wingStripeR.position.x = 3.2;
planeGroup.add(wingStripeL, wingStripeR);
// Wingtip glowing navigation lights
const navRed = new THREE.Mesh(new THREE.SphereGeometry(0.18, 8, 8), new THREE.MeshBasicMaterial({ color: srgbColor('#ff4d4d') }));
navRed.position.set(-4.6, 0.2, -0.45);
const navGreen = new THREE.Mesh(new THREE.SphereGeometry(0.18, 8, 8), new THREE.MeshBasicMaterial({ color: srgbColor('#4dff88') }));
navGreen.position.set(4.6, 0.2, -0.45);
planeGroup.add(navRed, navGreen);
// Landing gear struts & wheels
[-0.9, 0.9].forEach(sx => {
const strut = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.08, 1.05, 6), darkMat);
strut.position.set(sx * 0.85, -0.82, -0.85);
strut.rotation.z = sx > 0 ? -0.22 : 0.22;
planeGroup.add(strut);
const wheel = new THREE.Mesh(new THREE.CylinderGeometry(0.36, 0.36, 0.24, 12), darkMat);
wheel.rotation.z = Math.PI / 2;
wheel.position.set(sx, -1.28, -0.85);
planeGroup.add(wheel);
});
// Underbelly visible fish crate waiting to drop
underbellyCrate = new THREE.Mesh(
new THREE.BoxGeometry(1.15, 0.9, 1.15),
new THREE.MeshLambertMaterial({ map: crateTex })
);
underbellyCrate.position.set(0, -1.05, -0.1);
underbellyCrate.castShadow = true;
planeGroup.add(underbellyCrate);
// Spinning Propeller Assembly at Nose
propAssembly = new THREE.Group();
propAssembly.position.set(0, 0.05, -2.75);
const spinner = new THREE.Mesh(new THREE.ConeGeometry(0.32, 0.65, 10), redMat);
spinner.rotation.x = -Math.PI / 2;
spinner.position.z = -0.25;
propAssembly.add(spinner);
const bladeGeo = new THREE.BoxGeometry(2.55, 0.22, 0.06);
const blade = new THREE.Mesh(bladeGeo, woodMat);
propAssembly.add(blade);
const blade2 = new THREE.Mesh(new THREE.BoxGeometry(0.22, 2.55, 0.06), woodMat);
propAssembly.add(blade2);
propBlurDisc = new THREE.Mesh(
new THREE.CircleGeometry(1.32, 24),
new THREE.MeshBasicMaterial({
color: srgbColor('#ffe8c4'),
transparent: true,
opacity: 0.16,
side: THREE.DoubleSide,
depthWrite: false
})
);
propAssembly.add(propBlurDisc);
planeGroup.add(propAssembly);
// Exterior Orange Cat Pilot (visible in Behind & Above views)
const orangeFur = new THREE.MeshLambertMaterial({ color: srgbColor('#f2852a') });
const creamFur = new THREE.MeshLambertMaterial({ color: srgbColor('#ffe6c4') });
const goggleGlass = new THREE.MeshBasicMaterial({ color: srgbColor('#7ce8ff') });
const scarfMat = new THREE.MeshLambertMaterial({ color: srgbColor('#e6453c') });
const catTorso = new THREE.Mesh(new THREE.CylinderGeometry(0.45, 0.55, 0.85, 8), orangeFur);
catTorso.position.set(0, 0.72, 0.1);
exteriorPilotGroup.add(catTorso);
const catHead = new THREE.Mesh(new THREE.SphereGeometry(0.56, 12, 10), orangeFur);
catHead.position.set(0, 1.38, 0.08);
catHead.castShadow = true;
exteriorPilotGroup.add(catHead);
// Muzzle & ears
const muzzle = new THREE.Mesh(new THREE.SphereGeometry(0.28, 8, 6), creamFur);
muzzle.position.set(0, 1.24, -0.38);
exteriorPilotGroup.add(muzzle);
const catEarGeo = new THREE.ConeGeometry(0.2, 0.45, 4);
const cEarL = new THREE.Mesh(catEarGeo, orangeFur);
cEarL.position.set(-0.34, 1.9, 0.08);
cEarL.rotation.z = 0.25;
const cEarR = new THREE.Mesh(catEarGeo, orangeFur);
cEarR.position.set(0.34, 1.9, 0.08);
cEarR.rotation.z = -0.25;
exteriorPilotGroup.add(cEarL, cEarR);
// Aviator Goggles on forehead
const gBand = new THREE.Mesh(new THREE.CylinderGeometry(0.57, 0.57, 0.18, 12), darkMat);
gBand.position.set(0, 1.54, 0.08);
exteriorPilotGroup.add(gBand);
[-0.2, 0.2].forEach(gx => {
const lens = new THREE.Mesh(new THREE.CylinderGeometry(0.16, 0.16, 0.14, 10), goggleGlass);
lens.rotation.x = Math.PI / 2;
lens.position.set(gx, 1.54, -0.45);
exteriorPilotGroup.add(lens);
});
// Animated trailing scarf
const scarfNeck = new THREE.Mesh(new THREE.TorusGeometry(0.44, 0.13, 6, 12), scarfMat);
scarfNeck.rotation.x = Math.PI / 2;
scarfNeck.position.set(0, 1.0, 0.1);
exteriorPilotGroup.add(scarfNeck);
for (let s = 0; s < 4; s++) {
const seg = new THREE.Mesh(new THREE.BoxGeometry(0.28, 0.08, 0.42), scarfMat);
seg.position.set(0.12, 1.02, 0.52 + s * 0.36);
exteriorPilotGroup.add(seg);
scarfSegments.push(seg);
}
// Dedicated Cockpit Interior (visible ONLY in Cockpit mode!)
cockpitInteriorGroup.visible = false;
const dash = new THREE.Mesh(new THREE.BoxGeometry(1.65, 0.52, 0.45), woodMat);
dash.position.set(0, 0.85, -1.15);
cockpitInteriorGroup.add(dash);
const coaming = new THREE.Mesh(new THREE.TorusGeometry(0.84, 0.09, 8, 20, Math.PI), darkMat);
coaming.position.set(0, 1.05, -1.02);
cockpitInteriorGroup.add(coaming);
// Thin windscreen frame struts (leaving center completely clear)
[-0.78, 0.78].forEach(sx => {
const post = new THREE.Mesh(new THREE.CylinderGeometry(0.035, 0.04, 0.72, 6), darkMat);
post.position.set(sx, 1.38, -0.92);
post.rotation.z = sx > 0 ? 0.22 : -0.22;
post.rotation.x = 0.28;
cockpitInteriorGroup.add(post);
});
// Gauge dials + directional compass gauge pointing toward next ring!
const gaugeTex = createGaugeTexture();
const dialMat = new THREE.MeshBasicMaterial({ map: gaugeTex });
const altDial = new THREE.Mesh(new THREE.CircleGeometry(0.16, 16), dialMat);
altDial.position.set(-0.34, 0.96, -0.91);
cockpitInteriorGroup.add(altDial);
const compDial = new THREE.Mesh(new THREE.CircleGeometry(0.19, 16), dialMat);
compDial.position.set(0.32, 0.96, -0.91);
cockpitInteriorGroup.add(compDial);
cockpitCompassNeedle = new THREE.Group();
cockpitCompassNeedle.position.set(0.32, 0.96, -0.90);
const needleMesh = new THREE.Mesh(
new THREE.ConeGeometry(0.04, 0.15, 4),
new THREE.MeshBasicMaterial({ color: srgbColor('#ffd166') })
);
needleMesh.position.y = 0.05;
cockpitCompassNeedle.add(needleMesh);
cockpitInteriorGroup.add(cockpitCompassNeedle);
// Moving Yoke + Orange Cat Paws gripping it!
cockpitYoke = new THREE.Group();
cockpitYoke.position.set(0, 0.72, -0.82);
const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.04, 0.04, 0.35, 8), darkMat);
stem.rotation.x = Math.PI / 2;
stem.position.z = -0.12;
cockpitYoke.add(stem);
const wheel = new THREE.Mesh(new THREE.TorusGeometry(0.24, 0.038, 8, 18), darkMat);
cockpitYoke.add(wheel);
[-0.23, 0.23].forEach(px => {
const paw = new THREE.Mesh(new THREE.SphereGeometry(0.085, 8, 8), orangeFur);
paw.position.set(px, 0.03, 0.02);
cockpitYoke.add(paw);
const toe = new THREE.Mesh(new THREE.SphereGeometry(0.055, 6, 6), creamFur);
toe.position.set(px * 0.92, 0.05, -0.04);
cockpitYoke.add(toe);
});
cockpitInteriorGroup.add(cockpitYoke);
}
buildPlane();
// =========================================================================
// 10. PARACHUTING CRATES & POOLED PARTICLES
// =========================================================================
const activeParachutes = [];
const crateGeo = new THREE.BoxGeometry(1.5, 1.25, 1.5);
const crateMat = new THREE.MeshLambertMaterial({ map: crateTex });
const chuteDomeGeo = new THREE.SphereGeometry(2.6, 14, 10, 0, Math.PI * 2, 0, Math.PI * 0.52);
const chuteRedMat = new THREE.MeshLambertMaterial({ color: srgbColor('#ff6b4a'), side: THREE.DoubleSide });
const chuteCreamMat = new THREE.MeshLambertMaterial({ color: srgbColor('#fff3dc'), side: THREE.DoubleSide });
const ropeMat = new THREE.MeshBasicMaterial({ color: srgbColor('#f2dfc4') });
function spawnParachuteCrate(startPos, station) {
const g = new THREE.Group();
g.position.copy(startPos);
const box = new THREE.Mesh(crateGeo, crateMat);
box.castShadow = true;
g.add(box);
const canopyGroup = new THREE.Group();
canopyGroup.position.y = 3.8;
canopyGroup.scale.setScalar(0.05);
const dome = new THREE.Mesh(chuteDomeGeo, chuteRedMat);
canopyGroup.add(dome);
const band = new THREE.Mesh(
new THREE.SphereGeometry(2.63, 14, 6, 0, Math.PI * 2, 0.28, 0.35),
chuteCreamMat
);
canopyGroup.add(band);
// 4 thin shroud cords
const cordGeo = new THREE.CylinderGeometry(0.03, 0.03, 3.9, 4);
[[-1.3, 1.3], [1.3, 1.3], [-1.3, -1.3], [1.3, -1.3]].forEach(([cx, cz]) => {
const cord = new THREE.Mesh(cordGeo, ropeMat);
cord.position.set(cx * 0.45, -1.8, cz * 0.45);
cord.lookAt(0, -3.7, 0);
cord.rotateX(Math.PI / 2);
canopyGroup.add(cord);
});
g.add(canopyGroup);
scene.add(g);
activeParachutes.push({
group: g,
box,
canopyGroup,
station,
age: 0,
targetPos: station.padPos.clone().add(new THREE.Vector3(0, 0.65, 0)),
velY: -8.5
});
}
// Lightweight Particle Pool
const particlePool = [];
const pGeo = new THREE.DodecahedronGeometry(0.45, 0);
for (let i = 0; i < 160; i++) {
const mat = new THREE.MeshBasicMaterial({
color: srgbColor('#ffd980'),
transparent: true,
opacity: 0
});
const mesh = new THREE.Mesh(pGeo, mat);
mesh.visible = false;
scene.add(mesh);
particlePool.push({
mesh,
mat,
vel: new THREE.Vector3(),
age: 0,
life: 1,
startScale: 1,
endScale: 0.1,
active: false
});
}
let pCursor = 0;
function emitParticle(pos, vel, hex, life, startScale, endScale) {
const p = particlePool[pCursor];
pCursor = (pCursor + 1) % particlePool.length;
p.active = true;
p.age = 0;
p.life = life;
p.startScale = startScale;
p.endScale = endScale;
p.vel.copy(vel);
p.mat.color.set(hex).convertSRGBToLinear();
p.mat.opacity = 0.9;
p.mesh.position.copy(pos);
p.mesh.scale.setScalar(startScale);
p.mesh.visible = true;
}
// =========================================================================
// 11. SUNSET-TO-NIGHTFALL ATMOSPHERE INTERPOLATOR
// =========================================================================
const keyframes = [
{
t: 0.0,
zenith: srgbColor('#3b6099'),
horizon: srgbColor('#ff8e53'),
sunGlow: srgbColor('#ffd98c'),
fog: srgbColor('#ef8e5f'),
sunCol: srgbColor('#ffd078'),
sunInt: 2.05,
hemiSky: srgbColor('#ffd2a6'),
hemiGnd: srgbColor('#435947'),
hemiInt: 0.88,
water: srgbColor('#1e4f63'),
cloud: srgbColor('#ffe2c6'),
cloudEm: srgbColor('#7a433d'),
sunElev: 0.30
},
{
t: 0.42,
zenith: srgbColor('#2d376d'),
horizon: srgbColor('#ff5d5e'),
sunGlow: srgbColor('#ffb26b'),
fog: srgbColor('#ca5a61'),
sunCol: srgbColor('#ff8e5a'),
sunInt: 1.55,
hemiSky: srgbColor('#f29e8e'),
hemiGnd: srgbColor('#313847'),
hemiInt: 0.72,
water: srgbColor('#17364f'),
cloud: srgbColor('#f5a69d'),
cloudEm: srgbColor('#59293f'),
sunElev: 0.12
},
{
t: 0.75,
zenith: srgbColor('#171c40'),
horizon: srgbColor('#a83c5c'),
sunGlow: srgbColor('#e06855'),
fog: srgbColor('#582b47'),
sunCol: srgbColor('#d46055'),
sunInt: 0.82,
hemiSky: srgbColor('#886694'),
hemiGnd: srgbColor('#1c2033'),
hemiInt: 0.52,
water: srgbColor('#102038'),
cloud: srgbColor('#8e5c78'),
cloudEm: srgbColor('#2a1833'),
sunElev: -0.02
},
{
t: 1.0,
zenith: srgbColor('#090d22'),
horizon: srgbColor('#24254d'),
sunGlow: srgbColor('#624d85'),
fog: srgbColor('#181933'),
sunCol: srgbColor('#6d7cb0'),
sunInt: 0.45,
hemiSky: srgbColor('#455080'),
hemiGnd: srgbColor('#101324'),
hemiInt: 0.44,
water: srgbColor('#091124'),
cloud: srgbColor('#383d5e'),
cloudEm: srgbColor('#101226'),
sunElev: -0.14
}
];
function updateAtmosphere(progress) {
const p = clamp(progress, 0, 1);
let k0 = keyframes[0];
let k1 = keyframes[keyframes.length - 1];
for (let i = 0; i < keyframes.length - 1; i++) {
if (p >= keyframes[i].t && p <= keyframes[i + 1].t) {
k0 = keyframes[i];
k1 = keyframes[i + 1];
break;
}
}
const u = k1.t === k0.t ? 0 : (p - k0.t) / (k1.t - k0.t);
skyUniforms.uZenithColor.value.copy(k0.zenith).lerp(k1.zenith, u);
skyUniforms.uHorizonColor.value.copy(k0.horizon).lerp(k1.horizon, u);
skyUniforms.uSunGlowColor.value.copy(k0.sunGlow).lerp(k1.sunGlow, u);
skyUniforms.uNightFactor.value = p;
const elev = lerp(k0.sunElev, k1.sunElev, u);
const sunAz = -2.25 + p * 0.25;
skyUniforms.uSunDir.value.set(
Math.cos(sunAz) * Math.cos(elev),
Math.sin(elev),
Math.sin(sunAz) * Math.cos(elev)
).normalize();
sunLight.position.copy(skyUniforms.uSunDir.value).multiplyScalar(280);
sunLight.position.y = Math.max(sunLight.position.y, 24); // keep shadows gentle even at dusk
sunLight.color.copy(k0.sunCol).lerp(k1.sunCol, u);
sunLight.intensity = lerp(k0.sunInt, k1.sunInt, u);
hemiLight.color.copy(k0.hemiSky).lerp(k1.hemiSky, u);
hemiLight.groundColor.copy(k0.hemiGnd).lerp(k1.hemiGnd, u);
hemiLight.intensity = lerp(k0.hemiInt, k1.hemiInt, u);
fog.color.copy(k0.fog).lerp(k1.fog, u);
waterUniforms.uSunColor.value.copy(skyUniforms.uSunGlowColor.value);
waterUniforms.uWaterBaseColor.value.copy(k0.water).lerp(k1.water, u);
cloudMat.color.copy(k0.cloud).lerp(k1.cloud, u);
cloudMat.emissive.copy(k0.cloudEm).lerp(k1.cloudEm, u);
// Town windows & lanterns glow warmer as twilight deepens
const lanternScale = smoothstep(0.15, 0.85, p);
const winBright = lerp(0.55, 1.45, lanternScale);
windowEmissiveMat.color.set('#ffcf75').convertSRGBToLinear().multiplyScalar(winBright);
lanternGlowMat.color.set('#ffe39b').convertSRGBToLinear().multiplyScalar(lerp(0.85, 1.55, lanternScale));
for (let i = 0; i < townPointLights.length; i++) {
townPointLights[i].intensity = lerp(0.2, 1.65, lanternScale);
}
}
// =========================================================================
// 12. GAME STATE, FLIGHT PHYSICS & CAMERA MODES
// =========================================================================
const isDemoInit = window.location.hash === '#demo' || window.location.href.endsWith('#demo');
const state = {
mode: isDemoInit ? 'demo' : 'title', // 'title' | 'playing' | 'demo' | 'won' | 'lost'
cameraMode: 'behind', // 'behind' | 'cockpit' | 'above'
score: 0,
cratesDropped: 0,
cratesDelivered: 0,
timeLeft: TOTAL_FLIGHT_SECONDS,
sunsetProgress: 0.08,
demoTime: 0,
planePos: new THREE.Vector3(105, 30, 125),
prevPlanePos: new THREE.Vector3(105, 30, 125),
yaw: 0.75,
pitch: 0,
roll: 0,
speed: 35,
steerX: 0,
steerY: 0,
camPos: new THREE.Vector3(115, 36, 138),
camLook: new THREE.Vector3(100, 29, 120),
camUp: new THREE.Vector3(0, 1, 0),
camSnap: true
};
// UI Elements
const scoreVal = document.getElementById('scoreVal');
const cratesVal = document.getElementById('cratesVal');
const scorePill = document.getElementById('scorePill');
const cratesPill = document.getElementById('cratesPill');
const daylightPill = document.getElementById('daylightPill');
const daylightFill = document.getElementById('daylightFill');
const timePhaseLabel = document.getElementById('timePhaseLabel');
const timeLeftVal = document.getElementById('timeLeftVal');
const startOverlay = document.getElementById('startOverlay');
const endOverlay = document.getElementById('endOverlay');
const endTitle = document.getElementById('endTitle');
const endSubtitle = document.getElementById('endSubtitle');
const endScore = document.getElementById('endScore');
const endDelivered = document.getElementById('endDelivered');
const endBest = document.getElementById('endBest');
const toastEl = document.getElementById('toast');
const demoBanner = document.getElementById('demoBanner');
const ringPointerEl = document.getElementById('ringPointer');
const ringArrowShape = document.getElementById('ringArrowShape');
const ringDistLabel = document.getElementById('ringDistLabel');
const mouseReticle = document.getElementById('mouseReticle');
const touchIndicator = document.getElementById('touchIndicator');
const touchBase = document.getElementById('touchBase');
const touchKnob = document.getElementById('touchKnob');
const soundBtn = document.getElementById('soundBtn');
const soundOnIcon = document.getElementById('soundOnIcon');
const soundOffIcon = document.getElementById('soundOffIcon');
const camButtons = Array.from(document.querySelectorAll('.cam-btn'));
let toastTimer = null;
function showToast(msg) {
toastEl.textContent = msg;
toastEl.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toastEl.classList.remove('show'), 2200);
}
function bumpPill(el) {
el.classList.remove('bump');
void el.offsetWidth;
el.classList.add('bump');
}
function updateHUD() {
scoreVal.textContent = String(state.score);
const left = TOTAL_CRATES - state.cratesDropped;
cratesVal.textContent = String(left);
const tSec = Math.max(0, Math.ceil(state.timeLeft));
const mins = Math.floor(tSec / 60);
const secs = tSec % 60;
timeLeftVal.textContent = `${mins}:${secs < 10 ? '0' : ''}${secs}`;
const ratio = clamp(state.timeLeft / TOTAL_FLIGHT_SECONDS, 0, 1);
daylightFill.style.width = `${(ratio * 100).toFixed(1)}%`;
if (state.sunsetProgress < 0.38) timePhaseLabel.textContent = 'Sunset';
else if (state.sunsetProgress < 0.72) timePhaseLabel.textContent = 'Dusk';
else timePhaseLabel.textContent = 'Twilight';
if (state.timeLeft <= 15 && state.mode === 'playing' && left > 0) {
daylightPill.classList.add('urgent');
} else {
daylightPill.classList.remove('urgent');
}
}
function setCameraMode(mode) {
state.cameraMode = mode;
camButtons.forEach(btn => {
btn.classList.toggle('active', btn.dataset.cam === mode);
});
const isCockpit = mode === 'cockpit';
exteriorPilotGroup.visible = !isCockpit;
fuselageRearGroup.visible = !isCockpit;
cockpitInteriorGroup.visible = isCockpit;
if (isCockpit) state.camSnap = true;
}
function resetWorldAndFlight(keepPose) {
// Clear active parachutes & landed crates
while (activeParachutes.length > 0) {
const p = activeParachutes.pop();
scene.remove(p.group);
}
deliveryStations.forEach(st => {
if (st.landedCrate) {
scene.remove(st.landedCrate);
st.landedCrate = null;
}
st.dropped = false;
st.delivered = false;
st.happyTimer = 0;
st.ringGroup.visible = true;
st.ringGroup.scale.setScalar(1);
st.outerMat.color.set('#ffcb5c').convertSRGBToLinear();
st.innerMat.color.set('#7cf6ff').convertSRGBToLinear();
});
state.score = 0;
state.cratesDropped = 0;
state.cratesDelivered = 0;
state.timeLeft = TOTAL_FLIGHT_SECONDS;
state.sunsetProgress = 0.04;
underbellyCrate.visible = true;
if (!keepPose) {
// Aim smoothly toward Station 0
const target = deliveryStations[0].ringPos;
state.planePos.set(95, 29, 130);
state.prevPlanePos.copy(state.planePos);
state.yaw = Math.atan2(-(target.x - state.planePos.x), -(target.z - state.planePos.z));
state.pitch = 0;
state.roll = 0;
state.steerX = 0;
state.steerY = 0;
state.camSnap = true;
}
updateHUD();
}
function startPlay() {
sound.init();
resetWorldAndFlight(false);
state.mode = 'playing';
startOverlay.classList.add('hidden');
endOverlay.classList.add('hidden');
demoBanner.style.display = 'none';
showToast('Fly through the glowing rings!');
}
function endGame(won) {
if (state.mode !== 'playing') return;
state.mode = won ? 'won' : 'lost';
sound.playFanfare(won);
if (won) {
const timeBonus = Math.round(state.timeLeft * 10);
state.score += timeBonus;
endTitle.textContent = 'All Crates Delivered!';
endSubtitle.textContent = `Every cat in Lake Town got dinner with ${Math.ceil(state.timeLeft)}s of light left (+${timeBonus} daylight bonus)!`;
} else {
endTitle.textContent = 'Night Has Fallen';
endSubtitle.textContent = 'The town lanterns are glowing bright — take off again to reach every cat!';
}
saveBestScore(state.score);
const best = Math.max(readBestScore(), state.score);
endScore.textContent = String(state.score);
endDelivered.textContent = `${state.cratesDelivered}/${TOTAL_CRATES}`;
endBest.textContent = String(best);
mouseReticle.style.opacity = '0';
touchIndicator.style.display = 'none';
ringPointerEl.style.display = 'none';
endOverlay.classList.remove('hidden');
}
// =========================================================================
// 13. INPUT CONTROLLER (ONE-FINGER TOUCH DRAG & MOUSE POINTER FOLLOW)
// =========================================================================
const input = {
mouseActive: false,
mouseX: 0,
mouseY: 0,
touchId: null,
originX: 0,
originY: 0,
curX: 0,
curY: 0,
touchSteerX: 0,
touchSteerY: 0
};
function exitDemoFromRealTouch(e) {
if (state.mode !== 'demo') return;
if (e && e.isTrusted === false) return;
sound.init();
demoBanner.style.display = 'none';
resetWorldAndFlight(true);
state.mode = 'playing';
showToast("You're at the controls!");
}
canvas.addEventListener('pointerdown', (e) => {
if (state.mode === 'demo') exitDemoFromRealTouch(e);
if (state.mode !== 'playing') return;
sound.init();
if (e.pointerType !== 'mouse') {
input.mouseActive = false;
mouseReticle.style.opacity = '0';
input.touchId = e.pointerId;
input.originX = e.clientX;
input.originY = e.clientY;
input.curX = e.clientX;
input.curY = e.clientY;
input.touchSteerX = 0;
input.touchSteerY = 0;
try { canvas.setPointerCapture(e.pointerId); } catch (err) {}
touchBase.style.left = `${input.originX}px`;
touchBase.style.top = `${input.originY}px`;
touchKnob.style.left = `${input.curX}px`;
touchKnob.style.top = `${input.curY}px`;
touchIndicator.style.display = 'block';
} else {
input.mouseActive = true;
input.mouseX = (e.clientX / window.innerWidth) * 2 - 1;
input.mouseY = -((e.clientY / window.innerHeight) * 2 - 1);
}
});
window.addEventListener('pointermove', (e) => {
if (state.mode !== 'playing') return;
if (e.pointerType === 'mouse' && input.touchId === null) {
const vw = window.innerWidth || 1;
const vh = window.innerHeight || 1;
input.mouseActive = true;
input.mouseX = clamp((e.clientX / vw) * 2 - 1, -1, 1);
input.mouseY = clamp(-((e.clientY / vh) * 2 - 1), -1, 1);
mouseReticle.style.left = `${e.clientX}px`;
mouseReticle.style.top = `${e.clientY}px`;
mouseReticle.style.opacity = '0.88';
} else if (e.pointerId === input.touchId) {
input.curX = e.clientX;
input.curY = e.clientY;
const maxR = clamp(Math.min(window.innerWidth, window.innerHeight) * 0.14, 56, 92);
let dx = input.curX - input.originX;
let dy = -(input.curY - input.originY);
const dist = Math.hypot(dx, dy);
if (dist > maxR * 1.35) {
// Slide origin smoothly so continuous single-finger drag never stalls
const excess = dist - maxR * 1.1;
input.originX += (dx / dist) * excess;
input.originY -= (dy / dist) * excess;
dx = input.curX - input.originX;
dy = -(input.curY - input.originY);
}
input.touchSteerX = clamp(dx / maxR, -1, 1);
input.touchSteerY = clamp(dy / maxR, -1, 1);
const clampedD = Math.min(Math.hypot(dx, dy), maxR);
const ang = Math.atan2(-dy, dx);
touchBase.style.left = `${input.originX}px`;
touchBase.style.top = `${input.originY}px`;
touchKnob.style.left = `${input.originX + Math.cos(ang) * clampedD}px`;
touchKnob.style.top = `${input.originY + Math.sin(ang) * clampedD}px`;
}
});
function clearTouch(e) {
if (e.pointerId === input.touchId) {
input.touchId = null;
input.touchSteerX = 0;
input.touchSteerY = 0;
touchIndicator.style.display = 'none';
}
}
window.addEventListener('pointerup', clearTouch);
window.addEventListener('pointercancel', clearTouch);
document.addEventListener('mouseleave', () => {
input.mouseActive = false;
mouseReticle.style.opacity = '0';
});
// UI Button Listeners (stopPropagation so canvas steering isn't touched)
camButtons.forEach(btn => {
btn.addEventListener('pointerdown', (e) => {
e.stopPropagation();
if (state.mode === 'demo') exitDemoFromRealTouch(e);
});
btn.addEventListener('click', (e) => {
e.stopPropagation();
setCameraMode(btn.dataset.cam);
});
});
soundBtn.addEventListener('pointerdown', (e) => {
e.stopPropagation();
if (state.mode === 'demo') exitDemoFromRealTouch(e);
});
soundBtn.addEventListener('click', (e) => {
e.stopPropagation();
const nextMuted = !sound.muted;
sound.setMuted(nextMuted);
soundOnIcon.style.display = nextMuted ? 'none' : 'block';
soundOffIcon.style.display = nextMuted ? 'block' : 'none';
});
document.getElementById('startBtn').addEventListener('click', startPlay);
document.getElementById('playAgainBtn').addEventListener('click', startPlay);
if (isDemoInit) {
startOverlay.classList.add('hidden');
demoBanner.style.display = 'block';
resetWorldAndFlight(false);
setCameraMode('behind');
}
// =========================================================================
// 14. HELPERS: SEGMENT DISTANCE, NEAREST RING, DEMO AUTOPILOT
// =========================================================================
function distPointToSegmentSq(p, a, b) {
const abX = b.x - a.x, abY = b.y - a.y, abZ = b.z - a.z;
const apX = p.x - a.x, apY = p.y - a.y, apZ = p.z - a.z;
const lenSq = abX * abX + abY * abY + abZ * abZ;
if (lenSq < 1e-6) return apX * apX + apY * apY + apZ * apZ;
const t = clamp((apX * abX + apY * abY + apZ * abZ) / lenSq, 0, 1);
const cx = a.x + abX * t - p.x;
const cy = a.y + abY * t - p.y;
const cz = a.z + abZ * t - p.z;
return cx * cx + cy * cy + cz * cz;
}
function findNearestUndroppedStation() {
let best = null;
let bestD = Infinity;
for (let i = 0; i < deliveryStations.length; i++) {
const st = deliveryStations[i];
if (st.dropped) continue;
const d = state.planePos.distanceToSquared(st.ringPos);
if (d < bestD) {
bestD = d;
best = st;
}
}
return best;
}
function normalizeAngle(a) {
while (a > Math.PI) a -= Math.PI * 2;
while (a < -Math.PI) a += Math.PI * 2;
return a;
}
function steerTowardPoint(targetPos) {
const dx = targetPos.x - state.planePos.x;
const dy = targetPos.y - state.planePos.y;
const dz = targetPos.z - state.planePos.z;
const horizDist = Math.max(1, Math.hypot(dx, dz));
const desiredYaw = Math.atan2(-dx, -dz);
const yawDiff = normalizeAngle(desiredYaw - state.yaw);
// Notice: turning left increases yaw, steerX < 0 turns left
const sx = clamp(-yawDiff * 1.45, -1, 1);
const desiredPitch = clamp(Math.atan2(dy, horizDist), -0.55, 0.55);
const sy = clamp((desiredPitch - state.pitch) * 2.2, -1, 1);
return { sx, sy };
}
// =========================================================================
// 15. MAIN UPDATE LOOP
// =========================================================================
const tmpVec = new THREE.Vector3();
const tmpForward = new THREE.Vector3();
const tmpRight = new THREE.Vector3();
const tmpUp = new THREE.Vector3();
const projVec = new THREE.Vector3();
const invPlaneQuat = new THREE.Quaternion();
let elapsed = 0;
let lastTime = performance.now();
let smokeTimer = 0;
let trailTimer = 0;
function stepSimulation(dt) {
elapsed += dt;
skyUniforms.uTime.value = elapsed;
waterUniforms.uTime.value = elapsed;
// Drift clouds gently
for (let i = 0; i < clouds.length; i++) {
const c = clouds[i];
c.mesh.position.x += c.speed * dt;
if (c.mesh.position.x > 460) c.mesh.position.x = -460;
}
// Sailboats gliding on lake
for (let i = 0; i < sailBoats.length; i++) {
const sb = sailBoats[i];
sb.ang += sb.speed * dt;
sb.group.position.set(
Math.cos(sb.ang) * sb.rad,
Math.sin(elapsed * 1.8 + sb.phase) * 0.14,
Math.sin(sb.ang) * sb.rad
);
sb.group.rotation.y = -sb.ang;
sb.group.rotation.z = Math.sin(elapsed * 1.4 + sb.phase) * 0.05;
}
// Chimney smoke puffs
smokeTimer += dt;
if (smokeTimer > 0.32) {
smokeTimer = 0;
const idx = Math.floor(Math.random() * chimneyOrigins.length);
emitParticle(
chimneyOrigins[idx],
new THREE.Vector3((Math.random() - 0.5) * 0.8 + 0.5, 2.2 + Math.random() * 0.8, (Math.random() - 0.5) * 0.6),
'#f2ded8',
2.1,
0.55,
1.9
);
}
// Update mode-specific timers & steering
let targetSX = 0;
let targetSY = 0;
const isFlying = (state.mode === 'playing' || state.mode === 'demo' || state.mode === 'title' || state.mode === 'won' || state.mode === 'lost');
if (state.mode === 'title' || state.mode === 'won' || state.mode === 'lost') {
// Peaceful scenic circle over the lake
const orbitTarget = new THREE.Vector3(
Math.cos(elapsed * 0.22) * 115,
34,
Math.sin(elapsed * 0.22) * 115
);
const res = steerTowardPoint(orbitTarget);
targetSX = res.sx;
targetSY = res.sy;
if (state.mode === 'title') {
state.sunsetProgress = 0.08 + 0.04 * Math.sin(elapsed * 0.2);
}
} else if (state.mode === 'demo') {
state.demoTime += dt;
if (state.demoTime >= DEMO_LOOP_SECONDS) {
state.demoTime = 0;
resetWorldAndFlight(false);
}
// Showcase all 3 camera modes across 20s
const desiredDemoCam = state.demoTime < 6.8 ? 'behind' : (state.demoTime < 13.4 ? 'cockpit' : 'above');
if (state.cameraMode !== desiredDemoCam) setCameraMode(desiredDemoCam);
state.sunsetProgress = lerp(0.06, 0.62, state.demoTime / DEMO_LOOP_SECONDS);
state.timeLeft = TOTAL_FLIGHT_SECONDS * (1 - state.sunsetProgress);
updateHUD();
const nextSt = findNearestUndroppedStation();
if (nextSt) {
const res = steerTowardPoint(nextSt.ringPos);
targetSX = res.sx;
targetSY = res.sy;
}
} else if (state.mode === 'playing') {
// Pause nightfall countdown once all crates are dropped so player watches final chute land
if (state.cratesDropped < TOTAL_CRATES) {
state.timeLeft = Math.max(0, state.timeLeft - dt);
state.sunsetProgress = clamp(1.0 - state.timeLeft / TOTAL_FLIGHT_SECONDS, 0, 1);
updateHUD();
if (state.timeLeft <= 0) {
endGame(false);
}
}
if (input.touchId !== null) {
targetSX = input.touchSteerX;
targetSY = input.touchSteerY;
} else if (input.mouseActive) {
// Gentle center deadzone for smooth level cruising
const dz = 0.07;
targetSX = Math.abs(input.mouseX) < dz ? 0 : clamp((input.mouseX - Math.sign(input.mouseX) * dz) / (1 - dz), -1, 1);
targetSY = Math.abs(input.mouseY) < dz ? 0 : clamp((input.mouseY - Math.sign(input.mouseY) * dz) / (1 - dz), -1, 1);
}
}
// Soft world perimeter guide so plane never wanders off map
const distFromCenter = Math.hypot(state.planePos.x, state.planePos.z);
if (distFromCenter > 305 && state.mode === 'playing') {
const centerRes = steerTowardPoint(new THREE.Vector3(0, 30, 0));
const blend = smoothstep(305, 360, distFromCenter);
targetSX = lerp(targetSX, centerRes.sx, blend);
targetSY = lerp(targetSY, centerRes.sy, blend);
}
// Smooth steering response
state.steerX = lerp(state.steerX, targetSX, 1 - Math.exp(-6.5 * dt));
state.steerY = lerp(state.steerY, targetSY, 1 - Math.exp(-6.5 * dt));
// Plane kinematics
state.prevPlanePos.copy(state.planePos);
const maxTurnRate = 1.52;
state.yaw -= state.steerX * maxTurnRate * dt;
const targetPitch = state.steerY * 0.56;
state.pitch = lerp(state.pitch, targetPitch, 1 - Math.exp(-4.6 * dt));
// Gentle ground/water safety cushion so you skim rather than crash
const groundHere = Math.max(0, getTerrainHeight(state.planePos.x, state.planePos.z));
const minSafeY = groundHere + 4.0;
if (state.planePos.y < minSafeY) {
const push = clamp((minSafeY - state.planePos.y) * 0.25, 0, 0.5);
state.pitch = Math.max(state.pitch, push);
if (groundHere <= 0.2 && Math.random() < 0.45) {
emitParticle(
new THREE.Vector3(state.planePos.x, 0.35, state.planePos.z),
new THREE.Vector3((Math.random() - 0.5) * 4, 2.5 + Math.random() * 2, (Math.random() - 0.5) * 4),
'#e3f6ff',
0.6,
0.55,
1.4
);
}
} else if (state.planePos.y > 95) {
state.pitch = Math.min(state.pitch, -0.15);
}
const targetRoll = -state.steerX * 0.68;
state.roll = lerp(state.roll, targetRoll, 1 - Math.exp(-6.2 * dt));
// Speed subtly accelerates in dives, eases in climbs
const targetSpeed = (state.mode === 'demo' ? 37.5 : 35.0) - Math.sin(state.pitch) * 6.5;
state.speed = lerp(state.speed, targetSpeed, 1 - Math.exp(-3.0 * dt));
tmpForward.set(
-Math.sin(state.yaw) * Math.cos(state.pitch),
Math.sin(state.pitch),
-Math.cos(state.yaw) * Math.cos(state.pitch)
).normalize();
state.planePos.addScaledVector(tmpForward, state.speed * dt);
state.planePos.y = Math.max(state.planePos.y, minSafeY - 1.2);
// Apply transform to plane group
planeGroup.position.copy(state.planePos);
planeGroup.rotation.set(state.pitch, state.yaw, state.roll, 'YXZ');
planeGroup.updateMatrixWorld(true);
// Propeller spin & waving cat scarf
propAssembly.rotation.z += dt * 36.0;
propBlurDisc.material.opacity = 0.14 + 0.04 * Math.sin(elapsed * 40);
for (let s = 0; s < scarfSegments.length; s++) {
scarfSegments[s].position.x = 0.14 + Math.sin(elapsed * 16 - s * 1.1) * (0.08 + s * 0.05);
scarfSegments[s].position.y = 1.02 + Math.cos(elapsed * 13 - s * 0.9) * 0.06;
}
// Wingtip contrail ribbons when turning or cruising
trailTimer += dt;
if (trailTimer > 0.055 && (Math.abs(state.roll) > 0.14 || state.mode === 'demo')) {
trailTimer = 0;
[-4.6, 4.6].forEach(wx => {
tmpVec.set(wx, 0.2, -0.2).applyMatrix4(planeGroup.matrixWorld);
emitParticle(tmpVec, new THREE.Vector3(0, 0.2, 0), '#fff3df', 0.55, 0.24, 0.05);
});
}
// Cockpit dashboard yoke & compass needle animation
if (cockpitInteriorGroup.visible) {
cockpitYoke.rotation.z = -state.steerX * 0.58;
cockpitYoke.rotation.x = state.steerY * 0.22;
const nearest = findNearestUndroppedStation();
if (nearest) {
tmpVec.copy(nearest.ringPos).sub(state.planePos);
invPlaneQuat.copy(planeGroup.quaternion).invert();
tmpVec.applyQuaternion(invPlaneQuat);
const relAng = Math.atan2(tmpVec.x, -tmpVec.z);
cockpitCompassNeedle.rotation.z = -relAng;
}
}
// Audio propeller hum update
sound.updateProp(clamp((state.speed - 28) / 14, 0, 1), state.mode === 'playing');
// Ring animations & collision check
const canDrop = (state.mode === 'playing' || state.mode === 'demo');
const rHitSq = RING_HIT_RADIUS * RING_HIT_RADIUS;
for (let i = 0; i < deliveryStations.length; i++) {
const st = deliveryStations[i];
if (!st.dropped) {
st.ringGroup.position.y = Math.max(st.padPos.y + 18, 25 + (i % 3) * 2) + Math.sin(elapsed * 2.1 + i) * 1.1;
st.innerTorus.rotation.z = elapsed * 1.4 + i;
const pulse = 1.0 + 0.05 * Math.sin(elapsed * 4.2 + i);
st.outerTorus.scale.setScalar(pulse);
if (canDrop && distPointToSegmentSq(st.ringGroup.position, state.prevPlanePos, state.planePos) <= rHitSq) {
st.dropped = true;
state.cratesDropped++;
state.score += 100;
underbellyCrate.visible = state.cratesDropped < TOTAL_CRATES;
// Burst sparkles from ring
for (let k = 0; k < 18; k++) {
const a = (k / 18) * Math.PI * 2;
emitParticle(
st.ringGroup.position,
new THREE.Vector3(Math.cos(a) * 12, (Math.random() - 0.5) * 9, Math.sin(a) * 12),
k % 2 === 0 ? '#ffd166' : '#7cf6ff',
0.75,
0.75,
0.08
);
}
st.ringGroup.visible = false;
spawnParachuteCrate(state.planePos.clone().add(new THREE.Vector3(0, -1.3, 0)), st);
if (state.mode === 'playing') {
sound.playRingChime(state.cratesDropped - 1);
bumpPill(scorePill);
bumpPill(cratesPill);
updateHUD();
showToast(`Crate dropped over ${st.label}! +100`);
}
}
}
// Waiting cat wave / happy bounce
if (st.delivered) {
st.happyTimer += dt * 7.5;
st.cat.group.position.y = st.padPos.y + Math.abs(Math.sin(st.happyTimer)) * 0.9;
st.cat.arm.rotation.z = -1.2 + Math.sin(elapsed * 12 + i) * 0.5;
} else {
st.cat.arm.rotation.z = -0.8 + Math.sin(elapsed * 4.8 + i) * 0.45;
st.cat.head.rotation.x = -0.25 + Math.sin(elapsed * 2.0 + i) * 0.08;
}
}
// Parachute descent & landing
for (let i = activeParachutes.length - 1; i >= 0; i--) {
const pc = activeParachutes[i];
pc.age += dt;
// Pop open canopy smoothly after brief freefall
const openScale = smoothstep(0.08, 0.36, pc.age);
pc.canopyGroup.scale.setScalar(Math.max(0.05, openScale));
// Gentle sway & horizontal homing onto rooftop/dock pad
const sway = Math.sin(pc.age * 3.2) * 0.14;
pc.group.rotation.z = sway;
pc.group.position.x = lerp(pc.group.position.x, pc.targetPos.x, 1 - Math.exp(-2.6 * dt));
pc.group.position.z = lerp(pc.group.position.z, pc.targetPos.z, 1 - Math.exp(-2.6 * dt));
pc.group.position.y += pc.velY * dt;
if (pc.group.position.y <= pc.targetPos.y) {
// Landed!
const st = pc.station;
st.delivered = true;
state.cratesDelivered++;
state.score += 50;
// Leave landed crate neatly on rooftop/dock
const landed = new THREE.Mesh(crateGeo, crateMat);
landed.position.copy(pc.targetPos);
landed.castShadow = true;
scene.add(landed);
st.landedCrate = landed;
// Happy delivery particles
for (let h = 0; h < 10; h++) {
emitParticle(
pc.targetPos.clone().add(new THREE.Vector3(0, 1.5, 0)),
new THREE.Vector3((Math.random() - 0.5) * 4, 4 + Math.random() * 4, (Math.random() - 0.5) * 4),
h % 2 === 0 ? '#ff7b89' : '#ffd166',
1.1,
0.6,
0.1
);
}
scene.remove(pc.group);
activeParachutes.splice(i, 1);
if (state.mode === 'playing') {
sound.playDeliveryMeow();
bumpPill(scorePill);
updateHUD();
if (state.cratesDelivered >= TOTAL_CRATES) {
endGame(true);
} else {
showToast(`Delivered to ${st.label}! +50`);
}
}
}
}
// Update particles
for (let i = 0; i < particlePool.length; i++) {
const p = particlePool[i];
if (!p.active) continue;
p.age += dt;
if (p.age >= p.life) {
p.active = false;
p.mesh.visible = false;
continue;
}
const k = p.age / p.life;
p.mesh.position.addScaledVector(p.vel, dt);
p.mesh.scale.setScalar(lerp(p.startScale, p.endScale, k));
p.mat.opacity = (1 - k) * 0.85;
}
// Update sky, lights & fog
updateAtmosphere(state.sunsetProgress);
// Update Camera
updateCamera(dt);
// Update Off-Screen Ring Compass Arrow
updateRingCompassPointer();
}
function updateCamera(dt) {
tmpForward.set(
-Math.sin(state.yaw) * Math.cos(state.pitch),
Math.sin(state.pitch),
-Math.cos(state.yaw) * Math.cos(state.pitch)
).normalize();
const horizFwdX = -Math.sin(state.yaw);
const horizFwdZ = -Math.cos(state.yaw);
const desiredPos = new THREE.Vector3();
const desiredLook = new THREE.Vector3();
const desiredUp = new THREE.Vector3(0, 1, 0);
if (state.cameraMode === 'cockpit') {
// Directly inside cockpit looking over instruments & spinning prop
desiredPos.set(0, 1.38, -0.35).applyMatrix4(planeGroup.matrixWorld);
desiredLook.set(0, 1.18, -28).applyMatrix4(planeGroup.matrixWorld);
// Softened cockpit roll so horizon tilts naturally without dizzying spin
const localUp = new THREE.Vector3(0, 1, 0).applyQuaternion(planeGroup.quaternion);
desiredUp.set(0, 1, 0).lerp(localUp, 0.55).normalize();
mainCam.position.copy(desiredPos);
mainCam.up.copy(desiredUp);
mainCam.lookAt(desiredLook);
state.camPos.copy(desiredPos);
state.camLook.copy(desiredLook);
state.camUp.copy(desiredUp);
state.camSnap = false;
return;
}
if (state.cameraMode === 'above') {
// High bird's-eye diorama camera tracking behind & high above plane
desiredPos.set(
state.planePos.x - horizFwdX * 19,
state.planePos.y + 56,
state.planePos.z - horizFwdZ * 19
);
desiredLook.set(
state.planePos.x + horizFwdX * 14,
Math.max(2, state.planePos.y - 12),
state.planePos.z + horizFwdZ * 14
);
} else {
// 'behind' — Smooth scenic chase camera behind the orange cat pilot
desiredPos.set(
state.planePos.x - horizFwdX * 13.5,
Math.max(3.5, state.planePos.y + 4.4 - tmpForward.y * 3.0),
state.planePos.z - horizFwdZ * 13.5
);
desiredLook.set(
state.planePos.x + tmpForward.x * 16,
state.planePos.y + tmpForward.y * 16 + 0.8,
state.planePos.z + tmpForward.z * 16
);
desiredUp.set(Math.sin(-state.roll * 0.22), Math.cos(state.roll * 0.22), 0).applyAxisAngle(
new THREE.Vector3(0, 1, 0),
state.yaw
);
// Keep mostly world up
desiredUp.lerp(new THREE.Vector3(0, 1, 0), 0.72).normalize();
}
if (state.camSnap) {
state.camPos.copy(desiredPos);
state.camLook.copy(desiredLook);
state.camUp.copy(desiredUp);
state.camSnap = false;
} else {
const kPos = 1 - Math.exp(-7.5 * dt);
const kLook = 1 - Math.exp(-10.0 * dt);
state.camPos.lerp(desiredPos, kPos);
state.camLook.lerp(desiredLook, kLook);
state.camUp.lerp(desiredUp, kPos).normalize();
}
mainCam.position.copy(state.camPos);
mainCam.up.copy(state.camUp);
mainCam.lookAt(state.camLook);
}
function updateRingCompassPointer() {
if (state.mode !== 'playing') {
ringPointerEl.style.display = 'none';
return;
}
const nearest = findNearestUndroppedStation();
if (!nearest) {
ringPointerEl.style.display = 'none';
return;
}
const dist = Math.round(state.planePos.distanceTo(nearest.ringGroup.position));
projVec.copy(nearest.ringGroup.position).project(mainCam);
const isBehind = projVec.z > 1;
let nx = projVec.x;
let ny = projVec.y;
if (isBehind) {
nx = -nx;
ny = -ny;
}
const insideView = !isBehind && Math.abs(nx) < 0.80 && Math.abs(ny) < 0.78;
if (insideView) {
ringPointerEl.style.display = 'none';
return;
}
// Clamp direction to screen inset margin
const mag = Math.max(Math.abs(nx) / 0.84, Math.abs(ny) / 0.76, 1e-4);
const cx = nx / mag;
const cy = ny / mag;
const vw = window.innerWidth;
const vh = window.innerHeight;
const sx = (cx * 0.5 + 0.5) * vw;
const sy = (-cy * 0.5 + 0.5) * vh;
const angDeg = Math.atan2(cx, cy) * (180 / Math.PI);
ringPointerEl.style.display = 'flex';
ringPointerEl.style.left = `${clamp(sx, 36, vw - 36)}px`;
ringPointerEl.style.top = `${clamp(sy, 84, vh - 94)}px`;
ringArrowShape.style.transform = `rotate(${angDeg.toFixed(1)}deg)`;
ringDistLabel.textContent = `${dist}m`;
}
// =========================================================================
// 16. RENDER WITH REAL-TIME PLANAR LAKE WATER REFLECTION
// =========================================================================
function renderFrame() {
mainCam.updateMatrixWorld(true);
// Update sun shadow map once per frame
renderer.shadowMap.needsUpdate = true;
// 1) Planar Reflection Pass (mirror mainCam across y = 0)
waterMesh.visible = false;
skyMesh.position.set(mainCam.position.x, -mainCam.position.y, mainCam.position.z);
// Extract camera basis vectors to build exact right-handed mirrored camera
mainCam.getWorldDirection(tmpForward);
tmpUp.copy(mainCam.up).normalize();
tmpRight.crossVectors(tmpForward, tmpUp).normalize();
tmpUp.crossVectors(tmpRight, tmpForward).normalize();
reflCam.fov = mainCam.fov;
reflCam.aspect = mainCam.aspect;
reflCam.near = mainCam.near;
reflCam.far = mainCam.far;
reflCam.updateProjectionMatrix();
reflCam.position.set(mainCam.position.x, -mainCam.position.y, mainCam.position.z);
// Reflected look target & reflected right-handed up vector (-M * U = (-ux, uy, -uz))
const reflLook = new THREE.Vector3(
mainCam.position.x + tmpForward.x,
-(mainCam.position.y + tmpForward.y),
mainCam.position.z + tmpForward.z
);
reflCam.up.set(-tmpUp.x, tmpUp.y, -tmpUp.z).normalize();
reflCam.lookAt(reflLook);
reflCam.updateMatrixWorld(true);
reflProjView.multiplyMatrices(reflCam.projectionMatrix, reflCam.matrixWorldInverse);
renderer.clippingPlanes = [reflClipPlane];
renderer.setRenderTarget(reflTarget);
renderer.clear();
renderer.render(scene, reflCam);
// 2) Main Screen Pass
renderer.clippingPlanes = [];
renderer.setRenderTarget(null);
waterMesh.visible = true;
skyMesh.position.copy(mainCam.position);
renderer.render(scene, mainCam);
}
function onResize() {
const w = window.innerWidth;
const h = window.innerHeight;
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(w, h, false);
mainCam.aspect = w / h;
mainCam.updateProjectionMatrix();
const rw = Math.max(128, Math.floor(w * 0.45));
const rh = Math.max(128, Math.floor(h * 0.45));
reflTarget.setSize(rw, rh);
}
window.addEventListener('resize', onResize);
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min((now - lastTime) * 0.001, 0.05);
lastTime = now;
if (dt > 0) stepSimulation(dt);
renderFrame();
}
updateAtmosphere(state.sunsetProgress);
updateHUD();
requestAnimationFrame(animate);
})();
</script>
</body>
</html>
