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
use bevy::prelude::*;
use de_core::{
    cleanup::DespawnOnGameExit, gamestate::GameState, gconfig::GameConfig,
    objects::ObjectTypeComponent, schedule::InputSchedule, state::AppState,
};
use de_spawner::{DraftAllowed, DraftBundle, SpawnLocalActiveEvent};
use de_types::objects::{BuildingType, ObjectType};

use crate::mouse::{Pointer, PointerSet};

pub(crate) struct DraftPlugin;

impl Plugin for DraftPlugin {
    fn build(&self, app: &mut App) {
        app.add_event::<SpawnDraftsEvent>()
            .add_event::<NewDraftEvent>()
            .add_event::<DiscardDraftsEvent>()
            .add_systems(
                InputSchedule,
                (
                    (
                        spawn
                            .run_if(on_event::<SpawnDraftsEvent>())
                            .in_set(DraftSet::Spawn),
                        new_drafts.in_set(DraftSet::New),
                        discard_drafts
                            .run_if(on_event::<DiscardDraftsEvent>())
                            .in_set(DraftSet::Discard),
                    )
                        .run_if(in_state(AppState::InGame)),
                    move_drafts
                        .run_if(in_state(GameState::Playing))
                        .after(PointerSet::Update),
                ),
            );
    }
}

#[derive(Copy, Clone, Hash, Debug, PartialEq, Eq, SystemSet)]
pub(crate) enum DraftSet {
    Spawn,
    New,
    Discard,
}

#[derive(Event)]
pub(crate) struct SpawnDraftsEvent;

#[derive(Event)]
pub(crate) struct NewDraftEvent {
    point: Vec3,
    building_type: BuildingType,
}

#[derive(Event)]
pub(crate) struct DiscardDraftsEvent;

impl NewDraftEvent {
    pub(crate) fn new(point: Vec3, building_type: BuildingType) -> Self {
        Self {
            point,
            building_type,
        }
    }

    fn point(&self) -> Vec3 {
        self.point
    }

    fn building_type(&self) -> BuildingType {
        self.building_type
    }
}

fn spawn(
    mut commands: Commands,
    game_config: Res<GameConfig>,
    drafts: Query<(Entity, &Transform, &ObjectTypeComponent, &DraftAllowed)>,
    mut spawn_active_events: EventWriter<SpawnLocalActiveEvent>,
) {
    for (entity, &transform, &object_type, draft) in drafts.iter() {
        if draft.allowed() {
            commands.entity(entity).despawn_recursive();
            let ObjectType::Active(object_type) = *object_type else {
                panic!("Cannot place draft of an inactive object.");
            };

            spawn_active_events.send(SpawnLocalActiveEvent::stationary(
                object_type,
                transform,
                game_config.locals().playable(),
            ));
        }
    }
}

fn new_drafts(
    mut commands: Commands,
    mut events: EventReader<NewDraftEvent>,
    drafts: Query<Entity, With<DraftAllowed>>,
) {
    let event = match events.read().last() {
        Some(event) => event,
        None => return,
    };

    for entity in drafts.iter() {
        commands.entity(entity).despawn_recursive();
    }

    commands.spawn((
        DraftBundle::new(
            event.building_type(),
            Transform {
                translation: event.point(),
                ..Default::default()
            },
        ),
        DespawnOnGameExit,
    ));
}

fn discard_drafts(mut commands: Commands, drafts: Query<Entity, With<DraftAllowed>>) {
    for entity in drafts.iter() {
        commands.entity(entity).despawn_recursive();
    }
}

fn move_drafts(pointer: Res<Pointer>, mut drafts: Query<&mut Transform, With<DraftAllowed>>) {
    let pointer_changed = pointer.is_changed();

    let point = match pointer.terrain_point() {
        Some(point) => point,
        None => return,
    };

    for mut transform in drafts.iter_mut() {
        if transform.is_added() || pointer_changed {
            transform.translation = point;
        }
    }
}