wallswitch 0.60.6

randomly selects wallpapers for multiple monitors
Documentation
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
//! Julia Set fractal generator overlay.
//!
//! This module provides the implementation of the Julia Set fractal renderer,
//! using pre-programmed coordinate presets. It generates mathematical overlays
//! dynamically fitted to the display dimensions and blends them using high-contrast
//! dual-tone chromatic borders and 3D shadow depth offsets.

use crate::effects::{
    FractalPreset, MAX_ITERATIONS, MIN_ITERATIONS, ProceduralEffect, Viewport, ViewportSpecs,
    color_distance_estimator, compute_escape_iterations, get_rotation_phasors, partition_rows,
};
use crate::{Complex, ImageEffect, NEON_PALETTES, NeonColor, get_random_integer};
use image::RgbImage;
use std::thread;

/// Implementation of the [`ImageEffect`] trait for rendering Julia Set fractals.
impl ImageEffect for JuliaGenerator {
    /// Applies the Julia Set procedural overlay onto an in-memory image buffer.
    fn apply(&self, rgb_img: &mut RgbImage) {
        let (width, height) = rgb_img.dimensions();
        let w_f = width as f64;
        let h_f = height as f64;

        let specs = ViewportSpecs {
            center: self.preset.center,
            zoom: self.zoom,
            cos_angle: self.cos_angle,
            sin_angle: self.sin_angle,
            is_julia: true,
        };
        let viewport = Viewport::new(w_f, h_f, &specs);

        let scan_iterations = self.scan_iterations;
        let center = self.preset.center;
        let (mut rows, width_usize) = partition_rows(rgb_img);

        let cores = thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(4);
        let chunk_size = (rows.len() / cores).max(1);

        let min_dim = w_f.min(h_f);
        let scale = self.zoom / min_dim;

        thread::scope(|scope| {
            let viewport_ref = &viewport;
            let color_palette = self.color_palette;
            for chunk in rows.chunks_mut(chunk_size) {
                scope.spawn(move || {
                    for (y, row_data) in chunk.iter_mut() {
                        let y_f = *y as f64;
                        for x in 0..width_usize {
                            let x_f = x as f64;
                            let z_init = viewport_ref.map(x_f, y_f);

                            let (i, z, dz) = compute_escape_iterations(
                                ProceduralEffect::JuliaSet,
                                z_init,
                                center,
                                scan_iterations,
                            );

                            let (fractal_rgb, alpha, s_alpha) = color_distance_estimator(
                                i,
                                scan_iterations,
                                z,
                                dz,
                                scale,
                                color_palette,
                            );

                            let idx = x * 3;
                            crate::effects::blend_and_vignette_pixel(
                                row_data,
                                idx,
                                fractal_rgb,
                                alpha,
                                s_alpha,
                            );
                        }
                    }
                });
            }
        });
    }

    /// Returns formatting diagnostic information about the active generator.
    fn info(&self) -> String {
        format!(
            "fractal [{}]\n\
            f(z) = z^2 + c, where c = {:8.5} {} {:7.5}i (iter = {:4}, zoom = {:.2}), color: {}",
            self.preset.fractal_name,
            self.preset.center.re,
            if self.preset.center.im >= 0.0 {
                "+"
            } else {
                "-"
            },
            self.preset.center.im.abs(),
            self.scan_iterations,
            self.zoom,
            self.color_palette
        )
    }
}

/// A procedural generator for rendering Julia Set fractals onto desktop backgrounds.
///
/// Combines mathematical coordinate presets with viewport fitting, lighting shaders,
/// and color interpolation to produce high-definition digital art overlays.
///
/// # Mathematical Foundation
/// The Julia Set is computed by mapping viewport coordinates z_0 in complex space under
/// the quadratic recurrence relation:
///
/// z_(n+1) = f(z_n) = z_n^2 + c
///
/// Where the perturbation parameter c is a constant determined by the preset.
/// Points are classified as escaping if at any step n, the magnitude of z_n is greater than 2.
pub struct JuliaGenerator {
    /// The active coordinate preset, enclosing the center points and metadata.
    pub preset: FractalPreset,
    /// The maximum iteration limit for escape-time calculations.
    pub scan_iterations: u32,
    /// The base color palette selected for the neon glow.
    pub color_palette: NeonColor,
    /// The viewport zoom level.
    pub zoom: f64,
    /// The cosine of the rotation angle.
    pub cos_angle: f64,
    /// The sine of the rotation angle.
    pub sin_angle: f64,
}

impl Default for JuliaGenerator {
    /// Returns the default fallback instance of the Julia Set generator.
    fn default() -> Self {
        Self {
            preset: FractalPreset {
                center: Complex::new(-0.7, 0.27015),
                fractal_name: "Classic dendrite",
                effect_name: ProceduralEffect::JuliaSet,
            },
            scan_iterations: get_random_integer(MIN_ITERATIONS, MAX_ITERATIONS),
            color_palette: NEON_PALETTES[5],
            zoom: 3.0,
            cos_angle: 1.0,
            sin_angle: 0.0,
        }
    }
}

impl JuliaGenerator {
    /// Generates a randomized Julia Set configuration fitted to the target aspect ratio.
    ///
    /// Selects one of the built-in coordinate presets, assigns a neon color palette,
    /// rotates the coordinate system randomly, and optimizes the viewport fit.
    pub fn random(monitor: &crate::Monitor) -> Self {
        let width = monitor.resolution.width as u32;
        let height = monitor.resolution.height as u32;

        let presets = [
            FractalPreset {
                center: Complex::new(-0.4, 0.6),
                fractal_name: "Classic cloud swirls",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.8, 0.156),
                fractal_name: "Detailed spirals",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.7269, 0.1889),
                fractal_name: "Lace structures",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.75, 0.11),
                fractal_name: "Feathery branches",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.1, 0.651),
                fractal_name: "Cosmic dust style",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(0.355, 0.355),
                fractal_name: "Spiral galaxy arms",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.4, -0.59),
                fractal_name: "Swirling vortexes",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.54, 0.54),
                fractal_name: "Ornamental lace borders",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.835, -0.2321),
                fractal_name: "Lightning rods",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.77269, 0.12428),
                fractal_name: "Coral reefs",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.51251, 0.5213),
                fractal_name: "Fine lace filaments",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.55, 0.55),
                fractal_name: "Intricate leaf outlines",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.624, 0.435),
                fractal_name: "Crystalline snowflake patterns",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.12, 0.85),
                fractal_name: "Flowing plasma plumes",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.391, -0.587),
                fractal_name: "Swirling storm clouds",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.73, 0.21),
                fractal_name: "Feathery dendritic lace",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.81, 0.2),
                fractal_name: "Spiral galaxy filaments",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.68, 0.34),
                fractal_name: "Delicate coral spirals",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.76, 0.08),
                fractal_name: "Lightning tree branches",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(0.285, 0.01),
                fractal_name: "Cosmic galaxy vortex swirls",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.8, 0.17),
                fractal_name: "Spidery lace denderites",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.7269, -0.1889),
                fractal_name: "Conjugate lace structures",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.835, 0.2321),
                fractal_name: "Conjugate lightning rods",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.75, 0.05),
                fractal_name: "Dense branching coral reef",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.70176, 0.3842),
                fractal_name: "Conjugate dragon-like curves",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.8, 0.16),
                fractal_name: "Deep sea coral spirals",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.722, 0.246),
                fractal_name: "Dendritic pine branch variation",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.11, 0.655),
                fractal_name: "Triple helix rotational cosmic swirls",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.52519, 0.5215),
                fractal_name: "Intertwined Gothic Cathedral window arches",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(0.28, 0.008),
                fractal_name: "Centrifugal pinwheel galaxy vortex generator",
                effect_name: ProceduralEffect::JuliaSet,
            },
            FractalPreset {
                center: Complex::new(-0.83, -0.232),
                fractal_name: "Sharp crystalline glacial ice column needles",
                effect_name: ProceduralEffect::JuliaSet,
            },
        ];

        let p_idx: usize = get_random_integer(0, NEON_PALETTES.len() - 1);
        let color_palette = NEON_PALETTES[p_idx];

        let angle_degrees: f64 = get_random_integer(0, 359);
        let radians = angle_degrees.to_radians();

        let preset_idx: usize = get_random_integer(0, presets.len() - 1);
        let selected_preset = presets[preset_idx];

        let mut julia = Self {
            preset: selected_preset,
            scan_iterations: get_random_integer(MIN_ITERATIONS, MAX_ITERATIONS),
            color_palette,
            zoom: 3.0,
            cos_angle: radians.cos(),
            sin_angle: radians.sin(),
        };

        julia.optimize_fit(width, height);
        julia
    }

    /// Optimizes the viewport boundaries by scanning complex boundaries and finding a balanced zoom.
    ///
    /// Preserves exact spatial conformality during search limits calculation.
    pub fn optimize_fit(&mut self, width: u32, height: u32) {
        let w_f = width as f64;
        let h_f = height as f64;
        let min_dim = w_f.min(h_f);

        let c_abs = self.preset.center.norm_sq().sqrt();
        let r_bound = (1.0 + (1.0 + 4.0 * c_abs).sqrt()) / 2.0;
        let search_limit = r_bound * 1.2;

        let steps = 128;
        let inv_steps_minus_1 = 1.0 / (steps - 1) as f64;
        let range = 2.0 * search_limit;

        let scan_iterations = self.scan_iterations;
        let mut active_points = Vec::with_capacity(steps * steps / 2);

        for step_y in 0..steps {
            let ry = -search_limit + (step_y as f64 * inv_steps_minus_1) * range;
            for step_x in 0..steps {
                let rx = -search_limit + (step_x as f64 * inv_steps_minus_1) * range;

                let (i, _, _) = compute_escape_iterations(
                    ProceduralEffect::JuliaSet,
                    Complex::new(rx, ry),
                    self.preset.center,
                    scan_iterations,
                );

                if i > 3 && i < scan_iterations {
                    // Coordinates are pushed directly as Complex coordinates
                    active_points.push(Complex::new(rx, ry));
                }
            }
        }

        if !active_points.is_empty() {
            let mut best_zoom = f64::MAX;
            let mut best_cos = self.cos_angle;
            let mut best_sin = self.sin_angle;

            for phasor in get_rotation_phasors() {
                let mut max_cx_abs = 0.0_f64;
                let mut max_cy_abs = 0.0_f64;

                // To map active points from complex space back to viewport space
                // for bounding box calculations, we must apply the inverse rotation.
                // In complex algebra, the inverse is represented by the complex conjugate.
                let inverse_phasor = phasor.conj();

                for &point in &active_points {
                    let rotated = point * inverse_phasor;
                    max_cx_abs = max_cx_abs.max(rotated.re.abs());
                    max_cy_abs = max_cy_abs.max(rotated.im.abs());
                }

                let zoom_x = 2.0 * max_cx_abs * min_dim / w_f;
                let zoom_y = 2.0 * max_cy_abs * min_dim / h_f;
                let required_zoom = zoom_x.max(zoom_y);

                if required_zoom < best_zoom {
                    best_zoom = required_zoom;
                    best_cos = phasor.re;
                    best_sin = phasor.im;
                }
            }

            self.zoom = best_zoom * 1.10;
            self.cos_angle = best_cos;
            self.sin_angle = best_sin;
        } else {
            self.zoom = 2.0 * r_bound * 1.10;
        }
    }
}

#[cfg(test)]
mod tests_julia {
    use super::*;
    use crate::core::Monitor;

    #[test]
    fn test_julia_generation_random() {
        let monitor = Monitor::default();
        let julia = JuliaGenerator::random(&monitor);
        assert!(julia.zoom > 0.0);
        assert_eq!(julia.preset.effect_name, ProceduralEffect::JuliaSet);
    }
}