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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/*
  Copyright 2017 Takashi Ogura

  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.
*/
//! graph structure for kinematic chain
use na::{Isometry3, RealField, Translation3, UnitQuaternion};
use nalgebra as na;
use parking_lot::{Mutex, MutexGuard};
use simba::scalar::SubsetOf;
use std::fmt::{self, Display};
use std::ops::Deref;
use std::sync::{Arc, Weak};

use super::errors::*;
use super::iterator::*;
use super::joint::*;
use super::link::*;

type WeakNode<T> = Weak<Mutex<NodeImpl<T>>>;

/// Node for joint tree struct
#[derive(Debug)]
pub struct NodeImpl<T>
where
    T: RealField,
{
    pub parent: Option<WeakNode<T>>,
    pub children: Vec<Node<T>>,
    pub joint: Joint<T>,
    pub mimic_parent: Option<WeakNode<T>>,
    pub mimic_children: Vec<Node<T>>,
    pub mimic: Option<Mimic<T>>,
    pub link: Option<Link<T>>,
}

/// Parts of `Chain`
///
/// It contains joint, joint (transform), and parent/children.
#[derive(Debug)]
pub struct Node<T: RealField>(pub(crate) Arc<Mutex<NodeImpl<T>>>);

impl<T> Node<T>
where
    T: RealField + SubsetOf<f64>,
{
    pub(crate) fn from_arc(arc_mutex_node: Arc<Mutex<NodeImpl<T>>>) -> Self {
        Node(arc_mutex_node)
    }

    pub fn new(joint: Joint<T>) -> Self {
        Node::<T>(Arc::new(Mutex::new(NodeImpl {
            parent: None,
            children: Vec::new(),
            joint,
            mimic_parent: None,
            mimic_children: Vec::new(),
            mimic: None,
            link: None,
        })))
    }

    pub(crate) fn lock(&self) -> MutexGuard<'_, NodeImpl<T>> {
        self.0.lock()
    }

    pub fn joint(&self) -> JointRefGuard<'_, T> {
        JointRefGuard { guard: self.lock() }
    }

    pub fn joint_position(&self) -> Option<T> {
        self.lock().joint.joint_position()
    }

    pub fn parent(&self) -> Option<Node<T>> {
        match self.lock().parent {
            Some(ref weak) => weak.upgrade().map(Node::from_arc),
            None => None,
        }
    }

    pub fn children(&self) -> ChildrenRefGuard<'_, T> {
        ChildrenRefGuard { guard: self.lock() }
    }

    /// iter from the end to root, it contains `nodes[id]` itself
    #[inline]
    pub fn iter_ancestors(&self) -> Ancestors<T> {
        Ancestors::new(Some(self.clone()))
    }
    /// iter to the end, it contains `nodes[id]` itself
    #[inline]
    pub fn iter_descendants(&self) -> Descendants<T> {
        Descendants::new(vec![self.clone()])
    }

    /// Set parent and child relations at same time
    pub fn set_parent(&self, parent: &Node<T>) {
        self.lock().parent = Some(Arc::downgrade(&parent.0));
        parent.0.lock().children.push(self.clone());
    }

    /// Remove parent and child relations at same time
    pub fn remove_parent(&self, parent: &Node<T>) {
        self.lock().parent = None;
        parent.0.lock().children.retain(|x| *x != *self);
    }

    /// # Examples
    ///
    /// ```
    /// use k::*;
    ///
    /// let l0 = k::NodeBuilder::<f32>::new().into_node();
    /// let l1 = k::NodeBuilder::new().into_node();
    /// l1.set_parent(&l0);
    /// assert!(l0.is_root());
    /// assert!(!l1.is_root());
    /// ```
    pub fn is_root(&self) -> bool {
        self.lock().parent.is_none()
    }

    /// # Examples
    ///
    /// ```
    /// let l0 = k::NodeBuilder::<f64>::new().into_node();
    /// let l1 = k::NodeBuilder::new().into_node();
    /// l1.set_parent(&l0);
    /// assert!(!l0.is_end());
    /// assert!(l1.is_end());
    /// ```
    pub fn is_end(&self) -> bool {
        self.0.lock().children.is_empty()
    }

    /// Set the origin transform of the joint
    #[inline]
    pub fn set_origin(&self, trans: Isometry3<T>) {
        self.lock().joint.set_origin(trans);
    }

    /// Get the origin transform of the joint
    #[inline]
    pub fn origin(&self) -> Isometry3<T> {
        self.joint().origin().clone()
    }

    /// Set the position (angle) of the joint
    ///
    /// If position is out of limit, it returns Err.
    ///
    /// # Examples
    ///
    /// ```
    /// use k::*;
    /// let l0 = NodeBuilder::new()
    ///     .joint_type(JointType::Linear{axis: Vector3::z_axis()})
    ///     .limits(Some((0.0..=2.0).into()))
    ///     .into_node();
    /// assert!(l0.set_joint_position(1.0).is_ok());
    /// assert!(l0.set_joint_position(-1.0).is_err());
    /// ```
    ///
    /// Setting position for Fixed joint is error.
    ///
    /// ```
    /// use k::*;
    /// let l0 = NodeBuilder::new()
    ///     .joint_type(JointType::Fixed)
    ///     .into_node();
    /// assert!(l0.set_joint_position(0.0).is_err());
    /// ```
    ///
    /// `k::joint::Mimic` can be used to copy other joint's position.
    ///
    /// ```
    /// use k::*;
    /// let j0 = NodeBuilder::new()
    ///     .joint_type(JointType::Linear{axis: Vector3::z_axis()})
    ///     .limits(Some((0.0..=2.0).into()))
    ///     .into_node();
    /// let j1 = NodeBuilder::new()
    ///     .joint_type(JointType::Linear{axis: Vector3::z_axis()})
    ///     .limits(Some((0.0..=2.0).into()))
    ///     .into_node();
    /// j1.set_mimic_parent(&j0, k::joint::Mimic::new(1.5, 0.1));
    /// assert_eq!(j0.joint_position().unwrap(), 0.0);
    /// assert_eq!(j1.joint_position().unwrap(), 0.0);
    /// assert!(j0.set_joint_position(1.0).is_ok());
    /// assert_eq!(j0.joint_position().unwrap(), 1.0);
    /// assert_eq!(j1.joint_position().unwrap(), 1.6);
    /// ```
    pub fn set_joint_position(&self, position: T) -> Result<(), Error> {
        let mut node = self.lock();
        if node.mimic_parent.is_some() {
            return Ok(());
        }
        node.joint.set_joint_position(position.clone())?;
        for child in &node.mimic_children {
            let mut child_node = child.lock();
            let mimic = child_node.mimic.clone();
            match mimic {
                Some(m) => child_node
                    .joint
                    .set_joint_position(m.mimic_position(position.clone()))?,
                None => {
                    let from = self.joint().name.to_owned();
                    let to = child.joint().name.to_owned();
                    return Err(Error::MimicError { from, to });
                }
            };
        }
        Ok(())
    }

    /// Set the clamped position (angle) of the joint
    ///
    /// It refers to the joint limit and clamps the argument. This function does nothing if this is fixed joint.
    ///
    /// # Examples
    ///
    /// ```
    /// use k::*;
    /// let l0 = NodeBuilder::new()
    ///     .joint_type(JointType::Linear{axis: Vector3::z_axis()})
    ///     .limits(Some((-1.0..=1.0).into()))
    ///     .into_node();
    /// l0.set_joint_position_clamped(2.0);
    /// assert_eq!(l0.joint().joint_position(), Some(1.0));
    /// l0.set_joint_position_clamped(-2.0);
    /// assert_eq!(l0.joint().joint_position(), Some(-1.0));
    /// ```
    pub fn set_joint_position_clamped(&self, position: T) {
        self.0.lock().joint.set_joint_position_clamped(position);
    }

    #[inline]
    pub fn set_joint_position_unchecked(&self, position: T) {
        self.0.lock().joint.set_joint_position_unchecked(position);
    }

    pub(crate) fn parent_world_transform(&self) -> Option<Isometry3<T>> {
        //match self.0.borrow().parent {
        match self.parent() {
            Some(ref parent) => parent.world_transform(),
            None => Some(Isometry3::identity()),
        }
    }

    pub(crate) fn parent_world_velocity(&self) -> Option<Velocity<T>> {
        match self.parent() {
            Some(ref parent) => parent.world_velocity(),
            None => Some(Velocity::zero()),
        }
    }

    /// Get the calculated world transform.
    /// Call `Chain::update_transforms()` before using this method.
    ///
    ///  # Examples
    ///
    /// ```
    /// use k::*;
    /// use k::prelude::*;
    ///
    /// let l0 = NodeBuilder::new()
    ///     .translation(Translation3::new(0.0, 0.0, 0.2))
    ///     .joint_type(JointType::Rotational{axis: Vector3::y_axis()})
    ///     .into_node();
    /// let l1 = NodeBuilder::new()
    ///     .translation(Translation3::new(0.0, 0.0, 1.0))
    ///     .joint_type(JointType::Linear{axis: Vector3::z_axis()})
    ///     .into_node();
    /// l1.set_parent(&l0);
    /// let tree = Chain::<f64>::from_root(l0);
    /// tree.set_joint_positions(&vec![3.141592 * 0.5, 0.1]).unwrap();
    /// assert!(l1.world_transform().is_none());
    /// assert!(l1.world_transform().is_none());
    /// let _poses = tree.update_transforms();
    /// assert!((l1.world_transform().unwrap().translation.vector.x - 1.1).abs() < 0.0001);
    /// assert!((l1.world_transform().unwrap().translation.vector.z - 0.2).abs() < 0.0001);
    ///
    /// // _poses[0] is as same as l0.world_transform()
    /// // _poses[1] is as same as l1.world_transform()
    #[inline]
    pub fn world_transform(&self) -> Option<Isometry3<T>> {
        self.joint().world_transform()
    }
    #[inline]
    pub fn world_velocity(&self) -> Option<Velocity<T>> {
        self.joint().world_velocity()
    }

    pub fn mimic_parent(&self) -> Option<Node<T>> {
        match self.lock().mimic_parent {
            Some(ref weak) => weak.upgrade().map(Node::from_arc),
            None => None,
        }
    }

    pub fn set_mimic_parent(&self, parent: &Node<T>, mimic: Mimic<T>) {
        self.lock().mimic_parent = Some(Arc::downgrade(&parent.0));
        parent.lock().mimic_children.push(self.clone());
        self.lock().mimic = Some(mimic);
    }

    pub fn set_link(&self, link: Option<Link<T>>) {
        self.lock().link = link;
    }

    pub fn link(&self) -> OptionLinkRefGuard<'_, T> {
        OptionLinkRefGuard { guard: self.lock() }
    }
}

