-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweather-overlay.js
More file actions
2392 lines (2193 loc) · 87.9 KB
/
weather-overlay.js
File metadata and controls
2392 lines (2193 loc) · 87.9 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
// Weather Overlay for Home Assistant
// Fullscreen canvas weather animations based on weather entity state
// Version 2.0 - Improved defaults and debugging
(function() {
'use strict';
// ============================================
// CONFIGURATION - Edit these values as needed
// ============================================
// Global config object that can be controlled by the
// Fork U - Weather Aware Lovelace card editor.
const DEFAULT_OVERLAY_CONFIG = {
enabled: true,
weather_entity: 'weather.openweathermap',
development_mode: false,
test_effect: 'Use Real Weather',
sun_entity: 'sun.sun',
moon_phase_entity: null,
uv_index_entity: null,
moon_position_entity: null, // Single entity with attributes (Moon Astro, etc.)
moon_azimuth_entity: null, // Lunar Phase: separate sensor (Moon Azimuth)
moon_altitude_entity: null, // Lunar Phase: separate sensor (Moon Altitude)
moon_distance_entity: null, // Lunar Phase: separate sensor (Moon Distance)
gaming_mode_entity: null, // input_boolean.gaming_mode – Gaming/Ambient Immersive
pm25_entity: null, // PM2.5 µg/m³ (Google Air Quality etc.)
pm4_entity: null, // PM4 µg/m³ (for Cystic Fibrosis awareness)
pm10_entity: null, // PM10 µg/m³
smog_threshold_pm25: 35, // µg/m³ – WHO/EPA unhealthy for sensitive (24h); trigger fog
smog_threshold_pm4: 50, // µg/m³ – no global standard; CF awareness
smog_threshold_pm10: 50, // µg/m³ – EU 24h limit / WHO guideline
cloud_coverage_entity: null, // % – cloud/fog density
wind_speed_entity: null,
wind_direction_entity: null,
precipitation_entity: null, // mm – dynamic rain/snow speed
lightning_counter_entity: null,
lightning_distance_entity: null,
debug_precipitation: null, // 'light'|'medium'|'heavy' – mm/h equiv
debug_wind_speed: null, // 'none'|'light'|'medium'|'strong'
debug_wind_direction: null, // 0–360 or 'N','NE','E','SE','S','SW','W','NW'
debug_lightning_distance: null, // km override
debug_lightning_counter: null, // strike count override
debug_cloud_coverage: null, // 0–100 % override
cloud_speed_multiplier: 1, // 0.5–2: manual cloud speed (1=default, wind still scales)
rain_max_tilt_deg: 30, // max rain tilt from wind (degrees); 0 = always vertical
rain_wind_min_kmh: 3, // min wind speed (km/h) to apply tilt; below = vertical
theme_mode: null, // 'light'|'dark' – set by card from HA theme; null = auto-detect
drizzle_precipitation_max: 2.5, // mm – above this rainy is normal rain; below = drizzle (light rain)
speed_factor_rain: 1,
speed_factor_snow: 1,
speed_factor_clouds: 1,
speed_factor_fog: 1,
speed_factor_smog: 1,
speed_factor_hail: 1,
speed_factor_lightning: 1,
speed_factor_stars: 1,
speed_factor_matrix: 1,
wind_sway_factor: 0.7, // 0–2: how strongly wind bends rain/snow (default 0.7)
spatial_mode: 'foreground', // 'background' | 'bubble' | 'gradient-mask' | 'foreground'
// Effect toggles – disable heavy effects if needed
enable_rain: true,
enable_snow: true,
enable_clouds: true,
enable_fog: true,
enable_smog_effect: true,
enable_sun_glow: true,
enable_moon_glow: true,
enable_stars: true,
enable_hail: true,
enable_lightning_effect: true,
enable_matrix: true,
enable_window_droplets: true,
stars_require_moon: false,
// Mobile performance options (can be toggled in editor)
mobile_limit_dpr: true, // cap canvas DPR on phones (sharper vs performance)
mobile_reduce_particles: true,// reduce particle counts on phones
mobile_snowy2_light: true, // lighter snowy2 layers on phones
mobile_smog_simple: false, // simpler smog rendering on phones
mobile_30fps: false, // cap animation to ~30 FPS on phones
gaming_matrix_only: false // when gaming ON: show only Matrix (no weather layer)
};
window.ForkUWeatherAwareConfig = Object.assign(
{},
DEFAULT_OVERLAY_CONFIG,
window.ForkUWeatherAwareConfig || {}
);
window.ForkUWeatherAwareDefaultConfig = DEFAULT_OVERLAY_CONFIG;
// Always announce presence in console (even when DEBUG_MODE is false)
try {
// Styled banner – easy to spot but not noisy
console.log(
'%cFork U – Weather Aware%c overlay loaded · spatial, theme & mobile aware',
'background:#ffcc00;color:#000;font-weight:bold;padding:2px 6px;border-radius:3px 0 0 3px;',
'background:#1e1e1e;color:#fff;padding:2px 6px;border-radius:0 3px 3px 0;'
);
} catch (e) {
// ignore
}
// Your weather entity (REQUIRED - change this to match your setup)
// Examples: 'weather.home', 'weather.openweathermap', 'weather.accuweather'
const WEATHER_ENTITY = window.ForkUWeatherAwareConfig.weather_entity;
// Optional: Toggle to enable/disable overlay (set to '' to disable this feature)
// Legacy helper toggle is no longer required. Enable/disable is now driven by card config.
const TOGGLE_ENTITY = '';
// Optional: Test selector for different weather states (set to '' to disable)
// Legacy input_select is no longer required; development mode is now driven by card config.
const TEST_ENTITY = '';
// How often to check weather (in milliseconds)
const UPDATE_INTERVAL = 5000;
// Optional: Rain sensor for cross-checking (set to '' to disable)
// If your weather service reports false rain, this sensor can verify
const RAIN_SENSOR_ENTITY = ''; // e.g., 'sensor.rain_gauge' or 'sensor.hydrawise_rain'
const REQUIRE_RAIN_CONFIRMATION = false; // Set to true to require rain sensor confirmation
// Dashboard filtering
// [] = Show on ALL dashboards (recommended for most users)
// ['lovelace'] = Only on default dashboard
// ['home', 'weather'] = Only on specific dashboards
const ENABLED_DASHBOARDS = []; // Empty = ALL dashboards
// Debug mode - set to true to see detailed logs in browser console
// (kept off by default to avoid extra work on mobile; can be enabled via console)
const DEBUG_MODE = false;
function isMobileDevice() {
return window.innerWidth < 600 || 'ontouchstart' in window;
}
function getMobilePerfConfig() {
return window.ForkUWeatherAwareConfig || {};
}
function getEffectiveDpr() {
const cfg = getMobilePerfConfig();
let dpr = window.devicePixelRatio || 1;
if (isMobileDevice() && cfg.mobile_limit_dpr) {
dpr = Math.min(dpr, 2);
}
return dpr;
}
// ============================================
// END CONFIGURATION
// ============================================
// Logging helper
function log(message, data = null) {
if (DEBUG_MODE) {
if (data) {
console.log(`[Weather Overlay] ${message}`, data);
} else {
console.log(`[Weather Overlay] ${message}`);
}
}
}
function warn(message, data = null) {
if (data) {
console.warn(`[Weather Overlay] ⚠️ ${message}`, data);
} else {
console.warn(`[Weather Overlay] ⚠️ ${message}`);
}
}
function error(message, data = null) {
if (data) {
console.error(`[Weather Overlay] ❌ ${message}`, data);
} else {
console.error(`[Weather Overlay] ❌ ${message}`);
}
}
let canvas = null;
let ctx = null;
let particles = [];
let animationId = null;
let currentWeather = null;
let lastUpdateTime = 0;
let lightningTimer = 0;
let lightningInterval = 15000 + Math.random() * 25000;
let lightningFirstBoltAt = 0;
let lastLightningCounter = null;
let showLightning = false;
let lightningDuration = 0;
let lightningBrightness = 0;
let lightningFadeSpeed = 0;
let lightningScheduledFlashAt = 0;
let initializationComplete = false;
let cachedSunPosition = null;
let cachedMoonPosition = null;
let cachedUvIndex = null;
let sensorCacheTime = 0;
const SENSOR_CACHE_MS = 3000; // Refresh sun/moon/UV every 3 seconds
let matrixCanvas = null;
let matrixCtx = null;
let matrixStreams = [];
let matrixSpawnTimer = 0;
let smogCanvas = null;
let smogCtx = null;
let smogParticles = [];
let smogSpawnTimer = 0;
let lastAnimateTime = 0;
let meteorNextAt = 0;
let meteorActive = null;
let cachedPrecipMultiplier = 1;
let cachedCloudCoverage = null;
let cachedWindData = { speed: 5, bearing: 270 };
let windowDroplets = [];
let windowDropletSpawnTimer = 0;
let windowDropletNextIntervalMs = 0;
let snowy2Canvas = null;
let snowy2Ctx = null;
let snowy2Layers = null;
const MATRIX_CHARS = ['園','迎','簡','益','大','诶','比','西','迪','伊','弗','吉','尺','杰','开','艾','勒','马','娜'];
const MATRIX_GREEN = '#00ff41';
const MATRIX_GREEN_DIM = '#00cc33';
const MATRIX_MIN_STREAM_DIST = 85;
// Refresh all sensor-derived data (sun, moon, UV) in one pass
function refreshSensorCache() {
const now = Date.now();
if (now - sensorCacheTime < SENSOR_CACHE_MS) return;
sensorCacheTime = now;
try {
const cfg = window.ForkUWeatherAwareConfig || {};
const ha = getHomeAssistant();
if (!ha || !ha.hass) {
return;
}
// UV index
const uvEntityId = cfg.uv_index_entity || 'sensor.uv_index';
if (uvEntityId) {
const uvEntity = ha.hass.states[uvEntityId];
if (uvEntity && uvEntity.state !== 'unavailable' && uvEntity.state !== 'unknown') {
const val = parseFloat(uvEntity.state);
cachedUvIndex = isNaN(val) ? null : val;
} else {
cachedUvIndex = null;
}
} else {
cachedUvIndex = null;
}
if (cachedUvIndex === undefined || cachedUvIndex === null) {
const weatherEntity = ha.hass.states[cfg.weather_entity || WEATHER_ENTITY];
if (weatherEntity?.attributes) {
const uv = weatherEntity.attributes.uv_index ?? weatherEntity.attributes.uv;
if (uv !== undefined) {
const val = parseFloat(uv);
if (!isNaN(val)) cachedUvIndex = val;
}
}
}
// Sun position
const sunId = cfg.sun_entity || 'sun.sun';
const sun = ha.hass.states[sunId];
if (sun) {
const aboveHorizon = sun.state === 'above_horizon';
const elevation = parseFloat(sun.attributes?.elevation) || 0;
const azimuth = parseFloat(sun.attributes?.azimuth);
if (!isNaN(azimuth)) {
let x = (azimuth - 90) / 180;
x = Math.max(0, Math.min(1, x));
const y = 0.08 + 0.22 * (1 - Math.max(0, elevation) / 90);
cachedSunPosition = { x, y, aboveHorizon };
} else {
cachedSunPosition = aboveHorizon ? { x: 0.9, y: 0.1, aboveHorizon } : null;
}
} else {
cachedSunPosition = null;
}
// Moon position and distance
// 1) Single entity with attributes (Moon Astro, frlequ moon-phase): azimuth, elevation/altitude, distance
// 2) Lunar Phase integration: 3 separate sensors (Moon Azimuth, Moon Altitude, Moon Distance) – state holds value
const moonPosId = cfg.moon_position_entity;
const moonPhaseId = cfg.moon_phase_entity;
const moonAzId = cfg.moon_azimuth_entity;
const moonAltId = cfg.moon_altitude_entity;
const moonDistId = cfg.moon_distance_entity;
let moonPos = { x: 0.75, y: 0.12, distance: null };
for (const eid of [moonPosId, moonPhaseId].filter(Boolean)) {
const ent = ha.hass.states[eid];
if (!ent?.attributes) continue;
const attrs = ent.attributes;
const azimuth = parseFloat(attrs.azimuth ?? attrs.moon_azimuth_deg);
const elev = parseFloat(attrs.elevation ?? attrs.altitude ?? attrs.moon_altitude_deg);
const distKm = parseFloat(attrs.distance ?? attrs.moon_distance_km);
if (!isNaN(azimuth) && !isNaN(elev) && elev > 0) {
let x = (azimuth - 90) / 180;
moonPos.x = Math.max(0, Math.min(1, x));
moonPos.y = 0.08 + 0.22 * (1 - Math.min(90, elev) / 90);
} else if (!isNaN(elev) && elev > 0) {
moonPos.y = 0.08 + 0.22 * (1 - Math.min(90, elev) / 90);
}
if (!isNaN(distKm) && distKm > 0) moonPos.distance = distKm;
}
// Lunar Phase: read from 3 separate sensors (state = numeric value)
if (moonAzId || moonAltId || moonDistId) {
const azEnt = moonAzId ? ha.hass.states[moonAzId] : null;
const altEnt = moonAltId ? ha.hass.states[moonAltId] : null;
const distEnt = moonDistId ? ha.hass.states[moonDistId] : null;
const azimuth = azEnt ? parseFloat(azEnt.state) : NaN;
const elev = altEnt ? parseFloat(altEnt.state) : NaN;
const distKm = distEnt ? parseFloat(distEnt.state) : NaN;
if (!isNaN(azimuth) && !isNaN(elev) && elev > 0) {
let x = (azimuth - 90) / 180;
moonPos.x = Math.max(0, Math.min(1, x));
moonPos.y = 0.08 + 0.22 * (1 - Math.min(90, elev) / 90);
} else if (!isNaN(elev) && elev > 0) {
moonPos.y = 0.08 + 0.22 * (1 - Math.min(90, elev) / 90);
}
if (!isNaN(distKm) && distKm > 0) moonPos.distance = distKm;
}
cachedMoonPosition = moonPos;
} catch (e) {
// Keep previous cache on error
}
}
// Weather particle configurations
const weatherConfigs = {
'rainy': {
maxParticles: 50,
color: 'rgba(174, 194, 224, 0.45)',
speedMin: 0.8,
speedMax: 1.5,
sizeMin: 1,
sizeMax: 2,
swayAmount: 0.5,
type: 'rain',
rainLength: 14
},
'pouring': {
maxParticles: 70,
color: 'rgba(174, 194, 224, 0.5)',
speedMin: 1,
speedMax: 2,
sizeMin: 1,
sizeMax: 2,
swayAmount: 0.6,
type: 'rain',
rainLength: 18
},
'cloudy': {
maxParticles: 13,
color: 'rgba(180, 180, 180, 0.10)',
speedMin: 0.3,
speedMax: 0.8,
sizeMin: 80,
sizeMax: 150,
swayAmount: 0.5,
type: 'clouds'
},
'partlycloudy': {
maxParticles: 8,
color: 'rgba(200, 200, 200, 0.08)',
speedMin: 0.4,
speedMax: 1,
sizeMin: 70,
sizeMax: 130,
swayAmount: 0.6,
type: 'clouds'
},
'fog': {
maxParticles: 70,
color: 'rgba(220, 220, 220, 0.05)',
speedMin: 0.2,
speedMax: 0.4,
sizeMin: 1000,
sizeMax: 2000,
swayAmount: 0.5,
type: 'fog'
},
'snowy': {
maxParticles: 40,
color: 'rgba(255, 255, 255, 0.4)',
speedMin: 0.5,
speedMax: 2,
sizeMin: 2,
sizeMax: 5,
swayAmount: 1.5,
type: 'snow'
},
'snowy-rainy': {
maxParticles: 0, // handled by snowy2 overlay + window droplets
color: 'rgba(210, 220, 240, 0.38)',
speedMin: 0.5,
speedMax: 1.2,
sizeMin: 1.2,
sizeMax: 3.5,
swayAmount: 1.1,
type: 'snow'
},
'lightning': {
maxParticles: 0,
type: 'lightning'
},
'lightning-rainy': {
maxParticles: 50,
color: 'rgba(174, 194, 224, 0.45)',
speedMin: 0.8,
speedMax: 1.5,
sizeMin: 1,
sizeMax: 2,
swayAmount: 0.5,
type: 'rain',
rainLength: 14,
hasLightning: true
},
'clear-night': {
maxParticles: 36,
type: 'stars'
},
'sunny': {
maxParticles: 0,
type: 'sunny'
},
'sunny2': {
maxParticles: 0,
type: 'sunny2'
},
'rainy-drizzle': {
maxParticles: 28,
color: 'rgba(174, 194, 224, 0.38)',
speedMin: 0.35,
speedMax: 0.65,
sizeMin: 0.9,
sizeMax: 1.5,
swayAmount: 0.3,
type: 'rain',
rainLength: 9
},
// Additional states for compatibility
'windy': {
maxParticles: 8,
color: 'rgba(200, 200, 200, 0.06)',
speedMin: 2,
speedMax: 4,
sizeMin: 70,
sizeMax: 130,
swayAmount: 0.6,
type: 'clouds'
},
'hail': {
// Strong, clearly visible hail – dense, fast, big chunks
maxParticles: 24,
color: 'rgba(242, 250, 255, 0.95)',
speedMin: 7, // very fast start
speedMax: 14, // brutal impacts
sizeMin: 6,
sizeMax: 10,
swayAmount: 0, // no wind sway – straight meteors
type: 'hail'
},
'exceptional': {
maxParticles: 0,
type: 'sunny'
},
'snowy2': {
maxParticles: 0,
type: 'snowy2'
},
'snowy3': {
maxParticles: 0,
type: 'snowy3'
}
};
const SNOWY2_LAYERS = [
{ sizeMin: 24, sizeMax: 40, speedFactor: 0.12, swayAmpMin: 10, swayAmpMax: 30, opacity: 1, blur: 0, colorMin: 255, colorMax: 255 },
{ sizeMin: 20, sizeMax: 28, speedFactor: 0.09, swayAmpMin: 10, swayAmpMax: 25, opacity: 0.85, blur: 2, colorMin: 255, colorMax: 255 },
{ sizeMin: 16, sizeMax: 24, speedFactor: 0.07, swayAmpMin: 10, swayAmpMax: 20, opacity: 0.75, blur: 4, colorMin: 255, colorMax: 255 },
{ sizeMin: 12, sizeMax: 18, speedFactor: 0.05, swayAmpMin: 10, swayAmpMax: 20, opacity: 0.65, blur: 5, colorMin: 220, colorMax: 229 },
{ sizeMin: 10, sizeMax: 14, speedFactor: 0.03, swayAmpMin: 10, swayAmpMax: 20, opacity: 0.55, blur: 7, colorMin: 210, colorMax: 219 },
{ sizeMin: 8, sizeMax: 12, speedFactor: 0.01, swayAmpMin: 10, swayAmpMax: 20, opacity: 0.4, blur: 30, colorMin: 200, colorMax: 209 }
];
// Texture Cache for performance optimization
const textureCache = {};
function getCloudPuffTexture(color) {
const key = `cloud_${color}`;
if (textureCache[key]) return textureCache[key];
const size = 64;
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
if (!ctx) return null;
const half = size / 2;
const gradient = ctx.createRadialGradient(half, half, 0, half, half, half);
gradient.addColorStop(0, color);
gradient.addColorStop(0.6, color.replace(/[\d.]+\)$/g, '0.02)'));
gradient.addColorStop(1, 'rgba(180, 180, 180, 0)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, size, size);
textureCache[key] = canvas;
return canvas;
}
function getFogTexture(color, theme) {
const key = `fog_${color}_${theme}`;
if (textureCache[key]) return textureCache[key];
const width = 256;
const height = 1;
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) return null;
const grad = ctx.createLinearGradient(0, 0, width, 0);
if (theme === 'light') {
grad.addColorStop(0, 'rgba(200, 200, 200, 0)');
grad.addColorStop(0.5, color || 'rgba(210,210,210,0.25)');
grad.addColorStop(1, 'rgba(200, 200, 200, 0)');
} else {
grad.addColorStop(0, 'rgba(220, 220, 220, 0)');
grad.addColorStop(0.5, color);
grad.addColorStop(1, 'rgba(220, 220, 220, 0)');
}
ctx.fillStyle = grad;
ctx.fillRect(0, 0, width, height);
textureCache[key] = canvas;
return canvas;
}
function getSmogTexture(isMobile, theme) {
const key = `smog_${isMobile}_${theme}`;
if (textureCache[key]) return textureCache[key];
const size = 128;
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
if (!ctx) return null;
const half = size / 2;
// Use a generic gradient structure, we can modulate opacity via globalAlpha
const grad = ctx.createRadialGradient(half, half, 0, half, half, half);
const scale = theme === 'light' ? 1.2 : 1;
// Base colors (using max opacity, will fade with globalAlpha)
grad.addColorStop(0, `rgba(138,140,145,${Math.min(1, 0.38 * scale)})`);
grad.addColorStop(0.3, `rgba(128,130,135,${Math.min(1, 0.25 * scale)})`);
grad.addColorStop(0.6, `rgba(118,120,125,${Math.min(1, 0.11 * scale)})`);
grad.addColorStop(0.9, `rgba(108,110,115,${Math.min(1, 0.035 * scale)})`);
grad.addColorStop(1, 'rgba(98,100,105,0)');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, size, size);
textureCache[key] = canvas;
return canvas;
}
function getSunGlowTexture(isHighUv) {
const key = `sun_glow_${isHighUv}`;
if (textureCache[key]) return textureCache[key];
const radius = 500;
const size = radius * 2;
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
if (!ctx) return null;
const half = size / 2;
const sunGradient = ctx.createRadialGradient(half, half, 0, half, half, radius);
if (isHighUv) {
sunGradient.addColorStop(0, 'rgba(255, 140, 50, 0.35)');
sunGradient.addColorStop(0.2, 'rgba(255, 110, 40, 0.22)');
sunGradient.addColorStop(0.5, 'rgba(255, 90, 30, 0.12)');
sunGradient.addColorStop(0.8, 'rgba(255, 70, 20, 0.04)');
sunGradient.addColorStop(1, 'rgba(255, 50, 10, 0)');
} else {
sunGradient.addColorStop(0, 'rgba(255, 220, 120, 0.22)');
sunGradient.addColorStop(0.2, 'rgba(255, 200, 90, 0.14)');
sunGradient.addColorStop(0.5, 'rgba(255, 185, 70, 0.07)');
sunGradient.addColorStop(0.8, 'rgba(255, 160, 50, 0.02)');
sunGradient.addColorStop(1, 'rgba(255, 140, 40, 0)');
}
ctx.fillStyle = sunGradient;
ctx.fillRect(0, 0, size, size);
textureCache[key] = canvas;
return canvas;
}
// Particle class
class Particle {
constructor(config) {
this.reset(config);
if (config.type === 'stars') {
this.y = Math.random() * (window.innerHeight * 0.5);
this.twinkleSpeed = 0.02 + Math.random() * 0.03;
this.twinklePhase = Math.random() * Math.PI * 2;
} else {
this.y = Math.random() * window.innerHeight;
}
}
reset(config) {
this.x = Math.random() * window.innerWidth;
if (config.type === 'stars') {
this.x = Math.random() * window.innerWidth;
this.y = Math.random() * (window.innerHeight * 0.3);
this.size = 1 + Math.random() * 1.5;
this.phase = Math.random() * 6;
this.cycleLength = 6;
this.opacity = 0;
} else {
if (config.type === 'clouds') {
this.x = Math.random() * window.innerWidth;
this.y = Math.random() * (window.innerHeight * 0.22);
} else {
this.y = -10;
}
this.speed = config.speedMin + Math.random() * (config.speedMax - config.speedMin);
this.size = config.sizeMin + Math.random() * (config.sizeMax - config.sizeMin);
this.sway = (Math.random() - 0.5) * config.swayAmount;
this.opacity = 0.5 + Math.random() * 0.5;
if (config.type === 'rain') {
this.rainLength = (config.rainLength || 14) * (0.85 + Math.random() * 0.3);
}
if (config.type === 'hail') {
this.rotation = Math.random() * Math.PI * 2;
}
if (config.type === 'clouds') {
this.puffCount = 5 + Math.floor(Math.random() * 3);
this.puffSizes = [];
for (let i = 0; i < this.puffCount; i++) {
this.puffSizes.push(0.4 + Math.random() * 0.3);
}
}
}
this.type = config.type;
}
update(config) {
if (this.type === 'stars') {
this.phase += 0.016 * getSpeedFactor('stars');
if (this.phase >= this.cycleLength) {
this.phase = 0;
this.x = Math.random() * window.innerWidth;
this.y = Math.random() * (window.innerHeight * 0.3);
}
if (this.phase < 1) {
this.opacity = this.phase;
} else if (this.phase < 3) {
this.opacity = 0.8 + Math.sin((this.phase - 1) * Math.PI) * 0.2;
} else if (this.phase < 4) {
this.opacity = 1 - (this.phase - 3);
} else {
this.opacity = 0;
}
return;
}
if (this.type === 'hail') {
// Meteoroid-like fall: no wind sway, accelerating towards ground.
// We don't have deltaMs here, so use a normalized step based on speed and hail factor.
const hailFactor = getSpeedFactor('hail');
const accel = 0.12 * hailFactor;
this.speed += accel;
this.y += this.speed * 0.9 * hailFactor;
if (this.y > window.innerHeight + this.size * 2) {
this.reset(config);
this.y = -10;
}
return;
}
if (this.type === 'clouds' || this.type === 'fog') {
const windKmh = cachedWindData.speed;
const windScale = Math.max(0.05, Math.min(1.2, windKmh / 35));
const cfg = window.ForkUWeatherAwareConfig || {};
const mult = (cfg.cloud_speed_multiplier != null && !isNaN(parseFloat(cfg.cloud_speed_multiplier))) ? parseFloat(cfg.cloud_speed_multiplier) : 1;
const moveSpeed = (this.type === 'clouds' ? this.speed * windScale : this.speed * Math.max(0.03, windScale * 0.5)) * mult * getSpeedFactor(this.type);
this.x += moveSpeed;
if (this.type === 'clouds'){
this.y += Math.sin(this.x * 0.01) * 0.2;
this.y = Math.min(this.y, window.innerHeight * 0.22);
} else{
this.y += Math.sin(this.x * 0.01) * 0.02;
}
if (this.x > window.innerWidth + this.size) {
this.x = -this.size;
this.y = Math.random() * (window.innerHeight * (this.type === 'clouds' ? 0.22 : 1));
}
return;
}
const swayFactor = getWindSwayFactor();
const windSway = -Math.sin(cachedWindData.bearing * Math.PI / 180) * cachedWindData.speed * 0.06 * swayFactor;
const precipFactor = getSpeedFactor(this.type);
// Vertical fall speed depends on rain/snow speed and wind speed, but NOT on swayFactor
this.y += this.speed * cachedPrecipMultiplier * (1 + cachedWindData.speed * 0.03) * precipFactor;
this.x += this.sway + windSway;
if (this.type === 'hail') this.rotation += 0.18 * precipFactor;
if (this.y > window.innerHeight) {
this.reset(config);
}
if (this.x < 0 || this.x > window.innerWidth) {
this.x = Math.random() * window.innerWidth;
}
}
draw() {
ctx.globalAlpha = this.opacity;
if (this.type === 'stars') {
if (this.opacity > 0) {
ctx.globalAlpha = this.opacity * 0.7;
ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
ctx.shadowColor = 'rgba(200, 220, 255, 0.6)';
ctx.shadowBlur = 4 + this.opacity * 3;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size * 0.8, 0, Math.PI * 2);
ctx.fill();
ctx.shadowBlur = 0;
}
} else if (this.type === 'clouds') {
const baseOpacity = this.opacity * 0.6;
const baseColor = weatherConfigs[currentWeather]?.color || 'rgba(180, 180, 180, 0.10)';
const cloudTex = getCloudPuffTexture(baseColor);
if (cloudTex) {
for (let i = 0; i < this.puffCount; i++) {
const angle = (i / this.puffCount) * Math.PI * 2;
const puffSize = this.size * this.puffSizes[i];
const offsetX = Math.cos(angle) * this.size * 0.4;
const offsetY = Math.sin(angle) * this.size * 0.25;
ctx.globalAlpha = baseOpacity;
// Draw cached texture centered at puff position
ctx.drawImage(cloudTex, this.x + offsetX - puffSize, this.y + offsetY - puffSize, puffSize * 2, puffSize * 2);
}
}
ctx.globalAlpha = 1;
} else if (this.type === 'snow') {
const theme = getThemeMode();
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
if (theme === 'light') {
// On light themes, use solid white snow so it stands out over cards
ctx.fillStyle = 'rgba(255, 255, 255, 0.98)';
} else {
ctx.fillStyle = weatherConfigs[currentWeather]?.color || 'rgba(255, 255, 255, 0.4)';
}
ctx.fill();
} else if (this.type === 'mixed') {
const isMixed = Math.random() > 0.5;
if (isMixed) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
const theme = getThemeMode();
if (theme === 'light') {
ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
} else {
ctx.fillStyle = weatherConfigs[currentWeather]?.color || 'rgba(200, 210, 230, 0.35)';
}
ctx.fill();
} else {
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.x + this.sway, this.y + this.size * 4);
const theme = getThemeMode();
ctx.strokeStyle = theme === 'light'
? 'rgba(140, 160, 190, 0.9)'
: (weatherConfigs[currentWeather]?.color || 'rgba(200, 210, 230, 0.35)');
ctx.lineWidth = this.size * 0.7;
ctx.stroke();
}
} else if (this.type === 'rain') {
const config = weatherConfigs[currentWeather] || {};
const cfg = window.ForkUWeatherAwareConfig || {};
const len = this.rainLength != null ? this.rainLength : (this.size * 4);
const halfW = Math.max(1.2, Math.min(2.5, len * 0.12));
const maxTiltDeg = (cfg.rain_max_tilt_deg != null && !isNaN(parseFloat(cfg.rain_max_tilt_deg))) ? Math.abs(parseFloat(cfg.rain_max_tilt_deg)) : 30;
const windMin = (cfg.rain_wind_min_kmh != null && !isNaN(parseFloat(cfg.rain_wind_min_kmh))) ? parseFloat(cfg.rain_wind_min_kmh) : 3;
const windSpeed = cachedWindData.speed;
const bearing = cachedWindData.bearing * Math.PI / 180;
let tiltDeg = 0;
if (windSpeed >= windMin && maxTiltDeg > 0) {
const windDirX = -Math.sin(bearing);
const magnitude = Math.min(maxTiltDeg, (windSpeed / 2));
// Flip sign so the visible droplet shape leans in the same direction it moves
tiltDeg = -Math.sign(windDirX) * magnitude;
}
const tiltRad = tiltDeg * Math.PI / 180;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(tiltRad);
ctx.beginPath();
ctx.moveTo(-halfW, 0);
ctx.lineTo(0, -len);
ctx.lineTo(halfW, 0);
ctx.arc(0, 0, halfW, 0, Math.PI);
ctx.closePath();
const theme = getThemeMode();
if (theme === 'light') {
// Slightly darker, more visible on light themes
ctx.fillStyle = 'rgba(120, 145, 170, 0.55)';
} else {
ctx.fillStyle = config.color || 'rgba(175, 195, 204, 0.35)';
}
ctx.fill();
ctx.restore();
} else if (this.type === 'fog') {
const theme = getThemeMode();
const fogColor = weatherConfigs[currentWeather].color;
const fogTex = getFogTexture(fogColor, theme);
if (fogTex) {
ctx.globalAlpha = this.opacity * 0.2;
// Stretch the 1px high texture to full height (300px) and width
ctx.drawImage(fogTex, this.x - this.size, this.y - 15, this.size * 2000, 300);
ctx.globalAlpha = 1;
}
} else if (this.type === 'hail') {
// Bright, circular hailstones with icy gradient – very visible on both themes
const theme = getThemeMode();
const r = (this.size || 6) * 1.2;
const cx = this.x;
const cy = this.y;
const grad = ctx.createRadialGradient(cx, cy, 0, cx, cy, r);
if (theme === 'light') {
grad.addColorStop(0, 'rgba(255,255,255,1)');
grad.addColorStop(0.3, 'rgba(245,250,255,1)');
grad.addColorStop(0.8, 'rgba(210,225,245,0.9)');
grad.addColorStop(1, 'rgba(180,200,230,0.7)');
} else {
grad.addColorStop(0, 'rgba(255,255,255,1)');
grad.addColorStop(0.3, 'rgba(245,250,255,0.95)');
grad.addColorStop(0.8, 'rgba(220,235,250,0.85)');
grad.addColorStop(1, 'rgba(190,210,235,0.6)');
}
ctx.fillStyle = grad;
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.fill();
}
ctx.globalAlpha = 1;
}
}
// Initialize canvas
function initCanvas() {
if (canvas) {
log('Canvas already exists, skipping initialization');
return;
}
canvas = document.createElement('canvas');
canvas.id = 'fork-u-weather-aware-canvas';
canvas.style.position = 'fixed';
canvas.style.top = '0';
canvas.style.left = '0';
canvas.style.width = '100vw';
canvas.style.height = '100vh';
canvas.style.pointerEvents = 'none';
canvas.style.zIndex = '9999';
const dpr = getEffectiveDpr();
canvas.width = window.innerWidth * dpr;
canvas.height = window.innerHeight * dpr;
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
log('Canvas initialized', {
width: canvas.width,
height: canvas.height,
dpr: dpr
});
initOverlayCanvases();
applySpatialZIndex();
}
// Initialize Matrix (gaming) and Smog overlay canvases
function initOverlayCanvases() {
const dpr = getEffectiveDpr();
if (!matrixCanvas) {
matrixCanvas = document.createElement('canvas');
matrixCanvas.id = 'fork-u-weather-aware-matrix';
matrixCanvas.style.cssText = 'position:fixed;top:0;left:0;width:100vw;height:100vh;pointer-events:none;z-index:10000;display:none';
matrixCanvas.width = window.innerWidth * dpr;
matrixCanvas.height = window.innerHeight * dpr;
document.body.appendChild(matrixCanvas);
matrixCtx = matrixCanvas.getContext('2d');
matrixCtx.scale(dpr, dpr);
}
if (!smogCanvas) {
smogCanvas = document.createElement('canvas');
smogCanvas.id = 'fork-u-weather-aware-smog';
smogCanvas.style.cssText = 'position:fixed;top:0;left:0;width:100vw;height:100vh;pointer-events:none;z-index:10001;display:none';
smogCanvas.width = window.innerWidth * dpr;
smogCanvas.height = window.innerHeight * dpr;
document.body.appendChild(smogCanvas);
smogCtx = smogCanvas.getContext('2d');
smogCtx.scale(dpr, dpr);
}
if (!snowy2Canvas) {
snowy2Canvas = document.createElement('canvas');
snowy2Canvas.id = 'fork-u-weather-aware-snowy2';
snowy2Canvas.style.cssText = 'position:fixed;top:0;left:0;width:100vw;height:100vh;pointer-events:none;z-index:9998;display:none';
snowy2Canvas.width = window.innerWidth * dpr;
snowy2Canvas.height = window.innerHeight * dpr;
document.body.appendChild(snowy2Canvas);
snowy2Ctx = snowy2Canvas.getContext('2d');
snowy2Ctx.scale(dpr, dpr);
}
applySpatialZIndex();
}
function initSnowy2Layers() {
const W = window.innerWidth;
const H = window.innerHeight;
const SEGMENT_WIDTH = 5;
const cfg = getMobilePerfConfig();
let totalFlakes = (isMobileDevice() && cfg.mobile_snowy2_light) ? 180 : 300;
if (currentWeather === 'snowy-rainy') {
totalFlakes = Math.round(totalFlakes * 0.5);
}
snowy2Layers = SNOWY2_LAYERS.map((lp, idx) => {
const numFlakes = Math.floor(totalFlakes / SNOWY2_LAYERS.length);
const snowflakes = [];
for (let i = 0; i < numFlakes; i++) {
const size = lp.sizeMin + Math.random() * (lp.sizeMax - lp.sizeMin);
const fallSpeed = size * lp.speedFactor + Math.random() * 0.5;
const swayAmp = lp.swayAmpMin + Math.random() * (lp.swayAmpMax - lp.swayAmpMin);
const cv = lp.colorMin + Math.floor(Math.random() * (lp.colorMax - lp.colorMin + 1));
snowflakes.push({
x: Math.random() * W,
y: Math.random() * -H,
size, fallSpeed, swayAmp, swaySpeed: 0.01 + Math.random() * 0.02,
swayOffset: Math.random() * Math.PI * 2,
opacity: lp.opacity, blur: lp.blur,
color: `rgba(${cv},${cv},${cv},${lp.opacity})`,
rotation: Math.random() * Math.PI * 2,
rotationSpeed: (Math.random() - 0.5) * 0.02
});
}
const NUM_SEG = Math.ceil(W / SEGMENT_WIDTH);
const pileHeights = [];
for (let j = 0; j < NUM_SEG; j++) {
if (j === 0) pileHeights[j] = H - 30 + (Math.random() * 10 - 5);
else {
let h = pileHeights[j - 1] + (Math.random() * 10 - 5);
pileHeights[j] = Math.max(H - 100, Math.min(H - 10, h));
}
}
for (let iter = 0; iter < 2; iter++) {
const t = [...pileHeights];
for (let i = 1; i < NUM_SEG - 1; i++)
t[i] = (pileHeights[i - 1] + pileHeights[i] + pileHeights[i + 1]) / 3;
pileHeights.splice(0, pileHeights.length, ...t);
}
return { snowflakes, pileHeights, layerProps: lp, SEGMENT_WIDTH, NUM_SEG };
});
}
function updateSnowy2Effect(deltaMs) {