-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcelestial-sim-1.html
More file actions
404 lines (355 loc) · 13 KB
/
celestial-sim-1.html
File metadata and controls
404 lines (355 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Celestial Simulation</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
html,body{width:100%;height:100%;overflow:hidden;background:#000;touch-action:none}
canvas{display:block}
#loading{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);color:#889;font:16px monospace;z-index:20;text-align:center}
#ui{position:fixed;bottom:0;left:0;right:0;padding:8px;background:rgba(0,0,10,0.8);
color:#aab;font:13px monospace;z-index:10;display:flex;flex-wrap:wrap;align-items:center;
justify-content:center;gap:6px;border-top:1px solid #223}
#ui input,#ui select,#ui button{font:13px monospace;background:#112;color:#aab;
border:1px solid #334;padding:4px 8px;border-radius:4px;-webkit-appearance:none}
#ui button{cursor:pointer;min-width:36px}
#ui button:active{background:#334}
#datetime-display{width:100%;text-align:center;font-size:11px;opacity:0.6;margin-bottom:2px}
#info{position:fixed;top:8px;left:8px;color:#556;font:11px monospace;z-index:10}
</style>
<script src="https://cdn.jsdelivr.net/npm/astronomy-engine@2.1.19/astronomy.browser.min.js"></script>
<script type="importmap">
{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.183.2/build/three.module.js","three/addons/":"https://cdn.jsdelivr.net/npm/three@0.183.2/examples/jsm/"}}
</script>
</head>
<body>
<div id="loading">Loading stars...</div>
<div id="info">Evanston, IL</div>
<div id="ui">
<span id="datetime-display"></span>
<input type="date" id="date-input">
<input type="time" id="time-input" step="60">
<button id="now-btn">Now</button>
<button id="play-btn">▶</button>
<select id="speed-select">
<option value="1">1m/s</option>
<option value="10">10m/s</option>
<option value="60" selected>1h/s</option>
<option value="1440">1d/s</option>
</select>
</div>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// ── Constants ──
const DEG2RAD = Math.PI / 180;
const RAD2DEG = 180 / Math.PI;
const SKY_R = 500;
const OBJ_R = 490;
// ── Observer: Evanston, IL ──
const observer = new Astronomy.Observer(41.88, -87.68, 0);
// ── State ──
let simDate = new Date();
let playing = false;
let speedMinPerSec = 60;
let lastFrameTime = 0;
let starData = null;
// ── Renderer ──
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x000008);
// ── Camera ──
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// Start slightly below origin so we look UP at the zenith
camera.position.set(0, -0.001, 0.0001);
// ── Controls ──
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0, 0);
controls.enableZoom = false;
controls.enablePan = false;
controls.enableDamping = true;
controls.dampingFactor = 0.12;
controls.rotateSpeed = 0.5;
// ── Sky Sphere ──
scene.add(new THREE.Mesh(
new THREE.SphereGeometry(SKY_R, 48, 48),
new THREE.MeshBasicMaterial({ color: 0x000010, side: THREE.BackSide })
));
// ── Ground Plane (semi-transparent horizon) ──
const ground = new THREE.Mesh(
new THREE.CircleGeometry(SKY_R * 0.99, 64),
new THREE.MeshBasicMaterial({ color: 0x1a2a15, side: THREE.DoubleSide, transparent: true, opacity: 0.25 })
);
ground.rotation.x = -Math.PI / 2;
ground.renderOrder = 1;
scene.add(ground);
// ── Coordinate Helpers ──
function azAltToXYZ(azDeg, altDeg, r) {
const azRad = azDeg * DEG2RAD;
const phi = (90 - altDeg) * DEG2RAD;
return new THREE.Vector3(
r * Math.sin(phi) * Math.sin(azRad),
r * Math.cos(phi),
-r * Math.sin(phi) * Math.cos(azRad)
);
}
function bvToRGB(bv) {
bv = Math.max(-0.4, Math.min(2.0, bv));
if (bv < 0) return [0.7 - bv * 0.5, 0.8 - bv * 0.3, 1.0];
if (bv < 0.4) { const t = bv / 0.4; return [1.0, 1.0 - 0.12 * t, 1.0 - 0.45 * t]; }
const t = Math.min(1, (bv - 0.4) / 1.2);
return [1.0, 0.88 - 0.48 * t, 0.55 - 0.4 * t];
}
// ── Stars ──
let starPoints, starPositions, starColors, starSizes;
const starVertShader = `
attribute float aSize;
attribute vec3 aColor;
varying vec3 vColor;
void main() {
vColor = aColor;
gl_PointSize = aSize;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const starFragShader = `
varying vec3 vColor;
void main() {
float d = length(gl_PointCoord - 0.5);
if (d > 0.5) discard;
float a = 1.0 - smoothstep(0.1, 0.5, d);
gl_FragColor = vec4(vColor, a);
}
`;
function initStars() {
const n = starData.length;
starPositions = new Float32Array(n * 3);
starColors = new Float32Array(n * 3);
starSizes = new Float32Array(n);
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.BufferAttribute(starPositions, 3));
geo.setAttribute('aColor', new THREE.BufferAttribute(starColors, 3));
geo.setAttribute('aSize', new THREE.BufferAttribute(starSizes, 1));
const mat = new THREE.ShaderMaterial({
vertexShader: starVertShader,
fragmentShader: starFragShader,
transparent: true,
depthTest: false
});
starPoints = new THREE.Points(geo, mat);
starPoints.renderOrder = 0;
scene.add(starPoints);
}
function updateStars(date) {
if (!starData) return;
const gast = Astronomy.SiderealTime(date);
const lstDeg = gast * 15 + observer.longitude; // local sidereal time in degrees
const latRad = observer.latitude * DEG2RAD;
const sinLat = Math.sin(latRad);
const cosLat = Math.cos(latRad);
for (let i = 0; i < starData.length; i++) {
const raDeg = starData[i][2];
const decDeg = starData[i][3];
const mag = starData[i][1];
const bv = starData[i][4];
const haRad = (lstDeg - raDeg) * DEG2RAD;
const decRad = decDeg * DEG2RAD;
const sinDec = Math.sin(decRad);
const cosDec = Math.cos(decRad);
const cosHA = Math.cos(haRad);
const sinHA = Math.sin(haRad);
// Altitude
const sinAlt = sinDec * sinLat + cosDec * cosLat * cosHA;
const altRad = Math.asin(sinAlt);
const altDeg = altRad * RAD2DEG;
// Azimuth (from North through East)
const azRad = Math.atan2(-cosDec * sinHA, sinDec * cosLat - cosDec * sinLat * cosHA);
const azDeg = azRad * RAD2DEG;
// 3D position
const phi = Math.PI / 2 - altRad;
const sinPhi = Math.sin(phi);
const azR = azDeg * DEG2RAD;
const j = i * 3;
starPositions[j] = OBJ_R * sinPhi * Math.sin(azR);
starPositions[j + 1] = OBJ_R * Math.cos(phi);
starPositions[j + 2] = -OBJ_R * sinPhi * Math.cos(azR);
// Color + dimming below horizon
const [cr, cg, cb] = bvToRGB(bv);
const dim = altDeg < 0 ? 0.12 : 1.0;
starColors[j] = cr * dim;
starColors[j + 1] = cg * dim;
starColors[j + 2] = cb * dim;
// Size from magnitude
starSizes[i] = Math.max(1.5, 7 - mag) * (window.devicePixelRatio || 1);
}
starPoints.geometry.attributes.position.needsUpdate = true;
starPoints.geometry.attributes.aColor.needsUpdate = true;
starPoints.geometry.attributes.aSize.needsUpdate = true;
}
// ── Celestial Bodies (Sun + Planets) ──
const bodyDefs = [
{ name: 'Sun', color: 0xffdd33, size: 14, label: '☉' },
{ name: 'Moon', color: 0xddddcc, size: 11, label: '☽' },
{ name: 'Mercury', color: 0xaaaaaa, size: 5, label: '☿' },
{ name: 'Venus', color: 0xffffcc, size: 7, label: '♀' },
{ name: 'Mars', color: 0xff5533, size: 6, label: '♂' },
{ name: 'Jupiter', color: 0xddcc88, size: 7, label: '♃' },
{ name: 'Saturn', color: 0xccbb55, size: 6, label: '♄' },
];
const bodySprites = [];
function makeGlowTexture(hex, label) {
const c = document.createElement('canvas');
c.width = 64; c.height = 64;
const ctx = c.getContext('2d');
const col = new THREE.Color(hex);
const r = Math.floor(col.r * 255), g = Math.floor(col.g * 255), b = Math.floor(col.b * 255);
const grad = ctx.createRadialGradient(32, 32, 0, 32, 32, 28);
grad.addColorStop(0, `rgba(${r},${g},${b},1)`);
grad.addColorStop(0.25, `rgba(${r},${g},${b},0.7)`);
grad.addColorStop(1, `rgba(${r},${g},${b},0)`);
ctx.fillStyle = grad;
ctx.fillRect(0, 0, 64, 64);
// Label
ctx.fillStyle = '#fff';
ctx.font = 'bold 20px serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(label, 32, 32);
return new THREE.CanvasTexture(c);
}
function initBodies() {
bodyDefs.forEach(b => {
const tex = makeGlowTexture(b.color, b.label);
const mat = new THREE.SpriteMaterial({ map: tex, transparent: true, depthTest: false });
const sprite = new THREE.Sprite(mat);
sprite.scale.set(b.size, b.size, 1);
sprite.renderOrder = 2;
scene.add(sprite);
bodySprites.push({ def: b, sprite });
});
}
function updateBodies(date) {
bodySprites.forEach(({ def, sprite }) => {
try {
const equ = Astronomy.Equator(def.name, date, observer, true, true);
const hor = Astronomy.Horizon(date, observer, equ.ra, equ.dec, 'normal');
const pos = azAltToXYZ(hor.azimuth, hor.altitude, OBJ_R);
sprite.position.copy(pos);
sprite.material.opacity = hor.altitude < 0 ? 0.15 : 1.0;
} catch (e) {
sprite.visible = false;
}
});
}
// ── Cardinal Direction Labels ──
function initCardinals() {
['N','E','S','W'].forEach((txt, i) => {
const c = document.createElement('canvas');
c.width = 64; c.height = 64;
const ctx = c.getContext('2d');
ctx.fillStyle = '#445566';
ctx.font = 'bold 44px monospace';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(txt, 32, 32);
const tex = new THREE.CanvasTexture(c);
const mat = new THREE.SpriteMaterial({ map: tex, transparent: true, depthTest: false });
const sprite = new THREE.Sprite(mat);
sprite.scale.set(18, 18, 1);
const pos = azAltToXYZ(i * 90, 3, OBJ_R);
sprite.position.copy(pos);
sprite.renderOrder = 3;
scene.add(sprite);
});
}
// ── Load Star Data ──
async function loadStars() {
const loadEl = document.getElementById('loading');
try {
const resp = await fetch('https://raw.githubusercontent.com/gmiller123456/hip2000/master/hipparcos_5_concise.js');
let text = await resp.text();
text = text.replace('hipparcos_catalog=', '').trim();
if (text.endsWith(';')) text = text.slice(0, -1);
// Fix trailing commas (valid JS but invalid JSON)
text = text.replace(/,\s*]/g, ']').replace(/,\s*}/g, '}');
starData = JSON.parse(text);
// Keep stars up to magnitude 5.5
starData = starData.filter(s => s[1] <= 5.5);
loadEl.style.display = 'none';
initStars();
updateAll();
} catch (e) {
loadEl.textContent = 'Error loading stars. Check connection.';
console.error(e);
// Still run bodies
updateBodies(simDate);
}
}
// ── UI ──
const dateInput = document.getElementById('date-input');
const timeInput = document.getElementById('time-input');
const playBtn = document.getElementById('play-btn');
const speedSelect = document.getElementById('speed-select');
const dtDisplay = document.getElementById('datetime-display');
function pad(n) { return String(n).padStart(2, '0'); }
function syncUI() {
const d = simDate;
dateInput.value = `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`;
timeInput.value = `${pad(d.getHours())}:${pad(d.getMinutes())}`;
dtDisplay.textContent = d.toLocaleString();
}
function readUI() {
if (!dateInput.value || !timeInput.value) return;
const [y, m, d] = dateInput.value.split('-').map(Number);
const [hh, mm] = timeInput.value.split(':').map(Number);
simDate = new Date(y, m - 1, d, hh, mm);
updateAll();
}
document.getElementById('now-btn').addEventListener('click', () => {
simDate = new Date(); updateAll();
});
playBtn.addEventListener('click', () => {
playing = !playing;
playBtn.innerHTML = playing ? '▮▮' : '▶';
});
speedSelect.addEventListener('change', () => { speedMinPerSec = +speedSelect.value; });
dateInput.addEventListener('change', readUI);
timeInput.addEventListener('change', readUI);
// ── Update All ──
function updateAll() {
syncUI();
updateStars(simDate);
updateBodies(simDate);
}
// ── Resize ──
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// ── Animation Loop ──
function animate(t) {
requestAnimationFrame(animate);
if (playing && lastFrameTime > 0) {
const dt = (t - lastFrameTime) / 1000;
simDate = new Date(simDate.getTime() + dt * speedMinPerSec * 60000);
updateAll();
}
lastFrameTime = t;
controls.update();
renderer.render(scene, camera);
}
// ── Init ──
initBodies();
initCardinals();
syncUI();
loadStars();
animate(0);
</script>
</body>
</html>