-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsystem.rs
More file actions
207 lines (177 loc) · 7.41 KB
/
system.rs
File metadata and controls
207 lines (177 loc) · 7.41 KB
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
use std::pin::Pin;
use common::*;
use crate::activity::context::ActivityContext;
use crate::activity::NopActivity;
use crate::ai::{AiAction, AiComponent};
use crate::ecs::*;
use crate::activity::status::{StatusReceiver, StatusRef};
use crate::event::EntityEventQueue;
use crate::job::{SocietyJobRef, SocietyTask};
use crate::runtime::{Runtime, TaskRef, TaskResult};
use crate::{Societies, SocietyComponent};
use std::mem::transmute;
use std::rc::Rc;
#[derive(Component, EcsComponent, Default)]
#[storage(DenseVecStorage)]
#[name("activity")]
#[clone(disallow)]
pub struct ActivityComponent {
current_society_task: Option<(SocietyJobRef, SocietyTask)>,
/// Set by AI to trigger a new activity
new_activity: Option<(AiAction, Option<(SocietyJobRef, SocietyTask)>)>,
current: Option<ActiveTask>,
/// Reused between tasks
status: StatusReceiver,
}
struct ActiveTask {
task: TaskRef,
description: Box<dyn Display>,
}
/// Interrupts current with new activities
pub struct ActivitySystem<'a>(pub Pin<&'a EcsWorld>);
impl<'a> System<'a> for ActivitySystem<'a> {
type SystemData = (
Read<'a, EntitiesRes>,
Read<'a, Runtime>,
Write<'a, EntityEventQueue>,
Read<'a, Societies>,
WriteStorage<'a, ActivityComponent>,
WriteStorage<'a, AiComponent>,
ReadStorage<'a, SocietyComponent>,
);
fn run(
&mut self,
(
entities,
runtime,
mut event_queue,
societies_res,
mut activities,
mut ais,
societies,
): Self::SystemData,
) {
for (e, activity, ai) in (&entities, &mut activities, &mut ais).join() {
let e = Entity::from(e);
let mut new_activity = None;
if let Some((new_action, new_society_task)) = activity.new_activity.take() {
// TODO handle society task
debug!("interrupting activity with new"; e, "action" => ?new_action);
// cancel current
if let Some(task) = activity.current.take() {
task.task.cancel();
// unsubscribe from all events from previous activity
event_queue.unsubscribe_all(e);
}
// replace current with new activity, dropping the old one
new_activity = Some(new_action.into_activity());
activity.current_society_task = new_society_task;
// not necessary to manually cancel society reservation here, as the ai interruption
// already did
} else {
let (finished, result) = match activity.current.as_ref() {
None => (true, None),
Some(task) => {
let result = task.task.result();
(result.is_some(), result)
}
};
if finished {
// current task has finished
if let Some(res) = result.as_ref() {
debug!("activity finished, reverting to nop"; e, "result" => ?res);
// post debug event with activity result
#[cfg(feature = "testing")]
{
use crate::event::EntityEventDebugPayload;
use crate::{EntityEvent, EntityEventPayload};
if let Some(current) = activity.current.as_ref() {
event_queue.post(EntityEvent {
subject: e,
payload: EntityEventPayload::Debug(
EntityEventDebugPayload::FinishedActivity {
description: current.description.to_string(),
result: res.into(),
},
),
})
}
}
} else {
debug!("activity finished, reverting to nop"; e);
}
new_activity = Some(Rc::new(NopActivity::default()));
// interrupt ai and unreserve society task
let society = e
.get(&societies)
.and_then(|soc| societies_res.society_by_handle(soc.handle()));
ai.interrupt_current_action(e, None, society);
// next tick ai should return a new decision rather than unchanged to avoid
// infinite Nop loops
ai.clear_last_action();
// notify society job of completion
if let Some((job, task)) = activity.current_society_task.take() {
if let Some(TaskResult::Finished(finish)) = result {
job.borrow_mut().notify_completion(task, finish.into());
}
}
}
}
// spawn task for new activity
if let Some(new_activity) = new_activity {
// safety: ecs world is pinned and guaranteed to be valid as long as this system
// is being ticked
let world = unsafe { transmute::<Pin<&EcsWorld>, Pin<&'static EcsWorld>>(self.0) };
let description = new_activity.description();
let status_tx = activity.status.updater();
let (taskref_tx, taskref_rx) = futures::channel::oneshot::channel();
let task = runtime.spawn(taskref_tx, async move {
// recv task ref from runtime
let task = taskref_rx.await.unwrap(); // will not be cancelled
// create context
let ctx = ActivityContext::new(
e,
world,
task,
status_tx,
new_activity.clone(),
);
let result = new_activity.dew_it(&ctx).await;
match result.as_ref() {
Ok(_) => {
debug!("activity finished"; e, "activity" => ?new_activity);
// TODO need to notify society here, as above?
}
Err(err) => {
debug!("activity failed"; e, "activity" => ?new_activity, "err" => %err);
}
};
result
});
activity.current = Some(ActiveTask { task, description });
}
}
}
}
impl ActivityComponent {
pub fn interrupt_with_new_activity(
&mut self,
action: AiAction,
society_task: Option<(SocietyJobRef, SocietyTask)>,
) {
self.new_activity = Some((action, society_task));
}
pub fn task(&self) -> Option<&TaskRef> {
self.current.as_ref().map(|t| &t.task)
}
/// (activity description, current status)
pub fn status(&self) -> Option<(&dyn Display, StatusRef)> {
self.current
.as_ref()
.map(|t| (&*t.description, self.status.current()))
}
/// Exertion of current subactivity
pub fn exertion(&self) -> f32 {
self.status.current().exertion()
}
}