Skip to content

Instantly share code, notes, and snippets.

@SethDusek
Created July 29, 2017 05:32
Show Gist options
  • Save SethDusek/c67cff9ccd9f5e6e7e79d867cc3c636d to your computer and use it in GitHub Desktop.
Save SethDusek/c67cff9ccd9f5e6e7e79d867cc3c636d to your computer and use it in GitHub Desktop.
#![feature(iterator_step_by)]
extern crate sdl2;
use std::ops::Add;
use sdl2::pixels::Color;
use sdl2::render::Canvas;
use sdl2::event::Event;
const MAX_ITER: u64 = 12;
#[derive(Copy, Clone, Debug)]
pub struct Complex(f64, f64);
impl Add for Complex {
type Output = Self;
fn add(self, other: Complex) -> Self {
Complex(self.0+other.0, self.1+other.1)
}
}
impl Complex {
fn abs(self) -> Complex {
Complex(self.0.abs(), self.1.abs())
}
fn powi(self, val: i32) -> Complex {
Complex(self.0.powi(val), self.1.powi(val))
}
fn pow(self, val: Complex) -> Complex {
Complex(self.0.powf(val.0), self.1.powf(val.1))
}
}
pub fn mandelbrot<T: sdl2::render::RenderTarget>(size: u64, canvas: &mut Canvas<T>) {
let step: f64 = 4.0/size as f64; //-2i to 2i
let mut z = Complex(0.0, 0.0);
let mut x=-2.0;
let mut y=-2.0;
let mut x_surf = 0;
let mut y_surf = 0;
let mut c = Complex(x, y);
loop {
let mut iters = 0;
while (iters<MAX_ITER) && (z.abs().0 < 2.0 && z.abs().1 < 2.0) {
z = z.pow(z) + c;
iters+=1;
}
if iters == MAX_ITER {
canvas.set_draw_color(Color::RGB(0, 0, 0));
canvas.fill_rect(sdl2::rect::Rect::new(x_surf, y_surf, 1, 1)).unwrap();
}
else {
canvas.set_draw_color(Color::RGB(255, 255, 255));
canvas.fill_rect(sdl2::rect::Rect::new(x_surf, y_surf, 1, 1)).unwrap();
}
x+=step;
if x >= 2.0 {
y+=step;
x=0.0;
x_surf=0;
y_surf+=1;
}
if x >= 2.0 || y >= 2.0 { break }
}
canvas.present();
}
fn main() {
let sdl = sdl2::init().unwrap();
let video = sdl.video().unwrap();
let mut pump = sdl.event_pump().unwrap();
let mut window = video.window("Mandelbrot", 800, 800).build().unwrap().into_canvas().build().unwrap();
mandelbrot(800, &mut window);
loop {
match pump.poll_event() {
Some(Event::Quit{timestamp}) => break,
_ => continue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment