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
//! Edge states.

use derive_new::new;
use getset::{CopyGetters, Getters};
use serde::{Deserialize, Serialize};
use traffloat_types::units;
use typed_builder::TypedBuilder;

use crate::building;
use crate::node::NodeId;

/// The state of an edge.
#[derive(Debug, Clone, Getters, CopyGetters, TypedBuilder, Serialize, Deserialize)]
#[cfg_attr(feature = "xy", derive(xylem::Xylem))]
#[cfg_attr(feature = "xy", xylem(derive(Deserialize)))]
pub struct Edge {
    /// The endpoints of an edge.
    #[getset(get_copy = "pub")]
    #[cfg_attr(feature = "xy", xylem(serde(flatten)))]
    endpoints: AlphaBeta,
    /// The radius of an edge.
    #[getset(get_copy = "pub")]
    radius:    f64,
    /// The hitpoint portion of the edge.
    #[getset(get_copy = "pub")]
    hitpoint:  units::Portion<units::Hitpoint>,
    /// The ducts built in the edge.
    #[getset(get = "pub")]
    #[cfg_attr(feature = "xy", xylem(serde(default)))]
    ducts:     Vec<Duct>,
}

/// The endpoints of an edge.
#[derive(Debug, Clone, Copy, CopyGetters, new, Serialize, Deserialize)]
#[cfg_attr(feature = "xy", derive(xylem::Xylem))]
#[cfg_attr(feature = "xy", xylem(derive(Deserialize), process))]
pub struct AlphaBeta {
    /// The "alpha" endpoint of an edge.
    #[getset(get_copy = "pub")]
    alpha: NodeId,
    /// The "beta" endpoint of an edge.
    #[getset(get_copy = "pub")]
    beta:  NodeId,
}

impl AlphaBeta {
    /// The edge endpoints, sorted.
    #[must_use]
    pub fn sorted(self) -> Self {
        if self.alpha > self.beta {
            Self { alpha: self.beta, beta: self.alpha }
        } else {
            self
        }
    }
}

/// An [`AlphaBeta`] wrapper with direction-insensitive equivalence and ordering.
#[derive(Debug, Clone, Copy)]
pub struct UndirectedAlphaBeta(pub AlphaBeta);

impl PartialEq for UndirectedAlphaBeta {
    fn eq(&self, other: &Self) -> bool {
        self.0.alpha == other.0.alpha && self.0.beta == other.0.beta
            || self.0.alpha == other.0.beta && self.0.beta == other.0.alpha
    }
}

impl Eq for UndirectedAlphaBeta {}

impl PartialOrd for UndirectedAlphaBeta {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) }
}

impl Ord for UndirectedAlphaBeta {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        let this = self.0.sorted();
        let that = other.0.sorted();
        this.alpha.cmp(&that.alpha).then_with(|| this.beta.cmp(&that.beta))
    }
}

/// The state of a duct.
#[derive(Debug, Clone, Getters, CopyGetters, TypedBuilder, Serialize, Deserialize)]
#[cfg_attr(feature = "xy", derive(xylem::Xylem))]
#[cfg_attr(feature = "xy", xylem(derive(Deserialize)))]
pub struct Duct {
    /// The position of the center of the duct, relative to the center of the edge.
    #[getset(get_copy = "pub")]
    center: nalgebra::Vector2<f64>,
    /// The radius of the duct.
    #[getset(get_copy = "pub")]
    radius: f64,
    /// The type of the duct.
    #[getset(get_copy = "pub")]
    ty:     DuctType,
}

/// The type of a duct.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "xy", derive(xylem::Xylem))]
#[cfg_attr(feature = "xy", xylem(derive(Deserialize), serde(tag = "type")))]
pub enum DuctType {
    /// A rail that vehicles can move along.
    ///
    /// The first parameter is the direction of the rail,
    /// or [`None`] if the rail is disabled.
    Rail(RailDuctType),
    /// A pipe that liquids can be transferred through.
    ///
    /// The first parameter is the direction of the pipe,
    /// or [`None`] if the rail is disabled.
    ///
    /// The second and third parameters are the liquid storage IDs in the endpoints.
    Liquid(LiquidDuctType),
    /// A cable that electricity can pass through.
    ///
    /// The first parameter specifies whether the cable is enabled.
    Electricity(ElectricityDuctType),
}

impl DuctType {
    /// Whether the duct is active.
    pub fn active(self) -> bool {
        match self {
            Self::Rail(ty) => ty.direction.is_some(),
            Self::Liquid(ty) => !matches!(ty, LiquidDuctType::Disabled),
            Self::Electricity(ty) => !ty.disabled,
        }
    }

    /// The direction of the duct, if any.
    pub fn direction(self) -> Option<Direction> {
        match self {
            Self::Rail(ty) => ty.direction,
            Self::Liquid(LiquidDuctType::AlphaToBeta { .. }) => Some(Direction::AlphaToBeta),
            Self::Liquid(LiquidDuctType::BetaToAlpha { .. }) => Some(Direction::BetaToAlpha),
            _ => None,
        }
    }
}

/// Details of a rail duct.
#[derive(Debug, Clone, Copy, PartialEq, Eq, CopyGetters, Serialize, Deserialize)]
pub struct RailDuctType {
    /// The direction of the rail.
    #[getset(get_copy = "pub")]
    direction: Option<Direction>,
}

