voxel-framework 0.12.2

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
//! Optional, asset-free default presentation for collectible drops.

use std::{collections::HashMap, marker::PhantomData};

use bevy::camera::visibility::VisibilitySystems;
use bevy::prelude::*;
use bevy::transform::TransformSystems;

use super::{DroppedItem, ItemType};

/// Draws positioned drops as small, unlit cubes colored by [`ItemType::color`].
///
/// Add after `DefaultPlugins`, alongside [`super::DropsPlugin`]. This plugin
/// requires `Assets<Mesh>` and `Assets<StandardMaterial>`; it does not install
/// gameplay, cameras, or lighting. It is not included in convenience bundles.
///
/// Cubes are 0.25 world units wide, sharing one mesh and one material per item
/// variant. Render components live on the drop itself, so pickup and expiration
/// also remove its visual. Drops with an existing `Mesh3d` or
/// `MeshMaterial3d<StandardMaterial>` are left untouched. To own all presentation,
/// omit this plugin. Drop transforms and quantities are never changed here.
///
/// Optional idle motion (spin and bob) is configured through
/// [`DropVisualConfig`]. With motion enabled the cube lives on a child entity
/// marked [`DropVisual`] instead of on the drop, and only that child moves.
///
/// Colors are sampled on first use; changing a rendered drop's item identity or
/// dynamically recoloring the palette is not supported by this default.
///
/// ```no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugins((MiningPlugin, DropsPlugin::<DefaultItem>::new(), DropVisualPlugin::<DefaultItem>::new()));
/// ```
pub struct DropVisualPlugin<I: ItemType> {
    _marker: PhantomData<I>,
}

impl<I: ItemType> DropVisualPlugin<I> {
    /// Creates the optional default drop renderer.
    pub fn new() -> Self {
        Self {
            _marker: PhantomData,
        }
    }
}

impl<I: ItemType> Default for DropVisualPlugin<I> {
    fn default() -> Self {
        Self::new()
    }
}

/// Idle motion for the default drop visuals: a slow spin and a bob.
///
/// The default is no motion, which keeps the visual on the drop entity itself.
/// With any motion enabled, a drop's cube is spawned as a **child** entity
/// marked [`DropVisual`] and only that child's local transform is animated, so
/// the drop's own `Transform` (its logical position, used by attraction and
/// pickup) is never touched.
///
/// [`DropVisualPlugin`] initializes this resource. Insert your own value to
/// enable motion:
///
/// ```no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugins((DropsPlugin::<DefaultItem>::new(), DropVisualPlugin::<DefaultItem>::new()))
///     .insert_resource(DropVisualConfig {
///         spin_rad_per_sec: 1.5,
///         bob_amplitude: 0.05,
///         bob_period: 2.0,
///     });
/// ```
///
/// The values are read every frame, so they can be changed while drops exist.
/// Whether a drop gets a child visual is decided once, when its visual is
/// first attached.
#[derive(Resource, Debug, Clone, Copy, PartialEq, Default)]
pub struct DropVisualConfig {
    /// Spin around the drop's local Y axis, in radians per second. `0.0`
    /// disables spinning.
    pub spin_rad_per_sec: f32,
    /// Peak offset of the bob along the drop's local Y axis, in world units.
    /// `0.0` disables bobbing.
    pub bob_amplitude: f32,
    /// Seconds for one full up-and-down cycle. Bobbing needs a positive,
    /// finite period.
    pub bob_period: f32,
}

impl DropVisualConfig {
    /// `true` when the configuration produces any motion.
    pub fn is_animated(&self) -> bool {
        self.spins() || self.bobs()
    }

    fn spins(&self) -> bool {
        self.spin_rad_per_sec.is_finite() && self.spin_rad_per_sec != 0.0
    }

    fn bobs(&self) -> bool {
        self.bob_amplitude.is_finite()
            && self.bob_amplitude != 0.0
            && self.bob_period.is_finite()
            && self.bob_period > 0.0
    }
}

/// Marks the child entity that carries an animated drop's default visual.
///
/// Present only when [`DropVisualConfig`] had motion enabled when the visual
/// was attached. The child is despawned together with its drop.
#[derive(Component, Debug, Clone, Copy, PartialEq)]
pub struct DropVisual {
    /// Per-drop offset, in seconds, so that drops do not move in unison.
    pub phase_secs: f32,
}

/// Put on a drop whose default visual lives on a [`DropVisual`] child.
#[derive(Component)]
struct HasDropVisualChild;

impl<I: ItemType> Plugin for DropVisualPlugin<I> {
    fn build(&self, app: &mut App) {
        app.init_resource::<DropVisualConfig>();
        app.insert_resource(DropVisualAssets::<I> {
            mesh: None,
            materials: HashMap::new(),
        })
        .add_systems(
            PostUpdate,
            (attach_visuals::<I>, animate_drop_visuals)
                .chain()
                .before(TransformSystems::Propagate)
                .before(VisibilitySystems::VisibilityPropagate)
                .before(VisibilitySystems::CalculateBounds),
        );
    }
}

#[derive(Resource)]
struct DropVisualAssets<I: ItemType> {
    mesh: Option<Handle<Mesh>>,
    materials: HashMap<I, Handle<StandardMaterial>>,
}

fn attach_visuals<I: ItemType>(
    mut commands: Commands,
    drops: Query<
        (Entity, &DroppedItem<I>),
        (
            With<Transform>,
            Without<Mesh3d>,
            Without<MeshMaterial3d<StandardMaterial>>,
            Without<HasDropVisualChild>,
        ),
    >,
    config: Res<DropVisualConfig>,
    mut cache: ResMut<DropVisualAssets<I>>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    let animated = config.is_animated();
    for (entity, drop) in &drops {
        let mesh = cache
            .mesh
            .get_or_insert_with(|| meshes.add(Cuboid::new(0.25, 0.25, 0.25)))
            .clone();
        let material = cache
            .materials
            .entry(drop.item)
            .or_insert_with(|| {
                let [r, g, b, a] = drop.item.color();
                materials.add(StandardMaterial {
                    base_color: Color::srgba(r, g, b, a),
                    unlit: true,
                    alpha_mode: if a < 1.0 {
                        AlphaMode::Blend
                    } else {
                        AlphaMode::Opaque
                    },
                    ..default()
                })
            })
            .clone();
        if animated {
            // The cube goes on a child so its motion never touches the drop's
            // own transform. Despawning the drop despawns the child with it.
            commands
                .entity(entity)
                .insert(HasDropVisualChild)
                .insert_if_new(Visibility::Inherited)
                .with_child((
                    DropVisual {
                        phase_secs: phase_for(entity),
                    },
                    Mesh3d(mesh),
                    MeshMaterial3d(material),
                    Transform::IDENTITY,
                ));
        } else {
            commands
                .entity(entity)
                .insert((Mesh3d(mesh), MeshMaterial3d(material)))
                .insert_if_new(Visibility::Inherited);
        }
    }
}

/// A stable, per-entity offset in seconds, so drops spawned together do not
/// spin and bob in unison.
fn phase_for(entity: Entity) -> f32 {
    // Golden-ratio spacing spreads consecutive indices evenly over [0, 8).
    (entity.index_u32() as f32 * 0.618_034).fract() * 8.0
}

