Prompt specification
Build or customize the Three.js 3D scene "One Location Rotates Through a Day" 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: One Location Rotates Through a Day
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/one-location-rotates-through-a-day-x3806
Scene Description Prompt:
Make a voxel globe rotate beneath fixed light while one marked location passes dawn, noon, dusk, and night. One HTML file, Three.js from cdnjs.
Working Three.js Starter (one-location-rotates-through-a-day-x3806):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>Voxel Globe — One Place Under a Fixed Sun</title>
<style>
:root{
--ink:#e9eefc; --dim:#93a1c4;
--panel:rgba(10,16,30,.55); --edge:rgba(140,175,225,.16);
--dawn:#ff9f43; --noon:#ffd166; --dusk:#ef5b6b; --night:#7f8bf0;
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#04060c}
body{
font:12.5px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
color:var(--ink);
background:
radial-gradient(1300px 760px at 74% 20%, rgba(40,66,120,.55), rgba(4,6,12,0) 62%),
radial-gradient(1000px 900px at 18% 88%, rgba(78,32,92,.32), rgba(4,6,12,0) 62%),
#04060c;
}
#c{position:fixed;inset:0;display:block;touch-action:none}
.panel{
position:fixed;background:var(--panel);border:1px solid var(--edge);border-radius:14px;
backdrop-filter:blur(14px) saturate(150%);-webkit-backdrop-filter:blur(14px) saturate(150%);
box-shadow:0 20px 60px rgba(0,0,0,.5);padding:14px 16px;user-select:none;
}
#title{top:16px;left:16px;max-width:290px}
#title h1{margin:0 0 4px;font-size:14px;letter-spacing:.16em;text-transform:uppercase}
#title p{margin:0;color:var(--dim);font-size:11.5px}
#phase{bottom:16px;left:16px;width:330px}
#controls{top:16px;right:16px;width:252px}
.row{display:flex;justify-content:space-between;align-items:baseline;gap:10px}
.k{color:var(--dim);letter-spacing:.08em;font-size:10.5px;text-transform:uppercase}
.v{font-variant-numeric:tabular-nums}
#badge{
font-size:30px;letter-spacing:.22em;font-weight:600;line-height:1;margin:2px 0 2px;
text-shadow:0 0 26px currentColor;transition:color .35s ease;
}
#sub{color:var(--dim);font-size:11px;margin-bottom:10px}
.bar{position:relative;height:9px;border-radius:6px;overflow:hidden;
background:linear-gradient(90deg,#26315c 0 25%,#ff9f43 25% 29%,#9ad7ff 29% 71%,#ef5b6b 71% 75%,#26315c 75% 100%);
border:1px solid rgba(255,255,255,.12)}
#dot{position:absolute;top:-3px;width:3px;height:15px;background:#fff;border-radius:2px;
box-shadow:0 0 10px #fff;transform:translateX(-1.5px)}
.scale{display:flex;justify-content:space-between;color:var(--dim);font-size:9.5px;margin-top:3px}
.chips{display:flex;gap:6px;margin-top:10px}
.chip{flex:1;text-align:center;padding:5px 0;border-radius:8px;font-size:10px;letter-spacing:.12em;
border:1px solid rgba(255,255,255,.1);color:var(--dim);cursor:pointer;background:rgba(255,255,255,.03);
transition:all .25s ease}
.chip:hover{border-color:rgba(255,255,255,.3);color:var(--ink)}
.chip[data-p="dawn"].on{color:#08101f;background:var(--dawn);border-color:var(--dawn)}
.chip[data-p="noon"].on{color:#08101f;background:var(--noon);border-color:var(--noon)}
.chip[data-p="dusk"].on{color:#fff;background:var(--dusk);border-color:var(--dusk)}
.chip[data-p="night"].on{color:#fff;background:var(--night);border-color:var(--night)}
.btn{display:block;width:100%;margin-top:7px;padding:8px 10px;border-radius:9px;cursor:pointer;
background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.14);color:var(--ink);
font:inherit;font-size:11.5px;letter-spacing:.1em;text-align:left;transition:.2s}
.btn:hover{background:rgba(255,255,255,.12)}
.btn b{float:right;color:var(--dim);font-weight:500}
input[type=range]{width:100%;accent-color:#9ad7ff;margin:6px 0 2px}
.lbl{font-size:10.5px;letter-spacing:.08em;text-transform:uppercase;color:var(--dim)}
#markerLabel{position:fixed;left:0;top:0;pointer-events:none;transform:translate(-9999px);
font-size:10.5px;letter-spacing:.1em;color:#ffd166;text-shadow:0 0 10px rgba(0,0,0,.9),0 0 3px #000;
white-space:nowrap;transition:opacity .2s}
#markerLabel i{display:inline-block;width:6px;height:6px;border-radius:50%;background:#ffd166;
box-shadow:0 0 10px #ffd166;margin-right:6px;vertical-align:middle}
#hint{bottom:16px;right:16px;color:var(--dim);font-size:10.5px;text-align:right;opacity:.75}
@media (max-width:760px){
#title{max-width:200px}#phase{width:calc(100% - 32px)}#controls{display:none}
}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="title" class="panel">
<h1>Voxel Globe</h1>
<p>One tracked place passes <b style="color:#ffd166">dawn → noon → dusk → night</b> while the sun stays fixed in the sky. Drag to orbit, scroll to zoom.</p>
</div>
<div id="phase" class="panel">
<div class="row"><span class="k">Local phase</span><span class="k" id="clock">--:--</span></div>
<div id="badge">—</div>
<div id="sub">tracking beacon</div>
<div class="bar"><div id="dot"></div></div>
<div class="scale"><span>00</span><span>06</span><span>12</span><span>18</span><span>24</span></div>
<div class="chips">
<div class="chip" data-p="dawn">DAWN</div>
<div class="chip" data-p="noon">NOON</div>
<div class="chip" data-p="dusk">DUSK</div>
<div class="chip" data-p="night">NIGHT</div>
</div>
</div>
<div id="controls" class="panel">
<button class="btn" id="play">Pause spin <b>SPACE</b></button>
<div class="lbl">Rotation speed</div>
<input type="range" id="speed" min="5" max="120" value="42">
<button class="btn" id="term">Terminator ring <b>ON</b></button>
<button class="btn" id="orbit">Auto-orbit camera <b>OFF</b></button>
<button class="btn" id="reset">Reset view <b>HOME</b></button>
</div>
<div id="hint">drag · orbit | wheel · zoom | space · pause</div>
<div id="markerLabel"><i></i>BEACON</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ──────────────────────────────────────────────────────────────
Renderer / scene
────────────────────────────────────────────────────────────── */
const canvas = document.getElementById('c');
const renderer = new THREE.WebGLRenderer({ canvas, antialias:true, alpha:true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.outputColorSpace = THREE.SRGBColorSpace;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(42, innerWidth/innerHeight, 0.1, 3000);
camera.position.set(12, 7, 26);
/* ──────────────────────────────────────────────────────────────
The FIXED light: sun direction never changes in world space.
The globe is tilted 23.4°, and the sun sits exactly in the
tilted equator plane → every latitude gets a clean day/night.
────────────────────────────────────────────────────────────── */
const TILT = THREE.MathUtils.degToRad(23.4);
const sunDir = new THREE.Vector3(Math.cos(TILT), Math.sin(TILT), 0).normalize();
const sunlight = new THREE.DirectionalLight(0xfff2dc, 3.1);
sunlight.position.copy(sunDir).multiplyScalar(120);
scene.add(sunlight, sunlight.target);
scene.add(new THREE.AmbientLight(0x1d2a4a, 0.55)); // faint fill so night isn't pure black
scene.add(new THREE.HemisphereLight(0x2b3f6b, 0x0a0e18, 0.35));
/* ──────────────────────────────────────────────────────────────
Voxel planet
────────────────────────────────────────────────────────────── */
const R = 9.5, V = 0.24;
/* --- tiny value-noise so the voxel continents look organic --- */
function hash3(x, y, z){
let n = Math.imul(x|0, 374761393) + Math.imul(y|0, 668265263) + Math.imul(z|0, 2147483647);
n = Math.imul(n ^ (n >>> 13), 1274126177);
n = n ^ (n >>> 16);
return (n >>> 0) / 4294967296;
}
const sm = t => t*t*(3-2*t);
function vnoise(x, y, z){
const xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z);
const xf = sm(x-xi), yf = sm(y-yi), zf = sm(z-zi);
const H = (a,b,c) => hash3(xi+a, yi+b, zi+c);
const x00 = H(0,0,0) + (H(1,0,0)-H(0,0,0))*xf;
const x10 = H(0,1,0) + (H(1,1,0)-H(0,1,0))*xf;
const x01 = H(0,0,1) + (H(1,0,1)-H(0,0,1))*xf;
const x11 = H(0,1,1) + (H(1,1,1)-H(0,1,1))*xf;
const y0 = x00 + (x10-x00)*yf, y1 = x01 + (x11-x01)*yf;
return y0 + (y1-y0)*zf;
}
function fbm(x, y, z, oct=4){
let a=0.5, f=1, s=0, n=0;
for(let i=0;i<oct;i++){ s += a*vnoise(x*f, y*f, z*f); n += a; a*=0.5; f*=2.07; }
return s/n;
}
const clamp01 = v => v < 0 ? 0 : v > 1 ? 1 : v;
const smoothstep = (a,b,x) => { const t = clamp01((x-a)/(b-a)); return t*t*(3-2*t); };
const C_OCEAN_DEEP = new THREE.Color(0x071d38);
const C_OCEAN_SHAL = new THREE.Color(0x12608c);
const C_LOW = new THREE.Color(0x3d7a41);
const C_SAVANNA = new THREE.Color(0x7c7b42);
const C_ROCK = new THREE.Color(0x8e8677);
const C_SNOW = new THREE.Color(0xf1f5f7);
const C_DESERT = new THREE.Color(0xc9a86a);
const C_ICE = new THREE.Color(0xe6f2fb);
function colorFor(u, f, m, d, rand){
const col = new THREE.Color();
if(f < 0.53){ // ocean
col.copy(C_OCEAN_DEEP).lerp(C_OCEAN_SHAL, clamp01((f-0.26)/0.27));
} else { // land
const e = (f-0.53)/0.30;
col.copy(C_LOW);
if(e > 0.22) col.lerp(C_SAVANNA, clamp01((e-0.22)/0.30));
if(e > 0.52) col.lerp(C_ROCK, clamp01((e-0.52)/0.26));
if(e > 0.80) col.lerp(C_SNOW, clamp01((e-0.80)/0.20));
const alat = Math.abs(u.y);
if(alat > 0.15 && alat < 0.47 && d > 0.55) col.lerp(C_DESERT, 0.85);
}
col.lerp(C_ICE, smoothstep(0.74, 0.90, Math.abs(u.y))); // polar caps
col.multiplyScalar(0.88 + 0.24*rand);
return col;
}
/* --- build the voxel shell --- */
const tilt = new THREE.Group(); tilt.rotation.z = TILT; scene.add(tilt);
const spin = new THREE.Group(); tilt.add(spin);
const N = Math.ceil(R / V);
const cells = [];
for(let i=-N;i<=N;i++) for(let j=-N;j<=N;j++) for(let k=-N;k<=N;k++){
const x=i*V, y=j*V, z=k*V, r=Math.hypot(x,y,z);
if(r <= R && r >= R - 1.9*V) cells.push([x,y,z,r]);
}
const geo = new THREE.BoxGeometry(V*0.93, V*0.93, V*0.93);
const mat = new THREE.MeshStandardMaterial({ roughness:0.95, metalness:0.0, flatShading:true });
const globe = new THREE.InstancedMesh(geo, mat, cells.length);
globe.frustumCulled = false;
const dummy = new THREE.Object3D();
const lightCells = []; // city-light positions
let bestLand = -1, bestAny = -1;
const targetDir = new THREE.Vector3(Math.cos(0.32)*Math.cos(0.42), Math.sin(0.32), Math.cos(0.32)*Math.sin(0.42)).normalize();
for(let i=0;i<cells.length;i++){
const [x,y,z,r] = cells[i];
const dir = new THREE.Vector3(x,y,z).normalize();
const f = fbm(dir.x*2.05+11.3, dir.y*2.05-4.7, dir.z*2.05+2.1, 4);
const m = fbm(dir.x*4.6-7.2, dir.y*4.6+9.4, dir.z*4.6-1.3, 3);
const d = fbm(dir.x*3.1+31.0, dir.y*3.1+5.5, dir.z*3.1-8.8, 3);
const rand = hash3(x*7, y*13, z*29);
const c = colorFor(dir, f, m, d, rand);
dummy.position.set(x,y,z); dummy.rotation.set(0,0,0); dummy.scale.set(1,1,1);
dummy.updateMatrix();
globe.setMatrixAt(i, dummy.matrix);
globe.setColorAt(i, c);
const dot = dir.dot(targetDir);
if(dot > bestAny){ bestAny = i; }
if(f >= 0.53 && dot > bestLand){ bestLand = i; }
if(f > 0.54 && Math.abs(dir.y) < 0.80 && rand > 0.90){
lightCells.push([x + dir.x*0.145, y + dir.y*0.145, z + dir.z*0.145, rand]);
}
}
globe.instanceMatrix.needsUpdate = true;
globe.instanceColor.needsUpdate = true;
spin.add(globe);
/* --- city lights: only visible on the night side (shader) --- */
if(lightCells.length){
const lgeo = new THREE.BoxGeometry(0.075,0.075,0.075);
const lmat = new THREE.MeshBasicMaterial({ color:0xffffff, transparent:true, depthWrite:false });
lmat.onBeforeCompile = sh => {
sh.uniforms.uSunDir = { value: sunDir };
sh.vertexShader = sh.vertexShader
.replace('#include <common>', '#include <common>\nuniform vec3 uSunDir;\nvarying float vNight;')
.replace('#include <begin_vertex>', `#include <begin_vertex>
#ifdef USE_INSTANCING
vec4 wPos = modelMatrix * instanceMatrix * vec4(transformed,1.0);
#else
vec4 wPos = modelMatrix * vec4(transformed,1.0);
#endif
vNight = smoothstep(0.16,-0.16, dot(normalize(wPos.xyz), uSunDir));`);
sh.fragmentShader = sh.fragmentShader
.replace('#include <common>', '#include <common>\nvarying float vNight;')
.replace('#include <color_fragment>', '#include <color_fragment>\n diffuseColor.a *= vNight;');
};
const lights = new THREE.InstancedMesh(lgeo, lmat, lightCells.length);
lights.frustumCulled = false;
for(let i=0;i<lightCells.length;i++){
const [x,y,z,r] = lightCells[i];
dummy.position.set(x,y,z); dummy.rotation.set(0,0,0); dummy.scale.set(1,1,1); dummy.updateMatrix();
lights.setMatrixAt(i, dummy.matrix);
const warm = new THREE.Color().setHSL(0.09 + 0.06*r, 0.85, 0.55 + 0.35*r);
lights.setColorAt(i, warm);
}
lights.instanceMatrix.needsUpdate = true;
lights.instanceColor.needsUpdate = true;
spin.add(lights);
}
/* ──────────────────────────────────────────────────────────────
Atmosphere shell (custom shader, additive rim glow)
────────────────────────────────────────────────────────────── */
const atmo = new THREE.Mesh(
new THREE.SphereGeometry(R*1.10, 64, 48),
new THREE.ShaderMaterial({
uniforms:{ uSunDir:{ value:sunDir } },
vertexShader:`varying vec3 vN; varying vec3 vP;
void main(){ vec4 w = modelMatrix*vec4(position,1.0); vP=w.xyz;
vN = normalize(mat3(modelMatrix)*normal);
gl_Position = projectionMatrix*viewMatrix*w; }`,
fragmentShader:`uniform vec3 uSunDir; varying vec3 vN; varying vec3 vP;
void main(){
vec3 N = normalize(vN);
vec3 V = normalize(cameraPosition - vP);
float rim = pow(1.0 - clamp(dot(N,V),0.0,1.0), 3.2);
float lit = smoothstep(-0.5, 0.4, dot(N, uSunDir));
vec3 col = mix(vec3(0.10,0.16,0.42), vec3(0.38,0.62,1.0), lit);
gl_FragColor = vec4(col, rim*(0.12+0.80*lit));
}`,
transparent:true, blending:THREE.AdditiveBlending,
depthWrite:false, side:THREE.FrontSide
})
);
scene.add(atmo);
/* ──────────────────────────────────────────────────────────────
Stars + the visible sun disc (fixed in world space)
────────────────────────────────────────────────────────────── */
{
const Ns = 2200, pos = new Float32Array(Ns*3), col = new Float32Array(Ns*3);
const bandAxis = new THREE.Vector3(0.32,0.86,-0.4).normalize();
for(let i=0;i<Ns;i++){
const d = new THREE.Vector3().randomDirection();
if(i % 3 === 0){ // denser galactic band
d.addScaledVector(bandAxis, Math.pow(hash3(i,7,3)-0.5, 1) * 1.6).normalize();
}
d.multiplyScalar(500 + hash3(i,3,11)*700);
pos.set([d.x,d.y,d.z], i*3);
const b = 0.45 + 0.55*Math.pow(hash3(i,5,2), 2.5);
const warm = hash3(i,9,4);
col.set([b*(0.85+0.3*warm), b*(0.9+0.12*warm), b], i*3);
}
const sg = new THREE.BufferGeometry();
sg.setAttribute('position', new THREE.BufferAttribute(pos,3));
sg.setAttribute('color', new THREE.BufferAttribute(col,3));
scene.add(new THREE.Points(sg, new THREE.PointsMaterial({
size:1.8, sizeAttenuation:false, vertexColors:true, transparent:true, opacity:.95, depthWrite:false
})));
}
function glowTexture(){
const c = document.createElement('canvas'); c.width = c.height = 128;
const g = c.getContext('2d');
const grd = g.createRadialGradient(64,64,0,64,64,64);
grd.addColorStop(0,'rgba(255,255,245,1)');
grd.addColorStop(0.10,'rgba(255,240,205,0.95)');
grd.addColorStop(0.30,'rgba(255,196,120,0.35)');
grd.addColorStop(1,'rgba(255,170,80,0)');
g.fillStyle = grd; g.fillRect(0,0,128,128);
const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
}
const sunSprite = new THREE.Sprite(new THREE.SpriteMaterial({
map:glowTexture(), blending:THREE.AdditiveBlending, depthWrite:false, transparent:true
}));
sunSprite.position.copy(sunDir).multiplyScalar(230);
sunSprite.scale.setScalar(70);
scene.add(sunSprite);
const sunCore = new THREE.Mesh(new THREE.SphereGeometry(2.2,24,16),
new THREE.MeshBasicMaterial({ color:0xfffaf0 }));
sunCore.position.copy(sunDir).multiplyScalar(230);
scene.add(sunCore);
/* ──────────────────────────────────────────────────────────────
The tracked beacon
────────────────────────────────────────────────────────────── */
const markerIdx = bestLand >= 0 ? bestLand : bestAny;
const markerLocal = new THREE.Vector3(cells[markerIdx][0], cells[markerIdx][1], cells[markerIdx][2]).normalize();
const anchor = new THREE.Object3D();
anchor.position.copy(markerLocal).multiplyScalar(R*0.985);
anchor.quaternion.setFromUnitVectors(new THREE.Vector3(0,1,0), markerLocal);
spin.add(anchor);
const ringGeo = new THREE.TorusGeometry(0.34, 0.055, 10, 40);
ringGeo.rotateX(Math.PI/2); // normal along +Y (= outward)
const beaconRing = new THREE.Mesh(ringGeo, new THREE.MeshStandardMaterial({
color:0xff3b5c, emissive:0xff2d4d, emissiveIntensity:1.6, roughness:.4, metalness:.1 }));
anchor.add(beaconRing);
const beaconPost = new THREE.Mesh(new THREE.CylinderGeometry(0.055,0.075,0.75,10),
new THREE.MeshStandardMaterial({ color:0xffd0d6, emissive:0xff4466, emissiveIntensity:.9, roughness:.5 }));
beaconPost.position.y = 0.36; anchor.add(beaconPost);
const beaconTip = new THREE.Mesh(new THREE.SphereGeometry(0.13,20,14),
new THREE.MeshStandardMaterial({ color:0xffffff, emissive:0xff5c7a, emissiveIntensity:2.2, roughness:.3 }));
beaconTip.position.y = 0.80; anchor.add(beaconTip);
const halo = new THREE.Sprite(new THREE.SpriteMaterial({
map:glowTexture(), blending:THREE.AdditiveBlending, depthTest:false, depthWrite:false, transparent:true, opacity:.9 }));
halo.scale.setScalar(2.2); halo.position.y = 0.80; anchor.add(halo);
/* ──────────────────────────────────────────────────────────────
Terminator ring (the day/night boundary, fixed in world space)
────────────────────────────────────────────────────────────── */
const termPts = [];
{
const e1 = new THREE.Vector3(0,1,0).cross(sunDir).normalize();
const e2 = new THREE.Vector3().crossVectors(sunDir, e1).normalize();
for(let i=0;i<=256;i++){
const a = i/256*Math.PI*2;
termPts.push(new THREE.Vector3()
.addScaledVector(e1, Math.cos(a)*R*1.006)
.addScaledVector(e2, Math.sin(a)*R*1.006));
}
}
const termRing = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(termPts),
new THREE.LineBasicMaterial({ color:0x7fe3ff, transparent:true, opacity:.38 }));
scene.add(termRing);
/* ──────────────────────────────────────────────────────────────
Solar geometry for the tracked point
────────────────────────────────────────────────────────────── */
const axis = new THREE.Vector3(); // tilted polar axis (world)
const uVec = new THREE.Vector3(); // equatorial reference ⊥ sun
const nWorld = new THREE.Vector3(); // marker normal (world)
const nPerp = new THREE.Vector3();
const mWorld = new THREE.Vector3();
function markerFrame(){
axis.setFromMatrixColumn(tilt.matrixWorld, 1).normalize();
uVec.crossVectors(axis, sunDir).normalize();
nWorld.setFromMatrixColumn(anchor.matrixWorld, 1).normalize();
nPerp.copy(nWorld).addScaledVector(axis, -nWorld.dot(axis));
const h = Math.atan2(nPerp.dot(uVec), nPerp.dot(sunDir)); // hour angle, radians
const elev = Math.asin(THREE.MathUtils.clamp(nWorld.dot(sunDir), -1, 1)) * THREE.MathUtils.RAD2DEG;
return { h, elev };
}
/* start the globe ~15° before sunrise so dawn happens on screen */
(function startAtDawn(){
const m = new THREE.Matrix4().makeRotationZ(TILT);
const tmp = new THREE.Matrix4();
const p = new THREE.Vector3();
const step = 0.004, N2 = Math.ceil(2*Math.PI/step);
let prev = null, dawnTheta = 0;
for(let i=0;i<=N2;i++){
const th = i*step;
p.copy(markerLocal).applyMatrix4(tmp.makeRotationY(th)).applyMatrix4(m);
const e = Math.asin(THREE.MathUtils.clamp(p.dot(sunDir),-1,1));
if(prev !== null && prev < 0 && e >= 0){ dawnTheta = th; break; }
prev = e;
}
spin.rotation.y = dawnTheta - 0.26;
})();
/* ──────────────────────────────────────────────────────────────
Camera rig (hand-rolled orbit + pinch zoom)
────────────────────────────────────────────────────────────── */
const rig = { r:29, th:0.52, ph:1.12, tr:29, tth:0.52, tph:1.12 };
const ptrs = new Map();
let pinchDist = 0;
canvas.addEventListener('pointerdown', e => {
canvas.setPointerCapture(e.pointerId);
ptrs.set(e.pointerId, { x:e.clientX, y:e.clientY });
if(ptrs.size === 2){
const [a,b] = [...ptrs.values()];
pinchDist = Math.hypot(a.x-b.x, a.y-b.y);
}
});
canvas.addEventListener('pointermove', e => {
if(!ptrs.has(e.pointerId)) return;
const p = ptrs.get(e.pointerId);
const dx = e.clientX - p.x, dy = e.clientY - p.y;
p.x = e.clientX; p.y = e.clientY;
if(ptrs.size === 1){
rig.tth -= dx*0.005;
rig.tph = THREE.MathUtils.clamp(rig.tph - dy*0.005, 0.12, Math.PI-0.12);
} else if(ptrs.size === 2){
const [a,b] = [...ptrs.values()];
const d = Math.hypot(a.x-b.x, a.y-b.y);
if(pinchDist > 0) rig.tr = THREE.MathUtils.clamp(rig.tr * (pinchDist/d), 13, 90);
pinchDist = d;
}
});
const drop = e => ptrs.delete(e.pointerId);
canvas.addEventListener('pointerup', drop);
canvas.addEventListener('pointercancel', drop);
canvas.addEventListener('wheel', e => {
e.preventDefault();
rig.tr = THREE.MathUtils.clamp(rig.tr * (1 + e.deltaY*0.0012), 13, 90);
}, { passive:false });
/* ──────────────────────────────────────────────────────────────
UI
────────────────────────────────────────────────────────────── */
const $ = id => document.getElementById(id);
const badge = $('badge'), sub = $('sub'), clock = $('clock'), dot = $('dot'), label = $('markerLabel');
const chips = [...document.querySelectorAll('.chip')];
let speed = 42/100, running = true, autoOrbit = false;
$('play').onclick = () => { running = !running; $('play').innerHTML = (running?'Pause spin':'Resume spin') + ' <b>SPACE</b>'; };
$('speed').oninput = e => speed = e.target.value/100;
$('term').onclick = () => { termRing.visible = !termRing.visible; $('term').innerHTML = 'Terminator ring <b>'+(termRing.visible?'ON':'OFF')+'</b>'; };
$('orbit').onclick = () => { autoOrbit = !autoOrbit; $('orbit').innerHTML = 'Auto-orbit camera <b>'+(autoOrbit?'ON':'OFF')+'</b>'; };
$('reset').onclick = () => { rig.tr=29; rig.tth=0.52; rig.tph=1.12; };
chips.forEach(c => c.onclick = () => {
const target = { dawn:-85, noon:0, dusk:85, night:140 }[c.dataset.p];
const cur = markerFrame().h * THREE.MathUtils.RAD2DEG;
let d = target - cur;
while(d > 180) d -= 360;
while(d < -180) d += 360;
spin.rotation.y += d * THREE.MathUtils.DEG2RAD;
});
addEventListener('keydown', e => {
if(e.code === 'Space'){ e.preventDefault(); $('play').click(); }
if(e.key === 'h' || e.key === 'H') $('reset').click();
});
/* ──────────────────────────────────────────────────────────────
Frame loop
────────────────────────────────────────────────────────────── */
const clock3 = new THREE.Clock();
let hAcc = null, prevElev = null, dhdt = 0, phaseKey = '';
const DEG = THREE.MathUtils.RAD2DEG;
function tick(){
const dt = Math.min(clock3.getDelta(), 0.05);
if(running) spin.rotation.y += speed*dt*0.55;
if(autoOrbit) rig.tth += dt*0.05;
// camera easing
rig.r += (rig.tr - rig.r) * Math.min(1, dt*7);
rig.th += (rig.tth - rig.th)* Math.min(1, dt*7);
rig.ph += (rig.tph - rig.ph)* Math.min(1, dt*7);
camera.position.setFromSpherical(new THREE.Spherical(rig.r, rig.ph, rig.th));
camera.lookAt(0,0,0);
scene.updateMatrixWorld(true);
// solar state of the tracked point
const { h, elev } = markerFrame();
if(hAcc === null) hAcc = h;
let dh = h - hAcc;
while(dh > Math.PI) dh -= 2*Math.PI;
while(dh < -Math.PI) dh += 2*Math.PI;
hAcc += dh;
const hDeg = ((hAcc*DEG + 180) % 360 + 360) % 360 - 180;
// rising if the elevation trend and the hour-angle sign disagree
const rising = (dh > 0 && hDeg < 0) || (dh < 0 && hDeg > 0);
if(prevElev !== null){
const raw = (elev - prevElev) / Math.max(dt, 1e-4);
dhdt += (raw - dhdt) * 0.15;
}
prevElev = elev;
// latitude of the marker relative to the tilted axis → max elevation
const lat = Math.asin(THREE.MathUtils.clamp(axis.dot(nWorld),-1,1)) * DEG;
const maxElev = 90 - Math.abs(lat);
let key, txt, col;
if(elev < -7){ key='night'; txt='NIGHT'; col='#7f8bf0'; }
else if(elev > maxElev - 13){ key='noon'; txt='NOON'; col='#ffd166'; }
else if(elev < 11){ key = rising?'dawn':'dusk';
txt = rising?'DAWN':'DUSK';
col = rising?'#ff9f43':'#ef5b6b'; }
else { key = rising?'day':'day'; txt = rising?'MORNING':'AFTERNOON'; col='#8fd3ff'; }
if(key !== phaseKey){
phaseKey = key;
badge.textContent = txt; badge.style.color = col;
sub.textContent = `solar elevation ${elev>=0?'+':''}${elev.toFixed(1)}° · lat ${lat>=0?'N':'S'}${Math.abs(lat).toFixed(1)}°`;
chips.forEach(c => c.classList.toggle('on', c.dataset.p === key ||
(c.dataset.p === 'night' && key === 'night') || (c.dataset.p === 'noon' && key === 'noon')));
}
badge.style.color = col;
// local solar time from the hour angle
let hrs = 12 + hDeg/15; hrs = ((hrs % 24) + 24) % 24;
const hh = Math.floor(hrs), mm = Math.floor((hrs-hh)*60);
clock.textContent = `${String(hh).padStart(2,'0')}:${String(mm).padStart(2,'0')}`;
dot.style.left = (hrs/24*100) + '%';
// beacon pulse + screen label
const pulse = 1 + 0.12*Math.sin(performance.now()*0.004);
beaconTip.scale.setScalar(pulse);
halo.scale.setScalar(2.0*pulse);
anchor.getWorldPosition(mWorld);
const proj = mWorld.clone().project(camera);
const sx = (proj.x*0.5+0.5)*innerWidth, sy = (-proj.y*0.5+0.5)*innerHeight;
label.style.transform = `translate(${sx}px, ${sy}px) translate(-50%,-160%)`;
const facing = camera.position.clone().sub(mWorld).normalize().dot(mWorld.clone().normalize());
label.style.opacity = facing > 0.06 ? 1 : 0.35;
label.style.display = (proj.z > 1) ? 'none' : 'block';
renderer.render(scene, camera);
}
renderer.setAnimationLoop(tick);
addEventListener('resize', () => {
camera.aspect = innerWidth/innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
</script>
</body>
</html>
```