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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use std::{collections::VecDeque, time::Duration};

use ahash::AHashMap;
use bevy::prelude::*;
use de_core::{
    gamestate::GameState,
    objects::{Local, ObjectTypeComponent},
    player::PlayerComponent,
    state::AppState,
};
use de_index::SpatialQuery;
use de_objects::SolidObjects;
use de_pathing::{PathQueryProps, PathTarget};
use de_signs::{
    LineLocation, UpdateLineEndEvent, UpdateLineLocationEvent, UpdatePoleLocationEvent,
};
use de_spawner::{ObjectCounter, SpawnLocalActiveEvent};
use de_types::{
    objects::{ActiveObjectType, ObjectType, UnitType, PLAYER_MAX_UNITS},
    player::Player,
    projection::{ToAltitude, ToFlat},
};
use parry2d::bounding_volume::Aabb;
use parry3d::math::Isometry;

const MANUFACTURING_TIME: Duration = Duration::from_secs(2);
const DEFAULT_TARGET_DISTANCE: f32 = 20.;

pub(crate) struct ManufacturingPlugin;

impl Plugin for ManufacturingPlugin {
    fn build(&self, app: &mut App) {
        app.add_event::<EnqueueAssemblyEvent>()
            .add_event::<ChangeDeliveryLocationEvent>()
            .add_event::<DeliverEvent>()
            .add_systems(
                PreUpdate,
                (
                    change_locations.in_set(ManufacturingSet::ChangeLocations),
                    check_spawn_locations.before(ManufacturingSet::Produce),
                    produce.in_set(ManufacturingSet::Produce),
                    deliver
                        .after(ManufacturingSet::ChangeLocations)
                        .after(ManufacturingSet::Produce),
                )
                    .run_if(in_state(GameState::Playing)),
            )
            .add_systems(Update, enqueue.run_if(in_state(GameState::Playing)))
            .add_systems(PostUpdate, configure.run_if(in_state(AppState::InGame)));
    }
}

#[derive(Copy, Clone, Hash, Debug, PartialEq, Eq, SystemSet)]
enum ManufacturingSet {
    ChangeLocations,
    Produce,
}

/// Send this event to change target location of freshly manufactured units.
#[derive(Event)]
pub struct ChangeDeliveryLocationEvent {
    factory: Entity,
    position: Vec2,
}

impl ChangeDeliveryLocationEvent {
    pub fn new(factory: Entity, position: Vec2) -> Self {
        Self { factory, position }
    }

    fn factory(&self) -> Entity {
        self.factory
    }

    fn position(&self) -> Vec2 {
        self.position
    }
}

/// Send this event to enqueue a unit to be manufactured by a factory.
#[derive(Event)]
pub struct EnqueueAssemblyEvent {
    factory: Entity,
    unit: UnitType,
}

impl EnqueueAssemblyEvent {
    /// # Arguments
    ///
    /// `factory` - the building to produce the unit.
    ///
    /// `unit` - unit to be produced.
    pub fn new(factory: Entity, unit: UnitType) -> Self {
        Self { factory, unit }
    }

    fn factory(&self) -> Entity {
        self.factory
    }

    fn unit(&self) -> UnitType {
        self.unit
    }
}

#[derive(Event)]
struct DeliverEvent {
    factory: Entity,
    unit: UnitType,
}

impl DeliverEvent {
    fn new(factory: Entity, unit: UnitType) -> Self {
        Self { factory, unit }
    }

    fn factory(&self) -> Entity {
        self.factory
    }

    fn unit(&self) -> UnitType {
        self.unit
    }
}

#[derive(Component)]
struct DeliveryLocation(Vec2);

impl DeliveryLocation {
    fn initial(local_aabb: Aabb, transform: &Transform) -> Self {
        let target = Vec2::new(
            local_aabb.maxs.x + DEFAULT_TARGET_DISTANCE,
            0.5 * (local_aabb.mins.y + local_aabb.maxs.y),
        );
        Self(transform.transform_point(target.to_msl()).to_flat())
    }
}

/// An assembly line attached to every building and capable of production of
/// any units.
#[derive(Component, Default)]
pub struct AssemblyLine {
    blocks: Blocks,
    queue: VecDeque<ProductionItem>,
}

impl AssemblyLine {
    fn blocks_mut(&mut self) -> &mut Blocks {
        &mut self.blocks
    }

    /// Returns the first item in the assembly line (i.e. the first one to be
    /// delivered).
    fn current(&self) -> Option<UnitType> {
        self.queue.front().map(|item| item.unit())
    }

    /// Put another unit into the manufacturing queue.
    fn enqueue(&mut self, unit: UnitType, time: Duration) {
        let mut item = ProductionItem::new(unit);
        if self.queue.is_empty() {
            item.restart(time);
        }
        self.queue.push_back(item);
    }

