wallswitch 0.60.5

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
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
//! Newton-Raphson Basin fractal generator overlay.
//!
//! This module implements the Relaxed Newton-Raphson fractal for solving complex polynomial
//! equations of the form z^p - 1 = 0. By introducing a complex relaxation parameter (lambda),
//! the standard basins of attraction warp into intricate, symmetric, mandala-like
//! structures featuring nested circular bands, spiral arms, and crystalline structures.

use crate::effects::{
    MAX_ITERATIONS, MIN_ITERATIONS, Viewport, ViewportSpecs, blend_and_vignette_pixel,
    get_rotation_steps, partition_rows, rotate_point,
};
use crate::{
    Complex, ImageEffect, NEON_PALETTES, NeonColor, WallSwitchError, WallSwitchResult,
    get_random_integer,
};
use image::RgbImage;
use std::{io::Error, path::Path, thread};

/// Valid operational range for randomized zoom viewport allocation.
const ZOOM_RANGE: [f64; 2] = [1.5, 3.8];

/// Structural parameters for polynomial evaluation and deformation.
///
/// Holds the power p of the equation z^p - 1 = 0, the relaxation parameter lambda,
/// and a user-friendly preset name.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NewtonPreset {
    /// Power of the polynomial.
    pub power: u32,
    /// Complex relaxation scale parameter.
    pub lambda: Complex,
    /// Human-readable name of the specific layout.
    pub name: &'static str,
}

impl ImageEffect for NewtonGenerator {
    /// Applies the Newton-Raphson fractal overlay directly onto an in-memory image buffer.
    fn apply(&self, rgb_img: &mut RgbImage) {
        self.apply_effect_in_memory(rgb_img);
    }

    /// Returns a formatted string containing specific diagnostic details of the active effect.
    fn info(&self) -> String {
        format!(
            "fractal [{}]\n\
            f(z) = z^{} - 1 = 0, where lambda = {:5.2} {} {:4.2}i (iter = {:4}, zoom = {:.2}), color: {}",
            self.preset.name,
            self.preset.power,
            self.preset.lambda.re,
            if self.preset.lambda.im >= 0.0 {
                "+"
            } else {
                "-"
            },
            self.preset.lambda.im.abs(),
            self.scan_iterations,
            self.zoom,
            self.color_palette
        )
    }
}

/// A procedural generator for rendering Newton-Raphson Basin fractals onto backgrounds.
pub struct NewtonGenerator {
    /// Active parameters governing formula geometry.
    pub preset: NewtonPreset,
    /// Maximum scan operations limits.
    pub scan_iterations: u32,
    /// Neon visual coloring profiles.
    pub color_palette: NeonColor,
    /// Viewport translation zoom index.
    pub zoom: f64,
    /// Cosine of active viewport rotation angle.
    pub cos_angle: f64,
    /// Sine of active viewport rotation angle.
    pub sin_angle: f64,
}

impl Default for NewtonGenerator {
    fn default() -> Self {
        Self {
            preset: NewtonPreset {
                power: 3,
                lambda: Complex::new(1.0, 0.3),
                name: "Gothic Rose Mandala",
            },
            scan_iterations: get_random_integer::<_, u32>(MIN_ITERATIONS / 10, MAX_ITERATIONS / 10)
                .max(60),
            color_palette: NEON_PALETTES[0],
            zoom: 2.0,
            cos_angle: 1.0,
            sin_angle: 0.0,
        }
    }
}

impl NewtonGenerator {
    /// Generates a randomized Newton Basin configuration fitted to the aspect ratio.
    pub fn random(monitor: &crate::Monitor) -> Self {
        let width = monitor.resolution.width as u32;
        let height = monitor.resolution.height as u32;

        let presets = [
            // --- Classical Geometric Patterns ---
            NewtonPreset {
                power: 3,
                lambda: Complex::new(1.0, 0.3),
                name: "Gothic Rose Mandala",
            },
            NewtonPreset {
                power: 5,
                lambda: Complex::new(0.9, 0.1),
                name: "Imperial Star Compass",
            },
            NewtonPreset {
                power: 4,
                lambda: Complex::new(1.0, 0.0),
                name: "Stained Glass Kaleidoscope",
            },
            NewtonPreset {
                power: 6,
                lambda: Complex::new(0.85, 0.2),
                name: "Cosmic Snowflake Grid",
            },
            NewtonPreset {
                power: 3,
                lambda: Complex::new(1.35, 0.0),
                name: "Spiked Crown of Thorns",
            },
            NewtonPreset {
                power: 8,
                lambda: Complex::new(0.7, 0.4),
                name: "Quantum Energy Shells",
            },
            NewtonPreset {
                power: 5,
                lambda: Complex::new(1.1, 0.25),
                name: "Solar Flare Compass",
            },
            NewtonPreset {
                power: 3,
                lambda: Complex::new(0.8, 0.5),
                name: "Celtic Knotwork Ribbon",
            },
            NewtonPreset {
                power: 4,
                lambda: Complex::new(0.6, 0.6),
                name: "Nautilus Spiral Chamber",
            },
            NewtonPreset {
                power: 7,
                lambda: Complex::new(1.0, 0.05),
                name: "Hyper-Dimensional Matrix",
            },
            // --- Twisted & High-Deformation Wave Mandalas ---
            NewtonPreset {
                power: 6,
                lambda: Complex::new(1.15, 0.15),
                name: "Aetheric Frost Flower",
            },
            NewtonPreset {
                power: 8,
                lambda: Complex::new(0.90, 0.30),
                name: "Celestial Gearwork",
            },
            NewtonPreset {
                power: 3,
                lambda: Complex::new(0.75, 0.60),
                name: "Byzantine Dome",
            },
            NewtonPreset {
                power: 5,
                lambda: Complex::new(1.25, -0.20),
                name: "Abyssal Starfish",
            },
            NewtonPreset {
                power: 4,
                lambda: Complex::new(0.80, 0.45),
                name: "Hyperborean Sigil",
            },
            NewtonPreset {
                power: 7,
                lambda: Complex::new(1.0, -0.30),
                name: "Prismatic Labyrinth",
            },
            NewtonPreset {
                power: 3,
                lambda: Complex::new(0.95, 0.80),
                name: "Nebula Core Spiral",
            },
            NewtonPreset {
                power: 5,
                lambda: Complex::new(0.60, 0.80),
                name: "Aura Borealis Compass",
            },
            NewtonPreset {
                power: 10,
                lambda: Complex::new(0.85, 0.0),
                name: "Obsidian Glass Lattices",
            },
            NewtonPreset {
                power: 4,
                lambda: Complex::new(1.40, -0.40),
                name: "Bio-Polymer Filament",
            },
        ];

        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 newton = Self {
            preset: selected_preset,
            scan_iterations: get_random_integer(40, 100),
            color_palette,
            zoom: 2.0,
            cos_angle: radians.cos(),
            sin_angle: radians.sin(),
        };

        newton.optimize_fit(width, height);
        newton
    }

