-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathresman.rs
More file actions
1505 lines (1360 loc) · 47.5 KB
/
Copy pathresman.rs
File metadata and controls
1505 lines (1360 loc) · 47.5 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
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Lemonade Stand / Restaurant Simulation
//!
//! Purpose
//! - A minimal, end-to-end example of using bevy_dogoap to drive agents via goals, precondition/effect actions, sensing, and reactive replanning.
//!
//! - Model planner state as datums (components) like `Thirst`, `AtOrderDesk`, `HasPendingOrder`.
//! - Define actions with preconditions and effects (e.g., `PlaceOrder`, `ProduceLemonade`, `ServeOrder`).
//! - Sense/derive facts each frame and pick goals; replan when conditions change.
//! - Coordinate multi-actor steps with simple desk “sessions” (order + serve) using timers.
//!
//! World
//! - Customers: thirst increases; when above a threshold, they plan to drink. They go to the
//! desk, place an order, wait, pick up, drink, then wander.
//! - Worker: reacts to demand (or a call-to-desk), takes the order, produces at the maker,
//! returns and serves. Has energy; rests at a chair when low.
//! - Business: money increases on serve; simple UI + debug text visualize state.
//!
//! Patterns used
//! - Multi-actor sessions: OrderSession/ServeSession coordinate customers and worker, requiring
//! both actors present at the desk. Timers gate completion; if either leaves, session cancels.
//! - Reactive goals: thirst/energy drift continuously, goals activate/clear based on thresholds
//! rather than discrete events. Triggers replanning when crossed.
//! - Idle behavior: when goals clear (thirst satisfied, no work), agents wander rather than freeze.
//! - Call semantics: customers trigger ShouldGoToOrderDesk when placing orders, pulling the
//! worker to the desk reactively rather than polling.
//! - Activity-dependent state: energy decay multiplier varies (producing vs idle), modeling
//! realistic effort costs.
//! - Atomic session updates: all state changes (spawn order, transfer item, pay money) happen
//! together when session timer completes, avoiding partial states.
//! - Schedule: FixedPreUpdate derives facts and sets goals → planner runs → FixedUpdate executes
//! movement/actions and sessions → facts re-derived → invariants/UI.
use std::collections::VecDeque;
use bevy::{
color::palettes::css::*,
prelude::*,
window::{Window, WindowPlugin},
};
use bevy_dogoap::plugin::DogoapSystems;
use bevy_dogoap::prelude::*;
use rand::Rng;
const THIRST_RATE: f64 = 0.2;
const THIRST_THRESHOLD: f64 = 6.0; // when to trigger drinking behaviour
const MOVE_SPEED: f32 = 96.0;
const ARRIVAL_RADIUS: f32 = 5.0; // px
const DRINK_TIME: f32 = 1.0;
const PRODUCE_TIME: f32 = 1.2;
const SERVE_TIME: f32 = 0.7;
const ORDERING_TIME: f32 = 1.0; // joint PlaceOrder/TakeOrder session duration
// Worker Energy
const ENERGY_LOW_THRESH: f64 = 0.1; // trigger rest
const ENERGY_TARGET: f64 = 0.8; // target to stop resting
const ENERGY_DECAY_RATE: f64 = 0.04; // per second when not resting
const ENERGY_GAIN_RATE: f64 = 0.08; // per second when at chair
const ENERGY_DECAY_PRODUCE_MULT: f64 = 1.6; // when producing lemonade, decay multiplier
// Customer wander area (around spawn area)
const WANDER_CENTER_X: f32 = -220.0; // between the two customer spawns
const WANDER_CENTER_Y: f32 = -100.0; // spawn y
const WANDER_HALF_WIDTH: f32 = 60.0; // total width ~120
const WANDER_HALF_HEIGHT: f32 = 40.0; // total height ~80
const WANDER_MIN_X: f32 = WANDER_CENTER_X - WANDER_HALF_WIDTH;
const WANDER_MAX_X: f32 = WANDER_CENTER_X + WANDER_HALF_WIDTH;
const WANDER_MIN_Y: f32 = WANDER_CENTER_Y - WANDER_HALF_HEIGHT;
const WANDER_MAX_Y: f32 = WANDER_CENTER_Y + WANDER_HALF_HEIGHT;
// Visual layout offsets
const DESK_CUSTOMER_OFFSET: Vec3 = Vec3::new(-50.0, 0.0, 0.0);
const DESK_WORKER_OFFSET: Vec3 = Vec3::new(50.0, 0.0, 0.0);
#[derive(Resource, Default, Debug, Clone, Copy)]
struct Money(i64);
// Markers
#[derive(Component)]
struct Agent;
#[derive(Component, Default)]
struct Customer {
order: Option<Entity>,
}
#[derive(Component)]
struct Worker;
#[derive(Component)]
struct LemonadeMaker;
#[derive(Component)]
struct Chair;
#[derive(Component, Default)]
struct OrderDesk {
// Derived each frame from presence and occupancy
can_take_order: bool,
current_order: Option<Entity>,
}
#[derive(Component, Default)]
struct OrderSession {
customer: Option<Entity>,
worker: Option<Entity>,
timer: Option<Timer>,
}
#[derive(Component, Default)]
struct ServeSession {
customer: Option<Entity>,
worker: Option<Entity>,
timer: Option<Timer>,
}
#[derive(Component)]
struct Order {
items_to_produce: VecDeque<Item>,
}
#[derive(Clone, Default, Copy, Reflect, Debug, PartialEq, Eq)]
enum Item {
#[default]
Nothing,
Lemonade,
}
#[derive(Component)]
struct StateDebugText;
#[derive(Component)]
struct MoneyText;
#[derive(Component)]
struct MoveTo(Vec3);
#[derive(Component)]
struct ActionProgress(Timer);
#[derive(Component)]
struct IdleWanderTimer(Timer);
// Small helpers to de-duplicate common patterns
fn random_wander_target() -> Vec3 {
let mut rng = rand::rng();
let rx = rng.random_range(WANDER_MIN_X..WANDER_MAX_X);
let ry = rng.random_range(WANDER_MIN_Y..WANDER_MAX_Y);
Vec3::new(rx, ry, 0.0)
}
fn move_or_arrive(commands: &mut Commands, e: Entity, t: &Transform, dest: Vec3) -> bool {
if t.translation.distance(dest) > ARRIVAL_RADIUS {
commands.entity(e).insert(MoveTo(dest));
false
} else {
true
}
}
fn progress_or_start(
commands: &mut Commands,
e: Entity,
progress: Option<Mut<ActionProgress>>,
secs: f32,
time: &Time,
) -> bool {
if let Some(mut prog) = progress {
if prog.0.tick(time.delta()).just_finished() {
true
} else {
false
}
} else {
commands
.entity(e)
.insert(ActionProgress(Timer::from_seconds(secs, TimerMode::Once)));
false
}
}
fn set_goals_and_replan(
commands: &mut Commands,
e: Entity,
planner: &mut Planner,
goals: Vec<Goal>,
) {
if planner.goals.as_slice() != goals.as_slice() {
planner.goals = goals;
planner.current_plan = None;
planner.current_action = None;
commands.entity(e).trigger(UpdatePlan::from);
}
}
fn has_any_action(e: Entity, q_actions: &Query<(Entity, &dyn ActionComponent)>) -> bool {
for (_ent, actions) in q_actions.get(e).iter() {
if actions.iter().next().is_some() {
return true;
}
}
false
}
fn desk_pos_for_customer(desk_t: &Transform) -> Vec3 {
desk_t.translation + DESK_CUSTOMER_OFFSET
}
fn desk_pos_for_worker(desk_t: &Transform) -> Vec3 {
desk_t.translation + DESK_WORKER_OFFSET
}
fn remove_if<C: Component>(commands: &mut Commands, e: Entity, cond: bool) {
if cond {
commands.entity(e).remove::<C>();
}
}
fn session_step(time: &Time, timer: &mut Option<Timer>, both_present: bool, start_secs: Option<f32>) -> bool {
if timer.is_some() && !both_present {
*timer = None;
return false;
}
if timer.is_none() {
if let Some(secs) = start_secs {
*timer = Some(Timer::from_seconds(secs, TimerMode::Once));
}
}
if let Some(t) = timer.as_mut() {
if t.tick(time.delta()).just_finished() {
*timer = None;
return true;
}
}
false
}
fn spawn_labeled<T: Component>(
commands: &mut Commands,
name: &str,
marker: T,
pos: Vec3,
label: &str,
label_offset: Vec3,
) {
commands
.spawn((
Name::new(name.to_string()),
marker,
InheritedVisibility::default(),
Transform::from_translation(pos),
)).with_children(|sub| {
sub.spawn((
Transform::from_translation(label_offset),
Text2d(label.into()),
TextFont { font_size: 12.0, ..default() },
bevy::sprite::Anchor::TOP_LEFT,
));
});
}
// Datums ("state fields")
#[derive(Component, Clone, DatumComponent)]
struct Thirst(f64);
#[derive(Component, Clone, EnumComponent)]
struct CarryingItem(Item);
#[derive(Component, Clone, DatumComponent)]
struct PlacedOrder(bool);
#[derive(Component, Clone, DatumComponent)]
struct OrderReady(bool);
#[derive(Component, Clone, DatumComponent)]
struct AtOrderDesk(bool);
#[derive(Component, Clone, DatumComponent)]
struct AtLemonadeMaker(bool);
#[derive(Component, Clone, DatumComponent)]
struct AtChair(bool);
#[derive(Component, Clone, DatumComponent)]
struct ShouldGoToOrderDesk(bool);
#[derive(Component, Clone, DatumComponent)]
struct HasPendingOrder(bool);
#[derive(Component, Clone, DatumComponent)]
struct ServedOrder(bool);
#[derive(Component, Clone, DatumComponent)]
struct OrderTaken(bool);
#[derive(Component, Clone, DatumComponent)]
struct Energy(f64);
// Actions
#[derive(Component, Clone, Default, ActionComponent)]
struct DrinkLemonade;
#[derive(Component, Clone, Default, ActionComponent)]
struct PickupOrder;
#[derive(Component, Clone, Default, ActionComponent)]
struct WaitForOrder;
#[derive(Component, Clone, Default, ActionComponent)]
struct PlaceOrder;
#[derive(Component, Clone, Default, ActionComponent)]
struct GoToOrderDesk;
#[derive(Component, Clone, Default, ActionComponent)]
struct GoToLemonadeMaker;
#[derive(Component, Clone, Default, ActionComponent)]
struct ProduceLemonade;
#[derive(Component, Clone, Default, ActionComponent)]
struct ServeOrder;
#[derive(Component, Clone, Default, ActionComponent)]
struct Rest;
#[derive(Component, Clone, Default, ActionComponent)]
struct TakeOrder;
#[derive(Component, Clone, Default, ActionComponent)]
struct GoToChair;
// App entry and setup
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
enum ExampleSystems {
Exec,
PostSense,
Invariants,
}
fn main() {
let mut app = App::new();
register_components!(
app,
[
Thirst,
CarryingItem,
PlacedOrder,
OrderReady,
AtOrderDesk,
AtLemonadeMaker,
AtChair,
ShouldGoToOrderDesk,
HasPendingOrder,
ServedOrder,
OrderTaken,
Energy
]
);
register_actions!(
app,
[
DrinkLemonade,
PickupOrder,
WaitForOrder,
PlaceOrder,
GoToOrderDesk,
GoToLemonadeMaker,
GoToChair,
TakeOrder,
ProduceLemonade,
ServeOrder,
Rest
]
);
app.insert_resource(Money(0))
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
canvas: Some("#example-canvas".into()),
..default()
}),
..default()
}))
.add_plugins(DogoapPlugin::default())
.add_systems(Startup, setup)
.add_systems(Update, (draw_state_debug, draw_ui, update_money_text))
// Sense + Goals: happen before planner runs (FixedPreUpdate)
.add_systems(
FixedPreUpdate,
(
derive_at_stations,
derive_has_pending_order,
derive_can_take_order,
update_energy,
update_thirst,
update_customer_goal,
update_worker_goal,
trigger_replanning,
)
.chain()
.before(DogoapSystems::RunPlanner),
)
// Execution & domain handlers in FixedUpdate
.configure_sets(
FixedUpdate,
(
ExampleSystems::Exec,
ExampleSystems::PostSense,
ExampleSystems::Invariants,
)
.chain(),
)
.add_systems(
FixedUpdate,
(
handle_move_to,
handle_go_to_order_desk,
handle_go_to_lemonade_maker,
handle_go_to_chair,
handle_customer_wander,
handle_order_session,
handle_take_order,
handle_wait_for_order,
handle_produce_lemonade,
handle_serve_session,
handle_serve_order,
handle_pickup_order,
handle_drink_lemonade,
handle_rest,
call_worker_to_desk,
)
.in_set(ExampleSystems::Exec),
)
// Re-derive post-exec so invariants and next-frame logic see fresh facts
.add_systems(
FixedUpdate,
(derive_at_stations, derive_has_pending_order, derive_can_take_order)
.in_set(ExampleSystems::PostSense),
)
.add_systems(FixedUpdate, check_invariants.in_set(ExampleSystems::Invariants))
.run();
}
fn setup(mut commands: Commands) {
// Customers
spawn_customer(&mut commands, "Customer 1", 12.0, Vec3::new(-200.0, -100.0, 1.0));
spawn_customer(&mut commands, "Customer 2", 0.0, Vec3::new(-240.0, -100.0, 1.0));
// Workers
spawn_worker(&mut commands, Vec3::new(140.0, -100.0, 1.0));
// Stations
spawn_labeled(
&mut commands,
"LemonadeMaker",
LemonadeMaker,
Vec3::new(170.0, 0.0, 1.0),
"Lemonade Maker",
Vec3::new(0.0, 30.0, 10.0),
);
commands
.spawn((
Name::new("OrderDesk"),
OrderDesk::default(),
OrderSession::default(),
ServeSession::default(),
InheritedVisibility::default(),
Transform::from_xyz(-100.0, 0.0, 1.0),
))
.with_children(|sub| {
sub.spawn((
Transform::from_translation(Vec3::new(0.0, 50.0, 10.0)),
Text2d("Order Desk".into()),
TextFont { font_size: 12.0, ..default() },
bevy::sprite::Anchor::TOP_LEFT,
));
});
// Chair
spawn_labeled(
&mut commands,
"Chair",
Chair,
Vec3::new(70.0, -120.0, 1.0),
"Chair",
Vec3::new(0.0, 20.0, 10.0),
);
// Camera
commands.spawn(Camera2d);
// Money UI
commands.spawn((
Transform::from_translation(Vec3::new(-360.0, 220.0, 100.0)),
Text2d("Money: 0".into()),
TextFont { font_size: 16.0, ..default() },
bevy::sprite::Anchor::TOP_LEFT,
MoneyText,
));
}
fn spawn_customer(commands: &mut Commands, name: &str, thirst_initial: f64, pos: Vec3) {
let customer_goal = Goal::from_reqs(&[Thirst::is_less(THIRST_THRESHOLD)]);
let drink = DrinkLemonade::action()
.with_precondition(CarryingItem::is(Item::Lemonade))
.with_mutator(CarryingItem::set(Item::Nothing))
.with_mutator(Thirst::decrease(10.0));
let pickup = PickupOrder::action()
.with_precondition(CarryingItem::is(Item::Nothing))
.with_precondition(OrderReady::is(true))
.with_precondition(AtOrderDesk::is(true))
.with_mutator(CarryingItem::set(Item::Lemonade))
.with_mutator(PlacedOrder::set(false))
.with_mutator(OrderReady::set(false))
.with_mutator(AtOrderDesk::set(false));
let wait = WaitForOrder::action()
.with_precondition(PlacedOrder::is(true))
.with_precondition(OrderReady::is(false))
.with_precondition(AtOrderDesk::is(true))
.with_mutator(OrderReady::set(true));
let place = PlaceOrder::action()
.with_precondition(PlacedOrder::is(false))
.with_precondition(CarryingItem::is(Item::Nothing))
.with_precondition(AtOrderDesk::is(true))
.with_mutator(PlacedOrder::set(true));
let go_to_desk = GoToOrderDesk::action()
.with_precondition(AtOrderDesk::is(false))
.with_mutator(AtOrderDesk::set(true));
let (planner, state) = create_planner!({
actions: [
(DrinkLemonade, drink),
(PickupOrder, pickup),
(WaitForOrder, wait),
(PlaceOrder, place),
(GoToOrderDesk, go_to_desk),
],
state: [
Thirst(thirst_initial),
CarryingItem(Item::Nothing),
PlacedOrder(false),
OrderReady(false),
AtOrderDesk(false),
AtLemonadeMaker(false),
],
goals: [customer_goal],
});
commands
.spawn((
Agent,
Name::new(name.to_string()),
Customer::default(),
InheritedVisibility::default(),
planner,
state,
Transform::from_translation(pos),
))
.with_children(|sub| {
sub.spawn((
Transform::from_translation(Vec3::new(-70.0, 0.0, 10.0)),
Text2d("".into()),
TextFont { font_size: 12.0, ..default() },
bevy::sprite::Anchor::TOP_LEFT,
StateDebugText,
));
});
}
fn spawn_worker(commands: &mut Commands, pos: Vec3) {
let serve = ServeOrder::action()
.with_precondition(CarryingItem::is(Item::Lemonade))
.with_precondition(AtOrderDesk::is(true))
.with_mutator(CarryingItem::set(Item::Nothing))
.with_mutator(ServedOrder::set(true))
.with_mutator(HasPendingOrder::set(false));
let produce = ProduceLemonade::action()
.with_precondition(HasPendingOrder::is(true))
.with_precondition(OrderTaken::is(true))
.with_precondition(AtLemonadeMaker::is(true))
.with_mutator(CarryingItem::set(Item::Lemonade));
let go_to_maker = GoToLemonadeMaker::action()
.with_precondition(HasPendingOrder::is(true))
.with_precondition(OrderTaken::is(true))
.with_precondition(AtLemonadeMaker::is(false))
.with_mutator(AtLemonadeMaker::set(true))
.with_mutator(AtOrderDesk::set(false));
let take_order = TakeOrder::action()
.with_precondition(AtOrderDesk::is(true))
.with_precondition(CarryingItem::is(Item::Nothing))
.with_precondition(OrderTaken::is(false))
.with_mutator(OrderTaken::set(true))
.with_mutator(ShouldGoToOrderDesk::set(false));
let go_to_desk = GoToOrderDesk::action()
.with_precondition(AtOrderDesk::is(false))
.with_mutator(AtOrderDesk::set(true))
.with_mutator(AtLemonadeMaker::set(false))
.with_mutator(ShouldGoToOrderDesk::set(false));
let rest = Rest::action()
.with_precondition(AtChair::is(true))
.with_mutator(Energy::increase(1.0));
let go_to_chair = GoToChair::action()
.with_precondition(AtChair::is(false))
.with_mutator(AtChair::set(true))
.with_mutator(AtOrderDesk::set(false))
.with_mutator(AtLemonadeMaker::set(false));
let worker_goal = Goal::from_reqs(&[ShouldGoToOrderDesk::is(false), HasPendingOrder::is(false)]);
let (planner, state) = create_planner!({
actions: [
(TakeOrder, take_order),
(ServeOrder, serve),
(ProduceLemonade, produce),
(GoToLemonadeMaker, go_to_maker),
(GoToChair, go_to_chair),
(GoToOrderDesk, go_to_desk),
(Rest, rest),
],
state: [
CarryingItem(Item::Nothing),
HasPendingOrder(false),
AtOrderDesk(false),
AtLemonadeMaker(false),
AtChair(false),
ShouldGoToOrderDesk(false),
ServedOrder(false),
OrderTaken(false),
Energy(0.7),
],
goals: [worker_goal],
});
commands
.spawn((
Agent,
Name::new("Worker"),
Worker,
InheritedVisibility::default(),
planner,
state,
Transform::from_translation(pos),
))
.with_children(|sub| {
sub.spawn((
Transform::from_translation(Vec3::new(50.0, 0.0, 10.0)),
Text2d("".into()),
TextFont { font_size: 12.0, ..default() },
bevy::sprite::Anchor::TOP_LEFT,
StateDebugText,
));
});
}
// Derived data
fn derive_at_stations(
q_desk: Query<&Transform, With<OrderDesk>>,
q_maker: Query<&Transform, With<LemonadeMaker>>,
q_chair: Query<&Transform, With<Chair>>,
mut sets: ParamSet<(
Query<(&Transform, &mut AtOrderDesk, &mut AtLemonadeMaker), With<Customer>>,
Query<(&Transform, &mut AtOrderDesk, &mut AtLemonadeMaker, &mut AtChair), With<Worker>>,
)>,
) {
let desk_t = q_desk
.single()
.expect("Exactly one OrderDesk expected");
let maker_t = q_maker
.single()
.expect("Exactly one LemonadeMaker expected");
{
let mut q_customers = sets.p0();
for (t, mut at_desk, mut at_maker) in q_customers.iter_mut() {
let target = desk_pos_for_customer(desk_t);
at_desk.0 = t.translation.distance(target) <= ARRIVAL_RADIUS;
at_maker.0 = t.translation.distance(maker_t.translation) <= ARRIVAL_RADIUS;
}
}
let chair_t = q_chair
.single()
.expect("Exactly one Chair expected");
{
let mut q_workers = sets.p1();
for (t, mut at_desk, mut at_maker, mut at_chair) in q_workers.iter_mut() {
let target = desk_pos_for_worker(desk_t);
at_desk.0 = t.translation.distance(target) <= ARRIVAL_RADIUS;
at_maker.0 = t.translation.distance(maker_t.translation) <= ARRIVAL_RADIUS;
at_chair.0 = t.translation.distance(chair_t.translation) <= ARRIVAL_RADIUS;
}
}
}
fn derive_has_pending_order(
mut q_workers: Query<&mut HasPendingOrder, With<Worker>>,
q_desk: Query<&OrderDesk>,
) {
let desk = q_desk
.single()
.expect("Exactly one OrderDesk expected");
let pending = desk.current_order.is_some();
for mut has in q_workers.iter_mut() {
has.0 = pending;
}
}
fn derive_can_take_order(
mut q_desk: Query<(
&Transform,
&mut OrderDesk,
Option<&OrderSession>,
Option<&ServeSession>,
)>,
q_customers: Query<&AtOrderDesk, With<Customer>>,
q_workers: Query<&AtOrderDesk, With<Worker>>,
) {
let (_t, mut desk, order_session, serve_session) = q_desk
.single_mut()
.expect("Exactly one OrderDesk expected");
let cust_here = q_customers.iter().any(|a| a.0);
let worker_here = q_workers.iter().any(|a| a.0);
let order_active = order_session.and_then(|s| s.timer.as_ref()).is_some();
let serve_active = serve_session.and_then(|s| s.timer.as_ref()).is_some();
desk.can_take_order = cust_here
&& worker_here
&& desk.current_order.is_none()
&& !order_active
&& !serve_active;
}
// General continuous behaviours
fn update_thirst(time: Res<Time>, mut q: Query<&mut Thirst, With<Customer>>) {
for mut thirst in q.iter_mut() {
thirst.0 += time.delta_secs_f64() * THIRST_RATE;
if thirst.0 > 100.0 {
thirst.0 = 100.0;
}
}
}
fn update_energy(
time: Res<Time>,
mut q: Query<(&AtChair, &mut Energy, Option<&ProduceLemonade>), With<Worker>>,
) {
let dt = time.delta_secs_f64();
for (at_chair, mut energy, producing) in q.iter_mut() {
let delta = if at_chair.0 {
ENERGY_GAIN_RATE * dt
} else if producing.is_some() {
// Slightly faster drain while producing
-(ENERGY_DECAY_RATE * ENERGY_DECAY_PRODUCE_MULT) * dt
} else {
-ENERGY_DECAY_RATE * dt
};
energy.0 = (energy.0 + delta).clamp(0.0, 1.0);
}
}
fn update_customer_goal(mut commands: Commands, mut q: Query<(Entity, &mut Planner, &Thirst), With<Customer>>) {
for (e, mut planner, thirst) in q.iter_mut() {
if thirst.0 > THIRST_THRESHOLD {
if planner.goals.is_empty() {
let goal = Goal::from_reqs(&[Thirst::is_less(THIRST_THRESHOLD)]);
set_goals_and_replan(&mut commands, e, &mut planner, vec![goal]);
}
} else {
if !planner.goals.is_empty() {
planner.goals.clear();
planner.current_plan = None;
planner.current_action = None;
}
}
}
}
fn update_worker_goal(
mut commands: Commands,
mut q: Query<(
Entity,
&mut Planner,
&ShouldGoToOrderDesk,
&HasPendingOrder,
&Energy,
), With<Worker>>,
) {
for (e, mut planner, should_go, pending, energy) in q.iter_mut() {
// Rest goal has priority when energy is low
if energy.0 < ENERGY_LOW_THRESH {
let rest_goal = Goal::from_reqs(&[Energy::is_more(ENERGY_TARGET)]);
set_goals_and_replan(&mut commands, e, &mut planner, vec![rest_goal]);
continue;
}
// Otherwise, handle work/demand goal
let needs_work = should_go.0 || pending.0;
if needs_work {
let goal = Goal::from_reqs(&[ShouldGoToOrderDesk::is(false), HasPendingOrder::is(false)]);
set_goals_and_replan(&mut commands, e, &mut planner, vec![goal]);
} else if !planner.goals.is_empty() {
planner.goals.clear();
planner.current_plan = None;
planner.current_action = None;
}
}
}
fn trigger_replanning(mut commands: Commands, q: Query<(Entity, &Planner)>) {
for (e, planner) in q.iter() {
if !planner.goals.is_empty() && planner.current_plan.is_none() {
commands.entity(e).trigger(UpdatePlan::from);
}
}
}
// Execution systems (movement and actions)
fn handle_move_to(mut commands: Commands, time: Res<Time>, mut q: Query<(Entity, &MoveTo, &mut Transform)>) {
for (e, move_to, mut t) in q.iter_mut() {
let dest = move_to.0;
if t.translation.distance(dest) > ARRIVAL_RADIUS {
let dir = (dest - t.translation).normalize();
t.translation += dir * MOVE_SPEED * time.delta_secs();
} else {
commands.entity(e).remove::<MoveTo>();
}
}
}
fn handle_go_to_order_desk(
mut commands: Commands,
q_desk: Query<&Transform, With<OrderDesk>>,
mut sets: ParamSet<(
Query<(Entity, &Transform, &GoToOrderDesk, &mut AtOrderDesk), (With<Customer>, Without<MoveTo>)>,
Query<(
Entity,
&Transform,
&GoToOrderDesk,
&mut AtOrderDesk,
&mut OrderTaken,
), (With<Worker>, Without<MoveTo>)>,
)>,
) {
let desk_t = q_desk
.single()
.expect("Exactly one OrderDesk expected");
{
let mut q_cust = sets.p0();
for (e, t, _a, mut at) in q_cust.iter_mut() {
let target = desk_pos_for_customer(desk_t);
if move_or_arrive(&mut commands, e, t, target) {
at.0 = true;
commands.entity(e).remove::<GoToOrderDesk>();
}
}
}
{
let mut q_work = sets.p1();
for (e, t, _a, mut at, mut taken) in q_work.iter_mut() {
let target = desk_pos_for_worker(desk_t);
if move_or_arrive(&mut commands, e, t, target) {
at.0 = true;
taken.0 = false;
commands.entity(e).remove::<GoToOrderDesk>();
}
}
}
}
fn handle_take_order(
mut commands: Commands,
q_place_cust: Query<&AtOrderDesk, (With<Customer>, With<PlaceOrder>)>,
mut q: Query<(Entity, &TakeOrder, &AtOrderDesk), With<Worker>>,
) {
let any_customer_ordering_here = q_place_cust.iter().any(|a| a.0);
for (e, _a, at_desk) in q.iter_mut() {
remove_if::<TakeOrder>(&mut commands, e, !at_desk.0 || !any_customer_ordering_here);
}
}
fn handle_go_to_lemonade_maker(
mut commands: Commands,
q_maker: Query<&Transform, With<LemonadeMaker>>,
mut q: Query<(
Entity,
&Transform,
&GoToLemonadeMaker,
&mut AtLemonadeMaker,
&mut AtOrderDesk,
&OrderTaken,
), Without<MoveTo>>,
) {
let maker_t = q_maker
.single()
.expect("Exactly one LemonadeMaker expected");
for (e, t, _a, mut at_maker, mut at_desk, taken) in q.iter_mut() {
if !taken.0 {
commands.entity(e).remove::<GoToLemonadeMaker>();
continue;
}
if move_or_arrive(&mut commands, e, t, maker_t.translation) {
at_maker.0 = true;
at_desk.0 = false;
commands.entity(e).remove::<GoToLemonadeMaker>();
}
}
}
fn handle_go_to_chair(
mut commands: Commands,
q_chair: Query<&Transform, With<Chair>>,
mut q: Query<(Entity, &Transform, &GoToChair, &mut AtChair, &mut AtOrderDesk, &mut AtLemonadeMaker), Without<MoveTo>>,
) {
let chair_t = q_chair
.single()
.expect("Exactly one Chair expected");
for (e, t, _a, mut at_chair, mut at_desk, mut at_maker) in q.iter_mut() {
if move_or_arrive(&mut commands, e, t, chair_t.translation) {
at_chair.0 = true;
at_desk.0 = false;
at_maker.0 = false;
commands.entity(e).remove::<GoToChair>();
}
}
}
fn handle_wait_for_order(
mut commands: Commands,
q_orders: Query<&Order>,
mut q: Query<(Entity, &WaitForOrder, &Customer, &OrderReady)>,
) {
for (e, _a, cust, ready) in q.iter_mut() {
if let Some(o) = cust.order {
if q_orders.get(o).is_err() || ready.0 {
commands.entity(e).remove::<WaitForOrder>();
}
} else {
commands.entity(e).remove::<WaitForOrder>();
}
}
}
fn handle_produce_lemonade(
mut commands: Commands,
time: Res<Time>,
mut q: Query<(
Entity,
&ProduceLemonade,
&mut CarryingItem,
&AtLemonadeMaker,
&OrderTaken,
Option<&mut ActionProgress>,
)>,
q_desk: Query<&OrderDesk>,
mut q_orders: Query<&mut Order>,
) {
let desk = q_desk
.single()
.expect("Exactly one OrderDesk expected");
for (e, _a, mut carry, at_maker, taken, progress) in q.iter_mut() {
if !at_maker.0 {
continue;
}
if !taken.0 {
// Plan requires TakeOrder, but if invalidated, drop action to replan
commands.entity(e).remove::<ProduceLemonade>();
continue;
}
let Some(order_e) = desk.current_order else {
commands.entity(e).remove::<ProduceLemonade>();
continue;
};
if let Ok(mut order) = q_orders.get_mut(order_e) {
if order.items_to_produce.is_empty() {
commands.entity(e).remove::<ProduceLemonade>();
continue;
}