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
#![allow(clippy::type_complexity)]
#![allow(clippy::needless_doctest_main)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::let_unit_value)]
#![warn(missing_docs)]

//! ## Aery
//! A plugin that adds a subset of Entity Relationship features to Bevy.
//!
//! ### Currently supported:
//! - ZST edge types only (simply means edges can't hold data)
//! - Fragmenting on edge types
//! - Cleanup policies
//! - Declarative APIs for:
//!   - Joining
//!   - Traversing
//!   - Spawning
//!
//! # API tour:
//! Non exhaustive. Covers most common parts.
//! ```
//! // Modeling RPG mechanics that resemble TOTK:
//! // - Items interacting with enviornment climate
//! // - Powering connected devices
//! use bevy::prelude::*;
//! use aery::prelude::*;
//!
//! #[derive(Clone, Copy, Component)]
//! struct Pos(Vec3);
//!
//! #[derive(Component)]
//! struct Character;
//!
//! #[derive(Component)]
//! struct Weapon {
//!     uses: u32,
//!     strength: u32,
//! }
//!
//! #[derive(Component)]
//! struct Stick;
//!
//! #[derive(Clone, Copy)]
//! enum Climate {
//!     Freezing,
//!     Cold,
//!     Neutral,
//!     Hot,
//!     Blazing,
//! }
//!
//! #[derive(Resource)]
//! struct ClimateMap {
//!     // ..
//! }
//!
//! impl ClimateMap {
//!     fn climate_at(&self, pos: Pos) -> Climate {
//!         todo!()
//!     }
//! }
//!
//! #[derive(Component)]
//! enum Food {
//!     Raw { freshness: f32 },
//!     Cooked,
//!     Spoiled,
//! }
//!
//! impl Food {
//!     fn tick(&mut self, climate: Climate) {
//!         let Food::Raw { freshness } = self else { return };
//!
//!         if *freshness < 0. {
//!             *self = Food::Spoiled;
//!             return
//!         }
//!
//!         match climate {
//!             Climate::Neutral => *freshness -= 1.,       // spoils over time
//!             Climate::Cold => *freshness -= 0.1,         // spoils slowly
//!             Climate::Freezing => *freshness -= 0.01,    // spoils very slowly
//!             Climate::Hot => *freshness -= 5.,           // spoils quickly
//!             Climate::Blazing => *self = Food::Cooked,   // Cooks food (should add a timer)
//!         }
//!     }
//! }
//!
//! #[derive(Component)]
//! struct Apple;
//!
//! #[derive(Relation)]
//! struct Inventory;
//!
//! fn setup(mut cmds: Commands) {
//!     // Spawn character with some starting items.
//!     cmds.spawn((Character, Pos(Vec3::default())))
//!         .scope::<Inventory>(|invt| {
//!             // Give them a starting weapon & 3 food items
//!             invt.add((Weapon { uses: 32, strength: 4 }, Stick))
//!                 .add((Food::Raw { freshness: 128. }, Apple))
//!                 .add((Food::Raw { freshness: 128. }, Apple))
//!                 .add((Food::Raw { freshness: 128. }, Apple));
//!         });
//!
//!     // Alternatively construct relatiosn manually.
//!     // This might be more appropriate for changing an inventory or making more complex graphs.
//!     let char = cmds.spawn((Character, Pos(Vec3::default()))).id();
//!     cmds.spawn((Weapon { uses: 32, strength: 4, }, Stick)).set::<Inventory>(char);
//!     cmds.spawn((Food::Raw { freshness: 128. }, Apple)).set::<Inventory>(char);
//!     cmds.spawn((Food::Raw { freshness: 128. }, Apple)).set::<Inventory>(char);
//!     cmds.spawn((Food::Raw { freshness: 128. }, Apple)).set::<Inventory>(char);
//! }
//!
//! fn tick_food(
//!     mut characters: Query<((&Character, &Pos), Relations<Inventory>)>,
//!     mut inventory_food: Query<&mut Food, Without<Pos>>,
//!     mut food: Query<(&mut Food, &Pos)>,
//!     climate_map: Res<ClimateMap>,
//! ) {
//!     // Tick foods that are just in the world somewhere
//!     for (mut food, pos) in food.iter_mut() {
//!         food.tick(climate_map.climate_at(*pos));
//!     }
//!
//!     // Tick foods that are in a character's inventory based on the character's position
//!     for ((_, pos), edges) in characters.iter() {
//!         let climate = climate_map.climate_at(*pos);
//!         edges.join::<Inventory>(&mut inventory_food).for_each(|mut food| {
//!             food.tick(climate);
//!         });
//!     }
//! }
//!
//! fn drop_item_from_inventory(
//!     mut commands: Commands,
//!     mut events: EventReader<TargetEvent>,
//!     characters: Query<&Pos, With<Character>>,
//!     food: Query<Entity, With<Food>>,
//! ) {
//!     // Set an items position to the position of the character that last had the item
//!     // in their inventory when they drop it.
//!     for event in events
//!         .iter()
//!         .filter(|event| event.matches(Wc, Op::Unset, Inventory, Wc))
//!     {
//!         let Ok(pos) = characters.get(event.target) else { return };
//!         commands.entity(event.host).insert(*pos);
//!     }
//!
//! }
//!
//! #[derive(Relation)]
//! #[aery(Symmetric, Poly)]
//! struct FuseJoint;
//!
//! #[derive(Component)]
//! struct Fan {
//!     orientation: Quat
//! }
//!
//! #[derive(Component)]
//! struct Powered;
//!
//! fn tick_devices(
//!     mut devices: Query<((Entity, &mut Pos), Relations<FuseJoint>)>,
//!     mut fans: Query<(Entity, &Fan, &mut Pos), With<Powered>>,
//! ) {
//!     for (entity, fan, pos) in fans.iter_mut() {
//!         // Move the fan based on its orientation
//!         pos = todo!();
//!
//!         // Track visited nodes because this is a symmetric relationship
//!         let mut updated = vec![entity];
//!
//!         devices.traverse_mut::<FuseJoint>([entity]).for_each(|(entity, ref mut pos), _| {
//!             if updated.contains(&entity) {
//!                 TCF::Close
//!             } else {
//!                 // Move connected device based on fan direction
//!                 pos = todo!();
//!                 updated.push(*entity);
//!                 TCF::Continue
//!             }
//!         });
//!     }
//! }
//! ```

use bevy_app::{App, Plugin};
use bevy_ecs::entity::Entity;

///
pub mod edges;
///
pub mod events;
///
pub mod for_each;
///
pub mod operations;
///
pub mod relation;
///
pub mod scope;
///
pub mod tuple_traits;

use events::{CleanupEvent, TargetEvent};

/// A type to enable wildcard APIs
pub enum Var<T> {
    /// Sepcific value.
    Val(T),
    /// Wildcard. Will match anything.
    Wc,
}

impl<T> Default for Var<T> {
    fn default() -> Self {
        Self::Wc
    }
}

impl<T: PartialEq> PartialEq<T> for Var<T> {
    fn eq(&self, other: &T) -> bool {
        match self {
            Self::Val(v) if v == other => true,
            Self::Wc => true,
            _ => false,
        }
    }
}

impl<T> From<Option<T>> for Var<T> {
    fn from(value: Option<T>) -> Self {
        match value {
            Some(value) => Self::Val(value),
            None => Self::Wc,
        }
    }
}

impl From<Entity> for Var<Entity> {
    fn from(value: Entity) -> Self {
        Self::Val(value)
    }
}

/// Plugin that adds the resources and events created by aery.
pub struct Aery;

impl Plugin for Aery {
    fn build(&self, app: &mut App) {
        app.add_event::<TargetEvent>().add_event::<CleanupEvent>();
    }
}

///
pub mod prelude {
    #[doc(no_inline)]
    pub use super::{
        Aery,
        Var::{self, Wc},
    };
    #[doc(no_inline)]
    pub use crate::{
        edges::{Abstains, Branch, Leaf, Participates, RelationCommands, Root, Set, Unset},
        events::{CleanupEvent, Op, TargetEvent},
        for_each::*,
        operations::{
            utils::{EdgeSide, Relations, Up},
            FoldBreadth, Join, Track, TrackSelf, Traverse,
        },
        relation::{CleanupPolicy, Hierarchy, Relation, ZstOrPanic},
        scope::{AeryEntityCommandsExt, AeryEntityWorldMutExt},
        tuple_traits::{Joinable, RelationSet},
    };
    #[doc(no_inline)]
    pub use aery_macros::*;
}