Spaces:
Running

File size: 28,435 Bytes
929e2a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Plasma, aurora, plume and atmosphere effects for each moon.
//
// Everything is built in the moon's own frame, in units of the moon's radius, and the group is
// attached to the (tidally locked) moon mesh. In that frame the direction to the planet is +x and
// the planet's spin axis is +y. Corotating magnetospheric plasma moves faster than the moon, so it
// overtakes the moon from behind: the flow runs along +z, hitting the trailing hemisphere and
// leaving a wake ahead of the moon. Earth's Moon instead sits in the solar wind (flow mode 'sun').

import * as THREE from 'three';

const TAU = Math.PI * 2;
const D = Math.PI / 180;

/* ---------------------------------------------------------------- config */
// halo: [r,g,b,opacity] glow that makes the moon visible from far away
// flow: background plasma flowing past (obs = obstacle radius it is deflected around)
// tail: pick-up ions stripped from the moon and carried downstream
// shells: glowing atmosphere/aurora shells (atmo limb glow, spots, ovals, lens)
// plumes: volcanoes / geysers; wings: Alfvén wings; minimag: Ganymede's magnetosphere
// drape: field draping (Titan); cloud: neutral cloud along the orbit
const FX = {
  moon: {
    halo: [0.55, 0.6, 0.75, 0.12],
    flow: { mode: 'sun', n: 170, obs: 1.02, c: [1.0, 0.85, 0.55], label: 'solarwind' },
    wake: true,
    shells: [{ r: 1.02, atmo: [0.65, 0.7, 1.0], a: 0.18 }]
  },
  io: {
    halo: [1.0, 0.6, 0.25, 0.5],
    flow: { n: 240, obs: 1.15 },
    tail: { n: 260, c: [1.0, 0.7, 0.3], len: 7 },
    shells: [{ r: 1.03, atmo: [1.0, 0.35, 0.3], a: 1.1, spots: 1.5, c1: [1.0, 0.3, 0.25], c2: [0.5, 0.6, 1.0], c3: [0.4, 1.0, 0.5], rock: 0.6, label: 'spots' }],
    plumes: {
      type: 'umbrella', label: 'volcano', h: 0.32, n: 55,
      vents: [[-19, 170], [15, 140], [35, -150], [-40, -140], [5, 110], [50, 180], [-5, -110], [10, 95], [-25, -95]],
      colors: [[0.55, 0.75, 1.0], [0.55, 0.75, 1.0], [1.0, 0.5, 0.3]]
    },
    wings: { c: [1.0, 0.85, 0.45], r: 1.1 },
    cloud: { c: [1.0, 0.72, 0.28], arc: 1.2, tube: 0.13, a: 0.55, label: 'sodium' }
  },
  europa: {
    halo: [0.6, 0.75, 1.0, 0.28],
    flow: { n: 210, obs: 1.08 },
    tail: { n: 170, c: [0.5, 0.85, 1.0], len: 6 },
    shells: [{ r: 1.03, atmo: [0.55, 0.6, 1.0], a: 0.6, spots: 0.95, c1: [0.75, 0.5, 1.0], c2: [0.5, 0.7, 1.0], c3: [0.75, 0.5, 1.0], rock: 0.5, label: 'spots' }],
    plumes: { type: 'umbrella', label: 'plume', h: 0.45, n: 80, vents: [[-60, 175]], colors: [[0.75, 0.9, 1.0]] },
    wings: { c: [0.7, 0.8, 1.0], r: 1.1 }
  },
  ganymede: {
    halo: [0.7, 0.6, 1.0, 0.32],
    flow: { n: 280, obs: 2.15 },
    shells: [{ r: 1.03, atmo: [0.6, 0.6, 1.0], a: 0.5, oval: 1.4, ovalLat: 0.75, c1: [0.8, 0.45, 1.0], c2: [0.45, 0.7, 1.0], rock: 0.5, label: 'aurora' }],
    minimag: { c: [0.6, 0.55, 1.0] },
    wings: { c: [0.8, 0.7, 1.0], r: 2.1 }
  },
  callisto: {
    halo: [0.6, 0.7, 0.9, 0.15],
    flow: { n: 190, obs: 1.12 },
    tail: { n: 90, c: [0.6, 0.8, 1.0], len: 5 },
    shells: [{ r: 1.03, atmo: [0.65, 0.7, 1.0], a: 0.4, spots: 0.35, c1: [0.7, 0.6, 1.0], c2: [0.6, 0.7, 1.0], c3: [0.7, 0.6, 1.0], rock: 0.3, label: 'spots' }]
  },
  mimas: {
    halo: [0.7, 0.75, 0.9, 0.1], flow: { n: 130, obs: 1.02 },
    shells: [{ r: 1.02, atmo: [0.6, 0.7, 1.0], a: 0.15, lens: 0.9, lensSide: 1, lensC: [0.4, 0.8, 1.0], label: 'lens' }]
  },
  enceladus: {
    halo: [0.6, 0.85, 1.0, 0.45],
    flow: { n: 190, obs: 1.25 },
    tail: { n: 200, c: [0.45, 0.7, 1.0], len: 7 },
    shells: [{ r: 1.03, atmo: [0.6, 0.8, 1.0], a: 0.5 }],
    plumes: {
      type: 'jets', label: 'geysers', n: 70,
      vents: [[-82, 0], [-80, 60], [-84, 120], [-79, 180], [-83, 240], [-78, 300], [-87, 30]],
      colors: [[0.85, 0.95, 1.0], [0.6, 0.8, 1.0]]
    },
    wings: { c: [0.6, 0.85, 1.0], r: 1.3 },
    cloud: { c: [0.5, 0.75, 1.0], arc: 1.0, tube: 0.12, a: 0.42, label: 'neutral' }
  },
  tethys: {
    halo: [0.7, 0.75, 0.9, 0.1], flow: { n: 140, obs: 1.02 },
    shells: [{ r: 1.02, atmo: [0.6, 0.7, 1.0], a: 0.15, lens: 0.8, lensSide: 1, lensC: [0.4, 0.8, 1.0], label: 'lens' }]
  },
  dione: {
    halo: [0.65, 0.75, 0.95, 0.14], flow: { n: 150, obs: 1.04 }, tail: { n: 60, c: [0.55, 0.8, 1.0], len: 4 },
    shells: [{ r: 1.03, atmo: [0.6, 0.75, 1.0], a: 0.35, lens: 0.3, lensSide: 1, lensC: [0.4, 0.8, 1.0], label: 'exo' }]
  },
  rhea: {
    halo: [0.65, 0.75, 0.95, 0.14], flow: { n: 160, obs: 1.04 }, tail: { n: 60, c: [0.55, 0.8, 1.0], len: 4 },
    shells: [{ r: 1.03, atmo: [0.6, 0.75, 1.0], a: 0.4, label: 'exo' }]
  },
  titan: {
    halo: [1.0, 0.65, 0.3, 0.42],
    flow: { n: 270, obs: 1.7, c: [0.55, 0.8, 1.0] },
    tail: { n: 230, c: [0.4, 0.7, 1.0], len: 8 },
    shells: [
      { r: 1.12, atmo: [1.0, 0.6, 0.25], a: 1.6, label: 'haze' },
      { r: 1.35, atmo: [0.35, 0.6, 1.0], a: 0.35 }
    ],
    drape: { c: [0.4, 0.85, 1.0] }
  },
  iapetus: {
    halo: [0.7, 0.7, 0.8, 0.08], flow: { n: 100, obs: 1.02 },
    shells: [{ r: 1.02, atmo: [0.6, 0.7, 1.0], a: 0.12 }]
  },
  miranda: { halo: [0.55, 0.95, 0.9, 0.1], flow: { n: 130, obs: 1.02, c: [0.55, 0.95, 0.9] }, shells: [{ r: 1.02, atmo: [0.5, 0.9, 0.9], a: 0.15 }] },
  ariel: {
    halo: [0.55, 0.95, 0.9, 0.14], flow: { n: 140, obs: 1.03, c: [0.55, 0.95, 0.9] },
    shells: [{ r: 1.02, atmo: [0.5, 0.9, 0.9], a: 0.18, lens: 0.7, lensSide: -1, lensC: [0.5, 1.0, 0.8], label: 'co2' }]
  },
  umbriel: { halo: [0.55, 0.95, 0.9, 0.08], flow: { n: 130, obs: 1.02, c: [0.55, 0.95, 0.9] }, shells: [{ r: 1.02, atmo: [0.5, 0.9, 0.9], a: 0.12 }] },
  titania: { halo: [0.55, 0.95, 0.9, 0.12], flow: { n: 140, obs: 1.03, c: [0.55, 0.95, 0.9] }, tail: { n: 50, c: [0.5, 1.0, 0.85], len: 4 }, shells: [{ r: 1.02, atmo: [0.5, 0.9, 0.9], a: 0.2 }] },
  oberon: { halo: [0.55, 0.95, 0.9, 0.1], flow: { n: 130, obs: 1.02, c: [0.55, 0.95, 0.9] }, shells: [{ r: 1.02, atmo: [0.5, 0.9, 0.9], a: 0.15 }] },
  triton: {
    halo: [0.6, 0.85, 1.0, 0.28],
    flow: { n: 210, obs: 1.15 },
    tail: { n: 150, c: [0.6, 0.9, 1.0], len: 6 },
    shells: [{ r: 1.04, atmo: [0.55, 0.75, 1.0], a: 0.6, oval: 0.6, ovalLat: 1.05, c1: [0.5, 0.9, 1.0], c2: [0.7, 0.6, 1.0], rock: 0.4, label: 'aurora' }],
    plumes: { type: 'geyser', label: 'n2geysers', h: 0.3, n: 45, vents: [[-50, 170], [-58, 140], [-55, -160], [-48, -130]], colors: [[0.75, 0.75, 0.8]] }
  }
};

