-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsuper-sky.js
executable file
·1455 lines (1275 loc) · 61.2 KB
/
super-sky.js
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
const AFRAME = window.AFRAME
const THREE = window.THREE
AFRAME.registerPrimitive('a-super-sky', {
defaultComponents: {
// mimic the a-sky primitive, to paint our shader on the inside of a sphere as designed
// https://github.com/aframevr/aframe/blob/master/src/extras/primitives/primitives/a-sky.js
geometry: {
primitive: 'sphere',
// radius: 500, // see default 'sunshaderdistance' in component
segmentsWidth: 64,
segmentsHeight: 32
},
material: {
// color: '#FFF',
// shader: 'flat',
side: 'back',
npot: true
},
scale: '-1 1 1',
'super-sky': {},
},
mappings: {
orbitduration: 'super-sky.orbitduration',
throttle: 'super-sky.throttle',
targetfpd: 'super-sky.targetfpd',
starttime: 'super-sky.starttime',
startpercent: 'super-sky.startpercent',
mooncycle: 'super-sky.mooncycle',
disablefog: 'super-sky.disablefog',
fogmin: 'super-sky.fogmin',
showstars: 'super-sky.showstars',
starcount: 'super-sky.starcount',
starlightintensity: 'super-sky.starlightintensity',
starloopstart: 'super-sky.starloopstart',
showhemilight: 'super-sky.showhemilight',
showsurfacelight: 'super-sky.showsurfacelight',
showshadowlight: 'super-sky.showshadowlight',
groundcolor: 'super-sky.groundcolor',
sunbeamdistance: 'super-sky.sunbeamdistance',
starfielddistance: 'super-sky.starfielddistance',
sunshaderdistance: 'super-sky.sunshaderdistance',
sunbeamtarget: 'super-sky.sunbeamtarget',
shadowsize: 'super-sky.shadowsize',
seed: 'super-sky.seed',
moonrayleigh: 'super-sky.moonrayleigh',
moonluminance: 'super-sky.moonluminance',
moonturbidity: 'super-sky.moonturbidity',
moonintensity: 'super-sky.moonintensity',
sunintensity: 'super-sky.sunintensity',
sunrayleigh: 'super-sky.sunrayleigh',
sunluminance: 'super-sky.sunluminance',
sunturbidity: 'super-sky.sunturbidity',
sunriseoffset: 'super-sky.sunriseoffset',
moonriseoffset: 'super-sky.moonriseoffset',
'super-sky-debug': 'super-sky.debug',
}
});
AFRAME.registerComponent('super-sky', {
schema: {
orbitduration: {
// time for one sun cycle. if moon cycle is enabled, then a full day will be twice this length.
// set to `infinite`
type: 'number',
default: 1, // in minutes
},
throttle: { // overrides targetfpd if set
// -1 means that throttle will be auto-set according to targetfpd
// how much to throttle, if desired
// higher values make sky computed less often, which will make sky 'choppy'
// to tune for performance:
// make cycle duration as long as possible first,
// then increase throttle as high as you can before it starts looking jerky
type: 'number',
default: -1, // min ms to wait before recalculating sky change since last calculation; e.g., 10 = 100fps cap
},
targetfpd: { // fpd = frames per degree
// -1 means that an auto-set value will be used
// set to 0 to make scene static
// fpd of '1' would mean the sun/moon will 'click' into each 1/360 position of its rotation, '2' would mean per .5 degree, and so on
// sane value is usually around 10 (per 10th of a degree, attempt refresh)
type: 'number',
default: -1,
},
starttime: {
// this will be auto-set to date.now(), but you can specify a start time to sync the sky to other
// users or to a consistent in-world epoch time.
type: 'number',
default: 0,
},
startpercent: {
// percent of full day/night (or day, if moon cycle disabled) to skip at initialization
// .83 = start at 83% of a full cycle
type: 'number',
default: 0,
},
mooncycle: {
// turn on/off moon cycle; also turns off stars. nights are 'just black' when false.
// relies on setting and controlling 'fog' component for a-scene.
// night becomes 3x length, and features a 'moon' for 1/3 of that
type: 'boolean',
default: true,
},
disablefog: {
type: 'boolean',
default: false,
},
fogmin: {
// how far you can see when night is at its darkest
// which is, how close the shadows creep in to the user
type: 'number',
default: 70, // number from 0 -> 360
},
showstars: {
// use if you want to show moon, but no stars
type: 'boolean',
default: true,
},
starcount: {
// how many stars to show at night
type: 'number',
default: 2000,
},
starlightintensity: {
// used as minimum light intensity at any time of active lights, which is,
// how bright ambient lighting is when only stars are out
type: 'number',
default: 0.2, //number from 0 to 1
},
moonintensity: {
// how bright the actual light from the moon is
// this is just a multiplier used, actual value is dynamic according to position in sky
type: 'number',
default: 0.05, //number from 0 to 1
},
sunintensity: {
// how bright the actual light from the moon is
// this is just a multiplier used, actual value is dynamic according to position in sky
type: 'number',
default: 0.5, //number from 0 to 1
},
starloopstart: {
// you shouldn't touch this.
// sets offset (compare with no offset at 180) of when stars should rise and fog should creep in
// code treats this as a constant, likely will break things if adjusted
type: 'number',
default: 200, // number from 0 -> 360; 180 is sunset
// should have been 20, not 200. derp. that is where the forwarrd offset by ~2/8 comes from.
},
showhemilight: {
type: 'boolean',
default: true,
},
showsurfacelight: {
type: 'boolean',
default: false,
},
showshadowlight: {
type: 'boolean',
default: true,
},
groundcolor: {
// gets mixed in for calculations about sunlight colors, fog color
type: 'color',
default: '#553e35',
},
sunbeamdistance: {
// how far away the shadow-casting sun is
// while the shader for the sun/moon can be virtually any length,
// if the sunbeam light source is too far away, shadows don't work properly
// should always be at least a few meters smaller than the sunshaderdistance,
// but no camera movement = any distance works, and less camera movement = more distance works
type: 'number',
default: 900,
},
starfielddistance: {
// how far away the stars are
// correct distance is important to make sure fog shows/hides them with correct timing
// should be within (so, smaller than) the sunshaderdistance
// should also be within the sunbeam distance, or they won't be illuminated at night
// they are finicky on being illuminated properly at diferent depths
// starfield depth will be auto-set to be the difference between starfield and shader,
type: 'number',
default: 300,
},
sunshaderdistance: {
// the 'sun'/'moon' you see is projected on the inside of a sphere. this can be any distance by itself,
// however, if too close, you'll 'run into' it (creating a 'truman show' effect), but the further the discrepancy
// between this and sunbeam, the more 'off' the shadows and reflections will feel from the shader
type: 'number',
default: 1000,
},
sunbeamtarget: {
// target of directional sunlight that casts shadows
// see: https://aframe.io/docs/1.2.0/components/light.html#directional
// and: https://threejs.org/docs/#api/en/lights/directionallight
type: 'string',
default: "[camera]",
},
shadowsize: {
// size of shadow-casting beam of directional light
// smaller is more performant, but cuts off shadow calculation within a tighter box around the target
type: 'number',
default: 15, // in meters
},
seed: {
// currently only used for star position in aframe >=1.2.0
type: 'number',
default: 1,
},
// shader variations between night and day:
// moonheight // todo
moonrayleigh: {
//number from 0 to 1; higher causes more red in the sky
type: 'number',
default: 0.1,
},
moonluminance: {
// recommended range: 1.09 to 1.19; 1.18 creates a beautiful halo; 1.19 creates a serene, simple moon; go higher, things get weird; go lower, skyline turns red
type: 'number',
default: 1.18,
},
moonturbidity: {
//number from 0 to 1 // moon aura size, especially at sunrise/sunset
type: 'number',
default: .3,
},
sunrayleigh: {
type: 'number',
default: 1, //number from 0 to 1
},
sunluminance: {
type: 'number',
default: 1, //number from 0 to 1
},
sunturbidity: {
type: 'number',
default: 0.8, //number from 0 to 1
},
sunriseoffset: {
// experimental, not recommended, problems if anything has absolute positioning
// where on the horizon the sun rises from
// accomplishes this by rotating a-scene
type: 'number',
default: 0, // number from 0 -> 360
},
moonriseoffset: {
// experimental, not recommended, problems if anything has absolute positioning
// where on the horizon the moon rises from
// this is accomplished adding rotation to a-scene
type: 'number',
default: 45, // number from 0 -> 360
},
debug: {
type: 'boolean',
default: false,
},
},
init: function () {
// see update()
this.el.classList.add('super-sky');
this.tickBackup = this.tick;
if (AFRAME.version === "1.0.4" || AFRAME.version === "1.1.0" || AFRAME.version[0] === "0") {
if (this.data.debug) console.warn("detected pre 1.2.0, make sure to include star library (see readme)");
this.version = 0;
}
else {
if (this.data.debug) console.log("detected AFRAME >=1.2.0, highest tested is 1.2.0");
this.version = 1;
}
this.sky = this.el;
this.sky.classList.add('star-sky');
this.sky.setAttribute('material', 'opacity', 0); // may not be necessary anymore
this.sky.setAttribute('material', 'shader', 'sky');
this.sky.setAttribute('geometry', 'thetaLength', 110);
this.fogRangeMax = this.data.starfielddistance * 2;
},
throttle: 0, // dynamically set
// initializer functions, broken out from this.init() so that they can be re-called from update() if needed
f: {
setThrottle() {
this.msPerDegree = (this.data.orbitduration/360)*1000*60;
if (this.data.targetfpd === -1) {
if (this.data.debug) console.log("no given targetfpd, will fall back to 40fps (throttle=25) / 60fpd cap default");
this.data.targetfpd = this.msPerDegree / 25 // first aim for 40fps minimum, but...
this.data.targetfpd = this.data.targetfpd > 60 ? 60 : this.data.targetfpd; // if we're getting more than 60 renders per degree, set the ceiling her to massively reduce renders
}
if (this.data.throttle !== -1) {
if (this.data.debug) console.warn("custom throttle set, will ignore targetfpd")
this.throttle = this.data.throttle;
this.data.targetfpd = this.msPerDegree / this.throttle;
}
else if (this.data.targetfpd === 0) {
if (this.data.debug) console.warn("static sky")
this.tickBackup = this.tick;
this.throttle = Infinity;
this.data.throttle = Infinity;
return
}
else {
this.throttle = this.msPerDegree / this.data.targetfpd;
}
this.fps = 1000/this.throttle;
if (this.data.debug) {
console.log(this.cleanNumber(this.msPerDegree),'ms per degree at',this.cleanNumber(this.data.targetfpd),',fpd; throttle:',this.cleanNumber(this.throttle),', fps:',this.cleanNumber(this.fps));
if (this.throttle < 10 || this.fps > 60) console.warn("likely wasteful rendering; consider setting `targetfpd` below", this.cleanNumber(this.data.targetfpd / (15 / this.throttle)),"to optimize performance");
else if (this.data.targetfpd < 60 && this.fps < 40) console.warn("animation may be choppy; if needed, consider increasing cycleduration, or setting `targetfpd` above", this.cleanNumber(this.data.targetfpd / (50 / this.throttle))+0.01,"to improve");
}
this.tick = AFRAME.utils.throttleTick(this.tickBackup, this.throttle, this);
},
startFromPercent() {
if (this.data.startpercent < 0) this.data.startpercent = 1 - (-this.data.startpercent % 1) ;
if (this.data.mooncycle && (this.data.startpercent % 1) >= .5) {
this.secondHalf = true;
this.moon = true;
}
this.moonSunSwitchFlag = false;
const cycleInMs = (this.data.orbitduration * 1000 * 60) * (this.data.mooncycle ? 2 : 1)
this.data.starttime = Date.now() - (this.data.startpercent * cycleInMs);
this.getOrbit()
this.setStarLoop()
// add stars if needed
this.getEighth()
this.getEighthStarLoop()
if (this.inRange(this.ranges.extendedStarRange)) {
if (this.data.debug) console.warn("add stars to init")
this.setStars()
} else {
if (this.data.debug) console.warn("remove stars from init")
this.setStars(0)
}
if (this.data.debug) {
console.log("skipping first",`${this.data.startpercent*100}%`,(this.data.startpercent * cycleInMs)/1000,'seconds of orbitduration',cycleInMs/1000,Date.now(),'-',this.data.starttime)
console.log(this.orbit,this.currentEighth,this.currentEighthStarLoop)
}
},
hemilight(){
this.hemilight = document.createElement('a-entity');
this.hemilight.setAttribute('id','hemilight');
this.hemilight.setAttribute('position', '0 50 0');
this.hemilight.setAttribute('light', {
type: 'hemisphere',
color: '#CEE4F0',
intensity: 0.1
});
this.hemilight.setAttribute('visible', true);
if (this.hemilight) this.hemilight.setAttribute('light', {groundColor: this.data.groundcolor});
this.el.appendChild(this.hemilight);
this.activeLights.push(this.hemilight)
},
sunbeam() {
this.sunbeam = document.createElement(this.data.debug ? 'a-sphere' : 'a-entity')
this.sunbeam.setAttribute('light', {
type: 'directional',
intensity: 0.1, // dynamically set during the day
groundColor: this.data.groundcolor,
shadowCameraVisible: this.data.debug,
castShadow: true,
shadowMapWidth: 1024,
shadowMapHeight: 1024,
shadowRadius: 1,
shadowCameraLeft: -this.data.shadowsize,
shadowCameraBottom: -this.data.shadowsize,
shadowCameraRight: this.data.shadowsize,
shadowCameraTop: this.data.shadowsize,
shadowCameraFar: this.data.sunbeamdistance + 100, // this.data.shadowsize, // shadowsize was not enough
shadowCameraNear: this.data.sunbeamdistance - 100, // could probably safelu lower this substantially...
target: this.data.sunbeamtarget || "[camera]",
});
this.sunbeam.setAttribute('id', 'sunbeam')
// this.sunbeam.setAttribute('scale', '1 1 1')
this.el.appendChild(this.sunbeam);
this.activeLights.push(this.sunbeam)
},
surfaceLight() {
if (this.data.debug) {
this.sunlight = document.createElement('a-sphere');
const nose = document.createElement('a-cone');
nose.setAttribute('position','z',1.15)
nose.setAttribute('rotation',{'x':270, z:180})
nose.setAttribute('scale',{x:.2,y:.2,z:.2})
nose.setAttribute('material', 'color', 'blue')
this.sunlight.appendChild(nose)
} else {
this.sunlight = document.createElement('a-entity');
}
this.sunlight.setAttribute('id','sunlight-noshadow');
this.sunlight.setAttribute('light', {
type:'directional',
intensity: 0.1,
shadowCameraVisible: this.data.debug,
castShadow: false,
shadowCameraLeft: -this.data.shadowsize,
shadowCameraBottom: -this.data.shadowsize,
shadowCameraRight: this.data.shadowsize,
shadowCameraTop: this.data.shadowsize
});
this.sunlight.setAttribute('visible', true);
this.el.appendChild(this.sunlight);
this.activeLights.push(this.sunlight)
},
},
activeLights: [],
// {
// orbitduration: 'super-sky.orbitduration',
// throttle: 'super-sky.throttle',
// targetfpd: 'super-sky.targetfpd',
// starttime: 'super-sky.starttime',
// startpercent: 'super-sky.startpercent',
// mooncycle: 'super-sky.mooncycle',
// disablefog: 'super-sky.disablefog',
// fogmin: 'super-sky.fogmin',
// showstars: 'super-sky.showstars',
// starcount: 'super-sky.starcount',
// starlightintensity: 'super-sky.starlightintensity',
// starloopstart: 'super-sky.starloopstart',
// showhemilight: 'super-sky.showhemilight',
// showsurfacelight: 'super-sky.showsurfacelight',
// showshadowlight: 'super-sky.showshadowlight',
// groundcolor: 'super-sky.groundcolor',
// sunbeamdistance: 'super-sky.sunbeamdistance',
// starfielddistance: 'super-sky.starfielddistance',
// sunshaderdistance: 'super-sky.sunshaderdistance',
// sunbeamtarget: 'super-sky.sunbeamtarget',
// shadowsize: 'super-sky.shadowsize',
// seed: 'super-sky.seed',
// moonrayleigh: 'super-sky.moonrayleigh',
// moonluminance: 'super-sky.moonluminance',
// moonturbidity: 'super-sky.moonturbidity',
// moonintensity: 'super-sky.moonintensity',
// sunintensity: 'super-sky.sunintensity',
// sunrayleigh: 'super-sky.sunrayleigh',
// sunluminance: 'super-sky.sunluminance',
// sunturbidity: 'super-sky.sunturbidity',
// sunriseoffset: 'super-sky.sunriseoffset',
// moonriseoffset: 'super-sky.moonriseoffset',
// 'super-sky-debug': 'super-sky.debug',
// }
changed(key) {
return this.oldData[key] !== this.data[key]
},
isEmptyObject: function(testObj) {
return (Object.keys(testObj).length === 0 && testObj.constructor === Object);
},
update(oldData) {
// I think this should be handled differently, and is probably automatically handled by tick() behavior
// if (this.data.groundcolor != oldData.groundcolor) {
// this.activeLights.forEach(el => {
// el.setAttribute('light', {'groundColor': this.data.groundcolor});
// });
// }
if (this.data.debug) console.log('update dif', AFRAME.utils.diff (oldData, this.data))
this.oldData = oldData;
let firstUpdate = false;
if (!this.firstUpdatePast) {
this.firstUpdatePast = true;
firstUpdate = true;
// continue
} else if (this.isEmptyObject(oldData)) {
// attempts to prevent firing update whenever inspector is opened
if (this.data.debug) console.warn("skipping update because of empty object... update() is broken")
return
}
if (!this.data.debug) {
this.trackPerformanceBackup = this.trackPerformance;
this.trackPerformance = () => {};
} else if (this.trackPerformanceBackup) {
this.trackPerformance = this.trackPerformanceBackup;
}
if (this.changed('throttle') || this.changed('targetfpd')) {
if (this.data.debug) console.warn("throttle/targetfpd update")
if (oldData.targetfpd === 0 && this.data.targetfpd !== 0) this.tick = this.tickBackup; // restore tick to attempt to allow restarting from static scene
this.f.setThrottle.bind(this)()
}
if (this.changed('mooncycle') && !this.data.mooncycle) {
// turning off moon cycle
this.data.startpercent = this.orbit / 360;
this.f.startFromPercent.bind(this)();
this.tickHandlers() // flip one frame forward to show the change while paused from inspector
// this.tickBackup();
}
if (this.changed('starttime') && this.data.starttime) {
if (this.data.debug) console.log('will use custom starttime:', !!this.data.starttime)
// do we even need to do anything? We could prevent 'jerk' by pausing until the times match, perhaps? Or just slow down by half until times match...?
// probably 80/20 is to just ramp up/down fog
// and run this.init?
// new idea, we now have implemented .updateOrbitDuration(10)
// so just do double their orbitduration until percent, and then back to same speed.
// increased fog might also be nice, though.
this.updateSkyEpoch()
}
else if (this.changed('startpercent') && this.data.startpercent) {
if (this.data.debug) console.log('will use custom startpercent:', this.data.starttime)
this.f.startFromPercent.bind(this)();
}
else if (!this.data.starttime) {
if (this.data.debug) console.log('no custom starttime:', this.data.starttime)
this.data.starttime = Date.now();
}
if (this.changed('showhemilight')) {
if (this.data.debug) console.warn("hemi light change update")
if (this.hemilight) this.el.removeChild(this.hemilight)
if (this.data.showhemilight) this.f.hemilight.bind(this)();
}
if (this.changed('showsurfacelight')) {
if (this.data.debug) console.warn("surface light change update")
if (this.sunlight) this.el.removeChild(this.sunlight)
if (this.data.showsurfacelight) this.f.surfaceLight.bind(this)();
}
if (this.changed('showshadowlight') || this.changed('shadowsize')) {
if (this.data.debug) console.warn("sunbeam light change update")
if (this.sunbeam) this.el.removeChild(this.sunbeam)
if (this.data.showshadowlight) this.f.sunbeam.bind(this)();
}
if (this.changed('sunshaderdistance')) {
if (this.data.debug) console.warn("sunshader update")
this.sky.setAttribute('geometry', 'radius', this.data.sunshaderdistance);
}
if (this.changed('sunbeamtarget')) {
if (this.data.debug) console.warn("sunbeamtarget update")
this.sunbeam?.setAttribute('light', 'target', this.data.sunbeamtarget)
}
if (firstUpdate) return
// else
// put things that should run on first update below this point
if (this.changed('orbitduration')) {
// for some reason, update() seems very broken, and this condition will only reliably fire the first time. needs to be done manually in another function, it seems.
this.updateOrbitDuration();
}
if (this.changed('starfielddistance') || this.changed('seed')) {
if (this.data.debug) console.warn("starfield update")
if (this.stars) {
this.el.removeChild(this.stars);
delete this.stars;
}
// no need to add them in, when `this.setStars()` is called, it'll create correctly as needed
}
if (
this.changed('moonrayleigh') ||
this.changed('moonluminance') ||
this.changed('moonturbidity') ||
this.changed('sunrayleigh') ||
this.changed('sunluminance') ||
this.changed('sunturbidity')
) {
if (this.data.debug) console.warn("shader update")
this.sunShaderTick()
}
if (
this.changed('groundcolor') ||
this.changed('moonintensity') ||
this.changed('sunintensity') ||
this.changed('starlightintensity') ||
this.changed('debug') //|| // debug, because we change some stuff for e.g. showing shadowcamera
// this.changed('sunturbidity')
) {
if (this.data.debug) console.warn("light color/brightness update")
this.lightSourcesTick()
}
},
updateOrbitDuration(newOrbitDuration) {
if (newOrbitDuration) {
this.data.orbitduration = newOrbitDuration;
}
if (this.data.debug) console.warn("experimental: orbit duration shift without jerk?")
const denom = this.data.mooncycle ? 8 : 4;
this.data.startpercent = ((this.currentEighth.which+1) / denom) - ((1-this.currentEighth.percent)/denom)
if (this.data.debug) console.log('current percent through cycle:',this.data.startpercent)
// this.f.startFromPercent.bind(this)();
// this.tickHandlers() // flip one frame forward to show the change while paused from inspector
if (this.data.debug) console.warn('will clear old targetfpd and auto-calc new value')
this.data.targetfpd = -1
this.data.throttle = -1
this.f.setThrottle.bind(this)()
this.f.startFromPercent.bind(this)();
},
dayPercent() {
return (((this.currentEighth.which/8)+(1/8* this.currentEighth.percent)) + (.125*3) + this.data.startpercent) % 1;
},
timeOfDay() {
return `${this.padTime(Math.floor(this.dayPercent() * 24))}:${this.padTime(Math.floor(this.dayPercent() * 60 * 24) % 60)}:${this.padTime(Math.floor(this.dayPercent()* 60 * 60 * 24) % 60)}`
},
padTime(n) {
return (n+"").length < 2 ? "0" + n : ""+n;
},
shareSky() {
return {
mooncycle: this.data.mooncycle,
orbitduration: this.data.orbitduration,
starttime: this.data.starttime,
};
},
updateSkyEpoch(newStartTime=this.data.starttime){
// set moon cycle
// set orbit duration
// set starttime
// call this function
// e.g.,
/*
screen1:
let user1Sky = JSON.stringify(document.querySelector('[super-sky]').components['super-sky'].shareSky())
screen2:
user1Sky = JSON.parse(
user1Sky
)
document.querySelector('[super-sky]').components['super-sky'].data.mooncycle = user1Sky.mooncycle
document.querySelector('[super-sky]').components['super-sky'].updateOrbitDuration(user1Sky.orbitduration)
document.querySelector('[super-sky]').components['super-sky'].data.starttime = user1Sky.starttime
document.querySelector('[super-sky]').components['super-sky'].updateSkyEpoch()
*/
this.data.startpercent = this.timestampToOrbitPercent(newStartTime, this.data.mooncycle);
if (this.data.debug) console.warn("will attempt to start with new time percent", this.data.startpercent)
this.f.startFromPercent.bind(this)();
},
// Custom Math.random() with seed. Given this.environmentData.seed and x, it always returns the same "random" number
random: function (x) {
return parseFloat('0.' + Math.sin(this.data.seed * 9999 * x).toString().substr(7));
},
createStars: function() {
this.stars = document.createElement('a-entity');
this.stars.setAttribute('id','stars');
if (this.data.showstars && this.version === 0) {
if (this.data.debug) console.log("appending old style star system")
// this.starsOld = document.createElement('a-entity');
// this.starsOld.setAttribute('id', 'stars');
// this.getSunSky().setAttribute('material', 'shader', 'sunSky');
// this.getSunSky().setAttribute('material','shader','sunSky');
// this.getSunSky().setAttribute('geometry','primitive','sphere');
// this.getSunSky().setAttribute('geometry','radius','1000');
this.stars.setAttribute('star-system',{
count: this.data.starcount,
radius: this.data.starfielddistance,
starSize: this.data.starfielddistance / 400, // .25
depth: 25, // this.data.sunshaderdistance-this.data.starfielddistance,
});
// this.el.appendChild(this.starsOld);
}
else {
if (this.data.debug) console.log("appending new style star geometry")
// initializes the BufferGeometry for the stars in >= AF 1.2.0
// code here is more or less pulled from aframe-environment-component
var numStars = this.data.starcount;
var geometry = new THREE.BufferGeometry();
var positions = new Float32Array( numStars * 3 );
var radius = this.data.starfielddistance;
var v = new THREE.Vector3();
for (var i = 0; i < positions.length; i += 3) {
v.set(this.random(i + 23) - 0.5, this.random(i + 24), this.random(i + 25) - 0.5);
v.normalize();
v.multiplyScalar(radius);
positions[i ] = v.x;
positions[i+1] = v.y;
positions[i+2] = v.z;
}
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setDrawRange(0, 0); // don't draw any yet
var material = new THREE.PointsMaterial({size: 0.01, color: 0xCCCCCC, fog: false});
this.stars.setObject3D('mesh', new THREE.Points(geometry, material));
}
this.el.appendChild(this.stars);
},
setStars: function (starCount = this.howManyStars()) {
this.starlight = !!starCount;
if ( (!this.stars) ){
this.createStars();
}
if (this.data.debug) console.log("starcount",starCount)
if (!this.version) {
this.stars.setAttribute('star-system', "count", starCount);
} else {
this.stars.getObject3D('mesh').geometry.setDrawRange(0, starCount);
}
if (this.data.debug) console.log("setStars", starCount, this.starlight)
},
starCycle: 0, // dynamic
fogValue: 0, // dynamic
fogRangeMax: 1000,
timestampToOrbitPercent(timestamp, x2) {
this.msSinceStart = Date.now() - (timestamp||this.data.starttime);
this.minSinceStart = this.msSinceStart / 1000 / 60;
this.minIntoCycle = this.minSinceStart % (this.data.orbitduration * (x2 ? 2:1));
this.fractionOfCurrentCycle = this.minIntoCycle * ( 1 / (this.data.orbitduration * (x2 ? 2:1)) );
return this.fractionOfCurrentCycle;
},
getOrbit(other) {
// converts time passed into a fraction of 360, so 0,1,2...359,360,0,1...etc.
// if (this.fractionOfCurrentCycle < 0) this.fractionOfCurrentCycle = -this.fractionOfCurrentCycle // might be wrong, just a test
this.orbit = 360 * this.timestampToOrbitPercent();
return this.orbit;
},
moon: false,
moonSunSwitchFlag: false,
getEighthStarLoop() {
// dividing day and night each into four cycles, we get 8 total cycles.
// returns a corresponding value from 0-7 for which eighth of day you are in
// also returns what percent through that eighth you are
// this one follows 20 degrees behind the 'real' loop
// except for just before and after sunrise, when it returns modified values to adjust fog.
// that part is a bit of a hack and should be adjusted, so: "todo"
// 90 === 360/4
this.quarterCount = Math.floor( this.starLoop / 90 );
this.lastEighthStarLoop = this.currentEighthStarLoop;
this.currentEighthStarLoop = {
which: this.moon ? this.quarterCount + 4 : this.quarterCount,
percent: ((this.starLoop % 90) * (1/90)),
}
if (this.currentEighthStarLoop.which === 1 && this.currentEighthStarLoop.percent > .65) {
this.currentEighthStarLoop.which = 2; // cheap way to prevent fog from increasing even after sunrise
this.currentEighthStarLoop.percent = .2 // speed up to cause fog pre-sunrise early
}
else if (this.currentEighthStarLoop.which === 2) {
this.currentEighthStarLoop.percent = this.currentEighthStarLoop.percent < .2 ?
.2 : this.currentEighthStarLoop.percent; // matching up beginning of 2 with faux end of 1
this.currentEighthStarLoop.percent = this.currentEighthStarLoop.percent < .5 ?
this.currentEighthStarLoop.percent * 2 : this.currentEighthStarLoop.percent // speed up to cause shadows pre-sunrise early
}
if (this.data.debug && this.lastEighthStarLoop.which !== this.currentEighthStarLoop.which) {
// console.log('new eighth star', {
// eighth: this.currentEighth.which,
// moon: this.moon,
// starlight: this.starlight,
// sunOrMoonUp: this.sunOrMoonUp(),
// fog: this.fogValue,
// intensity: this.lights.lightProps.intensity,
// multiplier: this.lights.intensityMultiplier
// })
// document.querySelector('#log').setAttribute('value', "fog: "+this.fogValue)
// document.querySelector('#log').setAttribute('value', 's: ' + this.currentEighthStarLoop.which + "/8; e: " + this.currentEighth.which + "/8")
}
},
currentEighthStarLoop: { // dynamically set
which: 2,
percent: 0.001,
},
secondHalf: false,
getEighth() {
// dividing day and night each into four cycles, we get 8 total cycles.
// returns a corresponding value from 0-7 for which eighth of day you are in
// also returns what percent through that eighth you are
// on this loop, 0% @ 0/8 is sunrise, 100% @ 1/8 is sunset, 0% @ 4/8 is moonrise, 100% @ 5/8 is moonset
// 90 === 360/4
this.quarterCount = Math.floor( this.orbit / 90 );
this.lastEighth = this.currentEighth;
if (this.data.mooncycle &&
(this.quarterCount === 0 && this.lastEighth.which === 3)
|| this.quarterCount === 0 && this.lastEighth.which === 7
) {
this.secondHalf = !this.secondHalf
}
this.currentEighth = {
which: this.secondHalf ? this.quarterCount + 4 : this.quarterCount,
percent: ((this.orbit % 90) * (1/90)),
}
if (this.data.debug && this.lastEighth.which !== this.currentEighth.which) {
console.log('new eighth', {
eighth: this.currentEighth.which,
moon: this.moon,
starlight: this.starlight,
fog: this.fogValue,
intensity: this.lights.intensity,
multiplier: this.lights.intensityMultiplier
})
}
},
currentEighth: { // dynamically set
which: 0,
percent: 0.001,
},
setStarLoop() {
// this was early code; would be nice to refactor this to this.inRange()
if (this.orbit > this.data.starloopstart) {
this.starLoop = this.orbit - this.data.starloopstart;
} else {
this.starLoop = this.orbit + (360 - this.data.starloopstart);
}
},
handleMoonCycle(orbit) {
if (orbit < this.data.starloopstart && this.moonSunSwitchFlag) {
this.moonSunSwitchFlag = false;
}
if (orbit > this.data.starloopstart && !this.moonSunSwitchFlag) {
if (this.data.debug) console.log("switching sun/moon", orbit, 'moon:', this.moon)
this.moon = !this.moon;
this.moonSunSwitchFlag = true;
if (this.moon) {
if (this.data.debug) console.log('switch to moon cycle, would rotate scene for moonrise')
// this.el.sceneEl.setAttribute('rotation', {y:this.data.moonriseOffset})
if (this.data.showstars) {
// show stars right after sunset
this.setStars();
if (this.data.debug) console.log('starlight on')
}
} else {
if (this.data.debug) console.log('switch to sun cycle, would rotate scene for sunrise; feature removed')
// this.el.sceneEl.setAttribute('rotation', {y:this.data.sunriseOffset})
}
}
// track star loop separately to have stars rise and fog come in offset just after sunset
this.setStarLoop();
this.starCycle = this.starLoop * ( 1 / 180 ); // 0 -> 2 scale for the 0 -> 360 rotation; we do until 2 so that we can make it negative after 1.
this.starCycle = this.starCycle > 1 ? 2 - this.starCycle : this.starCycle;
// fog:
// - 0 just after sunset,
// - 0 just before sunrise,
// - 1 at full day
// - 1 at full night
this.getEighthStarLoop();
if (this.currentEighthStarLoop.which === 2 || this.currentEighthStarLoop.which === 4) {
// console.log("ready-to-detect-starlight-off", this.moon, this.starlight)
// sunrise -> noon
// or
// sunset -> starlight
// less fog (so, higher fog value) as percent of this.currentEighth goes up
this.fogValue = this.currentEighthStarLoop.percent * this.fogRangeMax
if (this.data.showstars && !this.moon && this.starlight) {
this.setStars(0);
}
}
else if (this.currentEighthStarLoop.which === 3 || this.currentEighthStarLoop.which === 1) {
// noon -> sunset
// or
// dusk -> sunrise
// more fog (so, lower fog value) as percent of this.currentEighthStarLoop goes up
this.fogValue = (1 - this.currentEighthStarLoop.percent) * this.fogRangeMax
}
else {
this.fogValue = this.fogRangeMax
}
// if (this.data.debug) console.log('fogValue', this.fogValue, this.currentEighthStarLoop.percent, this.fogRangeMax)
if (this.fogValue < this.data.fogmin) this.fogValue = this.data.fogmin;
if (!this.data.disablefog) {
this.el.sceneEl.setAttribute('fog', 'far', this.fogValue);
}
},
starlight: false, // dynamically set, indicates if stars are an active light source, which they are for 3/4s of the day/night cycle
howManyStars() {
// can be used to cause stars to drop out one by one, fog creates more attractive effect, though.
return this.data.starcount;
// return (1 - Math.max(0, ( this.sunPos.y + 0.08) * 8)) * this.data.starcount;
},
sunPosition: {x:0,y:0,z:-1}, // dynamically set
sunPos: {x:0,y:0,z:0}, // dynamically set
theta: Math.PI * (-.25), // putting it at .5 changes to a sun that goes straight overhead, but shader only supports movement in its very small range
phi() {return (2 * Math.PI * ((this.orbit / 360) - 0.5))}, // percent of circumference
// I think this 0.5 is the source of the offset by 2/8ths. it forces it to start at sunrise! // -.25 correspondes to noon, -0 corresponds to sunset
lastTick: Date.now(),
slowTickBuildup: 0,
tolerance: -10, // normal ms delay
notified: false,
trackPerformance() {
// NOTE: DOES NOT RUN UNLESS DEBUG ENABLED
// console.log(this.throttle - (Date.now()-this.lastTick),this.tolerance)
if (this.throttle - (Date.now()-this.lastTick) < this.tolerance) {
// if (this.data.debug) console.warn("slow tick")
this.slowTickBuildup++
} else if (this.slowTickBuildup > 0) {
this.slowTickBuildup--
}
if (this.slowTickBuildup > 5) {
if (!this.notified)
if (this.data.debug) console.error("demands may be too high, should increase throttle and reduce cycleduration", this.slowTickBuildup, this.throttle, this.throttle - (Date.now()-this.lastTick) )
this.notified = true;
}
else if (!this.slowTickBuildup) this.notified = false;
this.lastTick = Date.now();
},
tick() {
this.trackPerformance()
this.orbit = this.getOrbit();
this.tickHandlers(); // why? so we can call 'tick' when changing settings but without updating the orbit, if we are paused.
},
tickHandlers(){
if (this.data.mooncycle) {
this.handleMoonCycle(this.orbit);
}
this.sunShaderTick();
this.lightSourcesTick();
},
sunShaderTick() {
// draw the surface of the sphere with sunrise/sunset/moonlight colors, and 'visible' sun/moon
this.sunPosition.x = Math.cos(this.phi());
this.sunPosition.y = Math.sin(this.phi()) * Math.sin(this.theta);
this.setSunSkyMaterial()
this.sky.setAttribute('material', this.sunSkyMaterial);
},
sunSkyMaterial: { // dynamically set
rayleigh: 1,
luminance: 1,
turbidity: .8,
},
setSunSkyMaterial() {
// adjusts sky factors to give variation between day and night
// let label;
if (this.currentEighthStarLoop.which === 1) {
// 1
// console.log("moon to sun", this.currentEighthStarLoop.which)
// label = this.currentEighthStarLoop.which+' moon to sun; ';
// from moon to sun
this.sunSkyMaterial.rayleigh = this.data.moonrayleigh + (this.currentEighthStarLoop.percent * (this.data.sunrayleigh - this.data.moonrayleigh));
this.sunSkyMaterial.luminance = this.data.moonluminance + (this.currentEighthStarLoop.percent * (this.data.sunluminance - this.data.moonluminance));
this.sunSkyMaterial.turbidity = this.data.moonturbidity + (this.currentEighthStarLoop.percent * (this.data.sunturbidity - this.data.moonturbidity));
}
else if (this.currentEighthStarLoop.which === 2 || this.currentEighthStarLoop.which === 3) {
// 2 3