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
//! Core structs and traits

use std::rc::Rc;

use euclid::{Point2D, UnknownUnit};
use rand::prelude::*;

/// The parametric value t
#[derive(Clone, Copy, PartialEq)]
pub struct T(f32);

impl T {
    /// values outside 0 to 1 will be clamped!
    pub fn new(value: f32) -> Self {
        if value <= 0.0 {
            return T(0.0);
        }

        if value >= 1.0 {
            return T(1.0);
        }

        T(value)
    }

    /// returns the value of the `[T]`
    pub fn value(&self) -> f32 {
        self.0
    }

    /// returns "Zero"
    pub fn start() -> Self {
        Self(0.0)
    }

    /// returns "One"
    pub fn end() -> Self {
        Self(1.0)
    }
}

/// Point type from Euclid
pub type Point = Point2D<f32, UnknownUnit>;

/// 2D parametric function trait
pub trait ParametricFunction2D {
    /// returns the value of the parametric function at the point `t`
    fn evaluate(&self, t: T) -> Point;

    /// returns `n` equally spaced points along the entire parametric function from [`T::start`] to [`T::end`]
    fn linspace(&self, n: usize) -> Vec<Point> {
        let step_size = 1.0 / n as f32;
        (0..=n)
            .map(|i| {
                let t = T::new((i as f32) * step_size);
                self.evaluate(t)
            })
            .collect()
    }

    /// returns start, or "first", point on the parametric function
    fn start(&self) -> Point {
        self.evaluate(T::start())
    }

    /// returns end, or"last", point on the parametric function
    fn end(&self) -> Point {
        self.evaluate(T::end())
    }

    /// return a random point on the parametric function
    fn random_point(&self) -> Point {
        let mut rng = rand::thread_rng();
        let t = T::new(rng.gen());
        self.evaluate(t)
    }

    /// return n random points on the parametric function
    fn random_points(&self, n: usize) -> Vec<Point> {
        (0..n).map(|_| self.random_point()).collect()
    }
}

/// 1D parametric function trait
pub trait ParametricFunction1D {
    /// returns the value of the parametric function at the point `t`
    fn evaluate(&self, t: T) -> f32;

    /// returns `n` equally spaced points along the entire parametric function from [`T::start`] to [`T::end`]
    fn linspace(&self, n: usize) -> Vec<f32> {
        let step_size = 1.0 / n as f32;
        (0..=n)
            .map(|i| {
                let t = T::new((i as f32) * step_size);
                self.evaluate(t)
            })
            .collect()
    }

    /// returns start, or "first", point on the parametric function
    fn start(&self) -> f32 {
        self.evaluate(T::start())
    }

    /// returns end, or"last", point on the parametric function
    fn end(&self) -> f32 {
        self.evaluate(T::end())
    }

    /// return a random point on the parametric function
    fn random_point(&self) -> f32 {
        let mut rng = rand::thread_rng();
        let t = T::new(rng.gen());
        self.evaluate(t)
    }

    /// return n random points on the parametric function
    fn random_points(&self, n: usize) -> Vec<f32> {
        (0..n).map(|_| self.random_point()).collect()
    }
}

/// The concatenation of multiple things that implement [`ParametricFunction2D`]
pub struct Concat {
    pub functions: Vec<Rc<Box<dyn ParametricFunction2D>>>,
}

impl ParametricFunction2D for Concat {
    fn evaluate(&self, t: T) -> Point {
        if t == T::start() {
            return self.functions[0].evaluate(t);
        }

        if t == T::end() {
            return self.functions[self.functions.len() - 1].evaluate(t);
        }

        let gap = 1.0 / self.functions.len() as f32;
        let interp = self.functions.len() as f32 * t.value();
        let index = interp.floor() as usize;

        let diff = t.value() - (index as f32) * gap;

        let interp_t = T::new(diff / gap);

        self.functions[index].evaluate(interp_t)
    }
}

/// The repetition `n` times of a thing that implements [`ParametricFunction2D`]
pub struct Repeat {
    pub function: Rc<Box<dyn ParametricFunction2D>>,
    pub n: usize,
}
impl ParametricFunction2D for Repeat {
    fn evaluate(&self, t: T) -> Point {
        let functions = (0..self.n).map(|_| self.function.clone()).collect();
        let concat = Concat { functions };
        concat.evaluate(t)
    }
}
/// The rotation around `centre` by `angle` (in "turns") of a thing that implements [`ParametricFunction2D`]
pub struct Rotate {
    pub function: Rc<Box<dyn ParametricFunction2D>>,
    pub centre: Point,
    pub angle: T,
}
impl ParametricFunction2D for Rotate {
    fn evaluate(&self, t: T) -> Point {
        let val = self.function.evaluate(t);

        (
            self.centre.x
                + (val.x - self.centre.x) * f32::cos(self.angle.value() * std::f32::consts::TAU)
                - (val.y - self.centre.y) * f32::sin(self.angle.value() * std::f32::consts::TAU),
            self.centre.y
                + (val.x - self.centre.x) * f32::sin(self.angle.value() * std::f32::consts::TAU)
                + (val.y - self.centre.y) * f32::cos(self.angle.value() * std::f32::consts::TAU),
        )
            .into()
    }
}

/// The translation by `by` of a thing that implements [`ParametricFunction2D`]
pub struct Translate {
    pub function: Rc<Box<dyn ParametricFunction2D>>,
    pub by: Point,
}

impl ParametricFunction2D for Translate {
    fn evaluate(&self, t: T) -> Point {
        let val = self.function.evaluate(t);
        (val.x + self.by.x, val.y + self.by.y).into()
    }
}

/// Combination of [`Rotate`] and [`Translate`]
pub struct RotateTranslate {
    pub function: Rc<Box<dyn ParametricFunction2D>>,
    pub by: Point,
    pub centre: Point,
    pub angle: T,
    pub rotate_first: bool,
}

impl ParametricFunction2D for RotateTranslate {
    fn evaluate(&self, t: T) -> Point {
        if self.rotate_first {
            let r = Rotate {
                function: self.function.clone(),
                centre: self.centre,
                angle: self.angle,
            };
            let tr = Translate {
                function: Rc::new(Box::new(r)),
                by: self.by,
            };
            tr.evaluate(t)
        } else {
            let tr = Translate {
                function: self.function.clone(),
                by: self.by,
            };
            let r = Rotate {
                function: Rc::new(Box::new(tr)),
                centre: self.centre,
                angle: self.angle,
            };
            r.evaluate(t)
        }
    }
}

impl<F> ParametricFunction2D for F
where
    F: Fn(T) -> Point,
{
    fn evaluate(&self, t: T) -> Point {
        self(t)
    }
}

impl<F> ParametricFunction1D for F
where
    F: Fn(T) -> f32,
{
    fn evaluate(&self, t: T) -> f32 {
        self(t)
    }
}

impl<F, G> ParametricFunction2D for (F, G)
where
    F: ParametricFunction1D,
    G: ParametricFunction1D,
{
    fn evaluate(&self, t: T) -> Point {
        (self.0.evaluate(t), self.1.evaluate(t)).into()
    }
}

pub struct Scale {
    pub function: Rc<Box<dyn ParametricFunction2D>>,
    pub centre: Point,
    pub scale_x: f32,
    pub scale_y: f32,
}

impl ParametricFunction2D for Scale {
    fn evaluate(&self, t: T) -> Point {
        let val = self.function.evaluate(t);
        let val_trans_origin: Point = (val.x - self.centre.x, val.y - self.centre.y).into();
        let scaled: Point = (
            val_trans_origin.x * self.scale_x,
            val_trans_origin.y * self.scale_y,
        )
            .into();
        (scaled.x + self.centre.x, scaled.y + self.centre.y).into()
    }
}
#[cfg(test)]
mod tests {
    use approx::assert_relative_eq;

    use crate::{segment::Segment, Circle};

    use super::*;

    #[test]
    fn test_repeat() {
        let s = Segment {
            start: (0.0, 0.0).into(),
            end: (1.0, 1.0).into(),
        };
        let rep = Repeat {
            function: Rc::new(Box::new(s)),
            n: 2,
        };

        let res = rep.evaluate(T::start());

        assert_relative_eq!(res.x, 0.0);
        assert_relative_eq!(res.y, 0.0);

        let res = rep.evaluate(T::end());

        assert_relative_eq!(res.x, 1.0);
        assert_relative_eq!(res.y, 1.0);

        let res = rep.evaluate(T::new(0.5));

        assert_relative_eq!(res.x, 0.0);
        assert_relative_eq!(res.y, 0.0);
    }

    #[test]
    fn test_concat() {
        let s1 = Segment {
            start: (0.0, 0.0).into(),
            end: (1.0, 1.0).into(),
        };
        let s2 = Segment {
            start: (1.0, 1.0).into(),
            end: (0.0, 2.0).into(),
        };

        let concat = Concat {
            functions: vec![Rc::new(Box::new(s1)), Rc::new(Box::new(s2))],
        };

        let res = concat.evaluate(T::start());

        assert_relative_eq!(res.x, 0.0);
        assert_relative_eq!(res.y, 0.0);

        let res = concat.evaluate(T::end());

        assert_relative_eq!(res.x, 0.0);
        assert_relative_eq!(res.y, 2.0);

        let res = concat.evaluate(T::new(0.5));

        assert_relative_eq!(res.x, 1.0);
        assert_relative_eq!(res.y, 1.0);
    }

    #[test]
    fn test_concat_repeat() {
        let s1 = Segment {
            start: (0.0, 0.0).into(),
            end: (1.0, 1.0).into(),
        };
        let s2 = Segment {
            start: (1.0, 1.0).into(),
            end: (0.0, 2.0).into(),
        };

        let concat = Concat {
            functions: vec![Rc::new(Box::new(s1)), Rc::new(Box::new(s2))],
        };
        let repeat = Repeat {
            function: Rc::new(Box::new(concat)),
            n: 2,
        };

        let res = repeat.evaluate(T::start());
        assert_relative_eq!(res.x, 0.0);
        assert_relative_eq!(res.y, 0.0);

        let res = repeat.evaluate(T::end());
        assert_relative_eq!(res.x, 0.0);
        assert_relative_eq!(res.y, 2.0);

        let res = repeat.evaluate(T::new(0.5));
        assert_relative_eq!(res.x, 0.0);
        assert_relative_eq!(res.y, 0.0);

        let res = repeat.evaluate(T::new(0.75));
        assert_relative_eq!(res.x, 1.0);
        assert_relative_eq!(res.y, 1.0);

        let res = repeat.evaluate(T::new(0.125));
        assert_relative_eq!(res.x, 0.5);
        assert_relative_eq!(res.y, 0.5);
    }

    #[test]
    fn test_random() {
        let s = Segment {
            start: (0.0, 0.0).into(),
            end: (1.0, 1.0).into(),
        };

        let _p = s.random_point();
        let ps = s.random_points(100);
        assert_eq!(ps.len(), 100)
    }

    #[test]
    fn test_rotate() {
        let s = Segment {
            start: (0.0, 0.0).into(),
            end: (1.0, 1.0).into(),
        };
        let r = Rotate {
            function: Rc::new(Box::new(s)),
            centre: (0.5, 0.5).into(),
            angle: T::new(0.25),
        };

        let t = T::start();
        let res = r.evaluate(t);

        assert_relative_eq!(res.x, 1.0, epsilon = f32::EPSILON * 10.0);
        assert_relative_eq!(res.y, 0.0, epsilon = f32::EPSILON * 10.0);

        let t = T::end();
        let res = r.evaluate(t);

        assert_relative_eq!(res.x, 0.0, epsilon = f32::EPSILON * 10.0);
        assert_relative_eq!(res.y, 1.0, epsilon = f32::EPSILON * 10.0);
    }

    #[test]
    fn test_translate() {
        let s = Segment {
            start: (0.0, 0.0).into(),
            end: (1.0, 1.0).into(),
        };
        let tr = Translate {
            function: Rc::new(Box::new(s)),
            by: (0.5, 0.5).into(),
        };

        let t = T::start();
        let res = tr.evaluate(t);

        assert_relative_eq!(res.x, 0.5, epsilon = f32::EPSILON * 10.0);
        assert_relative_eq!(res.y, 0.5, epsilon = f32::EPSILON * 10.0);

        let t = T::end();
        let res = tr.evaluate(t);

        assert_relative_eq!(res.x, 1.5, epsilon = f32::EPSILON * 10.0);
        assert_relative_eq!(res.y, 1.5, epsilon = f32::EPSILON * 10.0);
    }

    #[test]
    fn test_rotate_translate() {
        let s = Segment {
            start: (0.0, 0.0).into(),
            end: (1.0, 1.0).into(),
        };
        let r_tr = RotateTranslate {
            function: Rc::new(Box::new(s)),
            centre: (0.5, 0.5).into(),
            angle: T::new(0.25),
            by: (0.5, 0.5).into(),
            rotate_first: true,
        };

        let t = T::start();
        let res = r_tr.evaluate(t);

        assert_relative_eq!(res.x, 1.5, epsilon = f32::EPSILON * 10.0);
        assert_relative_eq!(res.y, 0.5, epsilon = f32::EPSILON * 10.0);

        let t = T::end();
        let res = r_tr.evaluate(t);

        assert_relative_eq!(res.x, 0.5, epsilon = f32::EPSILON * 10.0);
        assert_relative_eq!(res.y, 1.5, epsilon = f32::EPSILON * 10.0);

        let s = Segment {
            start: (0.0, 0.0).into(),
            end: (1.0, 1.0).into(),
        };
        let r_tr = RotateTranslate {
            function: Rc::new(Box::new(s)),
            centre: (0.5, 0.5).into(),
            angle: T::new(0.25),
            by: (0.5, 0.5).into(),
            rotate_first: false,
        };

        let t = T::start();
        let res = r_tr.evaluate(t);

        assert_relative_eq!(res.x, 0.5, epsilon = f32::EPSILON * 10.0);
        assert_relative_eq!(res.y, 0.5, epsilon = f32::EPSILON * 10.0);

        let t = T::end();
        let res = r_tr.evaluate(t);

        assert_relative_eq!(res.x, -0.5, epsilon = f32::EPSILON * 10.0);
        assert_relative_eq!(res.y, 1.5, epsilon = f32::EPSILON * 10.0);
    }

    #[test]
    fn test_for_closures() {
        let foo = |t: T| Into::<Point>::into((t.value(), t.value()));

        let res = foo.evaluate(T::start());
        assert_relative_eq!(res.x, 0.0);
        assert_relative_eq!(res.y, 0.0);

        let c = Repeat {
            function: Rc::new(Box::new(foo)),
            n: 2,
        };
        c.linspace(10);
    }

    #[test]
    fn test_1d() {
        let foo = |t: T| t.value();
        let res = foo.evaluate(T::start());
        assert_relative_eq!(res, 0.0);

        let bar = (foo, foo);
        let res = bar.evaluate(T::start());
        assert_relative_eq!(res.x, 0.0);
        assert_relative_eq!(res.y, 0.0);

        let rep = Repeat {
            function: Rc::new(Box::new(bar)),
            n: 2,
        };

        let res = rep.evaluate(T::new(0.5));
        assert_relative_eq!(res.x, 0.0);
        assert_relative_eq!(res.y, 0.0);
    }

    #[test]
    fn test_scale() {
        let c = Circle::new((1.0, 1.0).into(), 10.0, None);
        let scaled_c = Scale {
            function: Rc::new(Box::new(c)),
            centre: (1.0, 1.0).into(),
            scale_x: 0.5,
            scale_y: 2.0,
        };

        let s = scaled_c.start();
        assert_relative_eq!(s.x, 6.0, epsilon = f32::EPSILON * 10.0);
        assert_relative_eq!(s.y, 1.0, epsilon = f32::EPSILON * 10.0);

        let s = scaled_c.evaluate(T::new(0.25));
        assert_relative_eq!(s.x, 1.0, epsilon = f32::EPSILON * 10.0);
        assert_relative_eq!(s.y, 21.0, epsilon = f32::EPSILON * 10.0);
    }
}