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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use slab::{Iter, IterMut, Slab};
use std::iter::Map;

use joint::Joint;
use math::{Inertia, Isometry, Point, Vector};
use na::Real;
use object::{Body, BodyMut, BodyPart, BodyPartMut, Ground, Multibody, MultibodyLinkId,
             MultibodyLinkMut, MultibodyLinkRef, MultibodyWorkspace, RigidBody};
use solver::IntegrationParameters;

// FIXME: remove the pub(crate) after this is replaced by -> impl Iterator
pub(crate) type RigidBodies<'a, N> =
    Map<Iter<'a, RigidBody<N>>, fn((usize, &RigidBody<N>)) -> &RigidBody<N>>;
pub(crate) type RigidBodiesMut<'a, N> =
    Map<IterMut<'a, RigidBody<N>>, fn((usize, &mut RigidBody<N>)) -> &mut RigidBody<N>>;
pub(crate) type Multibodies<'a, N> =
    Map<Iter<'a, Multibody<N>>, fn((usize, &Multibody<N>)) -> &Multibody<N>>;
pub(crate) type MultibodiesMut<'a, N> =
    Map<IterMut<'a, Multibody<N>>, fn((usize, &mut Multibody<N>)) -> &mut Multibody<N>>;

/// A unique identifier of a body added to the world.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct BodyHandle {
    handle: usize,
    reserved: usize, // NOTE: reserved for future use (e.g. for soft bodies).
}

impl BodyHandle {
    pub(crate) fn new(handle: usize) -> Self {
        BodyHandle {
            handle: handle,
            reserved: 0,
        }
    }

    /// The unique identifier of the ground.
    pub fn ground() -> Self {
        Self::new(usize::max_value())
    }

    /// Tests if this handle corresponds to the ground.
    pub fn is_ground(&self) -> bool {
        self.handle == usize::max_value()
    }
}

// FIXME: remove the pub(crate) after this is replaced by -> impl Iterator
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum BodyId {
    MultibodyLinkId(usize, MultibodyLinkId),
    RigidBodyId(usize),
}

impl BodyId {
    #[inline]
    pub fn is_same_body(&self, other: BodyId) -> bool {
        match (*self, other) {
            (BodyId::MultibodyLinkId(id1, _), BodyId::MultibodyLinkId(id2, _)) => id1 == id2,
            (BodyId::RigidBodyId(id1), BodyId::RigidBodyId(id2)) => id1 == id2,
            _ => false,
        }
    }
}

/// A set containing all the bodies added to the world.
pub struct BodySet<N: Real> {
    ground: Ground<N>,
    ids: Slab<BodyId>,
    mbs: Slab<Multibody<N>>,
    rbs: Slab<RigidBody<N>>,
}

impl<N: Real> BodySet<N> {
    /// Create a new empty set of bodies.
    pub fn new() -> Self {
        BodySet {
            ground: Ground::new(),
            ids: Slab::new(),
            mbs: Slab::new(),
            rbs: Slab::new(),
        }
    }

    /// The number of bodies in this set.
    pub fn len(&self) -> usize {
        self.mbs.len() + self.rbs.len()
    }

    /// Check if the two given handles identify the same body.
    ///
    /// In particular, returns `true` if both handles indentify multibody links belonging
    /// to the same multibody.
    pub fn are_same_body(&self, body1: BodyHandle, body2: BodyHandle) -> bool {
        if body1.handle == body2.handle {
            return true;
        }

        let ids = (self.ids[body1.handle], self.ids[body2.handle]);
        if let (BodyId::MultibodyLinkId(mb1, _), BodyId::MultibodyLinkId(mb2, _)) = ids {
            return mb1 == mb2;
        }

        false
    }

    /// Update the kinematics of all the bodies.
    pub fn update_kinematics(&mut self) {
        for (_, mb) in &mut self.mbs {
            mb.update_kinematics();
        }
    }

    /// Clear the dynamics of all the bodies.
    pub fn clear_dynamics(&mut self) {
        for (_, mb) in &mut self.mbs {
            mb.clear_dynamics();
        }

        for (_, rb) in &mut self.rbs {
            rb.clear_dynamics()
        }
    }

