From a1b9a274f757be54af3095a0c62f727cfd85b2ff Mon Sep 17 00:00:00 2001 From: Bradlee Speice Date: Fri, 3 Jul 2026 11:30:40 -0400 Subject: [PATCH 1/7] Implement transform colors --- enkou-shaders/examples/gasket.rs | 7 +- enkou-shaders/src/camera.rs | 7 +- enkou-shaders/src/chaos_game.rs | 38 +++++++---- enkou-shaders/src/rng.rs | 2 +- enkou-shaders/src/transform.rs | 112 ++++++++++++++++++++++++++++++- enkou-shaders/src/variation.rs | 6 ++ 6 files changed, 152 insertions(+), 20 deletions(-) diff --git a/enkou-shaders/examples/gasket.rs b/enkou-shaders/examples/gasket.rs index 55d0001..87991b4 100644 --- a/enkou-shaders/examples/gasket.rs +++ b/enkou-shaders/examples/gasket.rs @@ -5,7 +5,7 @@ use enkou_shaders::camera::entry::main_camera; use enkou_shaders::chaos_game::entry::main_chaos_game; use enkou_shaders::transform::Transform; use enkou_shaders::variation::Variation; -use glam::{Affine2, IVec2, UVec2, Vec2, uvec2}; +use glam::{Affine2, IVec2, UVec2, Vec2, Vec4, uvec2, vec2}; use image::{GrayImage, Luma}; use std::mem; use std::process::Command; @@ -21,16 +21,19 @@ pub fn main() -> Result<()> { Transform::new( Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.0), uvec2(0, 1), + vec2(0.0, 0.0), ), // F_1: ((x + 1) / 2, y / 2) Transform::new( Affine2::from_coefficients(0.5, 0.0, 0.5, 0.0, 0.5, 0.0), uvec2(0, 1), + vec2(0.0, 0.0), ), // F_2: (x / 2, (y + 1) / 2) Transform::new( Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.5), uvec2(0, 1), + vec2(0.0, 0.0), ), ]; @@ -39,7 +42,7 @@ pub fn main() -> Result<()> { let variations = [Variation::IDENTITY]; let mut output_points_ifs = Vec::new(); - output_points_ifs.resize(ITERATIONS as usize, Vec2::ZERO); + output_points_ifs.resize(ITERATIONS as usize, Vec4::ZERO); main_chaos_game( ITERATIONS_DISCARD, diff --git a/enkou-shaders/src/camera.rs b/enkou-shaders/src/camera.rs index 10c4d84..0cf6863 100644 --- a/enkou-shaders/src/camera.rs +++ b/enkou-shaders/src/camera.rs @@ -93,18 +93,19 @@ impl Camera { /// Shader entry point for running the camera transformation over a list of IFS coordinates pub mod entry { use crate::camera::Camera; - use spirv_std::glam::{IVec2, Vec2}; + use glam::{Vec4, Vec4Swizzles}; + use spirv_std::glam::IVec2; use spirv_std::spirv; /// Transform IFS coordinates to pixel coordinates #[spirv(compute(entry_point_name = "main_camera", threads(1)))] pub fn main_camera( #[spirv(storage_buffer, descriptor_set = 0, binding = 0)] camera: &Camera, - #[spirv(storage_buffer, descriptor_set = 0, binding = 1)] coordinates_ifs: &[Vec2], + #[spirv(storage_buffer, descriptor_set = 0, binding = 1)] coordinates_ifs: &[Vec4], #[spirv(storage_buffer, descriptor_set = 1, binding = 0)] coordinates_pixel: &mut [IVec2], ) { for i in 0..coordinates_ifs.len() { - coordinates_pixel[i] = camera.transform_point(coordinates_ifs[i]) + coordinates_pixel[i] = camera.transform_point(coordinates_ifs[i].xy()) } } } diff --git a/enkou-shaders/src/chaos_game.rs b/enkou-shaders/src/chaos_game.rs index 8ac3858..a403024 100644 --- a/enkou-shaders/src/chaos_game.rs +++ b/enkou-shaders/src/chaos_game.rs @@ -12,7 +12,6 @@ //! //! This algorithm is also known as the ["chaos game"](https://en.wikipedia.org/wiki/Chaos_game), //! and it forms the basic system for producing images. - use crate::transform::Transform; use crate::variation::Variation; use rand::distr::{Distribution, StandardUniform}; @@ -36,13 +35,14 @@ impl Distribution for BiUnit { /// * `weights` - Weights are assumed to be normalized; adding all elements together should return the value 1 pub fn step_chaos_game( point: Vec2, + color: f32, rng: &mut R, transforms: &[Transform], weights: &[f32], variations: &[Variation], -) -> (Vec2, u32) { +) -> (Vec2, f32, usize) { let mut choice_weight = rng.sample::(StandardUniform); - let mut transform_index: u32 = 0; + let mut transform_index: usize = 0; for i in 0..weights.len() { choice_weight -= weights[i]; @@ -53,8 +53,10 @@ pub fn step_chaos_game( transform_index += 1; } + let ref transform = transforms[transform_index]; ( - transforms[transform_index as usize].transform_point(rng, variations, point), + transform.transform_point(rng, variations, point), + transform.transform_color(color), transform_index, ) } @@ -65,6 +67,7 @@ pub fn step_chaos_game( /// New points in the chaos game are produced by iterating on the chaos game. pub struct ChaosGame<'a, R: Rng> { current_point: Vec2, + current_color: f32, rng: &'a mut R, transforms: &'a [Transform], weights: &'a [f32], @@ -79,9 +82,9 @@ impl<'a, R: Rng> ChaosGame<'a, R> { weights: &'a [f32], variations: &'a [Variation], ) -> Self { - let current_point = vec2(rng.sample(BiUnit), rng.sample(BiUnit)); ChaosGame { - current_point, + current_point: vec2(rng.sample(BiUnit), rng.sample(BiUnit)), + current_color: rng.sample(StandardUniform), rng, transforms, weights, @@ -91,19 +94,21 @@ impl<'a, R: Rng> ChaosGame<'a, R> { } impl<'a, R: Rng> Iterator for ChaosGame<'a, R> { - type Item = Vec2; + type Item = (Vec2, f32); fn next(&mut self) -> Option { - let (next_point, _) = step_chaos_game( + let (next_point, next_color, _) = step_chaos_game( self.current_point, + self.current_color, self.rng, self.transforms, self.weights, self.variations, ); self.current_point = next_point; + self.current_color = next_color; - Some(next_point) + Some((next_point, next_color)) } } @@ -113,11 +118,17 @@ pub mod entry { use crate::rng::xoshiro256starstar_from_seed; use crate::transform::Transform; use crate::variation::Variation; - use glam::Vec2; + use glam::Vec4; use spirv_std::spirv; /// Given a set of fractal flame parameters, generate new IFS coordinates /// and store them in the output array. + /// + /// Arguments: + /// * `iteration_discard` - Choas game steps to discard prior to recording into the output buffer + /// * `output` - Output buffer to record chaos game steps into. Because of alignment issues, + /// the output is recorded as a [`Vec4`]; the IFS (x, y) coordinate is in `x` and `y`, + /// and color is in `w` #[spirv(compute(entry_point_name = "main_chaos_game", threads(1)))] pub fn main_chaos_game( #[spirv(spec_constant(id = 1, default = 20))] iteration_discard: u32, @@ -125,7 +136,7 @@ pub mod entry { #[spirv(storage_buffer, descriptor_set = 0, binding = 1)] transforms: &[Transform], #[spirv(storage_buffer, descriptor_set = 0, binding = 2)] weights: &[f32], #[spirv(storage_buffer, descriptor_set = 0, binding = 3)] variations: &[Variation], - #[spirv(storage_buffer, descriptor_set = 1, binding = 0)] output: &mut [Vec2], + #[spirv(storage_buffer, descriptor_set = 1, binding = 0)] output: &mut [Vec4], ) { let mut rng_seed_actual = [0u8; 32]; (0..32).for_each(|i| rng_seed_actual[i] = rng_seed[i]); @@ -138,7 +149,10 @@ pub mod entry { } for i in 0..output.len() { - output[i] = chaos_game.next().unwrap(); + output[i] = chaos_game + .next() + .map(|output| (output.0, 0.0, output.1).into()) + .unwrap(); } } } diff --git a/enkou-shaders/src/rng.rs b/enkou-shaders/src/rng.rs index 7dbeae8..0c7cb2e 100644 --- a/enkou-shaders/src/rng.rs +++ b/enkou-shaders/src/rng.rs @@ -19,7 +19,7 @@ pub(crate) fn xoshiro256starstar_from_seed( ) -> Xoshiro256StarStar { let mut rng_state_actual = [0u64; 4]; - // NOTE: Bit shifting is bad, but we don't have great alternatives: + // NOTE: Bit shifting is tedious, but we don't have great alternatives: // - `chunks_exact` has issues with pointer casting // - `u64::from_le_bytes` has issues with `OpBitcast` in SPIR-V validation for i in 0..rng_state_actual.len() { diff --git a/enkou-shaders/src/transform.rs b/enkou-shaders/src/transform.rs index 3b8badc..1dc9965 100644 --- a/enkou-shaders/src/transform.rs +++ b/enkou-shaders/src/transform.rs @@ -5,7 +5,7 @@ //! but produce more interesting images once we add variations. use crate::variation::Variation; use bytemuck::{Pod, Zeroable}; -use glam::{Affine2, UVec2, Vec2}; +use glam::{Affine2, FloatExt, UVec2, Vec2}; use rand::Rng; /// Affine transform for use in the [`chaos_game`](crate::chaos_game). @@ -14,14 +14,21 @@ use rand::Rng; pub struct Transform { coefficients: Affine2, variation_range: UVec2, + color: Vec2, } impl Transform { /// Create a new transform from an affine transformation matrix - pub fn new(coefficients: Affine2, variation_range: UVec2) -> Self { + /// + /// Arguments: + /// * `coefficients` - Affine transform coefficients for this transformation. Applied prior to variations + /// * `variation_range` - (half-open) range of variations to apply during [`Self::transform_point`] + /// * `color` - Color value and speed to apply during [`Self::transform_color`] + pub fn new(coefficients: Affine2, variation_range: UVec2, color: Vec2) -> Self { Transform { coefficients, variation_range, + color, } } @@ -45,4 +52,105 @@ impl Transform { point_output } + + /// Mix an existing color with this transform's color + pub fn transform_color(&self, color: f32) -> f32 { + color.lerp(self.color.x, self.color.y) + } +} + +#[cfg(test)] +mod test { + use crate::Coefficients2; + use crate::transform::Transform; + use crate::variation::{Variation, VariationKind}; + use core::convert::Infallible; + use glam::{Affine2, Vec2, uvec2, vec2}; + use rand::TryRng; + + struct NullRng; + + impl NullRng { + pub fn new() -> Self { + NullRng + } + } + + impl TryRng for NullRng { + type Error = Infallible; + + fn try_next_u32(&mut self) -> Result { + Ok(0) + } + + fn try_next_u64(&mut self) -> Result { + Ok(0) + } + + fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> { + dst.iter_mut().for_each(|b| *b = 0); + Ok(()) + } + } + + #[test] + fn test_transform_point_identity() { + let transform = Transform::new(Affine2::IDENTITY, uvec2(0, 1), vec2(0.0, 0.0)); + let variations = [Variation::IDENTITY]; + + let transform_point = + |point: Vec2| transform.transform_point(&mut NullRng::new(), &variations, point); + for (input, expected) in [ + (vec2(0.0, 1.0), vec2(0.0, 1.0)), + (vec2(1.0, 0.0), vec2(1.0, 0.0)), + (vec2(1.0, 1.0), vec2(1.0, 1.0)), + ] { + assert_eq!(transform_point(input), expected); + } + } + + #[test] + fn test_transform_point_scaling() { + let transform = Transform::new( + Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.0), + uvec2(0, 1), + vec2(0.0, 0.0), + ); + let variations = [Variation::IDENTITY]; + + let transform_point = + |point: Vec2| transform.transform_point(&mut NullRng::new(), &variations, point); + for (input, expected) in [ + (vec2(0.0, 1.0), vec2(0.0, 0.5)), + (vec2(1.0, 0.0), vec2(0.5, 0.0)), + (vec2(1.0, 1.0), vec2(0.5, 0.5)), + ] { + assert_eq!(transform_point(input), expected); + } + } + + #[test] + fn test_transform_point_scaling_variation() { + let transform = Transform::new(Affine2::IDENTITY, uvec2(0, 1), vec2(0.0, 0.0)); + let variations = [Variation::new(VariationKind::Linear, 2.0, [0.0; 4].into())]; + + let transform_point = + |point: Vec2| transform.transform_point(&mut NullRng::new(), &variations, point); + for (input, expected) in [ + (vec2(0.0, 1.0), vec2(0.0, 2.0)), + (vec2(1.0, 0.0), vec2(2.0, 0.0)), + (vec2(1.0, 1.0), vec2(2.0, 2.0)), + ] { + assert_eq!(transform_point(input), expected); + } + } + + #[test] + fn test_color_mixing() { + let transform = Transform::new(Affine2::IDENTITY, uvec2(0, 1), vec2(0.0, 0.5)); + + assert_eq!(transform.transform_color(0.0), 0.0); + assert_eq!(transform.transform_color(1.0), 0.5); + assert_eq!(transform.transform_color(0.5), 0.25); + } } diff --git a/enkou-shaders/src/variation.rs b/enkou-shaders/src/variation.rs index 06a0df0..381b9be 100644 --- a/enkou-shaders/src/variation.rs +++ b/enkou-shaders/src/variation.rs @@ -20,6 +20,12 @@ use rand::{Rng, RngExt}; #[repr(C)] pub struct VariationParams([f32; 4]); +impl From<[f32; 4]> for VariationParams { + fn from(value: [f32; 4]) -> Self { + VariationParams(value) + } +} + /// Enum for all supported variation types /// /// ID numbers are chosen to match the variation identifier also used by `flam3` -- 2.52.0 From 54ba76b380f3d86e91322ab33579bc31b0ac12a4 Mon Sep 17 00:00:00 2001 From: Bradlee Speice Date: Fri, 3 Jul 2026 14:07:45 -0400 Subject: [PATCH 2/7] Implement camera colors Still needs some unit tests, and to fix the gasket example --- enkou-shaders-tests/build.rs | 7 +- enkou-shaders-tests/src/lib.rs | 7 +- enkou-shaders/examples/gasket.rs | 34 ++++---- enkou-shaders/src/camera.rs | 129 +++++++++++++++++++++---------- 4 files changed, 120 insertions(+), 57 deletions(-) diff --git a/enkou-shaders-tests/build.rs b/enkou-shaders-tests/build.rs index 117b150..78f08d6 100644 --- a/enkou-shaders-tests/build.rs +++ b/enkou-shaders-tests/build.rs @@ -16,7 +16,12 @@ pub fn main() -> anyhow::Result<()> { builder.build_script.defaults = true; builder.shader_panic_strategy = ShaderPanicStrategy::SilentExit; builder.spirv_metadata = SpirvMetadata::Full; - builder.capabilities = vec![Capability::Int8, Capability::Int16, Capability::Int64]; + builder.capabilities = vec![ + Capability::Int8, + Capability::Int16, + Capability::Int64, + Capability::Float64, + ]; let compile_result = builder.build()?; let spv_path = compile_result.module.unwrap_single(); diff --git a/enkou-shaders-tests/src/lib.rs b/enkou-shaders-tests/src/lib.rs index 5827196..dd97640 100644 --- a/enkou-shaders-tests/src/lib.rs +++ b/enkou-shaders-tests/src/lib.rs @@ -64,7 +64,10 @@ mod test { } #[test] - pub fn has_entry_main_camera() { - assert!(has_entry_point(ExecutionModel::GLCompute, "main_camera")) + pub fn has_entry_main_image_render() { + assert!(has_entry_point( + ExecutionModel::GLCompute, + "main_image_render" + )) } } diff --git a/enkou-shaders/examples/gasket.rs b/enkou-shaders/examples/gasket.rs index 87991b4..21b2af9 100644 --- a/enkou-shaders/examples/gasket.rs +++ b/enkou-shaders/examples/gasket.rs @@ -1,12 +1,12 @@ use anyhow::{Context, Result}; use enkou_shaders::Coefficients2; use enkou_shaders::camera::Camera; -use enkou_shaders::camera::entry::main_camera; +use enkou_shaders::camera::entry::main_image_render; use enkou_shaders::chaos_game::entry::main_chaos_game; use enkou_shaders::transform::Transform; use enkou_shaders::variation::Variation; -use glam::{Affine2, IVec2, UVec2, Vec2, Vec4, uvec2, vec2}; -use image::{GrayImage, Luma}; +use glam::{Affine2, UVec2, Vec2, Vec4, uvec2, vec2}; +use image::{Rgba, Rgba32FImage}; use std::mem; use std::process::Command; use tempfile::NamedTempFile; @@ -62,20 +62,26 @@ pub fn main() -> Result<()> { IMAGE_DIMENSION.as_vec2(), ); + let palette = &[Vec4::ONE; 2]; + let mut output_points_pixel = Vec::new(); - output_points_pixel.resize(ITERATIONS as usize, IVec2::ZERO); + output_points_pixel.resize(ITERATIONS as usize, Vec4::ZERO); - main_camera(&camera, &output_points_ifs, &mut output_points_pixel); + main_image_render( + &camera, + palette, + &output_points_ifs, + &mut output_points_pixel, + ); - let mut image = GrayImage::new(IMAGE_DIMENSION.x, IMAGE_DIMENSION.y); - let dimensions = image.dimensions(); - output_points_pixel - .iter() - .skip_while(|p| { - p.x < 0 || (p.x as u32) > dimensions.0 || p.y < 0 || (p.y as u32) > dimensions.1 - }) - .map(|p| (p.x as u32, p.y as u32)) - .for_each(|(x, y)| image.put_pixel(x, y, Luma([255u8]))); + let mut image = Rgba32FImage::new(IMAGE_DIMENSION.x, IMAGE_DIMENSION.y); + for x in 0..image.dimensions().0 { + for y in 0..image.dimensions().1 { + let pixel_index = y * IMAGE_DIMENSION.x + x; + let pixel = output_points_pixel[pixel_index as usize]; + image.put_pixel(x, y, Rgba(pixel.into())); + } + } let temp = NamedTempFile::with_suffix(".png").context("Unable to create file for image")?; image.save(temp.path()).context("Unable to save image")?; diff --git a/enkou-shaders/src/camera.rs b/enkou-shaders/src/camera.rs index 0cf6863..82a752f 100644 --- a/enkou-shaders/src/camera.rs +++ b/enkou-shaders/src/camera.rs @@ -2,8 +2,47 @@ //! //! Map points from the IFS coordinate system to pixel coordinates. This is a lossy transformation. use bytemuck::{Pod, Zeroable}; -use glam::{Affine2, IVec2, UVec2, Vec2, vec2}; -use libm::powf; +use glam::{Affine2, IVec2, UVec2, Vec2, Vec4, Vec4Swizzles, vec2}; +use libm::{ceilf, floorf, powf}; + +/// Blending modes for mapping IFS color values (which are on a scale `[0, 1]`) +/// to RGBA colors. +#[derive(Copy, Clone)] +#[repr(u32)] +pub enum BlendMode { + /// Map IFS color values to a linear blend of the nearest two palette colors + Linear = 0, + + /// Map IFS color values to the nearest single palette color + Step = 1, +} + +impl Default for BlendMode { + fn default() -> Self { + BlendMode::Linear + } +} + +impl BlendMode { + /// Map an IFS color value to RGBA color from the provided palette. + pub fn ifs_to_rgb(&self, color: f32, palette: &[Vec4]) -> Vec4 { + let palette_index = color * palette.len() as f32; + let palette_index_lower = floorf(palette_index) as usize; + let palette_index_upper = ceilf(palette_index) as usize; + + match self { + BlendMode::Linear => { + (palette[palette_index_lower] + palette[palette_index_upper]) / 2.0 + } + BlendMode::Step => palette[palette_index_lower], + } + } +} + +// UNSAFE: Sound because enum has guaranteed layout (u32) and defined zero-value +unsafe impl bytemuck::Zeroable for BlendMode {} +// UNSAFE: Sound because enum has guaranteed layout (u32) and defined zero-value +unsafe impl bytemuck::Pod for BlendMode {} /// Settings used to map IFS coordinates to pixel coordinates. /// @@ -14,6 +53,8 @@ use libm::powf; pub struct Camera { dimensions: UVec2, transform: Affine2, + blend_mode: BlendMode, + image_gamma: f32, } impl Camera { @@ -50,62 +91,70 @@ impl Camera { Camera { dimensions, transform, + blend_mode: BlendMode::Linear, + image_gamma: 1.5, } } - /// Map a point from IFS coordinates to pixel coordinates. - /// - /// ``` - /// # use glam::{vec2, ivec2, uvec2, Vec2}; - /// # use crate::enkou_shaders::camera::Camera; - /// // Output image is 600x600 pixels, centered at the origin, no rotation, no zoom, - /// // and scaled such that it covers the range [-2, 2]. - /// // Use the origin as the IFS coordinate, so the pixel coordinate is the center of the image - /// let camera = Camera::new( - /// uvec2(600, 600), - /// Vec2::ZERO, - /// 0.0, - /// Vec2::ZERO, - /// vec2(150.0, 150.0) - /// ); - /// assert_eq!(camera.transform_point(vec2(0.0, 0.0)), ivec2(300, 300)); - /// ``` - pub fn transform_point(&self, point: Vec2) -> IVec2 { + fn transform_point(&self, point: Vec2) -> IVec2 { self.transform.transform_point2(point).as_ivec2() } - /// Map a point from IFS coordinates to pixel coordinates (like [`transform_point`](Camera::transform_point)), - /// and check that the result is within the provided image dimensions. - pub fn transform_point_to_image(&self, point: Vec2) -> Option { - let pixel_coordinates = self.transform_point(point); + /// Map a point from IFS coordinates to a pixel index and RGBA value; if the IFS coordinate + /// is outside the viewable range, return [`None`]. + pub fn transform_point_to_image(&self, point: Vec4, palette: &[Vec4]) -> Option<(usize, Vec4)> { + let pixel_coordinates = self.transform_point(point.xy()); if pixel_coordinates.x < 0 || pixel_coordinates.y < 0 || (pixel_coordinates.x as u32) >= self.dimensions.x || (pixel_coordinates.y as u32) >= self.dimensions.y { - None - } else { - Some(pixel_coordinates.as_uvec2()) + return None; } + + let to_pixel_index = self.dimensions.with_y(0); + let pixel_index = pixel_coordinates.as_uvec2().dot(to_pixel_index) as usize; + + let rgba = self.blend_mode.ifs_to_rgb(point.w, palette); + + Some((pixel_index, rgba)) } } -/// Shader entry point for running the camera transformation over a list of IFS coordinates +#[allow(missing_docs)] pub mod entry { use crate::camera::Camera; - use glam::{Vec4, Vec4Swizzles}; - use spirv_std::glam::IVec2; + use glam::Vec4; + use libm::log10f; use spirv_std::spirv; - /// Transform IFS coordinates to pixel coordinates - #[spirv(compute(entry_point_name = "main_camera", threads(1)))] - pub fn main_camera( + /// Render an output image from a list of IFS coordinates. + /// + /// Arguments: + /// * `camera` - Camera settings for mapping IFS coordinates to pixel coordinates + /// * `palette` - Color palette to use when mapping IFS color to RGB colors. Individual elements + /// are assumed to be RGBA values on the scale of `[0, 1]` + /// * `coordinates_ifs` - IFS coordinates to use for the output image + /// * `image` - Buffer for the output image + #[spirv(compute(entry_point_name = "main_image_render", threads(1)))] + pub fn main_image_render( #[spirv(storage_buffer, descriptor_set = 0, binding = 0)] camera: &Camera, + #[spirv(storage_buffer, descriptor_set = 0, binding = 1)] palette: &[Vec4], #[spirv(storage_buffer, descriptor_set = 0, binding = 1)] coordinates_ifs: &[Vec4], - #[spirv(storage_buffer, descriptor_set = 1, binding = 0)] coordinates_pixel: &mut [IVec2], + #[spirv(storage_buffer, descriptor_set = 1, binding = 0)] image: &mut [Vec4], ) { - for i in 0..coordinates_ifs.len() { - coordinates_pixel[i] = camera.transform_point(coordinates_ifs[i].xy()) + for coordinate_index in 0..coordinates_ifs.len() { + camera + .transform_point_to_image(coordinates_ifs[coordinate_index], palette) + .map(|(pixel_index, rgba)| image[pixel_index] += rgba); + } + + for pixel_index in 0..image.len() { + // TODO: Fix the bootleg gamma adjustment + let pixel_unscaled = image[pixel_index]; + let pixel = + pixel_unscaled * log10f(pixel_unscaled.w) / (pixel_unscaled.w * camera.image_gamma); + image[pixel_index] = pixel; } } } @@ -117,7 +166,7 @@ mod test { use libm::powf; #[test] - pub fn manual_camera() { + fn manual_camera() { let starting_point = vec2(1.0, 1.0); // Move the origin; points move right and up by one unit, giving us (2.0, 2.0) @@ -155,7 +204,7 @@ mod test { } #[test] - pub fn point_outside_camera() { + fn point_outside_camera() { // Scale 250 for an image 1000 x 1000 gives an effective range of [-2, 2] let camera = Camera::new( uvec2(1000, 1000), @@ -170,7 +219,7 @@ mod test { } #[test] - pub fn point_outside_camera_negative() { + fn point_outside_camera_negative() { // Scale 250 for an image 1000 x 1000 gives an effective range of [-2, 2] let camera = Camera::new( uvec2(1000, 1000), @@ -185,7 +234,7 @@ mod test { } #[test] - pub fn aspect_ratio() { + fn aspect_ratio() { // Scale 100 for an image 1600 x 900 gives an effective X range of [-8, 8], // and effective Y range of [-4.5, 4.5] let camera = Camera::new( -- 2.52.0 From dfc9cf821c395f27d40a7edb4794093e288061ff Mon Sep 17 00:00:00 2001 From: Bradlee Speice Date: Fri, 3 Jul 2026 16:18:01 -0400 Subject: [PATCH 3/7] Fix palette blend modes, add unit tests --- enkou-shaders/src/camera.rs | 68 +++++++++++++++++++++++++++++-------- 1 file changed, 54 insertions(+), 14 deletions(-) diff --git a/enkou-shaders/src/camera.rs b/enkou-shaders/src/camera.rs index 82a752f..93adbee 100644 --- a/enkou-shaders/src/camera.rs +++ b/enkou-shaders/src/camera.rs @@ -3,7 +3,7 @@ //! Map points from the IFS coordinate system to pixel coordinates. This is a lossy transformation. use bytemuck::{Pod, Zeroable}; use glam::{Affine2, IVec2, UVec2, Vec2, Vec4, Vec4Swizzles, vec2}; -use libm::{ceilf, floorf, powf}; +use libm::{floorf, powf}; /// Blending modes for mapping IFS color values (which are on a scale `[0, 1]`) /// to RGBA colors. @@ -26,15 +26,15 @@ impl Default for BlendMode { impl BlendMode { /// Map an IFS color value to RGBA color from the provided palette. pub fn ifs_to_rgb(&self, color: f32, palette: &[Vec4]) -> Vec4 { - let palette_index = color * palette.len() as f32; - let palette_index_lower = floorf(palette_index) as usize; - let palette_index_upper = ceilf(palette_index) as usize; + let colors_m_one = palette.len() - 1; + let period = 1.0 / colors_m_one as f32; + let index_lower = floorf(color / period) as usize; + let index_upper = (index_lower + 1).clamp(0, colors_m_one); + let rem = color % period / period; match self { - BlendMode::Linear => { - (palette[palette_index_lower] + palette[palette_index_upper]) / 2.0 - } - BlendMode::Step => palette[palette_index_lower], + BlendMode::Linear => palette[index_lower].lerp(palette[index_upper], rem), + BlendMode::Step => palette[index_lower], } } } @@ -161,12 +161,52 @@ pub mod entry { #[cfg(test)] mod test { - use crate::camera::Camera; - use glam::{Affine2, Vec2, ivec2, uvec2, vec2}; + use crate::camera::{BlendMode, Camera}; + use glam::{Affine2, Vec2, Vec4, ivec2, uvec2, vec2}; use libm::powf; + fn vec4s(value: f32) -> Vec4 { + Vec4::splat(value) + } + #[test] - fn manual_camera() { + fn blend_linear() { + let ifs_to_rgb = |color, palette| BlendMode::Linear.ifs_to_rgb(color, palette); + + let palette = &[vec4s(0.0), vec4s(1.0)]; + assert_eq!(ifs_to_rgb(0.0, palette), vec4s(0.0)); + assert_eq!(ifs_to_rgb(0.5, palette), vec4s(0.5)); + assert_eq!(ifs_to_rgb(1.0, palette), vec4s(1.0)); + + let palette = &[vec4s(1.0), vec4s(2.0), vec4s(3.0)]; + assert_eq!(ifs_to_rgb(0.0, palette), vec4s(1.0)); + assert_eq!(ifs_to_rgb(0.5, palette), vec4s(2.0)); + assert_eq!(ifs_to_rgb(1.0, palette), vec4s(3.0)); + + let palette = &[vec4s(1.0), vec4s(2.0), vec4s(3.0), vec4s(4.0)]; + assert_eq!(ifs_to_rgb(0.0, palette), vec4s(1.0)); + assert_eq!(ifs_to_rgb(0.5, palette), vec4s(2.5)); + assert_eq!(ifs_to_rgb(1.0, palette), vec4s(4.0)); + } + + #[test] + fn blend_step() { + let ifs_to_rgb = |color, palette| BlendMode::Step.ifs_to_rgb(color, palette); + + let palette = &[vec4s(0.0), vec4s(1.0)]; + assert_eq!(ifs_to_rgb(0.5, palette), vec4s(0.0)); + + let palette = &[vec4s(1.0), vec4s(2.0), vec4s(3.0)]; + assert_eq!(ifs_to_rgb(0.0, palette), palette[0]); + assert_eq!(ifs_to_rgb(0.25, palette), palette[0]); + assert_eq!(ifs_to_rgb(0.4, palette), palette[0]); + assert_eq!(ifs_to_rgb(0.5, palette), palette[1]); + assert_eq!(ifs_to_rgb(0.7, palette), palette[1]); + assert_eq!(ifs_to_rgb(1.0, palette), palette[2]); + } + + #[test] + fn camera_manual() { let starting_point = vec2(1.0, 1.0); // Move the origin; points move right and up by one unit, giving us (2.0, 2.0) @@ -204,7 +244,7 @@ mod test { } #[test] - fn point_outside_camera() { + fn camera_point_outside_image() { // Scale 250 for an image 1000 x 1000 gives an effective range of [-2, 2] let camera = Camera::new( uvec2(1000, 1000), @@ -219,7 +259,7 @@ mod test { } #[test] - fn point_outside_camera_negative() { + fn camera_point_outside_image_negative() { // Scale 250 for an image 1000 x 1000 gives an effective range of [-2, 2] let camera = Camera::new( uvec2(1000, 1000), @@ -234,7 +274,7 @@ mod test { } #[test] - fn aspect_ratio() { + fn camera_aspect_ratio() { // Scale 100 for an image 1600 x 900 gives an effective X range of [-8, 8], // and effective Y range of [-4.5, 4.5] let camera = Camera::new( -- 2.52.0 From 4e508884ae057ce1b044c08544c5da386924e97d Mon Sep 17 00:00:00 2001 From: Bradlee Speice Date: Fri, 3 Jul 2026 11:30:40 -0400 Subject: [PATCH 4/7] Implement transform colors --- enkou-shaders/examples/gasket.rs | 7 +- enkou-shaders/src/camera.rs | 7 +- enkou-shaders/src/chaos_game.rs | 38 +++++++---- enkou-shaders/src/rng.rs | 2 +- enkou-shaders/src/transform.rs | 112 ++++++++++++++++++++++++++++++- enkou-shaders/src/variation.rs | 6 ++ 6 files changed, 152 insertions(+), 20 deletions(-) diff --git a/enkou-shaders/examples/gasket.rs b/enkou-shaders/examples/gasket.rs index 55d0001..87991b4 100644 --- a/enkou-shaders/examples/gasket.rs +++ b/enkou-shaders/examples/gasket.rs @@ -5,7 +5,7 @@ use enkou_shaders::camera::entry::main_camera; use enkou_shaders::chaos_game::entry::main_chaos_game; use enkou_shaders::transform::Transform; use enkou_shaders::variation::Variation; -use glam::{Affine2, IVec2, UVec2, Vec2, uvec2}; +use glam::{Affine2, IVec2, UVec2, Vec2, Vec4, uvec2, vec2}; use image::{GrayImage, Luma}; use std::mem; use std::process::Command; @@ -21,16 +21,19 @@ pub fn main() -> Result<()> { Transform::new( Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.0), uvec2(0, 1), + vec2(0.0, 0.0), ), // F_1: ((x + 1) / 2, y / 2) Transform::new( Affine2::from_coefficients(0.5, 0.0, 0.5, 0.0, 0.5, 0.0), uvec2(0, 1), + vec2(0.0, 0.0), ), // F_2: (x / 2, (y + 1) / 2) Transform::new( Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.5), uvec2(0, 1), + vec2(0.0, 0.0), ), ]; @@ -39,7 +42,7 @@ pub fn main() -> Result<()> { let variations = [Variation::IDENTITY]; let mut output_points_ifs = Vec::new(); - output_points_ifs.resize(ITERATIONS as usize, Vec2::ZERO); + output_points_ifs.resize(ITERATIONS as usize, Vec4::ZERO); main_chaos_game( ITERATIONS_DISCARD, diff --git a/enkou-shaders/src/camera.rs b/enkou-shaders/src/camera.rs index 10c4d84..0cf6863 100644 --- a/enkou-shaders/src/camera.rs +++ b/enkou-shaders/src/camera.rs @@ -93,18 +93,19 @@ impl Camera { /// Shader entry point for running the camera transformation over a list of IFS coordinates pub mod entry { use crate::camera::Camera; - use spirv_std::glam::{IVec2, Vec2}; + use glam::{Vec4, Vec4Swizzles}; + use spirv_std::glam::IVec2; use spirv_std::spirv; /// Transform IFS coordinates to pixel coordinates #[spirv(compute(entry_point_name = "main_camera", threads(1)))] pub fn main_camera( #[spirv(storage_buffer, descriptor_set = 0, binding = 0)] camera: &Camera, - #[spirv(storage_buffer, descriptor_set = 0, binding = 1)] coordinates_ifs: &[Vec2], + #[spirv(storage_buffer, descriptor_set = 0, binding = 1)] coordinates_ifs: &[Vec4], #[spirv(storage_buffer, descriptor_set = 1, binding = 0)] coordinates_pixel: &mut [IVec2], ) { for i in 0..coordinates_ifs.len() { - coordinates_pixel[i] = camera.transform_point(coordinates_ifs[i]) + coordinates_pixel[i] = camera.transform_point(coordinates_ifs[i].xy()) } } } diff --git a/enkou-shaders/src/chaos_game.rs b/enkou-shaders/src/chaos_game.rs index 8ac3858..a403024 100644 --- a/enkou-shaders/src/chaos_game.rs +++ b/enkou-shaders/src/chaos_game.rs @@ -12,7 +12,6 @@ //! //! This algorithm is also known as the ["chaos game"](https://en.wikipedia.org/wiki/Chaos_game), //! and it forms the basic system for producing images. - use crate::transform::Transform; use crate::variation::Variation; use rand::distr::{Distribution, StandardUniform}; @@ -36,13 +35,14 @@ impl Distribution for BiUnit { /// * `weights` - Weights are assumed to be normalized; adding all elements together should return the value 1 pub fn step_chaos_game( point: Vec2, + color: f32, rng: &mut R, transforms: &[Transform], weights: &[f32], variations: &[Variation], -) -> (Vec2, u32) { +) -> (Vec2, f32, usize) { let mut choice_weight = rng.sample::(StandardUniform); - let mut transform_index: u32 = 0; + let mut transform_index: usize = 0; for i in 0..weights.len() { choice_weight -= weights[i]; @@ -53,8 +53,10 @@ pub fn step_chaos_game( transform_index += 1; } + let ref transform = transforms[transform_index]; ( - transforms[transform_index as usize].transform_point(rng, variations, point), + transform.transform_point(rng, variations, point), + transform.transform_color(color), transform_index, ) } @@ -65,6 +67,7 @@ pub fn step_chaos_game( /// New points in the chaos game are produced by iterating on the chaos game. pub struct ChaosGame<'a, R: Rng> { current_point: Vec2, + current_color: f32, rng: &'a mut R, transforms: &'a [Transform], weights: &'a [f32], @@ -79,9 +82,9 @@ impl<'a, R: Rng> ChaosGame<'a, R> { weights: &'a [f32], variations: &'a [Variation], ) -> Self { - let current_point = vec2(rng.sample(BiUnit), rng.sample(BiUnit)); ChaosGame { - current_point, + current_point: vec2(rng.sample(BiUnit), rng.sample(BiUnit)), + current_color: rng.sample(StandardUniform), rng, transforms, weights, @@ -91,19 +94,21 @@ impl<'a, R: Rng> ChaosGame<'a, R> { } impl<'a, R: Rng> Iterator for ChaosGame<'a, R> { - type Item = Vec2; + type Item = (Vec2, f32); fn next(&mut self) -> Option { - let (next_point, _) = step_chaos_game( + let (next_point, next_color, _) = step_chaos_game( self.current_point, + self.current_color, self.rng, self.transforms, self.weights, self.variations, ); self.current_point = next_point; + self.current_color = next_color; - Some(next_point) + Some((next_point, next_color)) } } @@ -113,11 +118,17 @@ pub mod entry { use crate::rng::xoshiro256starstar_from_seed; use crate::transform::Transform; use crate::variation::Variation; - use glam::Vec2; + use glam::Vec4; use spirv_std::spirv; /// Given a set of fractal flame parameters, generate new IFS coordinates /// and store them in the output array. + /// + /// Arguments: + /// * `iteration_discard` - Choas game steps to discard prior to recording into the output buffer + /// * `output` - Output buffer to record chaos game steps into. Because of alignment issues, + /// the output is recorded as a [`Vec4`]; the IFS (x, y) coordinate is in `x` and `y`, + /// and color is in `w` #[spirv(compute(entry_point_name = "main_chaos_game", threads(1)))] pub fn main_chaos_game( #[spirv(spec_constant(id = 1, default = 20))] iteration_discard: u32, @@ -125,7 +136,7 @@ pub mod entry { #[spirv(storage_buffer, descriptor_set = 0, binding = 1)] transforms: &[Transform], #[spirv(storage_buffer, descriptor_set = 0, binding = 2)] weights: &[f32], #[spirv(storage_buffer, descriptor_set = 0, binding = 3)] variations: &[Variation], - #[spirv(storage_buffer, descriptor_set = 1, binding = 0)] output: &mut [Vec2], + #[spirv(storage_buffer, descriptor_set = 1, binding = 0)] output: &mut [Vec4], ) { let mut rng_seed_actual = [0u8; 32]; (0..32).for_each(|i| rng_seed_actual[i] = rng_seed[i]); @@ -138,7 +149,10 @@ pub mod entry { } for i in 0..output.len() { - output[i] = chaos_game.next().unwrap(); + output[i] = chaos_game + .next() + .map(|output| (output.0, 0.0, output.1).into()) + .unwrap(); } } } diff --git a/enkou-shaders/src/rng.rs b/enkou-shaders/src/rng.rs index 7dbeae8..0c7cb2e 100644 --- a/enkou-shaders/src/rng.rs +++ b/enkou-shaders/src/rng.rs @@ -19,7 +19,7 @@ pub(crate) fn xoshiro256starstar_from_seed( ) -> Xoshiro256StarStar { let mut rng_state_actual = [0u64; 4]; - // NOTE: Bit shifting is bad, but we don't have great alternatives: + // NOTE: Bit shifting is tedious, but we don't have great alternatives: // - `chunks_exact` has issues with pointer casting // - `u64::from_le_bytes` has issues with `OpBitcast` in SPIR-V validation for i in 0..rng_state_actual.len() { diff --git a/enkou-shaders/src/transform.rs b/enkou-shaders/src/transform.rs index 3b8badc..1dc9965 100644 --- a/enkou-shaders/src/transform.rs +++ b/enkou-shaders/src/transform.rs @@ -5,7 +5,7 @@ //! but produce more interesting images once we add variations. use crate::variation::Variation; use bytemuck::{Pod, Zeroable}; -use glam::{Affine2, UVec2, Vec2}; +use glam::{Affine2, FloatExt, UVec2, Vec2}; use rand::Rng; /// Affine transform for use in the [`chaos_game`](crate::chaos_game). @@ -14,14 +14,21 @@ use rand::Rng; pub struct Transform { coefficients: Affine2, variation_range: UVec2, + color: Vec2, } impl Transform { /// Create a new transform from an affine transformation matrix - pub fn new(coefficients: Affine2, variation_range: UVec2) -> Self { + /// + /// Arguments: + /// * `coefficients` - Affine transform coefficients for this transformation. Applied prior to variations + /// * `variation_range` - (half-open) range of variations to apply during [`Self::transform_point`] + /// * `color` - Color value and speed to apply during [`Self::transform_color`] + pub fn new(coefficients: Affine2, variation_range: UVec2, color: Vec2) -> Self { Transform { coefficients, variation_range, + color, } } @@ -45,4 +52,105 @@ impl Transform { point_output } + + /// Mix an existing color with this transform's color + pub fn transform_color(&self, color: f32) -> f32 { + color.lerp(self.color.x, self.color.y) + } +} + +#[cfg(test)] +mod test { + use crate::Coefficients2; + use crate::transform::Transform; + use crate::variation::{Variation, VariationKind}; + use core::convert::Infallible; + use glam::{Affine2, Vec2, uvec2, vec2}; + use rand::TryRng; + + struct NullRng; + + impl NullRng { + pub fn new() -> Self { + NullRng + } + } + + impl TryRng for NullRng { + type Error = Infallible; + + fn try_next_u32(&mut self) -> Result { + Ok(0) + } + + fn try_next_u64(&mut self) -> Result { + Ok(0) + } + + fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> { + dst.iter_mut().for_each(|b| *b = 0); + Ok(()) + } + } + + #[test] + fn test_transform_point_identity() { + let transform = Transform::new(Affine2::IDENTITY, uvec2(0, 1), vec2(0.0, 0.0)); + let variations = [Variation::IDENTITY]; + + let transform_point = + |point: Vec2| transform.transform_point(&mut NullRng::new(), &variations, point); + for (input, expected) in [ + (vec2(0.0, 1.0), vec2(0.0, 1.0)), + (vec2(1.0, 0.0), vec2(1.0, 0.0)), + (vec2(1.0, 1.0), vec2(1.0, 1.0)), + ] { + assert_eq!(transform_point(input), expected); + } + } + + #[test] + fn test_transform_point_scaling() { + let transform = Transform::new( + Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.0), + uvec2(0, 1), + vec2(0.0, 0.0), + ); + let variations = [Variation::IDENTITY]; + + let transform_point = + |point: Vec2| transform.transform_point(&mut NullRng::new(), &variations, point); + for (input, expected) in [ + (vec2(0.0, 1.0), vec2(0.0, 0.5)), + (vec2(1.0, 0.0), vec2(0.5, 0.0)), + (vec2(1.0, 1.0), vec2(0.5, 0.5)), + ] { + assert_eq!(transform_point(input), expected); + } + } + + #[test] + fn test_transform_point_scaling_variation() { + let transform = Transform::new(Affine2::IDENTITY, uvec2(0, 1), vec2(0.0, 0.0)); + let variations = [Variation::new(VariationKind::Linear, 2.0, [0.0; 4].into())]; + + let transform_point = + |point: Vec2| transform.transform_point(&mut NullRng::new(), &variations, point); + for (input, expected) in [ + (vec2(0.0, 1.0), vec2(0.0, 2.0)), + (vec2(1.0, 0.0), vec2(2.0, 0.0)), + (vec2(1.0, 1.0), vec2(2.0, 2.0)), + ] { + assert_eq!(transform_point(input), expected); + } + } + + #[test] + fn test_color_mixing() { + let transform = Transform::new(Affine2::IDENTITY, uvec2(0, 1), vec2(0.0, 0.5)); + + assert_eq!(transform.transform_color(0.0), 0.0); + assert_eq!(transform.transform_color(1.0), 0.5); + assert_eq!(transform.transform_color(0.5), 0.25); + } } diff --git a/enkou-shaders/src/variation.rs b/enkou-shaders/src/variation.rs index 06a0df0..381b9be 100644 --- a/enkou-shaders/src/variation.rs +++ b/enkou-shaders/src/variation.rs @@ -20,6 +20,12 @@ use rand::{Rng, RngExt}; #[repr(C)] pub struct VariationParams([f32; 4]); +impl From<[f32; 4]> for VariationParams { + fn from(value: [f32; 4]) -> Self { + VariationParams(value) + } +} + /// Enum for all supported variation types /// /// ID numbers are chosen to match the variation identifier also used by `flam3` -- 2.52.0 From 5bd325d0ea06f944bce770d5ccf4eef7139ae553 Mon Sep 17 00:00:00 2001 From: Bradlee Speice Date: Fri, 3 Jul 2026 14:07:45 -0400 Subject: [PATCH 5/7] Implement camera colors Still needs some unit tests, and to fix the gasket example --- enkou-shaders-tests/build.rs | 7 +- enkou-shaders-tests/src/lib.rs | 7 +- enkou-shaders/examples/gasket.rs | 34 ++++---- enkou-shaders/src/camera.rs | 129 +++++++++++++++++++++---------- 4 files changed, 120 insertions(+), 57 deletions(-) diff --git a/enkou-shaders-tests/build.rs b/enkou-shaders-tests/build.rs index 117b150..78f08d6 100644 --- a/enkou-shaders-tests/build.rs +++ b/enkou-shaders-tests/build.rs @@ -16,7 +16,12 @@ pub fn main() -> anyhow::Result<()> { builder.build_script.defaults = true; builder.shader_panic_strategy = ShaderPanicStrategy::SilentExit; builder.spirv_metadata = SpirvMetadata::Full; - builder.capabilities = vec![Capability::Int8, Capability::Int16, Capability::Int64]; + builder.capabilities = vec![ + Capability::Int8, + Capability::Int16, + Capability::Int64, + Capability::Float64, + ]; let compile_result = builder.build()?; let spv_path = compile_result.module.unwrap_single(); diff --git a/enkou-shaders-tests/src/lib.rs b/enkou-shaders-tests/src/lib.rs index 5827196..dd97640 100644 --- a/enkou-shaders-tests/src/lib.rs +++ b/enkou-shaders-tests/src/lib.rs @@ -64,7 +64,10 @@ mod test { } #[test] - pub fn has_entry_main_camera() { - assert!(has_entry_point(ExecutionModel::GLCompute, "main_camera")) + pub fn has_entry_main_image_render() { + assert!(has_entry_point( + ExecutionModel::GLCompute, + "main_image_render" + )) } } diff --git a/enkou-shaders/examples/gasket.rs b/enkou-shaders/examples/gasket.rs index 87991b4..21b2af9 100644 --- a/enkou-shaders/examples/gasket.rs +++ b/enkou-shaders/examples/gasket.rs @@ -1,12 +1,12 @@ use anyhow::{Context, Result}; use enkou_shaders::Coefficients2; use enkou_shaders::camera::Camera; -use enkou_shaders::camera::entry::main_camera; +use enkou_shaders::camera::entry::main_image_render; use enkou_shaders::chaos_game::entry::main_chaos_game; use enkou_shaders::transform::Transform; use enkou_shaders::variation::Variation; -use glam::{Affine2, IVec2, UVec2, Vec2, Vec4, uvec2, vec2}; -use image::{GrayImage, Luma}; +use glam::{Affine2, UVec2, Vec2, Vec4, uvec2, vec2}; +use image::{Rgba, Rgba32FImage}; use std::mem; use std::process::Command; use tempfile::NamedTempFile; @@ -62,20 +62,26 @@ pub fn main() -> Result<()> { IMAGE_DIMENSION.as_vec2(), ); + let palette = &[Vec4::ONE; 2]; + let mut output_points_pixel = Vec::new(); - output_points_pixel.resize(ITERATIONS as usize, IVec2::ZERO); + output_points_pixel.resize(ITERATIONS as usize, Vec4::ZERO); - main_camera(&camera, &output_points_ifs, &mut output_points_pixel); + main_image_render( + &camera, + palette, + &output_points_ifs, + &mut output_points_pixel, + ); - let mut image = GrayImage::new(IMAGE_DIMENSION.x, IMAGE_DIMENSION.y); - let dimensions = image.dimensions(); - output_points_pixel - .iter() - .skip_while(|p| { - p.x < 0 || (p.x as u32) > dimensions.0 || p.y < 0 || (p.y as u32) > dimensions.1 - }) - .map(|p| (p.x as u32, p.y as u32)) - .for_each(|(x, y)| image.put_pixel(x, y, Luma([255u8]))); + let mut image = Rgba32FImage::new(IMAGE_DIMENSION.x, IMAGE_DIMENSION.y); + for x in 0..image.dimensions().0 { + for y in 0..image.dimensions().1 { + let pixel_index = y * IMAGE_DIMENSION.x + x; + let pixel = output_points_pixel[pixel_index as usize]; + image.put_pixel(x, y, Rgba(pixel.into())); + } + } let temp = NamedTempFile::with_suffix(".png").context("Unable to create file for image")?; image.save(temp.path()).context("Unable to save image")?; diff --git a/enkou-shaders/src/camera.rs b/enkou-shaders/src/camera.rs index 0cf6863..82a752f 100644 --- a/enkou-shaders/src/camera.rs +++ b/enkou-shaders/src/camera.rs @@ -2,8 +2,47 @@ //! //! Map points from the IFS coordinate system to pixel coordinates. This is a lossy transformation. use bytemuck::{Pod, Zeroable}; -use glam::{Affine2, IVec2, UVec2, Vec2, vec2}; -use libm::powf; +use glam::{Affine2, IVec2, UVec2, Vec2, Vec4, Vec4Swizzles, vec2}; +use libm::{ceilf, floorf, powf}; + +/// Blending modes for mapping IFS color values (which are on a scale `[0, 1]`) +/// to RGBA colors. +#[derive(Copy, Clone)] +#[repr(u32)] +pub enum BlendMode { + /// Map IFS color values to a linear blend of the nearest two palette colors + Linear = 0, + + /// Map IFS color values to the nearest single palette color + Step = 1, +} + +impl Default for BlendMode { + fn default() -> Self { + BlendMode::Linear + } +} + +impl BlendMode { + /// Map an IFS color value to RGBA color from the provided palette. + pub fn ifs_to_rgb(&self, color: f32, palette: &[Vec4]) -> Vec4 { + let palette_index = color * palette.len() as f32; + let palette_index_lower = floorf(palette_index) as usize; + let palette_index_upper = ceilf(palette_index) as usize; + + match self { + BlendMode::Linear => { + (palette[palette_index_lower] + palette[palette_index_upper]) / 2.0 + } + BlendMode::Step => palette[palette_index_lower], + } + } +} + +// UNSAFE: Sound because enum has guaranteed layout (u32) and defined zero-value +unsafe impl bytemuck::Zeroable for BlendMode {} +// UNSAFE: Sound because enum has guaranteed layout (u32) and defined zero-value +unsafe impl bytemuck::Pod for BlendMode {} /// Settings used to map IFS coordinates to pixel coordinates. /// @@ -14,6 +53,8 @@ use libm::powf; pub struct Camera { dimensions: UVec2, transform: Affine2, + blend_mode: BlendMode, + image_gamma: f32, } impl Camera { @@ -50,62 +91,70 @@ impl Camera { Camera { dimensions, transform, + blend_mode: BlendMode::Linear, + image_gamma: 1.5, } } - /// Map a point from IFS coordinates to pixel coordinates. - /// - /// ``` - /// # use glam::{vec2, ivec2, uvec2, Vec2}; - /// # use crate::enkou_shaders::camera::Camera; - /// // Output image is 600x600 pixels, centered at the origin, no rotation, no zoom, - /// // and scaled such that it covers the range [-2, 2]. - /// // Use the origin as the IFS coordinate, so the pixel coordinate is the center of the image - /// let camera = Camera::new( - /// uvec2(600, 600), - /// Vec2::ZERO, - /// 0.0, - /// Vec2::ZERO, - /// vec2(150.0, 150.0) - /// ); - /// assert_eq!(camera.transform_point(vec2(0.0, 0.0)), ivec2(300, 300)); - /// ``` - pub fn transform_point(&self, point: Vec2) -> IVec2 { + fn transform_point(&self, point: Vec2) -> IVec2 { self.transform.transform_point2(point).as_ivec2() } - /// Map a point from IFS coordinates to pixel coordinates (like [`transform_point`](Camera::transform_point)), - /// and check that the result is within the provided image dimensions. - pub fn transform_point_to_image(&self, point: Vec2) -> Option { - let pixel_coordinates = self.transform_point(point); + /// Map a point from IFS coordinates to a pixel index and RGBA value; if the IFS coordinate + /// is outside the viewable range, return [`None`]. + pub fn transform_point_to_image(&self, point: Vec4, palette: &[Vec4]) -> Option<(usize, Vec4)> { + let pixel_coordinates = self.transform_point(point.xy()); if pixel_coordinates.x < 0 || pixel_coordinates.y < 0 || (pixel_coordinates.x as u32) >= self.dimensions.x || (pixel_coordinates.y as u32) >= self.dimensions.y { - None - } else { - Some(pixel_coordinates.as_uvec2()) + return None; } + + let to_pixel_index = self.dimensions.with_y(0); + let pixel_index = pixel_coordinates.as_uvec2().dot(to_pixel_index) as usize; + + let rgba = self.blend_mode.ifs_to_rgb(point.w, palette); + + Some((pixel_index, rgba)) } } -/// Shader entry point for running the camera transformation over a list of IFS coordinates +#[allow(missing_docs)] pub mod entry { use crate::camera::Camera; - use glam::{Vec4, Vec4Swizzles}; - use spirv_std::glam::IVec2; + use glam::Vec4; + use libm::log10f; use spirv_std::spirv; - /// Transform IFS coordinates to pixel coordinates - #[spirv(compute(entry_point_name = "main_camera", threads(1)))] - pub fn main_camera( + /// Render an output image from a list of IFS coordinates. + /// + /// Arguments: + /// * `camera` - Camera settings for mapping IFS coordinates to pixel coordinates + /// * `palette` - Color palette to use when mapping IFS color to RGB colors. Individual elements + /// are assumed to be RGBA values on the scale of `[0, 1]` + /// * `coordinates_ifs` - IFS coordinates to use for the output image + /// * `image` - Buffer for the output image + #[spirv(compute(entry_point_name = "main_image_render", threads(1)))] + pub fn main_image_render( #[spirv(storage_buffer, descriptor_set = 0, binding = 0)] camera: &Camera, + #[spirv(storage_buffer, descriptor_set = 0, binding = 1)] palette: &[Vec4], #[spirv(storage_buffer, descriptor_set = 0, binding = 1)] coordinates_ifs: &[Vec4], - #[spirv(storage_buffer, descriptor_set = 1, binding = 0)] coordinates_pixel: &mut [IVec2], + #[spirv(storage_buffer, descriptor_set = 1, binding = 0)] image: &mut [Vec4], ) { - for i in 0..coordinates_ifs.len() { - coordinates_pixel[i] = camera.transform_point(coordinates_ifs[i].xy()) + for coordinate_index in 0..coordinates_ifs.len() { + camera + .transform_point_to_image(coordinates_ifs[coordinate_index], palette) + .map(|(pixel_index, rgba)| image[pixel_index] += rgba); + } + + for pixel_index in 0..image.len() { + // TODO: Fix the bootleg gamma adjustment + let pixel_unscaled = image[pixel_index]; + let pixel = + pixel_unscaled * log10f(pixel_unscaled.w) / (pixel_unscaled.w * camera.image_gamma); + image[pixel_index] = pixel; } } } @@ -117,7 +166,7 @@ mod test { use libm::powf; #[test] - pub fn manual_camera() { + fn manual_camera() { let starting_point = vec2(1.0, 1.0); // Move the origin; points move right and up by one unit, giving us (2.0, 2.0) @@ -155,7 +204,7 @@ mod test { } #[test] - pub fn point_outside_camera() { + fn point_outside_camera() { // Scale 250 for an image 1000 x 1000 gives an effective range of [-2, 2] let camera = Camera::new( uvec2(1000, 1000), @@ -170,7 +219,7 @@ mod test { } #[test] - pub fn point_outside_camera_negative() { + fn point_outside_camera_negative() { // Scale 250 for an image 1000 x 1000 gives an effective range of [-2, 2] let camera = Camera::new( uvec2(1000, 1000), @@ -185,7 +234,7 @@ mod test { } #[test] - pub fn aspect_ratio() { + fn aspect_ratio() { // Scale 100 for an image 1600 x 900 gives an effective X range of [-8, 8], // and effective Y range of [-4.5, 4.5] let camera = Camera::new( -- 2.52.0 From 0d9d2b693ee247a64eb8cf2085fa6c124278ece3 Mon Sep 17 00:00:00 2001 From: Bradlee Speice Date: Fri, 3 Jul 2026 16:18:01 -0400 Subject: [PATCH 6/7] Fix palette blend modes, add unit tests --- enkou-shaders/src/camera.rs | 68 +++++++++++++++++++++++++++++-------- 1 file changed, 54 insertions(+), 14 deletions(-) diff --git a/enkou-shaders/src/camera.rs b/enkou-shaders/src/camera.rs index 82a752f..93adbee 100644 --- a/enkou-shaders/src/camera.rs +++ b/enkou-shaders/src/camera.rs @@ -3,7 +3,7 @@ //! Map points from the IFS coordinate system to pixel coordinates. This is a lossy transformation. use bytemuck::{Pod, Zeroable}; use glam::{Affine2, IVec2, UVec2, Vec2, Vec4, Vec4Swizzles, vec2}; -use libm::{ceilf, floorf, powf}; +use libm::{floorf, powf}; /// Blending modes for mapping IFS color values (which are on a scale `[0, 1]`) /// to RGBA colors. @@ -26,15 +26,15 @@ impl Default for BlendMode { impl BlendMode { /// Map an IFS color value to RGBA color from the provided palette. pub fn ifs_to_rgb(&self, color: f32, palette: &[Vec4]) -> Vec4 { - let palette_index = color * palette.len() as f32; - let palette_index_lower = floorf(palette_index) as usize; - let palette_index_upper = ceilf(palette_index) as usize; + let colors_m_one = palette.len() - 1; + let period = 1.0 / colors_m_one as f32; + let index_lower = floorf(color / period) as usize; + let index_upper = (index_lower + 1).clamp(0, colors_m_one); + let rem = color % period / period; match self { - BlendMode::Linear => { - (palette[palette_index_lower] + palette[palette_index_upper]) / 2.0 - } - BlendMode::Step => palette[palette_index_lower], + BlendMode::Linear => palette[index_lower].lerp(palette[index_upper], rem), + BlendMode::Step => palette[index_lower], } } } @@ -161,12 +161,52 @@ pub mod entry { #[cfg(test)] mod test { - use crate::camera::Camera; - use glam::{Affine2, Vec2, ivec2, uvec2, vec2}; + use crate::camera::{BlendMode, Camera}; + use glam::{Affine2, Vec2, Vec4, ivec2, uvec2, vec2}; use libm::powf; + fn vec4s(value: f32) -> Vec4 { + Vec4::splat(value) + } + #[test] - fn manual_camera() { + fn blend_linear() { + let ifs_to_rgb = |color, palette| BlendMode::Linear.ifs_to_rgb(color, palette); + + let palette = &[vec4s(0.0), vec4s(1.0)]; + assert_eq!(ifs_to_rgb(0.0, palette), vec4s(0.0)); + assert_eq!(ifs_to_rgb(0.5, palette), vec4s(0.5)); + assert_eq!(ifs_to_rgb(1.0, palette), vec4s(1.0)); + + let palette = &[vec4s(1.0), vec4s(2.0), vec4s(3.0)]; + assert_eq!(ifs_to_rgb(0.0, palette), vec4s(1.0)); + assert_eq!(ifs_to_rgb(0.5, palette), vec4s(2.0)); + assert_eq!(ifs_to_rgb(1.0, palette), vec4s(3.0)); + + let palette = &[vec4s(1.0), vec4s(2.0), vec4s(3.0), vec4s(4.0)]; + assert_eq!(ifs_to_rgb(0.0, palette), vec4s(1.0)); + assert_eq!(ifs_to_rgb(0.5, palette), vec4s(2.5)); + assert_eq!(ifs_to_rgb(1.0, palette), vec4s(4.0)); + } + + #[test] + fn blend_step() { + let ifs_to_rgb = |color, palette| BlendMode::Step.ifs_to_rgb(color, palette); + + let palette = &[vec4s(0.0), vec4s(1.0)]; + assert_eq!(ifs_to_rgb(0.5, palette), vec4s(0.0)); + + let palette = &[vec4s(1.0), vec4s(2.0), vec4s(3.0)]; + assert_eq!(ifs_to_rgb(0.0, palette), palette[0]); + assert_eq!(ifs_to_rgb(0.25, palette), palette[0]); + assert_eq!(ifs_to_rgb(0.4, palette), palette[0]); + assert_eq!(ifs_to_rgb(0.5, palette), palette[1]); + assert_eq!(ifs_to_rgb(0.7, palette), palette[1]); + assert_eq!(ifs_to_rgb(1.0, palette), palette[2]); + } + + #[test] + fn camera_manual() { let starting_point = vec2(1.0, 1.0); // Move the origin; points move right and up by one unit, giving us (2.0, 2.0) @@ -204,7 +244,7 @@ mod test { } #[test] - fn point_outside_camera() { + fn camera_point_outside_image() { // Scale 250 for an image 1000 x 1000 gives an effective range of [-2, 2] let camera = Camera::new( uvec2(1000, 1000), @@ -219,7 +259,7 @@ mod test { } #[test] - fn point_outside_camera_negative() { + fn camera_point_outside_image_negative() { // Scale 250 for an image 1000 x 1000 gives an effective range of [-2, 2] let camera = Camera::new( uvec2(1000, 1000), @@ -234,7 +274,7 @@ mod test { } #[test] - fn aspect_ratio() { + fn camera_aspect_ratio() { // Scale 100 for an image 1600 x 900 gives an effective X range of [-8, 8], // and effective Y range of [-4.5, 4.5] let camera = Camera::new( -- 2.52.0 From 6a7ce141374d38988b0919efefd678bc246434e2 Mon Sep 17 00:00:00 2001 From: Bradlee Speice Date: Sat, 4 Jul 2026 12:23:57 -0400 Subject: [PATCH 7/7] Start fixes for the gasket example The image is inverted for reasons I don't entirely understand yet --- enkou-shaders/examples/gasket.rs | 17 +++++++++------ enkou-shaders/src/camera.rs | 36 +++++++++++++++++++++----------- 2 files changed, 35 insertions(+), 18 deletions(-) diff --git a/enkou-shaders/examples/gasket.rs b/enkou-shaders/examples/gasket.rs index 21b2af9..5b147ed 100644 --- a/enkou-shaders/examples/gasket.rs +++ b/enkou-shaders/examples/gasket.rs @@ -5,8 +5,8 @@ use enkou_shaders::camera::entry::main_image_render; use enkou_shaders::chaos_game::entry::main_chaos_game; use enkou_shaders::transform::Transform; use enkou_shaders::variation::Variation; -use glam::{Affine2, UVec2, Vec2, Vec4, uvec2, vec2}; -use image::{Rgba, Rgba32FImage}; +use glam::{Affine2, UVec2, Vec2, Vec2Swizzles, Vec4, uvec2, vec2}; +use image::{Rgba, RgbaImage}; use std::mem; use std::process::Command; use tempfile::NamedTempFile; @@ -65,7 +65,7 @@ pub fn main() -> Result<()> { let palette = &[Vec4::ONE; 2]; let mut output_points_pixel = Vec::new(); - output_points_pixel.resize(ITERATIONS as usize, Vec4::ZERO); + output_points_pixel.resize(IMAGE_DIMENSION.xy().element_product() as usize, Vec4::ZERO); main_image_render( &camera, @@ -74,11 +74,16 @@ pub fn main() -> Result<()> { &mut output_points_pixel, ); - let mut image = Rgba32FImage::new(IMAGE_DIMENSION.x, IMAGE_DIMENSION.y); - for x in 0..image.dimensions().0 { - for y in 0..image.dimensions().1 { + let mut image = RgbaImage::new(IMAGE_DIMENSION.x, IMAGE_DIMENSION.y); + for y in 0..image.dimensions().1 { + for x in 0..image.dimensions().0 { let pixel_index = y * IMAGE_DIMENSION.x + x; let pixel = output_points_pixel[pixel_index as usize]; + let pixel = pixel.to_array().map(|channel| { + let channel = if channel.is_nan() { 0.0 } else { channel }; + let channel = channel * u8::MAX as f32; + channel as u8 + }); image.put_pixel(x, y, Rgba(pixel.into())); } } diff --git a/enkou-shaders/src/camera.rs b/enkou-shaders/src/camera.rs index 93adbee..90b0af6 100644 --- a/enkou-shaders/src/camera.rs +++ b/enkou-shaders/src/camera.rs @@ -3,7 +3,7 @@ //! Map points from the IFS coordinate system to pixel coordinates. This is a lossy transformation. use bytemuck::{Pod, Zeroable}; use glam::{Affine2, IVec2, UVec2, Vec2, Vec4, Vec4Swizzles, vec2}; -use libm::{floorf, powf}; +use libm::{floorf, log10f, powf}; /// Blending modes for mapping IFS color values (which are on a scale `[0, 1]`) /// to RGBA colors. @@ -102,7 +102,11 @@ impl Camera { /// Map a point from IFS coordinates to a pixel index and RGBA value; if the IFS coordinate /// is outside the viewable range, return [`None`]. - pub fn transform_point_to_image(&self, point: Vec4, palette: &[Vec4]) -> Option<(usize, Vec4)> { + pub fn transform_point_to_image_hist( + &self, + point: Vec4, + palette: &[Vec4], + ) -> Option<(usize, Vec4)> { let pixel_coordinates = self.transform_point(point.xy()); if pixel_coordinates.x < 0 || pixel_coordinates.y < 0 @@ -112,20 +116,29 @@ impl Camera { return None; } - let to_pixel_index = self.dimensions.with_y(0); + let to_pixel_index = self.dimensions.with_y(1); let pixel_index = pixel_coordinates.as_uvec2().dot(to_pixel_index) as usize; let rgba = self.blend_mode.ifs_to_rgb(point.w, palette); Some((pixel_index, rgba)) } + + /// Map an accumulated RGBA value to the final pixel color value + pub fn transform_image_hist_to_rgba(&self, pixel: Vec4) -> Vec4 { + if pixel.w <= 0.0 { + Vec4::ZERO + } else { + // TODO: Fix the bootleg gamma adjustment + (pixel * log10f(pixel.w) / (pixel.w * self.image_gamma)).clamp(Vec4::ZERO, Vec4::ONE) + } + } } #[allow(missing_docs)] pub mod entry { use crate::camera::Camera; use glam::Vec4; - use libm::log10f; use spirv_std::spirv; /// Render an output image from a list of IFS coordinates. @@ -144,17 +157,16 @@ pub mod entry { #[spirv(storage_buffer, descriptor_set = 1, binding = 0)] image: &mut [Vec4], ) { for coordinate_index in 0..coordinates_ifs.len() { - camera - .transform_point_to_image(coordinates_ifs[coordinate_index], palette) - .map(|(pixel_index, rgba)| image[pixel_index] += rgba); + if let Some((pixel_index, rgba)) = + camera.transform_point_to_image_hist(coordinates_ifs[coordinate_index], palette) + { + image[pixel_index] += rgba; + } } for pixel_index in 0..image.len() { - // TODO: Fix the bootleg gamma adjustment - let pixel_unscaled = image[pixel_index]; - let pixel = - pixel_unscaled * log10f(pixel_unscaled.w) / (pixel_unscaled.w * camera.image_gamma); - image[pixel_index] = pixel; + let rgba = camera.transform_image_hist_to_rgba(image[pixel_index]); + image[pixel_index] = rgba; } } } -- 2.52.0