    /// Update the production line.
    ///
    /// This method should be called repeatedly and during every tick until it
    /// returns None. The returned values correspond to finished units.
    ///
    /// # Arguments
    ///
    /// * `time` - elapsed time since a fixed point in time in the past.
    fn produce(&mut self, time: Duration) -> Option<UnitType> {
        if let Some(time_past) = self.queue.front().and_then(|item| item.finished(time)) {
            if self.blocks.blocked() {
                self.queue.front_mut().unwrap().block(time);
                None
            } else {
                let item = self.queue.pop_front().unwrap();

                if item.is_active() {
                    if let Some(next) = self.queue.front_mut() {
                        next.restart(time - time_past);
                    }
                }

                Some(item.unit())
            }
        } else {
            None
        }
    }
}

/// When the assembly line is blocked for any reason, the last unit is produced
/// up until 100% competition but is not delivered and next unit is not
/// started.
#[derive(Default)]
struct Blocks {
    /// Whether spawn location is currently occupied.
    spawn_location: bool,
    map_capacity: bool,
}

impl Blocks {
    fn blocked(&self) -> bool {
        self.spawn_location || self.map_capacity
    }
}

/// A single unit being manufactured / enqueued for manufacturing in an
/// assembly line.
struct ProductionItem {
    /// Total accumulated production time of the item until the last
    /// stop/restart to the manufacturing.
    accumulated: Duration,
    /// Time elapsed since a fixed point in the past until when manufacturing
    /// of the unit was restarted for the last time.
    restarted: Option<Duration>,
    unit: UnitType,
}

impl ProductionItem {
    fn new(unit: UnitType) -> Self {
        Self {
            accumulated: Duration::ZERO,
            restarted: None,
            unit,
        }
    }

    fn unit(&self) -> UnitType {
        self.unit
    }

    /// Returns true if the unit is actively manufactured.
    fn is_active(&self) -> bool {
        self.restarted.is_some()
    }

    /// Restarts (stops and starts) manufacturing of the unit.
    fn restart(&mut self, time: Duration) {
        self.stop(time);
        self.restarted = Some(time);
    }

    /// Stops manufacturing of the unit if it is currently being manufactured.
    ///
    /// Total accumulated manufacturing time is clipped to the time it takes to
    /// produce the unit.
    fn stop(&mut self, time: Duration) {
        if let Some(last) = self.restarted {
            self.accumulated += time - last;
            if self.accumulated > MANUFACTURING_TIME {
                self.accumulated = MANUFACTURING_TIME;
            }
        }
        self.restarted = None;
    }

    /// If the item is already finished, stop the manufacturing and clip its
    /// due time to just now.
    fn block(&mut self, time: Duration) {
        if self.progress(time) >= MANUFACTURING_TIME {
            self.accumulated = MANUFACTURING_TIME;
            self.restarted = Some(time);
        }
    }

    /// Returns None if the unit is not yet finished. Otherwise, it returns for
    /// how long it has been finished.
    fn finished(&self, time: Duration) -> Option<Duration> {
        let progress = self.progress(time);
        if progress >= MANUFACTURING_TIME {
            Some(progress - MANUFACTURING_TIME)
        } else {
            None
        }
    }

    /// Returns for how long cumulatively the unit has been manufactured.
    fn progress(&self, time: Duration) -> Duration {
        self.accumulated
            + self
                .restarted
                .map_or(Duration::ZERO, |restarted| time - restarted)
    }
}

fn configure(
    mut commands: Commands,
    solids: SolidObjects,
    new: Query<(Entity, &Transform, &ObjectTypeComponent), Added<Local>>,
    mut pole_events: EventWriter<UpdatePoleLocationEvent>,
    mut line_events: EventWriter<UpdateLineLocationEvent>,
) {
    for (entity, transform, &object_type) in new.iter() {
        let solid = solids.get(*object_type);
        if let Some(factory) = solid.factory() {
            let start = transform.transform_point(factory.position().to_msl());
            let local_aabb = solid.ichnography().local_aabb();
            let delivery_location = DeliveryLocation::initial(local_aabb, transform);
            pole_events.send(UpdatePoleLocationEvent::new(entity, delivery_location.0));
            let end = delivery_location.0.to_msl();
            line_events.send(UpdateLineLocationEvent::new(
                entity,
                LineLocation::new(start, end),
            ));
            commands
                .entity(entity)
                .insert((AssemblyLine::default(), delivery_location));
        }
    }
}

fn change_locations(
    mut events: EventReader<ChangeDeliveryLocationEvent>,
    mut locations: Query<&mut DeliveryLocation>,
    mut pole_events: EventWriter<UpdatePoleLocationEvent>,
    mut line_events: EventWriter<UpdateLineEndEvent>,
) {
    for event in events.read() {
        if let Ok(mut location) = locations.get_mut(event.factory()) {
            let owner = event.factory();
            location.0 = event.position();
            pole_events.send(UpdatePoleLocationEvent::new(owner, event.position()));
            let end = event.position().to_msl();
            line_events.send(UpdateLineEndEvent::new(owner, end));
        }
    }
}

fn enqueue(
    time: Res<Time>,
    mut events: EventReader<EnqueueAssemblyEvent>,
    mut lines: Query<&mut AssemblyLine>,
) {
    for event in events.read() {
        let Ok(mut line) = lines.get_mut(event.factory()) else {
            continue;
        };
        info!(
            "Enqueueing manufacturing of {} in {:?}.",
            event.unit(),
            event.factory()
        );
        line.enqueue(event.unit(), time.elapsed());
    }
}

fn check_spawn_locations(
    solids: SolidObjects,
    space: SpatialQuery<Entity>,
    mut factories: Query<(Entity, &ObjectTypeComponent, &Transform, &mut AssemblyLine)>,
) {
    for (entity, &object_type, transform, mut line) in factories.iter_mut() {
        line.blocks_mut().spawn_location = match line.current() {
            Some(unit_type) => {
                let factory = solids.get(*object_type).factory().unwrap();
                let collider = solids
                    .get(ObjectType::Active(ActiveObjectType::Unit(unit_type)))
                    .collider();

                let spawn_point = transform.transform_point(factory.position().to_msl());
                let isometry = Isometry::translation(spawn_point.x, spawn_point.y, spawn_point.z);
                let mut aabb = collider.aabb().transform_by(&isometry);
                aabb.mins.y = f32::NEG_INFINITY;
                aabb.maxs.y = f32::INFINITY;

                space.query_aabb(&aabb, Some(entity)).next().is_some()
            }
            None => false,
        };
    }
}

fn produce(
    time: Res<Time>,
    counter: Res<ObjectCounter>,
    mut factories: Query<(Entity, &PlayerComponent, &mut AssemblyLine)>,
    mut deliver_events: EventWriter<DeliverEvent>,
) {
    let mut counts: AHashMap<Player, u32> = AHashMap::from_iter(
        counter
            .counters()
            .map(|(&player, counter)| (player, counter.unit_count())),
    );

    for (factory, &player, mut assembly) in factories.iter_mut() {
        let player_count = counts.entry(*player).or_default();

        loop {
            assembly.blocks_mut().map_capacity = *player_count >= PLAYER_MAX_UNITS;

            let Some(unit_type) = assembly.produce(time.elapsed()) else {
                break;
            };
            *player_count += 1;

            deliver_events.send(DeliverEvent::new(factory, unit_type));
        }
    }
}

fn deliver(
    solids: SolidObjects,
    mut deliver_events: EventReader<DeliverEvent>,
    mut spawn_active_events: EventWriter<SpawnLocalActiveEvent>,
    factories: Query<(
        &Transform,
        &ObjectTypeComponent,
        &PlayerComponent,
        &DeliveryLocation,
    )>,
) {
    for delivery in deliver_events.read() {
        info!(
            "Manufacturing of {} in {:?} just finished.",
            delivery.unit(),
            delivery.factory()
        );

        let (transform, &factory_object_type, &player, delivery_location) =
            factories.get(delivery.factory()).unwrap();
        let object_type = ActiveObjectType::Unit(delivery.unit());

        let factory = solids.get(*factory_object_type).factory().unwrap();
        debug_assert!(factory.products().contains(&delivery.unit()));
        let spawn_point = transform.transform_point(factory.position().to_msl());

        let path_target = PathTarget::new(
            delivery_location.0,
            PathQueryProps::new(0., f32::INFINITY),
            false,
        );
        spawn_active_events.send(SpawnLocalActiveEvent::new(
            object_type,
            Transform::from_translation(spawn_point),
            *player,
            Some(path_target),
        ));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_assembly_line() {
        let mut line = AssemblyLine::default();

        assert!(line.produce(Duration::from_secs(20)).is_none());
        line.enqueue(UnitType::Attacker, Duration::from_secs(21));
        line.enqueue(UnitType::Attacker, Duration::from_secs(21));

        assert!(line.produce(Duration::from_secs(22)).is_none());
        line.blocks_mut().map_capacity = true;
        assert!(line.produce(Duration::from_secs(25)).is_none());
        line.blocks_mut().map_capacity = false;
        assert_eq!(
            line.produce(Duration::from_secs(26)).unwrap(),
            UnitType::Attacker
        );
        assert!(line.produce(Duration::from_secs(26)).is_none());
        assert_eq!(
            line.produce(Duration::from_secs(27)).unwrap(),
            UnitType::Attacker
        );
        assert!(line.produce(Duration::from_secs(30)).is_none());

        line.enqueue(UnitType::Attacker, Duration::from_secs(50));
        line.enqueue(UnitType::Attacker, Duration::from_secs(51));

        assert!(line.produce(Duration::from_secs(51)).is_none());
        assert_eq!(
            line.produce(Duration::from_secs(61)).unwrap(),
            UnitType::Attacker
        );
        assert_eq!(
            line.produce(Duration::from_secs(63)).unwrap(),
            UnitType::Attacker
        );
        assert!(line.produce(Duration::from_secs(90)).is_none());
    }
}