/// Details of a liquid duct.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LiquidDuctType {
    /// A duct from alpha node to beta node.
    AlphaToBeta {
        /// The source storage ID in the alpha node.
        alpha_storage: building::storage::liquid::Id,
        /// The destination storage ID in the beta node.
        beta_storage:  building::storage::liquid::Id,
    },
    /// A duct from beta node to alpha node.
    BetaToAlpha {
        /// The source storage ID in the beta node.
        beta_storage:  building::storage::liquid::Id,
        /// The destination storage ID in the alpha node.
        alpha_storage: building::storage::liquid::Id,
    },
    /// A disabled duct.
    Disabled,
}

/// Details of a electricity duct.
#[derive(Debug, Clone, Copy, PartialEq, Eq, CopyGetters, Serialize, Deserialize)]
#[cfg_attr(feature = "xy", derive(xylem::Xylem))]
#[cfg_attr(feature = "xy", xylem(derive(Deserialize)))]
pub struct ElectricityDuctType {
    /// Whether the duct is disabled.
    #[getset(get_copy = "pub")]
    #[cfg_attr(feature = "xy", xylem(serde(default)))]
    disabled: bool,
}

/// A direction across an edge.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "xy", derive(xylem::Xylem))]
#[cfg_attr(feature = "xy", xylem(derive(Deserialize)))]
pub enum Direction {
    /// A direction starting from the alpha endpoint and ending at the beta endpoint
    AlphaToBeta,
    /// A direction starting from the beta endpoint and ending at the alpha endpoint
    BetaToAlpha,
}

#[cfg(feature = "xy")]
mod xy {
    use std::any::TypeId;

    use anyhow::Context as _;
    use serde::Deserialize;
    use xylem::id::GlobalIdStore;
    use xylem::{Context as _, DefaultContext, NoArgs, Processable, Xylem};

    use super::Direction;
    use crate::node::xy::NodeBuildingMap;
    use crate::{building, Schema};

    struct EdgeEndpointBuildings {
        alpha: building::Id,
        beta:  building::Id,
    }

    impl Processable<Schema> for super::AlphaBeta {
        fn postprocess(&mut self, context: &mut DefaultContext) -> anyhow::Result<()> {
            let map = context
                .get::<NodeBuildingMap>(TypeId::of::<()>())
                .expect("NodeBuildingMap not initialized");

            let alpha = map.get(self.alpha).expect("Dangling node reference");
            let beta = map.get(self.beta).expect("Dangling node reference");

            context.get_mut::<EdgeEndpointBuildings, _>(TypeId::of::<super::Edge>(), || {
                EdgeEndpointBuildings { alpha, beta }
            });

            Ok(())
        }
    }

    impl Xylem<Schema> for super::RailDuctType {
        type From = RailDuctTypeXylem;
        type Args = NoArgs;

        fn convert_impl(
            from: Self::From,
            _: &mut DefaultContext,
            _: &NoArgs,
        ) -> anyhow::Result<Self> {
            Ok(Self {
                direction: match from.dir {
                    MaybeDirection::AlphaToBeta => Some(Direction::AlphaToBeta),
                    MaybeDirection::BetaToAlpha => Some(Direction::BetaToAlpha),
                    MaybeDirection::Disabled => None,
                },
            })
        }
    }

    #[derive(Deserialize)]
    pub struct RailDuctTypeXylem {
        dir: MaybeDirection,
    }

    #[derive(Deserialize)]
    pub enum MaybeDirection {
        AlphaToBeta,
        BetaToAlpha,
        Disabled,
    }

    impl Xylem<Schema> for super::LiquidDuctType {
        type From = LiquidDuctTypeXylem;
        type Args = NoArgs;

        fn convert_impl(
            from: Self::From,
            context: &mut DefaultContext,
            _: &NoArgs,
        ) -> anyhow::Result<Self> {
            Ok(match from {
                LiquidDuctTypeXylem::AlphaToBeta { ref alpha_storage, ref beta_storage }
                | LiquidDuctTypeXylem::BetaToAlpha { ref beta_storage, ref alpha_storage } => {
                    fn resolve_storage(
                        building: building::Id,
                        storage: &str,
                        context: &mut DefaultContext,
                    ) -> anyhow::Result<building::storage::liquid::Id> {
                        let store = context
                            .get::<GlobalIdStore<Schema, building::storage::liquid::Def>>(
                                TypeId::of::<()>(),
                            )
                            .expect("Liquid storage definitions are not getting tracked");
                        let ids = store
                            .ids()
                            .get([building.index()].as_ref())
                            .context("No liquid storages in building")?;
                        let id = ids.iter().position(|id| id == storage).with_context(|| {
                            format!("No liquid storage named {} in building", storage)
                        })?;
                        Ok(building::storage::liquid::Id::new(id))
                    }

                    let &EdgeEndpointBuildings { alpha, beta } = context
                        .get::<EdgeEndpointBuildings>(TypeId::of::<super::Edge>())
                        .expect("Edge endpoints was not initialized");

                    let alpha = resolve_storage(alpha, alpha_storage, context)?;
                    let beta = resolve_storage(beta, beta_storage, context)?;
                    match from {
                        LiquidDuctTypeXylem::AlphaToBeta { .. } => {
                            Self::AlphaToBeta { alpha_storage: alpha, beta_storage: beta }
                        }
                        LiquidDuctTypeXylem::BetaToAlpha { .. } => {
                            Self::AlphaToBeta { beta_storage: beta, alpha_storage: alpha }
                        }
                        _ => unreachable!("Within match arm"),
                    }
                }
                LiquidDuctTypeXylem::Disabled => Self::Disabled,
            })
        }
    }

    #[derive(Deserialize)]
    #[serde(tag = "direction")]
    pub enum LiquidDuctTypeXylem {
        AlphaToBeta { alpha_storage: String, beta_storage: String },
        BetaToAlpha { beta_storage: String, alpha_storage: String },
        Disabled,
    }
}