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
#![warn(missing_docs)]

//! # tahga::growth::hyphae::hypha
//!
//! The growth::hyphae::hyphae module defines a single hypha used in the hypha growth algorithm

use nannou::color::Alpha;
use nannou::prelude::*;
use uuid::Uuid;

use crate::stroke::line::Line;

/// A [`Hypha`] generator
#[derive(Debug)]
pub struct Factory {
    /// Return a value for direction variance
    pub fn_direction_variance: fn() -> f32,
    /// Return a min direction variance
    pub fn_min_direction_variance: fn() -> f32,
    /// Return a max direction variance
    pub fn_max_direction_variance: fn() -> f32,
    /// Return direction variance multiplier
    pub fn_direction_variance_multiplier: fn() -> f32,
    /// Probability of a hypha creating a branch
    pub fn_branch_probability: fn() -> f32,
    /// Return a value for speed
    pub fn_speed: fn() -> f32,
    /// Return a min speed
    pub fn_min_speed: fn() -> f32,
    /// Return a max speed
    pub fn_max_speed: fn() -> f32,
    /// Return speed multiplier
    pub fn_speed_multiplier: fn() -> f32,
    /// Return a value for weight
    pub fn_weight: fn() -> f32,
    /// Return a min weight
    pub fn_min_weight: fn() -> f32,
    /// Return a max weight
    pub fn_max_weight: fn() -> f32,
    /// Return weight multiplier
    pub fn_weight_multiplier: fn() -> f32,
    /// Return a cargo value
    pub fn_cargo: fn() -> i32,
}

impl Factory {
    /// Create a new [`Factory`] instance
    ///
    pub fn new() -> Self {
        Self {
            fn_direction_variance: || random_range(0.4, 0.8),
            fn_min_direction_variance: || 0.,
            fn_max_direction_variance: || 3.,
            fn_direction_variance_multiplier: || 1.1,
            fn_branch_probability: || 0.8,
            fn_speed: || random_range(4., 10.),
            fn_min_speed: || 4.,
            fn_max_speed: || 20.,
            fn_speed_multiplier: || 0.7,
            fn_weight: || random_range(4., 6.),
            fn_min_weight: || 1.,
            fn_max_weight: || 8.,
            fn_weight_multiplier: || 0.7,
            fn_cargo: || 0,
        }
    }

    /// Set the function which will return the direction variance
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_direction_variance(mut self, f: fn() -> f32) -> Self {
        self.fn_direction_variance = f;
        self
    }

    /// Set the function which will return the minimum direction variance
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_min_direction_variance(mut self, f: fn() -> f32) -> Self {
        self.fn_min_direction_variance = f;
        self
    }

    /// Set the function which will return the maximum direction variance
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_max_direction_variance(mut self, f: fn() -> f32) -> Self {
        self.fn_max_direction_variance = f;
        self
    }

    /// Set the function which will return the direction multiplier
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_direction_variance_multiplier(mut self, f: fn() -> f32) -> Self {
        self.fn_direction_variance_multiplier = f;
        self
    }

    /// Set the function which will return the branch probability
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_branch_probability(mut self, f: fn() -> f32) -> Self {
        self.fn_branch_probability = f;
        self
    }

    /// Set the function which will return the speed
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_speed(mut self, f: fn() -> f32) -> Self {
        self.fn_speed = f;
        self
    }

    /// Set the function which will return the minimum speed
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_min_speed(mut self, f: fn() -> f32) -> Self {
        self.fn_min_speed = f;
        self
    }

    /// Set the function which will return the maximum speed
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_max_speed(mut self, f: fn() -> f32) -> Self {
        self.fn_max_speed = f;
        self
    }

    /// Set the function which will return the speed multiplier
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_speed_multiplier(mut self, f: fn() -> f32) -> Self {
        self.fn_speed_multiplier = f;
        self
    }

    /// Set the function which will return the weight
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_weight(mut self, f: fn() -> f32) -> Self {
        self.fn_weight = f;
        self
    }

    /// Set the function which will return the minimum weight
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_min_weight(mut self, f: fn() -> f32) -> Self {
        self.fn_min_weight = f;
        self
    }

    /// Set the function which will return the maximum weight
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_max_weight(mut self, f: fn() -> f32) -> Self {
        self.fn_max_weight = f;
        self
    }

    /// Set the function which will return the weight multiplier
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_weight_multiplier(mut self, f: fn() -> f32) -> Self {
        self.fn_weight_multiplier = f;
        self
    }

    /// Set the function which will return the cargo
    ///
    /// # Arguments
    ///
    /// `f` - The new function
    ///
    pub fn fn_cargo(mut self, f: fn() -> i32) -> Self {
        self.fn_cargo = f;
        self
    }

    /// Generate a new [`Hypha`] wit values defined by the factory
    ///
    pub fn generate(&self) -> Hypha {
        let mut hypha = Hypha::new();
        hypha.direction_variance = (self.fn_direction_variance)();
        hypha.min_direction_variance = (self.fn_min_direction_variance)();
        hypha.max_direction_variance = (self.fn_max_direction_variance)();
        hypha.direction_variance_multiplier = (self.fn_direction_variance_multiplier)();
        hypha.branch_probability = (self.fn_branch_probability)();
        hypha.speed = (self.fn_speed)();
        hypha.min_speed = (self.fn_min_speed)();
        hypha.max_speed = (self.fn_max_speed)();
        hypha.speed_multiplier = (self.fn_speed_multiplier)();
        hypha.weight = (self.fn_weight)();
        hypha.min_weight = (self.fn_min_weight)();
        hypha.max_weight = (self.fn_max_weight)();
        hypha.weight_multiplier = (self.fn_weight_multiplier)();
        hypha.branch_probability = (self.fn_branch_probability)();
        hypha.cargo = (self.fn_cargo)();
        hypha
    }
}

/// A single hypha
#[derive(Clone, Debug)]
pub struct Hypha {
    /// A unique id for this hypha
    pub id: Uuid,
    /// The id if the parent hypha
    pub parent_id: Option<Uuid>,
    /// The current position
    pub position: Vec2,
    /// The current direction
    pub direction: f32,
    /// The amount the direction can vary
    pub direction_variance: f32,
    /// The minimum amount the direction can vary
    pub min_direction_variance: f32,
    /// The maximum amount the direction can vary
    pub max_direction_variance: f32,
    /// The amount to multiply the direction variance by during each growth cycle
    pub direction_variance_multiplier: f32,
    /// Probability of a hypha creating a branch
    pub branch_probability: f32,
    /// The rate of growth
    pub speed: f32,
    /// The minimum speed
    pub min_speed: f32,
    /// The maximum speed
    pub max_speed: f32,
    /// The amount to multiply the speed by during each growth cycle
    pub speed_multiplier: f32,
    /// The thickness of the hypha
    pub weight: f32,
    /// The minimum weight
    pub min_weight: f32,
    /// The maximum weight
    pub max_weight: f32,
    /// The amount to multiply the weight by during each growth cycle
    pub weight_multiplier: f32,
    /// This hypha's color
    pub color: Alpha<Hsl, f32>,
    /// A record of the hypha's path
    pub path: Vec<Line>,
    /// If true, the hypha has died
    pub dead: bool,
    /// A user-defined value to be carried along by the hypha
    pub cargo: i32,
}

impl Hypha {
    /// Create a new instance of [`Hypha`] with default values
    ///
    /// # Arguments
    ///
    /// `id` - A unique id for this [`Hypha`]
    ///
    pub fn new() -> Self {
        Self {
            id: Uuid::new_v4(),
            parent_id: None,
            position: vec2(0., 0.),
            direction: random_range(-std::f32::consts::PI, std::f32::consts::PI),
            direction_variance: random_range(0.4, 0.8),
            min_direction_variance: 0.,
            max_direction_variance: 3.,
            direction_variance_multiplier: 1.1,
            branch_probability: 0.2,
            speed: random_range(4., 10.),
            min_speed: 4.,
            max_speed: 20.,
            speed_multiplier: 0.5,
            weight: 6.,
            min_weight: 4.,
            max_weight: 20.,
            weight_multiplier: 0.5,
            color: hsla(0.0, 1., 0.5, 1.0),
            path: Vec::new(),
            dead: false,
            cargo: 0,
        }
    }

    /// Set the parent_id for the hypha
    ///
    /// This is intended to be chained with new() in a builder pattern
    ///
    /// # Arguments
    ///
    /// `id`: The parent_id
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use uuid::Uuid;
    /// use tahga::growth::hyphae::hypha::Hypha;
    /// let parent_id = Uuid::new_v4();
    /// let h = Hypha::new().parent_id(parent_id);
    /// assert_eq!(h.parent_id.unwrap(), parent_id);
    /// ```
    ///
    pub fn parent_id(mut self, id: Uuid) -> Self {
        self.parent_id = Some(id);
        self
    }

    /// Set the position for the hypha
    ///
    /// This is intended to be chained with new() in a builder pattern
    ///
    /// # Arguments
    ///
    /// `position`: The new position
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use tahga::growth::hyphae::hypha::Hypha;
    /// let h = Hypha::new().position(vec2(1.,2.));
    /// assert_eq!(h.position.x, 1.);
    /// assert_eq!(h.position.y, 2.);
    /// ```
    ///
    pub fn position(mut self, position: Vec2) -> Self {
        self.position = position;
        self
    }

    /// Set the direction for the hypha
    ///
    /// This is intended to be chained with new() in a builder pattern
    ///
    /// # Arguments
    ///
    /// `direction`: The new direction
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use tahga::growth::hyphae::hypha::Hypha;
    /// let h = Hypha::new().direction(2.1);
    /// assert_eq!(h.direction, 2.1);
    /// ```
    ///
    pub fn direction(mut self, direction: f32) -> Self {
        self.direction = direction;
        self
    }

    /// Set the direction variance for the hypha
    ///
    /// This is intended to be chained with new() in a builder pattern
    ///
    /// # Arguments
    ///
    /// `direction_variance`: The new direction_variance
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use tahga::growth::hyphae::hypha::Hypha;
    /// let h = Hypha::new().direction_variance(0.1);
    /// assert_eq!(h.direction_variance, 0.1);
    /// ```
    ///
    pub fn direction_variance(mut self, direction_variance: f32) -> Self {
        self.direction_variance = direction_variance;
        self
    }

    /// Set the speed for the hypha
    ///
    /// This is intended to be chained with new() in a builder pattern
    ///
    /// # Arguments
    ///
    /// `speed`: The new speed
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use tahga::growth::hyphae::hypha::Hypha;
    /// let h = Hypha::new().speed(5.);
    /// assert_eq!(h.speed, 5.);
    /// ```
    ///
    pub fn speed(mut self, speed: f32) -> Self {
        self.speed = speed;
        self
    }

    /// Set the weight for the hypha
    ///
    /// This is intended to be chained with new() in a builder pattern
    ///
    /// # Arguments
    ///
    /// `weight`: The new weight
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use tahga::growth::hyphae::hypha::Hypha;
    /// let h = Hypha::new().weight(5.);
    /// assert_eq!(h.weight, 5.);
    /// ```
    ///
    pub fn weight(mut self, weight: f32) -> Self {
        self.weight = weight;
        self
    }

    /// Set the color for the hypha
    ///
    /// This is intended to be chained with new() in a builder pattern
    ///
    /// # Arguments
    ///
    /// `color`: The new color
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use tahga::growth::hyphae::hypha::Hypha;
    /// let h = Hypha::new().color(hsla(0.7, 0.9, 0.3, 0.01));
    /// let c = h.color.into_components();
    /// assert_eq!(c.2, 0.3);
    /// ```
    ///
    pub fn color(mut self, color: Alpha<Hsl, f32>) -> Self {
        self.color = color;
        self
    }

    /// Grow a hypha, possibly branching a new hypha
    ///
    /// # Arguments
    ///
    /// `factory` - A reference to the factory to use to create a new [`Hypha`]
    ///
    pub fn update(&mut self, factory: &Factory) -> Option<Hypha> {
        let old_position = self.position;
        // Why use map_range() here instead of just using random_range()?
        // Because this way works even when the direction variance is zero.
        let direction = self.direction
            + map_range(random_f32(), 0., 1., -self.direction_variance, self.direction_variance);
        let dx = self.speed * direction.cos();
        let dy = self.speed * direction.sin();
        self.position += vec2(dx as f32, dy as f32);

        self.path.push(Line::new(old_position, self.position, self.weight, self.color));

        if random_f32() > self.branch_probability {
            return None;
        }

        // Create a new hypha
        let side = match random() {
            true => -1.,
            false => 1.,
        };
        let new_direction = direction
            + side * std::f32::consts::PI / 2.
            + map_range(random_f32(), 0., 1., -self.direction_variance / 2., self.direction_variance / 2.);
        let new_weight = match self.weight {
            n if n > self.max_weight => self.max_weight,
            n if n < self.min_weight => self.min_weight,
            _ => self.weight * self.weight_multiplier,
        };
        let new_speed = match self.speed {
            n if n > self.max_speed => self.max_speed,
            n if n < self.min_speed => self.min_speed,
            _ => self.speed * self.speed_multiplier,
        };
        let new_direction_variance = match self.direction_variance {
            n if n > self.max_direction_variance => self.max_direction_variance,
            n if n < self.min_direction_variance => self.min_direction_variance,
            _ => self.direction_variance * self.direction_variance_multiplier,
        };

        Some(factory.generate()
            .parent_id(self.id)
            .position(old_position)
            .color(self.color)
            .weight(new_weight)
            .speed(new_speed)
            .direction(new_direction)
            .direction_variance(new_direction_variance)
        )
    }
}