/// Applies [`DropVisualConfig`] to every [`DropVisual`] child.
///
/// Only the child's local transform is written. With motion disabled the
/// children return to rest.
fn animate_drop_visuals(
    time: Res<Time>,
    config: Res<DropVisualConfig>,
    mut visuals: Query<(&DropVisual, &mut Transform)>,
) {
    for (visual, mut transform) in &mut visuals {
        let t = time.elapsed_secs() + visual.phase_secs;
        let rotation = if config.spins() {
            Quat::from_rotation_y(config.spin_rad_per_sec * t)
        } else {
            Quat::IDENTITY
        };
        let offset = if config.bobs() {
            config.bob_amplitude * (std::f32::consts::TAU * t / config.bob_period).sin()
        } else {
            0.0
        };
        let target = Transform {
            translation: Vec3::new(0.0, offset, 0.0),
            rotation,
            scale: Vec3::ONE,
        };
        // Skip the write when nothing changes, so resting drops do not look
        // modified to change detection every frame.
        if *transform != target {
            *transform = target;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::items::{
        ContainerComponent, DefaultItem, DropTable, DropsPlugin, ItemCollector, ItemPickedUp,
        PrimaryContainer,
    };
    use crate::world::VoxelBroken;
    use bevy::camera::visibility::VisibilityPlugin;
    use bevy::transform::TransformPlugin;

    fn app(visuals: bool) -> App {
        let mut app = App::new();
        app.init_resource::<Time>()
            .init_resource::<Assets<Mesh>>()
            .init_resource::<Assets<StandardMaterial>>()
            .add_message::<VoxelBroken>()
            .add_plugins((
                TransformPlugin,
                VisibilityPlugin,
                DropsPlugin::<DefaultItem>::new(),
            ));
        if visuals {
            app.add_plugins(DropVisualPlugin::<DefaultItem>::new());
        }
        app
    }

    fn spawn(app: &mut App, item: DefaultItem, count: u32) -> Entity {
        app.world_mut()
            .spawn((
                DroppedItem {
                    item,
                    count,
                    velocity: Vec3::ZERO,
                    lifetime: 1.0,
                },
                Transform::from_xyz(2.0, 0.0, 0.0),
            ))
            .id()
    }

    fn animated() -> DropVisualConfig {
        DropVisualConfig {
            spin_rad_per_sec: 2.0,
            bob_amplitude: 0.1,
            bob_period: 4.0,
        }
    }

    fn visual_children(app: &mut App, drop: Entity) -> Vec<Entity> {
        let world = app.world_mut();
        let mut query = world.query::<(Entity, &ChildOf, &DropVisual)>();
        query
            .iter(world)
            .filter(|(_, parent, _)| parent.parent() == drop)
            .map(|(entity, _, _)| entity)
            .collect()
    }

    fn advance(app: &mut App, secs: f32) {
        app.world_mut()
            .resource_mut::<Time>()
            .advance_by(std::time::Duration::from_secs_f32(secs));
        app.update();
    }

    #[test]
    fn config_reports_motion_only_for_usable_values() {
        assert!(!DropVisualConfig::default().is_animated());
        assert!(animated().is_animated());
        assert!(
            DropVisualConfig {
                spin_rad_per_sec: 1.0,
                ..default()
            }
            .is_animated()
        );
        // A bob without a period, or with broken numbers, is no motion.
        assert!(
            !DropVisualConfig {
                bob_amplitude: 0.1,
                ..default()
            }
            .is_animated()
        );
        assert!(
            !DropVisualConfig {
                spin_rad_per_sec: f32::NAN,
                bob_amplitude: 0.1,
                bob_period: -1.0,
            }
            .is_animated()
        );
    }

    #[test]
    fn default_config_keeps_the_visual_on_the_drop_itself() {
        let mut app = app(true);
        let drop = spawn(&mut app, DefaultItem::RockFragment, 1);
        app.update();
        advance(&mut app, 0.5);

        assert!(app.world().get::<Mesh3d>(drop).is_some());
        assert!(visual_children(&mut app, drop).is_empty());
        assert_eq!(
            app.world().get::<Transform>(drop).unwrap(),
            &Transform::from_xyz(2.0, 0.0, 0.0)
        );
    }

    #[test]
    fn plugin_keeps_a_config_inserted_before_it() {
        let mut app = App::new();
        app.insert_resource(animated());
        app.add_plugins(DropVisualPlugin::<DefaultItem>::new());
        assert_eq!(*app.world().resource::<DropVisualConfig>(), animated());
    }

    #[test]
    fn idle_motion_animates_a_child_and_never_the_drop() {
        let mut app = app(true);
        app.insert_resource(animated());
        let drop = spawn(&mut app, DefaultItem::RockFragment, 1);
        let start = *app.world().get::<Transform>(drop).unwrap();
        app.update();
        app.update();

        assert!(
            app.world().get::<Mesh3d>(drop).is_none(),
            "the mesh belongs to the child when motion is enabled"
        );
        let children = visual_children(&mut app, drop);
        assert_eq!(children.len(), 1);
        let child = children[0];
        assert!(app.world().get::<Mesh3d>(child).is_some());
        assert!(
            app.world()
                .get::<MeshMaterial3d<StandardMaterial>>(child)
                .is_some()
        );
        assert!(app.world().get::<InheritedVisibility>(child).unwrap().get());

        let before = *app.world().get::<Transform>(child).unwrap();
        advance(&mut app, 0.7);
        let after = *app.world().get::<Transform>(child).unwrap();
        assert_ne!(after.rotation, before.rotation, "the child spins");
        assert_ne!(after.translation.y, before.translation.y, "the child bobs");
        assert!(after.translation.y.abs() <= 0.1 + 1e-5);
        assert_eq!(after.translation.x, 0.0);
        assert_eq!(after.translation.z, 0.0);

        // More frames never add a second child and never move the drop.
        advance(&mut app, 0.1);
        assert_eq!(visual_children(&mut app, drop).len(), 1);
        assert_eq!(*app.world().get::<Transform>(drop).unwrap(), start);
        // The rendered position follows the drop plus the bob offset.
        let rendered = app.world().get::<GlobalTransform>(child).unwrap();
        assert!((rendered.translation().x - start.translation.x).abs() < 1e-5);
    }

    #[test]
    fn idle_motion_shares_assets_and_respects_custom_presentation() {
        let mut app = app(true);
        app.insert_resource(animated());
        let first = spawn(&mut app, DefaultItem::RockFragment, 1);
        let second = spawn(&mut app, DefaultItem::RockFragment, 1);
        let custom = spawn(&mut app, DefaultItem::Crystal, 1);
        let mesh = app
            .world_mut()
            .resource_mut::<Assets<Mesh>>()
            .add(Cuboid::new(1.0, 1.0, 1.0));
        app.world_mut()
            .entity_mut(custom)
            .insert(Mesh3d(mesh.clone()));
        app.update();
        app.update();

        let a = visual_children(&mut app, first)[0];
        let b = visual_children(&mut app, second)[0];
        assert_eq!(
            app.world().get::<Mesh3d>(a).unwrap().0,
            app.world().get::<Mesh3d>(b).unwrap().0
        );
        assert_eq!(
            app.world()
                .get::<MeshMaterial3d<StandardMaterial>>(a)
                .unwrap()
                .0,
            app.world()
                .get::<MeshMaterial3d<StandardMaterial>>(b)
                .unwrap()
                .0
        );
        assert_ne!(
            app.world().get::<DropVisual>(a).unwrap().phase_secs,
            app.world().get::<DropVisual>(b).unwrap().phase_secs,
            "drops should not move in unison"
        );
        // A drop with its own mesh is left alone: no child, mesh untouched.
        assert!(visual_children(&mut app, custom).is_empty());
        assert_eq!(app.world().get::<Mesh3d>(custom).unwrap().0, mesh);
    }

    #[test]
    fn animated_visual_disappears_with_its_drop() {
        let mut app = app(true);
        app.insert_resource(animated());
        let drop = spawn(&mut app, DefaultItem::RockFragment, 1);
        app.update();
        app.update();
        assert_eq!(visual_children(&mut app, drop).len(), 1);

        // The drop's lifetime is one second.
        advance(&mut app, 1.0);

        assert!(app.world().get_entity(drop).is_err());
        assert_eq!(
            app.world_mut().query::<&Mesh3d>().iter(app.world()).count(),
            0
        );
    }

    #[test]
    fn disabling_motion_returns_existing_children_to_rest() {
        let mut app = app(true);
        app.insert_resource(animated());
        let drop = spawn(&mut app, DefaultItem::RockFragment, 1);
        // Long-lived so it survives the time steps below.
        app.world_mut()
            .get_mut::<DroppedItem<DefaultItem>>(drop)
            .unwrap()
            .lifetime = 60.0;
        app.update();
        app.update();
        advance(&mut app, 0.7);
        let child = visual_children(&mut app, drop)[0];
        assert_ne!(
            *app.world().get::<Transform>(child).unwrap(),
            Transform::IDENTITY
        );

        app.insert_resource(DropVisualConfig::default());
        advance(&mut app, 0.1);

        assert_eq!(
            *app.world().get::<Transform>(child).unwrap(),
            Transform::IDENTITY
        );
    }

    #[test]
    fn mapped_drop_gets_visible_shared_assets_in_spawn_frame() {
        let mut app = app(true);
        app.world_mut()
            .resource_mut::<DropTable<DefaultItem>>()
            .register(1, DefaultItem::RockFragment, 1, 1);
        let position = Vec3::new(2.5, 3.5, 4.5);
        app.world_mut().write_message(VoxelBroken {
            chunk_coord: IVec3::ZERO,
            local: (2, 3, 4),
            world_pos: position,
            voxel_byte: 1,
        });
        app.update();
        let world = app.world_mut();
        let mut query = world.query_filtered::<Entity, With<DroppedItem<DefaultItem>>>();
        let entity = query.single(world).unwrap();
        let mesh = world
            .get::<Mesh3d>(entity)
            .expect("mapped drop must have a mesh")
            .0
            .clone();
        let material = world
            .get::<MeshMaterial3d<StandardMaterial>>(entity)
            .unwrap()
            .0
            .clone();
        assert_eq!(
            world.get::<GlobalTransform>(entity).unwrap().translation(),
            position
        );
        assert_eq!(
            *world.get::<Visibility>(entity).unwrap(),
            Visibility::Inherited
        );
        assert!(world.get::<InheritedVisibility>(entity).unwrap().get());
        let assets = world.resource::<Assets<StandardMaterial>>();
        let mat = assets.get(&material).unwrap();
        assert!(mat.unlit);
        let [r, g, b, a] = DefaultItem::RockFragment.color();
        assert_eq!(mat.base_color, Color::srgba(r, g, b, a));
        assert!(world.resource::<Assets<Mesh>>().get(&mesh).is_some());
        let second = spawn(&mut app, DefaultItem::RockFragment, 4);
        let other = spawn(&mut app, DefaultItem::Crystal, 1);
        app.update();
        assert_eq!(app.world().get::<Mesh3d>(second).unwrap().0, mesh);
        assert_eq!(
            app.world()
                .get::<MeshMaterial3d<StandardMaterial>>(second)
                .unwrap()
                .0,
            material
        );
        assert_eq!(app.world().get::<Mesh3d>(other).unwrap().0, mesh);
        assert_ne!(
            app.world()
                .get::<MeshMaterial3d<StandardMaterial>>(other)
                .unwrap()
                .0,
            material
        );
        assert_eq!(app.world().resource::<Assets<Mesh>>().len(), 1);
        assert_eq!(app.world().resource::<Assets<StandardMaterial>>().len(), 2);
    }

    #[test]
    fn visuals_are_opt_in_and_preserve_custom_components_and_late_transforms() {
        let mut app = app(false);
        let ordinary = spawn(&mut app, DefaultItem::RockFragment, 1);
        app.update();
        assert!(app.world().get::<Mesh3d>(ordinary).is_none());
        app.add_plugins(DropVisualPlugin::<DefaultItem>::new());
        let custom = spawn(&mut app, DefaultItem::Crystal, 1);
        let mesh = app
            .world_mut()
            .resource_mut::<Assets<Mesh>>()
            .add(Cuboid::new(1.0, 1.0, 1.0));
        app.world_mut()
            .entity_mut(custom)
            .insert(Mesh3d(mesh.clone()));
        let custom_material = spawn(&mut app, DefaultItem::Crystal, 1);
        let material = app
            .world_mut()
            .resource_mut::<Assets<StandardMaterial>>()
            .add(StandardMaterial::default());
        app.world_mut()
            .entity_mut(custom_material)
            .insert(MeshMaterial3d(material.clone()));
        let late = app
            .world_mut()
            .spawn(DroppedItem {
                item: DefaultItem::Crystal,
                count: 1,
                velocity: Vec3::ZERO,
                lifetime: 1.0,
            })
            .id();
        app.update();
        assert!(app.world().get::<Mesh3d>(ordinary).is_some());
        assert_eq!(app.world().get::<Mesh3d>(custom).unwrap().0, mesh);
        assert!(
            app.world()
                .get::<MeshMaterial3d<StandardMaterial>>(custom)
                .is_none()
        );
        assert_eq!(
            app.world()
                .get::<MeshMaterial3d<StandardMaterial>>(custom_material)
                .unwrap()
                .0,
            material
        );
        assert!(app.world().get::<Mesh3d>(custom_material).is_none());
        assert!(app.world().get::<Mesh3d>(late).is_none());
        app.world_mut()
            .entity_mut(late)
            .insert(Transform::default());
        app.update();
        assert!(app.world().get::<Mesh3d>(late).is_some());
    }

    #[test]
    fn moving_drop_propagates_position_and_keeps_runtime_visual_replacement() {
        let mut app = app(true);
        let entity = spawn(&mut app, DefaultItem::RockFragment, 1);
        app.world_mut()
            .spawn((ItemCollector, Transform::from_xyz(50.0, 0.0, 0.0)));
        app.world_mut()
            .get_mut::<DroppedItem<DefaultItem>>(entity)
            .unwrap()
            .velocity = Vec3::new(1.0, 2.0, 3.0);
        app.update();
        let initial = app
            .world()
            .get::<GlobalTransform>(entity)
            .unwrap()
            .translation();
        let default_mesh = app.world().get::<Mesh3d>(entity).unwrap().0.clone();
        app.world_mut()
            .resource_mut::<Time>()
            .advance_by(std::time::Duration::from_millis(100));
        app.update();
        let moved = app.world().get::<Transform>(entity).unwrap().translation;
        assert_ne!(moved, initial, "DropsPlugin must actually move the drop");
        assert_eq!(
            app.world()
                .get::<GlobalTransform>(entity)
                .unwrap()
                .translation(),
            moved
        );
        assert_eq!(app.world().get::<Mesh3d>(entity).unwrap().0, default_mesh);

        let mesh = app
            .world_mut()
            .resource_mut::<Assets<Mesh>>()
            .add(Sphere::new(0.5));
        let material = app
            .world_mut()
            .resource_mut::<Assets<StandardMaterial>>()
            .add(StandardMaterial {
                base_color: Color::srgb(0.1, 0.8, 0.2),
                ..default()
            });
        app.world_mut().entity_mut(entity).insert((
            Mesh3d(mesh.clone()),
            MeshMaterial3d(material.clone()),
            Visibility::Hidden,
            Transform::from_xyz(-4.0, 5.0, 6.0),
        ));
        app.world_mut()
            .resource_mut::<Time>()
            .advance_by(std::time::Duration::ZERO);
        app.update();
        assert_eq!(
            app.world()
                .get::<GlobalTransform>(entity)
                .unwrap()
                .translation(),
            Vec3::new(-4.0, 5.0, 6.0)
        );
        assert_eq!(app.world().get::<Mesh3d>(entity).unwrap().0, mesh);
        assert_eq!(
            app.world()
                .get::<MeshMaterial3d<StandardMaterial>>(entity)
                .unwrap()
                .0,
            material
        );
        assert_eq!(
            *app.world().get::<Visibility>(entity).unwrap(),
            Visibility::Hidden
        );
    }

    #[test]
    fn visible_remainder_survives_partial_pickup_and_cleans_up_on_collection_or_expiry() {
        let mut app = app(true);
        let item = DefaultItem::RockFragment;
        let entity = spawn(&mut app, item, 3);
        app.update();
        let mesh = app.world().get::<Mesh3d>(entity).unwrap().0.clone();
        let material = app
            .world()
            .get::<MeshMaterial3d<StandardMaterial>>(entity)
            .unwrap()
            .0
            .clone();
        let mut inventory = ContainerComponent::<DefaultItem>::new(1);
        inventory.0.add(item, u32::MAX - 1);
        let player = app
            .world_mut()
            .spawn((
                ItemCollector,
                PrimaryContainer,
                inventory,
                Transform::from_xyz(2.0, 0.0, 0.0),
            ))
            .id();
        for expected in [1, 0, 2] {
            if expected == 2 {
                app.world_mut()
                    .get_mut::<ContainerComponent<DefaultItem>>(player)
                    .unwrap()
                    .0
                    .remove(item, 2);
            }
            app.update();
            let pickups: Vec<_> = app
                .world_mut()
                .resource_mut::<Messages<ItemPickedUp<DefaultItem>>>()
                .drain()
                .collect();
            assert_eq!(pickups.iter().map(|p| p.count).sum::<u32>(), expected);
            if expected != 2 {
                assert_eq!(
                    app.world()
                        .get::<DroppedItem<DefaultItem>>(entity)
                        .unwrap()
                        .count,
                    2
                );
                assert_eq!(app.world().get::<Mesh3d>(entity).unwrap().0, mesh);
                assert_eq!(
                    app.world()
                        .get::<MeshMaterial3d<StandardMaterial>>(entity)
                        .unwrap()
                        .0,
                    material
                );
            }
        }
        assert!(app.world().get_entity(entity).is_err());
        app.world_mut().despawn(player);
        let expired = spawn(&mut app, item, 1);
        app.update();
        assert_eq!(app.world().get::<Mesh3d>(expired).unwrap().0, mesh);
        app.world_mut()
            .resource_mut::<Time>()
            .advance_by(std::time::Duration::from_secs(1));
        app.update();
        assert!(app.world().get_entity(expired).is_err());
        assert_eq!(
            app.world_mut().query::<&Mesh3d>().iter(app.world()).count(),
            0
        );
        assert_eq!(app.world().resource::<Assets<Mesh>>().len(), 1);
        assert_eq!(app.world().resource::<Assets<StandardMaterial>>().len(), 1);
    }
}