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
//! Node management.
//!
//! A node is an instance of a building.

use std::collections::BTreeMap;
use std::num::NonZeroUsize;

use derive_new::new;
use legion::systems::CommandBuffer;
use legion::world::SubWorld;
use legion::{Entity, EntityStore};
use smallvec::{smallvec, SmallVec};
use typed_builder::TypedBuilder;

use crate::def::feature::Feature;
pub use crate::def::node::NodeId as Id;
use crate::def::{building, CustomizableName};
use crate::space::{Matrix, Position};
use crate::sun::LightStats;
use crate::{
    appearance, cargo, def, defense, gas, liquid, population, save, units, vehicle, SetupEcs,
};

codegen::component_depends! {
    Id = (
        LightStats,
        appearance::Appearance,
        cargo::StorageList,
        cargo::StorageCapacity,
        liquid::StorageList,
        gas::StorageList,
        gas::StorageCapacity,
        population::StorageList,
    ) + ?(
        defense::Core,
        population::Housing, // TODO multiple housing provisions?
        vehicle::RailPump,
        liquid::Pump,
        gas::Pump,
    )
}

/// A component applied to child entities of a node.
#[derive(Debug, Clone, new, getset::CopyGetters)]
pub struct Child {
    /// The entity ID of the parent node entity.
    #[getset(get_copy = "pub")]
    parent: Entity,
}

/// Indicates that a node is added
#[derive(Debug, new, getset::CopyGetters)]
pub struct AddEvent {
    /// The added node ID
    #[getset(get_copy = "pub")]
    node:   Id,
    /// The added node entity
    #[getset(get_copy = "pub")]
    entity: Entity,
}

/// Indicates that a node is flagged for removal
#[derive(Debug, new, getset::CopyGetters)]
pub struct RemoveEvent {
    /// The removed node
    #[getset(get_copy = "pub")]
    node: Id,
}

/// Indicates that nodes have been removed
#[derive(Debug, new, getset::CopyGetters)]
pub struct PostRemoveEvent {
    /// Number of nodes removed
    #[getset(get_copy = "pub")]
    count: NonZeroUsize,
}

/// Tracks the nodes in the world
#[derive(Default)]
pub struct Index {
    index: BTreeMap<Id, Entity>,
}

impl Index {
    /// Retrieves the entity ID for the given node
    pub fn get(&self, id: Id) -> Option<Entity> { self.index.get(&id).copied() }
}

#[codegen::system(Command)]
fn delete_nodes(
    cmd_buf: &mut legion::systems::CommandBuffer,
    #[resource] index: &mut Index,
    #[subscriber] removals: impl Iterator<Item = RemoveEvent>,
    #[publisher] post_remove_pub: impl FnMut(PostRemoveEvent),
) {
    let mut count = 0_usize;

    // queue deletion requests for the next event loop
    for removal in removals {
        let entity = index.index.remove(&removal.node).expect("Removing nonexistent node entity");
        cmd_buf.remove(entity);
        count += 1;
    }

    if let Some(count) = NonZeroUsize::new(count) {
        post_remove_pub(PostRemoveEvent { count });
    }
}

/// An event to schedule requests to initialize new nodes.
///
/// Do not subscribe to this event for listening to node creation.
/// Use [`AddEvent`] instead.
#[derive(TypedBuilder)]
pub struct CreationRequest {
    /// Type ID of the building to create.
    type_id:  building::Id,
    /// The position of the node.
    position: Position,
    /// The rotation matrix of the node.
    rotation: Matrix,
}