    /// Update the dynamics of all the bodies.
    pub fn update_dynamics(
        &mut self,
        gravity: &Vector<N>,
        params: &IntegrationParameters<N>,
        workspace: &mut MultibodyWorkspace<N>,
    ) {
        for (_, mb) in &mut self.mbs {
            mb.update_dynamics(gravity, params, workspace);
        }

        for (_, rb) in &mut self.rbs {
            rb.update_dynamics(gravity, params)
        }
    }

    /// Add a rigid body to the set and return its handle.
    pub fn add_rigid_body(
        &mut self,
        position: Isometry<N>,
        local_inertia: Inertia<N>,
        local_com: Point<N>,
    ) -> BodyHandle {
        let rb_entry = self.rbs.vacant_entry();
        let rb_id = rb_entry.key();
        let rb_handle = BodyHandle::new(self.ids.insert(BodyId::RigidBodyId(rb_id)));

        let _ = rb_entry.insert(RigidBody::new(
            rb_handle,
            position,
            local_inertia,
            local_com,
        ));
        rb_handle
    }

    /// Add a multibody link to the set and return its handle.
    pub fn add_multibody_link<J: Joint<N>>(
        &mut self,
        parent: BodyHandle,
        joint: J,
        parent_shift: Vector<N>,
        body_shift: Vector<N>,
        local_inertia: Inertia<N>,
        local_com: Point<N>,
    ) -> BodyHandle {
        if parent.is_ground() {
            let mb_entry = self.mbs.vacant_entry();
            let mb_id = mb_entry.key();
            let mb_handle = BodyHandle::new(
                self.ids
                    .insert(BodyId::MultibodyLinkId(mb_id, MultibodyLinkId::ground())),
            );
            let mb = mb_entry.insert(Multibody::new());
            let id = mb.add_link(
                mb_handle,
                MultibodyLinkId::ground(),
                joint,
                parent_shift,
                body_shift,
                local_inertia,
                local_com,
            ).id();
            self.ids[mb_handle.handle] = BodyId::MultibodyLinkId(mb_id, id);
            mb_handle
        } else {
            if let BodyId::MultibodyLinkId(mb_id, parent_id) = self.ids[parent.handle] {
                let mb_handle = BodyHandle::new(
                    self.ids
                        .insert(BodyId::MultibodyLinkId(mb_id, MultibodyLinkId::ground())),
                );
                let id = self.mbs[mb_id]
                    .add_link(
                        mb_handle,
                        parent_id,
                        joint,
                        parent_shift,
                        body_shift,
                        local_inertia,
                        local_com,
                    )
                    .id();
                self.ids[mb_handle.handle] = BodyId::MultibodyLinkId(mb_id, id);
                mb_handle
            } else {
                panic!("Attempting to attach a multibody link to a body that is neither a link nor the ground.")
            }
        }
    }

    /// Remove a body from this set.
    ///
    /// If `body` identify a mutibody link, the whole multibody is removed.
    pub fn remove_body(&mut self, body: BodyHandle) {
        if !body.is_ground() {
            let body_id = self.ids[body.handle];

            match body_id {
                BodyId::MultibodyLinkId(id, _) => {
                    let _ = self.mbs.remove(id);
                }
                BodyId::RigidBodyId(id) => {
                    let _ = self.rbs.remove(id);
                }
            }

            self.ids.retain(|_, id| !id.is_same_body(body_id));
        }
    }

    /// Remove some multibody links.
    ///
    /// If a multibody link which has descendent is removed, its immediat descendent in
    /// the kinematic tree becomes the root of a new multibody and its joint is replaced by
    /// a free joint attached to the ground.
    pub fn remove_multibody_links(&mut self, body_parts: &[BodyHandle]) {
        if body_parts.len() != 0 {
            if let BodyId::MultibodyLinkId(parent_id, _) = self.ids[body_parts[0].handle] {
                let mb = self.mbs.remove(parent_id);
                let mut links = Vec::with_capacity(body_parts.len());

                for part in body_parts {
                    if let BodyId::MultibodyLinkId(mb_id, id) = self.ids.remove(part.handle) {
                        if mb_id != parent_id {
                            panic!("Multibody link removal: all multibody link must belong to the same multibody.")
                        }

                        links.push(id);
                    } else {
                        panic!("Multibody link removal: all body must indentify a multibody link.")
                    }
                }

                let mbs = mb.remove_links(&links);

                // Update the links identifiers.
                for mb in mbs {
                    let mb_key = self.mbs.insert(mb);

                    for link in self.mbs[mb_key].links() {
                        self.ids[link.handle().handle] = BodyId::MultibodyLinkId(mb_key, link.id());
                    }
                }
            } else {
                panic!("Multibody link removal: all body must indentify a multibody link.")
            }
        }
    }

