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
/*
 * librePvZ: game logic implementation.
 * Copyright (c) 2022  Ruifeng Xie
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

//! Peashooter.

use bevy::prelude::*;
use bevy::sprite::Anchor;
use bevy_asset_loader::prelude::*;
use libre_pvz_animation::transform::SpriteBundle2D;
use libre_pvz_resources::cache_known_states;
use libre_pvz_resources::model::{
    MarkerRegistryExt, Model, ModelState, ModelSystem,
    CoolDown, StateTransitionEvent, TransitionTrigger,
};
use crate::core::kinematics::{Position, Velocity};
use crate::core::projectile::Projectile;
use crate::scene::loading::AssetState;

/// Peashooter plugin.
#[derive(Debug, Default, Copy, Clone)]
pub struct PeashooterPlugin;

impl Plugin for PeashooterPlugin {
    fn build(&self, app: &mut App) {
        app.register_marker::<Peashooter>("Peashooter")
            .register_marker::<PeashooterHead>("PeashooterHead")
            .add_loading_state(LoadingState::new(AssetState::AssetLoading)
                .continue_to_state(AssetState::AssetReady)
                .on_failure_continue_to_state(AssetState::LoadFailure)
                .load_collection::<PeashooterAssets>())
            .add_systems(OnEnter(AssetState::AssetReady), initialize_state_index_system)
            .add_systems(Update, peashooter_fire_system.run_if(in_state(AssetState::AssetReady)))
            .add_systems(Update, peashooter_force_shooting_system.run_if(in_state(AssetState::AssetReady))
                .before(ModelSystem::TransitionTrigger)
                .after(ModelSystem::CoolDownTicking));
    }
}

/// Assets for peashooters.
#[derive(Debug, AssetCollection, Resource)]
pub struct PeashooterAssets {
    #[asset(path = "Peashooter.model.bin")]
    pub(crate) model: Handle<Model>,
    #[asset(path = "ProjectilePea.png")]
    projectile_pea: Handle<Image>,
}

/// Marker for the full plant of peashooter.
#[derive(Default, Debug, Copy, Clone, Component)]
pub struct Peashooter;

/// Marker for the head of a peashooter.
#[derive(Default, Debug, Copy, Clone, Component)]
pub struct PeashooterHead;

cache_known_states! {
    idle,
    shooting_1,
    shooting_2,
}

const PEA_VELOCITY: f32 = 9.9 * 30.0;

fn initialize_state_index_system(
    assets: Res<PeashooterAssets>,
    models: Res<Assets<Model>>,
    mut commands: Commands,
) {
    let root = models.get(&assets.model).unwrap();
    let head = root.attachments[0].child_model.get(&models).unwrap();
    match StateIndex::cache(&head.states) {
        Ok(indices) => commands.insert_resource(indices),
        Err(err) => error!("state name mismatch: {err}"),
    }
}

/// Force the Peashooters to shoot bullet peas (for debugging purposes).
fn peashooter_force_shooting_system(
    mut head: Query<(Entity, &mut CoolDown, &ModelState), With<PeashooterHead>>,
    mut triggers: EventWriter<TransitionTrigger>,
    models: Res<Assets<Model>>,
    states: Res<StateIndex>,
) {
    for (entity, mut cool_down, state) in &mut head {
        if state.current_state != states.idle { continue; }
        if let Some(trigger) = state.trigger_if_ready(
            entity, &models, &mut cool_down, "shoot") {
            triggers.send(trigger);
        }
    }
}

/// Fire a pea every time we enter the `SHOOTING` state.
fn peashooter_fire_system(
    head: Query<(&ModelState, &GlobalTransform), With<PeashooterHead>>,
    mut transitions: EventReader<StateTransitionEvent>,
    assets: Res<PeashooterAssets>,
    states: Res<StateIndex>,
    mut commands: Commands,
) {
    for &StateTransitionEvent { target_entity, .. } in transitions.read() {
        let (state, trans) = head.get(target_entity).unwrap();
        // we want to keep that line aligned with other assignments
        #[allow(clippy::field_reassign_with_default)]
        if [states.shooting_1, states.shooting_2].contains(&state.current_state) {
            let trans = trans.translation();
            let x0 = trans.x + (20.0 + 40.0);
            let y0 = trans.y + (30.0 - 40.0);
            let p0 = Position(Vec3::new(x0, y0, 0.0));
            let vel = Velocity(Vec3::new(PEA_VELOCITY, 0.0, 0.0));
            let mut bundle = SpriteBundle2D::default();
            bundle.texture = assets.projectile_pea.clone();
            bundle.sprite.anchor = Anchor::TopLeft;
            bundle.transform.z_order = 100.0;
            commands.spawn((bundle, p0, vel, Projectile));
        }
    }
}