forge
Explore
Log in

Don't you dare go Hollow

courier

Clone
★ 0

0 watching0 forksRustAGPL-3.05.3 MiB6d9eeb9Tahinli21 days ago3 commits

demo.rs360 lines, 11.6 KiBHistoryRawDownload
1use crate::game::*;
2use crate::iso::*;
3use crate::player::*;
4use crate::world::*;
5use bevy::app::AppExit;
6use bevy::prelude::*;
7use bevy::render::view::window::screenshot::{Screenshot, ScreenshotCaptured, save_to_disk};
8use bevy::time::TimeUpdateStrategy;
9use std::io::Write;
10use std::process::{Child, ChildStdin, Command, Stdio};
11use std::sync::{Arc, Mutex};
12use std::time::Duration;
13
14pub const FPS: f32 = 30.0;
15
16pub struct DemoPlugin {
17 pub record: Option<String>,
18 pub script: bool,
19}
20
21#[derive(Clone)]
22pub enum Step {
23 Walk(Vec2),
24 Road { leg: usize, forward: bool, journey: bool, until: f32 },
25 Press,
26 Pick(&'static str),
27 Settle,
28 Wait(f32),
29 Camp,
30 Lantern,
31 Eat,
32 Inv,
33 Shot(&'static str),
34 Tp(Vec2),
35 Hour(f32),
36}
37
38#[derive(Resource)]
39struct Script {
40 steps: Vec<Step>,
41 i: usize,
42 t: f32,
43 road_i: Option<usize>,
44 auto_t: f32,
45 path: Vec<Vec2>,
46}
47
48fn find_path(map: &Map, from: Vec2, to: Vec2) -> Vec<Vec2> {
49 use std::collections::{HashMap, VecDeque};
50 let (a, b) = (cell(from), cell(to));
51 let mut prev: HashMap<IVec2, IVec2> = HashMap::new();
52 let mut q = VecDeque::from([a]);
53 prev.insert(a, a);
54 while let Some(c) = q.pop_front() {
55 if c == b {
56 break;
57 }
58 for d in [IVec2::X, IVec2::NEG_X, IVec2::Y, IVec2::NEG_Y] {
59 let n = c + d;
60 if prev.contains_key(&n) || (n - a).abs().max_element() > 40 {
61 continue;
62 }
63 if n != b && !map.walkable(n.as_vec2() + Vec2::splat(0.5)) {
64 continue;
65 }
66 prev.insert(n, c);
67 q.push_back(n);
68 }
69 }
70 if !prev.contains_key(&b) {
71 return vec![to];
72 }
73 let mut cells = vec![b];
74 let mut c = b;
75 while c != a {
76 c = prev[&c];
77 cells.push(c);
78 }
79 cells.reverse();
80 let mut out: Vec<Vec2> = cells.iter().skip(1).map(|c| c.as_vec2() + Vec2::splat(0.5)).collect();
81 out.pop();
82 out.push(to);
83 out
84}
85
86const AUTO: &[&str] = &["Light the lantern", "Throw them a ration", "Help him", "Offer him bread", "Point the way", "Press on", "Make camp", "Continue", "Leave", "Walk on", "Run for it"];
87
88fn pick(g: &Game, prefs: &[&str]) -> Option<usize> {
89 let (t, node) = g.dialog?;
90 let d = crate::content::talk(t, node, g);
91 if d.choices.is_empty() {
92 return Some(0);
93 }
94 for p in prefs {
95 if let Some(i) = d.choices.iter().position(|c| c.label.starts_with(p)) {
96 return Some(i);
97 }
98 }
99 None
100}
101
102#[derive(Resource)]
103struct Recorder {
104 pipe: Option<Arc<Mutex<ChildStdin>>>,
105 child: Option<Child>,
106 done_at: Option<u32>,
107 frame: u32,
108}
109
110impl Plugin for DemoPlugin {
111 fn build(&self, app: &mut App) {
112 if self.script {
113 app.insert_resource(Scripted)
114 .insert_resource(Script { steps: if std::env::var("COURIER_TEST").is_ok() { test_script() } else { script() }, i: 0, t: 0.0, road_i: None, auto_t: 0.0, path: Vec::new() })
115 .add_systems(PreUpdate, drive);
116 }
117 if let Some(path) = &self.record {
118 app.insert_resource(TimeUpdateStrategy::ManualDuration(Duration::from_secs_f32(1.0 / FPS)));
119 let mut child = Command::new("ffmpeg")
120 .args(["-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgba", "-s", "1280x720", "-r", "30", "-i", "-", "-c:v", "libx264", "-preset", "medium", "-crf", "20", "-pix_fmt", "yuv420p", path])
121 .stdin(Stdio::piped())
122 .spawn()
123 .expect("ffmpeg");
124 let stdin = child.stdin.take().unwrap();
125 app.insert_resource(Recorder { pipe: Some(Arc::new(Mutex::new(stdin))), child: Some(child), done_at: None, frame: 0 })
126 .add_systems(Last, record);
127 }
128 }
129}
130
131fn record(mut commands: Commands, off: Res<crate::Offscreen>, mut rec: ResMut<Recorder>, script: Option<Res<Script>>, mut exit: MessageWriter<AppExit>) {
132 rec.frame += 1;
133 let finished = script.map(|s| s.i >= s.steps.len()).unwrap_or(rec.frame > 30 * 20);
134 if finished && rec.done_at.is_none() {
135 rec.done_at = Some(rec.frame);
136 }
137 if let Some(d) = rec.done_at {
138 if rec.frame > d + 20 {
139 rec.pipe = None;
140 if let Some(mut c) = rec.child.take() {
141 let _ = c.wait();
142 }
143 exit.write(AppExit::Success);
144 }
145 return;
146 }
147 if rec.frame < 5 {
148 return;
149 }
150 let Some(pipe) = rec.pipe.clone() else { return };
151 commands.spawn(Screenshot::image(off.0.clone())).observe(move |ev: On<ScreenshotCaptured>| {
152 if let Ok(img) = ev.image.clone().try_into_dynamic() {
153 let rgba = img.to_rgba8();
154 if rgba.width() == 1280 && rgba.height() == 720 {
155 let _ = pipe.lock().unwrap().write_all(rgba.as_raw());
156 }
157 }
158 });
159}
160
161fn drive(
162 mut commands: Commands,
163 time: Res<Time>,
164 mut s: ResMut<Script>,
165 mut pad: ResMut<Pad>,
166 mut g: ResMut<Game>,
167 map: Res<Map>,
168 mut pq: Query<&mut Mover, With<Player>>,
169 mut exit: MessageWriter<AppExit>,
170 rec: Option<Res<Recorder>>,
171 off: Option<Res<crate::Offscreen>>,
172) {
173 *pad = Pad::default();
174 let Ok(mut m) = pq.single_mut() else { return };
175 let Some(step) = s.steps.get(s.i).cloned() else {
176 if rec.is_none() {
177 exit.write(AppExit::Success);
178 }
179 return;
180 };
181 s.t += time.delta_secs();
182 let mut next = false;
183 match step {
184 Step::Walk(target) => {
185 if s.t == time.delta_secs() || s.path.is_empty() {
186 s.path = find_path(&map, m.pos, target);
187 }
188 while s.path.len() > 1 && (s.path[0] - m.pos).length() < 0.3 {
189 s.path.remove(0);
190 }
191 let d = s.path[0] - m.pos;
192 if (target - m.pos).length() < 0.25 || s.t > 25.0 {
193 next = true;
194 s.path.clear();
195 } else {
196 pad.dir = to_screen(d).normalize();
197 }
198 }
199 Step::Road { leg, forward, journey, until } => {
200 let l = &map.legs[leg];
201 let i = *s.road_i.get_or_insert_with(|| {
202 l.iter().enumerate().min_by(|a, b| (*a.1 - m.pos).length().total_cmp(&(*b.1 - m.pos).length())).map(|(i, _)| i).unwrap_or(0)
203 });
204 let goal = ((l.len() - 1) as f32 * until) as usize;
205 let mut j = i;
206 while j != goal && (l[j] - m.pos).length() < 1.2 {
207 j = if forward { (j + 1).min(l.len() - 1) } else { j.saturating_sub(1) };
208 }
209 s.road_i = Some(j);
210 if j == goal && (l[j] - m.pos).length() < 0.6 {
211 next = true;
212 s.road_i = None;
213 } else {
214 pad.dir = to_screen(l[j] - m.pos).normalize();
215 pad.journey = journey;
216 }
217 if g.dialog.is_some() {
218 pad.dir = Vec2::ZERO;
219 s.auto_t += time.delta_secs();
220 if s.auto_t > 2.6 {
221 s.auto_t = 0.0;
222 pad.choice = pick(&g, AUTO);
223 }
224 } else {
225 s.auto_t = 0.0;
226 }
227 }
228 Step::Press => {
229 pad.interact = true;
230 next = true;
231 }
232 Step::Pick(label) => {
233 if s.t > 2.4 {
234 if let Some(i) = pick(&g, &[label]) {
235 pad.choice = Some(i);
236 }
237 next = true;
238 }
239 }
240 Step::Settle => next = s.t > 0.5 && g.dialog.is_none() && g.request.is_none() && !g.camping,
241 Step::Wait(w) => next = s.t >= w,
242 Step::Camp => {
243 pad.camp = true;
244 next = true;
245 }
246 Step::Lantern => {
247 if g.flag("lantern") {
248 next = true;
249 } else if g.is_night() {
250 pad.lantern = true;
251 }
252 }
253 Step::Eat => {
254 pad.eat = true;
255 next = true;
256 }
257 Step::Inv => {
258 pad.inventory = true;
259 next = true;
260 }
261 Step::Tp(p) => {
262 m.pos = p;
263 next = true;
264 }
265 Step::Hour(h) => {
266 g.minutes = (g.minutes / 1440.0).floor() * 1440.0 + h * 60.0;
267 next = true;
268 }
269 Step::Shot(name) => {
270 let shot = match &off {
271 Some(o) => Screenshot::image(o.0.clone()),
272 None => Screenshot::primary_window(),
273 };
274 commands.spawn(shot).observe(save_to_disk(format!("{name}.png")));
275 next = true;
276 }
277 }
278 if next {
279 s.i += 1;
280 s.t = 0.0;
281 }
282}
283
284fn a(x: f32, y: f32) -> Step {
285 Step::Walk(ASHFORD + Vec2::new(x, y))
286}
287
288fn m(x: f32, y: f32) -> Step {
289 Step::Walk(MILLBROOK + Vec2::new(x, y))
290}
291
292fn c(x: f32, y: f32) -> Step {
293 Step::Walk(COALBRIDGE + Vec2::new(x, y))
294}
295
296fn talk(steps: &mut Vec<Step>, picks: &[&'static str]) {
297 steps.push(Step::Press);
298 for p in picks {
299 steps.push(Step::Pick(p));
300 }
301 steps.push(Step::Settle);
302}
303
304fn script() -> Vec<Step> {
305 use Step::*;
306 let mut s = vec![Wait(1.5), a(-1.0, 8.4)];
307 talk(&mut s, &["Anything I can do?", "I'll look for him", "Leave"]);
308 s.push(a(-7.5, 1.5));
309 talk(&mut s, &["Any work going?", "Take the parcel"]);
310 talk(&mut s, &["Any more work?", "Take the letter"]);
311 s.push(a(-3.5, 1.5));
312 talk(&mut s, &["Show me your goods", "Firewood", "Ration", "Lantern", "Leave"]);
313 s.extend([Inv, Wait(2.5), Inv]);
314 s.extend([a(15.5, 0.5), Road { leg: 0, forward: true, journey: true, until: 1.0 }, Settle]);
315 s.push(m(6.5, 1.5));
316 talk(&mut s, &["Deliver the Millbrook parcel", "Leave"]);
317 talk(&mut s, &["Any extra work?", "Take the job"]);
318 for _ in 0..2 {
319 s.push(m(0.0, 0.2));
320 talk(&mut s, &["Heave a bale"]);
321 s.push(m(4.5, 1.5));
322 talk(&mut s, &["Drop the bale"]);
323 }
324 s.push(m(6.5, 1.5));
325 talk(&mut s, &["Collect your pay", "Leave"]);
326 s.push(m(-10.0, 1.5));
327 talk(&mut s, &["Songs of the Moor (6s)"]);
328 s.extend([m(14.0, 0.5), Road { leg: 1, forward: true, journey: true, until: 0.5 }, Settle]);
329 s.extend([Lantern, Wait(4.0), Camp, Pick("Make camp"), Settle, Eat]);
330 s.extend([Road { leg: 1, forward: true, journey: true, until: 1.0 }, Settle]);
331 s.push(c(-1.5, 1.5));
332 talk(&mut s, &["Deliver the sealed letter", "Leave"]);
333 s.push(c(-9.5, 1.5));
334 talk(&mut s, &["Why haven't you written?", "Leave"]);
335 talk(&mut s, &["I can write a letter for you", "Write it for him", "Leave"]);
336 s.extend([c(-14.0, 0.5), Road { leg: 1, forward: false, journey: true, until: 0.0 }, Settle]);
337 s.extend([m(-14.0, 0.5), Road { leg: 0, forward: false, journey: true, until: 0.0 }, Settle]);
338 s.push(a(9.5, 1.5));
339 talk(&mut s, &["Give him Songs of the Moor", "Leave"]);
340 s.push(a(-1.0, 8.4));
341 talk(&mut s, &["Give him the letter", "Leave"]);
342 s.push(a(-7.5, 7.8));
343 talk(&mut s, &["Sleep until morning"]);
344 s.push(Wait(4.5));
345 s
346}
347
348fn test_script() -> Vec<Step> {
349 use Step::*;
350 let dir = std::env::var("COURIER_TEST").unwrap();
351 let shot = |n: &str| Shot(Box::leak(format!("{dir}/{n}").into_boxed_str()));
352 vec![
353 Wait(1.0), shot("ashford"), a(3.0, 1.0), Wait(1.5), shot("ashford_walk"),
354 Tp(MILLBROOK + Vec2::new(3.0, 1.0)), Wait(1.5), shot("millbrook"),
355 Tp(COALBRIDGE + Vec2::new(-6.0, 1.0)), Wait(1.5), shot("coalbridge"),
356 Tp(ASHFORD + Vec2::new(40.0, -40.0)), Wait(1.0), Road { leg: 0, forward: true, journey: false, until: 0.4 }, shot("road"),
357 Hour(22.0), Wait(4.0), shot("night"), Step::Wait(4.0), shot("night2"),
358 Tp(ASHFORD + Vec2::new(0.0, 1.0)), Wait(1.5), shot("ashford_night"),
359 ]
360}