impl<T> ::std::clone::Clone for Node<T>
where
    T: RealField,
{
    fn clone(&self) -> Self {
        Node::<T>(self.0.clone())
    }
}

impl<T> PartialEq for Node<T>
where
    T: RealField,
{
    fn eq(&self, other: &Node<T>) -> bool {
        std::ptr::eq(&*self.0, &*other.0)
    }
}

impl<T: RealField + SubsetOf<f64>> Display for Node<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let inner = self.lock();
        inner.joint.fmt(f)?;

        if let Some(l) = &inner.link {
            write!(f, " => /{}/", l.name)?;
        }
        Ok(())
    }
}

impl<T> From<Joint<T>> for Node<T>
where
    T: RealField + SubsetOf<f64>,
{
    fn from(joint: Joint<T>) -> Self {
        Self::new(joint)
    }
}

macro_rules! def_ref_guard {
    ($guard_struct:ident, $target:ty, $member:ident) => {
        #[derive(Debug)]
        pub struct $guard_struct<'a, T>
        where
            T: RealField,
        {
            guard: MutexGuard<'a, NodeImpl<T>>,
        }

        impl<'a, T> Deref for $guard_struct<'a, T>
        where
            T: RealField,
        {
            type Target = $target;
            fn deref(&self) -> &Self::Target {
                &self.guard.$member
            }
        }
    };
}

/*

macro_rules! def_ref_guard_mut {
    ($guard_struct:ident, $target:ty, $member:ident) => {
        pub struct $guard_struct<'a, T>
        where
            T: RealField,
        {
            guard: RefMut<'a, NodeImpl<T>>,
        }

        impl<'a, T> Deref for $guard_struct<'a, T>
        where
            T: RealField,
        {
            type Target = $target;
            fn deref(&self) -> &Self::Target {
                &self.guard.$member
            }
        }

        impl<'a, T> DerefMut for $guard_struct<'a, T>
        where
            T: RealField,
        {
            fn deref_mut(&mut self) -> &mut $target {
                &mut self.guard.$member
            }
        }
    };
}
*/

def_ref_guard!(JointRefGuard, Joint<T>, joint);
def_ref_guard!(OptionLinkRefGuard, Option<Link<T>>, link);
//def_ref_guard!(LinkRefGuard, Link<T>, link);
def_ref_guard!(ChildrenRefGuard, Vec<Node<T>>, children);

#[derive(Debug)]
pub struct LinkRefGuard<'a, T>
where
    T: RealField,
{
    pub(crate) guard: MutexGuard<'a, NodeImpl<T>>,
}

impl<'a, T> Deref for LinkRefGuard<'a, T>
where
    T: RealField,
{
    type Target = Link<T>;
    fn deref(&self) -> &Self::Target {
        // danger
        self.guard.link.as_ref().unwrap()
    }
}

//def_ref_guard!(ParentRefGuard, Option<WeakNode<T>>, parent);

/*
pub struct ParentRefGuard<'a, T>
where
    T: RealField,
{
    guard: Ref<'a, NodeImpl<T>>,
    parent: Option<Node<T>>,
}

impl<'a, T>  ParentRefGuard<'a, T> where T:RealField {
    pub fn new(guard: Ref<'a, NodeImpl<T>>) -> Self {
        let parent = guard.parent.and_then(|weak| weak.upgrade().map(|arc| Node::from_arc(arc)));
        Self {
            guard,
            parent,
        }
    }
}
*/
/*
impl<'a, T> Deref for ParentRefGuard<'a, T>
where
    T: RealField,
{
    type Target = Option<Node<T>>;
    fn deref(&self) -> &Self::Target {
        &self.parent
    }
}
*/

//def_ref_guard_mut!(JointRefGuardMut, Joint<T>, joint);

/// Build a `Link<T>`
///
/// # Examples
///
/// ```
/// use k::*;
/// let l0 = NodeBuilder::new()
///     .name("link_pitch")
///     .translation(Translation3::new(0.0, 0.1, 0.0))
///     .joint_type( JointType::Rotational{axis: Vector3::y_axis()})
///     .finalize();
/// println!("{l0:?}");
/// ```
#[derive(Debug, Clone)]
pub struct NodeBuilder<T: RealField> {
    name: String,
    joint_type: JointType<T>,
    limits: Option<Range<T>>,
    origin: Isometry3<T>,
}

impl<T> Default for NodeBuilder<T>
where
    T: RealField + SubsetOf<f64>,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T> NodeBuilder<T>
where
    T: RealField + SubsetOf<f64>,
{
    pub fn new() -> NodeBuilder<T> {
        NodeBuilder {
            name: "".to_string(),
            joint_type: JointType::Fixed,
            limits: None,
            origin: Isometry3::identity(),
        }
    }
    /// Set the name of the `Link`
    pub fn name(mut self, name: &str) -> NodeBuilder<T> {
        self.name = name.to_string();
        self
    }
    /// Set the joint which is connected to this link
    pub fn joint_type(mut self, joint_type: JointType<T>) -> NodeBuilder<T> {
        self.joint_type = joint_type;
        self
    }
    /// Set joint limits
    pub fn limits(mut self, limits: Option<Range<T>>) -> NodeBuilder<T> {
        self.limits = limits;
        self
    }
    /// Set the origin transform of this joint
    pub fn origin(mut self, origin: Isometry3<T>) -> NodeBuilder<T> {
        self.origin = origin;
        self
    }
    /// Set the translation of the origin transform of this joint
    pub fn translation(mut self, translation: Translation3<T>) -> NodeBuilder<T> {
        self.origin.translation = translation;
        self
    }
    /// Set the rotation of the origin transform of this joint
    pub fn rotation(mut self, rotation: UnitQuaternion<T>) -> NodeBuilder<T> {
        self.origin.rotation = rotation;
        self
    }
    /// Create `Joint` instance
    pub fn finalize(self) -> Joint<T> {
        let mut joint = Joint::new(&self.name, self.joint_type);
        joint.set_origin(self.origin);
        joint.limits = self.limits;
        joint
    }
    /// Create `Node` instead of `Joint` as output
    pub fn into_node(self) -> Node<T> {
        self.finalize().into()
    }
}

/// set parents easily
///
/// ```
/// use k::connect;
/// # fn main() {
/// let l0 = k::NodeBuilder::<f64>::new().into_node();
/// let l1 = k::NodeBuilder::new().into_node();
/// let l2 = k::NodeBuilder::new().into_node();
///
/// // This is the same as below
/// // l1.set_parent(&l0);
/// // l2.set_parent(&l1);
/// connect![l0 => l1 => l2];
///
/// assert!(l0.is_root());
/// assert!(!l1.is_root());
/// assert!(!l1.is_end());
/// assert!(l2.is_end());
/// # }
/// ```
#[macro_export]
macro_rules! connect {
    ($x:expr => $y:expr) => {
        $y.set_parent(&$x);
    };
    ($x:expr => $y:expr => $($rest:tt)+) => {
        $y.set_parent(&$x);
        $crate::connect!($y => $($rest)*);
    };
}