// Labels shown for a moon, in display order (keys under fx.* in the i18n files).
export function moonFxKeys(key) {
  const f = FX[key];
  if (!f) return [];
  const out = [];
  if (f.plumes) out.push(f.plumes.label);
  f.shells?.forEach(s => s.label && out.push(s.label));
  if (f.minimag) out.push('minimag');
  if (f.drape) out.push('drape');
  if (f.wings) out.push('wings');
  if (f.tail) out.push('tail');
  if (f.cloud) out.push(f.cloud.label);
  if (f.flow) out.push(f.flow.label || 'flow');
  if (f.wake) out.push('wake');
  return out;
}

/* ------------------------------------------------------------ materials */
let GLOW = null;
function glowTex() {
  if (GLOW) return GLOW;
  const c = document.createElement('canvas'); c.width = c.height = 64;
  const g = c.getContext('2d');
  const r = g.createRadialGradient(32, 32, 0, 32, 32, 32);
  r.addColorStop(0, 'rgba(255,255,255,1)'); r.addColorStop(0.3, 'rgba(255,255,255,0.45)'); r.addColorStop(1, 'rgba(255,255,255,0)');
  g.fillStyle = r; g.fillRect(0, 0, 64, 64);
  GLOW = new THREE.CanvasTexture(c);
  return GLOW;
}