#[codegen::system(Command)]
fn create_new_node(
    entities: &mut CommandBuffer,
    #[subscriber] requests: impl Iterator<Item = CreationRequest>,
    #[publisher] add_events: impl FnMut(AddEvent),
    #[resource(no_init)] def: &save::GameDefinition,
    #[resource] index: &mut Index,
) {
    for request in requests {
        let building = &def[request.type_id];

        let id = loop {
            let id = Id::new(rand::random());
            if !index.index.contains_key(&id) {
                break id;
            }
        };

        let arbitrary_liquid_type = def.liquid_recipes().default();
        let liquids: SmallVec<_> = building
            .storage()
            .liquid()
            .iter()
            .map(|storage| {
                entities.push((
                    liquid::Storage::new(arbitrary_liquid_type),
                    liquid::NextStorageType::new(arbitrary_liquid_type),
                    liquid::StorageCapacity::new(storage.capacity()),
                    liquid::StorageSize::new(units::LiquidVolume(0.)),
                    liquid::NextStorageSize::new(units::LiquidVolume(0.)),
                    CustomizableName::Original(storage.name().clone()),
                ))
            })
            .collect();

        let entity = entities.push((
            id,
            request.type_id,
            CustomizableName::Original(building.name().clone()),
            request.position,
            appearance::Appearance::new(
                building
                    .shapes()
                    .iter()
                    .map(|shape| {
                        appearance::Component::builder()
                            .unit(shape.unit())
                            .matrix(request.rotation * shape.transform())
                            .texture(shape.texture())
                            .build()
                    })
                    .collect(),
            ),
            units::Portion::full(building.hitpoint()),
            LightStats::default(),
            cargo::StorageList::new(smallvec![]),
            cargo::StorageCapacity::new(building.storage().cargo()),
            liquid::StorageList::new(liquids.clone()),
            gas::StorageList::new(smallvec![]),
            gas::StorageCapacity::new(building.storage().gas()),
        ));

        for liquid in liquids {
            entities.add_component(liquid, Child::new(entity));
        }

        init_features(entities, entity, building.features());

        index.index.insert(id, entity);

        add_events(AddEvent { node: id, entity })
    }
}

/// An event to schedule requests to initialize saved nodes.
///
/// Do not subscribe to this event for listening to node creation.
/// Use [`AddEvent`] instead.
#[derive(TypedBuilder)]
pub struct LoadRequest {
    /// The saved node.
    save: Box<def::node::Node>,
}

#[codegen::system(Command)]
fn create_saved_node(
    entities: &mut CommandBuffer,
    #[subscriber] requests: impl Iterator<Item = LoadRequest>,
    #[publisher] add_events: impl FnMut(AddEvent),
    #[resource(no_init)] def: &save::GameDefinition,
    #[resource] index: &mut Index,
) {
    for LoadRequest { save } in requests {
        let building = &def[save.building()];

        let cargo_list = save
            .cargo()
            .iter()
            .map(|entry| {
                let entity = entities.push((
                    cargo::Storage::new(entry.ty()),
                    cargo::StorageSize::new(entry.size()),
                    cargo::NextStorageSize::new(entry.size()),
                ));
                (entry.ty(), entity)
            })
            .collect();

        let liquid_storages = building.storage().liquid();
        let liquid_list: SmallVec<_> = save
            .liquid()
            .iter()
            .zip(liquid_storages.iter())
            .map(|(entry, storage_def)| {
                entities.push((
                    liquid::Storage::new(entry.ty()),
                    liquid::NextStorageType::new(entry.ty()),
                    liquid::StorageCapacity::new(storage_def.capacity()),
                    liquid::StorageSize::new(entry.volume()),
                    liquid::NextStorageSize::new(entry.volume()),
                    storage_def.name().clone(),
                ))
            })
            .collect();
        let gas_list = save
            .gas()
            .iter()
            .map(|entry| {
                let entity = entities.push((
                    gas::Storage::new(entry.ty()),
                    gas::StorageSize::new(entry.volume()),
                    gas::NextStorageSize::new(entry.volume()),
                ));
                (entry.ty(), entity)
            })
            .collect();

        let entity = entities.push((
            save.id(),
            save.building(),
            save.name().clone(),
            save.position(),
            appearance::Appearance::new(
                building
                    .shapes()
                    .iter()
                    .map(|shape| {
                        appearance::Component::builder()
                            .unit(shape.unit())
                            .matrix(save.rotation() * shape.transform())
                            .texture(shape.texture())
                            .build()
                    })
                    .collect(),
            ),
            units::Portion::new(save.hitpoint(), building.hitpoint()),
            LightStats::default(),
            cargo::StorageList::new(cargo_list),
            cargo::StorageCapacity::new(building.storage().cargo()),
            liquid::StorageList::new(liquid_list.clone()),
            gas::StorageList::new(gas_list),
            gas::StorageCapacity::new(building.storage().gas()),
        ));

        for liquid in liquid_list {
            entities.add_component(liquid, Child::new(entity));
        }

        init_features(entities, entity, building.features());

        index.index.insert(save.id(), entity);
        add_events(AddEvent { node: save.id(), entity })
    }
}

fn init_features(entities: &mut CommandBuffer, entity: Entity, features: &[Feature]) {
    for feature in features {
        match feature {
            Feature::Core => entities.add_component(entity, defense::Core),
            Feature::ProvidesHousing(housing) => {
                entities.add_component(entity, population::Housing::new(housing.storage()))
            }
            Feature::Reaction(_) => todo!(),
            Feature::RailPump(_) => {
                // TODO refactor to entity list to support catalysts
            }
            Feature::LiquidPump(_) => {
                // TODO refactor to entity list to support catalysts
            }
            Feature::GasPump(_) => {
                // TODO refactor to entity list to support catalysts
            }
            Feature::SecureEntry(_) => todo!(),
            Feature::SecureExit(_) => todo!(),
        }
    }
}

#[codegen::system(Visualize)]
#[read_component(Id)]
#[read_component(building::Id)]
#[read_component(CustomizableName)]
#[read_component(Position)]
#[read_component(appearance::Appearance)]
#[read_component(units::Portion<units::Hitpoint>)]
#[read_component(cargo::StorageList)]
#[read_component(gas::StorageList)]
#[read_component(liquid::StorageList)]
fn save_nodes(world: &mut SubWorld, #[subscriber] requests: impl Iterator<Item = save::Request>) {
    use legion::IntoQuery;

    let mut query = <(
        &Id,
        &building::Id,
        &CustomizableName,
        &Position,
        &appearance::Appearance,
        &units::Portion<units::Hitpoint>,
        &cargo::StorageList,
        &gas::StorageList,
        &liquid::StorageList,
    )>::query();

    let (query_world, ra_world) = world.split_for_query(&query);

    for request in requests {
        for (
            &id,
            &building,
            name,
            &position,
            _appearance, // TODO use this
            hitpoint,
            cargo_list,
            gas_list,
            liquid_list,
        ) in query.iter(&query_world)
        {
            let cargo = cargo_list
                .storages()
                .iter()
                .map(|&(cargo_ty, storage)| {
                    let storage = ra_world.entry_ref(storage).expect("Dangling entity reference");
                    // TODO confirm that the deserialized state will setup NextStorageSize correctly.
                    let size = storage
                        .get_component::<cargo::StorageSize>()
                        .expect("Malformed entity reference");
                    def::node::CargoStorageEntry::new(cargo_ty, size.size())
                })
                .collect();
            let gas = gas_list
                .storages()
                .iter()
                .map(|&(gas_ty, storage)| {
                    let storage = ra_world.entry_ref(storage).expect("Dangling entity reference");
                    // TODO confirm that the deserialized state will setup NextStorageSize correctly.
                    let size = storage
                        .get_component::<gas::StorageSize>()
                        .expect("Malformed entity reference");
                    def::node::GasStorageEntry::new(gas_ty, size.size())
                })
                .collect();
            let liquid = liquid_list
                .storages()
                .iter()
                .map(|&storage| {
                    let storage = ra_world.entry_ref(storage).expect("Dangling entity reference");
                    // TODO confirm that the deserialized state will setup NextStorageType and NextStorageSize correctly.
                    let liquid_ty = storage
                        .get_component::<liquid::Storage>()
                        .expect("Malformed entity reference")
                        .liquid();
                    let size = storage
                        .get_component::<liquid::StorageSize>()
                        .expect("Malformed entity reference");
                    def::node::LiquidStorageEntry::new(liquid_ty, size.size())
                })
                .collect();

            let node = def::node::Node::builder()
                .id(id)
                .building(building)
                .name(name.clone())
                .position(position)
                .rotation(Matrix::identity()) // TODO persist rotation
                .hitpoint(hitpoint.current())
                .cargo(cargo)
                .gas(gas)
                .liquid(liquid)
                .build();

            {
                let mut file = request.file();
                file.state_mut().nodes_mut().push(node);
            }
        }
    }
}

/// Initializes ECS
pub fn setup_ecs(setup: SetupEcs) -> SetupEcs {
    setup
        .uses(delete_nodes_setup)
        .uses(create_new_node_setup)
        .uses(create_saved_node_setup)
        .uses(save_nodes_setup)
}