Skip to content

Instantly share code, notes, and snippets.

@red75prime

red75prime/main.rs

Created Mar 9, 2017
Embed
What would you like to do?
extern crate image;
extern crate rayon;
use rayon::prelude::*;
use image::ColorType;
fn calculate_point(x : f64, y : f64, depth : usize) -> f32 {
let mut zx = 0.0;
let mut zy = 0.0;
let mut zx1;
let mut zy1;
for i in 0 .. depth {
zx1 = (zx * zx) - (zy * zy) + x;
zy1 = zx * zy * 2.0 + y;
if zx1 * zx1 + zy1 * zy1 > 4.0 {
return (i as f32) / (depth as f32);
}
else {
zx = zx1;
zy = zy1;
}
}
return 1.0;//depth as f32;
}
const CHANNELS: usize = 3;
fn get_color(colors : &[[f32;3]], buffer : &mut [[f32;3]], x : f32) -> [u8; CHANNELS] {
let mut len = colors.len() - 1;
for i in 0 .. len {
for j in 0 .. 3 {
buffer[i][j] = colors[i][j] + (colors[i+1][j] - colors[i][j]) * x
}
}
while len > 1 {
for i in 0 .. len - 1 {
for j in 0 .. 3 {
buffer[i][j] = buffer[i][j] + (buffer[i+1][j] - buffer[i][j]) * x
}
}
len -= 1;
}
return [buffer[0][0] as u8, buffer[0][1] as u8, buffer[0][2] as u8];
}
fn fill_chunk(buf: &mut [u8], idx0: usize, w: usize, h: usize, colors: &[[f32;3]], color_buf: &mut [[f32;3]]) {
let mut x = (idx0/CHANNELS) % w;
let mut y = (idx0/CHANNELS) / w;
let kx = 2.0 / (w as f64);
let ky = 2.0 / (h as f64);
for pv in buf.chunks_mut(CHANNELS) {
let v = calculate_point(kx*(x as f64) - 1.0, ky*(y as f64) - 1.0, 1000);
pv.clone_from_slice(&get_color(colors, color_buf, v));
x += 1;
if x == w { y += 1; x = 0 }
}
}
fn main() {
const W: usize = 1000;
const H: usize = 1000;
let mut buf = vec![0; W*H*CHANNELS];
let colors = vec![[0.0,0.0,0.0], [255.0,0.0,0.0], [255.0,255.0,0.0], [255.0,255.0,255.0]];
buf.par_chunks_mut(W*CHANNELS).enumerate().for_each(|(i, buf)|{
let colors = &colors;
let mut color_buf = colors.clone();
fill_chunk(buf, i*W*CHANNELS, W, H, colors, &mut color_buf);
});
image::save_buffer("out.png", &buf, W as u32, H as u32, ColorType::RGB(8)).unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.