forked from bevyengine/bevy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
computed_states.rs
654 lines (608 loc) · 25.3 KB
/
computed_states.rs
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! This example illustrates the use of [`ComputedStates`] for more complex state handling patterns.
//!
//! In this case, we'll be implementing the following pattern:
//! - The game will start in a `Menu` state, which we can return to with `Esc`
//! - From there, we can enter the game - where our bevy symbol moves around and changes color
//! - While in game, we can pause and unpause the game using `Space`
//! - We can also toggle "Turbo Mode" with the `T` key - where the movement and color changes are all faster. This
//! is retained between pauses, but not if we exit to the main menu.
//!
//! In addition, we want to enable a "tutorial" mode, which will involve it's own state that is toggled in the main menu.
//! This will display instructions about movement and turbo mode when in game and unpaused, and instructions on how to unpause when paused.
//!
//! To implement this, we will create 2 root-level states: [`AppState`] and [`TutorialState`].
//! We will then create some computed states that derive from [`AppState`]: [`InGame`] and [`TurboMode`] are marker states implemented
//! as Zero-Sized Structs (ZSTs), while [`IsPaused`] is an enum with 2 distinct states.
//! And lastly, we'll add [`Tutorial`], a computed state deriving from [`TutorialState`], [`InGame`] and [`IsPaused`], with 2 distinct
//! states to display the 2 tutorial texts.
use bevy::{dev_tools::states::*, prelude::*};
use ui::*;
// To begin, we want to define our state objects.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
Menu,
// Unlike in the `states` example, we're adding more data in this
// version of our AppState. In this case, we actually have
// 4 distinct "InGame" states - unpaused and no turbo, paused and no
// turbo, unpaused and turbo and paused and turbo.
InGame {
paused: bool,
turbo: bool,
},
}
// The tutorial state object, on the other hand, is a fairly simple enum.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum TutorialState {
#[default]
Active,
Inactive,
}
// Because we have 4 distinct values of `AppState` that mean we're "InGame", we're going to define
// a separate "InGame" type and implement `ComputedStates` for it.
// This allows us to only need to check against one type
// when otherwise we'd need to check against multiple.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
struct InGame;
impl ComputedStates for InGame {
// Our computed state depends on `AppState`, so we need to specify it as the SourceStates type.
type SourceStates = AppState;
// The compute function takes in the `SourceStates`
fn compute(sources: AppState) -> Option<Self> {
// You might notice that InGame has no values - instead, in this case, the `State<InGame>` resource only exists
// if the `compute` function would return `Some` - so only when we are in game.
match sources {
// No matter what the value of `paused` or `turbo` is, we're still in the game rather than a menu
AppState::InGame { .. } => Some(Self),
_ => None,
}
}
}
// Similarly, we want to have the TurboMode state - so we'll define that now.
//
// Having it separate from [`InGame`] and [`AppState`] like this allows us to check each of them separately, rather than
// needing to compare against every version of the AppState that could involve them.
//
// In addition, it allows us to still maintain a strict type representation - you can't Turbo
// if you aren't in game, for example - while still having the
// flexibility to check for the states as if they were completely unrelated.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
struct TurboMode;
impl ComputedStates for TurboMode {
type SourceStates = AppState;
fn compute(sources: AppState) -> Option<Self> {
match sources {
AppState::InGame { turbo: true, .. } => Some(Self),
_ => None,
}
}
}
// For the [`IsPaused`] state, we'll actually use an `enum` - because the difference between `Paused` and `NotPaused`
// involve activating different systems.
//
// To clarify the difference, `InGame` and `TurboMode` both activate systems if they exist, and there is
// no variation within them. So we defined them as Zero-Sized Structs.
//
// In contrast, pausing actually involve 3 distinct potential situations:
// - it doesn't exist - this is when being paused is meaningless, like in the menu.
// - it is `NotPaused` - in which elements like the movement system are active.
// - it is `Paused` - in which those game systems are inactive, and a pause screen is shown.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
enum IsPaused {
NotPaused,
Paused,
}
impl ComputedStates for IsPaused {
type SourceStates = AppState;
fn compute(sources: AppState) -> Option<Self> {
// Here we convert from our [`AppState`] to all potential [`IsPaused`] versions.
match sources {
AppState::InGame { paused: true, .. } => Some(Self::Paused),
AppState::InGame { paused: false, .. } => Some(Self::NotPaused),
// If `AppState` is not `InGame`, pausing is meaningless, and so we set it to `None`.
_ => None,
}
}
}
// Lastly, we have our tutorial, which actually has a more complex derivation.
//
// Like `IsPaused`, the tutorial has a few fully distinct possible states, so we want to represent them
// as an Enum. However - in this case they are all dependant on multiple states: the root [`TutorialState`],
// and both [`InGame`] and [`IsPaused`] - which are in turn derived from [`AppState`].
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
enum Tutorial {
MovementInstructions,
PauseInstructions,
}
impl ComputedStates for Tutorial {
// We can also use tuples of types that implement [`States`] as our [`SourceStates`].
// That includes other [`ComputedStates`] - though circular dependencies are not supported
// and will produce a compile error.
//
// We could define this as relying on [`TutorialState`] and [`AppState`] instead, but
// then we would need to duplicate the derivation logic for [`InGame`] and [`IsPaused`].
// In this example that is not a significant undertaking, but as a rule it is likely more
// effective to rely on the already derived states to avoid the logic drifting apart.
//
// Notice that you can wrap any of the [`States`] here in [`Option`]s. If you do so,
// the computation will get called even if the state does not exist.
type SourceStates = (TutorialState, InGame, Option<IsPaused>);
// Notice that we aren't using InGame - we're just using it as a source state to
// prevent the computation from executing if we're not in game. Instead - this
// ComputedState will just not exist in that situation.
fn compute(
(tutorial_state, _in_game, is_paused): (TutorialState, InGame, Option<IsPaused>),
) -> Option<Self> {
// If the tutorial is inactive we don't need to worry about it.
if !matches!(tutorial_state, TutorialState::Active) {
return None;
}
// If we're paused, we're in the PauseInstructions tutorial
// Otherwise, we're in the MovementInstructions tutorial
match is_paused? {
IsPaused::NotPaused => Some(Tutorial::MovementInstructions),
IsPaused::Paused => Some(Tutorial::PauseInstructions),
}
}
}
fn main() {
// We start the setup like we did in the states example.
App::new()
.add_plugins(DefaultPlugins)
.init_state::<AppState>()
.init_state::<TutorialState>()
// After initializing the normal states, we'll use `.add_computed_state::<CS>()` to initialize our `ComputedStates`
.add_computed_state::<InGame>()
.add_computed_state::<IsPaused>()
.add_computed_state::<TurboMode>()
.add_computed_state::<Tutorial>()
// we can then resume adding systems just like we would in any other case,
// using our states as normal.
.add_systems(Startup, setup)
.add_systems(OnEnter(AppState::Menu), setup_menu)
.add_systems(Update, menu.run_if(in_state(AppState::Menu)))
.add_systems(OnExit(AppState::Menu), cleanup_menu)
// We only want to run the [`setup_game`] function when we enter the [`AppState::InGame`] state, regardless
// of whether the game is paused or not.
.add_systems(OnEnter(InGame), setup_game)
// And we only want to run the [`clear_game`] function when we leave the [`AppState::InGame`] state, regardless
// of whether we're paused.
.enable_state_scoped_entities::<InGame>()
// We want the color change, toggle_pause and quit_to_menu systems to ignore the paused condition, so we can use the [`InGame`] derived
// state here as well.
.add_systems(
Update,
(toggle_pause, change_color, quit_to_menu).run_if(in_state(InGame)),
)
// However, we only want to move or toggle turbo mode if we are not in a paused state.
.add_systems(
Update,
(toggle_turbo, movement).run_if(in_state(IsPaused::NotPaused)),
)
// We can continue setting things up, following all the same patterns used above and in the `states` example.
.add_systems(OnEnter(IsPaused::Paused), setup_paused_screen)
.enable_state_scoped_entities::<IsPaused>()
.add_systems(OnEnter(TurboMode), setup_turbo_text)
.enable_state_scoped_entities::<TurboMode>()
.add_systems(
OnEnter(Tutorial::MovementInstructions),
movement_instructions,
)
.add_systems(OnEnter(Tutorial::PauseInstructions), pause_instructions)
.enable_state_scoped_entities::<Tutorial>()
.add_systems(
Update,
(
log_transitions::<AppState>,
log_transitions::<TutorialState>,
),
)
.run();
}
fn menu(
mut next_state: ResMut<NextState<AppState>>,
tutorial_state: Res<State<TutorialState>>,
mut next_tutorial: ResMut<NextState<TutorialState>>,
mut interaction_query: Query<
(&Interaction, &mut BackgroundColor, &MenuButton),
(Changed<Interaction>, With<Button>),
>,
) {
for (interaction, mut color, menu_button) in &mut interaction_query {
match *interaction {
Interaction::Pressed => {
*color = if menu_button == &MenuButton::Tutorial
&& tutorial_state.get() == &TutorialState::Active
{
PRESSED_ACTIVE_BUTTON.into()
} else {
PRESSED_BUTTON.into()
};
match menu_button {
MenuButton::Play => next_state.set(AppState::InGame {
paused: false,
turbo: false,
}),
MenuButton::Tutorial => next_tutorial.set(match tutorial_state.get() {
TutorialState::Active => TutorialState::Inactive,
TutorialState::Inactive => TutorialState::Active,
}),
};
}
Interaction::Hovered => {
if menu_button == &MenuButton::Tutorial
&& tutorial_state.get() == &TutorialState::Active
{
*color = HOVERED_ACTIVE_BUTTON.into();
} else {
*color = HOVERED_BUTTON.into();
}
}
Interaction::None => {
if menu_button == &MenuButton::Tutorial
&& tutorial_state.get() == &TutorialState::Active
{
*color = ACTIVE_BUTTON.into();
} else {
*color = NORMAL_BUTTON.into();
}
}
}
}
}
fn toggle_pause(
input: Res<ButtonInput<KeyCode>>,
current_state: Res<State<AppState>>,
mut next_state: ResMut<NextState<AppState>>,
) {
if input.just_pressed(KeyCode::Space) {
if let AppState::InGame { paused, turbo } = current_state.get() {
next_state.set(AppState::InGame {
paused: !*paused,
turbo: *turbo,
});
}
}
}
fn toggle_turbo(
input: Res<ButtonInput<KeyCode>>,
current_state: Res<State<AppState>>,
mut next_state: ResMut<NextState<AppState>>,
) {
if input.just_pressed(KeyCode::KeyT) {
if let AppState::InGame { paused, turbo } = current_state.get() {
next_state.set(AppState::InGame {
paused: *paused,
turbo: !*turbo,
});
}
}
}
fn quit_to_menu(input: Res<ButtonInput<KeyCode>>, mut next_state: ResMut<NextState<AppState>>) {
if input.just_pressed(KeyCode::Escape) {
next_state.set(AppState::Menu);
}
}
mod ui {
use crate::*;
#[derive(Resource)]
pub struct MenuData {
pub root_entity: Entity,
}
#[derive(Component, PartialEq, Eq)]
pub enum MenuButton {
Play,
Tutorial,
}
pub const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
pub const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
pub const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
pub const ACTIVE_BUTTON: Color = Color::srgb(0.15, 0.85, 0.15);
pub const HOVERED_ACTIVE_BUTTON: Color = Color::srgb(0.25, 0.55, 0.25);
pub const PRESSED_ACTIVE_BUTTON: Color = Color::srgb(0.35, 0.95, 0.35);
pub fn setup(mut commands: Commands) {
commands.spawn(Camera2dBundle::default());
}
pub fn setup_menu(mut commands: Commands, tutorial_state: Res<State<TutorialState>>) {
let button_entity = commands
.spawn(NodeBundle {
style: Style {
// center button
width: Val::Percent(100.),
height: Val::Percent(100.),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
flex_direction: FlexDirection::Column,
row_gap: Val::Px(10.),
..default()
},
..default()
})
.with_children(|parent| {
parent
.spawn((
ButtonBundle {
style: Style {
width: Val::Px(200.),
height: Val::Px(65.),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
..default()
},
background_color: NORMAL_BUTTON.into(),
..default()
},
MenuButton::Play,
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"Play",
TextStyle {
font_size: 33.0,
color: Color::srgb(0.9, 0.9, 0.9),
..default()
},
));
});
parent
.spawn((
ButtonBundle {
style: Style {
width: Val::Px(200.),
height: Val::Px(65.),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
..default()
},
background_color: match tutorial_state.get() {
TutorialState::Active => ACTIVE_BUTTON,
TutorialState::Inactive => NORMAL_BUTTON,
}
.into(),
..default()
},
MenuButton::Tutorial,
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"Tutorial",
TextStyle {
font_size: 33.0,
color: Color::srgb(0.9, 0.9, 0.9),
..default()
},
));
});
})
.id();
commands.insert_resource(MenuData {
root_entity: button_entity,
});
}
pub fn cleanup_menu(mut commands: Commands, menu_data: Res<MenuData>) {
commands.entity(menu_data.root_entity).despawn_recursive();
}
pub fn setup_game(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn((
StateScoped(InGame),
SpriteBundle {
texture: asset_server.load("branding/icon.png"),
..default()
},
));
}
const SPEED: f32 = 100.0;
const TURBO_SPEED: f32 = 300.0;
pub fn movement(
time: Res<Time>,
input: Res<ButtonInput<KeyCode>>,
turbo: Option<Res<State<TurboMode>>>,
mut query: Query<&mut Transform, With<Sprite>>,
) {
for mut transform in &mut query {
let mut direction = Vec3::ZERO;
if input.pressed(KeyCode::ArrowLeft) {
direction.x -= 1.0;
}
if input.pressed(KeyCode::ArrowRight) {
direction.x += 1.0;
}
if input.pressed(KeyCode::ArrowUp) {
direction.y += 1.0;
}
if input.pressed(KeyCode::ArrowDown) {
direction.y -= 1.0;
}
if direction != Vec3::ZERO {
transform.translation += direction.normalize()
* if turbo.is_some() { TURBO_SPEED } else { SPEED }
* time.delta_seconds();
}
}
}
pub fn setup_paused_screen(mut commands: Commands) {
info!("Printing Pause");
commands
.spawn((
StateScoped(IsPaused::Paused),
NodeBundle {
style: Style {
// center button
width: Val::Percent(100.),
height: Val::Percent(100.),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
flex_direction: FlexDirection::Column,
row_gap: Val::Px(10.),
position_type: PositionType::Absolute,
..default()
},
..default()
},
))
.with_children(|parent| {
parent
.spawn((
NodeBundle {
style: Style {
width: Val::Px(400.),
height: Val::Px(400.),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
..default()
},
background_color: NORMAL_BUTTON.into(),
..default()
},
MenuButton::Play,
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"Paused",
TextStyle {
font_size: 33.0,
color: Color::srgb(0.9, 0.9, 0.9),
..default()
},
));
});
});
}
pub fn setup_turbo_text(mut commands: Commands) {
commands
.spawn((
StateScoped(TurboMode),
NodeBundle {
style: Style {
// center button
width: Val::Percent(100.),
height: Val::Percent(100.),
justify_content: JustifyContent::Start,
align_items: AlignItems::Center,
flex_direction: FlexDirection::Column,
row_gap: Val::Px(10.),
position_type: PositionType::Absolute,
..default()
},
..default()
},
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"TURBO MODE",
TextStyle {
font_size: 33.0,
color: Color::srgb(0.9, 0.3, 0.1),
..default()
},
));
});
}
pub fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) {
for mut sprite in &mut query {
let new_color = LinearRgba {
blue: ops::sin(time.elapsed_seconds() * 0.5) + 2.0,
..LinearRgba::from(sprite.color)
};
sprite.color = new_color.into();
}
}
pub fn movement_instructions(mut commands: Commands) {
commands
.spawn((
StateScoped(Tutorial::MovementInstructions),
NodeBundle {
style: Style {
// center button
width: Val::Percent(100.),
height: Val::Percent(100.),
justify_content: JustifyContent::End,
align_items: AlignItems::Center,
flex_direction: FlexDirection::Column,
row_gap: Val::Px(10.),
position_type: PositionType::Absolute,
..default()
},
..default()
},
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"Move the bevy logo with the arrow keys",
TextStyle {
font_size: 33.0,
color: Color::srgb(0.3, 0.3, 0.7),
..default()
},
));
parent.spawn(TextBundle::from_section(
"Press T to enter TURBO MODE",
TextStyle {
font_size: 33.0,
color: Color::srgb(0.3, 0.3, 0.7),
..default()
},
));
parent.spawn(TextBundle::from_section(
"Press SPACE to pause",
TextStyle {
font_size: 33.0,
color: Color::srgb(0.3, 0.3, 0.7),
..default()
},
));
parent.spawn(TextBundle::from_section(
"Press ESCAPE to return to the menu",
TextStyle {
font_size: 33.0,
color: Color::srgb(0.3, 0.3, 0.7),
..default()
},
));
});
}
pub fn pause_instructions(mut commands: Commands) {
commands
.spawn((
StateScoped(Tutorial::PauseInstructions),
NodeBundle {
style: Style {
// center button
width: Val::Percent(100.),
height: Val::Percent(100.),
justify_content: JustifyContent::End,
align_items: AlignItems::Center,
flex_direction: FlexDirection::Column,
row_gap: Val::Px(10.),
position_type: PositionType::Absolute,
..default()
},
..default()
},
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"Press SPACE to resume",
TextStyle {
font_size: 33.0,
color: Color::srgb(0.3, 0.3, 0.7),
..default()
},
));
parent.spawn(TextBundle::from_section(
"Press ESCAPE to return to the menu",
TextStyle {
font_size: 33.0,
color: Color::srgb(0.3, 0.3, 0.7),
..default()
},
));
});
}
}