Skip to content

Instantly share code, notes, and snippets.

@j-walk
Created January 14, 2018 04:30
Show Gist options
  • Save j-walk/baae47ebb3f2dc1201ee9e5502a1bfe2 to your computer and use it in GitHub Desktop.
Save j-walk/baae47ebb3f2dc1201ee9e5502a1bfe2 to your computer and use it in GitHub Desktop.
[package]
name = "MandelbrotImage"
version = "0.1.0"
authors = ["Johnathan Walker <jhwalking0@gmail.com>"]
[dependencies]
image = "*"
num = "*"
extern crate image;
extern crate num;
use std::fs::File;
use std::path::Path;
use num::Complex;
// a function which takes a borrowed Complex<f32> and checks if its within
// the bounds of the mandelbrot set
fn in_mandel(p : &Complex<f32>) -> bool {
p.norm_sqr() < 4.0
}
// takes in an iteration limit and a borrowed Complex<f32>
// preforms z = z^2 + p until it reaches the iteration limit or
// it goes out of bounds
fn iter(limit : usize, p : &Complex<f32>) -> usize {
let mut i : usize = 0;
let mut z : Complex<f32> = Complex::new(0.0, 0.0);
while i < limit && in_mandel(&z) {
z = z.powf(2.0) + p;
i += 1;
};
i
}
// really shitty color pallet just uses the iteration count as a color
// looks awful
fn color(i : usize) -> [u8;1] {
[ i as u8 ]
}
// main function o boi
fn main() {
// some dumb x and y offsets with variables
let x : f32 = 1.0;
let y : f32 = 0.0;
let scale : f32 = 0.005;
// reserves the space for the image in ram of size 1000x1000
let mut image = image::ImageBuffer::new(1000u32, 1000u32);
// showing off the beautiful iterator trait
// enumerate_pixels_mut() returns an iterator of the x, y, and reference to
// the pixels
for (re, im, p) in image.enumerate_pixels_mut() {
// this is dumb shit don't do this in practice
// just shoving functions into one another
// you can use some libs like command to have pipelines but I cba
*p = image::Luma(color(iter(
255
, &Complex::new( (re as f32 - 500.0 - x) * scale
, (im as f32 - 500.0 - y) * scale
))));
};
// creating the file reference
let ref mut fout = File::create(&Path::new("test.png")).unwrap();
// writing the image to the file and throwing away the result
let _ = image::ImageLuma8(image).save(fout, image::PNG);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment