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
use crate::prelude::*;

#[derive(HasSchema, Default, Debug, Clone)]
#[type_data(metadata_asset("stomp_boots"))]
#[repr(C)]
pub struct StompBootsMeta {
    pub map_icon: Handle<Atlas>,
    pub player_decoration: Handle<Atlas>,

    pub body_size: Vec2,
    pub grab_offset: Vec2,
}

pub fn game_plugin(game: &mut Game) {
    StompBootsMeta::register_schema();
    game.init_shared_resource::<AssetServer>();
}

pub fn session_plugin(session: &mut Session) {
    session
        .stages
        .add_system_to_stage(CoreStage::PreUpdate, hydrate)
        .add_system_to_stage(CoreStage::PostUpdate, update)
        .add_system_to_stage(CoreStage::PostUpdate, update_wearer);
}

/// Marker component added to things ( presumably players, but not necessarily! ) that are wearing
/// stomp boots
#[derive(Debug, Clone, Copy, Default, HasSchema)]
pub struct WearingStompBoots {
    stomp_boots: Entity,
}

#[derive(Copy, Clone, Debug, HasSchema, Default)]
pub struct StompBoots;

#[derive(Copy, Clone, Debug, HasSchema, Default)]
pub struct WornStompBoots;

fn hydrate(
    game_meta: Root<GameMeta>,
    mut entities: ResMutInit<Entities>,
    mut hydrated: CompMut<MapElementHydrated>,
    mut element_handles: CompMut<ElementHandle>,
    assets: Res<AssetServer>,
    mut stomp_boots: CompMut<StompBoots>,
    mut atlas_sprites: CompMut<AtlasSprite>,
    mut bodies: CompMut<KinematicBody>,
    mut transforms: CompMut<Transform>,
    mut items: CompMut<Item>,
    mut item_throws: CompMut<ItemThrow>,
    mut item_grabs: CompMut<ItemGrab>,
    mut respawn_points: CompMut<DehydrateOutOfBounds>,
    mut spawner_manager: SpawnerManager,
) {
    let mut not_hydrated_bitset = hydrated.bitset().clone();
    not_hydrated_bitset.bit_not();
    not_hydrated_bitset.bit_and(element_handles.bitset());

    let spawner_entities = entities
        .iter_with_bitset(&not_hydrated_bitset)
        .collect::<Vec<_>>();

    for spawner_ent in spawner_entities {
        let transform = *transforms.get(spawner_ent).unwrap();
        let element_handle = *element_handles.get(spawner_ent).unwrap();
        let element_meta = assets.get(element_handle.0);

        if let Ok(StompBootsMeta {
            grab_offset,
            body_size,
            map_icon,
            ..
        }) = assets.get(element_meta.data).try_cast_ref()
        {
            hydrated.insert(spawner_ent, MapElementHydrated);

            let entity = entities.create();
            items.insert(entity, Item);
            item_throws.insert(entity, ItemThrow::strength(0.0));
            item_grabs.insert(
                entity,
                ItemGrab {
                    fin_anim: "grab_2".into(),
                    sync_animation: false,
                    grab_offset: *grab_offset,
                },
            );
            stomp_boots.insert(entity, StompBoots);
            atlas_sprites.insert(entity, AtlasSprite::new(*map_icon));
            respawn_points.insert(entity, DehydrateOutOfBounds(spawner_ent));
            transforms.insert(entity, transform);
            element_handles.insert(entity, element_handle);
            hydrated.insert(entity, MapElementHydrated);
            bodies.insert(
                entity,
                KinematicBody {
                    shape: ColliderShape::Rectangle { size: *body_size },
                    has_mass: true,
                    has_friction: true,
                    gravity: game_meta.core.physics.gravity,
                    ..default()
                },
            );
            spawner_manager.create_spawner(spawner_ent, vec![entity])
        }
    }
}

fn update(
    entities: Res<Entities>,
    element_handles: Comp<ElementHandle>,
    assets: Res<AssetServer>,
    mut stomp_boots: CompMut<StompBoots>,
    items_used: Comp<ItemUsed>,
    player_inventories: PlayerInventories,
    mut inventoris: CompMut<Inventory>,
    mut commands: Commands,
    spawners: Comp<DehydrateOutOfBounds>,
) {
    for (entity, (_stomp_boots, element_handle, spawner)) in
        entities.iter_with((&mut stomp_boots, &element_handles, &spawners))
    {
        let element_meta = assets.get(element_handle.0);

        let asset = assets.get(element_meta.data);
        let Ok(StompBootsMeta {
            player_decoration, ..
        }) = asset.try_cast_ref()
        else {
            unreachable!();
        };

        // If the item is being held
        if let Some(Inv { player, .. }) = player_inventories.find_item(entity) {
            // If the item is being used
            let is_item_used = items_used.get(entity).is_some();
            let player_decoration = *player_decoration;

            if is_item_used {
                inventoris.insert(player, Inventory(None));
                let spawner = spawner.clone();

                commands.add(
                    move |mut entities: ResMutInit<Entities>,
                          mut sprites: CompMut<AtlasSprite>,
                          mut attachments: CompMut<Attachment>,
                          mut transforms: CompMut<Transform>,
                          mut worn_stomp_boots: CompMut<WornStompBoots>,
                          mut respawn_points: CompMut<DehydrateOutOfBounds>,
                          mut wearing_stomp_boots: CompMut<WearingStompBoots>| {
                        entities.kill(entity);

                        let attachment_ent = entities.create();
                        let attachment = Attachment {
                            entity: player,
                            sync_color: false,
                            offset: Vec3::ZERO,
                            sync_animation: true,
                            sync_flip: true,
                            offset_inherits_rotation: true,
                        };

                        worn_stomp_boots.insert(attachment_ent, WornStompBoots);
                        attachments.insert(attachment_ent, attachment);
                        sprites.insert(attachment_ent, AtlasSprite::new(player_decoration));
                        transforms.insert(attachment_ent, Transform::default());
                        respawn_points.insert(attachment_ent, spawner.clone());
                        wearing_stomp_boots.insert(
                            player,
                            WearingStompBoots {
                                stomp_boots: attachment_ent,
                            },
                        );
                    },
                );
            }
        }
    }
}

fn update_wearer(
    entities: Res<Entities>,
    mut commands: Commands,
    wearing_stomp_boots: CompMut<WearingStompBoots>,
    mut worn_stomp_boots: CompMut<WornStompBoots>,
    player_indexes: Comp<PlayerIdx>,
    collision_world: CollisionWorld,
    kinematic_bodies: Comp<KinematicBody>,
    killed_players: Comp<PlayerKilled>,
    mut hydrated: CompMut<MapElementHydrated>,
    spawners: Comp<DehydrateOutOfBounds>,
    transforms: Comp<Transform>,
) {
    for (entity, WearingStompBoots { stomp_boots }) in entities.iter_with(&wearing_stomp_boots) {
        if killed_players.get(entity).is_some() {
            // Respawn the boots worn by the player who was just killed
            if let Some(spawner) = spawners.get(*stomp_boots) {
                if worn_stomp_boots.get(*stomp_boots).is_some() {
                    worn_stomp_boots.remove(*stomp_boots);
                    hydrated.remove(**spawner);
                }
            }
            // We don't need to proceed because the player is dead
            continue;
        }

        let kinematic_body = kinematic_bodies.get(entity).unwrap();
        if kinematic_body.velocity.y > 0.
            || kinematic_body.is_on_ground
            || kinematic_body.is_on_platform
        {
            continue;
        }
        collision_world
            .actor_collisions_filtered(entity, |e| player_indexes.contains(e))
            .into_iter()
            .for_each(|player| {
                let wearer_transform = transforms
                    .get(entity)
                    .expect("stomp boots wearer should have Transform component");
                let player_transform = transforms.get(player).unwrap();
                let player_kinematic_body = kinematic_bodies.get(player).unwrap();
                if kinematic_body.bounding_box(*wearer_transform).bottom()
                    > player_kinematic_body
                        .bounding_box(*player_transform)
                        .center()
                        .y
                {
                    commands.add(PlayerCommand::kill(
                        player,
                        Some(player_transform.translation.xy()),
                    ))
                }
            });
    }
}