voxel-framework 0.13.0

A reusable voxel engine framework built on Bevy
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
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
//! Center-screen crosshair: the classic cross, optional shapes, and a
//! published "pointing at something" state.
//!
//! [`CrosshairPlugin`] draws the crosshair. [`CrosshairStyles`] optionally
//! replaces the classic cross with a [`CrosshairStyle`] per state, and
//! [`CrosshairTarget`] is the state itself: a resource written by the game, or
//! by the optional [`CrosshairTargetPlugin`].

use bevy::prelude::*;

use crate::chunk::Chunk;
use crate::voxel::VoxelType;
use crate::world::ChunkManager;
use crate::world::mining::ToolStats;
use crate::world::raycast::raycast;

// ─── Classic configuration ───────────────────────────────────────────────────

/// Visual configuration for the [`CrosshairPlugin`] overlay.
///
/// Insert this resource before adding [`CrosshairPlugin`] to override any
/// default. The crosshair is spawned once on `Startup`; changes made after
/// that point have no effect unless you despawn and re-spawn the crosshair
/// nodes. The one exception: when [`CrosshairStyles`] switches from a styled
/// shape back to the classic cross, the cross is rebuilt from the values this
/// resource has at that moment.
///
/// This resource describes the classic four-arm cross. To draw another shape,
/// or a different one while the player points at something, insert
/// [`CrosshairStyles`]; a state with a style there ignores `color`, `size`,
/// `gap` and `thickness` from this resource. `visible` always applies.
///
/// # Default values
///
/// | Field       | Default              | Notes |
/// |-------------|----------------------|-------|
/// | `color`     | `[1,1,1,1]` (white)  | RGBA, linear |
/// | `size`      | `20.0` px            | Half-length of each arm |
/// | `gap`       | `4.0` px             | Empty space between center and arm start |
/// | `thickness` | `2.0` px             | Width of each arm quad |
/// | `visible`   | `true`               | `false` skips spawning entirely |
#[derive(Resource, Debug, Clone)]
pub struct CrosshairConfig {
    /// RGBA color of the four crosshair arm quads in linear sRGB.
    /// Alpha controls overall transparency of the overlay.
    pub color: [f32; 4],
    /// Half-length of each arm in logical (UI) pixels. The total visual width
    /// of the crosshair is approximately `2 × (gap + size)`.
    pub size: f32,
    /// Empty gap in logical pixels between the screen center and the start of
    /// each arm. Increase this to leave a clear center dot.
    pub gap: f32,
    /// Width of each arm quad in logical pixels. Thicker values (`4.0`–`6.0`)
    /// are easier to see on busy backgrounds.
    pub thickness: f32,
    /// When `false`, [`CrosshairPlugin`] returns early from `spawn_crosshair`
    /// without creating any entities. Useful for games that manage their own
    /// reticle or disable the crosshair entirely in certain modes.
    pub visible: bool,
}

impl Default for CrosshairConfig {
    fn default() -> Self {
        Self {
            color: [1.0, 1.0, 1.0, 1.0],
            size: 20.0,
            gap: 4.0,
            thickness: 2.0,
            visible: true,
        }
    }
}

// ─── Shapes and styles ───────────────────────────────────────────────────────

/// Shape drawn by a [`CrosshairStyle`].
///
/// Every shape is centered on the screen. How `size`, `gap` and `thickness`
/// apply to each shape is documented on the fields of [`CrosshairStyle`].
#[derive(Debug, Clone, PartialEq, Default)]
pub enum CrosshairShape {
    /// Four arms around an empty center.
    #[default]
    Cross,
    /// A filled circle.
    Dot,
    /// The outline of a square standing on one corner.
    Diamond,
    /// An image supplied by the game, drawn in a square and tinted with the
    /// style's color. Use a white color to draw the image unchanged.
    Image(Handle<Image>),
}

/// One look of the crosshair: a shape, its color and its measures.
///
/// Used by [`CrosshairStyles`], which holds one optional style for each
/// [`CrosshairTarget`] state. Measures are in logical (UI) pixels; a value
/// that is negative or not finite counts as zero.
///
/// # Default values
///
/// | Field       | Default                 |
/// |-------------|-------------------------|
/// | `shape`     | [`CrosshairShape::Cross`] |
/// | `color`     | `[1, 1, 1, 1]` (white)  |
/// | `size`      | `20.0` px               |
/// | `gap`       | `4.0` px                |
/// | `thickness` | `2.0` px                |
///
/// # Example
///
/// ```rust
/// use voxel_framework::ui::{CrosshairShape, CrosshairStyle};
///
/// let ring = CrosshairStyle {
///     color: [1.0, 0.9, 0.3, 1.0],
///     thickness: 3.0,
///     ..CrosshairStyle::diamond(18.0)
/// };
/// assert_eq!(ring.shape, CrosshairShape::Diamond);
/// assert_eq!(CrosshairStyle::dot(4.0).size, 4.0);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct CrosshairStyle {
    /// Shape to draw.
    pub shape: CrosshairShape,
    /// RGBA color in sRGB, with alpha as opacity. For
    /// [`CrosshairShape::Image`] it is the tint multiplied with the image.
    pub color: [f32; 4],
    /// Main measure of the shape: the length of each arm for a cross, the
    /// diameter of a dot, the corner-to-corner width of a diamond, and the
    /// side of the square an image is drawn in.
    pub size: f32,
    /// Empty space between the screen center and the start of each arm. Only
    /// used by [`CrosshairShape::Cross`].
    pub gap: f32,
    /// Width of each arm of a cross, and of the outline of a diamond. Not
    /// used by dots and images.
    pub thickness: f32,
}

impl Default for CrosshairStyle {
    fn default() -> Self {
        Self {
            shape: CrosshairShape::Cross,
            color: [1.0, 1.0, 1.0, 1.0],
            size: 20.0,
            gap: 4.0,
            thickness: 2.0,
        }
    }
}

impl CrosshairStyle {
    /// A white dot of the given diameter.
    pub fn dot(size: f32) -> Self {
        Self {
            shape: CrosshairShape::Dot,
            size,
            ..Self::default()
        }
    }

    /// A white diamond outline of the given corner-to-corner width, with the
    /// default outline thickness.
    pub fn diamond(size: f32) -> Self {
        Self {
            shape: CrosshairShape::Diamond,
            size,
            ..Self::default()
        }
    }

    /// The given image drawn untinted in a square of the given side.
    pub fn image(image: Handle<Image>, size: f32) -> Self {
        Self {
            shape: CrosshairShape::Image(image),
            size,
            ..Self::default()
        }
    }
}

/// Optional crosshair styles, one per [`CrosshairTarget`] state.
///
/// [`CrosshairPlugin`] initializes this resource with [`Default`] when the
/// game has not inserted one, and never replaces one that is already there.
/// With the default (both fields `None`) the crosshair is the classic cross
/// described by [`CrosshairConfig`], whatever the state.
///
/// The crosshair is redrawn when this resource or [`CrosshairTarget`] changes
/// and the style to show is different from the one on screen, so both can be
/// changed at runtime. Nothing is drawn while [`CrosshairConfig::visible`] was
/// `false` at startup.
///
/// # Example
///
/// A small dot that becomes a diamond while a minable voxel is in reach:
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .insert_resource(CrosshairStyles {
///         idle: Some(CrosshairStyle::dot(4.0)),
///         targeting: Some(CrosshairStyle::diamond(18.0)),
///     })
///     .add_plugins(CrosshairPlugin)
///     .add_plugins(CrosshairTargetPlugin::<DefaultVoxel>::new())
///     .run();
/// ```
#[derive(Resource, Debug, Clone, PartialEq, Default)]
pub struct CrosshairStyles {
    /// Style shown while the state is [`CrosshairTarget::Idle`]. `None` draws
    /// the classic cross from [`CrosshairConfig`].
    pub idle: Option<CrosshairStyle>,
    /// Style shown while the state is [`CrosshairTarget::Targeting`]. `None`
    /// shows the same as the idle state.
    pub targeting: Option<CrosshairStyle>,
}

// ─── Target state ────────────────────────────────────────────────────────────

/// Whether the player is pointing at something they can act on.
///
/// The framework does not discover players or decide what "in reach" means:
/// this resource is published by the game. Write it from a game system
/// (ideally in [`CrosshairSystems::Publish`]), or add
/// [`CrosshairTargetPlugin`] to have it written from a camera raycast.
/// [`CrosshairPlugin`] reads it to choose between the two styles of
/// [`CrosshairStyles`], and any other system can read it too, for example
/// with the `resource_changed::<CrosshairTarget>` run condition.
///
/// Both [`CrosshairPlugin`] and [`CrosshairTargetPlugin`] initialize it to
/// [`CrosshairTarget::Idle`].
///
/// # Example
///
/// ```rust
/// use bevy::prelude::*;
/// use voxel_framework::ui::CrosshairTarget;
///
/// // A game-owned rule: the game decides what the player can act on.
/// fn publish_target(mut target: ResMut<CrosshairTarget>) {
///     let can_act = true;
///     let next = if can_act {
///         CrosshairTarget::Targeting
///     } else {
///         CrosshairTarget::Idle
///     };
///     // Only marks the resource as changed when the value is different.
///     target.set_if_neq(next);
/// }
/// ```
#[derive(Resource, Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum CrosshairTarget {
    /// Nothing to act on.
    #[default]
    Idle,
    /// The player is pointing at something they can act on.
    Targeting,
}

impl CrosshairTarget {
    /// Returns `true` for [`CrosshairTarget::Targeting`].
    pub fn is_targeting(self) -> bool {
        self == Self::Targeting
    }
}

/// Scheduling boundary between publishing [`CrosshairTarget`] and drawing the
/// crosshair, in `Update`.
///
/// Put the system that writes [`CrosshairTarget`] in
/// [`CrosshairSystems::Publish`] so the crosshair shows the new state in the
/// same frame. A system outside the set still works; its change may be drawn
/// one frame later.
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CrosshairSystems {
    /// Game-owned systems, and [`crosshair_target_system`], write
    /// [`CrosshairTarget`] here.
    Publish,
    /// The crosshair is redrawn here, after `Publish`.
    Render,
}

// ─── Rendering ───────────────────────────────────────────────────────────────

/// Marker component for crosshair quad entities.
#[derive(Component)]
pub(crate) struct CrosshairNode;

/// What the crosshair root currently shows. Stored on the root so a state or
/// style change only rebuilds the crosshair when the result is different.
#[derive(Component, Debug, Clone, PartialEq)]
enum CrosshairDrawn {
    /// The classic cross from [`CrosshairConfig`].
    Classic,
    /// A [`CrosshairStyle`] from [`CrosshairStyles`].
    Styled(CrosshairStyle),
}

/// Chooses what to draw for a state.
fn resolve_crosshair(styles: &CrosshairStyles, target: CrosshairTarget) -> CrosshairDrawn {
    let style = match target {
        CrosshairTarget::Idle => styles.idle.as_ref(),
        CrosshairTarget::Targeting => styles.targeting.as_ref().or(styles.idle.as_ref()),
    };
    match style {
        Some(style) => CrosshairDrawn::Styled(style.clone()),
        None => CrosshairDrawn::Classic,
    }
}

/// A measure that is negative or not finite counts as zero.
fn crosshair_measure(value: f32) -> f32 {
    if value.is_finite() && value > 0.0 {
        value
    } else {
        0.0
    }
}

fn crosshair_color(rgba: [f32; 4]) -> Color {
    Color::srgba(rgba[0], rgba[1], rgba[2], rgba[3])
}

/// Side of the square that holds a styled cross, and its four arms as
/// `[left, top, width, height]` inside that square, in the order left, right,
/// top, bottom.
fn cross_layout(size: f32, gap: f32, thickness: f32) -> (f32, [[f32; 4]; 4]) {
    let size = crosshair_measure(size);
    let gap = crosshair_measure(gap);
    let thickness = crosshair_measure(thickness);
    let extent = (2.0 * (gap + size)).max(thickness);
    let middle = (extent - thickness) / 2.0;
    let far = extent - size;
    (
        extent,
        [
            [0.0, middle, size, thickness],
            [far, middle, size, thickness],
            [middle, 0.0, thickness, size],
            [middle, far, thickness, size],
        ],
    )
}

/// Side of the rotated square that draws a diamond of the given
/// corner-to-corner width, and its outline width.
fn diamond_layout(size: f32, thickness: f32) -> (f32, f32) {
    let side = crosshair_measure(size) / std::f32::consts::SQRT_2;
    let border = crosshair_measure(thickness).min(side / 2.0);
    (side, border)
}

/// The classic four-arm cross from [`CrosshairConfig`], centered on screen.
///
/// The arms hang from one square that the root centers. The square carries no
/// [`CrosshairNode`], so the classic cross is still the root plus four arms.
fn spawn_classic_cross(root: &mut ChildSpawnerCommands, c: &CrosshairConfig) {
    let color = crosshair_color(c.color);
    let (extent, arms) = cross_layout(c.size, c.gap, c.thickness);
    root.spawn(Node {
        width: Val::Px(extent),
        height: Val::Px(extent),
        ..default()
    })
    .with_children(|cross| {
        for [left, top, width, height] in arms {
            cross.spawn((
                CrosshairNode,
                Node {
                    position_type: PositionType::Absolute,
                    left: Val::Px(left),
                    top: Val::Px(top),
                    width: Val::Px(width),
                    height: Val::Px(height),
                    ..default()
                },
                BackgroundColor(color),
            ));
        }
    });
}

/// Spawns one styled shape as a single child of the root, which centers it.
fn spawn_styled_shape(root: &mut ChildSpawnerCommands, style: &CrosshairStyle) {
    let color = crosshair_color(style.color);
    match &style.shape {
        CrosshairShape::Cross => {
            let (extent, arms) = cross_layout(style.size, style.gap, style.thickness);
            root.spawn((
                CrosshairNode,
                Node {
                    width: Val::Px(extent),
                    height: Val::Px(extent),
                    ..default()
                },
            ))
            .with_children(|cross| {
                for [left, top, width, height] in arms {
                    cross.spawn((
                        CrosshairNode,
                        Node {
                            position_type: PositionType::Absolute,
                            left: Val::Px(left),
                            top: Val::Px(top),
                            width: Val::Px(width),
                            height: Val::Px(height),
                            ..default()
                        },
                        BackgroundColor(color),
                    ));
                }
            });
        }
        CrosshairShape::Dot => {
            let diameter = crosshair_measure(style.size);
            root.spawn((
                CrosshairNode,
                Node {
                    width: Val::Px(diameter),
                    height: Val::Px(diameter),
                    border_radius: BorderRadius::MAX,
                    ..default()
                },
                BackgroundColor(color),
            ));
        }
        CrosshairShape::Diamond => {
            let (side, border) = diamond_layout(style.size, style.thickness);
            root.spawn((
                CrosshairNode,
                Node {
                    width: Val::Px(side),
                    height: Val::Px(side),
                    border: UiRect::all(Val::Px(border)),
                    ..default()
                },
                BorderColor::all(color),
                UiTransform::from_rotation(Rot2::degrees(45.0)),
            ));
        }
        CrosshairShape::Image(image) => {
            let side = crosshair_measure(style.size);
            root.spawn((
                CrosshairNode,
                Node {
                    width: Val::Px(side),
                    height: Val::Px(side),
                    ..default()
                },
                ImageNode::new(image.clone()).with_color(color),
            ));
        }
    }
}

fn spawn_crosshair_children(
    root: &mut ChildSpawnerCommands,
    config: &CrosshairConfig,
    drawn: &CrosshairDrawn,
) {
    match drawn {
        CrosshairDrawn::Classic => spawn_classic_cross(root, config),
        CrosshairDrawn::Styled(style) => spawn_styled_shape(root, style),
    }
}

fn spawn_crosshair(
    mut commands: Commands,
    config: Res<CrosshairConfig>,
    styles: Option<Res<CrosshairStyles>>,
    target: Option<Res<CrosshairTarget>>,
) {
    if !config.visible {
        return;
    }

    // Both are absent when the system runs without `CrosshairPlugin`.
    let drawn = match styles.as_deref() {
        Some(styles) => resolve_crosshair(styles, target.as_deref().copied().unwrap_or_default()),
        None => CrosshairDrawn::Classic,
    };

    // Root container — full screen, no interaction, just a layout anchor.
    commands
        .spawn((
            CrosshairNode,
            drawn.clone(),
            Node {
                width: Val::Percent(100.0),
                height: Val::Percent(100.0),
                position_type: PositionType::Absolute,
                justify_content: JustifyContent::Center,
                align_items: AlignItems::Center,
                ..default()
            },
            BackgroundColor(Color::NONE),
        ))
        .with_children(|root| spawn_crosshair_children(root, &config, &drawn));
}

/// Redraws the crosshair when the state or the styles ask for a different
/// look than the one on screen.
fn update_crosshair(
    mut commands: Commands,
    config: Res<CrosshairConfig>,
    styles: Res<CrosshairStyles>,
    target: Res<CrosshairTarget>,
    mut roots: Query<(Entity, &mut CrosshairDrawn)>,
) {
    if !styles.is_changed() && !target.is_changed() {
        return;
    }

    let wanted = resolve_crosshair(&styles, *target);
    for (entity, mut drawn) in &mut roots {
        if *drawn == wanted {
            continue;
        }
        *drawn = wanted.clone();
        commands
            .entity(entity)
            .despawn_children()
            .with_children(|root| spawn_crosshair_children(root, &config, &wanted));
    }
}

/// Plugin that renders a fixed center-screen crosshair from UI nodes.
///
/// By default the crosshair is built from four [`Node`] rectangles (left,
/// right, top, bottom arms) positioned with `PositionType::Absolute` relative
/// to a full-screen container. No images or asset loading are required.
///
/// Customize appearance by inserting [`CrosshairConfig`] before adding this
/// plugin. If [`CrosshairConfig::visible`] is `false`, no entities are spawned.
///
/// To draw a dot, a diamond outline or an image instead, or a different look
/// while the player points at something, insert [`CrosshairStyles`] and
/// publish [`CrosshairTarget`]. Both resources are initialized by this plugin
/// with defaults that keep the classic cross.
///
/// # Example
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::ui::{CrosshairPlugin, CrosshairConfig};
///
/// App::new()
///     .insert_resource(CrosshairConfig {
///         color: [0.0, 1.0, 0.0, 0.9],
///         gap: 6.0,
///         ..Default::default()
///     })
///     .add_plugins(CrosshairPlugin);
/// ```
pub struct CrosshairPlugin;

impl Plugin for CrosshairPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<CrosshairConfig>();
        app.init_resource::<CrosshairStyles>();
        app.init_resource::<CrosshairTarget>();
        app.configure_sets(
            Update,
            (CrosshairSystems::Publish, CrosshairSystems::Render).chain(),
        );
        app.add_systems(Startup, spawn_crosshair);
        app.add_systems(Update, update_crosshair.in_set(CrosshairSystems::Render));
    }
}

// ─── Raycast adapter ─────────────────────────────────────────────────────────

/// How far [`crosshair_target_system`] looks for a voxel.
///
/// Initialized by [`CrosshairTargetPlugin`]; insert it first to override the
/// default, or change it at runtime. The default, `6.0` world units, is the
/// distance used by
/// [`mining_input_system`](crate::world::mining::mining_input_system). A
/// distance that is not finite and positive finds nothing.
#[derive(Resource, Debug, Clone, Copy, PartialEq)]
pub struct CrosshairReach {
    /// Maximum distance from the camera to the voxel, in world units.
    pub max_distance: f32,
}

impl Default for CrosshairReach {
    fn default() -> Self {
        Self { max_distance: 6.0 }
    }
}

/// The state for a ray: [`CrosshairTarget::Targeting`] when the first solid
/// voxel within `max_distance` can be mined with `tool_level`.
fn voxel_target<V: VoxelType>(
    origin: Vec3,
    direction: Vec3,
    max_distance: f32,
    tool_level: u8,
    manager: &ChunkManager,
    chunks: &Query<&Chunk<V>>,
) -> CrosshairTarget {
    if !(max_distance.is_finite() && max_distance > 0.0) {
        return CrosshairTarget::Idle;
    }
    let Some(hit) = raycast(origin, direction, max_distance, manager, chunks) else {
        return CrosshairTarget::Idle;
    };
    let Some(chunk) = manager
        .get_entity(hit.chunk_coord)
        .and_then(|entity| chunks.get(entity).ok())
    else {
        return CrosshairTarget::Idle;
    };
    let (x, y, z) = hit.local;
    if tool_level >= chunk.get(x, y, z).mining_level() {
        CrosshairTarget::Targeting
    } else {
        CrosshairTarget::Idle
    }
}

/// Publishes [`CrosshairTarget`] from a raycast along the camera's forward
/// direction.
///
/// The state is [`CrosshairTarget::Targeting`] when the first solid voxel
/// within [`CrosshairReach::max_distance`] of the single [`Camera3d`] has a
/// [`mining_level`](crate::voxel::VoxelType::mining_level) that the current
/// [`ToolStats::tool_level`] satisfies, and [`CrosshairTarget::Idle`]
/// otherwise. A missing [`ToolStats`] resource counts as tool level `0`.
/// Without exactly one [`Camera3d`], or without a [`ChunkManager`], the state
/// is `Idle`. The resource is only marked as changed when the state changes.
///
/// Added by [`CrosshairTargetPlugin`]. It needs the [`CrosshairReach`] and
/// [`CrosshairTarget`] resources, which that plugin initializes.
pub fn crosshair_target_system<V: VoxelType>(
    camera_q: Query<&GlobalTransform, With<Camera3d>>,
    manager: Option<Res<ChunkManager>>,
    chunks: Query<&Chunk<V>>,
    tool_stats: Option<Res<ToolStats>>,
    reach: Res<CrosshairReach>,
    mut target: ResMut<CrosshairTarget>,
) {
    let tool_level = tool_stats.as_deref().map_or(0, |stats| stats.tool_level);
    let next = match (camera_q.single(), manager.as_deref()) {
        (Ok(camera), Some(manager)) => voxel_target(
            camera.translation(),
            camera.forward().as_vec3(),
            reach.max_distance,
            tool_level,
            manager,
            &chunks,
        ),
        _ => CrosshairTarget::Idle,
    };
    target.set_if_neq(next);
}

