Skip to content

Instantly share code, notes, and snippets.

@deankarn
Created January 25, 2018 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deankarn/2434c797692ef7f722129db2b8ef0446 to your computer and use it in GitHub Desktop.
Save deankarn/2434c797692ef7f722129db2b8ef0446 to your computer and use it in GitHub Desktop.
extern crate image;
extern crate num_cpus;
use std::fs::File;
use std::thread;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::channel;
use std::cell::RefCell;
const WIDTH: u32 = 2048;
const HEIGHT: u32 = 2048;
fn main() {
let cpus = num_cpus::get();
let (tx, rx) = channel();
let rx = Arc::new(Mutex::new(rx));
let mut img: image::GrayImage = image::ImageBuffer::new(WIDTH, HEIGHT);
let threads = (0..cpus)
.map(|_| {
let rx = rx.clone();
thread::spawn(move || loop {
let val = rx.lock().unwrap().recv();
match val {
Err(_) => break,
Ok(x) => for y in 0..HEIGHT {
img.put_pixel(x, y, image::Luma([generate_pixel(x, y) as u8]));
},
};
})
})
.collect::<Vec<_>>();
for x in 0..WIDTH {
let _ = tx.send(x);
}
drop(tx);
for h in threads {
let _ = h.join();
}
// // Save the image as “fractal.png”
// let ref mut fout = File::create("out.png").unwrap();
// // We must indicate the image's color type and what format to save as
// image::ImageLuma8(img).save(fout, image::PNG).unwrap();
}
fn generate_pixel(i: u32, j: u32) -> u8 {
let xi = norm(i as f64, WIDTH as f64, -1.0, 2.0);
let yi = norm(j as f64, HEIGHT as f64, -1.0, 1.0);
const COMPLEXITY: f64 = 1024.0;
let (mut x, mut y) = (0., 0.);
let mut i = 0;
while (x * x + y * y < COMPLEXITY) && i < 1000 {
let (xm, ym) = (x * x - y * y + xi, 2.0 * x * y + yi);
x = xm;
y = ym;
i = i + 1;
}
x as u8
}
fn norm(x: f64, total: f64, min: f64, max: f64) -> f64 {
(max - min) * x / total - max
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment