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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
|
//! Parser and sampler for the original sky.ske atmosphere schedule.
//!
//! The game stores a schedule rather than a list of named weather presets.
//! A schedule contains one or more compressed in-game days. Track durations
//! are real seconds, while key dates are hours, minutes, and seconds in the
//! in-game day. Sampling selects tracks in file order and interpolates the
//! two surrounding keys on the complete cyclic schedule, including adjacent
//! track boundaries.
//!
//! Fields not consumed by the original atmosphere renderer keep neutral names
//! such as raw, header_values, and parameters. They are retained so a later
//! renderer can use them without changing the file parser.
use fparkan_binary::{read_lp_bytes, Cursor, DecodeError};
use std::fmt;
/// sky.ske header marker.
pub const SKE_HEADER_MARKER: i32 = -1;
/// Supported sky.ske version.
pub const SKE_VERSION: u32 = 5;
/// Number of color parameters emitted by the sky sampler.
pub const SKY_COLOR_COUNT: usize = 13;
/// Number of packed colors in every on-disk key palette.
pub const KEY_COLOR_COUNT: usize = 15;
/// Number of fixed length-prefixed strings in every key.
pub const KEY_STRING_COUNT: usize = 6;
/// Number of words in an on-disk date.
pub const DATE_WORD_COUNT: usize = 8;
const MAX_TRACKS: u32 = 256;
const MAX_KEYS: u32 = 16_384;
const MAX_STRING_BYTES: u32 = 64 * 1024;
const MAX_REFERENCES: u32 = 256;
const DAY_SECONDS: f32 = 86_400.0;
const COLOR_MIN_COMPONENT: f32 = 80.0 / 255.0;
const WEATHER_ALPHA: f32 = 150.0 / 255.0;
/// A decoded atmosphere error.
#[derive(Clone, Debug, PartialEq)]
pub enum AtmosphereError {
/// A bounded binary read failed.
Decode(DecodeError),
/// The file marker or version is not supported.
InvalidHeader {
/// Header marker read from the file.
marker: i32,
/// Header version read from the file.
version: u32,
},
/// A track has a version other than one.
InvalidTrackVersion {
/// Track number.
track_index: usize,
/// Version read from the file.
version: u32,
},
/// A key has a version other than three.
InvalidKeyVersion {
/// Track number.
track_index: usize,
/// Key number.
key_index: usize,
/// Version read from the file.
version: u32,
},
/// A date contains an impossible time of day.
InvalidDate {
/// Context in which the date appeared.
context: &'static str,
/// Hour word.
hours: u32,
/// Minute word.
minutes: u32,
/// Second word.
seconds: u32,
},
/// A key date is earlier than the previous key date.
NonMonotonicKey {
/// Track number.
track_index: usize,
/// Key number that is out of order.
key_index: usize,
/// Previous key time in seconds.
previous_seconds: u32,
/// Current key time in seconds.
current_seconds: u32,
},
/// A track contains no key and therefore cannot be sampled.
EmptyTrack {
/// Track number.
track_index: usize,
},
/// A floating point value in a key is NaN or infinite.
NonFiniteValue {
/// Track number.
track_index: usize,
/// Key number.
key_index: usize,
/// Neutral field name.
field: &'static str,
/// Array element.
index: usize,
},
/// A real duration could not be represented.
InvalidDuration {
/// Track number.
track_index: usize,
},
}
impl From<DecodeError> for AtmosphereError {
fn from(value: DecodeError) -> Self {
Self::Decode(value)
}
}
impl fmt::Display for AtmosphereError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Decode(source) => write!(f, "{source}"),
Self::InvalidHeader { marker, version } => {
write!(f, "unsupported sky.ske header marker={marker} version={version}")
}
Self::InvalidTrackVersion {
track_index,
version,
} => write!(f, "unsupported sky.ske track {track_index} version {version}"),
Self::InvalidKeyVersion {
track_index,
key_index,
version,
} => write!(
f,
"unsupported sky.ske track {track_index} key {key_index} version {version}"
),
Self::InvalidDate {
context,
hours,
minutes,
seconds,
} => write!(
f,
"invalid sky.ske {context} time {hours:02}:{minutes:02}:{seconds:02}"
),
Self::NonMonotonicKey {
track_index,
key_index,
previous_seconds,
current_seconds,
} => write!(
f,
"sky.ske track {track_index} key {key_index} goes backward from {previous_seconds}s to {current_seconds}s"
),
Self::EmptyTrack { track_index } => {
write!(f, "sky.ske track {track_index} has no keys")
}
Self::NonFiniteValue {
track_index,
key_index,
field,
index,
} => write!(
f,
"sky.ske track {track_index} key {key_index} has non-finite {field}[{index}]"
),
Self::InvalidDuration { track_index } => {
write!(f, "sky.ske track {track_index} has an invalid duration")
}
}
}
}
impl std::error::Error for AtmosphereError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Decode(source) => Some(source),
Self::InvalidHeader { .. }
| Self::InvalidTrackVersion { .. }
| Self::InvalidKeyVersion { .. }
| Self::InvalidDate { .. }
| Self::NonMonotonicKey { .. }
| Self::EmptyTrack { .. }
| Self::NonFiniteValue { .. }
| Self::InvalidDuration { .. } => None,
}
}
}
/// The eight words copied by the original date reader.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct SkeDate {
/// Raw date words, preserved in file order.
pub words: [u32; DATE_WORD_COUNT],
}
impl SkeDate {
/// Constructs a date from its raw words.
#[must_use]
pub const fn from_words(words: [u32; DATE_WORD_COUNT]) -> Self {
Self { words }
}
/// In-game hour word.
#[must_use]
pub const fn hours(self) -> u32 {
self.words[3]
}
/// In-game minute word.
#[must_use]
pub const fn minutes(self) -> u32 {
self.words[4]
}
/// In-game second word.
#[must_use]
pub const fn seconds(self) -> u32 {
self.words[5]
}
/// Returns the time of day in seconds.
#[must_use]
pub const fn seconds_of_day(self) -> u32 {
self.hours() * 3_600 + self.minutes() * 60 + self.seconds()
}
/// Returns the hour/minute position used by the original atmosphere
/// scheduler. The serialized seconds word is deliberately ignored by the
/// scheduler and is retained only in [`Self::words`].
#[must_use]
pub const fn hour_minute_seconds(self) -> u32 {
(self.hours() * 60 + self.minutes()) * 60
}
/// Returns the hour and minute duration marker used by the original track
/// constructor.
#[must_use]
pub const fn real_duration_marker(self) -> u32 {
self.hour_minute_seconds()
}
}
/// A packed original ARGB color (0xAARRGGBB).
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct PackedColor(pub u32);
impl PackedColor {
/// Returns the raw ARGB word.
#[must_use]
pub const fn raw(self) -> u32 {
self.0
}
/// Decodes the word to normalized RGBA components.
#[must_use]
pub fn rgba(self) -> [f32; 4] {
[
f32::from((self.0 >> 16) as u8) / 255.0,
f32::from((self.0 >> 8) as u8) / 255.0,
f32::from(self.0 as u8) / 255.0,
f32::from((self.0 >> 24) as u8) / 255.0,
]
}
/// Interpolates two packed colors in normalized channel space and packs
/// the result back to ARGB.
#[must_use]
pub fn lerp(self, other: Self, factor: f32) -> Self {
let a = self.rgba();
let b = other.rgba();
Self::from_rgba([
lerp(a[0], b[0], factor),
lerp(a[1], b[1], factor),
lerp(a[2], b[2], factor),
lerp(a[3], b[3], factor),
])
}
/// Packs normalized RGBA components as ARGB.
#[must_use]
pub fn from_rgba(rgba: [f32; 4]) -> Self {
let channel = |value: f32| -> u32 { (value.clamp(0.0, 1.0) * 255.0).round() as u32 };
Self(
(channel(rgba[3]) << 24)
| (channel(rgba[0]) << 16)
| (channel(rgba[1]) << 8)
| channel(rgba[2]),
)
}
}
/// A length-prefixed string from a key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AtmosphereString {
/// Original bytes without a terminating NUL.
pub raw: Vec<u8>,
/// Lossy UTF-8 view. Resource names in the original files are ASCII.
pub text: String,
}
impl AtmosphereString {
/// Returns the decoded text.
#[must_use]
pub fn as_str(&self) -> &str {
&self.text
}
/// Whether the length-prefixed value is empty.
#[must_use]
pub fn is_empty(&self) -> bool {
self.raw.is_empty()
}
}
/// A key kind from the original atmosphere dispatcher.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AtmosphereKind {
/// Starts or updates the sun object.
SunStart,
/// Stops the sun object.
SunStop,
/// An unclassified state key with raw kind two.
State2,
/// Starts rain.
RainStart,
/// Stops rain.
RainStop,
/// Starts snow.
SnowStart,
/// Stops snow.
SnowStop,
/// An interpolated state key with raw kind seven.
State7,
/// Starts lightning.
LightningStart,
/// Stops lightning.
LightningStop,
/// A kind not present in the known original dispatcher.
Unknown(u32),
}
impl AtmosphereKind {
/// Converts the raw kind word without discarding unknown values.
#[must_use]
pub const fn from_raw(raw: u32) -> Self {
match raw {
0 => Self::SunStart,
1 => Self::SunStop,
2 => Self::State2,
3 => Self::RainStart,
4 => Self::RainStop,
5 => Self::SnowStart,
6 => Self::SnowStop,
7 => Self::State7,
8 => Self::LightningStart,
9 => Self::LightningStop,
other => Self::Unknown(other),
}
}
/// Returns the original kind word.
#[must_use]
pub const fn raw(self) -> u32 {
match self {
Self::SunStart => 0,
Self::SunStop => 1,
Self::State2 => 2,
Self::RainStart => 3,
Self::RainStop => 4,
Self::SnowStart => 5,
Self::SnowStop => 6,
Self::State7 => 7,
Self::LightningStart => 8,
Self::LightningStop => 9,
Self::Unknown(raw) => raw,
}
}
}
/// One exact key record from a version-five sky.ske.
#[derive(Clone, Debug, PartialEq)]
pub struct AtmosphereKey {
/// Key record version (three in the original files).
pub version: u32,
/// In-game date of this key.
pub date: SkeDate,
/// Decoded key kind.
pub kind: AtmosphereKind,
/// Original kind word.
pub kind_raw: u32,
/// Opaque key word following the kind.
pub raw: u32,
/// Four packed colors at the start of the key payload.
pub header_colors: [PackedColor; 4],
/// Two floating point values following header_colors.
pub header_values: [f32; 2],
/// Fifteen packed colors in the key palette.
pub colors: [PackedColor; KEY_COLOR_COUNT],
/// Six fixed length-prefixed strings.
pub strings: Vec<AtmosphereString>,
/// Four trailing floating point values.
pub parameters: [f32; 4],
/// Length-prefixed resource references.
pub references: Vec<AtmosphereString>,
}
impl AtmosphereKey {
/// Returns non-empty resource references in file order.
#[must_use]
pub fn resource_references(&self) -> Vec<&AtmosphereString> {
self.references
.iter()
.filter(|reference| !reference.is_empty())
.collect()
}
}
/// One atmosphere track.
#[derive(Clone, Debug, PartialEq)]
pub struct AtmosphereTrack {
/// Track version (one in the original files).
pub version: u32,
/// Track start date copied from disk.
pub start: SkeDate,
/// Track end/duration date copied from disk.
pub end: SkeDate,
/// Keys in file order.
pub keys: Vec<AtmosphereKey>,
/// Real seconds assigned to this track by the original constructor.
pub duration_seconds: u32,
}
impl AtmosphereTrack {
/// Returns a key's in-game time in seconds.
#[must_use]
pub fn key_seconds(&self, index: usize) -> Option<u32> {
self.keys.get(index).map(|key| key.date.seconds_of_day())
}
}
/// The final forty bytes of a sky.ske.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct AtmosphereTrailer {
/// Trailer date copied from disk.
pub date: SkeDate,
/// Two opaque trailer words.
pub values: [u32; 2],
}
/// A timeline record emitted by TypedAtmosphere::timeline and
/// TypedAtmosphere::events_between.
#[derive(Clone, Debug, PartialEq)]
pub struct AtmosphereEvent {
/// Track containing the key.
pub track_index: usize,
/// Key containing the event.
pub key_index: usize,
/// In-game time of the event in seconds.
pub day_seconds: f32,
/// Real time from the beginning of the repeating schedule.
pub real_seconds: f32,
/// Decoded event kind.
pub kind: AtmosphereKind,
/// Opaque key word.
pub raw: u32,
/// Non-empty resource references attached to the key.
pub resources: Vec<AtmosphereString>,
}
/// A sky sample with the thirteen color parameters used by the original
/// CSky sampler.
#[derive(Clone, Debug, PartialEq)]
pub struct SkySample {
/// Colors zero through eleven: four header colors, then two reordered
/// groups of four palette colors.
pub colors: [PackedColor; SKY_COLOR_COUNT],
/// The two floating point values copied from the key header values.
pub values: [f32; 2],
/// The two remaining packed color parameters.
pub packed: [PackedColor; 2],
}
/// Birth payload generated by the native atmosphere dispatcher for a named
/// celestial object.
///
/// The dispatcher does not serialize this payload in `sky.ske`. For a kind
/// zero key it chooses the angle pair from the fixed string in slot zero and
/// computes the lifetime from the following matching kind one key. Keeping
/// the generated values beside the sample lets the renderer reproduce the
/// native object without inventing a start time on its first active frame.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SunBirth {
/// Absolute real schedule time at which this interval began.
pub start_seconds: f32,
/// Real schedule duration until the matching stop key.
pub lifetime_seconds: f32,
/// Native birth angles in degrees.
pub initial_angles_degrees: [f32; 2],
/// WEA material row selected by the dispatcher.
pub material_row: usize,
}
/// A sampled sun parameter set. The same payload shape is used for the moon
/// because the original dispatcher creates both from the same object class.
#[derive(Clone, Debug, PartialEq)]
pub struct SunSample {
/// Whether the latest SunStart/SunStop lifecycle interval is active.
pub active: bool,
/// RGB color multiplied by the third trailing key parameter.
pub rgb: [f32; 3],
/// First two trailing key parameters, kept with neutral names.
pub values: [f32; 2],
/// Two packed parameters consumed by the original sun object.
pub packed: [PackedColor; 2],
/// The third trailing parameter used for RGB intensity.
pub intensity: f32,
/// Generated birth payload for the current named interval, if active.
pub birth: Option<SunBirth>,
}
/// A sampled moon parameter set with the native sun-object layout.
pub type MoonSample = SunSample;
/// A sampled precipitation or lightning state.
#[derive(Clone, Debug, PartialEq)]
pub struct WeatherSample {
/// Whether the corresponding start/stop state is active.
pub active: bool,
/// Interpolated fourth trailing key parameter.
pub intensity: f32,
/// Effective color. Active weather follows the original 80/255 RGB floor
/// and 150/255 alpha used by the particle objects.
pub color: [f32; 4],
/// Interpolated source color before the particle floor is applied.
pub raw_color: [f32; 4],
/// Resource references for the currently active interval.
pub resources: Vec<AtmosphereString>,
}
/// A complete atmosphere sample.
#[derive(Clone, Debug, PartialEq)]
pub struct AtmosphereFrame {
/// Requested real schedule time after finite-value sanitization.
pub real_seconds: f32,
/// Selected track.
pub track_index: usize,
/// Real seconds within the selected track.
pub track_seconds: f32,
/// In-game seconds within the selected day.
pub day_seconds: f32,
/// Interpolated sky parameters.
pub sky: SkySample,
/// Interpolated sun parameters.
pub sun: SunSample,
/// Interpolated moon parameters and its independent lifecycle.
pub moon: MoonSample,
/// Rain state.
pub rain: WeatherSample,
/// Snow state.
pub snow: WeatherSample,
/// Lightning state.
pub lightning: WeatherSample,
}
/// A parsed, repeating version-five atmosphere schedule.
#[derive(Clone, Debug, PartialEq)]
pub struct TypedAtmosphere {
/// Header marker.
pub marker: i32,
/// Header version.
pub version: u32,
/// Tracks in file order.
pub tracks: Vec<AtmosphereTrack>,
/// Trailer copied from disk.
pub trailer: AtmosphereTrailer,
}
impl TypedAtmosphere {
/// Parses a complete version-five sky.ske byte slice.
///
/// The parser consumes every byte, bounds all declared counts and strings,
/// checks every floating point field, and preserves unknown kinds and
/// payload words.
///
/// Returns an error for unsupported versions, malformed dates,
/// non-finite values, truncation, or trailing bytes.
pub fn parse(bytes: &[u8]) -> Result<Self, AtmosphereError> {
let mut cursor = Cursor::new(bytes);
let marker = cursor.read_i32_le()?;
let version = cursor.read_u32_le()?;
let track_count = cursor.read_u32_le()?;
if marker != SKE_HEADER_MARKER || version != SKE_VERSION {
return Err(AtmosphereError::InvalidHeader { marker, version });
}
checked_count(track_count, MAX_TRACKS)?;
let mut tracks = Vec::with_capacity(track_count as usize);
for track_index in 0..track_count as usize {
let track_version = cursor.read_u32_le()?;
if track_version != 1 {
return Err(AtmosphereError::InvalidTrackVersion {
track_index,
version: track_version,
});
}
let key_count = cursor.read_u32_le()?;
checked_count(key_count, MAX_KEYS)?;
let start = read_date(&mut cursor, "track start")?;
let end = read_date(&mut cursor, "track end")?;
let duration_seconds = end.real_duration_marker();
if duration_seconds == 0 {
return Err(AtmosphereError::InvalidDuration { track_index });
}
if key_count == 0 {
return Err(AtmosphereError::EmptyTrack { track_index });
}
let mut keys = Vec::with_capacity(key_count as usize);
let mut previous_seconds = None;
for key_index in 0..key_count as usize {
let key = read_key(&mut cursor, track_index, key_index)?;
let current_seconds = key.date.hour_minute_seconds();
if let Some(previous_seconds) = previous_seconds {
if current_seconds < previous_seconds {
return Err(AtmosphereError::NonMonotonicKey {
track_index,
key_index,
previous_seconds,
current_seconds,
});
}
}
previous_seconds = Some(current_seconds);
keys.push(key);
}
tracks.push(AtmosphereTrack {
version: track_version,
start,
end,
keys,
duration_seconds,
});
}
let trailer = AtmosphereTrailer {
date: read_date(&mut cursor, "trailer")?,
values: [cursor.read_u32_le()?, cursor.read_u32_le()?],
};
cursor.require_eof()?;
Ok(Self {
marker,
version,
tracks,
trailer,
})
}
/// Returns the duration of one complete repeating schedule.
#[must_use]
pub fn total_duration_seconds(&self) -> f32 {
self.tracks
.iter()
.map(|track| track.duration_seconds as f32)
.sum()
}
/// Returns the integer real-time offset selected by the trailer for the
/// initial atmosphere clock. The trailer's first word selects a track;
/// its hour/minute words are scaled by that track's duration and floored
/// exactly as in the original constructor.
#[must_use]
pub fn initial_offset_seconds(&self) -> u32 {
let track_index = usize::try_from(self.trailer.date.words[0]).ok();
let Some(track) = track_index.and_then(|index| self.tracks.get(index)) else {
return 0;
};
let scaled = u64::from(track.duration_seconds)
.saturating_mul(u64::from(self.trailer.date.hour_minute_seconds()))
/ DAY_SECONDS_U64;
let track_offset = track_index
.map(|index| self.track_offset_seconds(index))
.unwrap_or(0);
u32::try_from(track_offset.saturating_add(scaled)).unwrap_or(u32::MAX)
}
/// Samples at real seconds from the beginning of the repeating schedule.
///
/// Each track occupies its original real duration. Its in-game day is
/// then traversed from 00:00 through 24:00. Non-finite input is treated
/// as zero so a renderer cannot poison a frame with NaN coordinates.
#[must_use]
pub fn sample(&self, real_seconds: f32) -> AtmosphereFrame {
let real_seconds = if real_seconds.is_finite() {
real_seconds
} else {
0.0
};
if self.tracks.is_empty() {
return empty_frame(real_seconds);
}
let total = self.total_duration_seconds();
let wrapped = real_seconds.rem_euclid(total);
let (track_index, track_seconds) = self.locate_track(wrapped);
let track = &self.tracks[track_index];
let day_seconds = track_seconds / track.duration_seconds as f32 * DAY_SECONDS;
let points = self.schedule_points();
self.sample_track(
real_seconds,
wrapped,
real_seconds,
track_index,
track_seconds,
day_seconds,
&points,
)
}
/// Samples a selected track directly in in-game seconds.
///
/// This is useful for deterministic tests and tools that already have the
/// original game clock. The day wraps at 24 hours.
#[must_use]
pub fn sample_day(&self, track_index: usize, day_seconds: f32) -> AtmosphereFrame {
if self.tracks.is_empty() {
return empty_frame(0.0);
}
let track_index = track_index.min(self.tracks.len() - 1);
let track = &self.tracks[track_index];
let day_seconds = if day_seconds.is_finite() {
day_seconds.rem_euclid(DAY_SECONDS)
} else {
0.0
};
let track_seconds = day_seconds / DAY_SECONDS * track.duration_seconds as f32;
let schedule_seconds = self.track_offset_seconds(track_index) as f32 + track_seconds;
let wrapped = schedule_seconds.rem_euclid(self.total_duration_seconds());
let points = self.schedule_points();
self.sample_track(
schedule_seconds,
wrapped,
schedule_seconds,
track_index,
track_seconds,
day_seconds,
&points,
)
}
/// Returns every key in file order with real schedule offsets.
#[must_use]
pub fn timeline(&self) -> Vec<AtmosphereEvent> {
self.schedule_points()
.into_iter()
.map(|point| {
event_for_key(
point.track_index,
point.key_index,
point.key,
point.real_seconds as f32,
)
})
.collect()
}
/// Returns timeline records crossed by (start, end], including schedule
/// wraparound and track boundaries.
#[must_use]
pub fn events_between(&self, start: f32, end: f32) -> Vec<AtmosphereEvent> {
if self.tracks.is_empty() || !start.is_finite() || !end.is_finite() || end <= start {
return Vec::new();
}
let total = self.total_duration_seconds();
if total <= 0.0 || !total.is_finite() {
return Vec::new();
}
let base = self.timeline();
if base.is_empty() {
return Vec::new();
}
let first_cycle = (start / total).floor() as i64 - 1;
let last_cycle = (end / total).ceil() as i64 + 1;
let mut out = Vec::new();
for cycle in first_cycle..=last_cycle {
let offset = cycle as f32 * total;
for event in &base {
let event_time = event.real_seconds + offset;
if event_time > start && event_time <= end {
let mut event = event.clone();
event.real_seconds = event_time;
out.push(event);
}
}
}
out.sort_by(|a, b| {
a.real_seconds
.partial_cmp(&b.real_seconds)
.unwrap_or(std::cmp::Ordering::Equal)
});
out
}
fn locate_track(&self, wrapped_seconds: f32) -> (usize, f32) {
let mut offset = 0.0;
for (index, track) in self.tracks.iter().enumerate() {
let duration = track.duration_seconds as f32;
if wrapped_seconds < offset + duration || index + 1 == self.tracks.len() {
return (index, (wrapped_seconds - offset).clamp(0.0, duration));
}
offset += duration;
}
(self.tracks.len() - 1, 0.0)
}
fn track_offset_seconds(&self, track_index: usize) -> u64 {
self.tracks
.iter()
.take(track_index)
.map(|track| u64::from(track.duration_seconds))
.sum()
}
fn schedule_points(&self) -> Vec<SchedulePoint<'_>> {
let mut points = Vec::new();
let mut track_offset = 0_u64;
for (track_index, track) in self.tracks.iter().enumerate() {
for (key_index, key) in track.keys.iter().enumerate() {
let key_offset = u64::from(track.duration_seconds)
.saturating_mul(u64::from(key.date.hour_minute_seconds()))
/ DAY_SECONDS_U64;
points.push(SchedulePoint {
track_index,
key_index,
key,
real_seconds: track_offset.saturating_add(key_offset),
});
}
track_offset = track_offset.saturating_add(u64::from(track.duration_seconds));
}
points
}
fn sample_track(
&self,
real_seconds: f32,
sample_seconds: f32,
birth_seconds: f32,
track_index: usize,
track_seconds: f32,
day_seconds: f32,
points: &[SchedulePoint<'_>],
) -> AtmosphereFrame {
let interpolation =
interpolate_schedule(points, sample_seconds, self.total_duration_seconds());
let sky = sky_sample(&interpolation);
let total_seconds = self.total_duration_seconds();
let sun_birth = celestial_birth(points, birth_seconds, total_seconds, b"sun");
let moon_birth = celestial_birth(points, birth_seconds, total_seconds, b"moon");
let sun = sun_sample(&interpolation, sun_birth);
let moon = sun_sample(&interpolation, moon_birth);
let rain = weather_sample(
points,
sample_seconds,
self.total_duration_seconds(),
&[AtmosphereKind::RainStart, AtmosphereKind::RainStop],
);
let snow = weather_sample(
points,
sample_seconds,
self.total_duration_seconds(),
&[AtmosphereKind::SnowStart, AtmosphereKind::SnowStop],
);
let lightning = weather_sample(
points,
sample_seconds,
self.total_duration_seconds(),
&[
AtmosphereKind::LightningStart,
AtmosphereKind::LightningStop,
],
);
AtmosphereFrame {
real_seconds,
track_index,
track_seconds,
day_seconds,
sky,
sun,
moon,
rain,
snow,
lightning,
}
}
}
const DAY_SECONDS_U64: u64 = 86_400;
#[derive(Clone, Copy, Debug)]
struct SchedulePoint<'a> {
track_index: usize,
key_index: usize,
key: &'a AtmosphereKey,
real_seconds: u64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct InterpolatedKey {
header_colors: [PackedColor; 4],
header_values: [f32; 2],
colors: [PackedColor; KEY_COLOR_COUNT],
parameters: [f32; 4],
}
fn read_date(cursor: &mut Cursor<'_>, context: &'static str) -> Result<SkeDate, AtmosphereError> {
let mut words = [0_u32; DATE_WORD_COUNT];
for word in &mut words {
*word = cursor.read_u32_le()?;
}
let date = SkeDate::from_words(words);
if date.hours() > 24
|| date.minutes() > 59
|| date.seconds() > 59
|| (date.hours() == 24 && (date.minutes() != 0 || date.seconds() != 0))
{
return Err(AtmosphereError::InvalidDate {
context,
hours: date.hours(),
minutes: date.minutes(),
seconds: date.seconds(),
});
}
Ok(date)
}
fn read_key(
cursor: &mut Cursor<'_>,
track_index: usize,
key_index: usize,
) -> Result<AtmosphereKey, AtmosphereError> {
let version = cursor.read_u32_le()?;
if version != 3 {
return Err(AtmosphereError::InvalidKeyVersion {
track_index,
key_index,
version,
});
}
let date = read_date(cursor, "key")?;
let kind_raw = cursor.read_u32_le()?;
let raw = cursor.read_u32_le()?;
let mut header_colors = [PackedColor::default(); 4];
for color in &mut header_colors {
*color = PackedColor(cursor.read_u32_le()?);
}
let header_values = [cursor.read_f32_le()?, cursor.read_f32_le()?];
let mut colors = [PackedColor::default(); KEY_COLOR_COUNT];
for color in &mut colors {
*color = PackedColor(cursor.read_u32_le()?);
}
let mut strings = Vec::with_capacity(KEY_STRING_COUNT);
for _ in 0..KEY_STRING_COUNT {
strings.push(read_string(cursor)?);
}
let parameters = [
cursor.read_f32_le()?,
cursor.read_f32_le()?,
cursor.read_f32_le()?,
cursor.read_f32_le()?,
];
for (index, value) in header_values.iter().enumerate() {
if !value.is_finite() {
return Err(AtmosphereError::NonFiniteValue {
track_index,
key_index,
field: "header_values",
index,
});
}
}
for (index, value) in parameters.iter().enumerate() {
if !value.is_finite() {
return Err(AtmosphereError::NonFiniteValue {
track_index,
key_index,
field: "parameters",
index,
});
}
}
let reference_count = cursor.read_u32_le()?;
checked_count(reference_count, MAX_REFERENCES)?;
let mut references = Vec::with_capacity(reference_count as usize);
for _ in 0..reference_count {
references.push(read_string(cursor)?);
}
Ok(AtmosphereKey {
version,
date,
kind: AtmosphereKind::from_raw(kind_raw),
kind_raw,
raw,
header_colors,
header_values,
colors,
strings,
parameters,
references,
})
}
fn read_string(cursor: &mut Cursor<'_>) -> Result<AtmosphereString, AtmosphereError> {
let raw = read_lp_bytes(cursor, MAX_STRING_BYTES)?;
let text = String::from_utf8_lossy(&raw).into_owned();
Ok(AtmosphereString { raw, text })
}
fn checked_count(count: u32, limit: u32) -> Result<(), AtmosphereError> {
if count > limit {
return Err(AtmosphereError::Decode(DecodeError::LimitExceeded {
count: u64::from(count),
limit: u64::from(limit),
}));
}
Ok(())
}
fn lerp(a: f32, b: f32, factor: f32) -> f32 {
a + (b - a) * factor.clamp(0.0, 1.0)
}
fn interpolate_schedule(
points: &[SchedulePoint<'_>],
schedule_seconds: f32,
total_seconds: f32,
) -> InterpolatedKey {
let (before, after, factor) = surrounding_points(points, schedule_seconds, total_seconds);
InterpolatedKey {
header_colors: std::array::from_fn(|index| {
before.key.header_colors[index].lerp(after.key.header_colors[index], factor)
}),
header_values: std::array::from_fn(|index| {
lerp(
before.key.header_values[index],
after.key.header_values[index],
factor,
)
}),
colors: std::array::from_fn(|index| {
before.key.colors[index].lerp(after.key.colors[index], factor)
}),
parameters: std::array::from_fn(|index| {
lerp(
before.key.parameters[index],
after.key.parameters[index],
factor,
)
}),
}
}
fn surrounding_points<'a>(
points: &'a [SchedulePoint<'a>],
schedule_seconds: f32,
total_seconds: f32,
) -> (&'a SchedulePoint<'a>, &'a SchedulePoint<'a>, f32) {
debug_assert!(!points.is_empty());
if points.len() == 1 {
return (&points[0], &points[0], 0.0);
}
let sample_seconds = schedule_seconds.rem_euclid(total_seconds);
// The native previous-key helper is called with current time + 1 and a
// strict comparison, which makes an integer key at the current time the
// previous key. `<=` expresses that behavior without a frame epsilon.
let mut previous_index = None;
let mut next_index = None;
for (index, point) in points.iter().enumerate() {
let point_seconds = point.real_seconds as f32;
if point_seconds <= sample_seconds {
previous_index = Some(index);
}
if next_index.is_none() && point_seconds >= sample_seconds {
// Prefer the last key when several track boundaries share the
// same real timestamp. This selects the newly entered track.
let mut end = index;
while end + 1 < points.len() && points[end + 1].real_seconds == point.real_seconds {
end += 1;
}
next_index = Some(end);
}
}
let previous_index = previous_index.unwrap_or(points.len() - 1);
let next_index = next_index.unwrap_or(0);
let previous_wrap = if points[previous_index].real_seconds as f32 > sample_seconds {
total_seconds
} else {
0.0
};
let next_wrap = if (points[next_index].real_seconds as f32) < sample_seconds {
total_seconds
} else {
0.0
};
let previous_seconds = points[previous_index].real_seconds as f32 - previous_wrap;
let next_seconds = points[next_index].real_seconds as f32 + next_wrap;
let span = (next_seconds - previous_seconds).max(0.0);
let factor = if span > 0.0 {
((sample_seconds - previous_seconds) / span).clamp(0.0, 1.0)
} else {
0.0
};
(&points[previous_index], &points[next_index], factor)
}
fn sky_sample(key: &InterpolatedKey) -> SkySample {
let colors = [
key.header_colors[1],
key.header_colors[2],
key.header_colors[0],
key.header_colors[3],
key.colors[0],
key.colors[3],
key.colors[1],
key.colors[2],
key.colors[4],
key.colors[7],
key.colors[5],
key.colors[6],
key.colors[8],
];
SkySample {
colors,
values: key.header_values,
packed: [key.colors[11], key.colors[13]],
}
}
fn sun_sample(key: &InterpolatedKey, birth: Option<SunBirth>) -> SunSample {
let source = key.colors[12].rgba();
let intensity = key.parameters[2];
SunSample {
active: birth.is_some(),
rgb: [
source[0] * intensity,
source[1] * intensity,
source[2] * intensity,
],
values: [key.parameters[0], key.parameters[1]],
packed: [key.colors[10], key.colors[14]],
intensity,
birth,
}
}
fn weather_sample(
points: &[SchedulePoint<'_>],
schedule_seconds: f32,
total_seconds: f32,
markers: &[AtmosphereKind; 2],
) -> WeatherSample {
let (active, resources) = active_interval(points, schedule_seconds, total_seconds, markers);
let interpolation = interpolate_schedule(points, schedule_seconds, total_seconds);
let raw_color = interpolation.colors[12].rgba();
let intensity = if active {
interpolation.parameters[3].max(0.0)
} else {
0.0
};
let color = if active {
[
raw_color[0].max(COLOR_MIN_COMPONENT),
raw_color[1].max(COLOR_MIN_COMPONENT),
raw_color[2].max(COLOR_MIN_COMPONENT),
WEATHER_ALPHA,
]
} else {
[0.0; 4]
};
WeatherSample {
active,
intensity,
color,
raw_color,
resources,
}
}
fn active_interval(
points: &[SchedulePoint<'_>],
schedule_seconds: f32,
total_seconds: f32,
markers: &[AtmosphereKind; 2],
) -> (bool, Vec<AtmosphereString>) {
let sample_seconds = schedule_seconds.rem_euclid(total_seconds);
let mut latest = None;
for point in points {
if point.key.kind != markers[0] && point.key.kind != markers[1] {
continue;
}
if point.real_seconds as f32 <= sample_seconds {
latest = Some(point);
}
}
let Some(latest) = latest.or_else(|| {
points
.iter()
.rev()
.find(|point| point.key.kind == markers[0] || point.key.kind == markers[1])
}) else {
return (false, Vec::new());
};
if latest.key.kind == markers[0] {
(
true,
latest
.key
.resource_references()
.into_iter()
.cloned()
.collect(),
)
} else {
(false, Vec::new())
}
}
/// Reconstructs the native birth payload for one named celestial object.
///
/// The dispatcher compares the first fixed key string with `"sun"`; every
/// other celestial name uses the moon angle pair. It then scans forward for
/// the next matching stop event and stores the real-time difference as the
/// lifetime. Schedule points already contain the native integer floor, so no
/// fractional day-time conversion is introduced here.
fn celestial_birth(
points: &[SchedulePoint<'_>],
schedule_seconds: f32,
total_seconds: f32,
name: &[u8],
) -> Option<SunBirth> {
if points.is_empty() || !total_seconds.is_finite() || total_seconds <= 0.0 {
return None;
}
let schedule_seconds = if schedule_seconds.is_finite() {
schedule_seconds
} else {
0.0
};
let cycle = (schedule_seconds / total_seconds).floor();
let sample_absolute = cycle * total_seconds + schedule_seconds.rem_euclid(total_seconds);
let mut latest: Option<(f32, usize, AtmosphereKind)> = None;
for (index, point) in points.iter().enumerate() {
if !matches!(
point.key.kind,
AtmosphereKind::SunStart | AtmosphereKind::SunStop
) || point
.key
.strings
.first()
.map(|string| string.raw.as_slice())
!= Some(name)
{
continue;
}
let base = point.real_seconds as f32;
// Only the surrounding cycles can contain the latest event. Keeping
// all three also handles sample_day values at either schedule edge.
for cycle_delta in -1..=1 {
let time = base + (cycle + cycle_delta as f32) * total_seconds;
if time > sample_absolute {
continue;
}
let replace = latest
.map(|(old_time, old_index, _)| {
time > old_time || (time == old_time && index >= old_index)
})
.unwrap_or(true);
if replace {
latest = Some((time, index, point.key.kind));
}
}
}
let (start_seconds, start_index, kind) = latest?;
if kind != AtmosphereKind::SunStart {
return None;
}
let mut stop_seconds = None;
for point in points {
if point.key.kind != AtmosphereKind::SunStop
|| point
.key
.strings
.first()
.map(|string| string.raw.as_slice())
!= Some(name)
{
continue;
}
let base = point.real_seconds as f32;
for cycle_delta in -1..=2 {
let time = base + (cycle + cycle_delta as f32) * total_seconds;
if time <= start_seconds {
continue;
}
if stop_seconds.map(|old| time < old).unwrap_or(true) {
stop_seconds = Some(time);
}
}
}
let lifetime_seconds = stop_seconds
.map(|stop| stop - start_seconds)
.filter(|lifetime| lifetime.is_finite() && *lifetime > 0.0)?;
let (initial_angles_degrees, material_row) = if name == b"sun" {
([90.0, 30.0], 3)
} else {
([0.0, 50.0], 4)
};
let _ = start_index;
Some(SunBirth {
start_seconds,
lifetime_seconds,
initial_angles_degrees,
material_row,
})
}
fn event_for_key(
track_index: usize,
key_index: usize,
key: &AtmosphereKey,
real_seconds: f32,
) -> AtmosphereEvent {
AtmosphereEvent {
track_index,
key_index,
day_seconds: key.date.hour_minute_seconds() as f32,
real_seconds,
kind: key.kind,
raw: key.raw,
resources: key.resource_references().into_iter().cloned().collect(),
}
}
fn empty_frame(real_seconds: f32) -> AtmosphereFrame {
AtmosphereFrame {
real_seconds,
track_index: 0,
track_seconds: 0.0,
day_seconds: 0.0,
sky: SkySample {
colors: [PackedColor::default(); SKY_COLOR_COUNT],
values: [0.0; 2],
packed: [PackedColor::default(); 2],
},
sun: SunSample {
active: false,
rgb: [0.0; 3],
values: [0.0; 2],
packed: [PackedColor::default(); 2],
intensity: 0.0,
birth: None,
},
moon: SunSample {
active: false,
rgb: [0.0; 3],
values: [0.0; 2],
packed: [PackedColor::default(); 2],
intensity: 0.0,
birth: None,
},
rain: WeatherSample {
active: false,
intensity: 0.0,
color: [0.0; 4],
raw_color: [0.0; 4],
resources: Vec::new(),
},
snow: WeatherSample {
active: false,
intensity: 0.0,
color: [0.0; 4],
raw_color: [0.0; 4],
resources: Vec::new(),
},
lightning: WeatherSample {
active: false,
intensity: 0.0,
color: [0.0; 4],
raw_color: [0.0; 4],
resources: Vec::new(),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::{Path, PathBuf};
fn date(hours: u32, minutes: u32, seconds: u32) -> [u32; DATE_WORD_COUNT] {
[0, 0, 0, hours, minutes, seconds, 0, 0]
}
fn lp(bytes: &[u8], out: &mut Vec<u8>) {
out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
out.extend_from_slice(bytes);
}
fn key(
out: &mut Vec<u8>,
hours: u32,
minutes: u32,
kind: u32,
palette: [u32; KEY_COLOR_COUNT],
tail: [f32; 4],
references: &[&[u8]],
) {
key_with_seconds(out, hours, minutes, 0, kind, palette, tail, references);
}
fn key_with_seconds(
out: &mut Vec<u8>,
hours: u32,
minutes: u32,
seconds: u32,
kind: u32,
palette: [u32; KEY_COLOR_COUNT],
tail: [f32; 4],
references: &[&[u8]],
) {
out.extend_from_slice(&3_u32.to_le_bytes());
for word in date(hours, minutes, seconds) {
out.extend_from_slice(&word.to_le_bytes());
}
out.extend_from_slice(&kind.to_le_bytes());
out.extend_from_slice(&0xAABB_CCDD_u32.to_le_bytes());
for value in [0xFF11_2233_u32, 0xFF44_5566, 0xFF77_8899, 0xFFAA_BBCC] {
out.extend_from_slice(&value.to_le_bytes());
}
for value in [0.25_f32, 0.75_f32] {
out.extend_from_slice(&value.to_bits().to_le_bytes());
}
for value in palette {
out.extend_from_slice(&value.to_le_bytes());
}
for _ in 0..KEY_STRING_COUNT {
lp(b"", out);
}
for value in tail {
out.extend_from_slice(&value.to_bits().to_le_bytes());
}
out.extend_from_slice(&(references.len() as u32).to_le_bytes());
for reference in references {
lp(reference, out);
}
}
fn document(key_count: u32, keys: impl FnOnce(&mut Vec<u8>)) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&SKE_HEADER_MARKER.to_le_bytes());
out.extend_from_slice(&SKE_VERSION.to_le_bytes());
out.extend_from_slice(&1_u32.to_le_bytes());
out.extend_from_slice(&1_u32.to_le_bytes());
out.extend_from_slice(&key_count.to_le_bytes());
for word in date(23, 59, 0) {
out.extend_from_slice(&word.to_le_bytes());
}
for word in date(0, 15, 0) {
out.extend_from_slice(&word.to_le_bytes());
}
keys(&mut out);
for word in date(1, 30, 0) {
out.extend_from_slice(&word.to_le_bytes());
}
out.extend_from_slice(&0_u32.to_le_bytes());
out.extend_from_slice(&1_u32.to_le_bytes());
out
}
fn two_track_document(palette: [u32; KEY_COLOR_COUNT]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&SKE_HEADER_MARKER.to_le_bytes());
out.extend_from_slice(&SKE_VERSION.to_le_bytes());
out.extend_from_slice(&2_u32.to_le_bytes());
out.extend_from_slice(&1_u32.to_le_bytes());
out.extend_from_slice(&2_u32.to_le_bytes());
for word in date(23, 59, 0) {
out.extend_from_slice(&word.to_le_bytes());
}
for word in date(0, 1, 0) {
out.extend_from_slice(&word.to_le_bytes());
}
key_with_seconds(&mut out, 23, 0, 0, 7, palette, [0.0, 0.0, 0.0, 0.0], &[]);
key_with_seconds(&mut out, 23, 59, 59, 7, palette, [0.0, 0.0, 0.0, 0.0], &[]);
out.extend_from_slice(&1_u32.to_le_bytes());
out.extend_from_slice(&3_u32.to_le_bytes());
for word in date(23, 59, 0) {
out.extend_from_slice(&word.to_le_bytes());
}
for word in date(0, 2, 0) {
out.extend_from_slice(&word.to_le_bytes());
}
key_with_seconds(
&mut out,
0,
0,
0,
3,
palette,
[0.0, 0.0, 2.0, 1.0],
&[b"rain"],
);
key_with_seconds(
&mut out,
6,
0,
0,
7,
palette,
[0.0, 0.0, 2.0, 1.0],
&[b"future"],
);
key_with_seconds(
&mut out,
12,
0,
0,
4,
palette,
[0.0, 0.0, 0.0, 0.0],
&[b"stop"],
);
for word in [1_u32, 0, 0, 12, 0, 0, 0, 0] {
out.extend_from_slice(&word.to_le_bytes());
}
out.extend_from_slice(&0_u32.to_le_bytes());
out.extend_from_slice(&1_u32.to_le_bytes());
out
}
#[test]
fn parses_exact_v5_layout_and_rejects_trailing_bytes() {
let palette = [0xFF00_0000_u32; KEY_COLOR_COUNT];
let bytes = document(1, |out| {
key(out, 0, 0, 3, palette, [0.0, 0.0, 0.0, 1.0], &[b"rain"])
});
let parsed = TypedAtmosphere::parse(&bytes).expect("v5 parse");
assert_eq!(parsed.marker, -1);
assert_eq!(parsed.version, 5);
assert_eq!(parsed.tracks.len(), 1);
assert_eq!(parsed.tracks[0].duration_seconds, 900);
assert_eq!(parsed.tracks[0].keys[0].references[0].as_str(), "rain");
assert_eq!(parsed.trailer.date.hours(), 1);
assert!(matches!(
TypedAtmosphere::parse(&[bytes, vec![0]].concat()),
Err(AtmosphereError::Decode(DecodeError::TrailingBytes { .. }))
));
}
#[test]
fn maps_original_sky_color_order_and_interpolates() {
let first_palette = std::array::from_fn(|i| 0xFF00_0000_u32 | i as u32);
let second_palette = std::array::from_fn(|i| 0xFF00_1000_u32 | (i as u32) << 4);
let bytes = document(2, |out| {
key(out, 0, 0, 7, first_palette, [0.0, 0.0, 0.0, 0.0], &[]);
key(out, 12, 0, 7, second_palette, [1.0, 2.0, 3.0, 1.0], &[]);
});
let parsed = TypedAtmosphere::parse(&bytes).expect("parse");
let start = parsed.sample_day(0, 0.0);
assert_eq!(start.sky.colors[0].raw(), 0xFF44_5566);
assert_eq!(start.sky.colors[1].raw(), 0xFF77_8899);
assert_eq!(start.sky.colors[2].raw(), 0xFF11_2233);
assert_eq!(start.sky.colors[4].raw(), first_palette[0]);
assert_eq!(start.sky.colors[5].raw(), first_palette[3]);
assert_eq!(start.sky.colors[8].raw(), first_palette[4]);
assert_eq!(start.sky.colors[12].raw(), first_palette[8]);
assert_eq!(start.sun.intensity, 0.0);
let middle = parsed.sample_day(0, 6.0 * 3_600.0);
assert!((middle.sun.intensity - 1.5).abs() < 0.01);
assert_eq!(middle.rain.intensity, 0.0);
}
#[test]
fn wraps_last_key_to_first_and_emits_events() {
let palette = [0xFF00_0000_u32; KEY_COLOR_COUNT];
let bytes = document(2, |out| {
key(out, 6, 0, 3, palette, [0.0, 0.0, 0.0, 0.0], &[b"rain"]);
key(out, 12, 0, 4, palette, [1.0, 1.0, 1.0, 0.0], &[]);
});
let parsed = TypedAtmosphere::parse(&bytes).expect("parse");
let near_midnight = parsed.sample_day(0, 23.0 * 3_600.0);
assert!(!near_midnight.rain.active);
let events = parsed.events_between(0.0, 300.0);
assert_eq!(events.len(), 1);
assert_eq!(events[0].kind, AtmosphereKind::RainStart);
let wrapped = parsed.events_between(900.0, 1_300.0);
assert_eq!(wrapped.len(), 1);
assert_eq!(wrapped[0].kind, AtmosphereKind::RainStart);
}
#[test]
fn samples_across_tracks_uses_integer_key_times_and_trailer_offset() {
let palette = [0xFF00_0000_u32; KEY_COLOR_COUNT];
let parsed = TypedAtmosphere::parse(&two_track_document(palette)).expect("parse");
assert_eq!(parsed.tracks[0].duration_seconds, 60);
assert_eq!(parsed.tracks[1].duration_seconds, 120);
assert_eq!(parsed.initial_offset_seconds(), 120);
assert_eq!(parsed.timeline()[1].real_seconds, 59.0);
let before_transition = parsed.sample(59.5);
assert_eq!(before_transition.track_index, 0);
assert!((before_transition.sun.intensity - 1.0).abs() < 0.01);
let active = parsed.sample_day(1, 6.0 * 3_600.0);
assert_eq!(active.real_seconds, 90.0);
assert!(active.rain.active);
assert_eq!(active.rain.resources.len(), 1);
assert_eq!(active.rain.resources[0].as_str(), "rain");
assert!(parsed
.events_between(59.0, 61.0)
.iter()
.any(|event| event.kind == AtmosphereKind::RainStart));
}
#[test]
fn repeating_schedule_shifts_celestial_birth_with_absolute_clock() {
let palette = [0xFF00_0000_u32; KEY_COLOR_COUNT];
let bytes = document(2, |out| {
key(out, 0, 0, 0, palette, [0.0, 0.0, 1.0, 0.0], &[]);
key(out, 12, 0, 1, palette, [0.0, 0.0, 1.0, 0.0], &[]);
});
let mut parsed = TypedAtmosphere::parse(&bytes).expect("parse");
for (key, name) in parsed.tracks[0].keys.iter_mut().zip(["sun", "sun"]) {
key.strings[0] = AtmosphereString {
raw: name.as_bytes().to_vec(),
text: name.to_owned(),
};
}
let total = parsed.total_duration_seconds();
let first = parsed.sample(300.0);
let later = parsed.sample(300.0 + total);
let first_birth = first.sun.birth.expect("sun birth");
let later_birth = later.sun.birth.expect("wrapped sun birth");
assert!((later_birth.start_seconds - first_birth.start_seconds - total).abs() < 1.0e-5);
assert_eq!(first_birth.lifetime_seconds, later_birth.lifetime_seconds);
assert_eq!(
first_birth.initial_angles_degrees,
later_birth.initial_angles_degrees
);
assert_eq!(first_birth.material_row, later_birth.material_row);
let first_frame = crate::sky::sun_frame(
&first.sun,
300.0,
crate::sky::SunConfig::from_birth(first_birth),
);
let later_frame = crate::sky::sun_frame(
&later.sun,
300.0 + total,
crate::sky::SunConfig::from_birth(later_birth),
);
assert!((first_frame.age - later_frame.age).abs() < 1.0e-5);
for (first, later) in first_frame.direction.iter().zip(later_frame.direction) {
assert!((*first - later).abs() < 1.0e-5);
}
}
#[test]
fn rejects_non_finite_key_values() {
let palette = [0xFF00_0000_u32; KEY_COLOR_COUNT];
let mut bytes = document(1, |out| {
key(out, 0, 0, 7, palette, [f32::NAN, 0.0, 0.0, 0.0], &[])
});
assert!(matches!(
TypedAtmosphere::parse(&bytes),
Err(AtmosphereError::NonFiniteValue {
field: "parameters",
index: 0,
..
})
));
bytes[0] = 0;
assert!(matches!(
TypedAtmosphere::parse(&bytes),
Err(AtmosphereError::InvalidHeader { .. })
));
}
#[test]
#[ignore = "requires the original GOG installation"]
fn parses_all_original_gog_sky_files() {
let root = std::env::var_os("PARKAN_GOG_ROOT")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(r"C:\GOG Games\Parkan - Iron Strategy"));
let mission_root = root.join("MISSIONS");
let mut files = Vec::new();
collect_ske(&mission_root, &mut files);
files.sort();
assert_eq!(files.len(), 29);
for path in files {
let bytes = std::fs::read(&path).expect("read sky.ske");
let parsed = TypedAtmosphere::parse(&bytes)
.unwrap_or_else(|error| panic!("{}: {error}", path.display()));
assert!(parsed.total_duration_seconds().is_finite());
assert!(!parsed.timeline().is_empty(), "{}", path.display());
let materials = std::fs::read(path.with_file_name("sky.wea"))
.ok()
.and_then(|bytes| crate::sky::SkyMaterials::parse(&bytes).ok())
.unwrap_or_default();
let mut sky = crate::sky::SkySystem::new(Default::default(), materials)
.unwrap_or_else(|error| panic!("{}: {error}", path.display()));
for second in [0.0, 0.5, 900.0, 86_399.0, 172_800.0] {
let frame = parsed.sample(second);
assert!(frame.sky.values.iter().all(|value| value.is_finite()));
assert!(frame.sun.rgb.iter().all(|value| value.is_finite()));
assert!(frame.rain.intensity.is_finite());
assert!(frame.snow.intensity.is_finite());
assert!(frame.lightning.intensity.is_finite());
let sky_frame = sky
.update(&frame, second)
.unwrap_or_else(|error| panic!("{} at {second}: {error}", path.display()));
assert_eq!(sky_frame.directional_lights.len(), 4);
let optics = sky_frame
.sun_optics(crate::sky::SunVisibility {
projected_sun: [640.0, 360.0],
viewport: [1280.0, 720.0],
view_forward: [0.0, 0.0, 1.0],
unoccluded: true,
})
.expect("native sky optics");
assert_eq!(optics.flares.len(), 12);
}
}
}
fn collect_ske(root: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(root) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_ske(&path, out);
} else if path.file_name().is_some_and(|name| name == "sky.ske") {
out.push(path);
}
}
}
}
|