-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolarSystemEditor.html
More file actions
1644 lines (1398 loc) · 71.5 KB
/
SolarSystemEditor.html
File metadata and controls
1644 lines (1398 loc) · 71.5 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Solar System Editor</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<style>
:root { --accent: #00ff88; --panel: rgba(10, 10, 12, 0.95); --border: rgba(255,255,255,0.1); }
body { margin: 0; overflow: hidden; background: #000; color: #e0e0e0; font-family: 'Segoe UI', Roboto, sans-serif; font-size: 13px; }
#ui-layer { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; display: flex; justify-content: space-between; padding: 20px; box-sizing: border-box; z-index: 10; }
.panel {
pointer-events: auto; background: var(--panel); backdrop-filter: blur(12px);
width: 300px; padding: 0; border-radius: 8px; border: 1px solid var(--border);
display: flex; flex-direction: column;
max-height: 90vh; transition: height 0.3s;
box-shadow: 0 8px 40px rgba(0,0,0,0.8);
overflow: hidden; /* Important for collapse animation */
}
/* Collapsed State */
.panel.collapsed { width: auto; max-height: 48px; }
.panel.collapsed .panel-content { display: none; }
.panel.collapsed .collapse-btn { transform: rotate(180deg); }
/* Header Styling */
.panel-header {
display: flex; justify-content: space-between; align-items: center;
padding: 12px 16px; cursor: pointer; background: rgba(255,255,255,0.02);
border-bottom: 1px solid var(--border); user-select: none;
}
.panel-header:hover h2 { color: #fff; text-shadow: 0 0 8px var(--accent); }
.collapse-btn {
background: none; border: 1px solid #444; color: #888; width: 24px; height: 24px;
border-radius: 4px; cursor: pointer; font-size: 10px; display: flex; align-items: center;
justify-content: center; transition: all 0.2s; padding: 0;
}
.collapse-btn:hover { background: #333; color: #fff; border-color: #666; }
.panel-content { padding: 16px; overflow-y: auto; display: flex; flex-direction: column; gap: 10px; }
h2 { margin: 0; font-size: 14px; color: var(--accent); text-transform: uppercase; letter-spacing: 2px; font-weight: 800; }
h3 { margin: 10px 0 5px 0; font-size: 11px; color: #888; text-transform: uppercase; }
/* General Controls */
button.action-btn { background: #222; color: #fff; border: 1px solid #444; padding: 10px; border-radius: 4px; cursor: pointer; transition: 0.2s; text-transform: uppercase; font-size: 11px; font-weight: bold; width: 100%; }
button.action-btn:hover { background: var(--accent); color: #000; border-color: var(--accent); }
button.delete-btn { background: #422; border-color: #633; margin-top: 5px; }
button.delete-btn:hover { background: #f44; color: #fff; }
/* Hierarchy List Styling */
.body-list { display: flex; flex-direction: column; gap: 2px; }
.body-item { padding: 6px 8px; background: rgba(255,255,255,0.05); border-radius: 4px; cursor: pointer; display: flex; align-items: center; border: 1px solid transparent; transition: all 0.1s; }
.body-item:hover { background: rgba(255,255,255,0.1); }
.body-item.selected { border-color: var(--accent); background: rgba(0, 255, 136, 0.1); }
.body-icon { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 8px; box-shadow: 0 0 4px currentColor; }
.indent-0 { margin-left: 0px; border-left: 2px solid #444; }
.indent-1 { margin-left: 20px; border-left: 2px solid #666; }
.indent-2 { margin-left: 40px; border-left: 2px solid #888; }
.control-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px; }
input[type=range] { width: 100%; accent-color: var(--accent); cursor: pointer; margin: 4px 0; }
select { width: 100%; background: #222; color: #fff; border: 1px solid #444; padding: 6px; border-radius: 4px; margin-top: 4px; }
.val { font-family: monospace; color: var(--accent); }
#fileInput { display: none; }
/* Zoom indicator */
#zoom-indicator {
position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%);
background: var(--panel); padding: 10px 20px; border-radius: 8px;
border: 1px solid var(--border); pointer-events: auto;
display: flex; align-items: center; gap: 15px; z-index: 10;
}
#zoom-indicator .zoom-btn {
background: #333; border: 1px solid #555; color: #fff; width: 30px; height: 30px;
border-radius: 4px; cursor: pointer; font-size: 16px; font-weight: bold;
}
#zoom-indicator .zoom-btn:hover { background: var(--accent); color: #000; }
#zoom-level { font-family: monospace; color: var(--accent); min-width: 60px; text-align: center; }
/* Body selection label */
#body-label {
position: absolute; bottom: 80px; left: 50%; transform: translateX(-50%);
background: var(--panel); padding: 12px 24px; border-radius: 8px;
border: 1px solid var(--accent); pointer-events: none;
font-family: 'Segoe UI', sans-serif; font-size: 14px; z-index: 15;
display: none; text-align: center;
box-shadow: 0 0 20px rgba(0, 255, 136, 0.3);
}
#body-label .body-name { color: #fff; font-size: 18px; font-weight: bold; margin-bottom: 4px; }
#body-label .body-type { color: var(--accent); font-size: 12px; text-transform: uppercase; letter-spacing: 1px; }
#body-label .body-hint { color: #666; font-size: 10px; margin-top: 6px; }
/* WELCOME SCREEN */
#welcome {
position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
width: 400px; text-align: center; color: #fff; pointer-events: none;
background: rgba(0,0,0,0.8); padding: 40px; border-radius: 16px; border: 1px solid #333;
box-shadow: 0 0 50px rgba(0,0,0,0.5); z-index: 5;
transition: opacity 0.5s;
}
#welcome.hidden { opacity: 0; pointer-events: none; }
#welcome h1 { margin: 0 0 10px 0; color: var(--accent); font-weight: 300; letter-spacing: 4px; text-transform: uppercase; }
#welcome p { color: #888; line-height: 1.6; font-size: 14px; }
.step { background: #222; padding: 10px; margin: 10px 0; border-radius: 4px; border: 1px solid #333; display: flex; align-items: center; gap: 10px; text-align: left; }
.step-num { background: var(--accent); color: #000; width: 24px; height: 24px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; flex-shrink: 0; }
</style>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.168.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.168.0/examples/jsm/"
}
}
</script>
</head>
<body>
<div id="welcome">
<h1>System Editor</h1>
<p>Assemble your generated planets into a complete solar system.</p>
<div class="step">
<div class="step-num">1</div>
<div><strong>Import Sun:</strong> Start by importing your <em>sun_*.zip</em> file to act as the center.</div>
</div>
<div class="step">
<div class="step-num">2</div>
<div><strong>Add Planets:</strong> Import <em>planet_*.zip</em> files. They will automatically orbit the sun.</div>
</div>
<div class="step">
<div class="step-num">3</div>
<div><strong>Add Moons:</strong> Import <em>moon_*.zip</em> files. They will attach to the last planet added.</div>
</div>
<p style="margin-top:20px; font-size: 12px; color: #666;">Use the <strong>hierarchy panel</strong> on the left to reorganize orbits.</p>
</div>
<div id="ui-layer">
<div class="panel" id="leftPanel">
<div class="panel-header" onclick="togglePanel('leftPanel')">
<h2>Hierarchy</h2>
<button class="collapse-btn">▼</button>
</div>
<div class="panel-content">
<!-- Embedded Mode: Receive from Planet Editor -->
<button id="btnReceivePlanets" class="action-btn" style="display:none; background: linear-gradient(135deg, #ff6600, #ff8833); color: #000; border: none; font-weight: bold;">
📥 Import from Planet Editor <span id="stagedCount" style="background:#000;color:#ff6600;padding:2px 6px;border-radius:10px;margin-left:5px;font-size:10px;">0</span>
</button>
<button id="btnImport" class="action-btn">➕ Import Body (ZIP)</button>
<button id="btnRandomSystem" class="action-btn" style="background: #442; border-color: #664; margin-top: 5px;">🎲 Generate Random System</button>
<button id="btnExportSystem" class="action-btn" style="background: #264; border-color: #3a6; margin-top: 5px;">💾 Export Solar System</button>
<!-- Embedded Mode: Send to Galaxy Editor -->
<button id="btnSendToGalaxy" class="action-btn" style="display:none; margin-top:8px; background:linear-gradient(135deg, #9933ff, #cc66ff); color:#fff; border:none; font-weight:bold;">
📤 Send to Galaxy Editor
</button>
<input type="file" id="fileInput" accept=".zip">
<div id="bodyList" class="body-list">
</div>
</div>
</div>
<div class="panel" id="detailPanel" style="display:none;">
<div class="panel-header" onclick="togglePanel('detailPanel')">
<h2 id="detailName">Details</h2>
<button class="collapse-btn">▼</button>
</div>
<div class="panel-content">
<h3>Hierarchy</h3>
<div style="margin-bottom: 10px;">
<label style="color:#bbb;">Orbiting Parent</label>
<select id="parentSelect"></select>
</div>
<h3>Orbital Mechanics</h3>
<div class="control-row"><label>Distance</label><span id="distVal" class="val">0</span></div>
<input type="range" id="orbitDist" min="0" max="150" step="0.5">
<div class="control-row"><label>Orbit Speed</label><span id="speedVal" class="val">0</span></div>
<input type="range" id="orbitSpeed" min="0" max="3.0" step="0.01">
<button class="action-btn delete-btn" id="btnDelete">Remove Object</button>
</div>
</div>
</div>
<div id="zoom-indicator">
<button class="zoom-btn" id="btnZoomOut">−</button>
<span id="zoom-level">100%</span>
<button class="zoom-btn" id="btnZoomIn">+</button>
<span style="color:#666; margin-left: 10px;">|</span>
<button class="zoom-btn" id="btnResetView" style="width: auto; padding: 0 10px; font-size: 11px;">⌂</button>
</div>
<div id="body-label">
<div class="body-name" id="bodyLabelName">Planet Name</div>
<div class="body-type" id="bodyLabelType">Planet</div>
<div class="body-hint">Press ESC to return</div>
</div>
<script>
function togglePanel(id) {
const panel = document.getElementById(id);
panel.classList.toggle('collapsed');
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
// --- GLOBAL SCENE SETUP ---
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000);
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 2000);
camera.position.set(0, 40, 80);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
const composer = new EffectComposer(renderer);
const renderPass = new RenderPass(scene, camera);
const bloomPass = new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight), 1.5, 0.4, 0.85);
bloomPass.threshold = 0.2; bloomPass.strength = 1.2; bloomPass.radius = 0.5;
composer.addPass(renderPass);
composer.addPass(bloomPass);
// Starfield
const starGeo = new THREE.BufferGeometry();
const starPos = new Float32Array(5000 * 3);
for(let i=0; i<5000*3; i++) starPos[i] = (Math.random() - 0.5) * 1000;
starGeo.setAttribute('position', new THREE.BufferAttribute(starPos, 3));
scene.add(new THREE.Points(starGeo, new THREE.PointsMaterial({color:0xffffff, size:0.3, transparent: true, opacity: 0.6})));
// Lights
const sunLight = new THREE.PointLight(0xffffff, 2, 500);
scene.add(sunLight);
scene.add(new THREE.AmbientLight(0x404040, 0.5));
// --- SHADER UTILS ---
const shaderUtils = `
vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec4 permute(vec4 x) { return mod289(((x*34.0)+1.0)*x); }
vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }
float snoise(vec3 v) {
const vec2 C = vec2(1.0/6.0, 1.0/3.0);
const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
vec3 i = floor(v + dot(v, C.yyy));
vec3 x0 = v - i + dot(i, C.xxx);
vec3 g = step(x0.yzx, x0.xyz);
vec3 l = 1.0 - g;
vec3 i1 = min( g.xyz, l.zxy );
vec3 i2 = max( g.xyz, l.zxy );
vec3 x1 = x0 - i1 + C.xxx;
vec3 x2 = x0 - i2 + C.yyy;
vec3 x3 = x0 - D.yyy;
i = mod289(i);
vec4 p = permute( permute( permute(
i.z + vec4(0.0, i1.z, i2.z, 1.0 ))
+ i.y + vec4(0.0, i1.y, i2.y, 1.0 ))
+ i.x + vec4(0.0, i1.x, i2.x, 1.0 ));
float n_ = 0.142857142857;
vec3 ns = n_ * D.wyz - D.xzx;
vec4 j = p - 49.0 * floor(p * ns.z * ns.z);
vec4 x_ = floor(j * ns.z);
vec4 y_ = floor(j - 7.0 * x_ );
vec4 x = x_ *ns.x + ns.yyyy;
vec4 y = y_ *ns.x + ns.yyyy;
vec4 h = 1.0 - abs(x) - abs(y);
vec4 b0 = vec4( x.xy, y.xy );
vec4 b1 = vec4( x.zw, y.zw );
vec4 s0 = floor(b0)*2.0 + 1.0;
vec4 s1 = floor(b1)*2.0 + 1.0;
vec4 sh = -step(h, vec4(0.0));
vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;
vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;
vec3 p0 = vec3(a0.xy,h.x);
vec3 p1 = vec3(a0.zw,h.y);
vec3 p2 = vec3(a1.xy,h.z);
vec3 p3 = vec3(a1.zw,h.w);
vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2,p2), dot(p3,p3)));
p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;
vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);
m = m * m;
return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3) ) );
}
float fbm(vec3 p, int octaves, float persistence, float lacunarity) {
float total = 0.0; float amplitude = 1.0; float frequency = 1.0; float maxValue = 0.0;
for(int i=0; i<20; i++) {
if (i >= octaves) break;
total += snoise(p * frequency) * amplitude;
maxValue += amplitude; amplitude *= persistence; frequency *= lacunarity;
}
return total / maxValue;
}
vec2 getUV(vec3 p) {
vec3 n = normalize(p);
float u = 0.5 + (atan(n.z, n.x) / (2.0 * 3.14159));
float v = 0.5 - (asin(n.y) / 3.14159);
return vec2(u, v);
}
`;
const vertexShader = `
uniform float radius;
uniform float heightScale;
uniform float frequency;
uniform int octaves;
uniform float persistence;
uniform float ridge;
uniform float warpScale;
uniform vec3 seedOffset;
uniform float shapeFactor;
uniform sampler2D heightMap;
uniform float texMix;
uniform float isSun;
uniform float time;
varying vec3 vPos;
varying float vElevation;
varying vec2 vUv;
varying vec3 vBasePos;
varying float vSunNoise;
${shaderUtils}
void main() {
vUv = uv;
vec3 sphereP = normalize(position);
vec3 absP = abs(position);
float maxC = max(max(absP.x, absP.y), absP.z);
vec3 boxP = position / maxC;
vec3 baseDir = mix(sphereP, boxP, shapeFactor);
vec3 basePos = baseDir * radius;
vBasePos = baseDir;
vec3 warpPos = sphereP * 0.5 + seedOffset;
if (isSun > 0.5) warpPos += vec3(time * 0.1);
float warp = snoise(warpPos) * warpScale;
vec3 noisePos = (sphereP + vec3(warp)) * frequency + seedOffset;
if (isSun > 0.5) noisePos += vec3(time * 0.2, -time*0.1, time*0.1);
float n = fbm(noisePos, octaves, persistence, 2.0);
float r = 1.0 - abs(snoise(noisePos));
r = pow(r, 3.0);
float finalNoise = mix(n, r, ridge);
vec2 sphericalUV = getUV(sphereP);
float texHeight = texture2D(heightMap, sphericalUV).r;
float combinedHeight = mix(finalNoise, texHeight * 2.0 - 1.0, texMix);
float displacement = combinedHeight * heightScale;
vec3 finalPos = basePos + normalize(baseDir) * displacement;
vPos = finalPos;
vElevation = combinedHeight;
vSunNoise = finalNoise;
gl_Position = projectionMatrix * modelViewMatrix * vec4(finalPos, 1.0);
}
`;
const fragmentShader = `
uniform float oceanLevel;
uniform float snowLevel;
uniform float moistureOffset;
uniform vec3 sunDirection;
uniform float time;
uniform vec3 seedOffset;
uniform float isSun;
uniform float opacity;
uniform vec3 oceanColor;
uniform vec3 beachColor;
uniform vec3 grassColor;
uniform vec3 rockColor;
uniform vec3 snowColor;
varying vec3 vPos;
varying vec3 vBasePos;
varying float vElevation;
varying float vSunNoise;
${shaderUtils}
void main() {
if (isSun > 0.5) {
float heat = vSunNoise * 0.5 + 0.5;
float detail = snoise(vPos * 5.0 + vec3(time)) * 0.1;
heat += detail;
vec3 c1 = vec3(0.6, 0.0, 0.0); vec3 c2 = vec3(1.0, 0.4, 0.0);
vec3 c3 = vec3(1.0, 0.9, 0.4); vec3 c4 = vec3(2.0, 2.0, 2.0);
vec3 color;
if (heat < 0.33) color = mix(c1, c2, heat * 3.0);
else if (heat < 0.66) color = mix(c2, c3, (heat - 0.33) * 3.0);
else color = mix(c3, c4, (heat - 0.66) * 3.0);
vec3 N = normalize(vPos);
float rim = 1.0 - max(dot(N, vec3(0,0,1)), 0.0);
color += vec3(rim * 0.5, rim * 0.2, 0.0);
gl_FragColor = vec4(color, opacity);
return;
}
vec3 N = normalize(vPos);
vec3 L = normalize(sunDirection);
float h = vElevation;
bool hasWater = oceanLevel > -0.99;
vec3 color;
float slope = 1.0 - dot(N, normalize(vBasePos));
if (hasWater && h < oceanLevel) {
color = oceanColor;
} else {
if (hasWater && h < oceanLevel + 0.015) color = beachColor;
else if (h > snowLevel) color = snowColor;
else {
float moist = snoise(normalize(vPos) * 2.5 + seedOffset) + moistureOffset;
if (slope > 0.18) color = rockColor;
else color = mix(grassColor * 0.4, grassColor, smoothstep(0.0, 0.6, moist));
}
}
float diff = max(dot(N, L), 0.0);
vec3 finalColor = color * (diff * 0.8 + 0.2);
gl_FragColor = vec4(finalColor, opacity);
}
`;
function cyrb128(str) {
let h1 = 1779033703, h2 = 3144134277, h3 = 1013904242, h4 = 2773480762;
for (let i = 0, k; i < str.length; i++) {
k = str.charCodeAt(i);
h1 = h2 ^ Math.imul(h1 ^ k, 597399067);
h2 = h3 ^ Math.imul(h2 ^ k, 2869860233);
h3 = h4 ^ Math.imul(h3 ^ k, 951274213);
h4 = h1 ^ Math.imul(h4 ^ k, 2716044179);
}
h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067);
h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233);
h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213);
h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179);
return [(h1^h2^h3^h4)>>>0];
}
function mulberry32(a) {
return function() {
var t = a += 0x6D2B79F5;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
}
// ============================================
// PLANET LIBRARY SYSTEM
// ============================================
const planetLibrary = {
suns: [],
planets: [],
moons: [],
loaded: false,
loading: false
};
async function loadPlanetLibrary() {
if (planetLibrary.loading || planetLibrary.loaded) return;
planetLibrary.loading = true;
try {
// Try to fetch manifest from planets folder
const manifestResponse = await fetch('planets/manifest.json');
if (!manifestResponse.ok) {
console.log('No planets/manifest.json found - using procedural generation');
planetLibrary.loading = false;
return;
}
const manifest = await manifestResponse.json();
console.log(`Loading planet library: ${manifest.name}`);
// Load each body ZIP file
for (const filename of manifest.bodies) {
try {
const zipResponse = await fetch(`planets/${filename}`);
if (!zipResponse.ok) continue;
const zipBlob = await zipResponse.blob();
const zip = await JSZip.loadAsync(zipBlob);
const jsonStr = await zip.file("planet_data.json").async("string");
const data = JSON.parse(jsonStr);
// Load heightmap if present
let heightmapBase64 = null;
const imgFile = zip.file("heightmap.png");
if (imgFile) {
heightmapBase64 = await imgFile.async("base64");
}
const bodyEntry = { data, heightmapBase64, filename };
// Sort into appropriate category
if (data.type === 'sun') {
planetLibrary.suns.push(bodyEntry);
} else if (data.type === 'moon') {
planetLibrary.moons.push(bodyEntry);
} else {
planetLibrary.planets.push(bodyEntry);
}
console.log(` Loaded: ${filename} (${data.type})`);
} catch (err) {
console.warn(`Failed to load ${filename}:`, err);
}
}
planetLibrary.loaded = true;
console.log(`Library loaded: ${planetLibrary.suns.length} suns, ${planetLibrary.planets.length} planets, ${planetLibrary.moons.length} moons`);
// Update UI to show library status
updateLibraryStatus();
} catch (err) {
console.log('Planet library not available:', err.message);
updateLibraryStatus(); // Still update to show "procedural" mode
}
planetLibrary.loading = false;
}
function updateLibraryStatus() {
const btn = $('btnRandomSystem');
const suns = planetLibrary.suns.length;
const planets = planetLibrary.planets.length;
const moons = planetLibrary.moons.length;
const total = suns + planets + moons;
if (total > 0) {
// Show library count with breakdown on hover
btn.innerHTML = `🎲 Generate System <span style="font-size:9px;opacity:0.7;">(${total} in library)</span>`;
btn.title = `Library: ${suns} sun(s), ${planets} planet(s), ${moons} moon(s)\nMissing types will be procedurally generated.`;
btn.style.borderColor = '#00ff88';
} else {
// No library - purely procedural
btn.innerHTML = `🎲 Generate Random System`;
btn.title = `No planets/ folder found.\nAll bodies will be procedurally generated.`;
}
}
function getLibraryBody(type, rng) {
let pool;
if (type === 'sun') pool = planetLibrary.suns;
else if (type === 'moon') pool = planetLibrary.moons;
else pool = planetLibrary.planets;
if (pool.length === 0) return null;
// Pick a random body from the library
const idx = Math.floor(rng() * pool.length);
const entry = pool[idx];
// Clone the data so we don't modify the original
return {
data: JSON.parse(JSON.stringify(entry.data)),
heightmapBase64: entry.heightmapBase64
};
}
// Start loading library immediately
loadPlanetLibrary();
// --- CELESTIAL BODY CLASS ---
class CelestialBody {
constructor(data, texture, id, heightmapBase64 = null) {
this.id = id;
this.data = data;
this.type = data.type || 'planet';
this.name = `${this.type}_${data.seed}`;
this.heightmapBase64 = heightmapBase64; // Store for export
// HIERARCHY TRACKING
this.parentBody = null; // null means scene/center
this.childrenBodies = [];
this.orbitDistance = 0;
this.orbitSpeed = 0.2;
this.orbitAngle = Math.random() * Math.PI * 2;
const p = data.params;
const c = data.colors;
const seedHash = cyrb128(data.seed);
const rng = mulberry32(seedHash[0]);
const seedOffset = new THREE.Vector3(rng()*100, rng()*100, rng()*100);
// Ring support - check if data has ring parameters
this.hasRings = p.enableRings === true;
this.ringDiameter = parseFloat(p.ringDiameter || 1.5);
this.ringColorInner = p.ringColorInner || '#FFD700';
this.ringColorOuter = p.ringColorOuter || '#DAA520';
this.material = new THREE.ShaderMaterial({
uniforms: {
seedOffset: { value: seedOffset },
radius: { value: 1.0 },
heightScale: { value: parseFloat(p.heightScale) },
frequency: { value: parseFloat(p.frequency) },
octaves: { value: parseInt(p.octaves) },
persistence: { value: parseFloat(p.persistence) },
ridge: { value: parseFloat(p.ridge) },
warpScale: { value: parseFloat(p.warpScale) },
shapeFactor: { value: data.mode === 'cube' ? 0.7 : 0.0 },
oceanLevel: { value: parseFloat(p.oceanLevel) },
snowLevel: { value: parseFloat(p.snowLevel) },
moistureOffset: { value: parseFloat(p.moistureOffset) },
sunDirection: { value: new THREE.Vector3(1, 0, 0) },
time: { value: 0 },
heightMap: { value: texture },
texMix: { value: parseFloat(p.texMix || 0) },
oceanColor: { value: new THREE.Color(c.ocean) },
beachColor: { value: new THREE.Color(c.beach) },
grassColor: { value: new THREE.Color(c.grass) },
rockColor: { value: new THREE.Color(c.rock) },
snowColor: { value: new THREE.Color(c.snow) },
isSun: { value: this.type === 'sun' ? 1.0 : 0.0 },
opacity: { value: 1.0 },
// Ring uniforms
hasRings: { value: this.hasRings ? 1.0 : 0.0 },
ringInnerRadius: { value: parseFloat(p.radius) * 1.2 },
ringOuterRadius: { value: parseFloat(p.radius) * this.ringDiameter }
},
vertexShader: vertexShader,
fragmentShader: fragmentShader,
transparent: true
});
const geo = new THREE.BoxGeometry(1, 1, 1, 64, 64, 64);
this.mesh = new THREE.Mesh(geo, this.material);
// --- SIZE SCALING ---
// We use the radius from the ZIP parameters.
const baseRadius = parseFloat(p.radius);
this.mesh.scale.setScalar(baseRadius);
this.pivot = new THREE.Group();
this.holder = new THREE.Group();
this.pivot.add(this.holder);
this.holder.add(this.mesh);
const ringGeo = new THREE.RingGeometry(1, 1.05, 128);
const ringMat = new THREE.MeshBasicMaterial({ color: 0x666666, side: THREE.DoubleSide, transparent: true, opacity: 0.15 });
this.orbitRing = new THREE.Mesh(ringGeo, ringMat);
this.orbitRing.rotation.x = Math.PI / 2;
// Create ring mesh if enabled
this.ringMesh = null;
if (this.hasRings) {
this.updateRings();
}
}
setParent(newParent) {
if (this.parentBody && this.parentBody.childrenBodies) {
const idx = this.parentBody.childrenBodies.indexOf(this);
if (idx > -1) this.parentBody.childrenBodies.splice(idx, 1);
}
this.parentBody = newParent;
if (newParent instanceof CelestialBody) {
newParent.childrenBodies.push(this);
newParent.holder.add(this.pivot);
newParent.holder.add(this.orbitRing);
} else {
scene.add(this.pivot);
scene.add(this.orbitRing);
}
this.pivot.position.set(0,0,0);
this.pivot.rotation.set(0,0,0);
// Ensure rings stay with the body
if (this.ringMesh) {
this.ringMesh.removeFromParent();
this.holder.add(this.ringMesh);
}
}
update(dt) {
this.material.uniforms.time.value += dt;
this.mesh.rotation.y += dt * 0.5;
if (this.orbitDistance > 0.1) {
this.orbitAngle += this.orbitSpeed * dt * 0.5;
this.pivot.rotation.y = this.orbitAngle;
this.holder.position.set(this.orbitDistance, 0, 0);
this.orbitRing.visible = true;
this.orbitRing.scale.setScalar(this.orbitDistance);
} else {
this.holder.position.set(0,0,0);
this.orbitRing.visible = false;
}
const worldPos = new THREE.Vector3();
this.mesh.getWorldPosition(worldPos);
const sunDir = worldPos.clone().multiplyScalar(-1).normalize();
this.material.uniforms.sunDirection.value.copy(sunDir);
// Update ring shader if it exists
if (this.ringMesh) {
const worldPos = new THREE.Vector3();
this.mesh.getWorldPosition(worldPos);
// Rings need to match the body's current scale and position
this.ringMesh.position.copy(this.mesh.position);
}
}
// Ring update method
updateRings() {
if (this.ringMesh) {
this.holder.remove(this.ringMesh);
this.ringMesh = null;
}
if (!this.hasRings) return;
const planetRadius = parseFloat(this.data.params.radius);
const innerRadius = planetRadius * 1.2;
const outerRadius = planetRadius * this.ringDiameter;
// Create ring geometry (match PlanetEditor logic)
let ringGeometry;
if (this.data.mode === 'cube') {
// Square rings for cube planets
const shape = new THREE.Shape();
const hole = new THREE.Path();
shape.moveTo(-outerRadius, -outerRadius);
shape.lineTo(outerRadius, -outerRadius);
shape.lineTo(outerRadius, outerRadius);
shape.lineTo(-outerRadius, outerRadius);
shape.lineTo(-outerRadius, -outerRadius);
hole.moveTo(-innerRadius, -innerRadius);
hole.lineTo(innerRadius, -innerRadius);
hole.lineTo(innerRadius, innerRadius);
hole.lineTo(-innerRadius, innerRadius);
hole.lineTo(-innerRadius, -innerRadius);
shape.holes.push(hole);
ringGeometry = new THREE.ShapeGeometry(shape);
ringGeometry.rotateX(-Math.PI / 2);
} else {
// Circular rings
ringGeometry = new THREE.RingGeometry(innerRadius, outerRadius, 128, 8);
}
// Ring shader material
const ringMaterial = new THREE.ShaderMaterial({
uniforms: {
innerColor: { value: new THREE.Color(this.ringColorInner) },
outerColor: { value: new THREE.Color(this.ringColorOuter) },
innerRadius: { value: innerRadius },
outerRadius: { value: outerRadius }
},
vertexShader: `
varying vec2 vUv;
varying float vDist;
void main() {
vUv = uv;
vDist = length(position.xy);
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 innerColor;
uniform vec3 outerColor;
uniform float innerRadius;
uniform float outerRadius;
varying vec2 vUv;
varying float vDist;
void main() {
float t = (vDist - innerRadius) / (outerRadius - innerRadius);
vec3 color = mix(innerColor, outerColor, t);
float bands = sin(t * 80.0) * sin(t * 40.0) * sin(t * 120.0);
float density = 0.6 + 0.4 * bands;
float edgeFade = smoothstep(0.0, 0.1, t) * smoothstep(1.0, 0.9, t);
gl_FragColor = vec4(color, density * edgeFade * 0.8);
}
`,
transparent: true,
side: THREE.DoubleSide,
depthWrite: false
});
this.ringMesh = new THREE.Mesh(ringGeometry, ringMaterial);
this.ringMesh.rotation.y = 0.3; // Match PlanetEditor tilt
this.holder.add(this.ringMesh);
}
// Start catastrophic death spiral
startDeathSpiral() {
// Get current world position before detaching
const worldPos = new THREE.Vector3();
this.mesh.getWorldPosition(worldPos);
// Remove from parent hierarchy
this.pivot.removeFromParent();
this.orbitRing.removeFromParent();
// Add directly to scene at world position
scene.add(this.mesh);
this.mesh.position.copy(worldPos);
// Random velocity direction (tangent to orbit + outward + some chaos)
const outward = worldPos.clone().normalize();
const tangent = new THREE.Vector3(-outward.z, 0, outward.x);
const chaos = new THREE.Vector3(
(Math.random() - 0.5) * 2,
(Math.random() - 0.5) * 0.5,
(Math.random() - 0.5) * 2
);
this.deathVelocity = tangent.multiplyScalar(15 + Math.random() * 10)
.add(outward.multiplyScalar(5 + Math.random() * 8))
.add(chaos.multiplyScalar(5));
// Random tumble spin
this.deathSpin = new THREE.Vector3(
(Math.random() - 0.5) * 8,
(Math.random() - 0.5) * 8,
(Math.random() - 0.5) * 8
);
this.deathTime = 0;
this.deathDuration = 3 + Math.random() * 2; // 3-5 seconds
this.isDying = true;
}
// Update during death spiral
updateDeath(dt) {
if (!this.isDying) return false;
this.deathTime += dt;
const progress = this.deathTime / this.deathDuration;
// Move outward with velocity
this.mesh.position.add(this.deathVelocity.clone().multiplyScalar(dt));
// Accelerate slightly (gravitational slingshot feel)
this.deathVelocity.multiplyScalar(1 + dt * 0.3);
// Tumble faster and faster
this.mesh.rotation.x += this.deathSpin.x * dt * (1 + progress);
this.mesh.rotation.y += this.deathSpin.y * dt * (1 + progress);
this.mesh.rotation.z += this.deathSpin.z * dt * (1 + progress);
// Fade out using shader uniform
const opacity = Math.max(0, 1 - progress);
this.material.uniforms.opacity.value = opacity;
// Shrink slightly as it dies
const scale = this.mesh.scale.x * (1 - dt * 0.2);
this.mesh.scale.setScalar(Math.max(0.1, scale));
// Return true if death is complete
if (progress >= 1) {
scene.remove(this.mesh);
this.mesh.geometry.dispose();
this.mesh.material.dispose();
return true; // Remove from dying list
}
return false;
}
}
// --- APP STATE ---
const bodies = [];
let selectedBody = null;
let bodyCounter = 0;
const dyingBodies = []; // Bodies in death spiral
let hasEverAddedBody = false; // Track if user has ever added a body (for welcome screen)
// --- UI LOGIC ---
const $ = (id) => document.getElementById(id);
const listEl = $('bodyList');
const welcomeEl = $('welcome');
$('btnImport').onclick = () => $('fileInput').click();
// --- RANDOM GENERATION (matching PlanetEditor logic) ---
function generateRandomName() {
const prefixes = ['Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon', 'Zeta', 'Theta', 'Nova', 'Sol', 'Vega', 'Rigel', 'Sirius', 'Altair', 'Deneb', 'Polaris', 'Antares', 'Proxima', 'Kepler', 'Trappist', 'Gliese'];
const suffixes = ['Prime', 'Major', 'Minor', 'X', 'IX', 'VII', 'III', 'IV', 'V', 'VI', 'A', 'B', 'C'];
const numbers = ['', '-1', '-2', '-3', '-4', '-5', ' 47', ' 51', ' 186', ' 442'];
return prefixes[Math.floor(Math.random() * prefixes.length)] +
(Math.random() > 0.5 ? ' ' + suffixes[Math.floor(Math.random() * suffixes.length)] : '') +
numbers[Math.floor(Math.random() * numbers.length)];
}
function generateRandomBodyData(type, rng) {
const seed = generateRandomName();
// Base parameters (from PlanetEditor defaults)
let params = {
radius: type === 'sun' ? (1.2 + rng() * 0.8).toFixed(2) :
type === 'moon' ? (0.3 + rng() * 0.3).toFixed(2) :
(0.5 + rng() * 0.8).toFixed(2),
warpScale: (rng() * 0.16).toFixed(2),
heightScale: type === 'sun' ? '0.030' : (0.04 + rng() * 0.08).toFixed(3),
frequency: (0.5 + rng() * 2.0).toFixed(2),
octaves: Math.floor(3 + rng() * 4).toString(),
persistence: (0.1 + rng() * 0.3).toFixed(2),
ridge: (rng() * 0.3).toFixed(2),
oceanLevel: type === 'sun' ? '-1.0' :
type === 'moon' ? '-1.0' :
(0.1 - rng() * 1.5).toFixed(2),
snowLevel: (0.45 + rng() * 0.3).toFixed(2),
moistureOffset: ((rng() - 0.5) * 0.6).toFixed(2),
texMix: '0',
waterNoise: type === 'planet',
enableTrees: type === 'planet' && rng() > 0.3,
treeDensity: type === 'planet' ? Math.floor(rng() * 60).toString() : '0',
treeSize: '1.0'
};
// Generate colors based on type (from PlanetEditor randomizeBiomeColors)
let colors;
if (type === 'sun') {
colors = {
ocean: '#ffaa00',
beach: '#ff8800',
grass: '#ff4400',
rock: '#aa2200',
snow: '#ffffaa'
};
} else if (type === 'moon') {
colors = {
ocean: '#000000',
beach: '#' + new THREE.Color().setHSL(0, 0, 0.2 + rng() * 0.2).getHexString(),
grass: '#' + new THREE.Color().setHSL(0, 0, 0.3 + rng() * 0.2).getHexString(),
rock: '#' + new THREE.Color().setHSL(0, 0, 0.5 + rng() * 0.3).getHexString(),
snow: '#ffffff'
};
} else {
const oceanH = 180 + rng() * 60;
const beachH = 30 + rng() * 30;
const grassH = rng() * 360;
const rockH = rng() < 0.5 ? 30 + rng() * 20 : 0;
colors = {
ocean: '#' + new THREE.Color().setHSL(oceanH / 360, 0.3 + rng() * 0.4, 0.65 + rng() * 0.2).getHexString(),
beach: '#' + new THREE.Color().setHSL(beachH / 360, 0.4 + rng() * 0.3, 0.75 + rng() * 0.15).getHexString(),
grass: '#' + new THREE.Color().setHSL(grassH / 360, 0.4 + rng() * 0.4, 0.3 + rng() * 0.3).getHexString(),
rock: '#' + new THREE.Color().setHSL(rockH / 360, 0.1 + rng() * 0.2, 0.4 + rng() * 0.2).getHexString(),
snow: '#' + new THREE.Color().setHSL(0, 0, 0.9 + rng() * 0.1).getHexString()
};
}
return {
seed: seed,
type: type,
mode: 'quad',
hasHeightMap: false,
params: params,
colors: colors
};
}
function generateRandomSolarSystem() {
// Clear existing bodies
while (bodies.length > 0) {
const body = bodies.pop();
body.pivot.removeFromParent();
body.orbitRing.removeFromParent();
}
selectedBody = null;
$('detailPanel').style.display = 'none';
const masterSeed = Date.now();
const seedHash = cyrb128(masterSeed.toString());
const rng = mulberry32(seedHash[0]);
// Helper: get body from library or generate procedurally
function getOrGenerateBody(type) {
const libraryBody = getLibraryBody(type, rng);
if (libraryBody) {