Skip to main content

voxel_framework/items/
drop_visuals.rs

1//! Optional, asset-free default presentation for collectible drops.
2
3use std::{collections::HashMap, marker::PhantomData};
4
5use bevy::camera::visibility::VisibilitySystems;
6use bevy::prelude::*;
7use bevy::transform::TransformSystems;
8
9use super::{DroppedItem, ItemType};
10
11/// Draws positioned drops as small, unlit cubes colored by [`ItemType::color`].
12///
13/// Add after `DefaultPlugins`, alongside [`super::DropsPlugin`]. This plugin
14/// requires `Assets<Mesh>` and `Assets<StandardMaterial>`; it does not install
15/// gameplay, cameras, or lighting. It is not included in convenience bundles.
16///
17/// Cubes are 0.25 world units wide, sharing one mesh and one material per item
18/// variant. Render components live on the drop itself, so pickup and expiration
19/// also remove its visual. Drops with an existing `Mesh3d` or
20/// `MeshMaterial3d<StandardMaterial>` are left untouched. To own all presentation,
21/// omit this plugin. Drop transforms and quantities are never changed here.
22///
23/// Optional idle motion (spin and bob) is configured through
24/// [`DropVisualConfig`]. With motion enabled the cube lives on a child entity
25/// marked [`DropVisual`] instead of on the drop, and only that child moves.
26///
27/// Colors are sampled on first use; changing a rendered drop's item identity or
28/// dynamically recoloring the palette is not supported by this default.
29///
30/// ```no_run
31/// use bevy::prelude::*;
32/// use voxel_framework::prelude::*;
33/// App::new()
34///     .add_plugins(DefaultPlugins)
35///     .add_plugins((MiningPlugin, DropsPlugin::<DefaultItem>::new(), DropVisualPlugin::<DefaultItem>::new()));
36/// ```
37pub struct DropVisualPlugin<I: ItemType> {
38    _marker: PhantomData<I>,
39}
40
41impl<I: ItemType> DropVisualPlugin<I> {
42    /// Creates the optional default drop renderer.
43    pub fn new() -> Self {
44        Self {
45            _marker: PhantomData,
46        }
47    }
48}
49
50impl<I: ItemType> Default for DropVisualPlugin<I> {
51    fn default() -> Self {
52        Self::new()
53    }
54}
55
56/// Idle motion for the default drop visuals: a slow spin and a bob.
57///
58/// The default is no motion, which keeps the visual on the drop entity itself.
59/// With any motion enabled, a drop's cube is spawned as a **child** entity
60/// marked [`DropVisual`] and only that child's local transform is animated, so
61/// the drop's own `Transform` (its logical position, used by attraction and
62/// pickup) is never touched.
63///
64/// [`DropVisualPlugin`] initializes this resource. Insert your own value to
65/// enable motion:
66///
67/// ```no_run
68/// use bevy::prelude::*;
69/// use voxel_framework::prelude::*;
70/// App::new()
71///     .add_plugins(DefaultPlugins)
72///     .add_plugins((DropsPlugin::<DefaultItem>::new(), DropVisualPlugin::<DefaultItem>::new()))
73///     .insert_resource(DropVisualConfig {
74///         spin_rad_per_sec: 1.5,
75///         bob_amplitude: 0.05,
76///         bob_period: 2.0,
77///     });
78/// ```
79///
80/// The values are read every frame, so they can be changed while drops exist.
81/// Whether a drop gets a child visual is decided once, when its visual is
82/// first attached.
83#[derive(Resource, Debug, Clone, Copy, PartialEq, Default)]
84pub struct DropVisualConfig {
85    /// Spin around the drop's local Y axis, in radians per second. `0.0`
86    /// disables spinning.
87    pub spin_rad_per_sec: f32,
88    /// Peak offset of the bob along the drop's local Y axis, in world units.
89    /// `0.0` disables bobbing.
90    pub bob_amplitude: f32,
91    /// Seconds for one full up-and-down cycle. Bobbing needs a positive,
92    /// finite period.
93    pub bob_period: f32,
94}
95
96impl DropVisualConfig {
97    /// `true` when the configuration produces any motion.
98    pub fn is_animated(&self) -> bool {
99        self.spins() || self.bobs()
100    }
101
102    fn spins(&self) -> bool {
103        self.spin_rad_per_sec.is_finite() && self.spin_rad_per_sec != 0.0
104    }
105
106    fn bobs(&self) -> bool {
107        self.bob_amplitude.is_finite()
108            && self.bob_amplitude != 0.0
109            && self.bob_period.is_finite()
110            && self.bob_period > 0.0
111    }
112}
113
114/// Marks the child entity that carries an animated drop's default visual.
115///
116/// Present only when [`DropVisualConfig`] had motion enabled when the visual
117/// was attached. The child is despawned together with its drop.
118#[derive(Component, Debug, Clone, Copy, PartialEq)]
119pub struct DropVisual {
120    /// Per-drop offset, in seconds, so that drops do not move in unison.
121    pub phase_secs: f32,
122}
123
124/// Put on a drop whose default visual lives on a [`DropVisual`] child.
125#[derive(Component)]
126struct HasDropVisualChild;
127
128impl<I: ItemType> Plugin for DropVisualPlugin<I> {
129    fn build(&self, app: &mut App) {
130        app.init_resource::<DropVisualConfig>();
131        app.insert_resource(DropVisualAssets::<I> {
132            mesh: None,
133            materials: HashMap::new(),
134        })
135        .add_systems(
136            PostUpdate,
137            (attach_visuals::<I>, animate_drop_visuals)
138                .chain()
139                .before(TransformSystems::Propagate)
140                .before(VisibilitySystems::VisibilityPropagate)
141                .before(VisibilitySystems::CalculateBounds),
142        );
143    }
144}
145
146#[derive(Resource)]
147struct DropVisualAssets<I: ItemType> {
148    mesh: Option<Handle<Mesh>>,
149    materials: HashMap<I, Handle<StandardMaterial>>,
150}
151
152fn attach_visuals<I: ItemType>(
153    mut commands: Commands,
154    drops: Query<
155        (Entity, &DroppedItem<I>),
156        (
157            With<Transform>,
158            Without<Mesh3d>,
159            Without<MeshMaterial3d<StandardMaterial>>,
160            Without<HasDropVisualChild>,
161        ),
162    >,
163    config: Res<DropVisualConfig>,
164    mut cache: ResMut<DropVisualAssets<I>>,
165    mut meshes: ResMut<Assets<Mesh>>,
166    mut materials: ResMut<Assets<StandardMaterial>>,
167) {
168    let animated = config.is_animated();
169    for (entity, drop) in &drops {
170        let mesh = cache
171            .mesh
172            .get_or_insert_with(|| meshes.add(Cuboid::new(0.25, 0.25, 0.25)))
173            .clone();
174        let material = cache
175            .materials
176            .entry(drop.item)
177            .or_insert_with(|| {
178                let [r, g, b, a] = drop.item.color();
179                materials.add(StandardMaterial {
180                    base_color: Color::srgba(r, g, b, a),
181                    unlit: true,
182                    alpha_mode: if a < 1.0 {
183                        AlphaMode::Blend
184                    } else {
185                        AlphaMode::Opaque
186                    },
187                    ..default()
188                })
189            })
190            .clone();
191        if animated {
192            // The cube goes on a child so its motion never touches the drop's
193            // own transform. Despawning the drop despawns the child with it.
194            commands
195                .entity(entity)
196                .insert(HasDropVisualChild)
197                .insert_if_new(Visibility::Inherited)
198                .with_child((
199                    DropVisual {
200                        phase_secs: phase_for(entity),
201                    },
202                    Mesh3d(mesh),
203                    MeshMaterial3d(material),
204                    Transform::IDENTITY,
205                ));
206        } else {
207            commands
208                .entity(entity)
209                .insert((Mesh3d(mesh), MeshMaterial3d(material)))
210                .insert_if_new(Visibility::Inherited);
211        }
212    }
213}
214
215/// A stable, per-entity offset in seconds, so drops spawned together do not
216/// spin and bob in unison.
217fn phase_for(entity: Entity) -> f32 {
218    // Golden-ratio spacing spreads consecutive indices evenly over [0, 8).
219    (entity.index_u32() as f32 * 0.618_034).fract() * 8.0
220}
221
222/// Applies [`DropVisualConfig`] to every [`DropVisual`] child.
223///
224/// Only the child's local transform is written. With motion disabled the
225/// children return to rest.
226fn animate_drop_visuals(
227    time: Res<Time>,
228    config: Res<DropVisualConfig>,
229    mut visuals: Query<(&DropVisual, &mut Transform)>,
230) {
231    for (visual, mut transform) in &mut visuals {
232        let t = time.elapsed_secs() + visual.phase_secs;
233        let rotation = if config.spins() {
234            Quat::from_rotation_y(config.spin_rad_per_sec * t)
235        } else {
236            Quat::IDENTITY
237        };
238        let offset = if config.bobs() {
239            config.bob_amplitude * (std::f32::consts::TAU * t / config.bob_period).sin()
240        } else {
241            0.0
242        };
243        let target = Transform {
244            translation: Vec3::new(0.0, offset, 0.0),
245            rotation,
246            scale: Vec3::ONE,
247        };
248        // Skip the write when nothing changes, so resting drops do not look
249        // modified to change detection every frame.
250        if *transform != target {
251            *transform = target;
252        }
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use crate::items::{
260        ContainerComponent, DefaultItem, DropTable, DropsPlugin, ItemCollector, ItemPickedUp,
261        PrimaryContainer,
262    };
263    use crate::world::VoxelBroken;
264    use bevy::camera::visibility::VisibilityPlugin;
265    use bevy::transform::TransformPlugin;
266
267    fn app(visuals: bool) -> App {
268        let mut app = App::new();
269        app.init_resource::<Time>()
270            .init_resource::<Assets<Mesh>>()
271            .init_resource::<Assets<StandardMaterial>>()
272            .add_message::<VoxelBroken>()
273            .add_plugins((
274                TransformPlugin,
275                VisibilityPlugin,
276                DropsPlugin::<DefaultItem>::new(),
277            ));
278        if visuals {
279            app.add_plugins(DropVisualPlugin::<DefaultItem>::new());
280        }
281        app
282    }
283
284    fn spawn(app: &mut App, item: DefaultItem, count: u32) -> Entity {
285        app.world_mut()
286            .spawn((
287                DroppedItem {
288                    item,
289                    count,
290                    velocity: Vec3::ZERO,
291                    lifetime: 1.0,
292                },
293                Transform::from_xyz(2.0, 0.0, 0.0),
294            ))
295            .id()
296    }
297
298    fn animated() -> DropVisualConfig {
299        DropVisualConfig {
300            spin_rad_per_sec: 2.0,
301            bob_amplitude: 0.1,
302            bob_period: 4.0,
303        }
304    }
305
306    fn visual_children(app: &mut App, drop: Entity) -> Vec<Entity> {
307        let world = app.world_mut();
308        let mut query = world.query::<(Entity, &ChildOf, &DropVisual)>();
309        query
310            .iter(world)
311            .filter(|(_, parent, _)| parent.parent() == drop)
312            .map(|(entity, _, _)| entity)
313            .collect()
314    }
315
316    fn advance(app: &mut App, secs: f32) {
317        app.world_mut()
318            .resource_mut::<Time>()
319            .advance_by(std::time::Duration::from_secs_f32(secs));
320        app.update();
321    }
322
323    #[test]
324    fn config_reports_motion_only_for_usable_values() {
325        assert!(!DropVisualConfig::default().is_animated());
326        assert!(animated().is_animated());
327        assert!(
328            DropVisualConfig {
329                spin_rad_per_sec: 1.0,
330                ..default()
331            }
332            .is_animated()
333        );
334        // A bob without a period, or with broken numbers, is no motion.
335        assert!(
336            !DropVisualConfig {
337                bob_amplitude: 0.1,
338                ..default()
339            }
340            .is_animated()
341        );
342        assert!(
343            !DropVisualConfig {
344                spin_rad_per_sec: f32::NAN,
345                bob_amplitude: 0.1,
346                bob_period: -1.0,
347            }
348            .is_animated()
349        );
350    }
351
352    #[test]
353    fn default_config_keeps_the_visual_on_the_drop_itself() {
354        let mut app = app(true);
355        let drop = spawn(&mut app, DefaultItem::RockFragment, 1);
356        app.update();
357        advance(&mut app, 0.5);
358
359        assert!(app.world().get::<Mesh3d>(drop).is_some());
360        assert!(visual_children(&mut app, drop).is_empty());
361        assert_eq!(
362            app.world().get::<Transform>(drop).unwrap(),
363            &Transform::from_xyz(2.0, 0.0, 0.0)
364        );
365    }
366
367    #[test]
368    fn plugin_keeps_a_config_inserted_before_it() {
369        let mut app = App::new();
370        app.insert_resource(animated());
371        app.add_plugins(DropVisualPlugin::<DefaultItem>::new());
372        assert_eq!(*app.world().resource::<DropVisualConfig>(), animated());
373    }
374
375    #[test]
376    fn idle_motion_animates_a_child_and_never_the_drop() {
377        let mut app = app(true);
378        app.insert_resource(animated());
379        let drop = spawn(&mut app, DefaultItem::RockFragment, 1);
380        let start = *app.world().get::<Transform>(drop).unwrap();
381        app.update();
382        app.update();
383
384        assert!(
385            app.world().get::<Mesh3d>(drop).is_none(),
386            "the mesh belongs to the child when motion is enabled"
387        );
388        let children = visual_children(&mut app, drop);
389        assert_eq!(children.len(), 1);
390        let child = children[0];
391        assert!(app.world().get::<Mesh3d>(child).is_some());
392        assert!(
393            app.world()
394                .get::<MeshMaterial3d<StandardMaterial>>(child)
395                .is_some()
396        );
397        assert!(app.world().get::<InheritedVisibility>(child).unwrap().get());
398
399        let before = *app.world().get::<Transform>(child).unwrap();
400        advance(&mut app, 0.7);
401        let after = *app.world().get::<Transform>(child).unwrap();
402        assert_ne!(after.rotation, before.rotation, "the child spins");
403        assert_ne!(after.translation.y, before.translation.y, "the child bobs");
404        assert!(after.translation.y.abs() <= 0.1 + 1e-5);
405        assert_eq!(after.translation.x, 0.0);
406        assert_eq!(after.translation.z, 0.0);
407
408        // More frames never add a second child and never move the drop.
409        advance(&mut app, 0.1);
410        assert_eq!(visual_children(&mut app, drop).len(), 1);
411        assert_eq!(*app.world().get::<Transform>(drop).unwrap(), start);
412        // The rendered position follows the drop plus the bob offset.
413        let rendered = app.world().get::<GlobalTransform>(child).unwrap();
414        assert!((rendered.translation().x - start.translation.x).abs() < 1e-5);
415    }
416
417    #[test]
418    fn idle_motion_shares_assets_and_respects_custom_presentation() {
419        let mut app = app(true);
420        app.insert_resource(animated());
421        let first = spawn(&mut app, DefaultItem::RockFragment, 1);
422        let second = spawn(&mut app, DefaultItem::RockFragment, 1);
423        let custom = spawn(&mut app, DefaultItem::Crystal, 1);
424        let mesh = app
425            .world_mut()
426            .resource_mut::<Assets<Mesh>>()
427            .add(Cuboid::new(1.0, 1.0, 1.0));
428        app.world_mut()
429            .entity_mut(custom)
430            .insert(Mesh3d(mesh.clone()));
431        app.update();
432        app.update();
433
434        let a = visual_children(&mut app, first)[0];
435        let b = visual_children(&mut app, second)[0];
436        assert_eq!(
437            app.world().get::<Mesh3d>(a).unwrap().0,
438            app.world().get::<Mesh3d>(b).unwrap().0
439        );
440        assert_eq!(
441            app.world()
442                .get::<MeshMaterial3d<StandardMaterial>>(a)
443                .unwrap()
444                .0,
445            app.world()
446                .get::<MeshMaterial3d<StandardMaterial>>(b)
447                .unwrap()
448                .0
449        );
450        assert_ne!(
451            app.world().get::<DropVisual>(a).unwrap().phase_secs,
452            app.world().get::<DropVisual>(b).unwrap().phase_secs,
453            "drops should not move in unison"
454        );
455        // A drop with its own mesh is left alone: no child, mesh untouched.
456        assert!(visual_children(&mut app, custom).is_empty());
457        assert_eq!(app.world().get::<Mesh3d>(custom).unwrap().0, mesh);
458    }
459
460    #[test]
461    fn animated_visual_disappears_with_its_drop() {
462        let mut app = app(true);
463        app.insert_resource(animated());
464        let drop = spawn(&mut app, DefaultItem::RockFragment, 1);
465        app.update();
466        app.update();
467        assert_eq!(visual_children(&mut app, drop).len(), 1);
468
469        // The drop's lifetime is one second.
470        advance(&mut app, 1.0);
471
472        assert!(app.world().get_entity(drop).is_err());
473        assert_eq!(
474            app.world_mut().query::<&Mesh3d>().iter(app.world()).count(),
475            0
476        );
477    }
478
479    #[test]
480    fn disabling_motion_returns_existing_children_to_rest() {
481        let mut app = app(true);
482        app.insert_resource(animated());
483        let drop = spawn(&mut app, DefaultItem::RockFragment, 1);
484        // Long-lived so it survives the time steps below.
485        app.world_mut()
486            .get_mut::<DroppedItem<DefaultItem>>(drop)
487            .unwrap()
488            .lifetime = 60.0;
489        app.update();
490        app.update();
491        advance(&mut app, 0.7);
492        let child = visual_children(&mut app, drop)[0];
493        assert_ne!(
494            *app.world().get::<Transform>(child).unwrap(),
495            Transform::IDENTITY
496        );
497
498        app.insert_resource(DropVisualConfig::default());
499        advance(&mut app, 0.1);
500
501        assert_eq!(
502            *app.world().get::<Transform>(child).unwrap(),
503            Transform::IDENTITY
504        );
505    }
506
507    #[test]
508    fn mapped_drop_gets_visible_shared_assets_in_spawn_frame() {
509        let mut app = app(true);
510        app.world_mut()
511            .resource_mut::<DropTable<DefaultItem>>()
512            .register(1, DefaultItem::RockFragment, 1, 1);
513        let position = Vec3::new(2.5, 3.5, 4.5);
514        app.world_mut().write_message(VoxelBroken {
515            chunk_coord: IVec3::ZERO,
516            local: (2, 3, 4),
517            world_pos: position,
518            voxel_byte: 1,
519        });
520        app.update();
521        let world = app.world_mut();
522        let mut query = world.query_filtered::<Entity, With<DroppedItem<DefaultItem>>>();
523        let entity = query.single(world).unwrap();
524        let mesh = world
525            .get::<Mesh3d>(entity)
526            .expect("mapped drop must have a mesh")
527            .0
528            .clone();
529        let material = world
530            .get::<MeshMaterial3d<StandardMaterial>>(entity)
531            .unwrap()
532            .0
533            .clone();
534        assert_eq!(
535            world.get::<GlobalTransform>(entity).unwrap().translation(),
536            position
537        );
538        assert_eq!(
539            *world.get::<Visibility>(entity).unwrap(),
540            Visibility::Inherited
541        );
542        assert!(world.get::<InheritedVisibility>(entity).unwrap().get());
543        let assets = world.resource::<Assets<StandardMaterial>>();
544        let mat = assets.get(&material).unwrap();
545        assert!(mat.unlit);
546        let [r, g, b, a] = DefaultItem::RockFragment.color();
547        assert_eq!(mat.base_color, Color::srgba(r, g, b, a));
548        assert!(world.resource::<Assets<Mesh>>().get(&mesh).is_some());
549        let second = spawn(&mut app, DefaultItem::RockFragment, 4);
550        let other = spawn(&mut app, DefaultItem::Crystal, 1);
551        app.update();
552        assert_eq!(app.world().get::<Mesh3d>(second).unwrap().0, mesh);
553        assert_eq!(
554            app.world()
555                .get::<MeshMaterial3d<StandardMaterial>>(second)
556                .unwrap()
557                .0,
558            material
559        );
560        assert_eq!(app.world().get::<Mesh3d>(other).unwrap().0, mesh);
561        assert_ne!(
562            app.world()
563                .get::<MeshMaterial3d<StandardMaterial>>(other)
564                .unwrap()
565                .0,
566            material
567        );
568        assert_eq!(app.world().resource::<Assets<Mesh>>().len(), 1);
569        assert_eq!(app.world().resource::<Assets<StandardMaterial>>().len(), 2);
570    }
571
572    #[test]
573    fn visuals_are_opt_in_and_preserve_custom_components_and_late_transforms() {
574        let mut app = app(false);
575        let ordinary = spawn(&mut app, DefaultItem::RockFragment, 1);
576        app.update();
577        assert!(app.world().get::<Mesh3d>(ordinary).is_none());
578        app.add_plugins(DropVisualPlugin::<DefaultItem>::new());
579        let custom = spawn(&mut app, DefaultItem::Crystal, 1);
580        let mesh = app
581            .world_mut()
582            .resource_mut::<Assets<Mesh>>()
583            .add(Cuboid::new(1.0, 1.0, 1.0));
584        app.world_mut()
585            .entity_mut(custom)
586            .insert(Mesh3d(mesh.clone()));
587        let custom_material = spawn(&mut app, DefaultItem::Crystal, 1);
588        let material = app
589            .world_mut()
590            .resource_mut::<Assets<StandardMaterial>>()
591            .add(StandardMaterial::default());
592        app.world_mut()
593            .entity_mut(custom_material)
594            .insert(MeshMaterial3d(material.clone()));
595        let late = app
596            .world_mut()
597            .spawn(DroppedItem {
598                item: DefaultItem::Crystal,
599                count: 1,
600                velocity: Vec3::ZERO,
601                lifetime: 1.0,
602            })
603            .id();
604        app.update();
605        assert!(app.world().get::<Mesh3d>(ordinary).is_some());
606        assert_eq!(app.world().get::<Mesh3d>(custom).unwrap().0, mesh);
607        assert!(
608            app.world()
609                .get::<MeshMaterial3d<StandardMaterial>>(custom)
610                .is_none()
611        );
612        assert_eq!(
613            app.world()
614                .get::<MeshMaterial3d<StandardMaterial>>(custom_material)
615                .unwrap()
616                .0,
617            material
618        );
619        assert!(app.world().get::<Mesh3d>(custom_material).is_none());
620        assert!(app.world().get::<Mesh3d>(late).is_none());
621        app.world_mut()
622            .entity_mut(late)
623            .insert(Transform::default());
624        app.update();
625        assert!(app.world().get::<Mesh3d>(late).is_some());
626    }
627
628    #[test]
629    fn moving_drop_propagates_position_and_keeps_runtime_visual_replacement() {
630        let mut app = app(true);
631        let entity = spawn(&mut app, DefaultItem::RockFragment, 1);
632        app.world_mut()
633            .spawn((ItemCollector, Transform::from_xyz(50.0, 0.0, 0.0)));
634        app.world_mut()
635            .get_mut::<DroppedItem<DefaultItem>>(entity)
636            .unwrap()
637            .velocity = Vec3::new(1.0, 2.0, 3.0);
638        app.update();
639        let initial = app
640            .world()
641            .get::<GlobalTransform>(entity)
642            .unwrap()
643            .translation();
644        let default_mesh = app.world().get::<Mesh3d>(entity).unwrap().0.clone();
645        app.world_mut()
646            .resource_mut::<Time>()
647            .advance_by(std::time::Duration::from_millis(100));
648        app.update();
649        let moved = app.world().get::<Transform>(entity).unwrap().translation;
650        assert_ne!(moved, initial, "DropsPlugin must actually move the drop");
651        assert_eq!(
652            app.world()
653                .get::<GlobalTransform>(entity)
654                .unwrap()
655                .translation(),
656            moved
657        );
658        assert_eq!(app.world().get::<Mesh3d>(entity).unwrap().0, default_mesh);
659
660        let mesh = app
661            .world_mut()
662            .resource_mut::<Assets<Mesh>>()
663            .add(Sphere::new(0.5));
664        let material = app
665            .world_mut()
666            .resource_mut::<Assets<StandardMaterial>>()
667            .add(StandardMaterial {
668                base_color: Color::srgb(0.1, 0.8, 0.2),
669                ..default()
670            });
671        app.world_mut().entity_mut(entity).insert((
672            Mesh3d(mesh.clone()),
673            MeshMaterial3d(material.clone()),
674            Visibility::Hidden,
675            Transform::from_xyz(-4.0, 5.0, 6.0),
676        ));
677        app.world_mut()
678            .resource_mut::<Time>()
679            .advance_by(std::time::Duration::ZERO);
680        app.update();
681        assert_eq!(
682            app.world()
683                .get::<GlobalTransform>(entity)
684                .unwrap()
685                .translation(),
686            Vec3::new(-4.0, 5.0, 6.0)
687        );
688        assert_eq!(app.world().get::<Mesh3d>(entity).unwrap().0, mesh);
689        assert_eq!(
690            app.world()
691                .get::<MeshMaterial3d<StandardMaterial>>(entity)
692                .unwrap()
693                .0,
694            material
695        );
696        assert_eq!(
697            *app.world().get::<Visibility>(entity).unwrap(),
698            Visibility::Hidden
699        );
700    }
701
702    #[test]
703    fn visible_remainder_survives_partial_pickup_and_cleans_up_on_collection_or_expiry() {
704        let mut app = app(true);
705        let item = DefaultItem::RockFragment;
706        let entity = spawn(&mut app, item, 3);
707        app.update();
708        let mesh = app.world().get::<Mesh3d>(entity).unwrap().0.clone();
709        let material = app
710            .world()
711            .get::<MeshMaterial3d<StandardMaterial>>(entity)
712            .unwrap()
713            .0
714            .clone();
715        let mut inventory = ContainerComponent::<DefaultItem>::new(1);
716        inventory.0.add(item, u32::MAX - 1);
717        let player = app
718            .world_mut()
719            .spawn((
720                ItemCollector,
721                PrimaryContainer,
722                inventory,
723                Transform::from_xyz(2.0, 0.0, 0.0),
724            ))
725            .id();
726        for expected in [1, 0, 2] {
727            if expected == 2 {
728                app.world_mut()
729                    .get_mut::<ContainerComponent<DefaultItem>>(player)
730                    .unwrap()
731                    .0
732                    .remove(item, 2);
733            }
734            app.update();
735            let pickups: Vec<_> = app
736                .world_mut()
737                .resource_mut::<Messages<ItemPickedUp<DefaultItem>>>()
738                .drain()
739                .collect();
740            assert_eq!(pickups.iter().map(|p| p.count).sum::<u32>(), expected);
741            if expected != 2 {
742                assert_eq!(
743                    app.world()
744                        .get::<DroppedItem<DefaultItem>>(entity)
745                        .unwrap()
746                        .count,
747                    2
748                );
749                assert_eq!(app.world().get::<Mesh3d>(entity).unwrap().0, mesh);
750                assert_eq!(
751                    app.world()
752                        .get::<MeshMaterial3d<StandardMaterial>>(entity)
753                        .unwrap()
754                        .0,
755                    material
756                );
757            }
758        }
759        assert!(app.world().get_entity(entity).is_err());
760        app.world_mut().despawn(player);
761        let expired = spawn(&mut app, item, 1);
762        app.update();
763        assert_eq!(app.world().get::<Mesh3d>(expired).unwrap().0, mesh);
764        app.world_mut()
765            .resource_mut::<Time>()
766            .advance_by(std::time::Duration::from_secs(1));
767        app.update();
768        assert!(app.world().get_entity(expired).is_err());
769        assert_eq!(
770            app.world_mut().query::<&Mesh3d>().iter(app.world()).count(),
771            0
772        );
773        assert_eq!(app.world().resource::<Assets<Mesh>>().len(), 1);
774        assert_eq!(app.world().resource::<Assets<StandardMaterial>>().len(), 1);
775    }
776}