    /// Automatically scales the viewport boundaries with randomized micro-deviations.
    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 search_limit = 1.8_f64;
        let steps = 64;
        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);

        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_newton_escape(
                    Complex::new(rx, ry),
                    self.preset.power,
                    self.preset.lambda,
                    scan_iterations,
                );

                if i > 2 && i < scan_iterations - 2 {
                    active_points.push((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 (_rad, cos_t, sin_t) in get_rotation_steps() {
                let mut max_cx_abs = 0.0_f64;
                let mut max_cy_abs = 0.0_f64;

                for &(rx, ry) in &active_points {
                    let (cx, cy) = rotate_point(rx, ry, cos_t, sin_t);
                    max_cx_abs = max_cx_abs.max(cx.abs());
                    max_cy_abs = max_cy_abs.max(cy.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 = cos_t;
                    best_sin = sin_t;
                }
            }

            // Introduce a randomized scaling multiplier between 95% and 125%
            let rand_factor = get_random_integer::<_, f64>(95, 125) / 100.0;
            self.zoom = (best_zoom * rand_factor).clamp(ZOOM_RANGE[0], ZOOM_RANGE[1]);
            self.cos_angle = best_cos;
            self.sin_angle = best_sin;
        } else {
            // Roll a flat random zoom within the bounded range if no points detected
            let flat_rand = get_random_integer::<_, f64>(150, 250) / 100.0;
            self.zoom = flat_rand.clamp(ZOOM_RANGE[0], ZOOM_RANGE[1]);
        }
    }

    /// Renders the Newton Fractal Basin in-place over the active background memory buffer.
    pub fn apply_effect_in_memory(&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: Complex::new(0.0, 0.0),
            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 power = self.preset.power;
        let lambda = self.preset.lambda;

        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);

        thread::scope(|scope| {
            let viewport_ref = &viewport;
            let color_palette = self.color_palette.to_array();
            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, diff_norm, z_final) =
                                compute_newton_escape(z_init, power, lambda, scan_iterations);

                            let smooth_i = if i < scan_iterations {
                                i as f32
                                    + (diff_norm.ln() as f32 / (1e-6_f64).ln() as f32)
                                        .clamp(0.0, 1.0)
                            } else {
                                scan_iterations as f32
                            };

                            let (fractal_rgb, alpha, s_alpha) = if i < scan_iterations {
                                let ripple_frequency = 0.5_f32;
                                let norm_dist =
                                    (smooth_i * ripple_frequency * std::f32::consts::PI)
                                        .sin()
                                        .abs();

                                let core = if norm_dist > 0.95 {
                                    (norm_dist - 0.95) / 0.05
                                } else {
                                    0.0
                                };

                                let glow = norm_dist.powi(5) * 0.40;
                                let profile = core * 0.70 + glow * 0.30;

                                let shadow_profile = (1.0 - norm_dist).powi(2) * 0.35;

                                let angle = z_final.im.atan2(z_final.re) as f32;
                                let light = 0.70_f32 + 0.30_f32 * (angle * 3.0).cos().abs();

                                let t_cycled = (smooth_i * 0.08) % 1.0;
                                let secondary_color =
                                    [color_palette[1], color_palette[2], color_palette[0]];

                                let r_grad = color_palette[0] * (1.0 - t_cycled)
                                    + secondary_color[0] * t_cycled;
                                let g_grad = color_palette[1] * (1.0 - t_cycled)
                                    + secondary_color[1] * t_cycled;
                                let b_grad = color_palette[2] * (1.0 - t_cycled)
                                    + secondary_color[2] * t_cycled;

                                let core_color = [r_grad, g_grad, b_grad];

                                let mut border_color = [1.0 - r_grad, 1.0 - g_grad, 1.0 - b_grad];
                                let max_val =
                                    border_color[0].max(border_color[1]).max(border_color[2]);
                                if max_val > 0.0 {
                                    border_color[0] /= max_val;
                                    border_color[1] /= max_val;
                                    border_color[2] /= max_val;
                                }

                                let r_blended =
                                    core_color[0] * norm_dist + border_color[0] * (1.0 - norm_dist);
                                let g_blended =
                                    core_color[1] * norm_dist + border_color[1] * (1.0 - norm_dist);
                                let b_blended =
                                    core_color[2] * norm_dist + border_color[2] * (1.0 - norm_dist);

                                let brightness_boost = 1.25_f32;

                                let rgb = [
                                    (r_blended * light * brightness_boost).clamp(0.0, 1.0),
                                    (g_blended * light * brightness_boost).clamp(0.0, 1.0),
                                    (b_blended * light * brightness_boost).clamp(0.0, 1.0),
                                ];

                                let iteration_fade = if i < 8 { i as f32 / 8.0 } else { 1.0 };

                                (
                                    rgb,
                                    profile * 0.95 * iteration_fade,
                                    shadow_profile * iteration_fade,
                                )
                            } else {
                                ([0.0, 0.0, 0.0], 0.0, 0.0)
                            };

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

    /// Helper to process, render, and write output files directly to system storage.
    pub fn apply_effect<P: AsRef<Path>>(
        &self,
        input_path: P,
        output_path: P,
    ) -> WallSwitchResult<()> {
        let img = image::open(&input_path)
            .map_err(|e| WallSwitchError::UnableToFind(format!("Failed to open image: {e}")))?;

        let mut rgb_img = img.to_rgb8();
        self.apply_effect_in_memory(&mut rgb_img);

        rgb_img
            .save(&output_path)
            .map_err(|e| WallSwitchError::Io(Error::other(e)))?;

        Ok(())
    }
}

// ==============================================================================
// MATH ENGINE: RELAXED NEWTON-RAPHSON ROOT CONVERGENCE
// ==============================================================================

/// Evaluates polynomial convergence under a relaxed Newton-Raphson iteration loop.
///
/// This function uses the standard formula:
/// z_next = z - lambda * f(z) / f'(z)
///
/// where f(z) = z^p - 1 and f'(z) = p * z^(p-1).
#[inline(always)]
fn compute_newton_escape(
    z_init: Complex,
    power: u32,
    lambda: Complex,
    scan_iterations: u32,
) -> (u32, f64, Complex) {
    let mut z = z_init;
    let p_f = power as f64;

    let mut i = 0;
    let mut diff_norm = 1.0;

    while i < scan_iterations {
        if z.norm_sq() < 1e-8 {
            break;
        }

        let z_prev_p_minus_1 = z.pow(power - 1);
        let z_p = z_prev_p_minus_1 * z;

        // f(z) = z^p - 1
        let f_z = z_p - Complex::new(1.0, 0.0);

        // f'(z) = p * z^(p-1)
        let f_prime_z = z_prev_p_minus_1 * p_f;

        // step = lambda * f(z) / f'(z)
        let step = lambda * (f_z / f_prime_z);
        let z_next = z - step;

        diff_norm = step.norm_sq();

        if diff_norm < 1e-6 {
            z = z_next;
            break;
        }

        z = z_next;
        i += 1;
    }

    (i, diff_norm, z)
}