summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 06f041c90798fa31308b9ef15b0b52375a2aed37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use std::fs::File;
use std::io::Write;

const IMG_WIDTH: usize = 256;
const IMG_HEIGHT: usize = 256;

struct Pixel {
    r: u8,
    g: u8,
    b: u8,
}

fn main() {
    let mut txt_data = String::from("P3\n");
    txt_data.push_str(format!("{} {}\n255\n", IMG_WIDTH, IMG_HEIGHT).as_str());

    (0..IMG_HEIGHT).for_each(|j| {
        (0..IMG_WIDTH).for_each(|i| {
            let r = i as f32 / IMG_WIDTH as f32;
            let g = j as f32 / IMG_HEIGHT as f32;
            let b = 0.0f32;

            let ir = (255.999 * r) as u8;
            let ig = (255.999 * g) as u8;
            let ib = (255.999 * b) as u8;

            txt_data.push_str(&format!("{} {} {}\n", ir, ig, ib));
        })
    });

    match write_file("output.ppm", txt_data.as_str()) {
        Ok(_) => {println!("PPM file writen")},
        Err(e) => {println!("Error writing file {}", e)}
    }
}

fn write_file(file_path:  &str, txt_data:  &str) -> Result<(), std::io::Error> {
    let mut file = File::create(file_path)?;
    file.write_all(txt_data.as_bytes())
}