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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
use ahash::AHashMap;
use bevy::{
    prelude::*,
    tasks::{futures_lite::future, AsyncComputeTaskPool, Task},
};
use de_core::{
    gamestate::GameState,
    objects::MovableSolid,
    schedule::{PostMovement, PreMovement},
    state::AppState,
};
use de_types::{path::Path, projection::ToFlat};

use crate::{
    fplugin::{FinderRes, FinderSet, PathFinderUpdatedEvent},
    path::ScheduledPath,
    PathQueryProps, PathTarget,
};

const TARGET_TOLERANCE: f32 = 2.;

/// This plugin handles path finding requests and keeps scheduled paths
/// up-to-date.
pub struct PathingPlugin;

impl Plugin for PathingPlugin {
    fn build(&self, app: &mut App) {
        app.add_event::<UpdateEntityPathEvent>()
            .add_event::<PathFoundEvent>()
            .add_systems(OnEnter(AppState::InGame), setup)
            .add_systems(OnExit(AppState::InGame), cleanup)
            .add_systems(
                PreMovement,
                (
                    update_existing_paths
                        .run_if(on_event::<PathFinderUpdatedEvent>())
                        .in_set(PathingSet::UpdateExistingPaths)
                        .after(FinderSet::UpdateFinder),
                    update_requested_paths
                        .in_set(PathingSet::UpdateRequestedPaths)
                        .after(PathingSet::UpdateExistingPaths),
                    check_path_results
                        .in_set(PathingSet::PathResults)
                        // This system removes finished tasks from UpdatePathsState
                        // and inserts Scheduledpath components. When this happen,
                        // the tasks is no longer available however the component
                        // is not available as well until the end of the stage.
                        //
                        // System PathingSet::UpdateExistingPaths needs to detect
                        // that a path is either already scheduled or being
                        // computed. Thus this system must run after it.
                        .after(PathingSet::UpdateExistingPaths),
                    update_path_components
                        .after(PathingSet::PathResults)
                        // This is needed to avoid race condition in PathTarget
                        // removal which would happen if path was not-found before
                        // this system is run.
                        .before(PathingSet::UpdateRequestedPaths),
                )
                    .run_if(in_state(GameState::Playing)),
            )
            .add_systems(
                PostMovement,
                remove_path_targets.run_if(in_state(AppState::InGame)),
            );
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, SystemSet)]
pub(crate) enum PathingSet {
    UpdateRequestedPaths,
    UpdateExistingPaths,
    PathResults,
}

/// This event triggers computation of shortest path to a target and
/// replacement / insertion of this path to the entity.
#[derive(Event)]
pub struct UpdateEntityPathEvent {
    entity: Entity,
    target: PathTarget,
}

impl UpdateEntityPathEvent {
    /// # Arguments
    ///
    /// * `entity` - entity whose path should be updated / inserted. This must
    ///   be a locally simulated entity.
    ///
    /// * `target` - desired path target & path searching query configuration.
    pub fn new(entity: Entity, target: PathTarget) -> Self {
        Self { entity, target }
    }

    fn entity(&self) -> Entity {
        self.entity
    }

    fn target(&self) -> PathTarget {
        self.target
    }
}

/// This event is sent when a new path is found for a locally simulated entity.
#[derive(Event)]
pub(crate) struct PathFoundEvent {
    entity: Entity,
    path: Option<Path>,
}

impl PathFoundEvent {
    fn new(entity: Entity, path: Option<Path>) -> Self {
        Self { entity, path }
    }

    pub(crate) fn entity(&self) -> Entity {
        self.entity
    }

    pub(crate) fn path(&self) -> Option<&Path> {
        self.path.as_ref()
    }
}

#[derive(Default, Resource)]
struct UpdatePathsState {
    tasks: AHashMap<Entity, UpdatePathTask>,
}

impl UpdatePathsState {
    fn contains(&self, entity: Entity) -> bool {
        self.tasks.contains_key(&entity)
    }