const additive = { transparent: true, depthWrite: false, blending: THREE.AdditiveBlending };

function pointsMaterial(size) {
  return new THREE.PointsMaterial({ size, map: glowTex(), vertexColors: true, ...additive });
}

const NOISE = /* glsl */`
float h3(vec3 p){ p = fract(p*0.3183099 + 0.1); p *= 17.0; return fract(p.x*p.y*p.z*(p.x+p.y+p.z)); }
float n3(vec3 x){ vec3 i = floor(x); vec3 f = fract(x); f = f*f*(3.0-2.0*f);
  return mix(mix(mix(h3(i), h3(i+vec3(1,0,0)), f.x), mix(h3(i+vec3(0,1,0)), h3(i+vec3(1,1,0)), f.x), f.y),
             mix(mix(h3(i+vec3(0,0,1)), h3(i+vec3(1,0,1)), f.x), mix(h3(i+vec3(0,1,1)), h3(i+vec3(1,1,1)), f.x), f.y), f.z); }`;

function shellMaterial(s) {
  const v3 = a => new THREE.Vector3(...(a || [0, 0, 0]));
  return new THREE.ShaderMaterial({
    uniforms: {
      uTime: { value: 0 }, uAur: { value: 1 },
      uAtmoC: { value: v3(s.atmo) }, uAtmo: { value: s.a || 0 },
      uSpots: { value: s.spots || 0 }, uOval: { value: s.oval || 0 }, uOvalLat: { value: s.ovalLat || 0.8 },
      uRock: { value: s.rock || 0.5 },
      uLens: { value: s.lens || 0 }, uLensSide: { value: s.lensSide || 1 }, uLensC: { value: v3(s.lensC) },
      uC1: { value: v3(s.c1) }, uC2: { value: v3(s.c2) }, uC3: { value: v3(s.c3 || s.c1) }
    },
    vertexShader: /* glsl */`
      varying vec3 vObj; varying vec3 vN; varying vec3 vV;
      void main(){
        vObj = position;
        vN = normalize(mat3(modelMatrix) * normal);
        vec4 wp = modelMatrix * vec4(position, 1.0);
        vV = cameraPosition - wp.xyz;
        gl_Position = projectionMatrix * viewMatrix * wp;
      }`,
    fragmentShader: /* glsl */`
      uniform float uTime, uAur, uAtmo, uSpots, uOval, uOvalLat, uRock, uLens, uLensSide;
      uniform vec3 uAtmoC, uLensC, uC1, uC2, uC3;
      varying vec3 vObj; varying vec3 vN; varying vec3 vV;
      ${NOISE}
      void main(){
        vec3 n = normalize(vObj);
        float mu = abs(dot(normalize(vN), normalize(vV)));
        float limb = pow(1.0 - mu, 2.5);
        vec3 col = uAtmoC * (limb * 1.4 + 0.04) * uAtmo;
        // auroral ovals around both poles; they rock back and forth as the planet's field sweeps past
        if (uOval > 0.0) {
          float lat = asin(clamp(n.y, -1.0, 1.0));
          float lon = atan(n.z, n.x);
          float rock = 0.07 * sin(uTime * uRock) * sign(lat);
          float d = (abs(lat) - uOvalLat - rock - 0.06 * n.z) / 0.085;
          float band = exp(-d*d) * (0.45 + 0.9 * n3(vec3(cos(lon)*3.0, sin(lon)*3.0, uTime*0.45 + sign(lat)*4.0)));
          col += mix(uC1, uC2, 0.5 + 0.5*n.z) * band * uOval * (0.7 + 1.2*limb) * uAur;
        }
        // bright equatorial spots facing towards and away from the planet (Io, Europa, Callisto)
        if (uSpots > 0.0) {
          float r = 0.32 * sin(uTime * uRock);
          vec3 a = normalize(vec3(1.0, r, 0.15)), b = normalize(vec3(-1.0, -r, 0.15));
          float da = length(n - a), db = length(n - b);
          float sa = exp(-da*da / 0.07), sb = exp(-db*db / 0.07);
          float flick = 0.75 + 0.25 * sin(uTime*3.1 + n.y*5.0) * n3(n*6.0 + uTime*0.8);
          col += (uC1*sa + uC3*sb) * uSpots * flick * uAur;
          col += uC2 * (sa + sb) * 0.6 * uSpots * limb * uAur;
        }
        // lens-shaped pattern where energetic electrons hit one hemisphere (Mimas, Tethys) / CO2 on Ariel
        if (uLens > 0.0) {
          float lens = exp(-pow(n.y / 0.38, 2.0)) * smoothstep(0.15, 0.75, n.z * uLensSide);
          col += uLensC * lens * uLens * (0.35 + 0.65 * n3(n*9.0 + uTime*0.15));
        }
        gl_FragColor = vec4(col, 1.0);
      }`,
    ...additive
  });
}

