Skip to content

Instantly share code, notes, and snippets.

@joshsusser
Created March 20, 2018 05:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joshsusser/6e120319bdee9aa511d7a7964bf2dcb8 to your computer and use it in GitHub Desktop.
Save joshsusser/6e120319bdee9aa511d7a7964bf2dcb8 to your computer and use it in GitHub Desktop.
mandelbrot renderer - my first Rust program
extern crate image;
extern crate num_complex;
use std::fs::File;
use image::{ImageBuffer, Luma};
use num_complex::Complex;
fn main() {
// for a 3 x 2 image: (-2,-1) to (1,1)
const PPU: u32 = 500; // pixels per unit
const X_SIZE: u32 = 3 * PPU;
const Y_SIZE: u32 = 2 * PPU;
const X_ORIGIN: i32 = 2 * PPU as i32;
const Y_ORIGIN: i32 = PPU as i32;
let mut buffer = ImageBuffer::new(X_SIZE, Y_SIZE);
let bailout_norm_sqr = 2.0 * 2.0;
let bailout_cycles = 255;
for (x, y, pixel) in buffer.enumerate_pixels_mut() {
let x_re = (x as i32 - X_ORIGIN) as f64 / PPU as f64;
let y_im = (y as i32 - Y_ORIGIN) as f64 / PPU as f64;
let c = Complex::new(x_re, y_im);
let mut z = Complex::new(0.0, 0.0);
let mut escaped = 0;
for cycle in 0..bailout_cycles {
if z.norm_sqr() > bailout_norm_sqr { break }
z = z * z + c;
escaped = bailout_cycles - cycle;
}
*pixel = Luma([escaped as u8]);
}
let ref mut outfile = File::create("mandel.png").unwrap();
image::ImageLuma8(buffer).save(outfile, image::PNG).unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment