bevy_entitiles 0.11.0

A 2d tilemap library for bevy. With many useful algorithms/tools built in.
Documentation
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
use bevy::{
    asset::{AssetId, AssetServer, Assets},
    color::LinearRgba,
    ecs::{
        entity::Entity,
        system::{Commands, EntityCommands},
    },
    math::{IVec2, Vec2},
    prelude::{Component, SpatialBundle},
    sprite::SpriteBundle,
    transform::components::Transform,
    utils::HashMap,
};

use crate::{
    ldtk::{
        components::{EntityIid, LayerIid, LdtkLoadedLevel, LdtkTempTransform, LevelIid},
        events::LdtkLevelLoaderMode,
        json::{
            field::FieldInstance,
            level::{EntityInstance, LayerInstance, Level, TileInstance},
        },
        resources::{LdtkAssets, LdtkLevelConfig, LdtkPatterns},
        traits::{LdtkEntityRegistry, LdtkEntityTagRegistry},
    },
    math::GridRect,
    render::material::StandardTilemapMaterial,
    serializing::pattern::TilemapPattern,
    tilemap::{
        buffers::TileBuffer,
        bundles::StandardTilemapBundle,
        map::{
            TileRenderSize, TilemapLayerOpacities, TilemapName, TilemapSlotSize, TilemapStorage,
            TilemapTexture, TilemapTextures, TilemapTransform, TilemapType,
        },
        tile::{TileBuilder, TileFlip, TileLayer, TileTexture},
    },
    DEFAULT_CHUNK_SIZE,
};

#[cfg(feature = "algorithm")]
use crate::{
    algorithm::pathfinding::PathTilemaps,
    tilemap::{algorithm::path::PathTilemap, chunking::storage::ChunkedStorage},
};

#[cfg(feature = "physics")]
use crate::tilemap::physics::{DataPhysicsTilemap, SerializablePhysicsSource};
#[cfg(feature = "physics")]
use bevy::math::UVec2;

#[cfg(feature = "algorithm")]
pub mod path;
#[cfg(feature = "physics")]
pub mod physics;

#[derive(Debug, Clone)]
pub struct PackedLdtkEntity {
    pub instance: EntityInstance,
    pub fields: HashMap<String, FieldInstance>,
    pub iid: EntityIid,
    pub transform: LdtkTempTransform,
}

impl PackedLdtkEntity {
    pub fn instantiate(
        self,
        commands: &mut EntityCommands,
        entity_registry: &LdtkEntityRegistry,
        entity_tag_registry: &LdtkEntityTagRegistry,
        config: &LdtkLevelConfig,
        ldtk_assets: &LdtkAssets,
        asset_server: &AssetServer,
    ) {
        let phantom_entity = {
            if let Some(e) = entity_registry.get(&self.instance.identifier) {
                e
            } else if !config.ignore_unregistered_entities {
                panic!(
                    "Could not find entity type with entity identifier: {}! \
                    You need to register it using App::register_ldtk_entity::<T>() first!",
                    self.instance.identifier
                );
            } else {
                return;
            }
        };

        self.instance.tags.iter().for_each(|tag| {
            if let Some(entity_tag) = entity_tag_registry.get(tag) {
                entity_tag.add_tag(commands);
            } else if !config.ignore_unregistered_entity_tags {
                panic!(
                    "Could not find entity tag with tag: {}! \
                    You need to register it using App::register_ldtk_entity_tag::<T>() first! \
                    Or call LdtkLevelManager::ignore_unregistered_entity_tags to ignore.",
                    tag
                );
            }
        });

        phantom_entity.spawn(
            commands,
            &self.instance,
            &self.fields,
            asset_server,
            ldtk_assets,
        )
    }
}

pub type LayerOpacity = f32;

#[derive(Component)]
pub struct LdtkLayers {
    pub assets_id: AssetId<LdtkAssets>,
    pub ty: LdtkLevelLoaderMode,
    pub level_entity: Entity,
    pub level: Level,
    pub layers: Vec<Option<(TilemapPattern, TilemapTexture, LayerIid, LayerOpacity)>>,
    pub entities: Vec<PackedLdtkEntity>,
    pub tilesets: HashMap<i32, TilemapTexture>,
    pub translation: Vec2,
    pub base_z_index: f32,
    pub background: SpriteBundle,
    #[cfg(feature = "algorithm")]
    pub path_layer: Option<(
        path::LdtkPathLayer,
        HashMap<IVec2, crate::tilemap::algorithm::path::PathTile>,
    )>,
    #[cfg(feature = "physics")]
    pub physics_layer: Option<(physics::LdtkPhysicsLayer, Vec<i32>, UVec2)>,
}

impl LdtkLayers {
    pub fn new(
        level_entity: Entity,
        level: &Level,
        total_layers: usize,
        assets_id: AssetId<LdtkAssets>,
        ldtk_assets: &LdtkAssets,
        translation: Vec2,
        base_z_index: f32,
        ty: LdtkLevelLoaderMode,
        background: SpriteBundle,
    ) -> Self {
        Self {
            assets_id,
            level_entity,
            level: level.clone(),
            layers: vec![None; total_layers],
            entities: vec![],
            tilesets: ldtk_assets.tilesets.clone(),
            translation,
            base_z_index,
            background,
            ty,
            #[cfg(feature = "algorithm")]
            path_layer: None,
            #[cfg(feature = "physics")]
            physics_layer: None,
        }
    }

    pub fn set_tile(
        &mut self,
        layer_index: usize,
        layer: &LayerInstance,
        tile: &TileInstance,
        config: &LdtkLevelConfig,
        patterns: &LdtkPatterns,
        mode: &LdtkLevelLoaderMode,
    ) {
        self.try_create_new_layer(layer_index, layer);

        let (pattern, texture, _, _) = self.layers[layer_index].as_mut().unwrap();
        let tile_size = texture.desc.tile_size;
        let tile_index = IVec2 {
            x: tile.px[0] / tile_size.x as i32,
            y: match mode {
                LdtkLevelLoaderMode::Tilemap => -tile.px[1] / tile_size.y as i32 - 1,
                LdtkLevelLoaderMode::MapPattern => {
                    patterns.pattern_size.y as i32 - tile.px[1] / tile_size.y as i32 - 1
                }
            },
        };
        let atlas_index = tile.tile_id;

        if let Some(ser_tile) = pattern.tiles.get_mut(tile_index) {
            let TileTexture::Static(tile_layers) = &mut ser_tile.texture else {
                panic!(
                    "Trying to insert multiple layers into a animated tile at {}!",
                    tile_index
                );
            };
            tile_layers.push(TileLayer {
                atlas_index,
                ..Default::default()
            });
        } else {
            let mut builder = TileBuilder::new().with_tint(LinearRgba::new(1., 1., 1., tile.alpha));
            builder = {
                if let Some(anim) = config.animation_mapper.get(&(atlas_index as u32)) {
                    let animation = pattern.animations.register(anim.clone());
                    builder.with_animation(animation)
                } else {
                    let flip = tile.flip.reverse_bits() >> 30 & 0b11;
                    builder.with_layer(
                        0,
                        TileLayer {
                            #[cfg(feature = "atlas")]
                            texture_index: 0,
                            atlas_index,
                            flip: TileFlip::from_bits(flip as u32).unwrap(),
                        },
                    )
                }
            };

            pattern.tiles.tiles.insert(tile_index, builder);
        }
    }

    pub fn set_entity(&mut self, entity: PackedLdtkEntity) {
        self.entities.push(entity);
    }

    fn try_create_new_layer(&mut self, layer_index: usize, layer: &LayerInstance) {
        let tileset = self
            .tilesets
            .get(&layer.tileset_def_uid.unwrap())
            .cloned()
            .unwrap();

        if self.layers[layer_index].is_some() {
            return;
        }

        let aabb = GridRect::from_min_max(
            IVec2::new(0, -layer.c_hei + 1),
            IVec2::new(layer.c_wid - 1, 0),
        );

        self.layers[layer_index] = Some((
            TilemapPattern {
                label: Some(layer.identifier.clone()),
                tiles: TileBuffer {
                    aabb,
                    tiles: HashMap::new(),
                },
                animations: Default::default(),
                #[cfg(feature = "algorithm")]
                path_tiles: TileBuffer {
                    aabb,
                    tiles: HashMap::new(),
                },
                #[cfg(feature = "physics")]
                physics_tiles: SerializablePhysicsSource::Buffer(TileBuffer {
                    aabb,
                    tiles: HashMap::new(),
                }),
            },
            tileset,
            LayerIid(layer.iid.clone()),
            layer.opacity,
        ));
    }

    pub fn apply_all(
        &mut self,
        commands: &mut Commands,
        ldtk_patterns: &mut LdtkPatterns,
        entity_registry: &LdtkEntityRegistry,
        entity_tag_registry: &LdtkEntityTagRegistry,
        config: &LdtkLevelConfig,
        ldtk_assets: &LdtkAssets,
        asset_server: &AssetServer,
        material_assets: &mut Assets<StandardTilemapMaterial>,
        textures_assets: &mut Assets<TilemapTextures>,
        #[cfg(feature = "algorithm")] path_tilemaps: &mut PathTilemaps,
    ) {
        match self.ty {
            LdtkLevelLoaderMode::Tilemap => {
                let mut layers = HashMap::with_capacity(self.layers.len());
                let mut entities = HashMap::with_capacity(self.entities.len());

                self.entities.drain(..).for_each(|entity| {
                    let mut ldtk_entity =
                        commands.spawn((entity.transform.clone(), entity.iid.clone()));
                    entities.insert(entity.iid.clone(), ldtk_entity.id());
                    entity.instantiate(
                        &mut ldtk_entity,
                        entity_registry,
                        entity_tag_registry,
                        config,
                        ldtk_assets,
                        asset_server,
                    );
                });

                self.layers
                    .drain(..)
                    .enumerate()
                    .filter_map(|(i, e)| if let Some(e) = e { Some((i, e)) } else { None })
                    .for_each(|(index, (pattern, texture, iid, opacity))| {
                        let tilemap_entity = commands.spawn_empty().id();
                        let mut tilemap = StandardTilemapBundle {
                            name: TilemapName(pattern.label.clone().unwrap()),
                            ty: TilemapType::Square,
                            tile_render_size: TileRenderSize(texture.desc.tile_size.as_vec2()),
                            slot_size: TilemapSlotSize(texture.desc.tile_size.as_vec2()),
                            textures: textures_assets
                                .add(TilemapTextures::single(texture.clone(), config.filter_mode)),
                            storage: TilemapStorage::new(DEFAULT_CHUNK_SIZE, tilemap_entity),
                            transform: TilemapTransform {
                                translation: self.translation,
                                z_index: self.base_z_index - index as f32 - 1.,
                                ..Default::default()
                            },
                            material: material_assets.add(StandardTilemapMaterial::default()),
                            layer_opacities: TilemapLayerOpacities([opacity; 4].into()),
                            animations: pattern.animations.clone(),
                            ..Default::default()
                        };

                        tilemap
                            .storage
                            .fill_with_buffer(commands, IVec2::ZERO, pattern.tiles);

                        #[cfg(feature = "algorithm")]
                        if let Some((path_layer, path_tilemap)) = &self.path_layer {
                            if path_layer.parent == tilemap.name.0 {
                                path_tilemaps.insert(
                                    tilemap_entity,
                                    PathTilemap {
                                        storage: ChunkedStorage::from_mapper(
                                            path_tilemap.clone(),
                                            None,
                                        ),
                                    },
                                );
                            }
                        }

                        #[cfg(feature = "physics")]
                        if let Some((physics_layer, physics_data, size)) = &self.physics_layer {
                            if pattern.label.clone().unwrap() == physics_layer.parent {
                                commands
                                    .entity(tilemap_entity)
                                    .insert(DataPhysicsTilemap::new(
                                        IVec2::new(0, -(size.y as i32)),
                                        physics_data.clone(),
                                        *size,
                                        physics_layer.air,
                                        physics_layer.tiles.clone().unwrap_or_default(),
                                    ));
                            }
                        }

                        commands
                            .entity(tilemap_entity)
                            .insert((tilemap, iid.clone()));
                        layers.insert(iid, tilemap_entity);
                    });

                let bg = commands.spawn(self.background.clone()).id();

                commands.entity(self.level_entity).insert((
                    LdtkLoadedLevel {
                        identifier: self.level.identifier.clone(),
                        layers,
                        entities,
                        background: bg,
                    },
                    SpatialBundle {
                        transform: Transform::from_translation(self.translation.extend(0.)),
                        ..Default::default()
                    },
                    LevelIid(self.level.iid.clone()),
                ));
            }
            LdtkLevelLoaderMode::MapPattern => {
                self.layers
                    .drain(..)
                    .enumerate()
                    .for_each(|(layer_index, p)| {
                        #[allow(unused_mut)]
                        let Some((mut pattern, texture, iid, _)) = p
                        else {
                            return;
                        };

                        #[cfg(feature = "algorithm")]
                        if let Some((path_layer, path_tiles)) = &self.path_layer {
                            if path_layer.parent == pattern.label.clone().unwrap() {
                                pattern.path_tiles.tiles = path_tiles.clone();
                            }
                        }

                        #[cfg(feature = "physics")]
                        if let Some((physics_layer, physics_data, size)) =
                            self.physics_layer.as_ref()
                        {
                            pattern.physics_tiles =
                                SerializablePhysicsSource::Data(DataPhysicsTilemap::new(
                                    IVec2::ZERO,
                                    physics_data.clone(),
                                    *size,
                                    physics_layer.air,
                                    physics_layer.tiles.clone().unwrap_or_default(),
                                ));
                        }

                        ldtk_patterns.add_pattern(
                            layer_index,
                            &iid,
                            pattern,
                            &Some(texture),
                            &self.level.identifier,
                        );

                        ldtk_patterns
                            .add_background(&self.level.identifier, self.background.clone());
                    });

                commands.entity(self.level_entity).despawn();
            }
        }
    }

    #[cfg(feature = "algorithm")]
    pub fn assign_path_layer(
        &mut self,
        path: path::LdtkPathLayer,
        tilemap: HashMap<IVec2, crate::tilemap::algorithm::path::PathTile>,
    ) {
        self.path_layer = Some((path, tilemap));
    }

    #[cfg(feature = "physics")]
    pub fn assign_physics_layer(
        &mut self,
        physics_layer: physics::LdtkPhysicsLayer,
        physics_data: Vec<i32>,
        size: UVec2,
    ) {
        self.physics_layer = Some((physics_layer, physics_data, size));
    }
}