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
use super::*;
/// A 1-dimensional list of tiles that represents a grid of given dimension with
/// squared tiles of the same side length.
/// Only entities that have a defined location will be stored in this data
/// structure.
#[derive(Debug)]
pub struct Tiles<'e, K, C> {
dimension: Dimension,
tiles: Vec<Tile<'e, K, C>>,
}
impl<'e, K, C> Tiles<'e, K, C> {
/// Constructs a new list of tiles of the given dimension with no entities
/// assigned to it.
pub fn new(dimension: impl Into<Dimension>) -> Self {
let dimension = dimension.into();
let mut tiles = Vec::with_capacity(dimension.len());
for i in 0..dimension.len() {
tiles.push(Tile::new(Location::from_one_dimensional(i, dimension)));
}
Self { dimension, tiles }
}
/// Gets the Dimension of the Environment.
pub fn dimension(&self) -> Dimension {
self.dimension
}
/// Inserts the given Entity in the grid according to its location. If the
/// Entity has not location it will not be inserted.
/// Returns whether the Entity was inserted or not.
pub fn insert(&mut self, entity: &mut EntityTrait<'e, K, C>) -> bool {
if let Some(location) = entity.location() {
let index = location.one_dimensional(self.dimension);
debug_assert!(index < self.tiles.len());
let tile = &mut self.tiles[index];
tile.entities
.insert(entity.id(), entity as *mut EntityTrait<'e, K, C>);
true
} else {
false
}
}
/// Remove the Entity with the given ID from the given location.
/// Returns whether the Entity was removed or not.
pub fn remove(&mut self, id: Id, location: impl Into<Location>) -> bool {
let location = location.into();
let index = location.one_dimensional(self.dimension);
debug_assert!(index < self.tiles.len());
let tile = &mut self.tiles[index];
tile.entities.remove(&id).is_some()
}
/// Move the Entity with the given ID between a previous and a new location.
pub fn relocate(
&mut self,
id: Id,
from: impl Into<Location>,
to: impl Into<Location>,
) {
let from = from.into();
let index = from.one_dimensional(self.dimension);
debug_assert!(index < self.tiles.len());
let tile = &mut self.tiles[index];
if let Some(e) = tile.entities.remove(&id) {
let to = to.into();
let index = to.one_dimensional(self.dimension);
let tile = &mut self.tiles[index];
tile.entities.insert(id, e);
}
}
/// Gets an iterator over all the entities located at the given location.
///
/// The Environment is seen as a Torus from this method, therefore, out of
/// bounds offsets will be translated considering that the Environment
/// edges are joined.
pub fn entities_at(
&self,
location: impl Into<Location>,
) -> impl Iterator<Item = &EntityTrait<'e, K, C>> {
self.tile_at(location.into()).entities()
}
/// Gets an iterator over all the (mutable) entities located at the given
/// location.
///
/// The Environment is seen as a Torus from this method, therefore, out of
/// bounds offsets will be translated considering that the Environment
/// edges are joined.
pub fn entities_at_mut(
&mut self,
location: impl Into<Location>,
) -> impl Iterator<Item = &mut EntityTrait<'e, K, C>> {
self.tile_at_mut(location.into()).entities_mut()
}
/// Gets the tile at the given location.
fn tile_at(&self, location: Location) -> &Tile<'e, K, C> {
let index = self.tile_index_at(location);
let tile = &self.tiles[index];
debug_assert_eq!(tile.location, location);
tile
}
/// Gets the (mutable) tile at the given location.
fn tile_at_mut(&mut self, location: Location) -> &mut Tile<'e, K, C> {
let index = self.tile_index_at(location);
let tile = &mut self.tiles[index];
debug_assert_eq!(tile.location, location);
tile
}
/// Gets the tile index at the given location.
fn tile_index_at(&self, location: Location) -> usize {
let index = location.one_dimensional(self.dimension);
debug_assert!(index < self.tiles.len());
index
}
/// Gets the area of the environment surrounding the given Entity.
/// Returns None if the Entity has no location or scope, or if the scope of
/// the Entity forces its neighborhood to wrap onto itself due to the
/// dimensions of the Environment being not big enough to contain it.
pub fn neighborhood(
&self,
entity: &EntityTrait<'e, K, C>,
) -> Option<Neighborhood<'_, 'e, K, C>> {
match (entity.location(), entity.scope()) {
// only entities that have both a scope and a location can interact
// with the surrounding environment
(Some(center), Some(scope)) => {
if scope.overflows(self.dimension) {
// the dimension of the environment are not big enough to
// construct a valid neighborhood given this entity scope
return None;
}
let mut neighborhood =
Vec::with_capacity(Dimension::len_with_scope(scope));
let scope = scope.magnitude() as i32;
// build the portion of the environment seen by the entity tile
// by tile from the top-left corner to the bottom-down corner
for y in -scope..=scope {
for x in -scope..=scope {
let mut location = center;
location.translate(Offset { x, y }, self.dimension);
let index = location.one_dimensional(self.dimension);
debug_assert!(index < self.tiles.len());
let tile = &self.tiles[index];
neighborhood
.push(TileView::with_owner(entity.id(), tile));
}
}
Some(neighborhood.into())
}
_ => None,
}
}
}
/// A single tile of the environment. This data structure contains a map of
/// *weak* references to the entities.
#[derive(Debug)]
pub struct Tile<'e, K, C> {
// the location of the Tile in the Environment
location: Location,
// the entities that currently occupy this Tile
entities: HashMap<Id, *mut EntityTrait<'e, K, C>>,
}
impl<'e, K, C> Tile<'e, K, C> {
/// Constructs a new Tile with the given Location and no entities.
fn new(location: impl Into<Location>) -> Self {
Self {
location: location.into(),
entities: HashMap::default(),
}
}
/// Gets an iterator over all the entities located in this Tile.
/// The entities are returned in arbitrary order.
pub fn entities(&self) -> impl Iterator<Item = &EntityTrait<'e, K, C>> {
self.entities.iter().filter_map(move |(_id, e)| {
// Dereferencing the Entity pointer to return its reference
// is safe because the Environment guarantees that this
// method can only be called while the Entity pointed by this
// pointer still exist, and its lifetime will be equal to
// greater than the lifetime of self, besides the fact that is
// was properly allocated and initialized.
unsafe { e.as_ref() }
})
}
/// Gets an iterator over all the mutable entities located in this Tile.
/// The entities are returned in arbitrary order.
pub fn entities_mut(
&self,
) -> impl Iterator<Item = &mut EntityTrait<'e, K, C>> {
self.entities.iter().filter_map(move |(_id, e)| {
// Dereferencing the Entity pointer to return its reference
// is safe because the Environment guarantees that this
// method can only be called while the Entity pointed by this
// pointer still exist, and its lifetime will be equal to
// greater than the lifetime of self, besides the fact that is
// was properly allocated and initialized.
unsafe { e.as_mut() }
})
}
}
/// A single Environment tile as seen by a single Entity.
#[derive(Debug)]
pub struct TileView<'a, 'e, K, C> {
// the ID of the Entity that is seeing this tile
id: Option<Id>,
// the reference to the Tile in the Environment, where the *weak* references
// to the entities are stored
tile: &'a Tile<'e, K, C>,
}
impl<'a, 'e, K, C> TileView<'a, 'e, K, C> {
/// Gets the Location of this Tile within the Environment.
pub fn location(&self) -> Location {
self.tile.location
}
/// Gets an iterator over all the entities located in this Tile that does not
/// include the Entity that is seeing the tile.
///
/// The entities are returned in arbitrary order.
pub fn entities(&self) -> impl Iterator<Item = &EntityTrait<'e, K, C>> {
self.tile.entities().filter(move |e| {
!matches!(&self.id, Some(entity_id) if entity_id == &e.id())
})
}
/// Gets an iterator over all the mutable entities located in this Tile that
/// does not include the Entity that is seeing the tile.
///
/// The entities are returned in arbitrary order.
pub fn entities_mut(
&mut self,
) -> impl Iterator<Item = &mut EntityTrait<'e, K, C>> {
let entity_id = self.id;
self.tile.entities_mut().filter(move |e| {
!matches!(&entity_id, Some(entity_id) if entity_id == &e.id())
})
}
/// Gets the total number of entities located in this Tile, including the
/// Entity that is seeing the tile.
pub fn count(&self) -> usize {
self.tile.entities.len()
}
/// Returns true only if there are no entities located in this tile.
pub fn is_empty(&self) -> bool {
self.count() == 0
}
}
impl<'a, 'e, K: PartialEq, C> TileView<'a, 'e, K, C> {
/// Returns true only if this Tile contains an Entity of the given Kind,
/// without considering the Entity that is seeing the tile.
pub fn contains_kind(&self, kind: K) -> bool {
self.entities().any(|e| e.kind() == kind)
}
/// Gets the total number of entities in this Tile of the given Kind,
/// without considering the Entity that is seeing the tile.
pub fn count_kind(&self, kind: K) -> usize {
self.entities().filter(|e| e.kind() == kind).count()
}
}
impl<'a, 'e, K, C> TileView<'a, 'e, K, C> {
/// Constructs a new TileView with a specific Entity as owner.
pub(crate) fn with_owner(id: Id, tile: &'a Tile<'e, K, C>) -> Self {
Self { id: Some(id), tile }
}
/// Gets a reference to the inner Tile.
pub(crate) fn inner(&self) -> &Tile<'e, K, C> {
self.tile
}
}