3D engine that AI agents drive
Add interactive full-screen nature viewer and landscape controls
Nguyen Xuan Andf58924e10a1
diff --git a/nature.html b/nature.htmlnew file mode 100644index 00000000..c8e8a239--- /dev/null+++ b/nature.html@@ -0,0 +1,50 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="theme-color" content="#17231f" />+ <meta name="description" content="Explore a living alpine valley, built entirely from geometry in 67.js." />+ <title>67.js · Silverwater valley</title>+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='15' fill='%2317231f'/%3E%3Ctext x='7' y='45' font-family='sans-serif' font-weight='bold' font-size='38' fill='%23c9e4cc'%3E67%3C/text%3E%3C/svg%3E" />+ </head>+ <body>+ <main>+ <canvas id="viewport" tabindex="0" aria-label="Silverwater valley. Drag or use arrow keys to orbit; scroll or use plus and minus to zoom. Click the water to make a ripple."></canvas>+ <header class="world-header">+ <a class="brand" href="./index.html" aria-label="67.js home">67<span>.js</span></a>+ <nav aria-label="Scenes">+ <a href="./index.html">Object</a>+ <a href="./nature.html" aria-current="page">Nature</a>+ <a href="./film.html">Film</a>+ </nav>+ <button id="save-image">Save PNG <span aria-hidden="true">↗</span></button>+ </header>+ <div class="landscape-title">+ <h1>Silverwater valley</h1>+ <p>Take a breath. Stay a while.</p>+ </div>+ <section class="landscape-controls" aria-label="Landscape controls">+ <label class="view-control" for="viewpoint">View+ <select id="viewpoint"></select>+ </label>+ <label class="range-control" for="daylight"><span>Light <output id="daylight-value">Day</output></span>+ <input id="daylight" type="range" min="0" max="1" step="0.01" value="1" aria-label="Daylight, from dusk to day" />+ </label>+ <label class="range-control" for="wind"><span>Wind <output id="wind-value">Gentle</output></span>+ <input id="wind" type="range" min="0" max="1" step="0.01" value="0.35" />+ </label>+ <label for="detail">Detail+ <select id="detail"><option value="low">Low</option><option value="balanced" selected>Balanced</option><option value="high">High</option></select>+ </label>+ <button id="motion" aria-pressed="false">Pause motion</button>+ </section>+ <footer>+ <p class="hint">Drag to explore · Click the water</p>+ <div class="metrics" aria-label="Renderer statistics"><span id="geometry-stat"></span><span id="memory-stat"></span></div>+ </footer>+ <p id="notice" role="status" hidden></p>+ </main>+ <script type="module" src="/src/nature-viewer.js"></script>+ </body>+</html>diff --git a/src/nature-style.css b/src/nature-style.cssnew file mode 100644index 00000000..2326149e--- /dev/null+++ b/src/nature-style.css@@ -0,0 +1,79 @@+:root { font-family: system-ui, sans-serif; color: #f5f7f2; background: #17231f; color-scheme: dark; font-synthesis: none; }+* { box-sizing: border-box; }+body { margin: 0; }+main { height: 100dvh; min-height: 540px; position: relative; overflow: hidden; }+button, select, input { font: inherit; }+button, a, label, .metrics, .hint { -webkit-user-select: none; user-select: none; }+button, select { color: inherit; border: 0; cursor: pointer; }+button { padding: 11px 16px; border-radius: 8px; background: #f5f7f21a; white-space: nowrap; }+button:hover { background: #f5f7f22b; }+button:disabled { cursor: wait; opacity: .55; }+a { color: inherit; text-decoration: none; }+:focus-visible { outline: 2px solid #deefb5; outline-offset: 4px; }+#viewport { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; }+#viewport:focus-visible { outline-offset: -5px; }+.world-header { position: absolute; top: 22px; left: 28px; right: 28px; display: flex; align-items: center; gap: 32px; text-shadow: 0 1px 14px #13201c66; }+.brand { font-size: 26px; font-weight: 700; letter-spacing: -1px; }+.brand span { font-weight: 400; opacity: .8; }+nav { display: flex; gap: 5px; }+nav a { font-size: 14px; padding: 9px 13px; border-radius: 6px; }+nav a[aria-current] { background: #16211f7a; }+nav a:hover { background: #16211f55; }+#save-image { margin-left: auto; background: #16211fbb; font-size: 14px; }+#save-image:hover { background: #16211fe6; }+.landscape-title { position: absolute; left: 32px; bottom: 156px; text-shadow: 0 2px 20px #11201988; pointer-events: none; }+h1 { margin: 0 0 6px; font-size: clamp(26px, 3vw, 42px); font-weight: 500; letter-spacing: -1.3px; }+.landscape-title p { margin: 0; font-size: 15px; color: #f5f7f2dd; }+.landscape-controls { position: absolute; bottom: 52px; left: 28px; right: 28px; display: flex; align-items: center; gap: 28px; padding: 18px 22px; background: #17231feb; border-radius: 12px; backdrop-filter: blur(18px); }+.landscape-controls label { display: flex; align-items: center; gap: 12px; font-size: 14px; color: #d5dfd6; }+select { padding: 9px 28px 9px 11px; border-radius: 6px; background: #f5f7f20d; font-size: 14px; }+option { background: #22352b; }+.landscape-controls .range-control { display: block; width: 150px; }+.range-control span { display: flex; justify-content: space-between; margin-bottom: 5px; }+output { color: #a8baa9; font-size: 12px; }+input[type='range'] { display: block; width: 100%; height: 17px; margin: 0; accent-color: #c5dcaa; cursor: pointer; }+#motion { margin-left: auto; font-size: 14px; }+footer { position: absolute; left: 32px; right: 32px; bottom: 15px; display: flex; justify-content: space-between; gap: 18px; font-size: 12px; color: #f5f7f2d9; text-shadow: 0 1px 8px #10201c; }+footer p { margin: 0; }+.metrics { display: flex; gap: 20px; font-variant-numeric: tabular-nums; }+#notice { position: absolute; right: 28px; bottom: 224px; max-width: min(380px, calc(100% - 56px)); padding: 15px 20px; margin: 0; border-radius: 9px; color: #17231f; background: #f5f7f2; font-size: 14px; box-shadow: 0 8px 24px #0b1c1b33; }+#notice[data-failure='true'] { color: #914222; }+[hidden] { display: none !important; }+@media (max-width: 1050px) {+ .landscape-controls { gap: 15px; }+ .landscape-controls .range-control { width: 110px; }+ .landscape-controls label { gap: 7px; }+}+@media (max-width: 760px) {+ .world-header { top: 16px; left: 18px; right: 18px; gap: 14px; }+ .brand { font-size: 23px; }+ nav a { font-size: 13px; padding: 8px 9px; }+ #save-image { padding: 9px 10px; font-size: 12px; }+ .landscape-title { left: 22px; bottom: 252px; }+ .landscape-controls { left: 16px; right: 16px; bottom: 54px; padding: 16px; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px 20px; }+ .landscape-controls .range-control { width: 100%; }+ .view-control { grid-column: 1 / -1; }+ .view-control select { flex: 1; }+ .landscape-controls select { min-width: 0; max-width: 100%; }+ .landscape-controls label { justify-content: space-between; }+ #motion { width: 100%; padding: 10px; }+ footer { left: 20px; right: 20px; bottom: 13px; font-size: 11px; }+ .hint { display: none; }+ .metrics { width: 100%; justify-content: space-between; gap: 10px; }+ #notice { bottom: 330px; right: 16px; max-width: calc(100% - 32px); }+}+@media (max-width: 360px) {+ .world-header { gap: 8px; }+ nav { gap: 0; }+ nav a { font-size: 12px; padding: 8px 7px; }+ #save-image { font-size: 11px; padding: 9px 8px; }+ .landscape-controls label[for='detail'] { display: block; }+ #detail { width: 100%; margin-top: 5px; font-size: 13px; }+ #motion { align-self: end; font-size: 13px; }+ .landscape-title { bottom: 280px; }+}+@media (max-height: 650px) and (min-width: 761px) {+ main { min-height: 400px; }+ .landscape-title { bottom: 138px; }+}+@media (prefers-reduced-motion: reduce) { * { scroll-behavior: auto; } }diff --git a/src/nature-viewer.js b/src/nature-viewer.jsnew file mode 100644index 00000000..58e4558c--- /dev/null+++ b/src/nature-viewer.js@@ -0,0 +1,313 @@+import './nature-style.css';+import { vec4 } from 'gl-matrix';+import { Renderer67 } from './renderer.js';+import { createNatureWorld } from './nature.js';++const canvas = document.querySelector('#viewport');+const motionButton = document.querySelector('#motion');+const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)');+const state = {+ detail: 'balanced', daylight: 1, wind: 0.35, paused: reducedMotion.matches,+ time: 0, azimuth: 0, elevation: 0, distance: 1, target: [0, 0, 0],+ waterRipple: [10000, 0, 10000], rippleTime: -1000,+};+let world = createNatureWorld();+let renderer;+let scheduledFrame = 0;+let lastFrameTime = 0;+let dragging;+let noticeTimer;++function notify(message, failure = false) {+ const notice = document.querySelector('#notice');+ notice.textContent = `${failure ? '⚠' : '✓'} ${message}`;+ notice.dataset.failure = String(failure);+ notice.hidden = false;+ clearTimeout(noticeTimer);+ if (!failure) noticeTimer = setTimeout(() => { notice.hidden = true; }, 4000);+}++function setViewpoint(index) {+ const viewpoint = world.points[index];+ state.target = [...viewpoint.target];+ const offset = viewpoint.eye.map((value, axis) => value - viewpoint.target[axis]);+ state.distance = Math.hypot(...offset);+ state.azimuth = Math.atan2(offset[0], offset[2]);+ state.elevation = Math.asin(offset[1] / state.distance);+ document.querySelector('#viewpoint').value = String(index);+}++function camera() {+ return {+ target: state.target,+ eye: [+ state.target[0] + Math.sin(state.azimuth) * Math.cos(state.elevation) * state.distance,+ state.target[1] + Math.sin(state.elevation) * state.distance,+ state.target[2] + Math.cos(state.azimuth) * Math.cos(state.elevation) * state.distance,+ ],+ };+}++function environment() {+ const daylight = state.daylight;+ const blend = (dusk, day) => day.map((value, axis) => dusk[axis] + (value - dusk[axis]) * daylight);+ return {+ daylight: 0.25 + daylight * 0.75,+ fogColor: blend([0.23, 0.17, 0.25], world.environment.fogColor),+ skyTop: blend([0.16, 0.13, 0.3], world.environment.skyTop),+ skyBottom: blend([0.84, 0.48, 0.36], world.environment.skyBottom),+ lightDirection: blend([-0.8, 0.13, 0.5], world.environment.lightDirection),+ fogDensity: world.environment.fogDensity * (1.25 - daylight * 0.25),+ };+}++function renderFrame() {+ renderer?.render({ ...camera(), time: state.time, wind: state.wind, waterRipple: state.waterRipple, rippleTime: state.rippleTime, environment: environment() });+}++function stopAnimation() {+ cancelAnimationFrame(scheduledFrame);+ scheduledFrame = 0;+ lastFrameTime = 0;+}++function draw(timestamp) {+ scheduledFrame = 0;+ if (!renderer || document.hidden) return;+ if (!state.paused && lastFrameTime) state.time += Math.min((timestamp - lastFrameTime) / 1000, 0.1);+ lastFrameTime = timestamp;+ renderFrame();+ if (!state.paused) invalidate();+}++function invalidate() {+ if (!scheduledFrame && renderer && !document.hidden) scheduledFrame = requestAnimationFrame(draw);+}++function updateMotionButton() {+ motionButton.textContent = state.paused ? 'Resume motion' : 'Pause motion';+ motionButton.setAttribute('aria-pressed', String(state.paused));+}++function updateStatistics() {+ document.querySelector('#geometry-stat').textContent = `${Math.round(renderer.triangles / 1000)}k triangles · ${renderer.batches.length} draws`;+ document.querySelector('#memory-stat').textContent = `${Math.round(renderer.memoryPlan.estimatedBytes / 1048576)} MB estimated`;+}++function initializeRenderer() {+ renderer = new Renderer67(canvas, world.parts, {+ world: true, ground: false, environment: world.environment,+ pixelRatio: 1.25, memoryBudgetMiB: 256, samples: 4,+ });+ updateStatistics();+ renderFrame();+ invalidate();+}++function renderAt(time) {+ if (!Number.isFinite(time)) throw new TypeError('Render time must be finite.');+ stopAnimation();+ state.paused = true;+ state.time = time;+ updateMotionButton();+ renderFrame();+}++function waterHit(clientX, clientY) {+ if (!renderer) return null;+ const rectangle = canvas.getBoundingClientRect();+ const horizontal = (clientX - rectangle.left) / rectangle.width * 2 - 1;+ const vertical = 1 - (clientY - rectangle.top) / rectangle.height * 2;+ const near = vec4.transformMat4(vec4.create(), [horizontal, vertical, -1, 1], renderer.inverseViewProjection);+ const far = vec4.transformMat4(vec4.create(), [horizontal, vertical, 1, 1], renderer.inverseViewProjection);+ const origin = Array.from(near.subarray(0, 3)).map(value => value / near[3]);+ const end = Array.from(far.subarray(0, 3)).map(value => value / far[3]);+ const direction = end.map((value, axis) => value - origin[axis]);+ if (Math.abs(direction[1]) < 1e-6) return null;+ const distance = (0.22 - origin[1]) / direction[1];+ if (distance < 0 || distance > 1) return null;+ const position = origin.map((value, axis) => value + direction[axis] * distance);+ const water = world.parts.find(part => part.material.tag === 'water').geometry.positions;+ const firstDepth = water[2];+ const lastDepth = water[water.length - 1];+ if (position[2] < firstDepth || position[2] >= lastDepth) return null;+ const along = (position[2] - firstDepth) / (lastDepth - firstDepth) * (water.length / 6 - 1);+ const row = Math.floor(along);+ const fraction = along - row;+ const left = water[row * 6] + (water[(row + 1) * 6] - water[row * 6]) * fraction;+ const right = water[row * 6 + 3] + (water[(row + 1) * 6 + 3] - water[row * 6 + 3]) * fraction;+ return position[0] >= left && position[0] <= right ? position : null;+}++world.points.forEach((viewpoint, index) => {+ const option = document.createElement('option');+ option.value = String(index);+ option.textContent = viewpoint.name;+ document.querySelector('#viewpoint').append(option);+});+setViewpoint(0);+updateMotionButton();+try { initializeRenderer(); } catch (error) { notify(error.message, true); }++window.__nature = { get world() { return world; }, get renderer() { return renderer; }, state, camera, environment, renderAt, waterHit };++document.querySelector('#viewpoint').addEventListener('change', event => {+ setViewpoint(Number(event.target.value));+ invalidate();+});+document.querySelector('#daylight').addEventListener('input', event => {+ state.daylight = Number(event.target.value);+ document.querySelector('#daylight-value').textContent = state.daylight > 0.7 ? 'Day' : state.daylight > 0.3 ? 'Golden' : 'Dusk';+ invalidate();+});+document.querySelector('#wind').addEventListener('input', event => {+ state.wind = Number(event.target.value);+ document.querySelector('#wind-value').textContent = state.wind < 0.1 ? 'Still' : state.wind < 0.55 ? 'Gentle' : 'Breezy';+ invalidate();+});+motionButton.addEventListener('click', () => {+ state.paused = !state.paused;+ lastFrameTime = 0;+ updateMotionButton();+ invalidate();+});+document.querySelector('#detail').addEventListener('change', event => {+ stopAnimation();+ const previousDetail = state.detail;+ const previousWorld = world;+ try {+ const nextWorld = createNatureWorld({ detail: event.target.value });+ renderer?.dispose();+ renderer = null;+ world = nextWorld;+ state.detail = event.target.value;+ initializeRenderer();+ } catch (error) {+ world = previousWorld;+ state.detail = previousDetail;+ event.target.value = previousDetail;+ if (!renderer) {+ try { initializeRenderer(); } catch { renderer = null; }+ }+ notify(`Scene could not load: ${error.message}`, true);+ }+});++canvas.addEventListener('pointerdown', event => {+ if (event.button !== 0) return;+ dragging = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, startX: event.clientX, startY: event.clientY, moved: false };+ canvas.setPointerCapture(event.pointerId);+});+canvas.addEventListener('pointermove', event => {+ if (!dragging || dragging.pointerId !== event.pointerId) return;+ if (Math.hypot(event.clientX - dragging.startX, event.clientY - dragging.startY) > 4) dragging.moved = true;+ state.azimuth -= (event.clientX - dragging.x) * 0.005;+ state.elevation = Math.max(0.03, Math.min(1.25, state.elevation + (event.clientY - dragging.y) * 0.004));+ dragging.x = event.clientX;+ dragging.y = event.clientY;+ invalidate();+});+canvas.addEventListener('pointerup', event => {+ if (dragging && !dragging.moved) {+ const position = waterHit(event.clientX, event.clientY);+ if (position) {+ state.waterRipple = position;+ state.rippleTime = state.time;+ invalidate();+ }+ }+ dragging = null;+});+for (const eventName of ['pointercancel', 'lostpointercapture']) canvas.addEventListener(eventName, () => { dragging = null; });+canvas.addEventListener('wheel', event => {+ event.preventDefault();+ state.distance = Math.max(6, Math.min(110, state.distance * Math.exp(event.deltaY * 0.001)));+ invalidate();+}, { passive: false });+canvas.addEventListener('keydown', event => {+ const actions = {+ ArrowLeft: () => { state.azimuth -= 0.08; },+ ArrowRight: () => { state.azimuth += 0.08; },+ ArrowUp: () => { state.elevation = Math.min(1.25, state.elevation + 0.05); },+ ArrowDown: () => { state.elevation = Math.max(0.03, state.elevation - 0.05); },+ '+': () => { state.distance = Math.max(6, state.distance * 0.9); },+ '=': () => { state.distance = Math.max(6, state.distance * 0.9); },+ '-': () => { state.distance = Math.min(110, state.distance * 1.1); },+ r: () => { setViewpoint(0); },+ ' ': () => { motionButton.click(); },+ };+ const action = actions[event.key];+ if (action) {+ event.preventDefault();+ action();+ invalidate();+ }+});++document.querySelector('#save-image').addEventListener('click', event => {+ const button = event.currentTarget;+ button.disabled = true;+ try {+ renderFrame();+ canvas.toBlob(blob => {+ button.disabled = false;+ if (!blob) return notify('Image capture failed.', true);+ const url = URL.createObjectURL(blob);+ const link = document.createElement('a');+ link.href = url;+ link.download = '67js-silverwater-valley.png';+ link.click();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+ notify('Landscape saved.');+ }, 'image/png');+ } catch (error) {+ button.disabled = false;+ notify(`Image capture failed: ${error.message}`, true);+ }+});++const resizeObserver = new ResizeObserver(() => {+ if (!renderer) return;+ renderer.resize();+ updateStatistics();+ invalidate();+});+resizeObserver.observe(canvas);+document.addEventListener('visibilitychange', () => {+ stopAnimation();+ if (!document.hidden) invalidate();+});+reducedMotion.addEventListener('change', event => {+ if (event.matches) {+ state.paused = true;+ updateMotionButton();+ invalidate();+ }+});+canvas.addEventListener('webglcontextlost', event => {+ event.preventDefault();+ stopAnimation();+ // Release while the context is lost; restored contexts reject stale GPU handles.+ renderer?.dispose();+ renderer = null;+ notify('Graphics paused. Waiting for the browser to restore them.', true);+});+canvas.addEventListener('webglcontextrestored', () => {+ try {+ initializeRenderer();+ notify('Graphics restored.');+ } catch (error) { notify(error.message, true); }+});+window.addEventListener('pagehide', () => {+ stopAnimation();+ resizeObserver.disconnect();+ renderer?.dispose();+ renderer = null;+});+window.addEventListener('pageshow', event => {+ if (!event.persisted) return;+ try {+ initializeRenderer();+ resizeObserver.observe(canvas);+ } catch (error) { notify(error.message, true); }+});