Skip to content

Commit 2c17ca5

Browse files
committed
lock stdout
1 parent 80df640 commit 2c17ca5

File tree

2 files changed

+23
-20
lines changed

2 files changed

+23
-20
lines changed

Diff for: src/camera.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::{f64::INFINITY, io::stdout};
1+
use std::{f64::INFINITY, io::{self, stdout, BufWriter}};
22

33
use rand::{random, thread_rng, Rng};
44

@@ -48,6 +48,7 @@ impl Camera {
4848
}
4949
pub fn render(&mut self, world: &dyn Hittable) {
5050
self.initialize();
51+
let mut writer = BufWriter::new(io::stdout());
5152

5253
println!("P3\n{} {}\n255", self.image_width, self.image_height);
5354
for j in 0..=self.image_height {
@@ -58,7 +59,7 @@ impl Camera {
5859
let r = self.get_ray(i, j);
5960
pixel_color += Self::ray_color(&r, self.max_depth, world);
6061
}
61-
write_color(&mut stdout(), self.pixel_samples_scale * pixel_color);
62+
write_color(&mut writer, self.pixel_samples_scale * pixel_color);
6263
}
6364
}
6465
eprintln!("\rDone. \n");

Diff for: src/color.rs

+20-18
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,29 @@
1-
use std::io::{Stdout, Write};
1+
use std::io::Write;
22

33
use crate::{interval::Interval, vec3::Vec3};
44

55
pub type Color = Vec3;
66

7-
pub fn write_color(out: &mut Stdout, pixel_color: Color) {
8-
let r = pixel_color.x();
9-
let g = pixel_color.y();
10-
let b = pixel_color.z();
7+
pub fn write_color<W: Write>(mut out: W, pixel_color: Color) {
8+
let r = pixel_color.x();
9+
let g = pixel_color.y();
10+
let b = pixel_color.z();
1111

12-
let r = linear_to_gamma(r);
13-
let g = linear_to_gamma(g);
14-
let b = linear_to_gamma(b);
12+
let r = linear_to_gamma(r);
13+
let g = linear_to_gamma(g);
14+
let b = linear_to_gamma(b);
1515

16-
let intensity = Interval::new(0.0, 0.999);
17-
let rbyte = (256.0 * intensity.clamp(r)) as i32;
18-
let gbyte = (256.0 * intensity.clamp(g)) as i32;
19-
let bbyte = (256.0 * intensity.clamp(b)) as i32;
20-
out.write_all(format!("{rbyte} {gbyte} {bbyte}\n").as_bytes()).unwrap();
16+
let intensity = Interval::new(0.0, 0.999);
17+
let rbyte = (256.0 * intensity.clamp(r)) as i32;
18+
let gbyte = (256.0 * intensity.clamp(g)) as i32;
19+
let bbyte = (256.0 * intensity.clamp(b)) as i32;
20+
out.write_all(format!("{rbyte} {gbyte} {bbyte}\n").as_bytes())
21+
.unwrap();
2122
}
2223
pub fn linear_to_gamma(linear_component: f64) -> f64 {
23-
if linear_component > 0.0 {
24-
return linear_component.sqrt()
25-
}
26-
0.0
27-
}
24+
if linear_component > 0.0 {
25+
return linear_component.sqrt();
26+
}
27+
0.0
28+
}
29+

0 commit comments

Comments
 (0)