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

#[derive(HasSchema, Default, Debug, Clone)]
#[type_data(metadata_asset("sproinger"))]
#[repr(C)]
/// This is a sproinger
pub struct SproingerMeta {
    pub atlas: Handle<Atlas>,
    pub sound: Handle<AudioSource>,
    pub sound_volume: f64,
    pub body_size: Vec2,
    pub spring_velocity: f32,
}

pub fn game_plugin(game: &mut Game) {
    SproingerMeta::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);
}

#[derive(Clone, Debug, HasSchema, Default)]
pub struct Sproinger {
    pub frame: u32,
    pub sproinging: bool,
}

fn hydrate(
    entities: Res<Entities>,
    mut hydrated: CompMut<MapElementHydrated>,
    element_handles: Comp<ElementHandle>,
    assets: Res<AssetServer>,
    mut sproingers: CompMut<Sproinger>,
    mut atlas_sprites: CompMut<AtlasSprite>,
    mut bodies: CompMut<KinematicBody>,
    mut nav_graph: ResMutInit<NavGraph>,
    transforms: Comp<Transform>,
    map: Res<LoadedMap>,
) {
    let mut not_hydrated_bitset = hydrated.bitset().clone();
    not_hydrated_bitset.bit_not();
    not_hydrated_bitset.bit_and(element_handles.bitset());

    let mut new_sproingers = Vec::new();
    for entity in entities.iter_with_bitset(&not_hydrated_bitset) {
        let element_handle = element_handles.get(entity).unwrap();
        let element_meta = assets.get(element_handle.0);

        if let Ok(SproingerMeta {
            atlas, body_size, ..
        }) = assets.get(element_meta.data).try_cast_ref()
        {
            new_sproingers.push(entity);
            hydrated.insert(entity, MapElementHydrated);
            atlas_sprites.insert(entity, AtlasSprite::new(*atlas));
            bodies.insert(
                entity,
                KinematicBody {
                    shape: ColliderShape::Rectangle { size: *body_size },
                    has_mass: false,
                    ..default()
                },
            );
            sproingers.insert(entity, sproinger::default());
        }
    }

    // Update the navigation graph with the new sproingers
    if !new_sproingers.is_empty() {
        let mut new_graph = nav_graph.as_ref().clone();

        for ent in new_sproingers {
            let pos = transforms.get(ent).unwrap().translation;
            let node = NavNode((pos.truncate() / map.tile_size).as_ivec2());
            let sproing_to = node.above().above().above().above().above().above();

            new_graph.add_edge(
                node,
                sproing_to,
                NavGraphEdge {
                    inputs: [PlayerControl::default()].into(),
                    distance: node.distance(&sproing_to),
                },
            );
        }
        **nav_graph = Arc::new(new_graph);
    }
}

fn update(
    entities: Res<Entities>,
    element_handles: Comp<ElementHandle>,
    assets: Res<AssetServer>,
    mut sproingers: CompMut<Sproinger>,
    mut atlas_sprites: CompMut<AtlasSprite>,
    mut bodies: CompMut<KinematicBody>,
    dynamic_bodies: Comp<DynamicBody>,
    mut collision_world: CollisionWorld,
    mut audio_center: ResMut<AudioCenter>,
) {
    for (entity, (sproinger, sprite)) in entities.iter_with((&mut sproingers, &mut atlas_sprites)) {
        let element_handle = element_handles.get(entity).unwrap();
        let element_meta = assets.get(element_handle.0);

        let asset = assets.get(element_meta.data);
        let Ok(SproingerMeta {
            sound,
            sound_volume,
            spring_velocity,
            ..
        }) = asset.try_cast_ref()
        else {
            unreachable!();
        };

        if sproinger.sproinging {
            match sproinger.frame {
                1 => sprite.index = 2,
                4 => sprite.index = 3,
                8 => sprite.index = 4,
                12 => sprite.index = 5,
                x if x >= 20 => {
                    sprite.index = 0;
                    sproinger.sproinging = false;
                    sproinger.frame = 0;
                }
                _ => (),
            }
            sproinger.frame += 1;
        }

        for collider_ent in collision_world.actor_collisions(entity) {
            if let Some(body) = bodies.get_mut(collider_ent) {
                let dynamic_body = dynamic_bodies.get(collider_ent);
                let is_dynamic = if let Some(dynamic_body) = dynamic_body {
                    dynamic_body.is_dynamic
                } else {
                    false
                };

                if !is_dynamic {
                    if body.velocity.y < *spring_velocity {
                        audio_center.play_sound(*sound, *sound_volume);
                        body.velocity.y = *spring_velocity;
                        sproinger.sproinging = true;
                    }
                } else {
                    let spring_velocity = *spring_velocity;

                    let _ = collision_world.mutate_rigidbody(
                        collider_ent,
                        |rb: &mut rapier::RigidBody| {
                            let mut vel = *rb.linvel();
                            if vel.y < spring_velocity {
                                vel.y = spring_velocity;
                                rb.set_linvel(vel, true);
                                audio_center.play_sound(*sound, *sound_volume);
                            }
                        },
                    );
                }
            }
        }
    }
}