function lineMaterial(color, opacity = 0.75, speed = 0.6) {
  return new THREE.ShaderMaterial({
    uniforms: { uTime: { value: 0 }, uColor: { value: new THREE.Color(...color) }, uOpacity: { value: opacity }, uSpeed: { value: speed } },
    vertexShader: /* glsl */`
      attribute float aT; varying float vT;
      void main(){ vT = aT; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
    fragmentShader: /* glsl */`
      uniform float uTime, uOpacity, uSpeed; uniform vec3 uColor; varying float vT;
      void main(){
        float p = pow(fract(vT*4.0 - uTime*uSpeed), 8.0);
        float f = 1.0 - smoothstep(0.65, 1.0, vT);
        gl_FragColor = vec4(uColor * (0.22 + p*1.9) * uOpacity * f, 1.0);
      }`,
    ...additive
  });
}

function fresnelMaterial(color, strength) {
  return new THREE.ShaderMaterial({
    uniforms: { uColor: { value: new THREE.Color(...color) }, uS: { value: strength }, uTime: { value: 0 } },
    vertexShader: /* glsl */`
      varying vec3 vN; varying vec3 vV; varying vec3 vObj;
      void main(){ vObj = position; vN = normalize(mat3(modelMatrix) * normal); vec4 wp = modelMatrix * vec4(position, 1.0); vV = cameraPosition - wp.xyz; gl_Position = projectionMatrix * viewMatrix * wp; }`,
    fragmentShader: /* glsl */`
      uniform vec3 uColor; uniform float uS, uTime; varying vec3 vN; varying vec3 vV; varying vec3 vObj;
      void main(){ float f = pow(1.0 - abs(dot(normalize(vN), normalize(vV))), 2.2);
        float w = 0.8 + 0.2 * sin(vObj.z*3.0 - uTime*2.0);
        gl_FragColor = vec4(uColor * f * uS * w, 1.0); }`,
    side: THREE.DoubleSide, ...additive
  });
}

function cloudMaterial(color, opacity) {
  return new THREE.ShaderMaterial({
    uniforms: { uColor: { value: new THREE.Color(...color) }, uOpacity: { value: opacity }, uTime: { value: 0 } },
    vertexShader: /* glsl */`
      varying vec2 vUv; varying vec3 vN; varying vec3 vV;
      void main(){ vUv = uv; vN = normalize(mat3(modelMatrix) * normal); vec4 wp = modelMatrix * vec4(position, 1.0); vV = cameraPosition - wp.xyz; gl_Position = projectionMatrix * viewMatrix * wp; }`,
    fragmentShader: /* glsl */`
      uniform vec3 uColor; uniform float uOpacity, uTime; varying vec2 vUv; varying vec3 vN; varying vec3 vV;
      void main(){
        float u = vUv.x;
        float along = smoothstep(0.0, 0.05, u) * pow(1.0 - u, 1.7);
        float core = pow(abs(dot(normalize(vN), normalize(vV))), 1.3);
        float shimmer = 0.85 + 0.15 * sin(u * 40.0 - uTime * 1.5);
        gl_FragColor = vec4(uColor * along * core * shimmer * uOpacity, 1.0);
      }`,
    ...additive
  });
}

function linesGeometry(polys) {
  const pos = [], at = [];
  polys.forEach(({ pts, t }) => {
    for (let i = 1; i < pts.length; i++) {
      const a = pts[i - 1], b = pts[i];
      pos.push(a.x, a.y, a.z, b.x, b.y, b.z);
      at.push(t[i - 1], t[i]);
    }
  });
  const g = new THREE.BufferGeometry();
  g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
  g.setAttribute('aT', new THREE.Float32BufferAttribute(at, 1));
  return g;
}

function ventDir([lat, lon]) {
  return new THREE.Vector3(Math.cos(lat * D) * Math.cos(lon * D), Math.sin(lat * D), Math.cos(lat * D) * Math.sin(lon * D));
}

function makePoints(n, size) {
  const g = new THREE.BufferGeometry();
  g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(n * 3), 3));
  g.setAttribute('color', new THREE.BufferAttribute(new Float32Array(n * 3), 3));
  const p = new THREE.Points(g, pointsMaterial(size));
  p.frustumCulled = false;
  return p;
}

/* ------------------------------------------------------------- builder */
const DEFAULT_FLOW = [0.6, 0.75, 1.0];
const tmpQ = new THREE.Quaternion(), tmpV = new THREE.Vector3(), Z = new THREE.Vector3(0, 0, 1);

export function createMoonFX(key, { size, dist, holder }) {
  const f = FX[key];
  if (!f) return null;
  const group = new THREE.Group();
  group.scale.setScalar(size);
  const flowFrame = new THREE.Group();    // +z = direction of the plasma flow
  group.add(flowFrame);
  const anchors = [];                     // { key, obj, aurora }
  const anchor = (k, parent, x, y, z, aurora = false) => {
    const o = new THREE.Object3D(); o.position.set(x, y, z); parent.add(o); anchors.push({ key: k, obj: o, aurora });
  };
  const timed = [];                       // materials with uTime
  const updaters = [];

  let halo = null;
  // halo, so the moon stands out at planet scale
  if (f.halo) {
    const [r, g, b, a] = f.halo;
    const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTex(), color: new THREE.Color(r, g, b), opacity: a, ...additive }));
    sp.scale.set(5, 5, 1);
    group.add(sp);
    halo = sp;
  }

  // atmosphere / aurora shells
  const shellMats = [];
  f.shells?.forEach(s => {
    const m = shellMaterial(s);
    const mesh = new THREE.Mesh(new THREE.SphereGeometry(s.r, 64, 32), m);
    mesh.renderOrder = 2;
    group.add(mesh);
    shellMats.push(m); timed.push(m);
    if (s.label) {
      if (s.label === 'spots') anchor(s.label, group, -1.15, 0.45, 0.2, true);
      else if (s.label === 'aurora') anchor(s.label, group, 0, 1.25, 0.2, true);
      else if (s.label === 'lens' || s.label === 'co2') anchor(s.label, group, 0, -0.35, 1.3 * (s.lensSide || 1));
      else if (s.label === 'haze') anchor(s.label, group, -0.4, 1.3, 0);
      else anchor(s.label, group, 0, -1.3, 0);
    }
  });

  // background plasma flow, deflected around the obstacle
  if (f.flow) {
    const n = f.flow.n, obs = f.flow.obs, col = f.flow.c || DEFAULT_FLOW;
    const pts = makePoints(n, size * 0.16);
    flowFrame.add(pts);
    const P = pts.geometry.attributes.position.array, C = pts.geometry.attributes.color.array;
    const Z0 = -5, Z1 = 5, RAD = Math.max(3.4, obs * 1.9);
    const spawn = (i, anywhere) => {
      const a = Math.random() * TAU, r = Math.sqrt(Math.random()) * RAD;
      P[i * 3] = Math.cos(a) * r; P[i * 3 + 1] = Math.sin(a) * r;
      P[i * 3 + 2] = anywhere ? Z0 + Math.random() * (Z1 - Z0) : Z0 - Math.random() * 0.5;
    };
    for (let i = 0; i < n; i++) spawn(i, true);
    updaters.push((dt, sp) => {
      const v = 1.4 * dt * sp;
      for (let i = 0; i < n; i++) {
        const k = i * 3;
        let x = P[k], y = P[k + 1], z = P[k + 2] + v;
        let r = Math.hypot(x, y, z);
        if (r < obs) { const s = obs * 1.01 / r; x *= s; y *= s; z *= s; r = obs * 1.01; }
        if (z > Z1) { spawn(i, false); continue; }
        P[k] = x; P[k + 1] = y; P[k + 2] = z;
        const edge = Math.min(1, (z - Z0) / 1.2, (Z1 - z) / 1.5) * Math.max(0, 1 - Math.hypot(x, y) / RAD);
        const pile = Math.exp(-(((r - obs) / 0.45) ** 2)) * (z < 0.3 ? 1.6 : 0.5);
        const b = (0.28 + pile) * Math.max(0, edge);
        C[k] = col[0] * b; C[k + 1] = col[1] * b; C[k + 2] = col[2] * b;
      }
      pts.geometry.attributes.position.needsUpdate = true;
      pts.geometry.attributes.color.needsUpdate = true;
    });
    anchor(f.flow.label || 'flow', flowFrame, 0, Math.min(RAD, 2.6), -3.2);
    if (f.wake) anchor('wake', flowFrame, 0, 0.35, 3.0);
  }

  // pick-up ions: gas from the moon is ionised and swept downstream in a helical tail
  if (f.tail) {
    const n = f.tail.n, col = f.tail.c, len = f.tail.len;
    const pts = makePoints(n, size * 0.14);
    flowFrame.add(pts);
    const P = pts.geometry.attributes.position.array, C = pts.geometry.attributes.color.array;
    const S = new Float32Array(n * 5); // bx, by, z, vz, phase
    const spawn = (i, anywhere) => {
      const u = Math.random() * 2 - 1, a = Math.random() * TAU, rr = 1.05 + Math.random() * 0.25;
      const s = Math.sqrt(1 - u * u);
      S[i * 5] = Math.cos(a) * s * rr; S[i * 5 + 1] = Math.sin(a) * s * rr;
      S[i * 5 + 2] = anywhere ? Math.random() * len : u * rr;
      S[i * 5 + 3] = anywhere ? 0.6 + Math.random() * 0.6 : 0.05;
      S[i * 5 + 4] = Math.random() * TAU;
    };
    for (let i = 0; i < n; i++) spawn(i, true);
    updaters.push((dt, sp) => {
      const d = dt * sp;
      for (let i = 0; i < n; i++) {
        const s = i * 5, k = i * 3;
        S[s + 3] = Math.min(1.8, S[s + 3] + 0.9 * d);
        S[s + 2] += S[s + 3] * d;
        S[s + 4] += 5.0 * d;
        const z = S[s + 2];
        if (z > len) { spawn(i, false); continue; }
        const grow = Math.min(1, Math.max(0, z + 1) / 2);
        const rg = 0.18 * grow, spread = 1 + 0.12 * Math.max(0, z);
        P[k] = S[s] * spread + rg * Math.cos(S[s + 4]);
        P[k + 1] = S[s + 1] * spread + rg * Math.sin(S[s + 4]);
        P[k + 2] = z;
        const b = 1.1 * Math.max(0, 1 - z / len) * Math.min(1, (z + 1.3) / 0.8);
        C[k] = col[0] * b; C[k + 1] = col[1] * b; C[k + 2] = col[2] * b;
      }
      pts.geometry.attributes.position.needsUpdate = true;
      pts.geometry.attributes.color.needsUpdate = true;
    });
    anchor('tail', flowFrame, 0, 0.9, len * 0.62);
  }

  // volcanic plumes (ballistic umbrellas), Enceladus jets, Triton geysers
  if (f.plumes) {
    const pl = f.plumes, vents = pl.vents.map(ventDir), nv = vents.length, per = pl.n, n = nv * per;
    const sizeK = pl.type === 'jets' ? 0.12 : pl.type === 'geyser' ? 0.1 : 0.13;
    const pts = makePoints(n, size * sizeK);
    group.add(pts);
    const P = pts.geometry.attributes.position.array, C = pts.geometry.attributes.color.array;
    const V = new Float32Array(n * 3), A = new Float32Array(n * 3); // vel; age, life, palette
    const g = pl.type === 'jets' ? 0.22 : 1.6;
    const v0 = pl.type === 'jets' ? 2.0 : Math.sqrt(2 * g * (pl.h || 0.3));
    const winds = vents.map(nv_ => new THREE.Vector3(0, 1, 0).cross(nv_).normalize().multiplyScalar(0.28));
    const spawn = (i, anywhere) => {
      const vi = (i / per) | 0, nvec = vents[vi];
      const t1 = tmpV.set(0, 1, 0).cross(nvec); if (t1.lengthSq() < 1e-4) t1.set(1, 0, 0); t1.normalize();
      const t2 = new THREE.Vector3().crossVectors(nvec, t1);
      const a = Math.random() * TAU, sp = (pl.type === 'jets' ? 0.18 : 0.38) * Math.random();
      const k = i * 3;
      P[k] = nvec.x * 1.0; P[k + 1] = nvec.y * 1.0; P[k + 2] = nvec.z * 1.0;
      const vv = v0 * (0.75 + Math.random() * 0.35);
      V[k] = (nvec.x + (t1.x * Math.cos(a) + t2.x * Math.sin(a)) * sp) * vv;
      V[k + 1] = (nvec.y + (t1.y * Math.cos(a) + t2.y * Math.sin(a)) * sp) * vv;
      V[k + 2] = (nvec.z + (t1.z * Math.cos(a) + t2.z * Math.sin(a)) * sp) * vv;
      A[k] = 0; A[k + 1] = pl.type === 'jets' ? 9 + Math.random() * 4 : pl.type === 'geyser' ? 4 + Math.random() * 2 : (2 * vv / g) * 1.05;
      A[k + 2] = (Math.random() * pl.colors.length) | 0;
      if (anywhere) { // fast-forward to a random point in its life
        const steps = (Math.random() * A[k + 1] * 20) | 0;
        for (let s = 0; s < steps; s++) step(i, 0.05);
      }
    };
    const step = (i, dt) => {
      const k = i * 3, vi = (i / per) | 0;
      A[k] += dt;
      if (pl.type === 'geyser') {
        const nvec = vents[vi];
        const h = P[k] * nvec.x + P[k + 1] * nvec.y + P[k + 2] * nvec.z - 1;
        if (h < pl.h) { P[k] += nvec.x * v0 * dt; P[k + 1] += nvec.y * v0 * dt; P[k + 2] += nvec.z * v0 * dt; }
        else { const w = winds[vi]; P[k] += w.x * dt; P[k + 1] += w.y * dt; P[k + 2] += w.z * dt; }
        return;
      }
      const r = Math.hypot(P[k], P[k + 1], P[k + 2]) || 1;
      V[k] -= P[k] / r * g * dt; V[k + 1] -= P[k + 1] / r * g * dt; V[k + 2] -= P[k + 2] / r * g * dt;
      if (pl.type === 'jets') V[k + 2] += 0.22 * dt;  // drift downstream to feed the E ring / torus
      P[k] += V[k] * dt; P[k + 1] += V[k + 1] * dt; P[k + 2] += V[k + 2] * dt;
    };
    for (let i = 0; i < n; i++) spawn(i, true);
    updaters.push((dt, sp) => {
      const d = Math.min(dt * sp, 0.06);
      for (let i = 0; i < n; i++) {
        step(i, d);
        const k = i * 3, life = A[k + 1], age = A[k];
        const r = Math.hypot(P[k], P[k + 1], P[k + 2]);
        if (age > life || r < 0.985 || r > 8) { spawn(i, false); continue; }
        const x = age / life;
        const fade = pl.type === 'umbrella' ? Math.sin(Math.PI * Math.min(1, x)) ** 0.6 : Math.min(1, x * 8) * (1 - x);
        const c = pl.colors[A[k + 2]];
        const b = (pl.type === 'jets' ? 1.0 : 1.5) * fade;
        C[k] = c[0] * b; C[k + 1] = c[1] * b; C[k + 2] = c[2] * b;
      }
      pts.geometry.attributes.position.needsUpdate = true;
      pts.geometry.attributes.color.needsUpdate = true;
    });
    const v = vents[0];
    const lift = pl.type === 'jets' ? 2.4 : 1.55;
    anchor(pl.label, group, v.x * lift, v.y * lift, v.z * lift);
  }

  // Alfvén wings: the moon disturbs the field, and waves carry energy along it to the planet's aurora
  if (f.wings) {
    const polys = [], R0 = f.wings.r;
    for (const sg of [1, -1]) for (let k = 0; k < 6; k++) {
      const ph = k / 6 * TAU, pts = [], t = [];
      for (let i = 0; i <= 30; i++) {
        const u = i / 30;
        pts.push(new THREE.Vector3(Math.cos(ph) * R0 * (1 - 0.3 * u), sg * (0.25 + 7 * u), Math.sin(ph) * R0 * 0.6 + 2.6 * u + 0.4 * u * u));
        t.push(u);
      }
      polys.push({ pts, t });
    }
    const m = lineMaterial(f.wings.c, 0.8, 0.7);
    const lines = new THREE.LineSegments(linesGeometry(polys), m);
    lines.frustumCulled = false;
    group.add(lines); timed.push(m);
    anchor('wings', group, 0, 4.6, 2.0);
  }

  // Ganymede's own magnetosphere: closed loops near the equator, open field lines over the poles
  if (f.minimag) {
    const polys = [];
    for (const L of [1.5, 2.0, 2.6]) for (let k = 0; k < 8; k++) {
      const ph = k / 8 * TAU + L, th0 = Math.asin(Math.sqrt(1 / L)), pts = [], t = [];
      for (let i = 0; i <= 40; i++) {
        const u = i / 40, th = th0 + (Math.PI - 2 * th0) * u, r = L * Math.sin(th) ** 2;
        const p = new THREE.Vector3(r * Math.sin(th) * Math.cos(ph), r * Math.cos(th), r * Math.sin(th) * Math.sin(ph));
        p.z *= p.z < 0 ? 0.75 : 1.35;
        pts.push(p); t.push(u);
      }
      polys.push({ pts, t });
    }
    for (const sg of [1, -1]) for (let k = 0; k < 7; k++) {
      const ph = k / 7 * TAU, c = 0.32, pts = [], t = [];
      for (let i = 0; i <= 30; i++) {
        const r = 1 + 5 * i / 30;
        pts.push(new THREE.Vector3(Math.sin(c) * Math.cos(ph) * r, sg * Math.cos(c) * r, Math.sin(c) * Math.sin(ph) * r + 0.3 * (r - 1)));
        t.push(i / 30);
      }
      polys.push({ pts, t });
    }
    const m = lineMaterial(f.minimag.c, 0.85, 0.5);
    const lines = new THREE.LineSegments(linesGeometry(polys), m);
    lines.frustumCulled = false;
    group.add(lines); timed.push(m);
    const bub = new THREE.Mesh(new THREE.SphereGeometry(1, 48, 24), fresnelMaterial([0.55, 0.5, 1.0], 0.22));
    bub.scale.set(2.1, 2.3, 2.8); bub.position.z = 0.5;
    group.add(bub); timed.push(bub.material);
    anchor('minimag', group, 1.4, 2.4, 0.4);
  }

  // Titan: Saturn's field piles up and drapes around the ionosphere, forming an induced magnetotail
  if (f.drape) {
    const polys = [];
    for (const x of [-1.8, -0.9, 0, 0.9, 1.8]) for (const dz of [0, 0.7]) {
      const A = 3.4 - 0.5 * Math.abs(x) + dz, z0 = -1.6 + dz * 0.3, pts = [], t = [];
      for (let i = 0; i <= 60; i++) {
        const y = -4 + 8 * i / 60;
        pts.push(new THREE.Vector3(x, y, z0 + A * Math.exp(-(y * y) / 2.25)));
        t.push(Math.abs(y) / 4);
      }
      polys.push({ pts, t });
    }
    const m = lineMaterial(f.drape.c, 0.85, -0.5);
    const lines = new THREE.LineSegments(linesGeometry(polys), m);
    lines.frustumCulled = false;
    flowFrame.add(lines); timed.push(m);
    anchor('drape', flowFrame, 1.9, 2.6, 1.2);
  }

  // neutral cloud spread along the orbit ahead of the moon (Io's sodium "banana", Enceladus' water cloud)
  let cloud = null;
  if (f.cloud && holder) {
    const c = f.cloud;
    const geo = new THREE.TorusGeometry(dist, c.tube, 12, 96, c.arc);
    geo.rotateX(-Math.PI / 2);
    const m = cloudMaterial(c.c, c.a);
    cloud = new THREE.Mesh(geo, m);
    cloud.renderOrder = 1;
    holder.add(cloud); timed.push(m);
    const a = c.arc * 0.45;
    const o = new THREE.Object3D(); o.position.set(dist * Math.cos(a), c.tube * 1.6, -dist * Math.sin(a)); cloud.add(o);
    anchors.push({ key: c.label, obj: o, aurora: false });
  }

  return {
    group,
    anchors,
    // dt: real seconds; ang: orbit angle; t: elapsed seconds; sp: time-speed factor
    // camDist: camera distance in moon radii (halo and cloud fade out in close-up)
    update(dt, ang, t, { aurora = true, speed = 1, camDist = 100 } = {}) {
      const far = THREE.MathUtils.smoothstep(camDist, 10, 45);
      if (halo) halo.material.opacity = f.halo[3] * far;
      if (cloud) cloud.material.uniforms.uOpacity.value = f.cloud.a * (0.2 + 0.8 * far);
      if (f.flow?.mode === 'sun') {
        // flow from the Sun (world -x) expressed in this moon's frame
        group.getWorldQuaternion(tmpQ).invert();
        tmpV.set(-1, 0, 0).applyQuaternion(tmpQ).normalize();
        flowFrame.quaternion.setFromUnitVectors(Z, tmpV);
      }
      const sp = Math.max(0.25, Math.min(speed, 3));
      updaters.forEach(u => u(dt, sp));
      timed.forEach(m => { m.uniforms.uTime.value = t; });
      shellMats.forEach(m => { m.uniforms.uAur.value = aurora ? 1 : 0; });
      if (cloud) cloud.rotation.y = ang - 0.06;
    },
    setVisible(v) { group.visible = v; if (cloud) cloud.visible = v; }
  };
}