Skip to content

Instantly share code, notes, and snippets.

@cfsamson
Created March 7, 2019 19:48
Show Gist options
  • Save cfsamson/ba97095540502c4b72d55a672d3da51f to your computer and use it in GitHub Desktop.
Save cfsamson/ba97095540502c4b72d55a672d3da51f to your computer and use it in GitHub Desktop.
optimizing_fixing_mem_increase
// For the sake of brevity I won't repeat the code we replace here instead point out
// that this replaces lines 307-328 in our original code example and of course the
// lass change we made when introducint Rayon the first time
fn main() {
// {...}
// first we create a range iterator ower
let bytes: Vec<u8> = (0..h as u32)
// turn it in to a parrallell iterator
.into_par_iter()
// reverse the order in which we iterate so our picture doesn't end upside down
.rev()
// mapping each y-coordinate to an iterator ower x-coordinates
// then we flatten the result so we don't end up with a Vec of y coordinates
// where each element is a Vec of x-coordinates.
.flat_map(|y| -> Vec<u8> {
// this is our sub-iterator that iterates ower x-coordinates
(0..w as u32)
// we parallellize this too
.into_par_iter()
// reverse the order so our picture doesn't end upside down
.rev()
// again we map this to a sub iterator so we don't end up with a
// Vec of y-coordinates, where each element if the Vec is a Vec of
// x-coordinates, that in turn is av Vec of three u8 color bytes.
// Instead we get a "flattened" result of only u8 color bytes.
.flat_map(|x| {
let mut color = Vec3::from(0.0);
for _ in (0..samples_count).rev() {
color = color
+ trace(
position,
!(goal
+ left * (x as f32 - w / 2.0 + random_val()).into()
+ up * (y as f32 - h / 2.0 + random_val()).into()),
);
}
color = color * (1.0 / samples_count as f32).into() + (14.0 / 241.0).into();
let o: Vec3 = color + Vec3::from(1.0);
color = Vec3::new_abc(color.x / o.x, color.y / o.y, color.z / o.z)
* Vec3::from(255.0);
vec![color.x as u8, color.y as u8, color.z as u8]
})
// we collect this to a Vec<u8> which is Iterable so our flat_map
// method can take care of flattening everything for us
.collect()
})
.collect();
file.write_all(&bytes).unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment