Skip to content

Commit 35bfe24

Browse files
committed
[add] mandlebrot set
1 parent 349a2a8 commit 35bfe24

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

src/56-mandlebrot-set.rs

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
extern crate sdl2;
2+
3+
use sdl2::pixels::PixelFormatEnum;
4+
use sdl2::pixels::Color;
5+
use sdl2::event::Event;
6+
use sdl2::keyboard::Keycode;
7+
use sdl2::render::{Renderer, Texture};
8+
use sdl2::rect::Rect;
9+
use std::f32;
10+
11+
const W_WIDTH: u32 = 640;
12+
const W_HEIGHT: u32 = 480;
13+
const X_MIN: f32 = -2.5;
14+
const X_MAX: f32 = 1.0;
15+
const Y_MIN: f32 = -1.0;
16+
const Y_MAX: f32 = 1.0;
17+
const MAX_ITERATION: u8 = 255;
18+
19+
fn delta(min: f32, max: f32, width: f32) -> f32 {
20+
(min.abs() + max.abs()) / width
21+
}
22+
23+
fn render<'a>(renderer: &'a mut Renderer, texture: &Texture) {
24+
renderer.set_draw_color(Color::RGB(0, 0, 0));
25+
renderer.clear();
26+
renderer.copy(texture, None, Some(Rect::new(0, 0, W_WIDTH, W_HEIGHT))).unwrap();
27+
renderer.present();
28+
}
29+
30+
fn main() {
31+
let sdl_contex = sdl2::init().unwrap();
32+
let video_subsystem = sdl_contex.video().unwrap();
33+
let window = video_subsystem.window("mandlebrot set", W_WIDTH, W_HEIGHT)
34+
.position_centered()
35+
.build()
36+
.unwrap();
37+
let mut renderer = window.renderer()
38+
.present_vsync()
39+
.build()
40+
.unwrap();
41+
let dx = delta(X_MIN, X_MAX, W_WIDTH as f32);
42+
let dy = delta(Y_MIN, Y_MAX, W_HEIGHT as f32);
43+
let mut texture = renderer.create_texture_streaming(PixelFormatEnum::RGB24, W_WIDTH, W_HEIGHT).unwrap();
44+
texture.with_lock(None, |buffer: &mut [u8], pitch: usize| {
45+
for px in 0..W_WIDTH {
46+
for py in 0..W_HEIGHT {
47+
let x0 = (px as f32) * dx + X_MIN;
48+
let y0 = (py as f32) * dy + Y_MIN;
49+
let mut x: f32 = 0.0;
50+
let mut y: f32 = 0.0;
51+
let mut iteration = 0;
52+
while x.powi(2) + y.powi(2) < 4.0 && iteration < MAX_ITERATION {
53+
let xtemp = x.powi(2) - y.powi(2) + x0;
54+
y = 2.0 * x * y + y0;
55+
x = xtemp;
56+
iteration += 1;
57+
}
58+
let offset = (py as usize) * pitch + (px as usize) * 3;
59+
buffer[offset + 0] = 0;
60+
buffer[offset + 1] = 0;
61+
buffer[offset + 2] = iteration;
62+
}
63+
}
64+
}).unwrap();
65+
let mut event_pump = sdl_contex.event_pump().unwrap();
66+
'running: loop {
67+
for event in event_pump.poll_iter() {
68+
match event {
69+
Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape), ..} => {
70+
break 'running;
71+
}
72+
_ => ()
73+
}
74+
}
75+
render(&mut renderer, &texture);
76+
}
77+
}

0 commit comments

Comments
 (0)