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
use std::fmt::Debug;
use std::ops::Index;
use std::str::FromStr;
use bevy_ecs::system::{Res, SystemParam};
use crate::assets::LevelIndex;
use crate::ldtk::EntityInstance;
use crate::system::ActiveLevel;
use crate::{LdtkLayer, LdtkLevel};
#[derive(SystemParam)]
pub struct MapQuery<'w> {
active: Option<Res<'w, ActiveLevel>>,
index: Res<'w, LevelIndex>,
}
#[derive(Clone)]
pub struct InstanceRef<'a> {
pub entity: &'a EntityInstance,
}
impl<'a> InstanceRef<'a> {
/// Get the leftmost pixel of this entity's anchor point
pub fn x(&self) -> i64 {
self.entity.px[0]
}
/// Get the topmost pixel of this entity's anchor point
pub fn y(&self) -> i64 {
self.entity.px[1]
}
/// Get the pixel width of this entity
pub fn width(&self) -> i64 {
self.entity.width
}
/// Get the pixel width of this entity
pub fn height(&self) -> i64 {
self.entity.height
}
/// Get the category that this instance belongs to. Exactly matches the string name
/// found in the LDTK entities list
pub fn get_type(&self) -> &'a String {
&self.entity.identifier
}
/// Try to get a type safe representation of this entity's type, as long as the target type
/// can be produced from a [str] representation
///
/// ## Example
///
/// ```
/// # use std::str::FromStr;
/// # use micro_ldtk::InstanceRef;
/// # use micro_ldtk::ldtk::EntityInstance;
///
/// #[derive(PartialEq, Debug)]
/// enum MyEntityType {
/// Player,
/// Monster,
/// }
///
/// impl FromStr for MyEntityType {
/// # type Err = ();
/// fn from_str(s: &str) -> Result<Self, Self::Err> {
/// match s {
/// "player" => Ok(Self::Player),
/// "monster" => Ok(Self::Monster),
/// # _ => panic!("Oh no")
/// }
/// }
/// }
///
/// let data_from_ldtk: EntityInstance = EntityInstance {
/// identifier: "player".to_string(),
/// // ...other properties
/// # smart_color: "".to_string(),
/// # grid: vec![],
/// # pivot: vec![],
/// # tags: vec![],
/// # tile: None,
/// # world_x: None,
/// # world_y: None,
/// # def_uid: 0,
/// # field_instances: vec![],
/// # height: 0,
/// # iid: "".to_string(),
/// # px: vec![],
/// # width: 0,
/// };
/// #
/// # let process_ldtk_data = || -> InstanceRef<'_> {
/// # InstanceRef {
/// # entity: &data_from_ldtk,
/// # }
/// # };
///
/// let my_entity_type: InstanceRef<'_> = process_ldtk_data();
/// assert_eq!(my_entity_type.try_get_typed_id(), Ok(MyEntityType::Player));
/// ```
pub fn try_get_typed_id<T: FromStr>(&self) -> Result<T, T::Err> {
T::from_str(self.get_type().as_str())
}
/// Retrieve an associated property from this instance. Will return [serde_json::Value::Null]
/// if there is no property with the given name
pub fn property(&self, name: impl ToString) -> serde_json::Value {
self[name].clone()
}
/// Get a reference to the inner instance of this instance ref
pub fn instance_ref(&self) -> &EntityInstance {
self.entity
}
}
impl<T: ToString> Index<T> for InstanceRef<'_> {
type Output = serde_json::Value;
fn index(&self, index: T) -> &Self::Output {
let name = index.to_string();
for field in &self.entity.field_instances {
if field.identifier == name {
return field.value.as_ref().unwrap_or(&serde_json::Value::Null);
}
}
&serde_json::Value::Null
}
}
#[derive(Copy, Clone, Debug)]
pub struct CameraBounds {
pub left: f32,
pub top: f32,
pub bottom: f32,
pub right: f32,
}
impl CameraBounds {
pub fn get_min_x(&self, camera_width: f32) -> f32 {
self.left + (camera_width / 2.0) // - (get_ldtk_tile_scale() / 2.0)
}
pub fn get_max_x(&self, camera_width: f32) -> f32 {
self.right - (camera_width / 2.0) // - (get_ldtk_tile_scale() / 2.0)
}
pub fn get_min_y(&self, camera_height: f32) -> f32 {
self.bottom + (camera_height / 2.0) // - (get_ldtk_tile_scale() / 2.0)
}
pub fn get_max_y(&self, camera_height: f32) -> f32 {
self.top - (camera_height / 2.0) // - (get_ldtk_tile_scale() / 2.0)
}
}
impl MapQuery<'_> {
// --- We put our logic in static accessors because we might source a level other
// --- than the currently active one. 'active' methods are a convenience to
// --- call the static accessors on whatever the current level is
/// Perform an action on each layer of the given LDTK level
pub fn for_each_layer_of(level: &LdtkLevel, mut cb: impl FnMut(&LdtkLayer)) {
for layer in level.layers() {
cb(layer);
}
}
/// Retrieve an iterator over every layer in the given level, regardless of type
pub fn get_layers_of(level: &LdtkLevel) -> impl DoubleEndedIterator<Item = &LdtkLayer> {
level.layers()
}
/// Retrieve a reference to every entity stored in the given level, regardless of which layer it is found on
pub fn get_entities_of(level: &LdtkLevel) -> Vec<&EntityInstance> {
level
.layers()
.flat_map(|layer| layer.as_ref().entity_instances.iter())
.collect()
}
/// Retrieve an enhanced wrapper to every entity stored in the given level, regardless of which layer it is found on
pub fn get_instance_refs_of(level: &LdtkLevel) -> Vec<InstanceRef> {
level
.layers()
.flat_map(|layer| {
layer
.as_ref()
.entity_instances
.iter()
.map(|inst| InstanceRef { entity: inst })
})
.collect()
}
/// Retrieve a reference to every entity stored in the given level that matches the specified type name.
/// This must exactly match the name shown in the LDTK entity list
pub fn get_filtered_entities_of(
level: &LdtkLevel,
entity_type: impl ToString,
) -> Vec<&EntityInstance> {
let e_type = entity_type.to_string();
level
.layers()
.flat_map(|layer| layer.as_ref().entity_instances.iter())
.filter(|inst| inst.identifier == e_type)
.collect()
}
/// Retrieve an enhanced wrapper to every entity stored in the given level that matches the specified type name.
/// This must exactly match the name shown in the LDTK entity list
pub fn get_filtered_instance_refs_of(
level: &LdtkLevel,
entity_type: impl ToString,
) -> Vec<InstanceRef> {
let e_type = entity_type.to_string();
level
.layers()
.flat_map(|layer| {
layer
.as_ref()
.entity_instances
.iter()
.map(|inst| InstanceRef { entity: inst })
})
.filter(|inst| inst.entity.identifier == e_type)
.collect()
}
/// Retrieve an owned copy of all entity data in the given level
pub fn get_owned_entities_of(level: &LdtkLevel) -> Vec<EntityInstance> {
level
.layers()
.flat_map(|layer| layer.as_ref().entity_instances.iter().cloned())
.collect()
}
/// Use the size of the level to create a zero-based rectangle indicating the boundaries that a camera should
///stay within to avoid showing any out-of-level space
pub fn get_camera_bounds_of(level: &LdtkLevel) -> CameraBounds {
let level = level.level_ref();
CameraBounds {
left: 0.0,
top: level.px_hei as f32,
bottom: 0.0,
right: level.px_wid as f32,
}
}
/// Check to see if the currently active level has the given name. Will always return false if there
/// is no active level
pub fn active_level_is(&self, name: impl ToString) -> bool {
self.active
.as_ref()
.map(|active_level| active_level.map == name.to_string())
.unwrap_or(false)
}
/// Get the name of the currently active level, or `None` if no level is active
pub fn get_active_level_name(&self) -> Option<&String> {
self.active.as_ref().map(|m| &m.map)
}
/// Get a reference to the currently active level data
pub fn get_active_level(&self) -> Option<&LdtkLevel> {
self.get_active_level_name()
.and_then(|index| self.index.get(index))
}
/// Get a list of references to entities in the currently active level
/// See [MapQuery::get_entities_of]
pub fn get_entities(&self) -> Vec<&EntityInstance> {
self.get_active_level()
.map(MapQuery::get_entities_of)
.unwrap_or_default()
}
/// Get a list of enhanced wrapper to entities in the currently active level
/// See [MapQuery::get_instance_refs_of]
pub fn get_instance_refs(&self) -> Vec<InstanceRef> {
self.get_active_level()
.map(MapQuery::get_instance_refs_of)
.unwrap_or_default()
}
/// Get a zero based rect that indicated pixel bounds for a camera
/// See [MapQuery::get_camera_bounds_of]
pub fn get_camera_bounds(&self) -> Option<CameraBounds> {
self.get_active_level().map(MapQuery::get_camera_bounds_of)
}
/// Perform an action for every layer in the currently active level
/// See [MapQuery::for_each_layer_of]
pub fn for_each_layer(&self, cb: impl FnMut(&LdtkLayer)) {
if let Some(level) = self.get_active_level() {
Self::for_each_layer_of(level, cb);
}
}
/// Search for the first listed instance ref of a given entity type in any layer within the
/// currently active level
pub fn find_one(&self, entity_type: impl AsRef<str>) -> Option<InstanceRef> {
let name = entity_type.as_ref();
self.get_instance_refs()
.iter()
.find(|ir| ir.get_type() == name)
.cloned()
}
/// Search for an instance ref with a specific IID within the currently active level
pub fn find_entity_by_iid(&self, iid: impl ToString) -> Option<InstanceRef> {
let iid = iid.to_string();
self.get_instance_refs()
.iter()
.find(|ir| ir.instance_ref().iid == iid)
.cloned()
}
}