    /// Checks that the given handle identifies a valid body part.
    ///
    /// Returns `true` if `body.is_ground()` too.
    pub fn contains(&self, body: BodyHandle) -> bool {
        // FIXME: do we have to take body.reserved into account?
        body.is_ground() || self.ids.contains(body.handle)
    }

    /// Reference to the body identified by `body`.
    ///
    /// Panics if the body part is not found.
    #[inline]
    pub fn body(&self, body: BodyHandle) -> Body<N> {
        if body.is_ground() {
            Body::Ground(&self.ground)
        } else {
            match self.ids[body.handle] {
                BodyId::MultibodyLinkId(mb_id, _) => Body::Multibody(&self.mbs[mb_id]),
                BodyId::RigidBodyId(id) => Body::RigidBody(&self.rbs[id]),
            }
        }
    }

    /// Mutable reference to the body identified by `body`.
    ///
    /// Panics if the body part is not found.
    #[inline]
    pub fn body_mut(&mut self, body: BodyHandle) -> BodyMut<N> {
        if body.is_ground() {
            BodyMut::Ground(&mut self.ground)
        } else {
            match self.ids[body.handle] {
                BodyId::MultibodyLinkId(mb_id, _) => BodyMut::Multibody(&mut self.mbs[mb_id]),
                BodyId::RigidBodyId(id) => BodyMut::RigidBody(&mut self.rbs[id]),
            }
        }
    }

    /// Reference to the body part identified by `body`.
    ///
    /// Panics if the body part is not found.
    #[inline]
    pub fn body_part(&self, body: BodyHandle) -> BodyPart<N> {
        if body.is_ground() {
            BodyPart::Ground(&self.ground)
        } else {
            match self.ids[body.handle] {
                BodyId::MultibodyLinkId(mb_id, link_id) => {
                    BodyPart::MultibodyLink(self.mbs[mb_id].link(link_id))
                }
                BodyId::RigidBodyId(id) => BodyPart::RigidBody(&self.rbs[id]),
            }
        }
    }

    /// Mutable reference to the body part identified by `body`.
    ///
    /// Panics if the body part is not found.
    #[inline]
    pub fn body_part_mut(&mut self, body: BodyHandle) -> BodyPartMut<N> {
        if body.is_ground() {
            BodyPartMut::Ground(&mut self.ground)
        } else {
            match self.ids[body.handle] {
                BodyId::MultibodyLinkId(mb_id, link_id) => {
                    BodyPartMut::MultibodyLink(self.mbs[mb_id].link_mut(link_id))
                }
                BodyId::RigidBodyId(id) => BodyPartMut::RigidBody(&mut self.rbs[id]),
            }
        }
    }

    /// Reference to the multibody containing the multibody link identified by `body`.
    ///
    /// Returns `None` if it is not found or does not identify a multibody link.
    #[inline]
    pub fn multibody(&self, body: BodyHandle) -> Option<&Multibody<N>> {
        if let Some(&BodyId::MultibodyLinkId(mb_id, _)) = self.ids.get(body.handle) {
            Some(&self.mbs[mb_id])
        } else {
            None
        }
    }

    /// Mutable reference to the multibody containing the multibody link identified by `body`.
    ///
    /// Returns `None` if it is not found or does not identify a multibody link.
    #[inline]
    pub fn multibody_mut(&mut self, body: BodyHandle) -> Option<&mut Multibody<N>> {
        if let Some(&BodyId::MultibodyLinkId(mb_id, _)) = self.ids.get(body.handle) {
            Some(&mut self.mbs[mb_id])
        } else {
            None
        }
    }

    /// Reference to the multibody link identified by `body`.
    ///
    /// Returns `None` if it is not found or does not identify a multibody link.
    #[inline]
    pub fn multibody_link(&self, body: BodyHandle) -> Option<MultibodyLinkRef<N>> {
        if let Some(&BodyId::MultibodyLinkId(mb_id, link_id)) = self.ids.get(body.handle) {
            Some(self.mbs[mb_id].link(link_id))
        } else {
            None
        }
    }

    /// Mutable reference to the multibody link identified by `body`.
    ///
    /// Returns `None` if it is not found or does not identify a multibody link.
    #[inline]
    pub fn multibody_link_mut(&mut self, body: BodyHandle) -> Option<MultibodyLinkMut<N>> {
        if let Some(&BodyId::MultibodyLinkId(mb_id, link_id)) = self.ids.get(body.handle) {
            Some(self.mbs[mb_id].link_mut(link_id))
        } else {
            None
        }
    }

    /// Reference to the rigid body identified by `body`.
    ///
    /// Returns `None` if it is not found or does not identify a rigid body.
    #[inline]
    pub fn rigid_body(&self, body: BodyHandle) -> Option<&RigidBody<N>> {
        if let Some(&BodyId::RigidBodyId(id)) = self.ids.get(body.handle) {
            Some(&self.rbs[id])
        } else {
            None
        }
    }

    /// Mutable reference to the rigid body identified by `body`.
    ///
    /// Returns `None` if it is not found or does not identify a rigid body.
    #[inline]
    pub fn rigid_body_mut(&mut self, body: BodyHandle) -> Option<&mut RigidBody<N>> {
        if let Some(&BodyId::RigidBodyId(id)) = self.ids.get(body.handle) {
            Some(&mut self.rbs[id])
        } else {
            None
        }
    }

    /// Iterator yielding all the rigid bodies on this set.
    #[inline]
    pub fn rigid_bodies(&self) -> RigidBodies<N> {
        self.rbs.iter().map(|e| e.1)
    }

    /// Mutable iterator yielding all the rigid bodies on this set.
    #[inline]
    pub fn rigid_bodies_mut(&mut self) -> RigidBodiesMut<N> {
        self.rbs.iter_mut().map(|e| e.1)
    }

    /// Iterator yielding all the multibodies on this set.
    #[inline]
    pub fn multibodies(&self) -> Multibodies<N> {
        self.mbs.iter().map(|e| e.1)
    }

    /// Mutable iterator yielding all the multibodies on this set.
    #[inline]
    pub fn multibodies_mut(&mut self) -> MultibodiesMut<N> {
        self.mbs.iter_mut().map(|e| e.1)
    }

    /*
    #[inline]
    pub fn bodies(&self) -> Bodies<N> {
        Bodies {
            rbs_iter: self.rbs.iter(),
            mbs_iter: self.mbs.iter()
        }
    }
    */

    /// Mutable iterator yielding all the bodies on this set.
    #[inline]
    pub fn bodies_mut(&mut self) -> BodiesMut<N> {
        BodiesMut {
            rbs_iter: self.rbs.iter_mut(),
            mbs_iter: self.mbs.iter_mut(),
        }
    }
}

/// Iterator yielding all the bodies on a body set.
pub struct Bodies<'a, N: Real> {
    rbs_iter: Iter<'a, RigidBody<N>>,
    mbs_iter: Iter<'a, Multibody<N>>,
}

impl<'a, N: Real> Iterator for Bodies<'a, N> {
    type Item = Body<'a, N>;

    #[inline]
    fn next(&mut self) -> Option<Body<'a, N>> {
        if let Some(res) = self.rbs_iter.next() {
            return Some(Body::RigidBody(res.1));
        }

        if let Some(res) = self.mbs_iter.next() {
            return Some(Body::Multibody(res.1));
        }

        return None;
    }
}

/// Mutable iterator yielding all the bodies on a body set.
pub struct BodiesMut<'a, N: Real> {
    rbs_iter: IterMut<'a, RigidBody<N>>,
    mbs_iter: IterMut<'a, Multibody<N>>,
}

impl<'a, N: Real> Iterator for BodiesMut<'a, N> {
    type Item = BodyMut<'a, N>;

    #[inline]
    fn next(&mut self) -> Option<BodyMut<'a, N>> {
        if let Some(res) = self.rbs_iter.next() {
            return Some(BodyMut::RigidBody(res.1));
        }

        if let Some(res) = self.mbs_iter.next() {
            return Some(BodyMut::Multibody(res.1));
        }

        return None;
    }
}