forge
Explore
Log in

Don't you dare go Hollow

courier

Clone
★ 0

0 watching0 forksRustAGPL-3.05.3 MiB6d9eeb9Tahinli21 days ago3 commits

travel.rs437 lines, 12.5 KiBHistoryRawDownload
1use crate::game::*;
2use crate::iso::*;
3use crate::player::{facing_of, MainCamera, Mover, Pad, Player};
4use crate::sheets::CharSheets;
5use crate::sprites::{self, Spr};
6use crate::ui::Fade;
7use crate::world::{EventSpot, Glow};
8use bevy::prelude::*;
9use bevy::sprite::Anchor;
10
11const DAY: f32 = 1440.0;
12const FLAMES: [&Spr; 4] = [&sprites::FLAME0, &sprites::FLAME1, &sprites::FLAME2, &sprites::FLAME3];
13pub const BASE_CLEAR: Vec3 = Vec3::new(0.11, 0.16, 0.10);
14const DUSK: Vec3 = Vec3::new(0.9, 0.78, 0.72);
15pub const NIGHT: Vec3 = Vec3::new(0.42, 0.48, 0.72);
16const RAIN_COUNT: usize = 120;
17
18pub struct TravelPlugin;
19
20impl Plugin for TravelPlugin {
21 fn build(&self, app: &mut App) {
22 app.init_resource::<Travel>().add_systems(
23 Update,
24 (requests, clock, travel, needs, eat, camp_key, roadside, camp_flame, camp_light, rain).chain(),
25 );
26 }
27}
28
29#[derive(Clone, Copy, Default)]
30enum Phase {
31 #[default]
32 Idle,
33 Wait(f32),
34 Sleep { left: f32, camp: bool },
35}
36
37#[derive(Resource, Default)]
38pub struct Travel {
39 phase: Phase,
40 linger: f32,
41 rain_since: Option<f32>,
42}
43
44impl Travel {
45 pub fn busy(&self) -> bool {
46 !matches!(self.phase, Phase::Idle)
47 }
48}
49
50#[derive(Component)]
51struct CampPart;
52
53#[derive(Component)]
54pub struct CampLight(pub Vec2);
55
56#[derive(Component)]
57pub struct CampFlame {
58 frames: [Handle<Image>; 4],
59 idx: usize,
60 timer: f32,
61}
62
63#[derive(Component)]
64pub struct Bandit;
65
66#[derive(Component)]
67pub struct Rain;
68
69fn total(g: &Game) -> f32 {
70 g.day as f32 * DAY + g.minutes
71}
72
73pub fn day_tint(h: f32) -> Vec3 {
74 let day = Vec3::ONE;
75 if (7.0..18.0).contains(&h) {
76 day
77 } else if (18.0..19.0).contains(&h) {
78 day.lerp(DUSK, h - 18.0)
79 } else if (19.0..21.0).contains(&h) {
80 DUSK.lerp(NIGHT, (h - 19.0) / 2.0)
81 } else if h >= 21.0 || h < 5.0 {
82 NIGHT
83 } else if h < 6.0 {
84 NIGHT.lerp(DUSK, h - 5.0)
85 } else {
86 DUSK.lerp(day, h - 6.0)
87 }
88}
89
90pub fn night_amount(h: f32) -> f32 {
91 ((1.0 - day_tint(h).y) / (1.0 - NIGHT.y)).clamp(0.0, 1.0)
92}
93
94pub fn rnd(seed: &mut u32) -> f32 {
95 let mut x = (*seed).max(1);
96 x ^= x << 13;
97 x ^= x >> 17;
98 x ^= x << 5;
99 *seed = x;
100 x as f32 / u32::MAX as f32
101}
102
103fn requests(
104 mut commands: Commands,
105 assets: Res<AssetServer>,
106 mut g: ResMut<Game>,
107 mut t: ResMut<Travel>,
108 pq: Query<&Mover, With<Player>>,
109 camp_q: Query<Entity, With<CampPart>>,
110) {
111 if !matches!(t.phase, Phase::Idle) {
112 return;
113 }
114 let Some(req) = g.request.take() else { return };
115 match req {
116 Req::Wait { minutes } => t.phase = Phase::Wait(minutes),
117 Req::Sleep { until, camp } => {
118 if camp {
119 for e in &camp_q {
120 commands.entity(e).despawn();
121 }
122 if let Ok(m) = pq.single() {
123 spawn_camp(&mut commands, &assets, m.pos, g.has(Item::Firewood));
124 }
125 g.camping = true;
126 t.linger = 0.0;
127 }
128 let left = (until - g.minutes).rem_euclid(DAY);
129 t.phase = Phase::Sleep { left, camp };
130 }
131 Req::BreakCamp => {
132 for e in &camp_q {
133 commands.entity(e).despawn();
134 }
135 g.camping = false;
136 t.linger = 0.0;
137 }
138 }
139}
140
141fn spawn_camp(commands: &mut Commands, assets: &AssetServer, p: Vec2, fire: bool) {
142 let tent = p + Vec2::new(1.0, -1.0);
143 commands.spawn((
144 Sprite::from_image(assets.load(sprites::TENT.path)),
145 anchor(&sprites::TENT),
146 Transform::from_translation(to_screen(tent).extend(depth(tent + Vec2::splat(0.5)))).with_scale(Vec3::splat(PX)),
147 CampPart,
148 ));
149 let fire_at = p + Vec2::new(1.0, 1.0);
150 let z = depth(fire_at + Vec2::splat(0.5));
151 commands.spawn((
152 Sprite::from_image(assets.load(sprites::CAMPFIRE.path)),
153 anchor(&sprites::CAMPFIRE),
154 Transform::from_translation(to_screen(fire_at).extend(z)).with_scale(Vec3::splat(PX)),
155 CampPart,
156 ));
157 if !fire {
158 return;
159 }
160 commands.spawn((
161 Sprite::from_image(assets.load(FLAMES[0].path)),
162 anchor(FLAMES[0]),
163 Transform::from_translation(to_screen(fire_at).extend(z + 0.002)).with_scale(Vec3::splat(PX)),
164 CampFlame { frames: FLAMES.map(|s| assets.load(s.path)), idx: 0, timer: 0.0 },
165 CampPart,
166 ));
167 commands.spawn((
168 Sprite { image: assets.load(sprites::LIGHT.path), color: Color::srgba(1.0, 0.7, 0.35, 0.6), ..default() },
169 Transform::from_translation((to_screen(fire_at) + Vec2::new(0.0, 40.0)).extend(9.5)).with_scale(Vec3::splat(PX * 2.5)),
170 CampLight(fire_at),
171 CampPart,
172 ));
173}
174
175fn clock(time: Res<Time>, t: Res<Travel>, mut g: ResMut<Game>) {
176 if !matches!(t.phase, Phase::Idle) || g.dialog.is_some() || g.request.is_some() {
177 return;
178 }
179 let base = if g.zone == Zone::Road { 6.0 } else { 3.0 };
180 let k = if g.timelapse { base * 2.0 } else { base };
181 g.advance(time.delta_secs() * k);
182}
183
184fn wake(g: &mut Game, camp: bool) {
185 g.energy = if !camp || g.has(Item::Bedroll) { 100.0 } else { (g.energy + 45.0).min(100.0) };
186 if !camp {
187 g.warmth = 100.0;
188 } else if g.take(Item::Firewood) {
189 g.warmth = 100.0;
190 } else {
191 g.warmth = 35.0;
192 g.toasts.push("A cold night".into());
193 }
194 g.hunger = (g.hunger - 12.0).max(0.0);
195}
196
197fn travel(
198 mut commands: Commands,
199 time: Res<Time>,
200 mut g: ResMut<Game>,
201 mut t: ResMut<Travel>,
202 mut fade: ResMut<Fade>,
203 camp_q: Query<Entity, With<CampPart>>,
204) {
205 let dt = time.delta_secs();
206 match t.phase {
207 Phase::Idle => {}
208 Phase::Wait(left) => {
209 let step = left.min(300.0 * dt);
210 g.advance(step);
211 let left = left - step;
212 t.phase = if left <= 0.001 { Phase::Idle } else { Phase::Wait(left) };
213 }
214 Phase::Sleep { left, camp } => {
215 let step = left.min(if camp { 80.0 } else { 240.0 } * dt);
216 g.advance(step);
217 let left = left - step;
218 if left <= 0.001 {
219 wake(&mut g, camp);
220 t.phase = Phase::Idle;
221 if camp {
222 t.linger = 2.5;
223 }
224 } else {
225 t.phase = Phase::Sleep { left, camp };
226 }
227 }
228 }
229 let target = match t.phase {
230 Phase::Idle => 0.0,
231 Phase::Wait(_) => 0.35,
232 Phase::Sleep { camp: true, .. } => 0.45,
233 Phase::Sleep { camp: false, .. } => 0.85,
234 };
235 fade.0 += (target - fade.0) * (1.0 - (-dt * 6.0).exp());
236 if t.linger > 0.0 {
237 t.linger -= dt;
238 if t.linger <= 0.0 {
239 t.linger = 0.0;
240 for e in &camp_q {
241 commands.entity(e).despawn();
242 }
243 g.camping = false;
244 }
245 }
246}
247
248fn needs(mut g: ResMut<Game>, mut last: Local<Option<(u32, f32)>>, mut low: Local<[bool; 3]>) {
249 let prev = last.unwrap_or((g.day, g.minutes));
250 *last = Some((g.day, g.minutes));
251 let dm = ((g.day as f32 - prev.0 as f32) * DAY + (g.minutes - prev.1)).max(0.0);
252 let h = dm / 60.0;
253
254 let road = g.zone == Zone::Road;
255 let night = g.is_night();
256 g.hunger = (g.hunger - 4.0 * h).clamp(0.0, 100.0);
257 let drain = if road {
258 if g.timelapse { 7.5 } else { 5.0 }
259 } else {
260 2.0
261 };
262 let starve = if g.hunger <= 0.0 { 2.0 } else { 1.0 };
263 g.energy = (g.energy - drain * starve * h).clamp(0.0, 100.0);
264 let mut warm = if road && night {
265 if g.has(Item::Lantern) { -5.0 } else { -8.0 }
266 } else {
267 15.0
268 };
269 if road && g.raining {
270 warm -= 6.0;
271 }
272 g.warmth = (g.warmth + warm * h).clamp(0.0, 100.0);
273
274 let vals = [(g.hunger, "Hungry"), (g.energy, "Weary"), (g.warmth, "Cold")];
275 for (i, (v, msg)) in vals.into_iter().enumerate() {
276 if v < 20.0 {
277 if !low[i] {
278 low[i] = true;
279 g.toasts.push(msg.into());
280 }
281 } else {
282 low[i] = false;
283 }
284 }
285}
286
287fn eat(pad: Res<Pad>, mut g: ResMut<Game>) {
288 if pad.eat && g.take(Item::Ration) {
289 g.hunger = (g.hunger + 35.0).min(100.0);
290 g.toasts.push("Ate a Ration".into());
291 }
292}
293
294fn camp_key(pad: Res<Pad>, mut g: ResMut<Game>) {
295 if pad.camp && g.zone == Zone::Road && g.dialog.is_none() && !g.camping {
296 g.dialog = Some((Talk::Camp, "start"));
297 }
298}
299
300fn flag_of(ev: Ev) -> &'static str {
301 match ev {
302 Ev::BrokenCart => "cart_done",
303 Ev::Highwayman => "ev_highway",
304 Ev::Storm => "ev_storm",
305 Ev::Peddler => "ev_peddler",
306 Ev::Lost => "ev_lost",
307 Ev::Wolves => "ev_wolves_seen",
308 }
309}
310
311pub fn roadside(
312 mut commands: Commands,
313 sheets: Res<CharSheets>,
314 mut g: ResMut<Game>,
315 spots: Query<&EventSpot>,
316 pq: Query<&Mover, With<Player>>,
317 bandits: Query<Entity, With<Bandit>>,
318) {
319 if g.dialog.is_none() {
320 for e in &bandits {
321 commands.entity(e).despawn();
322 }
323 } else {
324 return;
325 }
326 let Ok(p) = pq.single() else { return };
327 for s in &spots {
328 if (s.pos - p.pos).length() > 2.5 {
329 continue;
330 }
331 let flag = flag_of(s.ev);
332 let open = match s.ev {
333 Ev::BrokenCart | Ev::Lost => !g.is_night(),
334 Ev::Highwayman => {
335 let h = g.hour();
336 h >= 18.5 || h < 5.0
337 }
338 Ev::Storm => !g.raining,
339 Ev::Peddler => true,
340 Ev::Wolves => false,
341 };
342 if !open || g.flag(flag) {
343 continue;
344 }
345 g.set(flag);
346 g.dialog = Some((Talk::Ev(s.ev), "start"));
347 if s.ev == Ev::Highwayman {
348 let pos = p.pos + Vec2::new(1.5, -1.5);
349 let facing = facing_of(to_screen(p.pos) - to_screen(pos));
350 commands.spawn((
351 sheets.sprite("bandit", facing * 9),
352 anchor(sheets.spr("bandit")),
353 Transform::from_translation(to_screen(pos).extend(depth(pos))).with_scale(Vec3::splat(PX)),
354 Mover::new(pos, facing),
355 Bandit,
356 ));
357 }
358 break;
359 }
360}
361
362fn camp_flame(time: Res<Time>, mut q: Query<(&mut CampFlame, &mut Sprite, &mut Anchor)>) {
363 let dt = time.delta_secs();
364 for (mut f, mut s, mut a) in &mut q {
365 f.timer += dt;
366 if f.timer >= 0.125 {
367 f.timer -= 0.125;
368 f.idx = (f.idx + 1) % 4;
369 s.image = f.frames[f.idx].clone();
370 *a = anchor(FLAMES[f.idx]);
371 }
372 }
373}
374
375fn camp_light(time: Res<Time>, mut q: Query<&mut Sprite, With<CampLight>>) {
376 let t = time.elapsed_secs();
377 let a = 0.6 + 0.07 * (t * 9.0).sin() + 0.03 * (t * 23.0).cos();
378 for mut s in &mut q {
379 s.color = Color::srgba(1.0, 0.7, 0.35, a);
380 }
381}
382
383fn rain(
384 mut commands: Commands,
385 time: Res<Time>,
386 mut g: ResMut<Game>,
387 mut t: ResMut<Travel>,
388 mut seed: Local<u32>,
389 cam: Query<(&Transform, &Projection), (With<MainCamera>, Without<Rain>)>,
390 mut drops: Query<(Entity, &mut Transform), With<Rain>>,
391) {
392 if g.raining && g.zone != Zone::Road {
393 g.raining = false;
394 }
395 let now = total(&g);
396 if g.raining {
397 let since = *t.rain_since.get_or_insert(now);
398 if now - since >= 180.0 {
399 g.raining = false;
400 }
401 } else {
402 t.rain_since = None;
403 }
404 if !g.raining {
405 for (e, _) in &drops {
406 commands.entity(e).despawn();
407 }
408 return;
409 }
410 let Ok((ct, proj)) = cam.single() else { return };
411 let scale = match proj {
412 Projection::Orthographic(o) => o.scale,
413 _ => 1.0,
414 };
415 let (hw, hh) = (640.0 * scale, 360.0 * scale);
416 let c = ct.translation.truncate();
417 let dt = time.delta_secs();
418 let count = drops.iter().count();
419 for _ in count..RAIN_COUNT {
420 let x = c.x + (rnd(&mut seed) * 2.0 - 1.0) * hw;
421 let y = c.y + (rnd(&mut seed) * 2.0 - 1.0) * hh;
422 commands.spawn((
423 Sprite { color: Color::srgba(0.8, 0.85, 1.0, 0.35), custom_size: Some(Vec2::new(2.0, 22.0)), ..default() },
424 Transform::from_xyz(x, y, 20.0).with_rotation(Quat::from_rotation_z(-0.2)),
425 Glow,
426 Rain,
427 ));
428 }
429 for (_, mut tr) in &mut drops {
430 tr.translation.y -= 900.0 * dt;
431 tr.translation.x -= 180.0 * dt;
432 if tr.translation.y < c.y - hh - 30.0 || tr.translation.x < c.x - hw - 30.0 {
433 tr.translation.y = c.y + hh + rnd(&mut seed) * 60.0;
434 tr.translation.x = c.x + (rnd(&mut seed) * 2.0 - 1.0) * hw;
435 }
436 }
437}