Prompt specification
Build or customize the Three.js 3D scene "Wind Shift Changes the Route" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Wind Shift Changes the Route
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/wind-shift-changes-the-route-x3680
Scene Description Prompt:
Create a standalone voxel scene in one HTML file using Three.js from cdnjs. Create a toy sailing route puzzle with one declared wind shift. Compare planned and revised paths under the same simplified rules and show unreachable direct headings.
Working Three.js Starter (wind-shift-changes-the-route-x3680):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Windward — Voxel Sailing Puzzle</title>
<style>
:root {
--bg: #07131f;
--panel: rgba(10, 25, 39, 0.88);
--panel-strong: rgba(13, 32, 49, 0.96);
--line: rgba(160, 210, 229, 0.15);
--text: #edf8fb;
--muted: #91aab7;
--cyan: #54e0d0;
--cyan-soft: rgba(84, 224, 208, 0.14);
--pink: #ff6d9e;
--pink-soft: rgba(255, 109, 158, 0.13);
--orange: #ffb45c;
--green: #8ee69f;
--red: #ff7080;
--shadow: 0 18px 60px rgba(0, 0, 0, 0.34);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.topbar {
position: fixed;
z-index: 20;
top: 20px;
left: 22px;
right: 22px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.brand,
.top-actions,
.weather {
pointer-events: auto;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
text-shadow: 0 2px 16px rgba(0, 0, 0, 0.6);
}
.brand-mark {
position: relative;
width: 38px;
height: 38px;
border: 1px solid rgba(84, 224, 208, 0.55);
border-radius: 11px;
background: rgba(7, 25, 38, 0.84);
box-shadow: 0 0 30px rgba(84, 224, 208, 0.12);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
background: var(--cyan);
border-radius: 2px;
}
.brand-mark::before {
width: 5px;
height: 24px;
left: 15px;
top: 7px;
transform: skewY(-18deg);
}
.brand-mark::after {
width: 15px;
height: 5px;
left: 18px;
top: 9px;
box-shadow: -10px 10px 0 rgba(84, 224, 208, 0.48);
}
.brand-name {
font-size: 15px;
font-weight: 850;
letter-spacing: 0.22em;
}
.brand-sub {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.top-right {
display: flex;
align-items: center;
gap: 10px;
}
.weather {
min-width: 164px;
display: flex;
align-items: center;
gap: 10px;
padding: 9px 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(9, 26, 40, 0.8);
backdrop-filter: blur(14px);
box-shadow: var(--shadow);
}
.wind-dot {
width: 10px;
height: 10px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 14px var(--cyan);
transition: 300ms ease;
}
.wind-dot.shifted {
background: var(--orange);
box-shadow: 0 0 14px var(--orange);
}
.weather small,
.weather strong {
display: block;
}
.weather small {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
}
.weather strong {
margin-top: 2px;
font-size: 12px;
letter-spacing: 0.04em;
}
.icon-btn {
height: 38px;
padding: 0 13px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(9, 26, 40, 0.82);
cursor: pointer;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
}
.icon-btn:hover {
border-color: rgba(84, 224, 208, 0.45);
background: rgba(19, 51, 67, 0.94);
transform: translateY(-1px);
}
.panel {
position: fixed;
z-index: 15;
top: 86px;
width: 326px;
max-height: calc(100vh - 112px);
overflow: auto;
padding: 19px;
border: 1px solid var(--line);
border-radius: 18px;
background:
linear-gradient(145deg, rgba(16, 39, 56, 0.96), rgba(7, 22, 35, 0.94));
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: rgba(84, 224, 208, 0.35) transparent;
}
.panel.left {
left: 22px;
}
.panel.right {
right: 22px;
width: 310px;
}
.eyebrow {
color: var(--cyan);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 8px;
font-size: 29px;
line-height: 1;
letter-spacing: -0.045em;
}
.intro {
margin: 0;
color: #b8cbd4;
font-size: 12px;
line-height: 1.6;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 13px;
}
.chip {
padding: 5px 8px;
border: 1px solid rgba(145, 170, 183, 0.2);
border-radius: 999px;
color: #b9cbd4;
background: rgba(255, 255, 255, 0.025);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 20px 0 9px;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.section-title span:last-child {
color: var(--muted);
font-size: 9px;
font-weight: 700;
}
.shift-card {
position: relative;
overflow: hidden;
padding: 14px;
border: 1px solid rgba(255, 180, 92, 0.27);
border-radius: 14px;
background:
linear-gradient(135deg, rgba(255, 180, 92, 0.1), rgba(255, 180, 92, 0.025));
transition: 300ms ease;
}
.shift-card::after {
content: "";
position: absolute;
top: -30px;
right: -30px;
width: 90px;
height: 90px;
border-radius: 50%;
background: rgba(255, 180, 92, 0.09);
}
.shift-card.triggered {
border-color: rgba(84, 224, 208, 0.36);
background: linear-gradient(135deg, rgba(84, 224, 208, 0.1), transparent);
}
.shift-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.shift-head strong {
font-size: 13px;
}
.one-badge {
padding: 4px 7px;
border-radius: 6px;
color: #21150a;
background: var(--orange);
font-size: 8px;
font-weight: 900;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.triggered .one-badge {
color: #052722;
background: var(--cyan);
}
.wind-transition {
display: grid;
grid-template-columns: 1fr 30px 1fr;
align-items: center;
margin-top: 13px;
}
.wind-box {
padding: 10px 8px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 10px;
background: rgba(2, 12, 20, 0.24);
text-align: center;
}
.wind-box small,
.wind-box strong {
display: block;
}
.wind-box small {
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.12em;
}
.wind-box strong {
margin-top: 3px;
font-size: 13px;
}
.transition-arrow {
color: var(--orange);
text-align: center;
font-size: 20px;
font-weight: 400;
}
.triggered .transition-arrow {
color: var(--cyan);
}
.shift-note {
margin: 9px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.probe-toggle {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
padding: 4px;
border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: 10px;
background: rgba(0, 0, 0, 0.14);
}
.probe-toggle button {
padding: 7px 6px;
border: 0;
border-radius: 7px;
color: var(--muted);
background: transparent;
cursor: pointer;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.probe-toggle button.active {
color: #dffbf7;
background: rgba(84, 224, 208, 0.14);
box-shadow: inset 0 0 0 1px rgba(84, 224, 208, 0.18);
}
.compass-wrap {
position: relative;
width: 214px;
height: 214px;
margin: 12px auto 9px;
}
.compass-ring {
position: absolute;
inset: 42px;
border: 1px dashed rgba(145, 170, 183, 0.23);
border-radius: 50%;
}
.compass-center {
position: absolute;
left: 50%;
top: 50%;
width: 58px;
height: 58px;
transform: translate(-50%, -50%);
display: grid;
place-items: center;
border: 1px solid rgba(84, 224, 208, 0.24);
border-radius: 50%;
color: var(--cyan);
background: rgba(84, 224, 208, 0.08);
box-shadow:
0 0 0 9px rgba(84, 224, 208, 0.025),
0 0 28px rgba(84, 224, 208, 0.08);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
}
.heading {
position: absolute;
width: 50px;
height: 42px;
padding: 0;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 10px;
color: var(--muted);
background: rgba(3, 13, 22, 0.62);
cursor: pointer;
font-size: 10px;
font-weight: 850;
transition: 140ms ease;
}
.heading:hover {
transform: translateY(-1px);
}
.heading.allowed {
color: var(--cyan);
border-color: rgba(84, 224, 208, 0.24);
background: rgba(84, 224, 208, 0.075);
}
.heading.blocked {
color: #e77b89;
border-color: rgba(255, 112, 128, 0.15);
background: rgba(255, 112, 128, 0.045);
}
.heading.selected {
outline: 2px solid rgba(255, 255, 255, 0.32);
outline-offset: 2px;
}
.heading.nw { left: 2px; top: 2px; }
.heading.n { left: 82px; top: 2px; }
.heading.ne { right: 2px; top: 2px; }
.heading.w { left: 2px; top: 86px; }
.heading.e { right: 2px; top: 86px; }
.heading.sw { left: 2px; bottom: 2px; }
.heading.s { left: 82px; bottom: 2px; }
.heading.se { right: 2px; bottom: 2px; }
.heading-status {
min-height: 48px;
padding: 9px 11px;
border: 1px solid rgba(255, 255, 255, 0.07);
border-radius: 10px;
background: rgba(0, 0, 0, 0.13);
}
.heading-status strong,
.heading-status span {
display: block;
}
.heading-status strong {
font-size: 11px;
letter-spacing: 0.04em;
}
.heading-status span {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.heading-status.good strong {
color: var(--cyan);
}
.heading-status.bad strong {
color: var(--red);
}
.rule-intro {
margin: 0 0 10px;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.route-card {
position: relative;
overflow: hidden;
margin-top: 9px;
padding: 13px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 13px;
background: rgba(2, 12, 20, 0.25);
}
.route-card.planned {
border-color: rgba(255, 109, 158, 0.22);
background: linear-gradient(145deg, var(--pink-soft), rgba(0, 0, 0, 0.12));
}
.route-card.revised {
border-color: rgba(84, 224, 208, 0.24);
background: linear-gradient(145deg, var(--cyan-soft), rgba(0, 0, 0, 0.12));
}
.route-card-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.route-name {
color: var(--muted);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.route-status {
padding: 4px 7px;
border-radius: 6px;
font-size: 8px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.planned .route-status {
color: #ffd1df;
background: rgba(255, 109, 158, 0.2);
}
.revised .route-status {
color: #c9fff8;
background: rgba(84, 224, 208, 0.17);
}
.route-main {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 10px;
margin-top: 9px;
}
.route-result {
font-size: 21px;
font-weight: 900;
letter-spacing: -0.035em;
}
.planned .route-result {
color: var(--pink);
}
.revised .route-result {
color: var(--cyan);
}
.route-metric {
color: var(--muted);
font-size: 9px;
line-height: 1.4;
text-align: right;
}
.route-description {
min-height: 28px;
margin: 7px 0 10px;
color: #aec2cc;
font-size: 10px;
line-height: 1.45;
}
.route-button {
width: 100%;
padding: 8px 10px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 9px;
background: rgba(255, 255, 255, 0.045);
cursor: pointer;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
transition: 160ms ease;
}
.route-button:hover {
background: rgba(255, 255, 255, 0.09);
transform: translateY(-1px);
}
.route-button.primary {
color: #062521;
border-color: var(--cyan);
background: var(--cyan);
}
.route-button.primary:hover {
background: #72eadc;
}
.rules {
display: grid;
gap: 7px;
margin-top: 10px;
}
.rule {
display: flex;
align-items: flex-start;
gap: 8px;
color: #a9bdc7;
font-size: 10px;
line-height: 1.4;
}
.rule b {
flex: 0 0 auto;
width: 17px;
height: 17px;
display: grid;
place-items: center;
border: 1px solid rgba(84, 224, 208, 0.25);
border-radius: 5px;
color: var(--cyan);
font-size: 8px;
}
.toggles {
display: flex;
gap: 14px;
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.07);
}
.toggle {
display: flex;
align-items: center;
gap: 6px;
color: var(--muted);
cursor: pointer;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.toggle input {
accent-color: var(--cyan);
}
.toggle.pink input {
accent-color: var(--pink);
}
.bottom-hint {
position: fixed;
z-index: 10;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 9px;
padding: 8px 12px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 999px;
color: rgba(207, 226, 234, 0.72);
background: rgba(6, 19, 30, 0.74);
backdrop-filter: blur(12px);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.07em;
text-transform: uppercase;
pointer-events: none;
}
.mouse-icon {
width: 12px;
height: 17px;
border: 1px solid rgba(255, 255, 255, 0.5);
border-radius: 7px;
position: relative;
}
.mouse-icon::before {
content: "";
position: absolute;
top: 3px;
left: 4px;
width: 2px;
height: 4px;
border-radius: 2px;
background: var(--cyan);
}
#toast {
position: fixed;
z-index: 40;
left: 50%;
top: 82px;
transform: translate(-50%, -15px);
padding: 10px 15px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 10px;
color: var(--text);
background: rgba(8, 25, 38, 0.94);
box-shadow: var(--shadow);
opacity: 0;
pointer-events: none;
font-size: 11px;
font-weight: 750;
transition:
opacity 180ms ease,
transform 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.good {
border-color: rgba(84, 224, 208, 0.38);
}
#toast.bad {
border-color: rgba(255, 112, 128, 0.38);
}
#labels {
position: fixed;
z-index: 8;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
transform: translate(-50%, -100%);
padding: 5px 7px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 6px;
color: #e8f5f8;
background: rgba(5, 17, 28, 0.82);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
font-size: 8px;
font-weight: 900;
letter-spacing: 0.12em;
text-transform: uppercase;
white-space: nowrap;
}
.world-label.start {
color: var(--green);
border-color: rgba(142, 230, 159, 0.25);
}
.world-label.shift {
color: var(--orange);
border-color: rgba(255, 180, 92, 0.25);
}
.world-label.goal {
color: #ffe09b;
border-color: rgba(255, 224, 155, 0.28);
}
.world-label.warning {
color: #ff9aae;
border-color: rgba(255, 109, 158, 0.32);
background: rgba(48, 16, 30, 0.88);
}
@media (max-width: 1020px) {
.panel.left {
width: 300px;
}
.panel.right {
width: 286px;
}
.weather {
display: none;
}
}
@media (max-width: 720px) {
body {
overflow: auto;
}
.topbar {
top: 12px;
left: 12px;
right: 12px;
}
.brand-sub {
display: none;
}
.brand-name {
font-size: 12px;
}
.top-actions .icon-btn:first-child {
display: none;
}
.panel {
top: 66px;
max-height: 42vh;
padding: 14px;
}
.panel.left {
left: 10px;
width: min(286px, calc(100vw - 20px));
}
.panel.right {
top: auto;
right: 10px;
bottom: 10px;
width: min(286px, calc(100vw - 20px));
}
h1 {
font-size: 23px;
}
.compass-wrap {
width: 190px;
height: 190px;
}
.heading.n,
.heading.s {
left: 70px;
}
.heading.w,
.heading.e {
top: 74px;
}
.bottom-hint {
display: none;
}
#toast {
top: 62px;
width: max-content;
max-width: calc(100vw - 24px);
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div id="labels"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark"></div>
<div>
<div class="brand-name">WINDWARD</div>
<div class="brand-sub">Voxel navigation lab · Route 07</div>
</div>
</div>
<div class="top-right">
<div class="weather">
<span class="wind-dot" id="windDot"></span>
<div>
<small>ACTIVE WIND</small>
<strong id="windValue">FROM W · 270°</strong>
</div>
</div>
<div class="top-actions">
<button class="icon-btn" id="resetRoute">Reset sail</button>
<button class="icon-btn" id="resetCamera">Reset view</button>
</div>
</div>
</header>
<aside class="panel left">
<div class="eyebrow">Toy sailing puzzle</div>
<h1>Catch the shift.</h1>
<p class="intro">
The forecast promises a straight pull north. One buoy changes the wind.
Compare the direct plan with a route that survives the declared shift.
</p>
<div class="chips">
<span class="chip">8 headings</span>
<span class="chip">1 shift</span>
<span class="chip">Shared rules</span>
</div>
<div class="section-title">
<span>Declared shift</span>
<span id="phaseValue">Pre-shift</span>
</div>
<div class="shift-card" id="shiftCard">
<div class="shift-head">
<strong>Buoy B6</strong>
<span class="one-badge">One event</span>
</div>
<div class="wind-transition">
<div class="wind-box">
<small>BEFORE</small>
<strong>FROM W</strong>
</div>
<div class="transition-arrow">→</div>
<div class="wind-box">
<small>AFTER</small>
<strong>FROM S</strong>
</div>
</div>
<p class="shift-note" id="shiftNote">
Contact with the orange buoy triggers the shift exactly once.
</p>
</div>
<div class="section-title">
<span>Direct heading probe</span>
<span>Click a heading</span>
</div>
<div class="probe-toggle">
<button class="active" data-probe="start">At start</button>
<button data-probe="shift">At shift buoy</button>
</div>
<div class="compass-wrap">
<div class="compass-ring"></div>
<div class="compass-center">BOAT</div>
<button class="heading blocked selected" data-dir="NW">NW</button>
<button class="heading blocked" data-dir="N">N</button>
<button class="heading allowed" data-dir="NE">NE</button>
<button class="heading blocked" data-dir="W">W</button>
<button class="heading allowed" data-dir="E">E</button>
<button class="heading blocked" data-dir="SW">SW</button>
<button class="heading blocked" data-dir="S">S</button>
<button class="heading allowed" data-dir="SE">SE</button>
</div>
<div class="heading-status bad" id="headingStatus">
<strong id="headingTitle">NW · NO-GO</strong>
<span id="headingReason">Outside the legal downwind arc.</span>
</div>
</aside>
<aside class="panel right">
<div class="eyebrow">Route comparison</div>
<h1 style="font-size: 24px; margin-top: 8px;">Same rules. New wind.</h1>
<p class="rule-intro">
Both routes use the same heading test, island collision test, and
one-event shift model.
</p>
<div class="route-card planned">
<div class="route-card-top">
<span class="route-name">Planned · direct</span>
<span class="route-status">Unreachable</span>
</div>
<div class="route-main">
<div class="route-result">NO-GO</div>
<div class="route-metric">6 moves<br />0 legal steps</div>
</div>
<p class="route-description">
A straight northbound pull. N sits on the no-go boundary while the
west wind is active.
</p>
<button class="route-button" id="testPlan">Test planned route</button>
</div>
<div class="route-card revised">
<div class="route-card-top">
<span class="route-name">Revised · shift-aware</span>
<span class="route-status">Valid</span>
</div>
<div class="route-main">
<div class="route-result">REACHABLE</div>
<div class="route-metric" id="revisedMetric">Finding route…</div>
</div>
<p class="route-description">
Reach the orange buoy, accept the new south wind, then climb northwest
around the reef.
</p>
<button class="route-button primary" id="sailRevised">Sail revised route</button>
</div>
<div class="section-title">
<span>Shared rule set</span>
<span>4 checks</span>
</div>
<div class="rules">
<div class="rule"><b>1</b><span>Use one of eight compass headings.</span></div>
<div class="rule"><b>2</b><span>Heading must be within 80° of downwind.</span></div>
<div class="rule"><b>3</b><span>Destination tile must be clear.</span></div>
<div class="rule"><b>4</b><span>The buoy changes the wind once.</span></div>
</div>
<div class="toggles">
<label class="toggle pink">
<input type="checkbox" id="plannedToggle" checked />
Planned
</label>
<label class="toggle">
<input type="checkbox" id="revisedToggle" checked />
Revised
</label>
</div>
</aside>
<div class="bottom-hint">
<span class="mouse-icon"></span>
Drag to orbit · Scroll to zoom
</div>
<div id="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Puzzle model
// -------------------------------------------------------------------------
const COLS = 13;
const ROWS = 9;
const CELL = 1;
const START = { x: 1, y: 7 };
const GOAL = { x: 1, y: 1 };
const SHIFT = { x: 5, y: 6 };
const INITIAL_WIND_FROM = 270; // Compass degrees: wind from west.
const SHIFT_WIND_FROM = 180; // Compass degrees: wind from south.
const MAX_OFF_DOWNWIND = 80;
const MIN_DOWNWIND_DOT = Math.cos(
THREE.MathUtils.degToRad(MAX_OFF_DOWNWIND)
);
const OBSTACLES = new Set([
"3,4",
"4,5",
"2,5"
]);
const DIRECTIONS = [
{ name: "N", dx: 0, dz: -1, angle: 0 },
{ name: "NE", dx: 1, dz: -1, angle: 45 },
{ name: "E", dx: 1, dz: 0, angle: 90 },
{ name: "SE", dx: 1, dz: 1, angle: 135 },
{ name: "S", dx: 0, dz: 1, angle: 180 },
{ name: "SW", dx: -1, dz: 1, angle: 225 },
{ name: "W", dx: -1, dz: 0, angle: 270 },
{ name: "NW", dx: -1, dz: -1, angle: 315 }
];
const directionByName = Object.fromEntries(
DIRECTIONS.map((direction) => [direction.name, direction])
);
const plannedRoute = Array.from({ length: 7 }, (_, index) => ({
x: START.x,
y: START.y - index,
shifted: false
}));
const worldX = (gridX) => gridX - (COLS - 1) / 2;
const worldZ = (gridY) => gridY - (ROWS - 1) / 2;
function isObstacle(x, y) {
return OBSTACLES.has(`${x},${y}`);
}
function inBounds(x, y) {
return x >= 0 && x < COLS && y >= 0 && y < ROWS;
}
function windVector(windFrom) {
const radians = THREE.MathUtils.degToRad(windFrom + 180);
return {
x: Math.sin(radians),
z: -Math.cos(radians)
};
}
function headingIsAllowed(direction, windFrom) {
const downwind = windVector(windFrom);
const dot =
direction.dx * downwind.x +
direction.dz * downwind.z;
return dot >= MIN_DOWNWIND_DOT;
}
function heuristic(x, y) {
return Math.hypot(x - GOAL.x, y - GOAL.y);
}
function findRoute(useDeclaredShift = true) {
const open = [{
x: START.x,
y: START.y,
shifted: false,
g: 0,
f: heuristic(START.x, START.y),
path: []
}];
const best = new Map();
while (open.length) {
open.sort((a, b) => a.f - b.f);
const current = open.shift();
const key = `${current.x},${current.y},${current.shifted}`;
if ((best.get(key) ?? Infinity) < current.g) continue;
if (current.x === GOAL.x && current.y === GOAL.y) {
return current.path;
}
const wind = current.shifted ? SHIFT_WIND_FROM : INITIAL_WIND_FROM;
for (const direction of DIRECTIONS) {
if (!headingIsAllowed(direction, wind)) continue;
const nx = current.x + direction.dx;
const ny = current.y + direction.dz;
if (!inBounds(nx, ny) || isObstacle(nx, ny)) continue;
const shifted =
current.shifted ||
(useDeclaredShift && nx === SHIFT.x && ny === SHIFT.y);
const nextKey = `${nx},${ny},${shifted}`;
const cost =
current.g +
(direction.dx !== 0 && direction.dz !== 0 ? Math.SQRT2 : 1);
if ((best.get(nextKey) ?? Infinity) <= cost) continue;
best.set(nextKey, cost);
const path = current.path.concat([{
x: nx,
y: ny,
shifted
}]);
open.push({
x: nx,
y: ny,
shifted,
g: cost,
f: cost + heuristic(nx, ny),
path
});
}
}
return null;
}
function validateRoute(route) {
let shifted = false;
let legalSteps = 0;
for (let index = 1; index < route.length; index++) {
const previous = route[index - 1];
const next = route[index];
const dx = next.x - previous.x;
const dy = next.y - previous.y;
const direction = DIRECTIONS.find(
(candidate) => candidate.dx === dx && candidate.dz === dy
);
const wind = shifted ? SHIFT_WIND_FROM : INITIAL_WIND_FROM;
if (!direction) {
return { valid: false, legalSteps, reason: "Non-compass heading." };
}
if (!headingIsAllowed(direction, wind)) {
return {
valid: false,
legalSteps,
reason: `${direction.name} is outside the legal downwind arc.`
};
}
if (!inBounds(next.x, next.y)) {
return { valid: false, legalSteps, reason: "Route leaves the map." };
}
if (isObstacle(next.x, next.y)) {
return { valid: false, legalSteps, reason: "Route enters a reef." };
}
legalSteps++;
shifted = shifted || (next.x === SHIFT.x && next.y === SHIFT.y);
}
const reachedGoal =
route.at(-1).x === GOAL.x && route.at(-1).y === GOAL.y;
return {
valid: reachedGoal,
legalSteps,
reason: reachedGoal ? "Goal reached." : "Goal not reached."
};
}
const revisedRoute = findRoute(true);
const noShiftRoute = findRoute(false);
const plannedValidation = validateRoute(plannedRoute);
const revisedValidation = validateRoute(revisedRoute ?? []);
document.getElementById("revisedMetric").innerHTML =
`${revisedRoute.length - 1} moves<br />${revisedValidation.legalSteps} legal steps`;
// -------------------------------------------------------------------------
// Renderer, scene, camera, and custom camera controls
// -------------------------------------------------------------------------
const sceneHost = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131f);
scene.fog = new THREE.Fog(0x07131f, 18, 36);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(-0.6, 0, -0.15);
const cameraState = {
radius: 18.2,
theta: 0.54,
phi: 0.76
};
function updateCamera() {
const { radius, theta, phi } = cameraState;
camera.position.set(
cameraTarget.x + radius * Math.sin(phi) * Math.sin(theta),
cameraTarget.y + radius * Math.cos(phi),
cameraTarget.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
let dragging = false;
let previousPointer = { x: 0, y: 0 };
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointer = { x: event.clientX, y: event.clientY };
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousPointer.x;
const dy = event.clientY - previousPointer.y;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.35,
1.24
);
previousPointer = { x: event.clientX, y: event.clientY };
updateCamera();
});
function stopDragging() {
dragging = false;
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
10,
27
);
updateCamera();
},
{ passive: false }
);
document.getElementById("resetCamera").addEventListener("click", () => {
cameraState.radius = 18.2;
cameraState.theta = 0.54;
cameraState.phi = 0.76;
updateCamera();
});
const hemisphere = new THREE.HemisphereLight(0xa9ddff, 0x102331, 1.8);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2d7, 3.1);
sun.position.set(7, 13, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.00025;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x49cde5, 1.4);
rimLight.position.set(-8, 6, -7);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Reusable voxel primitives
// -------------------------------------------------------------------------
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function voxel(
parent,
x,
y,
z,
sx,
sy,
sz,
material,
castShadow = true
) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.position.set(x, y, z);
mesh.scale.set(sx, sy, sz);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const materials = {
base: new THREE.MeshStandardMaterial({
color: 0x0a2635,
roughness: 0.9
}),
water: [
new THREE.MeshStandardMaterial({
color: 0x17475a,
roughness: 0.74,
metalness: 0.04
}),
new THREE.MeshStandardMaterial({
color: 0x194c60,
roughness: 0.72,
metalness: 0.04
}),
new THREE.MeshStandardMaterial({
color: 0x123f52,
roughness: 0.78,
metalness: 0.03
}),
new THREE.MeshStandardMaterial({
color: 0x1b5264,
roughness: 0.7,
metalness: 0.05
})
],
reefBase: new THREE.MeshStandardMaterial({
color: 0x356575,
roughness: 0.95
}),
reefMid: new THREE.MeshStandardMaterial({
color: 0x4a8e89,
roughness: 0.88
}),
reefTop: new THREE.MeshStandardMaterial({
color: 0x72b69b,
roughness: 0.82
}),
orange: new THREE.MeshStandardMaterial({
color: 0xffa94f,
emissive: 0x8f3600,
emissiveIntensity: 0.34,
roughness: 0.58
}),
orangeBright: new THREE.MeshStandardMaterial({
color: 0xffc36d,
emissive: 0xb25b12,
emissiveIntensity: 0.48,
roughness: 0.5
}),
green: new THREE.MeshStandardMaterial({
color: 0x7de29a,
emissive: 0x174a2a,
emissiveIntensity: 0.3
}),
cyan: new THREE.MeshStandardMaterial({
color: 0x58e2d2,
emissive: 0x126a65,
emissiveIntensity: 0.7
}),
pink: new THREE.MeshStandardMaterial({
color: 0xff6d9e,
emissive: 0x6d1737,
emissiveIntensity: 0.55
}),
cream: new THREE.MeshStandardMaterial({
color: 0xffecc5,
roughness: 0.72
}),
hull: new THREE.MeshStandardMaterial({
color: 0x15394a,
roughness: 0.72
}),
hullTrim: new THREE.MeshStandardMaterial({
color: 0xffa954,
roughness: 0.58
}),
dark: new THREE.MeshStandardMaterial({
color: 0x07141d,
roughness: 0.7
})
};
// Water and map base.
voxel(
scene,
0,
-0.38,
0,
COLS + 0.8,
0.45,
ROWS + 0.8,
materials.base
);
const waterTiles = [];
for (let y = 0; y < ROWS; y++) {
for (let x = 0; x < COLS; x++) {
const hash = (x * 17 + y * 31 + x * y * 3) % 4;
const tile = voxel(
scene,
worldX(x),
-0.065,
worldZ(y),
0.93,
0.13,
0.93,
materials.water[hash],
false
);
tile.receiveShadow = true;
waterTiles.push(tile);
}
}
// Subtle checker-like navigation lanes.
const laneMaterial = new THREE.MeshBasicMaterial({
color: 0x8adbe0,
transparent: true,
opacity: 0.035,
depthWrite: false
});
for (let y = 1; y < ROWS; y++) {
voxel(
scene,
0,
0.012,
worldZ(y) - 0.5,
COLS - 0.4,
0.012,
0.025,
laneMaterial,
false
);
}
for (let x = 1; x < COLS; x++) {
voxel(
scene,
worldX(x) - 0.5,
0.012,
0,
0.025,
0.012,
ROWS - 0.4,
laneMaterial,
false
);
}
// Reefs.
for (const key of OBSTACLES) {
const [x, y] = key.split(",").map(Number);
const group = new THREE.Group();
group.position.set(worldX(x), 0, worldZ(y));
voxel(group, 0, 0.2, 0, 0.86, 0.4, 0.86, materials.reefBase);
voxel(group, 0.1, 0.52, -0.08, 0.58, 0.34, 0.58, materials.reefMid);
voxel(group, -0.06, 0.82, 0.03, 0.32, 0.28, 0.32, materials.reefTop);
scene.add(group);
}
// Start marker.
const startGroup = new THREE.Group();
startGroup.position.set(worldX(START.x), 0, worldZ(START.y));
voxel(startGroup, 0, 0.06, 0, 0.88, 0.12, 0.88, materials.green);
voxel(startGroup, -0.3, 0.28, 0, 0.12, 0.45, 0.12, materials.dark);
voxel(startGroup, -0.13, 0.42, 0, 0.38, 0.16, 0.1, materials.green);
scene.add(startGroup);
// Goal harbor marker.
const goalGroup = new THREE.Group();
goalGroup.position.set(worldX(GOAL.x), 0, worldZ(GOAL.y));
voxel(goalGroup, 0, 0.08, 0, 1.02, 0.16, 1.02, materials.cream);
voxel(goalGroup, 0.18, 0.42, 0.12, 0.42, 0.6, 0.42, materials.cream);
voxel(goalGroup, 0.18, 0.84, 0.12, 0.58, 0.22, 0.58, materials.hullTrim);
voxel(goalGroup, 0.18, 1.12, 0.12, 0.34, 0.34, 0.34, materials.cream);
voxel(goalGroup, 0.18, 1.35, 0.12, 0.42, 0.1, 0.42, materials.orangeBright);
voxel(goalGroup, -0.35, 0.3, 0, 0.09, 0.45, 0.09, materials.dark);
voxel(goalGroup, -0.18, 0.45, 0, 0.36, 0.14, 0.09, materials.orangeBright);
scene.add(goalGroup);
// Shift buoy and pulsing square ring.
const shiftGroup = new THREE.Group();
shiftGroup.position.set(worldX(SHIFT.x), 0, worldZ(SHIFT.y));
voxel(shiftGroup, 0, 0.06, 0, 0.9, 0.12, 0.9, materials.orange);
voxel(shiftGroup, 0, 0.46, 0, 0.18, 0.72, 0.18, materials.orangeBright);
voxel(shiftGroup, 0, 0.86, 0, 0.62, 0.18, 0.16, materials.orangeBright);
const beaconLight = new THREE.PointLight(0xffa94f, 1.8, 5);
beaconLight.position.set(0, 1.15, 0);
shiftGroup.add(beaconLight);
const pulseRing = new THREE.Group();
const pulseMaterial = new THREE.MeshBasicMaterial({
color: 0xffbd66,
transparent: true,
opacity: 0.58,
depthWrite: false
});
voxel(pulseRing, 0, 0.025, 0.47, 0.72, 0.025, 0.08, pulseMaterial, false);
voxel(pulseRing, 0, 0.025, -0.47, 0.72, 0.025, 0.08, pulseMaterial, false);
voxel(pulseRing, 0.47, 0.025, 0, 0.08, 0.025, 0.72, pulseMaterial, false);
voxel(pulseRing, -0.47, 0.025, 0, 0.08, 0.025, 0.72, pulseMaterial, false);
shiftGroup.add(pulseRing);
scene.add(shiftGroup);
// -------------------------------------------------------------------------
// Voxel wind arrows
// -------------------------------------------------------------------------
function makeArrow(scale = 1) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color: 0x8ce8ee,
emissive: 0x277f91,
emissiveIntensity: 0.65,
transparent: true,
opacity: 0.78,
roughness: 0.6
});
voxel(group, 0.38, 0, 0, 0.82, 0.07, 0.07, material, false);
voxel(group, 0.86, 0, 0, 0.24, 0.09, 0.48, material, false);
voxel(group, 1.03, 0, 0, 0.2, 0.09, 0.2, material, false);
group.scale.setScalar(scale);
return group;
}
const windArrows = [];
const windArrowLocations = [
[-4.0, 1.8, 0.74],
[-2.7, -1.8, 0.63],
[1.3, 1.9, 0.69],
[3.0, -1.5, 0.8],
[4.5, 1.2, 0.6]
];
for (const [x, z, scale] of windArrowLocations) {
const arrow = makeArrow(scale);
arrow.position.set(x, 0.18, z);
scene.add(arrow);
windArrows.push(arrow);
}
// -------------------------------------------------------------------------
// Boat
// -------------------------------------------------------------------------
const boat = new THREE.Group();
boat.position.set(worldX(START.x), 0.3, worldZ(START.y));
voxel(boat, 0, 0.02, 0.03, 0.66, 0.2, 0.74, materials.hull);
voxel(boat, 0, 0.13, -0.45, 0.48, 0.16, 0.32, materials.hull);
voxel(boat, 0, 0.13, 0.47, 0.52, 0.16, 0.22, materials.hull);
voxel(boat, 0, 0.18, -0.08, 0.7, 0.08, 0.68, materials.hullTrim);
voxel(boat, 0, 0.76, 0.15, 0.075, 1.22, 0.075, materials.dark);
voxel(boat, 0.22, 0.73, 0.15, 0.48, 0.52, 0.07, materials.cream);
voxel(boat, 0.3, 1.02, 0.15, 0.32, 0.25, 0.07, materials.cream);
voxel(boat, 0.34, 0.8, 0.11, 0.12, 0.13, 0.08, materials.hullTrim);
voxel(boat, 0, 1.42, 0.15, 0.45, 0.09, 0.07, materials.orangeBright);
scene.add(boat);
// -------------------------------------------------------------------------
// Route visuals
// -------------------------------------------------------------------------
const plannedGroup = new THREE.Group();
const revisedGroup = new THREE.Group();
scene.add(plannedGroup, revisedGroup);
function drawRoute(group, route, material, planned = false) {
for (let index = 1; index < route.length; index++) {
const point = route[index];
voxel(
group,
worldX(point.x),
0.105,
worldZ(point.y),
planned ? 0.48 : 0.42,
0.065,
planned ? 0.48 : 0.42,
material,
false
);
}
if (planned) {
const points = route.map((point) =>
new THREE.Vector3(worldX(point.x), 0.17, worldZ(point.y))
);
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const lineMaterial = new THREE.LineDashedMaterial({
color: 0xff6d9e,
dashSize: 0.24,
gapSize: 0.15,
transparent: true,
opacity: 0.82
});
const line = new THREE.Line(geometry, lineMaterial);
line.computeLineDistances();
group.add(line);
}
}
drawRoute(plannedGroup, plannedRoute, materials.pink, true);
drawRoute(revisedGroup, revisedRoute ?? [], materials.cyan, false);
// Planned route stop marker.
const noGoMarker = new THREE.Group();
noGoMarker.position.set(worldX(START.x), 0.2, worldZ(START.y - 1));
const noGoMaterial = new THREE.MeshBasicMaterial({
color: 0xff6d9e,
transparent: true,
opacity: 0.9
});
voxel(noGoMarker, -0.16, 0, 0, 0.08, 0.08, 0.55, noGoMaterial, false);
voxel(noGoMarker, 0.16, 0, 0, 0.08, 0.08, 0.55, noGoMaterial, false);
voxel(noGoMarker, 0, 0, -0.16, 0.55, 0.08, 0.08, noGoMaterial, false);
voxel(noGoMarker, 0, 0, 0.16, 0.55, 0.08, 0.08, noGoMaterial, false);
plannedGroup.add(noGoMarker);
// Direction preview.
const previewArrow = makeArrow(1.08);
scene.add(previewArrow);
function setArrowColor(group, color, emissive) {
group.traverse((object) => {
if (object.isMesh && object.material?.color) {
object.material.color.set(color);
object.material.emissive?.set(emissive);
object.material.opacity = 0.88;
}
});
}
// -------------------------------------------------------------------------
// World-space labels
// -------------------------------------------------------------------------
const labelElements = [];
function addWorldLabel(text, className, position) {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.textContent = text;
document.getElementById("labels").appendChild(element);
labelElements.push({ element, position });
}
addWorldLabel(
"Start",
"start",
new THREE.Vector3(worldX(START.x), 0.9, worldZ(START.y))
);
addWorldLabel(
"Shift buoy · B6",
"shift",
new THREE.Vector3(worldX(SHIFT.x), 1.55, worldZ(SHIFT.y))
);
addWorldLabel(
"Goal harbor",
"goal",
new THREE.Vector3(worldX(GOAL.x), 1.65, worldZ(GOAL.y))
);
addWorldLabel(
"No-go",
"warning",
new THREE.Vector3(worldX(START.x), 0.55, worldZ(START.y - 1))
);
const projected = new THREE.Vector3();
function updateLabels() {
for (const label of labelElements) {
projected.copy(label.position).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
label.element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
}
}
// -------------------------------------------------------------------------
// Heading probe
// -------------------------------------------------------------------------
let probePoint = "start";
let selectedHeading = directionByName.NW;
const probeButtons = [...document.querySelectorAll("[data-probe]")];
const headingButtons = [...document.querySelectorAll("[data-dir]")];
const headingStatus = document.getElementById("headingStatus");
const headingTitle = document.getElementById("headingTitle");
const headingReason = document.getElementById("headingReason");
function probeCoordinates() {
return probePoint === "start" ? START : SHIFT;
}
function probeWind() {
if (probePoint === "shift") return SHIFT_WIND_FROM;
return simulationShifted ? SHIFT_WIND_FROM : INITIAL_WIND_FROM;
}
function headingAssessment(direction) {
const point = probeCoordinates();
const wind = probeWind();
const windAllowed = headingIsAllowed(direction, wind);
const nx = point.x + direction.dx;
const ny = point.y + direction.dz;
const edge = !inBounds(nx, ny);
const reef = inBounds(nx, ny) && isObstacle(nx, ny);
if (!windAllowed) {
return {
allowed: false,
reason: "Outside the legal downwind arc."
};
}
if (reef) {
return {
allowed: false,
reason: "Destination tile contains a reef."
};
}
if (edge) {
return {
allowed: false,
reason: "Destination is beyond the map edge."
};
}
return {
allowed: true,
reason: "Clear water and a legal downwind heading."
};
}
function updateHeadingProbe() {
for (const button of probeButtons) {
button.classList.toggle("active", button.dataset.probe === probePoint);
}
for (const button of headingButtons) {
const direction = directionByName[button.dataset.dir];
const assessment = headingAssessment(direction);
button.classList.toggle("allowed", assessment.allowed);
button.classList.toggle("blocked", !assessment.allowed);
button.classList.toggle(
"selected",
direction.name === selectedHeading.name
);
button.title = assessment.reason;
}
const assessment = headingAssessment(selectedHeading);
headingStatus.classList.toggle("good", assessment.allowed);
headingStatus.classList.toggle("bad", !assessment.allowed);
headingTitle.textContent = assessment.allowed
? `${selectedHeading.name} · OPEN`
: `${selectedHeading.name} · NO-GO`;
headingReason.textContent = assessment.reason;
const point = probeCoordinates();
previewArrow.position.set(worldX(point.x), 0.3, worldZ(point.y));
previewArrow.rotation.y =
THREE.MathUtils.degToRad(90 - selectedHeading.angle);
setArrowColor(
previewArrow,
assessment.allowed ? 0x54e0d0 : 0xff6d9e,
assessment.allowed ? 0x126a65 : 0x741637
);
}
for (const button of probeButtons) {
button.addEventListener("click", () => {
probePoint = button.dataset.probe;
updateHeadingProbe();
});
}
for (const button of headingButtons) {
button.addEventListener("click", () => {
selectedHeading = directionByName[button.dataset.dir];
updateHeadingProbe();
});
}
// -------------------------------------------------------------------------
// Simulation and UI state
// -------------------------------------------------------------------------
let simulationShifted = false;
let windTargetRotation = 0;
let windCurrentRotation = 0;
let animationFrame = null;
let toastTimer = null;
const windDot = document.getElementById("windDot");
const windValue = document.getElementById("windValue");
const phaseValue = document.getElementById("phaseValue");
const shiftCard = document.getElementById("shiftCard");
const shiftNote = document.getElementById("shiftNote");
function showToast(message, tone = "") {
const toast = document.getElementById("toast");
toast.textContent = message;
toast.className = `show ${tone}`;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.className = "";
}, 2700);
}
function updateSimulationUI() {
if (simulationShifted) {
windDot.classList.add("shifted");
windValue.textContent = "FROM S · 180°";
phaseValue.textContent = "Post-shift";
shiftCard.classList.add("triggered");
shiftNote.textContent =
"Shift consumed. The revised route now uses wind from south.";
} else {
windDot.classList.remove("shifted");
windValue.textContent = "FROM W · 270°";
phaseValue.textContent = "Pre-shift";
shiftCard.classList.remove("triggered");
shiftNote.textContent =
"Contact with the orange buoy triggers the shift exactly once.";
}
}
function triggerShift() {
if (simulationShifted) return;
simulationShifted = true;
windTargetRotation = Math.PI / 2;
updateSimulationUI();
updateHeadingProbe();
showToast("Buoy B6 reached — wind shifted from W to S.", "good");
}
function stopAnimation() {
if (animationFrame !== null) {
cancelAnimationFrame(animationFrame);
animationFrame = null;
}
}
function resetSimulation() {
stopAnimation();
simulationShifted = false;
windTargetRotation = 0;
windCurrentRotation = 0;
boat.position.set(worldX(START.x), 0.3, worldZ(START.y));
boat.rotation.y = 0;
updateSimulationUI();
updateHeadingProbe();
}
document.getElementById("resetRoute").addEventListener("click", () => {
resetSimulation();
showToast("Sail reset. Wind is from west.");
});
document.getElementById("testPlan").addEventListener("click", () => {
resetSimulation();
noGoMarker.scale.setScalar(1.5);
showToast(
plannedValidation.reason || "The planned route is unreachable.",
"bad"
);
});
document.getElementById("sailRevised").addEventListener("click", () => {
if (!revisedRoute) {
showToast("No revised route could be found.", "bad");
return;
}
resetSimulation();
plannedGroup.visible =
document.getElementById("plannedToggle").checked;
revisedGroup.visible = true;
const points = revisedRoute.map((point) => ({
x: worldX(point.x),
z: worldZ(point.y)
}));
let segment = 0;
let progress = 0;
let lastTime = performance.now();
function animate(now) {
const dt = Math.min((now - lastTime) / 1000, 0.05);
lastTime = now;
progress += dt / 0.62;
while (progress >= 1 && segment < revisedRoute.length - 1) {
const arrived = revisedRoute[segment + 1];
if (arrived.shifted && !simulationShifted) {
triggerShift();
}
segment++;
progress -= 1;
}
if (segment >= revisedRoute.length - 1) {
boat.position.set(
worldX(GOAL.x),
0.3,
worldZ(GOAL.y)
);
showToast("Goal reached — the revised route is valid.", "good");
animationFrame = null;
return;
}
const from = points[segment];
const to = points[segment + 1];
const eased = progress * progress * (3 - 2 * progress);
const x = THREE.MathUtils.lerp(from.x, to.x, eased);
const z = THREE.MathUtils.lerp(from.z, to.z, eased);
boat.position.x = x;
boat.position.z = z;
const dx = to.x - from.x;
const dz = to.z - from.z;
const desiredRotation = Math.atan2(-dx, -dz);
const rotationDelta = Math.atan2(
Math.sin(desiredRotation - boat.rotation.y),
Math.cos(desiredRotation - boat.rotation.y)
);
boat.rotation.y += rotationDelta * Math.min(1, dt * 12);
boat.position.y = 0.3 + Math.sin(now * 0.006) * 0.025;
animationFrame = requestAnimationFrame(animate);
}
animationFrame = requestAnimationFrame(animate);
});
document.getElementById("plannedToggle").addEventListener("change", (event) => {
plannedGroup.visible = event.target.checked;
});
document.getElementById("revisedToggle").addEventListener("change", (event) => {
revisedGroup.visible = event.target.checked;
});
// -------------------------------------------------------------------------
// Ambient animation
// -------------------------------------------------------------------------
const foam = [];
const foamMaterial = new THREE.MeshBasicMaterial({
color: 0x78cdd3,
transparent: true,
opacity: 0.12,
depthWrite: false
});
for (let index = 0; index < 28; index++) {
const mesh = new THREE.Mesh(unitBox, foamMaterial);
const x = worldX((index * 5 + 3) % COLS);
const z = worldZ((index * 3 + 2) % ROWS);
mesh.position.set(x, 0.025, z);
mesh.scale.set(0.18 + (index % 3) * 0.08, 0.015, 0.07);
scene.add(mesh);
foam.push({
mesh,
phase: index * 0.73,
baseX: x,
baseZ: z
});
}
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
windCurrentRotation = THREE.MathUtils.lerp(
windCurrentRotation,
windTargetRotation,
0.075
);
for (const arrow of windArrows) {
arrow.rotation.y = windCurrentRotation;
arrow.position.y = 0.18 + Math.sin(elapsed * 1.5 + arrow.position.x) * 0.025;
}
const pulse = 1 + Math.sin(elapsed * 3.2) * 0.1;
pulseRing.scale.set(pulse, 1, pulse);
pulseMaterial.opacity = simulationShifted
? 0.18
: 0.48 + Math.sin(elapsed * 3.2) * 0.12;
beaconLight.intensity = simulationShifted
? 0.65
: 1.5 + Math.sin(elapsed * 4) * 0.55;
for (const item of foam) {
item.mesh.position.x =
item.baseX + Math.sin(elapsed * 0.35 + item.phase) * 0.16;
item.mesh.position.z =
item.baseZ + Math.cos(elapsed * 0.29 + item.phase) * 0.12;
}
noGoMarker.scale.lerp(
new THREE.Vector3(1, 1, 1),
0.08
);
updateLabels();
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
updateSimulationUI();
updateHeadingProbe();
animate();
</script>
</body>
</html>
```