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
//!
//! # Cylindrical coordinates
//! 
//! Cylindrical coordinates use the distance to the origin of the point on a given plane, the angle to a reference on
//! that plane, and the altitude of the point.
//! - r: distance to origin, `[0, +∞`[
//! - theta: azimuth (longitude) of the point, `[0, 2π[`
//! - z: elevation (altitude) of the point, `]-∞, +∞`[
//! 
//! Support conversion to and from Cartesian and Spherical coordinates.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

use std::f64::consts::{         // Using std lib constants
    PI,                         // Pi
    TAU                         // Tau
};

use std::ops::{                 // Implementing basic operations
    Add,                        // Addition
    Sub,                        // Subtraction
    Mul,                        // Multiplication
    MulAssign,                  // Assigning multiplication
    Div,                        // Division
    DivAssign,                  // Assigning division
    Neg                         // Negation
};

use std::fmt::{                 // Formatter display
    Display,                    // The display itself
    Result as DRes              // The associated result
};

use super::{                    // Using parts from the crate
    cartesian::Cartesian,       // Cartesian coordinates
    spherical::Spherical        // Spherical coordinates
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/// # Cylindrical coordinates
/// 
/// Defined for 3D space
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Cylindrical {
    /// Radius from center of plane
    pub r: f64,
    /// Angle from reference on the plane
    pub theta: f64,
    /// Altitude
    pub z: f64
}

/// # Display for Cartesian
/// 
/// Simply shows each value associated to an axis.
impl Display for Cylindrical {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> DRes {
        write!(f, "r={} :: theta={}° :: z={}", self.r, self.theta.to_degrees(), self.z)?;
        Ok(())
    }
}

impl Cylindrical {
    /// # Creates a new entity
    /// 
    /// Returns the same value as `Self::default()`, all elements are equal to zero.
    /// 
    /// ```
    /// # use scilib::coordinate::cylindrical::Cylindrical;
    /// let m = Cylindrical { r: 0.0, theta: 0.0, z: 0.0 };
    /// let n = Cylindrical::new();
    /// let d = Cylindrical::default();
    /// 
    /// assert_eq!(m, n);
    /// assert_eq!(n, d);
    /// ```
    pub const fn new() -> Self {
        Self {
            r: 0.0,
            theta: 0.0,
            z: 0.0
        }
    }

    /// # From the point
    /// 
    /// Creates a Cylindrical struct from three given points in space.
    /// 
    /// ```
    /// # use scilib::coordinate::cylindrical::Cylindrical;
    /// let m = Cylindrical { r: 1.0, theta: 0.12, z: 2.8 };
    /// let f = Cylindrical::from(1, 0.12, 2.8);
    /// 
    /// assert_eq!(m, f);
    /// ```
    pub fn from<T, U, V>(r: T, theta: U, z: V) -> Self
    where T: Into<f64>, U: Into<f64>, V: Into<f64> {
        Self {
            r: r.into(),
            theta: theta.into() % TAU,
            z: z.into()
        }
    }    

    /// # From the point (degrees)
    /// 
    /// Creates a Cylindrical struct from three given points in space, with the angles in degrees.
    /// 
    /// ```
    /// # use scilib::coordinate::cylindrical::Cylindrical;
    /// let m = Cylindrical { r: 1.0, theta: 45.0_f64.to_radians(), z: -4.2 };
    /// let f = Cylindrical::from_degree(1, 45, -4.2);
    /// 
    /// assert_eq!(m, f);
    /// ```
    pub fn from_degree<T, U, V>(r: T, theta: U, z: V) -> Self
    where T: Into<f64>, U: Into<f64>, V: Into<f64> {
        let td: f64 = theta.into();
        Self {
            r: r.into(),
            theta: td.to_radians() % TAU,
            z: z.into()
        }
    }

    /// # From another coordinate system
    /// 
    /// Creates an Cylindrical struct from another coordinate system. Calls the `Into<Cylindrical>` method,
    /// which is verified in its implementation.
    /// 
    /// ```
    /// # use scilib::coordinate::cartesian::Cartesian;
    /// # use scilib::coordinate::spherical::Spherical;
    /// # use scilib::coordinate::cylindrical::Cylindrical;
    /// let c: Cartesian = Cartesian::from(0, 12, 3.2);
    /// let s: Spherical = Spherical::from_degree(1.2, 32, 60);
    /// let res1: Cylindrical = Cylindrical::from_coord(c);
    /// let res2: Cylindrical = Cylindrical::from_coord(s);
    /// 
    /// assert_eq!(res1, c.into());
    /// assert_eq!(res2, s.into());
    /// ```
    pub fn from_coord<T>(c: T) -> Self
    where T: Into<Self> {
        c.into()
    }

    /// # Distance between two points
    /// 
    /// ```
    /// # use std::f64::consts::SQRT_2;
    /// # use scilib::coordinate::cylindrical::Cylindrical;
    /// let s1 = Cylindrical::from_degree(SQRT_2, 45, 1.0);
    /// let s2 = Cylindrical::from_degree(SQRT_2, -45, -1.0);
    /// 
    /// assert_eq!(s1.distance(s2), 2.0 * SQRT_2);
    /// ```
    pub fn distance(&self, other: Self) -> f64 {
        let t1: f64 = self.r.powi(2) + other.r.powi(2);
        let t2: f64 = (self.theta - other.theta).cos() * 2.0 * self.r * other.r;
        let t3: f64 = (self.z - other.z).powi(2);

        (t1 - t2 + t3).sqrt()
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/// # Conversion to cartesian coordinates
/// 
/// ```
/// # use scilib::coordinate::cartesian::Cartesian;
/// # use scilib::coordinate::cylindrical::Cylindrical;
/// let s = Cylindrical::from_degree(3, 60, 4);
/// let conv: Cartesian = s.into();
/// let expected = Cartesian::from(1.5, 2.598076211, 4);
/// 
/// assert!((conv.x - expected.x).abs() < 1.0e-9);
/// assert!((conv.y - expected.y).abs() < 1.0e-9);
/// assert_eq!(conv.z, expected.z);
/// 
/// let s = Cylindrical::from_degree(5, 30, -2);
/// let conv: Cartesian = s.into();
/// let expected = Cartesian::from(4.330127019, 2.5, -2);
/// 
/// assert!((conv.x - expected.x).abs() < 1.0e-9);
/// assert!((conv.y - expected.y).abs() < 1.0e-9);
/// assert_eq!(conv.z, expected.z);
/// ```
impl Into<Cartesian> for Cylindrical {
    fn into(self) -> Cartesian {
        Cartesian {
            x: self.r * self.theta.cos(),
            y: self.r * self.theta.sin(),
            z: self.z
        }
    }
}

/// # Conversion to spherical coordinates
/// 
/// ```
/// # use scilib::coordinate::spherical::Spherical;
/// # use scilib::coordinate::cylindrical::Cylindrical;
/// 
/// let s = Cylindrical::from_degree(3, 60, 4);
/// let conv: Spherical = s.into();
/// let expected = Spherical::from_degree(5, 60, 36.86989765);
/// 
/// assert_eq!(conv.r, expected.r);
/// assert_eq!(conv.theta, expected.theta);
/// assert!((conv.phi - expected.phi).abs() < 1.0e-9);
/// 
/// let s = Cylindrical::from_degree(3, 60, -4);
/// let conv: Spherical = s.into();
/// let expected = Spherical::from_degree(5, 60, 143.1301024);
/// 
/// assert_eq!(conv.r, expected.r);
/// assert_eq!(conv.theta, expected.theta);
/// assert!((conv.phi - expected.phi).abs() < 1.0e-9);
/// ```
impl Into<Spherical> for Cylindrical {
    fn into(self) -> Spherical {
        let rho: f64 = (self.r.powi(2) + self.z.powi(2)).sqrt();
        let mut np: f64 = (self.r / self.z).atan();

        if self.z.is_sign_negative() {
            np += PI;
        }

        Spherical {
            r: rho,
            theta: self.theta,
            phi: np
        }
    }
}

/// # Addition
/// 
/// Converts the coordinate in cartesian for addition, then returns them as Cylindrical.
impl<T: Into<Cartesian>> Add<T> for Cylindrical {
    type Output = Self;
    fn add(self, rhs: T) -> Self::Output {
        let s: Cartesian = self.into();
        let r: Cartesian = rhs.into();
        (s + r).into()
    }
}

/// # Subtraction
/// 
/// Converts the coordinate in cartesian for subtraction, then returns them as Cylindrical.
impl<T: Into<Cartesian>> Sub<T> for Cylindrical {
    type Output = Self;
    fn sub(self, rhs: T) -> Self::Output {
        let s: Cartesian = self.into();
        let r: Cartesian = rhs.into();
        (s - r).into()
    }
}

/// # Scalar multiplication
/// 
/// Multiplies the radius by a scalar.
/// 
/// ```
/// # use scilib::coordinate::cylindrical::Cylindrical;
/// let s = Cylindrical::from_degree(1, 180, 2.1);
/// let res = s * -2;
/// let expected = Cylindrical::from(2, 0, -4.2);
/// 
/// assert_eq!(res, expected);
/// ```
impl<T: Into<f64>> Mul<T> for Cylindrical {
    type Output = Self;
    fn mul(self, rhs: T) -> Self::Output {
        let f: f64 = rhs.into();
        let res: Self = Self {
            r: self.r * f.abs(),
            theta: self.theta,
            z: self.z * f.abs()
        };

        // If the sign is negative, we need to flip the angles
        if f.is_sign_negative() {
            -res
        } else {
            res
        }
    }
}

/// # Assigning scalar multiplication
/// 
/// Multiplies the radius by a scalar in place.
/// 
/// ```
/// # use scilib::coordinate::cylindrical::Cylindrical;
/// let mut s = Cylindrical::from_degree(1, 180, 2.1);
/// s *= -2;
/// let expected = Cylindrical::from_degree(2, 0, -4.2);
/// 
/// assert_eq!(s, expected);
/// ```
impl<T: Into<f64>> MulAssign<T> for Cylindrical {
    fn mul_assign(&mut self, rhs: T) {
        let f: f64 = rhs.into();
        self.r *= f.abs();
        self.z *= f;

        // If the sign is negative, we need to flip the angles
        if f.is_sign_negative() {
            self.theta = (self.theta + PI) % TAU;
        }
    }
}

/// # Scalar division
/// 
/// Divides the radius by a scalar.
/// 
/// ```
/// # use scilib::coordinate::cylindrical::Cylindrical;
/// let s = Cylindrical::from_degree(2, 60, 2.1);
/// let res = s / 2;
/// let expected = Cylindrical::from_degree(1, 60, 1.05);
/// 
/// assert_eq!(res, expected);
/// ```
impl<T: Into<f64>> Div<T> for Cylindrical {
    type Output = Self;
    fn div(self, rhs: T) -> Self::Output {
        let f: f64 = rhs.into();
        let res: Self = Self {
            r: self.r / f.abs(),
            theta: self.theta,
            z: self.z / f.abs()
        };

        // If the sign is negative, we need to flip the angles
        if f.is_sign_negative() {
            -res
        } else {
            res
        }
    }
}

/// # Assigning scalar division
/// 
/// Divides the radius by a scalar in place.
/// 
/// ```
/// # use scilib::coordinate::cylindrical::Cylindrical;
/// let mut s = Cylindrical::from_degree(2, 30, 2.1);
/// s /= 2;
/// let expected = Cylindrical::from_degree(1, 30, 1.05);
/// 
/// assert_eq!(s, expected);
/// ```
impl<T: Into<f64>> DivAssign<T> for Cylindrical {
    fn div_assign(&mut self, rhs: T) {
        let f: f64 = rhs.into();
        self.r /= f.abs();
        self.z /= f;

        // If the sign is negative, we need to flip the angles
        if f.is_sign_negative() {
            self.theta = (self.theta + PI) % TAU;
        }
    }
}

/// # Negation
/// 
/// Going to the opposite point.
/// 
/// ```
/// # use scilib::coordinate::cylindrical::Cylindrical;
/// let c1 = Cylindrical::from_degree(2, 35, 6.0);
/// let c2 = -c1;
/// let expected = Cylindrical::from_degree(2, 215, -6);
/// 
/// assert_eq!(c2, expected);
/// ```
impl Neg for Cylindrical {
    type Output = Self;
    fn neg(self) -> Self::Output {
        Self {
            r: self.r,
            theta: (self.theta + PI) % TAU,
            z: -self.z
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////