rmf_site_format 0.0.2

File format parsing for rmf_site_editor
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
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
/*
 * Copyright (C) 2022 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

use crate::*;
#[cfg(feature = "bevy")]
use bevy::prelude::{Bundle, Component, Entity};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

pub const DEFAULT_DOOR_THICKNESS: f32 = 0.05;

#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(feature = "bevy", derive(Bundle))]
pub struct Door<T: RefTrait> {
    /// (left_anchor, right_anchor)
    pub anchors: Edge<T>,
    /// Name of the door. RMF requires each door name to be unique among all
    /// doors in the site.
    pub name: NameInSite,
    /// What kind of door is it.
    pub kind: DoorType,
    #[serde(skip)]
    pub marker: DoorMarker,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "bevy", derive(Component))]
pub enum DoorType {
    SingleSliding(SingleSlidingDoor),
    DoubleSliding(DoubleSlidingDoor),
    SingleSwing(SingleSwingDoor),
    DoubleSwing(DoubleSwingDoor),
    /// A custom model for the door. The reference frame for the model will be
    /// the center point of the two anchor points with the y axis facing the
    /// left anchor point and the z axis pointing upwards. The model must have
    /// its own door control plugin.
    Model(Model),
}

impl DoorType {
    pub fn single_sliding(&self) -> Option<&SingleSlidingDoor> {
        match self {
            Self::SingleSliding(v) => Some(v),
            _ => None,
        }
    }

    pub fn double_sliding(&self) -> Option<&DoubleSlidingDoor> {
        match self {
            Self::DoubleSliding(v) => Some(v),
            _ => None,
        }
    }

    pub fn single_swing(&self) -> Option<&SingleSwingDoor> {
        match self {
            Self::SingleSwing(v) => Some(v),
            _ => None,
        }
    }

    pub fn double_swing(&self) -> Option<&DoubleSwingDoor> {
        match self {
            Self::DoubleSwing(v) => Some(v),
            _ => None,
        }
    }

    pub fn model(&self) -> Option<&Model> {
        match self {
            Self::Model(v) => Some(v),
            _ => None,
        }
    }

    pub fn label(&self) -> &str {
        match self {
            Self::SingleSliding(_) => "Single Sliding",
            Self::DoubleSliding(_) => "Double Sliding",
            Self::SingleSwing(_) => "Single Swing",
            Self::DoubleSwing(_) => "Double Swing",
            Self::Model(_) => "Model",
        }
    }

    pub fn set_open(&mut self) {
        self.set_positions(1.0);
    }

    pub fn set_closed(&mut self) {
        self.set_positions(0.0);
    }

    pub fn set_positions(&mut self, position: f32) {
        match self {
            Self::SingleSliding(door) => {
                door.position = position;
            }
            Self::SingleSwing(door) => {
                door.position = position;
            }
            Self::DoubleSliding(door) => {
                door.left_position = position;
                door.right_position = position;
            }
            Self::DoubleSwing(door) => {
                door.left_position = position;
                door.right_position = position;
            }
            Self::Model(_) => {
                // Unsupported for now
            }
        }
    }
}

impl Default for DoorType {
    fn default() -> Self {
        SingleSlidingDoor::default().into()
    }
}

/// A single door that slides to one side
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct SingleSlidingDoor {
    /// Which side the door slides towards
    pub towards: Side,
    #[serde(default, skip_serializing_if = "is_default")]
    pub position: f32,
}

impl Default for SingleSlidingDoor {
    fn default() -> Self {
        Self {
            towards: Side::Left,
            position: 1.0,
        }
    }
}

impl From<SingleSlidingDoor> for DoorType {
    fn from(v: SingleSlidingDoor) -> Self {
        Self::SingleSliding(v)
    }
}

/// Two doors that each slide towards their own side
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct DoubleSlidingDoor {
    /// Length of the left door divided by the length of the right door
    pub left_right_ratio: f32,
    #[serde(default, skip_serializing_if = "is_default")]
    pub left_position: f32,
    #[serde(default, skip_serializing_if = "is_default")]
    pub right_position: f32,
}

impl DoubleSlidingDoor {
    /// Get the offset from the door center of the point where the doors
    /// separate. A value of 0.0 means the doors are even. A negative value
    /// means the left door is smaller while a positive value means the right
    /// door is smaller.
    pub fn compute_offset(&self, door_width: f32) -> f32 {
        let l = self.left_right_ratio * door_width / (self.left_right_ratio + 1.0);
        return door_width / 2.0 - l;
    }
}

impl Default for DoubleSlidingDoor {
    fn default() -> Self {
        Self {
            left_right_ratio: 1.0,
            left_position: 1.0,
            right_position: 1.0,
        }
    }
}

impl From<DoubleSlidingDoor> for DoorType {
    fn from(v: DoubleSlidingDoor) -> Self {
        Self::DoubleSliding(v)
    }
}

/// A single door that swings along a pivot on the left or right side
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct SingleSwingDoor {
    /// Which anchor (Left or Right) does the door pivot on
    pub pivot_on: Side,
    /// How does the door swing
    pub swing: Swing,
    #[serde(default, skip_serializing_if = "is_default")]
    pub position: f32,
}

impl Default for SingleSwingDoor {
    fn default() -> Self {
        Self {
            pivot_on: Side::Left,
            swing: Swing::Forward(Angle::Deg(90.0)),
            position: 1.0,
        }
    }
}

impl From<SingleSwingDoor> for DoorType {
    fn from(v: SingleSwingDoor) -> Self {
        Self::SingleSwing(v)
    }
}

/// Two doors, one left and one right, that each swing on their own pivot.
/// It is assumed their swinging parameters are symmetrical.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct DoubleSwingDoor {
    pub swing: Swing,
    /// Length of the left door divided by the length of the right door
    pub left_right_ratio: f32,
    #[serde(default, skip_serializing_if = "is_default")]
    pub left_position: f32,
    #[serde(default, skip_serializing_if = "is_default")]
    pub right_position: f32,
}

impl DoubleSwingDoor {
    /// Get the offset from the door center of the point where the doors
    /// separate. A value of 0.0 means the doors are even. A negative value
    /// means the left door is smaller while a positive value means the right
    /// door is smaller.
    pub fn compute_offset(&self, door_width: f32) -> f32 {
        let l = self.left_right_ratio * door_width / (self.left_right_ratio + 1.0);
        return door_width / 2.0 - l;
    }
}

impl Default for DoubleSwingDoor {
    fn default() -> Self {
        Self {
            swing: Swing::Forward(Angle::Deg(90.0)),
            left_right_ratio: 1.0,
            left_position: 1.0,
            right_position: 1.0,
        }
    }
}

impl From<DoubleSwingDoor> for DoorType {
    fn from(v: DoubleSwingDoor) -> Self {
        Self::DoubleSwing(v)
    }
}

impl From<Model> for DoorType {
    fn from(v: Model) -> Self {
        Self::Model(v)
    }
}

/// How the door swings relative to someone who is standing in the frame of door
/// with the left and right sides of their body aligned with the left and right
/// anchor points of the door.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
pub enum Swing {
    /// Swing forwards up to this (positive) angle
    Forward(Angle),
    /// Swing backwards up to this (positive) angle
    Backward(Angle),
    /// Swing each direction up to the given (positive) angle.
    Both { forward: Angle, backward: Angle },
}

impl Swing {
    pub fn label(&self) -> &'static str {
        match self {
            Self::Forward(_) => "Forward",
            Self::Backward(_) => "Backward",
            Self::Both { .. } => "Both",
        }
    }

    /// Given which side will be pivoted on, this function gives back
    /// 0. The initial angle of the swing
    /// 1. The angle that will be swept by the swing, relative to the initial angle
    /// For Both, the initial angle will be the backward angle and the sweep
    /// will reach the forward angle.
    pub fn swing_on_pivot(&self, pivot_on: Side) -> (Angle, Angle) {
        let pivot_sign = pivot_on.sign();
        let closed_angle = pivot_on.pivot_closed_angle();
        match self {
            Self::Forward(sweep) => (closed_angle, pivot_sign * *sweep),
            Self::Backward(sweep) => (closed_angle, -pivot_sign * *sweep),
            Self::Both { forward, backward } => (
                closed_angle - pivot_sign * *backward,
                pivot_sign * (*forward + *backward),
            ),
        }
    }

    pub fn assume_forward(&self) -> Self {
        match self {
            Self::Forward(angle) => Self::Forward(*angle),
            Self::Backward(angle) => Self::Forward(*angle),
            Self::Both { forward, .. } => Self::Forward(*forward),
        }
    }

    pub fn assume_backward(&self) -> Self {
        match self {
            Self::Forward(angle) => Self::Backward(*angle),
            Self::Backward(angle) => Self::Backward(*angle),
            Self::Both { backward, .. } => Self::Backward(*backward),
        }
    }

    pub fn assume_both(&self) -> Self {
        match self {
            Self::Forward(angle) => Self::Both {
                forward: *angle,
                backward: *angle,
            },
            Self::Backward(angle) => Self::Both {
                forward: *angle,
                backward: *angle,
            },
            Self::Both { forward, backward } => Self::Both {
                forward: *forward,
                backward: *backward,
            },
        }
    }
}

#[derive(Clone, Copy, Debug, Default)]
#[cfg_attr(feature = "bevy", derive(Component))]
pub struct DoorMarker;

#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "bevy", derive(Component))]
pub struct RecallDoorType {
    pub single_sliding: Option<DoorType>,
    pub double_sliding: Option<DoorType>,
    pub single_swing: Option<DoorType>,
    pub double_swing: Option<DoorType>,
    pub model: Option<DoorType>,
}

impl RecallDoorType {
    pub fn assume_single_sliding(&self, current: &DoorType) -> DoorType {
        current
            .single_sliding()
            .map(|x| x.clone().into())
            .unwrap_or(
                self.single_sliding
                    .as_ref()
                    .map(|x| x.clone())
                    .unwrap_or(SingleSlidingDoor::default().into()),
            )
    }

    pub fn assume_double_sliding(&self, current: &DoorType) -> DoorType {
        current
            .double_sliding()
            .map(|x| x.clone().into())
            .unwrap_or(
                self.double_sliding
                    .as_ref()
                    .map(|x| x.clone())
                    .unwrap_or(DoubleSlidingDoor::default().into()),
            )
    }

    pub fn assume_single_swing(&self, current: &DoorType) -> DoorType {
        current.single_swing().map(|x| x.clone().into()).unwrap_or(
            self.single_swing
                .as_ref()
                .map(|x| x.clone())
                .unwrap_or(SingleSwingDoor::default().into()),
        )
    }

    pub fn assume_double_swing(&self, current: &DoorType) -> DoorType {
        current.double_swing().map(|x| x.clone().into()).unwrap_or(
            self.double_swing
                .as_ref()
                .map(|x| x.clone())
                .unwrap_or(DoubleSwingDoor::default().into()),
        )
    }

    pub fn assume_model(&self, current: &DoorType) -> DoorType {
        current.model().map(|x| x.clone().into()).unwrap_or(
            self.model
                .as_ref()
                .map(|x| x.clone())
                .unwrap_or(DoorType::Model(Model::default())),
        )
    }
}

impl Recall for RecallDoorType {
    type Source = DoorType;

    fn remember(&mut self, source: &Self::Source) {
        match source {
            DoorType::SingleSliding(_) => {
                self.single_sliding = Some(source.clone());
            }
            DoorType::DoubleSliding { .. } => {
                self.double_sliding = Some(source.clone());
            }
            DoorType::SingleSwing { .. } => {
                self.single_swing = Some(source.clone());
            }
            DoorType::DoubleSwing(_) => {
                self.double_swing = Some(source.clone());
            }
            DoorType::Model(_) => {
                self.model = Some(source.clone());
            }
        }
    }
}

#[cfg(feature = "bevy")]
impl Door<Entity> {
    pub fn to_u32(&self, anchors: Edge<u32>) -> Door<u32> {
        Door {
            anchors,
            name: self.name.clone(),
            kind: self.kind.clone(),
            marker: Default::default(),
        }
    }
}

impl<T: RefTrait> Door<T> {
    pub fn convert<U: RefTrait>(&self, id_map: &HashMap<T, U>) -> Result<Door<U>, T> {
        Ok(Door {
            anchors: self.anchors.convert(id_map)?,
            name: self.name.clone(),
            kind: self.kind.clone(),
            marker: Default::default(),
        })
    }
}

impl<T: RefTrait> From<Edge<T>> for Door<T> {
    fn from(edge: Edge<T>) -> Self {
        // When converting an edge into a door, initialize it as closed instead of open.
        // This is more intuitive for users who are creating a door.
        let kind = SingleSlidingDoor {
            position: 0.0,
            ..Default::default()
        };

        Door {
            anchors: edge,
            name: NameInSite("<Unnamed>".to_string()),
            kind: kind.into(),
            marker: Default::default(),
        }
    }
}