/// Optional adapter that publishes [`CrosshairTarget`] from a camera raycast.
///
/// Adds [`crosshair_target_system`] for voxel type `V` to `Update`, in
/// [`CrosshairSystems::Publish`], and initializes [`CrosshairReach`] and
/// [`CrosshairTarget`]. It is not part of [`UiPlugin`](crate::ui::UiPlugin) or
/// of any bundle: a game whose notion of "in reach" is different (another
/// camera, another reach per tool, entities instead of voxels) leaves this
/// plugin out and writes [`CrosshairTarget`] from its own system.
///
/// It works without [`CrosshairPlugin`] too, for a game that draws its own
/// reticle and only wants the state.
///
/// # Example
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugins(VoxelCorePlugin::<DefaultVoxel>::new())
///     .insert_resource(CrosshairReach { max_distance: 4.0 })
///     .insert_resource(CrosshairStyles {
///         idle: Some(CrosshairStyle::dot(4.0)),
///         targeting: Some(CrosshairStyle::default()),
///     })
///     .add_plugins(CrosshairPlugin)
///     .add_plugins(CrosshairTargetPlugin::<DefaultVoxel>::new())
///     .run();
/// ```
pub struct CrosshairTargetPlugin<V: VoxelType> {
    _m: std::marker::PhantomData<V>,
}

impl<V: VoxelType> CrosshairTargetPlugin<V> {
    /// Creates a new [`CrosshairTargetPlugin`] for voxel type `V`.
    pub fn new() -> Self {
        Self {
            _m: std::marker::PhantomData,
        }
    }
}

impl<V: VoxelType> Default for CrosshairTargetPlugin<V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<V: VoxelType> Plugin for CrosshairTargetPlugin<V> {
    fn build(&self, app: &mut App) {
        app.init_resource::<CrosshairReach>();
        app.init_resource::<CrosshairTarget>();
        app.configure_sets(
            Update,
            (CrosshairSystems::Publish, CrosshairSystems::Render).chain(),
        );
        app.add_systems(
            Update,
            crosshair_target_system::<V>.in_set(CrosshairSystems::Publish),
        );
    }
}

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

    const WARM: [f32; 4] = [1.0, 0.8, 0.2, 1.0];

    fn app_with(styles: CrosshairStyles) -> App {
        let mut app = App::new();
        app.insert_resource(styles).add_plugins(CrosshairPlugin);
        app
    }

    fn root(app: &mut App) -> Entity {
        let mut query = app
            .world_mut()
            .query_filtered::<Entity, With<CrosshairDrawn>>();
        query.single(app.world()).expect("one crosshair root")
    }

    fn children_of(app: &App, entity: Entity) -> Vec<Entity> {
        app.world()
            .get::<Children>(entity)
            .map(|children| children.to_vec())
            .unwrap_or_default()
    }

    fn node_count(app: &mut App) -> usize {
        let mut query = app
            .world_mut()
            .query_filtered::<Entity, With<CrosshairNode>>();
        query.iter(app.world()).count()
    }

    fn set_target(app: &mut App, target: CrosshairTarget) {
        *app.world_mut().resource_mut::<CrosshairTarget>() = target;
    }

    #[test]
    fn defaults_keep_the_classic_cross() {
        let style = CrosshairStyle::default();
        let config = CrosshairConfig::default();
        assert_eq!(style.shape, CrosshairShape::Cross);
        assert_eq!(style.color, config.color);
        assert_eq!(style.size, config.size);
        assert_eq!(style.gap, config.gap);
        assert_eq!(style.thickness, config.thickness);

        assert_eq!(
            CrosshairStyles::default(),
            CrosshairStyles {
                idle: None,
                targeting: None,
            }
        );
        assert_eq!(CrosshairTarget::default(), CrosshairTarget::Idle);
        assert!(!CrosshairTarget::Idle.is_targeting());
        assert!(CrosshairTarget::Targeting.is_targeting());
        assert_eq!(CrosshairReach::default().max_distance, 6.0);
    }

    #[test]
    fn classic_cross_is_laid_out_inside_a_centered_square() {
        let mut app = app_with(CrosshairStyles::default());
        app.update();

        // The root is full screen and centers its children, so the arms must
        // hang from one square child, not from the root's own edges.
        let root = root(&mut app);
        let squares = children_of(&app, root);
        assert_eq!(squares.len(), 1);
        let config = CrosshairConfig::default();
        let side = 2.0 * (config.gap + config.size);
        let square = app.world().get::<Node>(squares[0]).unwrap();
        assert_eq!(square.width, Val::Px(side));
        assert_eq!(square.height, Val::Px(side));

        let arms = children_of(&app, squares[0]);
        assert_eq!(arms.len(), 4);
        for arm in arms {
            let node = app.world().get::<Node>(arm).unwrap();
            let (Val::Px(left), Val::Px(top), Val::Px(width), Val::Px(height)) =
                (node.left, node.top, node.width, node.height)
            else {
                panic!("arm is not positioned in pixels: {node:?}");
            };
            assert!(left >= 0.0 && top >= 0.0);
            assert!(left + width <= side && top + height <= side);
        }

        // Root plus four arms, as before; the square is not a marked node.
        assert_eq!(node_count(&mut app), 5);
    }

    #[test]
    fn resolve_picks_the_style_for_the_state() {
        let dot = CrosshairStyle::dot(4.0);
        let diamond = CrosshairStyle::diamond(18.0);

        let none = CrosshairStyles::default();
        assert_eq!(
            resolve_crosshair(&none, CrosshairTarget::Idle),
            CrosshairDrawn::Classic
        );
        assert_eq!(
            resolve_crosshair(&none, CrosshairTarget::Targeting),
            CrosshairDrawn::Classic
        );

        let both = CrosshairStyles {
            idle: Some(dot.clone()),
            targeting: Some(diamond.clone()),
        };
        assert_eq!(
            resolve_crosshair(&both, CrosshairTarget::Idle),
            CrosshairDrawn::Styled(dot.clone())
        );
        assert_eq!(
            resolve_crosshair(&both, CrosshairTarget::Targeting),
            CrosshairDrawn::Styled(diamond.clone())
        );

        // Without a targeting style, the targeting state shows the idle one.
        let idle_only = CrosshairStyles {
            idle: Some(dot.clone()),
            targeting: None,
        };
        assert_eq!(
            resolve_crosshair(&idle_only, CrosshairTarget::Targeting),
            CrosshairDrawn::Styled(dot)
        );

        // Without an idle style, the idle state keeps the classic cross.
        let targeting_only = CrosshairStyles {
            idle: None,
            targeting: Some(diamond.clone()),
        };
        assert_eq!(
            resolve_crosshair(&targeting_only, CrosshairTarget::Idle),
            CrosshairDrawn::Classic
        );
        assert_eq!(
            resolve_crosshair(&targeting_only, CrosshairTarget::Targeting),
            CrosshairDrawn::Styled(diamond)
        );
    }

    #[test]
    fn measures_that_are_negative_or_not_finite_count_as_zero() {
        assert_eq!(crosshair_measure(3.5), 3.5);
        assert_eq!(crosshair_measure(0.0), 0.0);
        assert_eq!(crosshair_measure(-2.0), 0.0);
        assert_eq!(crosshair_measure(f32::NAN), 0.0);
        assert_eq!(crosshair_measure(f32::INFINITY), 0.0);
    }

    #[test]
    fn styled_cross_arms_are_symmetric_around_the_center() {
        let (extent, [left, right, top, bottom]) = cross_layout(10.0, 3.0, 2.0);
        assert_eq!(extent, 26.0);
        assert_eq!(left, [0.0, 12.0, 10.0, 2.0]);
        assert_eq!(right, [16.0, 12.0, 10.0, 2.0]);
        assert_eq!(top, [12.0, 0.0, 2.0, 10.0]);
        assert_eq!(bottom, [12.0, 16.0, 2.0, 10.0]);

        // The gap is the distance from the center to where each arm starts.
        let center = extent / 2.0;
        assert_eq!(center - (left[0] + left[2]), 3.0);
        assert_eq!(right[0] - center, 3.0);
        assert_eq!(center - (top[1] + top[3]), 3.0);
        assert_eq!(bottom[1] - center, 3.0);

        // Invalid measures do not produce negative or non-finite nodes.
        let (extent, arms) = cross_layout(f32::NAN, -1.0, f32::INFINITY);
        assert_eq!(extent, 0.0);
        assert!(arms.iter().flatten().all(|value| *value == 0.0));
    }

    #[test]
    fn diamond_side_comes_from_its_width_and_the_outline_fits_inside() {
        let (side, border) = diamond_layout(20.0, 2.0);
        assert!((side - 20.0 / std::f32::consts::SQRT_2).abs() < 1e-5);
        assert_eq!(border, 2.0);

        let (side, border) = diamond_layout(4.0, 50.0);
        assert_eq!(border, side / 2.0);

        assert_eq!(diamond_layout(-1.0, 2.0), (0.0, 0.0));
    }

    #[test]
    fn default_crosshair_is_the_same_five_nodes_in_both_states() {
        let mut app = app_with(CrosshairStyles::default());
        app.update();

        let root = root(&mut app);
        let square = children_of(&app, root);
        assert_eq!(square.len(), 1);
        let arms = children_of(&app, square[0]);
        assert_eq!(node_count(&mut app), 5);
        assert_eq!(arms.len(), 4);

        // The arms sit in a 48 px square around the center.
        let left = app.world().get::<Node>(arms[0]).unwrap();
        assert_eq!(left.width, Val::Px(20.0));
        assert_eq!(left.height, Val::Px(2.0));
        assert_eq!(left.left, Val::Px(0.0));
        assert_eq!(left.top, Val::Px(23.0));
        let bottom = app.world().get::<Node>(arms[3]).unwrap();
        assert_eq!(bottom.width, Val::Px(2.0));
        assert_eq!(bottom.height, Val::Px(20.0));
        assert_eq!(bottom.left, Val::Px(23.0));
        assert_eq!(bottom.top, Val::Px(28.0));
        assert_eq!(
            app.world().get::<BackgroundColor>(arms[0]).unwrap().0,
            Color::srgba(1.0, 1.0, 1.0, 1.0)
        );

        set_target(&mut app, CrosshairTarget::Targeting);
        app.update();

        // Nothing to switch to: the same entities stay.
        assert_eq!(children_of(&app, root), square);
        assert_eq!(children_of(&app, square[0]), arms);
        assert_eq!(node_count(&mut app), 5);
    }

    #[test]
    fn styles_switch_with_the_target_state() {
        let mut app = app_with(CrosshairStyles {
            idle: Some(CrosshairStyle {
                color: WARM,
                ..CrosshairStyle::dot(6.0)
            }),
            targeting: Some(CrosshairStyle {
                color: WARM,
                thickness: 3.0,
                ..CrosshairStyle::diamond(20.0)
            }),
        });
        app.update();

        let root = root(&mut app);
        let idle = children_of(&app, root);
        assert_eq!(idle.len(), 1);
        assert_eq!(node_count(&mut app), 2);
        let dot = app.world().get::<Node>(idle[0]).unwrap();
        assert_eq!(dot.width, Val::Px(6.0));
        assert_eq!(dot.height, Val::Px(6.0));
        assert_eq!(dot.border_radius, BorderRadius::MAX);
        assert_eq!(
            app.world().get::<BackgroundColor>(idle[0]).unwrap().0,
            crosshair_color(WARM)
        );

        set_target(&mut app, CrosshairTarget::Targeting);
        app.update();

        let targeting = children_of(&app, root);
        assert_eq!(targeting.len(), 1);
        assert_ne!(targeting, idle);
        assert_eq!(node_count(&mut app), 2);
        let (side, _) = diamond_layout(20.0, 3.0);
        let diamond = app.world().get::<Node>(targeting[0]).unwrap();
        assert_eq!(diamond.width, Val::Px(side));
        assert_eq!(diamond.height, Val::Px(side));
        assert_eq!(diamond.border, UiRect::all(Val::Px(3.0)));
        assert_eq!(
            *app.world().get::<BorderColor>(targeting[0]).unwrap(),
            BorderColor::all(crosshair_color(WARM))
        );
        assert_eq!(
            app.world()
                .get::<UiTransform>(targeting[0])
                .unwrap()
                .rotation,
            Rot2::degrees(45.0)
        );

        // A frame without changes keeps the entities.
        app.update();
        assert_eq!(children_of(&app, root), targeting);

        set_target(&mut app, CrosshairTarget::Idle);
        app.update();

        let back = children_of(&app, root);
        assert_eq!(back.len(), 1);
        assert_eq!(
            app.world().get::<Node>(back[0]).unwrap().border_radius,
            BorderRadius::MAX
        );
        assert_eq!(node_count(&mut app), 2);
    }

    #[test]
    fn targeting_style_alone_replaces_the_classic_cross_and_restores_it() {
        let mut app = app_with(CrosshairStyles {
            idle: None,
            targeting: Some(CrosshairStyle {
                size: 10.0,
                gap: 3.0,
                thickness: 2.0,
                ..CrosshairStyle::default()
            }),
        });
        app.update();
        let root = root(&mut app);
        assert_eq!(children_of(&app, root).len(), 1);
        assert_eq!(node_count(&mut app), 5);

        set_target(&mut app, CrosshairTarget::Targeting);
        app.update();

        // A styled cross is one centered square holding the four arms.
        let holder = children_of(&app, root);
        assert_eq!(holder.len(), 1);
        let holder_node = app.world().get::<Node>(holder[0]).unwrap();
        assert_eq!(holder_node.width, Val::Px(26.0));
        assert_eq!(holder_node.height, Val::Px(26.0));
        assert_eq!(holder_node.position_type, PositionType::default());
        let arms = children_of(&app, holder[0]);
        assert_eq!(arms.len(), 4);
        let right = app.world().get::<Node>(arms[1]).unwrap();
        assert_eq!(right.left, Val::Px(16.0));
        assert_eq!(right.top, Val::Px(12.0));
        assert_eq!(right.width, Val::Px(10.0));
        assert_eq!(right.height, Val::Px(2.0));
        assert_eq!(node_count(&mut app), 6);

        set_target(&mut app, CrosshairTarget::Idle);
        app.update();

        assert_eq!(children_of(&app, root).len(), 1);
        assert_eq!(node_count(&mut app), 5);
    }

    #[test]
    fn styles_changed_at_runtime_redraw_the_crosshair() {
        let mut app = app_with(CrosshairStyles::default());
        app.update();
        let root = root(&mut app);
        assert_eq!(node_count(&mut app), 5);

        let image = Handle::<Image>::default();
        app.world_mut().resource_mut::<CrosshairStyles>().idle = Some(CrosshairStyle {
            color: WARM,
            ..CrosshairStyle::image(image.clone(), 32.0)
        });
        app.update();

        let children = children_of(&app, root);
        assert_eq!(children.len(), 1);
        let node = app.world().get::<Node>(children[0]).unwrap();
        assert_eq!(node.width, Val::Px(32.0));
        assert_eq!(node.height, Val::Px(32.0));
        let image_node = app.world().get::<ImageNode>(children[0]).unwrap();
        assert_eq!(image_node.image, image);
        assert_eq!(image_node.color, crosshair_color(WARM));
        assert_eq!(node_count(&mut app), 2);
    }

    #[test]
    fn hidden_crosshair_spawns_nothing_in_any_state() {
        let mut app = App::new();
        app.insert_resource(CrosshairConfig {
            visible: false,
            ..Default::default()
        })
        .insert_resource(CrosshairStyles {
            idle: Some(CrosshairStyle::dot(4.0)),
            targeting: Some(CrosshairStyle::diamond(18.0)),
        })
        .add_plugins(CrosshairPlugin);
        app.update();
        assert_eq!(node_count(&mut app), 0);

        set_target(&mut app, CrosshairTarget::Targeting);
        app.update();
        assert_eq!(node_count(&mut app), 0);
    }

    #[test]
    fn plugin_keeps_resources_inserted_by_the_game() {
        let styles = CrosshairStyles {
            idle: Some(CrosshairStyle::dot(4.0)),
            targeting: None,
        };
        let mut app = App::new();
        app.insert_resource(styles.clone())
            .insert_resource(CrosshairTarget::Targeting)
            .insert_resource(CrosshairReach { max_distance: 3.0 })
            .add_plugins(CrosshairPlugin)
            .add_plugins(CrosshairTargetPlugin::<ReachVoxel>::new());

        assert_eq!(*app.world().resource::<CrosshairStyles>(), styles);
        assert_eq!(
            *app.world().resource::<CrosshairTarget>(),
            CrosshairTarget::Targeting
        );
        assert_eq!(app.world().resource::<CrosshairReach>().max_distance, 3.0);
    }

    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
    enum ReachVoxel {
        #[default]
        Air,
        Soft,
        Ore,
    }

    impl VoxelType for ReachVoxel {
        fn name(&self) -> &'static str {
            "reach voxel"
        }
        fn is_solid(&self) -> bool {
            *self != Self::Air
        }
        fn color(&self) -> [f32; 4] {
            [1.0; 4]
        }
        fn to_byte(&self) -> u8 {
            *self as u8
        }
        fn from_byte(byte: u8) -> Self {
            match byte {
                1 => Self::Soft,
                2 => Self::Ore,
                _ => Self::Air,
            }
        }
        fn mining_level(&self) -> u8 {
            if *self == Self::Ore { 2 } else { 0 }
        }
    }

    /// An app with one chunk holding `voxel` at `(4, 4, 4)` and a camera three
    /// units in front of it, looking at it along `-Z`.
    fn reach_app(voxel: ReachVoxel) -> App {
        let mut app = App::new();
        app.insert_resource(ChunkManager::new(32.0, 48.0))
            .add_plugins(CrosshairTargetPlugin::<ReachVoxel>::new());
        let mut chunk = Chunk::<ReachVoxel>::new();
        chunk.set(4, 4, 4, voxel);
        let entity = app.world_mut().spawn(chunk).id();
        app.world_mut()
            .resource_mut::<ChunkManager>()
            .register(IVec3::ZERO, entity);
        app.world_mut().spawn((
            Camera3d::default(),
            GlobalTransform::from_translation(Vec3::new(4.5, 4.5, 8.0)),
        ));
        app
    }

    fn target(app: &App) -> CrosshairTarget {
        *app.world().resource::<CrosshairTarget>()
    }

    #[test]
    fn voxel_in_reach_is_targeted_and_out_of_reach_is_not() {
        let mut app = reach_app(ReachVoxel::Soft);
        app.update();
        assert_eq!(target(&app), CrosshairTarget::Targeting);

        app.world_mut()
            .resource_mut::<CrosshairReach>()
            .max_distance = 2.0;
        app.update();
        assert_eq!(target(&app), CrosshairTarget::Idle);

        app.world_mut()
            .resource_mut::<CrosshairReach>()
            .max_distance = f32::NAN;
        app.update();
        assert_eq!(target(&app), CrosshairTarget::Idle);
    }

    #[test]
    fn voxel_needs_a_tool_level_that_can_mine_it() {
        let mut app = reach_app(ReachVoxel::Ore);
        // Without `ToolStats` the tool level is zero.
        app.update();
        assert_eq!(target(&app), CrosshairTarget::Idle);

        app.insert_resource(ToolStats {
            tool_level: 1,
            tool_speed: 1.0,
        });
        app.update();
        assert_eq!(target(&app), CrosshairTarget::Idle);

        app.world_mut().resource_mut::<ToolStats>().tool_level = 2;
        app.update();
        assert_eq!(target(&app), CrosshairTarget::Targeting);
    }

    #[test]
    fn empty_view_and_missing_camera_are_idle() {
        let mut app = reach_app(ReachVoxel::Air);
        app.insert_resource(CrosshairTarget::Targeting);
        app.update();
        assert_eq!(target(&app), CrosshairTarget::Idle);

        let mut app = App::new();
        app.insert_resource(CrosshairTarget::Targeting)
            .add_plugins(CrosshairTargetPlugin::<ReachVoxel>::new());
        app.update();
        assert_eq!(target(&app), CrosshairTarget::Idle);
    }

    #[test]
    fn unchanged_state_does_not_mark_the_resource_as_changed() {
        #[derive(Resource, Default)]
        struct Changes(u32);

        fn count(target: Res<CrosshairTarget>, mut changes: ResMut<Changes>) {
            if target.is_changed() {
                changes.0 += 1;
            }
        }

        let mut app = reach_app(ReachVoxel::Soft);
        app.init_resource::<Changes>()
            .add_systems(Update, count.after(CrosshairSystems::Publish));
        for _ in 0..3 {
            app.update();
        }

        // Once when the resource is first seen and set; not on later frames.
        assert_eq!(app.world().resource::<Changes>().0, 1);
    }

    #[test]
    fn adapter_drives_the_crosshair_in_the_same_frame() {
        let mut app = reach_app(ReachVoxel::Soft);
        app.insert_resource(CrosshairStyles {
            idle: Some(CrosshairStyle::dot(4.0)),
            targeting: Some(CrosshairStyle::diamond(18.0)),
        })
        .add_plugins(CrosshairPlugin);

        app.update();

        let root = root(&mut app);
        let children = children_of(&app, root);
        assert_eq!(children.len(), 1);
        assert!(app.world().get::<UiTransform>(children[0]).is_some());
        assert_eq!(
            *app.world().get::<CrosshairDrawn>(root).unwrap(),
            CrosshairDrawn::Styled(CrosshairStyle::diamond(18.0))
        );
    }
}