    fn spawn_new(&mut self, finder: FinderRes, entity: Entity, source: Vec2, target: PathTarget) {
        let pool = AsyncComputeTaskPool::get();
        let task = pool.spawn(async move { finder.find_path(source, target) });
        self.tasks.insert(entity, UpdatePathTask::new(task));
    }

    fn check_results(&mut self) -> Vec<(Entity, Option<Path>)> {
        let mut results = Vec::new();
        self.tasks.retain(|&entity, task| match task.check() {
            UpdatePathState::Resolved(path) => {
                results.push((entity, path));
                false
            }
            UpdatePathState::Processing => true,
        });

        results
    }
}

struct UpdatePathTask(Task<Option<Path>>);

impl UpdatePathTask {
    fn new(task: Task<Option<Path>>) -> Self {
        Self(task)
    }

    fn check(&mut self) -> UpdatePathState {
        match future::block_on(future::poll_once(&mut self.0)) {
            Some(path) => UpdatePathState::Resolved(path),
            None => UpdatePathState::Processing,
        }
    }
}

enum UpdatePathState {
    Resolved(Option<Path>),
    Processing,
}

fn setup(mut commands: Commands) {
    commands.init_resource::<UpdatePathsState>()
}

fn cleanup(mut commands: Commands) {
    commands.remove_resource::<UpdatePathsState>();
}

fn update_existing_paths(
    finder: Res<FinderRes>,
    mut state: ResMut<UpdatePathsState>,
    entities: Query<(Entity, &Transform, &PathTarget, Has<ScheduledPath>)>,
) {
    for (entity, transform, target, has_path) in entities.iter() {
        let position = transform.translation.to_flat();
        if !has_path && !state.contains(entity) {
            let current_distance = position.distance(target.location());
            let desired_distance = target.properties().distance();
            if (current_distance - desired_distance).abs() <= TARGET_TOLERANCE {
                continue;
            }
        }

        let new_target = PathTarget::new(
            target.location(),
            // Set max distance to infinity: the object has already departed
            // from the original point so it would not make sense to stop in
            // the middle of the path instead of getting as close as possible.
            PathQueryProps::new(target.properties().distance(), f32::INFINITY),
            target.permanent(),
        );

        state.spawn_new(finder.clone(), entity, position, new_target);
    }
}

fn update_requested_paths(
    mut commands: Commands,
    finder: Res<FinderRes>,
    mut state: ResMut<UpdatePathsState>,
    mut events: EventReader<UpdateEntityPathEvent>,
    entities: Query<&Transform, With<MovableSolid>>,
) {
    for event in events.read() {
        if let Ok(transform) = entities.get(event.entity()) {
            commands.entity(event.entity()).insert(event.target());
            state.spawn_new(
                finder.clone(),
                event.entity(),
                transform.translation.to_flat(),
                event.target(),
            );
        }
    }
}

fn check_path_results(
    mut state: ResMut<UpdatePathsState>,
    mut events: EventWriter<PathFoundEvent>,
) {
    for (entity, path) in state.check_results() {
        events.send(PathFoundEvent::new(entity, path));
    }
}

fn update_path_components(
    mut commands: Commands,
    targets: Query<&PathTarget>,
    mut events: EventReader<PathFoundEvent>,
) {
    for event in events.read() {
        let mut entity_commands = commands.entity(event.entity());
        match event.path() {
            Some(path) => {
                entity_commands.insert(ScheduledPath::new(path.clone()));
            }
            None => {
                entity_commands.remove::<ScheduledPath>();

                // This must be here on top of target removal in
                // remove_path_targets due to the possibility that
                // `ScheduledPath` was never found.
                if let Ok(target) = targets.get(event.entity()) {
                    if !target.permanent() {
                        entity_commands.remove::<PathTarget>();
                    }
                }
            }
        }
    }
}

fn remove_path_targets(
    mut commands: Commands,
    targets: Query<&PathTarget>,
    mut removed: RemovedComponents<ScheduledPath>,
) {
    for entity in removed.read() {
        if let Ok(target) = targets.get(entity) {
            if !target.permanent() {
                commands.entity(entity).remove::<PathTarget>();
            }
        }
    }
}