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
554
555
556
557
558
559
560
561
562
563
564
565
566
//! Mandelbrot Set fractal generator overlay.
//!
//! This module provides the implementation of the Mandelbrot Set fractal renderer,
//! using precalculating zoom presets. It generates mathematical overlays dynamically
//! fitted to display proportions and blends them using high-definition neon curves,
//! chromatic dual-tone borders, and 3D parallax shadow depths.
use crate::effects::{
FractalPreset, MAX_ITERATIONS, MIN_ITERATIONS, ProceduralEffect, Viewport, ViewportSpecs,
blend_and_vignette_pixel, calculate_distance_estimator, calculate_smooth_potential,
compute_escape_iterations, get_rotation_steps, partition_rows,
};
use crate::{
ImageEffect, NEON_PALETTES, NeonColor, WallSwitchError, WallSwitchResult, get_random_integer,
smoothstep,
};
use image::RgbImage;
use std::{io::Error, path::Path, thread};
/// Target coverage ratio range for the Mandelbrot fractal viewport.
pub const TARGET_RANGE: [f64; 2] = [0.24, 0.26];
/// Implementation of the [`ImageEffect`] trait for rendering Mandelbrot Set fractals.
impl ImageEffect for MandelbrotGenerator {
/// Applies the Mandelbrot Set procedural overlay onto an in-memory image buffer.
fn apply(&self, rgb_img: &mut RgbImage) {
self.apply_effect_in_memory(rgb_img);
}
/// Returns formatting diagnostic information about the active generator.
fn info(&self) -> String {
format!(
"fractal [{}]\n\
f(z) = z² + c, where c = {:.5} {} {:.5}i (iter = {:3}, 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 Mandelbrot Set fractals onto desktop backgrounds.
///
/// Groups coordinate presets, escape iterations, colors, and camera viewpoints into
/// a structured pipeline to execute highly parallelized CPU rendering.
pub struct MandelbrotGenerator {
/// 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 MandelbrotGenerator {
/// Returns the default fallback instance of the Mandelbrot Set generator.
fn default() -> Self {
Self {
preset: FractalPreset {
center_re: -0.7436438,
center_im: 0.1318259,
fractal_name: "Deep double spirals in Seahorse Valley",
effect_name: ProceduralEffect::Mandelbrot,
},
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 MandelbrotGenerator {
/// Generates a randomized Mandelbrot Set configuration fitted to the target aspect ratio.
///
/// Pulls coordinates from 27 custom high-definition locations, sets neon colors,
/// applies random viewport rotations, and adjusts margins.
pub fn random(monitor: &crate::Monitor) -> Self {
let width = monitor.resolution.width as u32;
let height = monitor.resolution.height as u32;
let presets: [FractalPreset; 10] = [
FractalPreset {
center_re: -0.5623,
center_im: 0.6421,
fractal_name: "Filament branch patterns",
effect_name: ProceduralEffect::Mandelbrot,
},
FractalPreset {
center_re: -0.7756838,
center_im: 0.13646737,
fractal_name: "Seahorse tail section",
effect_name: ProceduralEffect::Mandelbrot,
},
FractalPreset {
center_re: -1.45,
center_im: 0.0,
fractal_name: "Needle Mini Mandelbrot",
effect_name: ProceduralEffect::Mandelbrot,
},
FractalPreset {
center_re: -1.75,
center_im: 0.0,
fractal_name: "Satellite Mini Mandelbrot",
effect_name: ProceduralEffect::Mandelbrot,
},
FractalPreset {
center_re: -0.1607,
center_im: 1.0376,
fractal_name: "Antenna Branching Plumes",
effect_name: ProceduralEffect::Mandelbrot,
},
FractalPreset {
center_re: -0.1011,
center_im: 0.9563,
fractal_name: "Tendril Valley Spirals",
effect_name: ProceduralEffect::Mandelbrot,
},
FractalPreset {
center_re: -0.8115,
center_im: 0.2014,
fractal_name: "Tenth-period Star Valley",
effect_name: ProceduralEffect::Mandelbrot,
},
FractalPreset {
center_re: -1.3996669964593604,
center_im: 0.0005429083913,
fractal_name: "Aokoroko V1",
effect_name: ProceduralEffect::Mandelbrot,
},
FractalPreset {
center_re: -0.6216751361351949,
center_im: -0.4629018082582385,
fractal_name: "Aokoroko V2",
effect_name: ProceduralEffect::Mandelbrot,
},
FractalPreset {
center_re: -0.6437677776968205,
center_im: -0.4541461552468023,
fractal_name: "Aokoroko V3",
effect_name: ProceduralEffect::Mandelbrot,
},
];
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: FractalPreset = presets[preset_idx];
let mut mandelbrot = 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(),
};
mandelbrot.optimize_fit(width, height);
mandelbrot
}
/// Calculates active coverage ratios to dynamically scale the viewport.
fn evaluate_ratio(&self, zoom: f64, width: u32, height: u32, min_escape_iter: u32) -> f64 {
self.evaluate_ratio_parametrized(zoom, width, height, min_escape_iter, 128, None)
}
/// Computes the ratio of active escape-time coordinates inside a grid, supporting optimization sweeps.
fn evaluate_ratio_parametrized(
&self,
zoom: f64,
width: u32,
height: u32,
min_escape_iter: u32,
grid_size: usize,
scan_iter_override: Option<u32>,
) -> f64 {
let w_f = width as f64;
let h_f = height as f64;
let specs = ViewportSpecs {
center_re: self.preset.center_re,
center_im: self.preset.center_im,
zoom,
cos_angle: self.cos_angle,
sin_angle: self.sin_angle,
is_julia: false,
};
let viewport = Viewport::new(w_f, h_f, &specs);
let mut active_count = 0;
let step_x = w_f / (grid_size as f64);
let step_y = h_f / (grid_size as f64);
let scan_iterations = scan_iter_override.unwrap_or(self.scan_iterations);
for gy in 0..grid_size {
let y_f = (gy as f64) * step_y;
for gx in 0..grid_size {
let x_f = (gx as f64) * step_x;
let (rx, ry) = viewport.map(x_f, y_f);
let (i, _, _, _, _) = compute_escape_iterations(
ProceduralEffect::Mandelbrot,
rx,
ry,
self.preset.center_re,
self.preset.center_im,
scan_iterations,
);
if i > min_escape_iter && i < scan_iterations {
active_count += 1;
}
}
}
(active_count as f64) / ((grid_size * grid_size) as f64)
}
/// Evaluates optimal viewport rotations by sweeping multiple angular increments.
pub fn evaluate_rotation(&mut self, width: u32, height: u32) -> f64 {
let original_cos = self.cos_angle;
let original_sin = self.sin_angle;
let mut working_zoom = 0.1;
let mut best_diff = f64::MAX;
for step in 0..8 {
let t = step as f64 / 7.0;
let log_z = 0.0001_f64.ln() + t * (3.0_f64.ln() - 0.0001_f64.ln());
let current_zoom = log_z.exp();
let ratio =
self.evaluate_ratio_parametrized(current_zoom, width, height, 16, 32, Some(100));
let diff = (ratio - 0.18).abs();
if diff < best_diff {
best_diff = diff;
working_zoom = current_zoom;
}
}
let mut best_angle_rad = 0.0;
let mut max_active_coverage = 0.0;
for (rad, cos_t, sin_t) in get_rotation_steps() {
self.cos_angle = cos_t;
self.sin_angle = sin_t;
let ratio = self.evaluate_ratio_parametrized(working_zoom, width, height, 24, 64, None);
if ratio > max_active_coverage && ratio <= 0.40 {
max_active_coverage = ratio;
best_angle_rad = rad;
}
}
self.cos_angle = original_cos;
self.sin_angle = original_sin;
best_angle_rad
}
/// Optimizes viewport parameters using progressive ratio sweeps.
pub fn optimize_fit(&mut self, width: u32, height: u32) {
let target_min = TARGET_RANGE[0];
let target_max = TARGET_RANGE[1];
let target_mid = (target_min + target_max) * 0.5;
let original_cos = self.cos_angle;
let original_sin = self.sin_angle;
let best_rad = self.evaluate_rotation(width, height);
if best_rad > 0.0 {
self.cos_angle = best_rad.cos();
self.sin_angle = best_rad.sin();
} else {
self.cos_angle = original_cos;
self.sin_angle = original_sin;
}
let mut log_min = 0.00001_f64.ln();
let mut log_max = 3.5_f64.ln();
let mut best_zoom = 0.02;
let mut best_difference = f64::MAX;
let max_iter = 32;
let min_escape_iter = 32;
for _ in 0..max_iter {
let current_log = (log_min + log_max) * 0.5;
let current_zoom = current_log.exp();
let ratio = self.evaluate_ratio(current_zoom, width, height, min_escape_iter);
let diff = if ratio >= target_min && ratio <= target_max {
0.0
} else if ratio < target_min {
target_min - ratio
} else {
ratio - target_max
};
if diff < best_difference {
best_difference = diff;
best_zoom = current_zoom;
}
if ratio > target_mid {
log_min = current_log;
} else {
log_max = current_log;
}
}
self.zoom = best_zoom;
}
/// Renders the Mandelbrot Set 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_re: self.preset.center_re,
center_im: self.preset.center_im,
zoom: self.zoom,
cos_angle: self.cos_angle,
sin_angle: self.sin_angle,
is_julia: false,
};
let viewport = Viewport::new(w_f, h_f, &specs);
let scan_iterations = self.scan_iterations;
let center_re = self.preset.center_re;
let center_im = self.preset.center_im;
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 inv_half_w = 2.0 / w_f;
let inv_half_h = 2.0 / h_f;
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.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;
let dy_vignette = (y_f * inv_half_h - 1.0) as f32;
let dy_vignette_sq = dy_vignette * dy_vignette;
for x in 0..width_usize {
let x_f = x as f64;
let (rx, ry) = viewport_ref.map(x_f, y_f);
let (i, z_re, z_im, dz_re, dz_im) = compute_escape_iterations(
ProceduralEffect::Mandelbrot,
rx,
ry,
center_re,
center_im,
scan_iterations,
);
let t = calculate_smooth_potential(i, scan_iterations, z_re, z_im);
let (fractal_rgb, alpha, s_alpha) = if t > 0.005 && i < scan_iterations
{
let dist_complex = calculate_distance_estimator(
i,
scan_iterations,
z_re,
z_im,
dz_re,
dz_im,
);
let dist_pixels = (dist_complex / scale) as f32;
// Base physical thickness (2.5px radius) for ultra-thin vector profiles
let thickness = 2.5_f32;
let max_radius = thickness * 2.0;
let shadow_radius = max_radius * 1.5;
if dist_pixels < shadow_radius {
let norm_dist = dist_pixels / max_radius;
// 1. Razor-sharp vector core line (1.2px width)
let core = if dist_pixels < 1.2 {
1.0 - (dist_pixels / 1.2)
} else {
0.0
};
// 2. Infinite nested structural ripples
let ripple_freq = 12.0_f32;
let ripple_wave =
(t * std::f32::consts::PI * ripple_freq).sin().abs();
let nested_detail = (1.0
- smoothstep(0.0, 0.4, 1.0 - ripple_wave))
* (1.0 - norm_dist);
// 3. Compact ambient outer glow (Sharp 6th-power attenuation curve)
let glow = if dist_pixels < max_radius {
(1.0 - norm_dist * norm_dist).powi(6) * 0.45
} else {
0.0
};
let profile = core * 0.65 + nested_detail * 0.20 + glow * 0.15;
// 4. Parallax drop shadow profile
let norm_shadow = dist_pixels / shadow_radius;
let shadow_profile =
(1.0 - norm_shadow * norm_shadow).powi(2) * 0.35;
// 3D Specular Light Approximation
let angle = z_im.atan2(z_re);
let light =
0.65_f32 + 0.35_f32 * (angle * 4.0).cos().abs() as f32;
// Multi-cycle recurring color gradient
let t_cycled = (t * 2.0) % 1.0;
let secondary_color =
[color_palette[1], color_palette[2], color_palette[0]];
let r_grad = if t_cycled < 0.5 {
let factor = t_cycled * 2.0;
color_palette[0] * (1.0 - factor)
+ secondary_color[0] * factor
} else {
let factor = (t_cycled - 0.5) * 2.0;
secondary_color[0] * (1.0 - factor)
+ color_palette[0] * factor
};
let g_grad = if t_cycled < 0.5 {
let factor = t_cycled * 2.0;
color_palette[1] * (1.0 - factor)
+ secondary_color[1] * factor
} else {
let factor = (t_cycled - 0.5) * 2.0;
secondary_color[1] * (1.0 - factor)
+ color_palette[1] * factor
};
let b_grad = if t_cycled < 0.5 {
let factor = t_cycled * 2.0;
color_palette[2] * (1.0 - factor)
+ secondary_color[2] * factor
} else {
let factor = (t_cycled - 0.5) * 2.0;
secondary_color[2] * (1.0 - factor)
+ color_palette[2] * factor
};
let core_color = [r_grad, g_grad, b_grad];
// High-saturation chromatic edge inversion
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 color_blend = norm_dist.powi(2);
let r_blended = core_color[0] * (1.0 - color_blend)
+ border_color[0] * color_blend;
let g_blended = core_color[1] * (1.0 - color_blend)
+ border_color[1] * color_blend;
let b_blended = core_color[2] * (1.0 - color_blend)
+ border_color[2] * color_blend;
// Emissive HDR brightness boost
let brightness_boost = 1.20_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 < 16 { (i as f32 - 3.0) / 13.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) // 100% transparent gap between branches
}
} else {
([0.0, 0.0, 0.0], 0.0, 0.0)
};
let idx = x * 3;
let dx_vignette = (x_f * inv_half_w - 1.0) as f32;
blend_and_vignette_pixel(
row_data,
idx,
fractal_rgb,
alpha,
s_alpha,
dx_vignette,
dy_vignette_sq,
);
}
}
});
}
});
}
/// 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(())
}
}