concinnity-engine 0.19.1

Runtime engine for Concinnity: ECS schedule, graphics, spawn, streaming
Documentation
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
// src/gfx/settings.rs
//
// The engine-side registry of user-facing settings a cycle row can change. The
// ordered option labels live in `concinnity_core::gfx::settings` (shared with
// the build pipeline, which reads a key's label count to pick a stepper vs a
// dropdown); this module re-exports `options` + `is_quality_toggle` from there
// and holds the client-only half: how a chosen option index maps to the applied
// value (the `*_at` / `*_index` pairs), the slider ranges, and the cycle math.
// How a chosen option is applied (which backend call, which persisted field)
// lives in GraphicsSystem's drain, keyed by the same string.

use crate::components::{
    AaMode, ReflectionBlurResolution, SettingOp, ShadowUpdate, SsgiResolution, UpscaleQuality,
    UpscalerBackend, WindowMode,
};
use crate::gfx::backend::GpuVendor;

// The shared option-label registry (labels + classification) lives in core so
// the cook and the client agree on every setting's option count. Re-exported
// under the historical `settings::*` paths the rest of the client uses.
pub(crate) use concinnity_core::gfx::settings::{QUALITY_TOGGLE_KEYS, is_quality_toggle, options};

// Whether setting `key` can be changed on a device with the given capabilities.
// A capability-gated setting (e.g. `ray_traced_reflections`, which needs
// hardware ray tracing) is unavailable when the device lacks that capability;
// every other setting is always available. The settings menu grays out and
// disables an unavailable row. This is the one place to gate a future
// capability-dependent toggle.
pub(crate) fn setting_available(key: &str, caps: &crate::gfx::backend::DeviceCapabilities) -> bool {
    match key {
        "ray_traced_reflections" => caps.ray_tracing,
        // The upscaler selector (FSR3 / DLSS / XeSS) grays out on a device whose
        // upscaler is fixed, rather than offering a dead selection.
        "upscale_backend" => caps.selectable_upscaler,
        _ => true,
    }
}

// InputKey-rebind settings (Controls tab) are a third setting category alongside
// cycle rows (`options`) and sliders (`slider_range`): a rebind key's value is a
// physical `InputKey`, not an option index or a fraction. Their classification +
// per-action data live in `gfx/keymap.rs` (the `Bindable` / `KeyMap` types) and
// the live map is owned by `GraphicsSystem`, so there is nothing to register
// here; this comment just records the third category for the reader.

// The discrete numeric levels each `*_at` / `*_index` mapping recovers from an
// option index (the ordered labels for these live in core's option registry).
// An authored value off a discrete level snaps to the nearest.
const FPS_CAP_VALUES: [u32; 6] = [0, 30, 60, 120, 144, 240];
const SSGI_RAYS_COUNTS: [u32; 4] = [4, 8, 16, 32];
const SSGI_STEPS_COUNTS: [u32; 4] = [8, 12, 24, 48];
const SHADOW_RESOLUTION_SIZES: [u32; 4] = [0, 1024, 2048, 4096];
const SHADOW_DISTANCE_VALUES: [u32; 4] = [40, 80, 160, 320];
const SHADOW_CASCADES_VALUES: [u32; 3] = [2, 3, 4];
const ANISOTROPY_LEVELS: [u32; 5] = [1, 2, 4, 8, 16];
const FRAME_BUFFERING_COUNTS: [u32; 3] = [1, 2, 3];
// Texture quality: one option index drives both the streaming pool cap (how many
// high-resolution textures stay resident) and the per-frame upload budget.
const TEXTURE_QUALITY_CAPS: [u32; 4] = [48, 96, 192, 384];
const TEXTURE_QUALITY_BUDGETS: [u32; 4] = [2, 4, 8, 12];

// The cycle (dropdown) quality knobs governed by the preset ceiling like the
// boolean QUALITY_TOGGLE_KEYS. Each rides the feature's live-reinit rebuild
// (`apply_quality_settings`) -- the sub-tunable travels in its settings payload,
// so no new backend method is needed. `GraphicsSystem` maps each key to the
// `PostProcessConfig` field it cycles.
pub(crate) const QUALITY_CYCLE_KEYS: [&str; 5] = [
    "aa_mode",
    "ssgi_resolution",
    "ssgi_rays",
    "ssgi_steps",
    "reflection_blur_resolution",
];

// Volume gains shared by the master and per-bus rows, one per option index
// (the labels live in core). Indices map to a linear gain via `volume_at` /
// `volume_index`.
const VOLUME_GAINS: [f32; 5] = [0.0, 0.25, 0.5, 0.75, 1.0];
// Effective volume for any stage the user has never chosen (full gain).
pub(crate) const DEFAULT_VOLUME: f32 = 1.0;

// Effective mouse sensitivity (radians per pixel) when the user has never
// chosen one. Matches `CameraController`'s authored default. Mouse sensitivity
// is a slider (1..100 -> radians/pixel), not a cycle row; see
// `MOUSE_SENSITIVITY_RANGE` and `slider_apply_value`.
pub(crate) const DEFAULT_MOUSE_SENSITIVITY: f32 = 0.0015;

// Effective gamepad look sensitivity (radians per second at full stick
// deflection) when the user has never chosen one. A slider (1..100 -> rate);
// see `GAMEPAD_LOOK_RANGE` and `slider_apply_value`.
pub(crate) const DEFAULT_GAMEPAD_LOOK_SENSITIVITY: f32 = 2.5;
// Effective gamepad stick deadzone (deflection fraction) when the user has
// never chosen one. A slider shown as a percentage; see
// `GAMEPAD_DEADZONE_RANGE` and `slider_apply_value`.
pub(crate) const DEFAULT_GAMEPAD_DEADZONE: f32 = 0.15;

// WindowMode for an option index, and the index for a WindowMode. Order matches
// WINDOW_MODE_OPTIONS, not the enum's declaration order.
pub(crate) fn window_mode_at(index: usize) -> WindowMode {
    match index {
        1 => WindowMode::Borderless,
        2 => WindowMode::Fullscreen,
        _ => WindowMode::Windowed,
    }
}
pub(crate) fn window_mode_index(mode: WindowMode) -> usize {
    match mode {
        WindowMode::Windowed => 0,
        WindowMode::Borderless => 1,
        WindowMode::Fullscreen => 2,
    }
}

// UpscaleQuality for an option index, and the index for a quality.
pub(crate) fn render_scale_at(index: usize) -> UpscaleQuality {
    match index {
        1 => UpscaleQuality::Balanced,
        2 => UpscaleQuality::Performance,
        3 => UpscaleQuality::UltraPerformance,
        _ => UpscaleQuality::Quality,
    }
}
pub(crate) fn render_scale_index(quality: UpscaleQuality) -> usize {
    match quality {
        UpscaleQuality::Quality => 0,
        UpscaleQuality::Balanced => 1,
        UpscaleQuality::Performance => 2,
        UpscaleQuality::UltraPerformance => 3,
    }
}

// UpscalerBackend for an option index, and the index for a backend. Order matches
// UPSCALE_BACKEND_OPTIONS (Auto / FSR3 / DLSS / XeSS).
pub(crate) fn upscale_backend_at(index: usize) -> UpscalerBackend {
    match index {
        1 => UpscalerBackend::Fsr3,
        2 => UpscalerBackend::Dlss,
        3 => UpscalerBackend::Xess,
        _ => UpscalerBackend::Auto,
    }
}
pub(crate) fn upscale_backend_index(backend: UpscalerBackend) -> usize {
    match backend {
        UpscalerBackend::Auto => 0,
        UpscalerBackend::Fsr3 => 1,
        UpscalerBackend::Dlss => 2,
        UpscalerBackend::Xess => 3,
    }
}

// Whether an upscaler backend is offered on the given GPU vendor. Auto and FSR3
// are vendor-agnostic; DLSS (NVIDIA NGX) is NVIDIA-only and XeSS is offered on
// Intel. The settings-menu cycle skips the unavailable entries so the user only
// lands on an upscaler the GPU can actually drive; the backend's `build_upscaler`
// still resolves + falls back on its own, so an unavailable explicit value is
// always safe even if it somehow gets set.
pub(crate) fn upscale_backend_available(backend: UpscalerBackend, vendor: GpuVendor) -> bool {
    match backend {
        UpscalerBackend::Auto | UpscalerBackend::Fsr3 => true,
        UpscalerBackend::Dlss => vendor == GpuVendor::Nvidia,
        UpscalerBackend::Xess => vendor == GpuVendor::Intel,
    }
}

// Anti-aliasing mode for an option index, and the index for a mode. Order
// matches AA_MODE_OPTIONS (Off, FXAA, TAA), which is also ascending cost so the
// index doubles as the aggressiveness rank the preset ceiling clamps against.
pub(crate) fn aa_mode_at(index: usize) -> AaMode {
    match index {
        0 => AaMode::Off,
        2 => AaMode::Taa,
        _ => AaMode::Fxaa,
    }
}
pub(crate) fn aa_mode_index(mode: AaMode) -> usize {
    match mode {
        AaMode::Off => 0,
        AaMode::Fxaa => 1,
        AaMode::Taa => 2,
    }
}

// SSGI gather resolution for an option index, and the index for a resolution.
// Order matches SSGI_RESOLUTION_OPTIONS (finest first).
pub(crate) fn ssgi_resolution_at(index: usize) -> SsgiResolution {
    match index {
        0 => SsgiResolution::Full,
        2 => SsgiResolution::Quarter,
        _ => SsgiResolution::Half,
    }
}
pub(crate) fn ssgi_resolution_index(res: SsgiResolution) -> usize {
    match res {
        SsgiResolution::Full => 0,
        SsgiResolution::Half => 1,
        SsgiResolution::Quarter => 2,
    }
}

// SSGI ray / step counts for an option index, and the menu index nearest an
// authored count (the world may author a value off the discrete levels; the row
// then shows the closest one).
pub(crate) fn ssgi_rays_at(index: usize) -> u32 {
    *SSGI_RAYS_COUNTS.get(index).unwrap_or(&SSGI_RAYS_COUNTS[1])
}
pub(crate) fn ssgi_rays_index(count: u32) -> usize {
    nearest_count_index(&SSGI_RAYS_COUNTS, count)
}
pub(crate) fn ssgi_steps_at(index: usize) -> u32 {
    *SSGI_STEPS_COUNTS
        .get(index)
        .unwrap_or(&SSGI_STEPS_COUNTS[1])
}
pub(crate) fn ssgi_steps_index(count: u32) -> usize {
    nearest_count_index(&SSGI_STEPS_COUNTS, count)
}
// The index of the level closest to `count` (ties pick the lower level).
fn nearest_count_index(levels: &[u32], count: u32) -> usize {
    levels
        .iter()
        .enumerate()
        .min_by_key(|&(_, &v)| v.abs_diff(count))
        .map(|(i, _)| i)
        .unwrap_or(0)
}

// Reflection blur resolution for an option index, and the index for a
// resolution. Order matches REFLECTION_BLUR_OPTIONS (finest first).
pub(crate) fn reflection_blur_at(index: usize) -> ReflectionBlurResolution {
    match index {
        0 => ReflectionBlurResolution::Full,
        2 => ReflectionBlurResolution::Quarter,
        _ => ReflectionBlurResolution::Half,
    }
}
pub(crate) fn reflection_blur_index(res: ReflectionBlurResolution) -> usize {
    match res {
        ReflectionBlurResolution::Full => 0,
        ReflectionBlurResolution::Half => 1,
        ReflectionBlurResolution::Quarter => 2,
    }
}

// Shadow-map resolution (texels) for an option index, and the menu index nearest
// an authored size (the world may author a size off the discrete levels; the row
// then shows the closest one). The default fallback is the world default (2048).
pub(crate) fn shadow_resolution_at(index: usize) -> u32 {
    *SHADOW_RESOLUTION_SIZES
        .get(index)
        .unwrap_or(&SHADOW_RESOLUTION_SIZES[2])
}
pub(crate) fn shadow_resolution_index(size: u32) -> usize {
    nearest_count_index(&SHADOW_RESOLUTION_SIZES, size)
}

// Shadow re-render cadence for an option index, and the index for a cadence.
// Order matches SHADOW_UPDATE_OPTIONS (EveryFrame first).
pub(crate) fn shadow_update_at(index: usize) -> ShadowUpdate {
    match index {
        0 => ShadowUpdate::EveryFrame,
        _ => ShadowUpdate::Hybrid,
    }
}
pub(crate) fn shadow_update_index(update: ShadowUpdate) -> usize {
    match update {
        ShadowUpdate::EveryFrame => 0,
        ShadowUpdate::Hybrid => 1,
    }
}

// Shadow distance (world units) for an option index, and the menu index nearest
// an authored distance (the world may author a distance off the discrete levels;
// the row then shows the closest one). The default fallback is the world default
// (80).
pub(crate) fn shadow_distance_at(index: usize) -> u32 {
    *SHADOW_DISTANCE_VALUES
        .get(index)
        .unwrap_or(&SHADOW_DISTANCE_VALUES[1])
}
pub(crate) fn shadow_distance_index(distance: u32) -> usize {
    nearest_count_index(&SHADOW_DISTANCE_VALUES, distance)
}

// Shadow cascade count for an option index, and the menu index nearest an
// authored count. The default fallback is the world default (4, the last index).
pub(crate) fn shadow_cascades_at(index: usize) -> u32 {
    *SHADOW_CASCADES_VALUES
        .get(index)
        .unwrap_or(&SHADOW_CASCADES_VALUES[2])
}
pub(crate) fn shadow_cascades_index(count: u32) -> usize {
    nearest_count_index(&SHADOW_CASCADES_VALUES, count)
}

// Anisotropic-filtering degree for an option index, and the menu index nearest an
// authored degree (the world may author a degree off the discrete levels; the row
// then shows the closest one). The default fallback is the world default (8x).
pub(crate) fn anisotropy_at(index: usize) -> u32 {
    *ANISOTROPY_LEVELS
        .get(index)
        .unwrap_or(&ANISOTROPY_LEVELS[3])
}
pub(crate) fn anisotropy_index(level: u32) -> usize {
    nearest_count_index(&ANISOTROPY_LEVELS, level)
}

// Frame-rate cap (FPS) for an option index, and the menu index nearest an
// authored cap (the world may author a cap off the discrete levels; the row then
// shows the closest one). The default fallback is "Unlimited" (index 0).
pub(crate) fn fps_cap_at(index: usize) -> u32 {
    *FPS_CAP_VALUES.get(index).unwrap_or(&FPS_CAP_VALUES[0])
}
pub(crate) fn fps_cap_index(cap: u32) -> usize {
    nearest_count_index(&FPS_CAP_VALUES, cap)
}

// Frames-in-flight (ring-buffer depth) for an option index, and the index for a
// count. Order matches FRAME_BUFFERING_OPTIONS (1, 2, 3); an out-of-range count
// snaps to the nearest level.
pub(crate) fn frames_in_flight_at(index: usize) -> u32 {
    *FRAME_BUFFERING_COUNTS
        .get(index)
        .unwrap_or(&FRAME_BUFFERING_COUNTS[1])
}
pub(crate) fn frames_in_flight_index(count: u32) -> usize {
    nearest_count_index(&FRAME_BUFFERING_COUNTS, count)
}

// Texture-quality level for an option index -> the (pool cap, per-frame budget)
// pair it sets, and the index recovered from a pool cap (the quality axis). An
// authored cap off the discrete levels snaps to the nearest level.
pub(crate) fn texture_quality_at(index: usize) -> (u32, u32) {
    let i = index.min(TEXTURE_QUALITY_CAPS.len() - 1);
    (TEXTURE_QUALITY_CAPS[i], TEXTURE_QUALITY_BUDGETS[i])
}
pub(crate) fn texture_quality_index(cap: u32) -> usize {
    nearest_count_index(&TEXTURE_QUALITY_CAPS, cap)
}

// Linear gain for a volume option index, and the index for a gain. A gain
// that is not a preset (an authored value) falls back to the last index
// (full).
pub(crate) fn volume_at(index: usize) -> f32 {
    *VOLUME_GAINS.get(index).unwrap_or(&DEFAULT_VOLUME)
}
pub(crate) fn volume_index(gain: f32) -> usize {
    VOLUME_GAINS
        .iter()
        .position(|g| (g - gain).abs() < 1.0e-4)
        .unwrap_or(VOLUME_GAINS.len() - 1)
}

// Advance an option index one step in the given direction (wrapping at the
// ends), or jump straight to a dropdown pick's absolute index. `len` must be
// non-zero (a known setting always has options). A `SetFraction` op only
// applies to slider settings and never reaches here.
pub(crate) fn cycle(index: usize, len: usize, op: SettingOp) -> usize {
    debug_assert!(len > 0);
    match op {
        SettingOp::Prev => (index + len - 1) % len,
        // A dropdown pick jumps to its option index, clamped to the last option.
        SettingOp::SetIndex(i) => i.min(len.saturating_sub(1)),
        // Next steps forward; the slider and rebind ops never reach a cycle
        // setting, so treating them as Next is harmless.
        SettingOp::Next
        | SettingOp::SetFraction(_)
        | SettingOp::Rebind(_)
        | SettingOp::RebindButton(_) => (index + 1) % len,
    }
}

// Slider (continuous) settings. Unlike the cycle settings above, these map a
// fraction in `[0, 1]` to a value in a fixed range; the range and the display
// format live here so a Slider row can only target a setting the engine knows
// how to apply. `slider_range` returning `Some` is what marks a key as a
// slider (vs `options` for a cycle row).

// Exposure slider range, in photographic stops (EV). Centered on 0 (neutral),
// so a fresh world reads as the midpoint.
const EXPOSURE_EV_RANGE: (f32, f32) = (-3.0, 3.0);
// Post-process slider ranges. The upper bounds are practical UI ceilings; the
// engine clamps applied values in `PostProcessConfig::resolve` (bloom is
// lower-bounded only, vignette / LUT are [0,1], ambient is [0,16]).
const BLOOM_INTENSITY_RANGE: (f32, f32) = (0.0, 2.0);
const BLOOM_THRESHOLD_RANGE: (f32, f32) = (0.0, 4.0);
const VIGNETTE_RANGE: (f32, f32) = (0.0, 1.0);
const LUT_STRENGTH_RANGE: (f32, f32) = (0.0, 1.0);
const AMBIENT_RANGE: (f32, f32) = (0.0, 4.0);
// Soft-knee width below the bloom threshold. Rides the live `update_post_process`
// path alongside the other bloom sliders (a `PostProcessParams` field).
const BLOOM_KNEE_RANGE: (f32, f32) = (0.0, 1.0);
// Per-feature sub-quality slider ranges. The UI ceilings are practical; the
// engine clamps the applied value in each feature's `*Settings::resolve`, mirrored
// by `slider_apply_value`. These ride the live `update_quality_params` path (the
// backend re-reads them into a per-frame uniform, no pass rebuild).
const SSAO_RADIUS_RANGE: (f32, f32) = (0.05, 2.0);
const SSAO_INTENSITY_RANGE: (f32, f32) = (0.0, 4.0);
const SSR_INTENSITY_RANGE: (f32, f32) = (0.0, 1.0);
const SSR_MAX_DISTANCE_RANGE: (f32, f32) = (1.0, 200.0);
const SSGI_INTENSITY_RANGE: (f32, f32) = (0.0, 4.0);
const SSGI_MAX_DISTANCE_RANGE: (f32, f32) = (0.5, 40.0);
const AE_MIN_EV_RANGE: (f32, f32) = (-16.0, 16.0);
const AE_MAX_EV_RANGE: (f32, f32) = (-16.0, 16.0);
const AE_SPEED_RANGE: (f32, f32) = (0.1, 6.0);

// The per-feature sub-quality slider keys, applied live by mutating the backend's
// stored `*Settings` (via `update_quality_params`) rather than rebuilding the pass.
// `bloom_knee` is deliberately NOT here: it is a `PostProcessParams` field and
// rides `update_post_process` like the other bloom sliders. These are look-tuning
// knobs, independent of the master quality preset (no ceiling, no Custom-flip),
// like the exposure / bloom / ambient sliders.
pub(crate) const QUALITY_PARAM_SLIDER_KEYS: [&str; 9] = [
    "ssao_radius",
    "ssao_intensity",
    "ssr_intensity",
    "ssr_max_distance",
    "ssgi_intensity",
    "ssgi_max_distance",
    "auto_exposure_min_ev",
    "auto_exposure_max_ev",
    "auto_exposure_speed",
];

// Whether `key` is one of the per-feature sub-quality sliders (applied live via
// `update_quality_params`, the stored-settings mutation path).
pub(crate) fn is_quality_param_slider(key: &str) -> bool {
    QUALITY_PARAM_SLIDER_KEYS.contains(&key)
}
// Mouse-sensitivity slider: a 1..100 UI scale (what the row shows) mapped
// linearly to a radians-per-pixel value in [MOUSE_SENS_MIN, MOUSE_SENS_MAX] by
// `slider_apply_value`. The endpoints span slow..fast; the camera's authored
// default (`DEFAULT_MOUSE_SENSITIVITY`) sits low on the track.
const MOUSE_SENSITIVITY_RANGE: (f32, f32) = (1.0, 100.0);
const MOUSE_SENS_MIN: f32 = 0.0003;
const MOUSE_SENS_MAX: f32 = 0.005;

// Gamepad look-sensitivity slider: the same 1..100 UI scale, mapped linearly
// to a radians-per-second rate at full stick deflection in
// [GAMEPAD_LOOK_MIN, GAMEPAD_LOOK_MAX]. The engine default sits mid-track.
const GAMEPAD_LOOK_RANGE: (f32, f32) = (1.0, 100.0);
const GAMEPAD_LOOK_MIN: f32 = 0.5;
const GAMEPAD_LOOK_MAX: f32 = 6.0;

// Gamepad deadzone slider: shown as a percentage of stick deflection, stored
// as the fraction the radial deadzone consumes.
const GAMEPAD_DEADZONE_RANGE: (f32, f32) = (0.0, 40.0);

// Field-of-view slider: a vertical FOV in degrees applied directly (the slider
// value IS the degrees, so `slider_apply_value` only clamps and the recover is
// the identity) to every Camera3D's `fov_y_degrees`. The range spans a narrow to
// a wide view; the engine's authored default (`DEFAULT_FOV`) sits mid-track.
const FOV_RANGE: (f32, f32) = (50.0, 100.0);
// Effective vertical FOV in degrees when the user has never chosen one. Matches
// Camera3D's authored default.
pub(crate) const DEFAULT_FOV: f32 = 75.0;

// Fraction of a slider's range one focused Left/Right pulse steps.
pub(crate) const SLIDER_STEP_FRACTION: f32 = 0.05;

// The (min, max) value range for a slider key, or `None` if the key is not a
// slider setting.
pub(crate) fn slider_range(key: &str) -> Option<(f32, f32)> {
    match key {
        "exposure" => Some(EXPOSURE_EV_RANGE),
        "bloom_intensity" => Some(BLOOM_INTENSITY_RANGE),
        "bloom_threshold" => Some(BLOOM_THRESHOLD_RANGE),
        "vignette" => Some(VIGNETTE_RANGE),
        "lut_strength" => Some(LUT_STRENGTH_RANGE),
        "ambient_intensity" => Some(AMBIENT_RANGE),
        "bloom_knee" => Some(BLOOM_KNEE_RANGE),
        "ssao_radius" => Some(SSAO_RADIUS_RANGE),
        "ssao_intensity" => Some(SSAO_INTENSITY_RANGE),
        "ssr_intensity" => Some(SSR_INTENSITY_RANGE),
        "ssr_max_distance" => Some(SSR_MAX_DISTANCE_RANGE),
        "ssgi_intensity" => Some(SSGI_INTENSITY_RANGE),
        "ssgi_max_distance" => Some(SSGI_MAX_DISTANCE_RANGE),
        "auto_exposure_min_ev" => Some(AE_MIN_EV_RANGE),
        "auto_exposure_max_ev" => Some(AE_MAX_EV_RANGE),
        "auto_exposure_speed" => Some(AE_SPEED_RANGE),
        "mouse_sensitivity" => Some(MOUSE_SENSITIVITY_RANGE),
        "gamepad_look_sensitivity" => Some(GAMEPAD_LOOK_RANGE),
        "gamepad_deadzone" => Some(GAMEPAD_DEADZONE_RANGE),
        "fov" => Some(FOV_RANGE),
        _ => None,
    }
}

// Whether `key` is a slider that acts on the camera / input path rather than a
// render param: its live apply travels as a ControlsCommand (or a graphics
// store write for FOV) and must skip the post-process push.
pub(crate) fn is_controls_slider(key: &str) -> bool {
    matches!(
        key,
        "mouse_sensitivity" | "fov" | "gamepad_look_sensitivity" | "gamepad_deadzone"
    )
}

// The setting value at a `0.0..=1.0` fraction of its range, or `None` for a
// non-slider key. The fraction is clamped.
pub(crate) fn slider_value_at(key: &str, fraction: f32) -> Option<f32> {
    let (lo, hi) = slider_range(key)?;
    Some(lo + (hi - lo) * fraction.clamp(0.0, 1.0))
}

// The `0.0..=1.0` fraction a value sits at within its range, or `None` for a
// non-slider key. The result is clamped, so an out-of-range authored value
// pins the handle to an end.
pub(crate) fn slider_fraction(key: &str, value: f32) -> Option<f32> {
    let (lo, hi) = slider_range(key)?;
    let span = hi - lo;
    if span.abs() < f32::EPSILON {
        return Some(0.0);
    }
    Some(((value - lo) / span).clamp(0.0, 1.0))
}

// Human-readable value text for a slider, shown in the row's value label.
pub(crate) fn format_slider_value(key: &str, value: f32) -> String {
    match key {
        // Exposure and the auto-exposure EV bounds read in photographic stops.
        "exposure" | "auto_exposure_min_ev" | "auto_exposure_max_ev" => {
            format!("{value:+.1} EV")
        }
        // World-space distances / radii read in metres.
        "ssr_max_distance" | "ssgi_max_distance" | "ssao_radius" => format!("{value:.1} m"),
        // [0, 1] strengths read more naturally as a percentage.
        "vignette" | "lut_strength" => format!("{}%", (value * 100.0).round() as i32),
        // The sensitivity sliders are whole-number 1..100 scales.
        "mouse_sensitivity" | "gamepad_look_sensitivity" => format!("{}", value.round() as i32),
        // The stick deadzone reads as a percentage of deflection.
        "gamepad_deadzone" => format!("{}%", value.round() as i32),
        // Field of view reads in whole degrees.
        "fov" => format!("{}\u{00b0}", value.round() as i32),
        _ => format!("{value:.2}"),
    }
}

// The value to store in the live render param for slider `key` at the given
// user-facing `value`, clamped to match `PostProcessConfig::resolve`. Exposure
// is authored in EV but stored as the linear multiplier 2^ev; the rest are
// stored as-is (only clamped). The single source of truth shared by the live
// drag-apply and the persisted re-apply at init, so those two cannot diverge.
// The 16.0 EV bound mirrors core's `EXPOSURE_EV_LIMIT`.
pub(crate) fn slider_apply_value(key: &str, value: f32) -> f32 {
    match key {
        "exposure" => value.clamp(-16.0, 16.0).exp2(),
        "bloom_intensity" | "bloom_threshold" => value.max(0.0),
        // Bloom soft-knee: lower-bounded only, like the other bloom params
        // (`PostProcessConfig::resolve` floors it at 0).
        "bloom_knee" => value.max(0.0),
        "vignette" | "lut_strength" => value.clamp(0.0, 1.0),
        "ambient_intensity" => value.clamp(0.0, 16.0),
        // Per-feature sub-quality clamps, mirroring each `*Settings::resolve`.
        "ssao_radius" => value.max(1.0e-3),
        "ssao_intensity" => value.clamp(0.0, 4.0),
        "ssr_intensity" => value.clamp(0.0, 1.0),
        "ssr_max_distance" => value.clamp(1.0, 200.0),
        "ssgi_intensity" => value.clamp(0.0, 4.0),
        "ssgi_max_distance" => value.clamp(0.5, 100.0),
        // The min/max EV bounds clamp to the engine EV limit; the resolve also
        // orders them (min <= max), which happens when the config is resolved.
        "auto_exposure_min_ev" | "auto_exposure_max_ev" => value.clamp(-16.0, 16.0),
        "auto_exposure_speed" => value.clamp(1.0e-3, 20.0),
        // 1..100 UI value -> radians/pixel, linearly across the sensitivity span.
        "mouse_sensitivity" => {
            let v = value.clamp(MOUSE_SENSITIVITY_RANGE.0, MOUSE_SENSITIVITY_RANGE.1);
            MOUSE_SENS_MIN + (MOUSE_SENS_MAX - MOUSE_SENS_MIN) * (v - 1.0) / 99.0
        }
        // 1..100 UI value -> radians/second at full deflection, linearly.
        "gamepad_look_sensitivity" => {
            let v = value.clamp(GAMEPAD_LOOK_RANGE.0, GAMEPAD_LOOK_RANGE.1);
            GAMEPAD_LOOK_MIN + (GAMEPAD_LOOK_MAX - GAMEPAD_LOOK_MIN) * (v - 1.0) / 99.0
        }
        // Percentage shown -> deflection fraction stored.
        "gamepad_deadzone" => {
            value.clamp(GAMEPAD_DEADZONE_RANGE.0, GAMEPAD_DEADZONE_RANGE.1) / 100.0
        }
        // FOV is stored as degrees, only clamped to the slider range.
        "fov" => value.clamp(FOV_RANGE.0, FOV_RANGE.1),
        _ => value,
    }
}

// The user-facing value recovered from a stored render param, the inverse of
// `slider_apply_value`, so a slider's handle + label re-sync to the live value
// at init. Only exposure is non-identity (2^ev stored -> EV shown).
pub(crate) fn slider_recover_value(key: &str, stored: f32) -> f32 {
    match key {
        // Guard log2(0); the slider range keeps the multiplier well above this.
        "exposure" => stored.max(1.0e-6).log2(),
        // radians/pixel -> 1..100 UI value (inverse of the apply mapping).
        "mouse_sensitivity" => {
            1.0 + (stored - MOUSE_SENS_MIN) / (MOUSE_SENS_MAX - MOUSE_SENS_MIN) * 99.0
        }
        // radians/second -> 1..100 UI value (inverse of the apply mapping).
        "gamepad_look_sensitivity" => {
            1.0 + (stored - GAMEPAD_LOOK_MIN) / (GAMEPAD_LOOK_MAX - GAMEPAD_LOOK_MIN) * 99.0
        }
        // Deflection fraction stored -> percentage shown.
        "gamepad_deadzone" => stored * 100.0,
        _ => stored,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn vsync_options_are_off_then_on() {
        assert_eq!(options("vsync"), Some(&["Off", "On"][..]));
    }

    #[test]
    fn stats_hud_toggles_are_off_then_on() {
        // The "Display performance stats" master and its per-readout sub-toggles
        // are plain Off/On cycle rows (index 0 = Off, 1 = On, like vsync).
        for key in ["perf_stats", "show_fps", "show_vram"] {
            assert_eq!(options(key), Some(&["Off", "On"][..]), "{key}");
            // Both are available regardless of GPU capability (not gated).
            let caps = crate::gfx::backend::DeviceCapabilities {
                ray_tracing: false,
                ..crate::gfx::backend::DeviceCapabilities::ALL
            };
            assert!(setting_available(key, &caps), "{key}");
        }
    }

    #[test]
    fn unknown_key_has_no_options() {
        assert!(options("does_not_exist").is_none());
    }

    #[test]
    fn graphics_quality_options_match_preset_order() {
        use crate::gfx::quality_preset::QualityPreset;
        // The master row's labels (in core's registry) must line up 1:1 with the
        // preset cycle order, so an index from `preset_index` selects the right
        // label and vice versa.
        let labels = options("graphics_quality").expect("graphics_quality options");
        assert_eq!(labels.len(), QualityPreset::ALL.len());
        for (i, p) in QualityPreset::ALL.iter().enumerate() {
            assert_eq!(labels[i], p.name(), "label {i}");
        }
    }

    #[test]
    fn quality_toggles_are_off_then_on_and_classified() {
        for key in QUALITY_TOGGLE_KEYS {
            assert!(is_quality_toggle(key), "{key} should classify as a toggle");
            assert_eq!(options(key), Some(&["Off", "On"][..]), "{key} options");
            // A quality toggle is a cycle row, never a slider.
            assert!(slider_range(key).is_none(), "{key} should not be a slider");
        }
        // Non-toggle keys are not misclassified.
        assert!(!is_quality_toggle("vsync"));
        assert!(!is_quality_toggle("exposure"));
        assert!(!is_quality_toggle("nope"));
    }

    #[test]
    fn rebind_keys_are_a_distinct_category() {
        use crate::gfx::keymap::Bindable;
        // A rebind key is neither a cycle row nor a slider, so the three setting
        // categories never collide on one key.
        for b in Bindable::ALL {
            let key = b.setting_key();
            assert!(options(key).is_none(), "{key} should not be a cycle row");
            assert!(slider_range(key).is_none(), "{key} should not be a slider");
        }
    }

    #[test]
    fn rt_toggle_gated_on_ray_tracing_capability() {
        use crate::gfx::backend::DeviceCapabilities;
        let capable = DeviceCapabilities {
            ray_tracing: true,
            ..DeviceCapabilities::ALL
        };
        let incapable = DeviceCapabilities {
            ray_tracing: false,
            ..DeviceCapabilities::ALL
        };
        // RT reflections follow the device's ray-tracing capability.
        assert!(setting_available("ray_traced_reflections", &capable));
        assert!(!setting_available("ray_traced_reflections", &incapable));
        // Every other setting is always available, regardless of capability.
        for key in ["vsync", "aa_mode", "ssao", "ssr", "ssgi", "auto_exposure"] {
            assert!(
                setting_available(key, &incapable),
                "{key} should be available"
            );
        }
        // The default reports all capabilities present (an unwired backend keeps
        // every toggle live).
        assert!(setting_available(
            "ray_traced_reflections",
            &DeviceCapabilities::default()
        ));
    }

    #[test]
    fn aa_mode_round_trips_and_orders_by_cost() {
        // Index order is ascending cost (Off < FXAA < TAA), so it doubles as the
        // aggressiveness rank the preset ceiling clamps against.
        for (i, mode) in [AaMode::Off, AaMode::Fxaa, AaMode::Taa]
            .into_iter()
            .enumerate()
        {
            assert_eq!(aa_mode_index(mode), i);
            assert_eq!(aa_mode_at(i), mode);
        }
        assert_eq!(options("aa_mode").unwrap().len(), 3);
        // An out-of-range index falls back to the FXAA default.
        assert_eq!(aa_mode_at(9), AaMode::Fxaa);
    }

    #[test]
    fn fps_cap_round_trips_and_snaps() {
        assert_eq!(options("fps_cap").unwrap().len(), FPS_CAP_VALUES.len());
        for (i, &cap) in FPS_CAP_VALUES.iter().enumerate() {
            assert_eq!(fps_cap_index(cap), i);
            assert_eq!(fps_cap_at(i), cap);
        }
        // "Unlimited" is 0 and the index-0 fallback.
        assert_eq!(fps_cap_at(0), 0);
        assert_eq!(fps_cap_at(99), 0);
        // An authored cap off the discrete levels snaps to the nearest.
        assert_eq!(fps_cap_index(58), fps_cap_index(60));
        assert_eq!(fps_cap_index(1000), FPS_CAP_VALUES.len() - 1);
    }

    #[test]
    fn cycle_next_wraps() {
        assert_eq!(cycle(0, 2, SettingOp::Next), 1);
        assert_eq!(cycle(1, 2, SettingOp::Next), 0);
    }

    #[test]
    fn cycle_prev_wraps() {
        assert_eq!(cycle(0, 2, SettingOp::Prev), 1);
        assert_eq!(cycle(1, 2, SettingOp::Prev), 0);
    }

    #[test]
    fn cycle_three_options() {
        assert_eq!(cycle(2, 3, SettingOp::Next), 0);
        assert_eq!(cycle(0, 3, SettingOp::Prev), 2);
    }

    #[test]
    fn cycle_set_index_jumps_and_clamps() {
        // A dropdown pick jumps straight to the chosen index, regardless of the
        // current one, and clamps to the last option if it is out of range.
        assert_eq!(cycle(0, 4, SettingOp::SetIndex(2)), 2);
        assert_eq!(cycle(3, 4, SettingOp::SetIndex(0)), 0);
        assert_eq!(cycle(1, 4, SettingOp::SetIndex(9)), 3);
    }

    #[test]
    fn known_settings_have_options() {
        assert_eq!(options("window_mode").unwrap().len(), 3);
        assert_eq!(options("render_scale").unwrap().len(), 4);
        // resolution is a dynamic dropdown: options are enumerated from the
        // display at runtime, so the static registry has none for it.
        assert!(options("resolution").is_none());
        assert!(concinnity_core::gfx::settings::is_dynamic_dropdown(
            "resolution"
        ));
        assert_eq!(options("master_volume").unwrap().len(), 5);
        // mouse_sensitivity is a slider, not a cycle row.
        assert!(options("mouse_sensitivity").is_none());
        assert!(slider_range("mouse_sensitivity").is_some());
    }

    #[test]
    fn volume_index_and_at_round_trip() {
        for i in 0..VOLUME_GAINS.len() {
            assert_eq!(volume_index(volume_at(i)), i);
        }
        // A non-preset gain falls back to the full (last) index.
        assert_eq!(volume_index(0.33), VOLUME_GAINS.len() - 1);
        // The default reads as the full preset.
        assert_eq!(volume_at(volume_index(DEFAULT_VOLUME)), 1.0);
    }

    #[test]
    fn mouse_sensitivity_is_a_slider_1_to_100() {
        // It is a slider (range present), not a cycle row.
        assert_eq!(slider_range("mouse_sensitivity"), Some((1.0, 100.0)));
        assert!(options("mouse_sensitivity").is_none());
        // The 1..100 UI value maps linearly to radians/pixel and back.
        for &ui in &[1.0_f32, 25.0, 50.0, 100.0] {
            let stored = slider_apply_value("mouse_sensitivity", ui);
            let back = slider_recover_value("mouse_sensitivity", stored);
            assert!((back - ui).abs() < 1.0e-2, "ui={ui} -> {stored} -> {back}");
        }
        // Endpoints land on the radians/pixel span; values rise with the UI value.
        assert!((slider_apply_value("mouse_sensitivity", 1.0) - MOUSE_SENS_MIN).abs() < 1.0e-9);
        assert!((slider_apply_value("mouse_sensitivity", 100.0) - MOUSE_SENS_MAX).abs() < 1.0e-9);
        assert!(
            slider_apply_value("mouse_sensitivity", 10.0)
                < slider_apply_value("mouse_sensitivity", 90.0)
        );
        // The label is a whole number.
        assert_eq!(format_slider_value("mouse_sensitivity", 26.3), "26");
        // The authored default recovers to a position inside the track.
        let def = slider_recover_value("mouse_sensitivity", DEFAULT_MOUSE_SENSITIVITY);
        assert!(
            (1.0..=100.0).contains(&def),
            "default UI value {def} in range"
        );
    }

    #[test]
    fn fov_is_a_degrees_slider() {
        // It is a slider (range present), not a cycle row.
        assert_eq!(slider_range("fov"), Some((50.0, 100.0)));
        assert!(options("fov").is_none());
        // The slider value IS the degrees: apply only clamps, recover is identity.
        for &deg in &[50.0_f32, 75.0, 100.0] {
            let stored = slider_apply_value("fov", deg);
            assert!((stored - deg).abs() < 1.0e-6);
            assert!((slider_recover_value("fov", stored) - deg).abs() < 1.0e-6);
        }
        // Out-of-range values clamp to the span.
        assert_eq!(slider_apply_value("fov", 10.0), 50.0);
        assert_eq!(slider_apply_value("fov", 200.0), 100.0);
        // The label reads in whole degrees, and the default sits inside the track.
        assert_eq!(format_slider_value("fov", 74.6), "75\u{00b0}");
        assert!((50.0..=100.0).contains(&DEFAULT_FOV));
    }

    #[test]
    fn window_mode_index_and_at_round_trip() {
        for m in [
            WindowMode::Windowed,
            WindowMode::Borderless,
            WindowMode::Fullscreen,
        ] {
            assert_eq!(window_mode_at(window_mode_index(m)), m);
        }
    }

    #[test]
    fn ssgi_sub_quality_round_trips_and_snaps() {
        // Resolution round-trips across every option.
        for r in [
            SsgiResolution::Full,
            SsgiResolution::Half,
            SsgiResolution::Quarter,
        ] {
            assert_eq!(ssgi_resolution_at(ssgi_resolution_index(r)), r);
        }
        // Ray / step levels round-trip on their preset values.
        for i in 0..SSGI_RAYS_COUNTS.len() {
            assert_eq!(ssgi_rays_index(ssgi_rays_at(i)), i);
        }
        for i in 0..SSGI_STEPS_COUNTS.len() {
            assert_eq!(ssgi_steps_index(ssgi_steps_at(i)), i);
        }
        // An authored value off the discrete levels snaps to the nearest.
        assert_eq!(ssgi_rays_index(7), 1); // 7 -> 8
        assert_eq!(ssgi_rays_index(20), 2); // 20 -> 16
        assert_eq!(ssgi_steps_index(40), 3); // 40 -> 48
        // The three SSGI sub-quality keys are cycle rows, not sliders.
        for key in ["ssgi_resolution", "ssgi_rays", "ssgi_steps"] {
            assert!(options(key).is_some(), "{key} should be a cycle row");
            assert!(slider_range(key).is_none(), "{key} should not be a slider");
        }
    }

    #[test]
    fn reflection_blur_round_trips() {
        for r in [
            ReflectionBlurResolution::Full,
            ReflectionBlurResolution::Half,
            ReflectionBlurResolution::Quarter,
        ] {
            assert_eq!(reflection_blur_at(reflection_blur_index(r)), r);
        }
        // It is registered as a cycle row + a governed cycle quality knob.
        assert_eq!(
            options("reflection_blur_resolution").map(|o| o.len()),
            Some(3)
        );
        assert!(QUALITY_CYCLE_KEYS.contains(&"reflection_blur_resolution"));
    }

    #[test]
    fn display_toggles_are_off_on_cycle_rows() {
        // The display-output / upscaling preferences are Off/On cycle rows, and
        // are NOT quality knobs (independent of the preset ceiling).
        for key in ["temporal_upscaling", "hdr_display", "hdr_pq"] {
            assert_eq!(options(key), Some(&["Off", "On"][..]), "{key} options");
            assert!(slider_range(key).is_none(), "{key} should not be a slider");
            assert!(!is_quality_toggle(key), "{key} is not a quality toggle");
            assert!(
                !QUALITY_CYCLE_KEYS.contains(&key),
                "{key} is not a quality cycle knob"
            );
        }
    }

    #[test]
    fn shadow_resolution_round_trips_and_snaps() {
        // Each discrete level round-trips through its index.
        for i in 0..SHADOW_RESOLUTION_SIZES.len() {
            assert_eq!(shadow_resolution_index(shadow_resolution_at(i)), i);
        }
        // "Off" is size 0 at index 0; the world default 2048 is index 2.
        assert_eq!(shadow_resolution_at(0), 0);
        assert_eq!(shadow_resolution_index(2048), 2);
        // An authored size off the discrete levels snaps to the nearest, and a
        // size above the top level snaps down to it.
        assert_eq!(shadow_resolution_index(1500), 1); // 1500 -> 1024
        assert_eq!(shadow_resolution_index(8192), 3); // 8192 -> 4096
        // It is a cycle row, not a slider.
        assert!(options("shadow_map_size").is_some());
        assert!(slider_range("shadow_map_size").is_none());
    }

    #[test]
    fn anisotropy_round_trips_and_snaps() {
        // Each discrete level round-trips through its index.
        for i in 0..ANISOTROPY_LEVELS.len() {
            assert_eq!(anisotropy_index(anisotropy_at(i)), i);
        }
        // "Off" is 1x at index 0; the world default 8x is index 3.
        assert_eq!(anisotropy_at(0), 1);
        assert_eq!(anisotropy_index(8), 3);
        // An authored degree off the discrete levels snaps to the nearest, and a
        // degree above the top level snaps down to it.
        assert_eq!(anisotropy_index(3), 1); // 3 -> 2x
        assert_eq!(anisotropy_index(32), 4); // 32 -> 16x
        // It is a cycle row, not a slider.
        assert!(options("anisotropy").is_some());
        assert!(slider_range("anisotropy").is_none());
    }

    #[test]
    fn shadow_distance_round_trips_and_snaps() {
        // Each discrete level round-trips through its index.
        for i in 0..SHADOW_DISTANCE_VALUES.len() {
            assert_eq!(shadow_distance_index(shadow_distance_at(i)), i);
        }
        // The world default 80 is index 1.
        assert_eq!(shadow_distance_at(1), 80);
        assert_eq!(shadow_distance_index(80), 1);
        // An authored distance off the discrete levels snaps to the nearest, and
        // one above the top level snaps down to it.
        assert_eq!(shadow_distance_index(50), 0); // 50 -> 40
        assert_eq!(shadow_distance_index(1000), 3); // 1000 -> 320
        // It is a cycle row, not a slider.
        assert!(options("shadow_distance").is_some());
        assert!(slider_range("shadow_distance").is_none());
    }

    #[test]
    fn shadow_cascades_round_trips_and_snaps() {
        for i in 0..SHADOW_CASCADES_VALUES.len() {
            assert_eq!(shadow_cascades_index(shadow_cascades_at(i)), i);
        }
        // The world default 4 is the last index; out-of-range falls back to it.
        assert_eq!(shadow_cascades_at(2), 4);
        assert_eq!(shadow_cascades_index(4), 2);
        assert_eq!(shadow_cascades_at(9), 4);
        // An authored count off the levels snaps to the nearest.
        assert_eq!(shadow_cascades_index(1), 0); // 1 -> 2
        assert!(options("shadow_cascades").is_some());
        assert!(slider_range("shadow_cascades").is_none());
    }

    #[test]
    fn shadow_update_round_trips() {
        for u in [ShadowUpdate::EveryFrame, ShadowUpdate::Hybrid] {
            assert_eq!(shadow_update_at(shadow_update_index(u)), u);
        }
        // EveryFrame leads the cycle (best / most expensive first).
        assert_eq!(shadow_update_at(0), ShadowUpdate::EveryFrame);
        assert_eq!(options("shadow_update").map(|o| o.len()), Some(2));
    }

    #[test]
    fn frame_buffering_round_trips_and_snaps() {
        for i in 0..FRAME_BUFFERING_COUNTS.len() {
            assert_eq!(frames_in_flight_index(frames_in_flight_at(i)), i);
        }
        assert_eq!(frames_in_flight_at(0), 1);
        // An out-of-range depth snaps to the nearest level.
        assert_eq!(frames_in_flight_index(4), 2); // 4 -> 3
        assert!(options("frames_in_flight").is_some());
    }

    #[test]
    fn texture_quality_pairs_cap_and_budget() {
        // Each level round-trips through its index (recovered from the pool cap),
        // and sets both the pool cap and the per-frame upload budget.
        for i in 0..TEXTURE_QUALITY_CAPS.len() {
            let (cap, budget) = texture_quality_at(i);
            assert_eq!(texture_quality_index(cap), i);
            assert_eq!(cap, TEXTURE_QUALITY_CAPS[i]);
            assert_eq!(budget, TEXTURE_QUALITY_BUDGETS[i]);
        }
        // The default world cap (96) reads as "Medium"; an authored cap off the
        // levels snaps to the nearest.
        assert_eq!(texture_quality_index(96), 1);
        assert_eq!(texture_quality_index(300), 3); // 300 -> 384 (Ultra)
        // occlusion_two_pass is an Off/On row, not a slider or preset knob.
        assert_eq!(options("occlusion_two_pass"), Some(&["Off", "On"][..]));
        assert!(slider_range("occlusion_two_pass").is_none());
        assert!(!is_quality_toggle("occlusion_two_pass"));
    }

    #[test]
    fn render_scale_index_and_at_round_trip() {
        for q in [
            UpscaleQuality::Quality,
            UpscaleQuality::Balanced,
            UpscaleQuality::Performance,
            UpscaleQuality::UltraPerformance,
        ] {
            assert_eq!(render_scale_at(render_scale_index(q)), q);
        }
    }

    #[test]
    fn upscale_backend_round_trips_and_vendor_gates() {
        // Every variant round-trips through its index, and the option table lines
        // up with the four variants.
        assert_eq!(options("upscale_backend").unwrap().len(), 4);
        for b in [
            UpscalerBackend::Auto,
            UpscalerBackend::Fsr3,
            UpscalerBackend::Dlss,
            UpscalerBackend::Xess,
        ] {
            assert_eq!(upscale_backend_at(upscale_backend_index(b)), b);
        }
        // It is a cycle row, not a slider.
        assert!(options("upscale_backend").is_some());
        assert!(slider_range("upscale_backend").is_none());
        // Auto / FSR3 are offered on every vendor; DLSS is NVIDIA-only and XeSS
        // is Intel-only, so the menu cycle skips them elsewhere. Auto / FSR3 stay
        // available even on an Unknown (Other) GPU, so the skip loop always
        // terminates.
        for vendor in [
            GpuVendor::Apple,
            GpuVendor::Nvidia,
            GpuVendor::Amd,
            GpuVendor::Intel,
            GpuVendor::Other,
        ] {
            assert!(upscale_backend_available(UpscalerBackend::Auto, vendor));
            assert!(upscale_backend_available(UpscalerBackend::Fsr3, vendor));
        }
        assert!(upscale_backend_available(
            UpscalerBackend::Dlss,
            GpuVendor::Nvidia
        ));
        assert!(!upscale_backend_available(
            UpscalerBackend::Dlss,
            GpuVendor::Amd
        ));
        assert!(upscale_backend_available(
            UpscalerBackend::Xess,
            GpuVendor::Intel
        ));
        assert!(!upscale_backend_available(
            UpscalerBackend::Xess,
            GpuVendor::Nvidia
        ));
        // The whole row is capability-gated: a device that offers a choice of
        // upscaler keeps it, one with a fixed upscaler grays it out.
        assert!(setting_available(
            "upscale_backend",
            &crate::gfx::backend::DeviceCapabilities::ALL
        ));
        assert!(!setting_available(
            "upscale_backend",
            &crate::gfx::backend::DeviceCapabilities {
                selectable_upscaler: false,
                ..crate::gfx::backend::DeviceCapabilities::ALL
            }
        ));
    }

    #[test]
    fn exposure_is_a_slider_not_a_cycle() {
        // A slider key has a range and no cycle option list, and vice versa.
        assert!(slider_range("exposure").is_some());
        assert!(options("exposure").is_none());
        assert!(slider_range("vsync").is_none());
    }

    #[test]
    fn slider_value_and_fraction_round_trip() {
        // Endpoints and the midpoint map exactly.
        assert_eq!(slider_value_at("exposure", 0.0), Some(-3.0));
        assert_eq!(slider_value_at("exposure", 1.0), Some(3.0));
        assert_eq!(slider_value_at("exposure", 0.5), Some(0.0));
        for &f in &[0.0_f32, 0.25, 0.5, 0.75, 1.0] {
            let v = slider_value_at("exposure", f).unwrap();
            let back = slider_fraction("exposure", v).unwrap();
            assert!((back - f).abs() < 1.0e-5, "f={f} -> v={v} -> {back}");
        }
    }

    #[test]
    fn slider_fraction_clamps_out_of_range() {
        // A value past either end pins the handle to that end.
        assert_eq!(slider_fraction("exposure", -100.0), Some(0.0));
        assert_eq!(slider_fraction("exposure", 100.0), Some(1.0));
        // The neutral default sits at the midpoint.
        assert_eq!(slider_fraction("exposure", 0.0), Some(0.5));
    }

    #[test]
    fn unknown_slider_key_has_no_range() {
        assert!(slider_range("nope").is_none());
        assert!(slider_value_at("nope", 0.5).is_none());
        assert!(slider_fraction("nope", 0.0).is_none());
    }

    #[test]
    fn exposure_value_is_formatted_in_stops() {
        assert_eq!(format_slider_value("exposure", 0.0), "+0.0 EV");
        assert_eq!(format_slider_value("exposure", 1.5), "+1.5 EV");
        assert_eq!(format_slider_value("exposure", -2.0), "-2.0 EV");
    }

    #[test]
    fn post_process_sliders_have_ranges_and_round_trip() {
        // Every live post-process slider key is a slider (not a cycle row) and
        // round-trips value<->fraction across its range.
        for key in [
            "bloom_intensity",
            "bloom_threshold",
            "vignette",
            "lut_strength",
            "ambient_intensity",
        ] {
            assert!(slider_range(key).is_some(), "{key} should be a slider");
            assert!(options(key).is_none(), "{key} should not be a cycle row");
            let (lo, hi) = slider_range(key).unwrap();
            assert!(lo < hi, "{key} range must be non-empty");
            assert_eq!(slider_value_at(key, 0.0), Some(lo));
            assert_eq!(slider_value_at(key, 1.0), Some(hi));
            for &f in &[0.0_f32, 0.25, 0.5, 0.75, 1.0] {
                let v = slider_value_at(key, f).unwrap();
                let back = slider_fraction(key, v).unwrap();
                assert!((back - f).abs() < 1.0e-5, "{key}: f={f} -> {v} -> {back}");
            }
        }
    }

    #[test]
    fn slider_apply_and_recover_round_trip() {
        // Applying a slider value to the live param then recovering it must
        // return the same value, so the handle never jumps when a persisted
        // choice is re-applied at the next launch. Locks the shared transform
        // used by both the live drag-apply and the init re-apply.
        for key in [
            "exposure",
            "bloom_intensity",
            "bloom_threshold",
            "vignette",
            "lut_strength",
            "ambient_intensity",
        ] {
            for &f in &[0.0_f32, 0.25, 0.5, 0.75, 1.0] {
                let v = slider_value_at(key, f).unwrap();
                let stored = slider_apply_value(key, v);
                let recovered = slider_recover_value(key, stored);
                assert!(
                    (recovered - v).abs() < 1.0e-4,
                    "{key}: v={v} stored={stored} recovered={recovered}"
                );
            }
        }
    }

    #[test]
    fn slider_apply_value_clamps_match_resolve() {
        // Out-of-range inputs (e.g. a hand-edited settings.bin) clamp to the
        // engine's domain, matching PostProcessConfig::resolve.
        assert_eq!(slider_apply_value("bloom_intensity", -5.0), 0.0);
        assert_eq!(slider_apply_value("vignette", 2.0), 1.0);
        assert_eq!(slider_apply_value("lut_strength", -1.0), 0.0);
        assert_eq!(slider_apply_value("ambient_intensity", 100.0), 16.0);
        // Exposure stores the linear multiplier 2^ev (clamped EV).
        assert_eq!(slider_apply_value("exposure", 2.0), 4.0);
        assert!((slider_recover_value("exposure", 4.0) - 2.0).abs() < 1.0e-5);
        // Per-feature sub-quality sliders clamp to their `*Settings::resolve`
        // domains; bloom_knee is lower-bounded like the other bloom params.
        assert_eq!(slider_apply_value("bloom_knee", -1.0), 0.0);
        assert_eq!(slider_apply_value("ssao_intensity", 100.0), 4.0);
        assert_eq!(slider_apply_value("ssr_intensity", 9.0), 1.0);
        assert_eq!(slider_apply_value("ssr_max_distance", 1.0e6), 200.0);
        assert_eq!(slider_apply_value("ssgi_intensity", 99.0), 4.0);
        assert_eq!(slider_apply_value("ssgi_max_distance", 1.0e6), 100.0);
        assert_eq!(slider_apply_value("auto_exposure_min_ev", -100.0), -16.0);
        assert_eq!(slider_apply_value("auto_exposure_max_ev", 100.0), 16.0);
        assert_eq!(slider_apply_value("auto_exposure_speed", 100.0), 20.0);
    }

    #[test]
    fn quality_param_sliders_are_independent_sliders() {
        // Each sub-quality slider is registered as a slider (has a range) and is
        // NOT a cycle row or a preset-governed quality knob (look-tuning, like the
        // exposure / bloom sliders).
        for key in QUALITY_PARAM_SLIDER_KEYS {
            assert!(
                is_quality_param_slider(key),
                "{key} should be a qparam slider"
            );
            assert!(
                slider_range(key).is_some(),
                "{key} should have a slider range"
            );
            assert!(options(key).is_none(), "{key} should not be a cycle row");
            assert!(
                !QUALITY_CYCLE_KEYS.contains(&key),
                "{key} should not be preset-governed"
            );
        }
        // bloom_knee is a slider but rides update_post_process, not the qparam path.
        assert!(slider_range("bloom_knee").is_some());
        assert!(!is_quality_param_slider("bloom_knee"));
    }

    #[test]
    fn strength_sliders_format_as_percent() {
        assert_eq!(format_slider_value("vignette", 0.0), "0%");
        assert_eq!(format_slider_value("vignette", 0.5), "50%");
        assert_eq!(format_slider_value("lut_strength", 1.0), "100%");
        // Bloom / ambient use the plain two-decimal fallback.
        assert_eq!(format_slider_value("bloom_intensity", 0.6), "0.60");
        assert_eq!(format_slider_value("ambient_intensity", 1.25), "1.25");
    }
}