Compare commits

31 Commits

Author SHA1 Message Date
bspeice 6a7ce14137 Start fixes for the gasket example
CI / cargo fmt (push) Successful in 25s
CI / cargo test (push) Successful in 13m26s
CI / cargo test (GPU) (push) Successful in 12m50s
The image is inverted for reasons I don't entirely understand yet
2026-07-04 12:23:57 -04:00
bspeice d79ff7be21 Merge remote-tracking branch 'origin/color' into color 2026-07-04 11:19:34 -04:00
bspeice 0d9d2b693e Fix palette blend modes, add unit tests
CI / cargo fmt (push) Successful in 27s
CI / cargo test (push) Successful in 13m16s
CI / cargo test (GPU) (push) Successful in 12m53s
2026-07-03 17:48:35 -04:00
bspeice 5bd325d0ea Implement camera colors
Still needs some unit tests, and to fix the gasket example
2026-07-03 17:48:35 -04:00
bspeice 4e508884ae Implement transform colors 2026-07-03 17:48:35 -04:00
bspeice 4005e14ab0 Merge pull request 'Include examples as part of cargo check' (#5) from ci_all_targets into main
CI / cargo fmt (push) Successful in 22s
CI / cargo test (push) Successful in 13m7s
CI / cargo test (GPU) (push) Successful in 12m35s
Reviewed-on: #5
2026-07-03 17:48:20 -04:00
bspeice 3bd01da563 Include examples as part of cargo check
CI / cargo fmt (push) Successful in 23s
CI / cargo test (push) Successful in 13m22s
CI / cargo test (GPU) (push) Successful in 12m35s
2026-07-03 16:23:11 -04:00
bspeice dfc9cf821c Fix palette blend modes, add unit tests
CI / cargo fmt (push) Successful in 21s
CI / cargo test (GPU) (push) Has been cancelled
CI / cargo test (push) Has been cancelled
2026-07-03 16:18:01 -04:00
bspeice 54ba76b380 Implement camera colors
CI / cargo fmt (push) Successful in 22s
CI / cargo test (push) Successful in 12m34s
CI / cargo test (GPU) (push) Successful in 12m51s
Still needs some unit tests, and to fix the gasket example
2026-07-03 14:07:45 -04:00
bspeice a1b9a274f7 Implement transform colors 2026-07-03 11:30:40 -04:00
bspeice 616bd2ae6d Merge pull request 'Variation' (#3) from variation into main
CI / cargo fmt (push) Successful in 27s
CI / cargo test (push) Successful in 14m32s
CI / cargo test (GPU) (push) Successful in 16m32s
Reviewed-on: #3
2026-07-03 09:29:05 -04:00
bspeice 86ef0887e3 Fix RNG transmutation
CI / cargo test (push) Successful in 14m31s
CI / cargo test (GPU) (push) Successful in 12m49s
CI / cargo fmt (push) Successful in 28s
2026-06-29 20:40:12 -04:00
bspeice 3c5563c940 Add documentation for recent functions
CI / cargo fmt (push) Successful in 28s
CI / cargo test (push) Successful in 14m23s
CI / cargo test (GPU) (push) Successful in 13m26s
2026-06-28 15:03:52 -04:00
bspeice c3224fadd8 Upgrade rand/rand_xoshiro version
CI / cargo fmt (push) Successful in 32s
CI / cargo test (push) Failing after 29s
CI / cargo test (GPU) (push) Successful in 17m53s
2026-06-27 18:27:43 -04:00
bspeice 44b71c2692 Add entry points for GPU 2026-06-27 18:25:41 -04:00
bspeice 6671475c75 Implement basic variation support
CI / cargo fmt (push) Successful in 24s
CI / cargo test (push) Failing after 26s
CI / cargo test (GPU) (push) Successful in 17m57s
2026-06-27 15:11:23 -04:00
bspeice df747855b6 Merge pull request 'Sierpinski Gasket' (#2) from sierpinski_gasket into main
CI / cargo fmt (push) Successful in 23s
CI / cargo test (push) Successful in 14m43s
CI / cargo test (GPU) (push) Successful in 17m35s
Reviewed-on: #2
2026-06-27 14:14:40 -04:00
bspeice 55cece063f Fix documentation whitespace
CI / cargo fmt (push) Successful in 21s
CI / cargo test (push) Successful in 14m18s
CI / cargo test (GPU) (push) Successful in 17m14s
2026-06-27 11:07:23 -04:00
bspeice 344ecc3450 Add missing documentation
CI / cargo fmt (push) Failing after 25s
CI / cargo test (GPU) (push) Has been cancelled
CI / cargo test (push) Has been cancelled
2026-06-27 11:02:19 -04:00
bspeice a9da463041 Fix the documentation 2026-06-27 10:11:26 -04:00
bspeice 67b94522d0 Run cargo fmt 2026-06-27 10:11:01 -04:00
bspeice beb1c8526f Implement a basic Sierpinski Gasket IFS
CI / cargo fmt (push) Failing after 1m23s
CI / cargo test (push) Failing after 33s
CI / cargo test (GPU) (push) Successful in 20m4s
2026-06-22 20:46:47 -04:00
bspeice 90f886f971 Implement the IFS camera
CI / cargo fmt (push) Successful in 22s
CI / cargo test (push) Failing after 13m52s
CI / cargo test (GPU) (push) Successful in 13m45s
2026-06-20 15:10:25 -04:00
bspeice 1709336062 Add an initial implementation of the chaos game 2026-06-20 10:05:04 -04:00
bspeice bb4e0aa669 Add a coefficients trait for converting the affine coefficient notation flam3 uses to how glam represents it 2026-06-20 09:20:38 -04:00
bspeice 5603f19c22 Merge pull request 'Automatically install rust toolchain for CI' (#1) from cargo_gpu_builder into main
CI / cargo fmt (push) Successful in 23s
CI / cargo test (push) Successful in 12m50s
CI / cargo test (GPU) (push) Successful in 12m47s
Reviewed-on: #1
2026-06-19 22:20:22 -04:00
bspeice 35784514d6 Fix the CI action, the build scripts were fine
CI / cargo fmt (push) Successful in 25s
CI / cargo test (push) Successful in 13m3s
CI / cargo test (GPU) (push) Successful in 12m57s
2026-06-19 21:50:41 -04:00
bspeice 24a40adcad Revert "Automatically install rust toolchain for CI"
This reverts commit 0a17b24451.
2026-06-19 21:49:29 -04:00
bspeice 0a17b24451 Automatically install rust toolchain for CI
CI / cargo fmt (push) Successful in 9m34s
CI / cargo test (push) Has been cancelled
CI / cargo test (GPU) (push) Has been cancelled
2026-06-19 20:56:04 -04:00
bspeice 3652de9fd1 Attempt to use the Gitea build cache
CI / cargo fmt (push) Has been cancelled
CI / cargo test (push) Has been cancelled
CI / cargo test (GPU) (push) Has been cancelled
2026-06-19 20:55:30 -04:00
bspeice bf82670f9e Disable running CI on pull requests
CI / cargo fmt (push) Has been cancelled
CI / cargo test (push) Has been cancelled
CI / cargo test (GPU) (push) Has been cancelled
It's already running on push for all branches.
2026-06-19 20:01:15 -04:00
13 changed files with 1979 additions and 46 deletions
+2 -3
View File
@@ -1,7 +1,6 @@
name: "CI"
on:
push:
pull_request:
workflow_dispatch:
jobs:
@@ -22,7 +21,7 @@ jobs:
steps:
- uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1
- run: cargo check
- run: cargo check --all-targets
- run: cargo test
test-gpu:
@@ -32,4 +31,4 @@ jobs:
- uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1
- run: cargo install --git https://github.com/rust-gpu/rust-gpu cargo-gpu
- run: cargo gpu check -p enkou-shaders
- run: cargo gpu check --auto-install-rust-toolchain -p enkou-shaders
Generated
+926 -1
View File
File diff suppressed because it is too large Load Diff
+6 -2
View File
@@ -21,6 +21,10 @@ spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "67f1ff2"
anyhow = "1.0.102"
bytemuck = { version = "1.25.0", features = ["derive"] }
glam = { version = "0.33.1", default-features = false, features = ["libm"] }
glam = { version = "0.33.1", default-features = false, features = ["bytemuck", "scalar-math"] }
image = { version = "0.25.10", default-features = false, features = ["default-formats"]}
libm = "0.2.16"
rand = { version = "0.10.1", default-features = false }
rand_xoshiro = "0.8.1"
rspirv = "0.13.0"
tempfile = "3.27.0"
+10 -6
View File
@@ -1,5 +1,5 @@
use cargo_gpu_install::install::Install;
use cargo_gpu_install::spirv_builder::{ShaderPanicStrategy, SpirvMetadata};
use cargo_gpu_install::spirv_builder::{Capability, ShaderPanicStrategy, SpirvMetadata};
use std::path::PathBuf;
pub fn main() -> anyhow::Result<()> {
@@ -9,15 +9,19 @@ pub fn main() -> anyhow::Result<()> {
.copied()
.collect::<PathBuf>();
let mut install = Install::from_shader_crate(crate_path.clone());
install.build_script = true;
install.auto_install_rust_toolchain = true;
let install = install.run()?;
let install = Install::from_shader_crate(crate_path.clone())
.within_build_script()
.run()?;
let mut builder = install.to_spirv_builder(crate_path, "spirv-unknown-vulkan1.3");
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,
Capability::Float64,
];
let compile_result = builder.build()?;
let spv_path = compile_result.module.unwrap_single();
+10 -4
View File
@@ -56,12 +56,18 @@ mod test {
}
#[test]
pub fn has_entry_main_fs() {
assert!(has_entry_point(ExecutionModel::Fragment, "main_fs"))
pub fn has_entry_main_chaos_game() {
assert!(has_entry_point(
ExecutionModel::GLCompute,
"main_chaos_game"
))
}
#[test]
pub fn has_entry_main_vs() {
assert!(has_entry_point(ExecutionModel::Vertex, "main_vs"))
pub fn has_entry_main_image_render() {
assert!(has_entry_point(
ExecutionModel::GLCompute,
"main_image_render"
))
}
}
+10 -2
View File
@@ -10,6 +10,14 @@ repository.workspace = true
workspace = true
[dependencies]
spirv-std.workspace = true
glam.workspace = true
bytemuck.workspace = true
glam.workspace = true
libm.workspace = true
rand.workspace = true
rand_xoshiro.workspace = true
spirv-std.workspace = true
[dev-dependencies]
anyhow.workspace = true
image.workspace = true
tempfile.workspace = true
+110
View File
@@ -0,0 +1,110 @@
use anyhow::{Context, Result};
use enkou_shaders::Coefficients2;
use enkou_shaders::camera::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, UVec2, Vec2, Vec2Swizzles, Vec4, uvec2, vec2};
use image::{Rgba, RgbaImage};
use std::mem;
use std::process::Command;
use tempfile::NamedTempFile;
const ITERATIONS_DISCARD: u32 = 20;
const ITERATIONS: u32 = 50_000;
const IMAGE_DIMENSION: UVec2 = uvec2(600, 600);
pub fn main() -> Result<()> {
let transforms = [
// F_0: (x / 2, y / 2)
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),
),
];
let weights = [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0];
let variations = [Variation::IDENTITY];
let mut output_points_ifs = Vec::new();
output_points_ifs.resize(ITERATIONS as usize, Vec4::ZERO);
main_chaos_game(
ITERATIONS_DISCARD,
&[4u8; 32],
&transforms,
&weights,
&variations,
&mut output_points_ifs,
);
// The gasket is defined on the range [0, 1] for both X and Y
let camera = Camera::new(
IMAGE_DIMENSION,
Vec2::ONE * 0.5,
0.0,
Vec2::ZERO,
IMAGE_DIMENSION.as_vec2(),
);
let palette = &[Vec4::ONE; 2];
let mut output_points_pixel = Vec::new();
output_points_pixel.resize(IMAGE_DIMENSION.xy().element_product() as usize, Vec4::ZERO);
main_image_render(
&camera,
palette,
&output_points_ifs,
&mut output_points_pixel,
);
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()));
}
}
let temp = NamedTempFile::with_suffix(".png").context("Unable to create file for image")?;
image.save(temp.path()).context("Unable to save image")?;
let open_program: &str = cfg_select! {
unix => Some("xdg-open"),
_ => None,
}
.expect("No available program to open images");
Command::new(open_program)
.arg(temp.path())
.spawn()?
.wait()?;
// In case the image viewer forks and gives control back prior to reading the file,
// drop it and don't run the destructor
mem::forget(temp);
Ok(())
}
+303
View File
@@ -0,0 +1,303 @@
//! # Camera
//!
//! 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, log10f, 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 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[index_lower].lerp(palette[index_upper], rem),
BlendMode::Step => 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.
///
/// The camera is itself an affine transformation, capable of zoom, rotation, and translation
/// of the IFS coordinates before rendering to the final image.
#[derive(Copy, Clone, Pod, Zeroable)]
#[repr(C)]
pub struct Camera {
dimensions: UVec2,
transform: Affine2,
blend_mode: BlendMode,
image_gamma: f32,
}
impl Camera {
/// Construct a new camera for translating IFS coordinates to pixel coordinates.
///
/// While the camera is implemented as a single affine transformation, it's helpful
/// to express the transform steps individually.
///
/// # Arguments
///
/// * `dimensions` - Width and height of the output image (in pixels).
/// * `center` - Location of the origin in IFS coordinates. Positive `x` shifts the image
/// left, and positive `y` position shifts the image up.
/// * `rotate` - Rotation angle (in radians) of IFS coordinates. Rotation is applied after the
/// `center` translation, so it is about the new origin.
/// * `zoom` - Zoom factor applied to IFS coordinates. IFS coordinates are scaled by
/// `pow(2, zoom)`, so a zoom factor of 0 is the identity.
/// * `scale` - Pixels per unit of IFS coordinates. This parameter is usually chosen such
/// that the largest dimension will cover the range `[-2, 2]`, but values higher or lower
/// can be used as a secondary zoom.
pub fn new(dimensions: UVec2, center: Vec2, rotate: f32, zoom: Vec2, scale: Vec2) -> Camera {
let ifs_center_transform = Affine2::from_translation(-center);
let zoom_transform = Affine2::from_scale(vec2(powf(2.0, zoom.x), powf(2.0, zoom.y)));
let scale_transform = Affine2::from_scale(scale);
let rotate_transform = Affine2::from_angle(rotate);
let image_center_transform = Affine2::from_translation((dimensions / 2).as_vec2());
let transform = image_center_transform
* rotate_transform
* scale_transform
* zoom_transform
* ifs_center_transform;
Camera {
dimensions,
transform,
blend_mode: BlendMode::Linear,
image_gamma: 1.5,
}
}
fn transform_point(&self, point: Vec2) -> IVec2 {
self.transform.transform_point2(point).as_ivec2()
}
/// 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_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
|| (pixel_coordinates.x as u32) >= self.dimensions.x
|| (pixel_coordinates.y as u32) >= self.dimensions.y
{
return None;
}
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 spirv_std::spirv;
/// 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)] image: &mut [Vec4],
) {
for coordinate_index in 0..coordinates_ifs.len() {
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() {
let rgba = camera.transform_image_hist_to_rgba(image[pixel_index]);
image[pixel_index] = rgba;
}
}
}
#[cfg(test)]
mod test {
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 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)
let center = vec2(-1.0, -1.0);
let point = starting_point - center;
// Rotate about the new origin; points move counter-clockwise, giving us (-2.0, 2.0)
let rotate = 90.0f32.to_radians();
let point = Affine2::from_angle(rotate).transform_point2(point);
// Zoom in by a factor of 1; points will be twice as far from the origin,
// giving us (-4.0, 4.0)
let zoom = vec2(1.0, 1.0);
let point = point * vec2(powf(2.0, zoom.x), powf(2.0, zoom.y));
// Apply scaling; scale 100 in a 1000 x 1000 image is an effective range
// of [-5, 5] in IFS coordinates.
// After scaling, the point is (-400.0, 400.0)
let scale = vec2(100.0, 100.0);
let point = point * scale;
// Move the origin from (0, 0) to image center,
// giving us (100.0, 900.0)
let dimensions = uvec2(1000, 1000);
let point = point.as_ivec2() + dimensions.as_ivec2() / 2;
// Check that the camera implementation ends up at the same point
let camera = Camera::new(dimensions, center, rotate, zoom, scale);
// The camera is implemented by composing affine transforms,
// which ends up with a slightly different result because of rounding.
let error = camera.transform_point(starting_point) - point;
assert!(error.x.abs() <= 1);
assert!(error.y.abs() <= 1);
}
#[test]
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),
Vec2::ZERO,
0.0,
Vec2::ZERO,
vec2(250.0, 250.0),
);
// Converting a point outside the effective range is legal, but outside the image bounds
assert_eq!(camera.transform_point(vec2(3.0, 3.0)), ivec2(1250, 1250));
}
#[test]
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),
Vec2::ZERO,
0.0,
Vec2::ZERO,
vec2(250.0, 250.0),
);
// Converting a point outside the effective range is legal, but outside the image bounds
assert_eq!(camera.transform_point(vec2(-3.0, -3.0)), ivec2(-250, -250));
}
#[test]
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(
uvec2(1600, 900),
Vec2::ZERO,
0.0,
Vec2::ZERO,
vec2(100.0, 100.0),
);
// This point is inside the image width, but outside its height
assert_eq!(camera.transform_point(vec2(6.0, 6.0)), ivec2(1400, 1050));
}
}
+158
View File
@@ -0,0 +1,158 @@
//! # Chaos Game
//!
//! Fractal flames are a class of
//! [iterated function systems](https://en.wikipedia.org/wiki/Iterated_function_system)
//! that generate images following a simple algorithm:
//!
//! - Pick a starting point `(x, y)`
//! - Iterate:
//! - Pick a [`Transform`] from the set of available transforms
//! - Apply the current point to the chosen transform, generating a new point `(x, y)`
//! - Plot the new point `(x, y)`
//!
//! 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};
use rand::{Rng, RngExt};
use spirv_std::glam::{Vec2, vec2};
struct BiUnit;
impl Distribution<f32> for BiUnit {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f32 {
rng.sample::<f32, _>(StandardUniform) * 2.0 - 1.0
}
}
/// Iterate one step in the chaos game; choose the next transform, apply it,
/// and return the resulting point. Also returns the transform index so that
/// path-dependent weights (the "Xaos" table in Apophysis) can be chosen
/// for the next iteration step.
///
/// # Arguments
///
/// * `weights` - Weights are assumed to be normalized; adding all elements together should return the value 1
pub fn step_chaos_game<R: Rng>(
point: Vec2,
color: f32,
rng: &mut R,
transforms: &[Transform],
weights: &[f32],
variations: &[Variation],
) -> (Vec2, f32, usize) {
let mut choice_weight = rng.sample::<f32, _>(StandardUniform);
let mut transform_index: usize = 0;
for i in 0..weights.len() {
choice_weight -= weights[i];
if choice_weight <= 0.0 {
break;
}
transform_index += 1;
}
let ref transform = transforms[transform_index];
(
transform.transform_point(rng, variations, point),
transform.transform_color(color),
transform_index,
)
}
/// Iterator for chaos game state. Holds the current point and references to all other data
/// necessary to generate fractal flame images.
///
/// 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],
variations: &'a [Variation],
}
impl<'a, R: Rng> ChaosGame<'a, R> {
/// Create a new chaos game iterator
pub fn new(
rng: &'a mut R,
transforms: &'a [Transform],
weights: &'a [f32],
variations: &'a [Variation],
) -> Self {
ChaosGame {
current_point: vec2(rng.sample(BiUnit), rng.sample(BiUnit)),
current_color: rng.sample(StandardUniform),
rng,
transforms,
weights,
variations,
}
}
}
impl<'a, R: Rng> Iterator for ChaosGame<'a, R> {
type Item = (Vec2, f32);
fn next(&mut self) -> Option<Self::Item> {
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, next_color))
}
}
/// Shader entry point for running the chaos game to produce new IFS coordinates
pub mod entry {
use crate::chaos_game::ChaosGame;
use crate::rng::xoshiro256starstar_from_seed;
use crate::transform::Transform;
use crate::variation::Variation;
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,
#[spirv(storage_buffer, descriptor_set = 0, binding = 0)] rng_seed: &[u8],
#[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 [Vec4],
) {
let mut rng_seed_actual = [0u8; 32];
(0..32).for_each(|i| rng_seed_actual[i] = rng_seed[i]);
let mut rng = xoshiro256starstar_from_seed(rng_seed_actual);
let mut chaos_game = ChaosGame::new(&mut rng, transforms, weights, variations);
for _ in 0..iteration_discard {
chaos_game.next().unwrap();
}
for i in 0..output.len() {
output[i] = chaos_game
.next()
.map(|output| (output.0, 0.0, output.1).into())
.unwrap();
}
}
}
+101 -28
View File
@@ -1,36 +1,109 @@
//! # Enkou
#![no_std]
#![warn(missing_docs)]
use bytemuck::{Pod, Zeroable};
use core::f32::consts::PI;
use glam::{Vec3, Vec4, vec2, vec3};
#[cfg(target_arch = "spirv")]
use spirv_std::num_traits::Float;
use spirv_std::spirv;
pub mod camera;
pub mod chaos_game;
mod rng;
pub mod transform;
pub mod variation;
#[derive(Copy, Clone, Pod, Zeroable)]
#[repr(C)]
pub struct ShaderConstants {
pub width: u32,
pub height: u32,
pub time: f32,
use glam::Affine2;
/// Utility trait to convert between `flam3` notation and [`glam`].
#[allow(missing_docs)]
pub trait Coefficients2 {
/// Convert affine transformation coefficients to the [`glam`] representation.
/// Parameters use the following form:
///
/// ```text
/// (a * x + b * y + c, d * x + e * y + f)
/// ```
///
/// ```
/// # use glam::{Affine2, vec2};
/// # use crate::enkou_shaders::Coefficients2;
/// let coefs = Affine2::from_coefficients(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
/// let (x, y) = (7.0, 8.0);
/// assert_eq!(
/// coefs.transform_point2(vec2(x, y)),
/// vec2(
/// coefs.a() * x + coefs.b() * y + coefs.c(),
/// coefs.d() * x + coefs.e() * y + coefs.f()
/// )
/// );
/// ```
fn from_coefficients(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Affine2;
/// Convert affine transformation coefficients to the [`glam`] representation.
/// Parameters use the following form:
///
/// ```text
/// (a * x + b * y + c, d * x + e * y + f)
/// ```
///
/// ```
/// # use glam::{Affine2, vec2};
/// # use crate::enkou_shaders::Coefficients2;
/// let coefs = Affine2::from_coefficients_arr([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
/// let (x, y) = (7.0, 8.0);
/// assert_eq!(
/// coefs.transform_point2(vec2(x, y)),
/// vec2(
/// coefs.a() * x + coefs.b() * y + coefs.c(),
/// coefs.d() * x + coefs.e() * y + coefs.f()
/// )
/// );
/// ```
fn from_coefficients_arr(coefficients: [f32; 6]) -> Affine2;
fn a(&self) -> f32;
fn b(&self) -> f32;
fn c(&self) -> f32;
fn d(&self) -> f32;
fn e(&self) -> f32;
fn f(&self) -> f32;
}
#[spirv(fragment)]
pub fn main_fs(vtx_color: Vec3, output: &mut Vec4) {
*output = Vec4::from((vtx_color, 1.));
}
impl Coefficients2 for Affine2 {
#[inline]
fn from_coefficients(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Affine2 {
Affine2::from_cols_array(&[a, d, b, e, c, f])
}
#[spirv(vertex)]
pub fn main_vs(
#[spirv(vertex_index)] vert_id: i32,
#[spirv(descriptor_set = 0, binding = 0, storage_buffer)] constants: &ShaderConstants,
#[spirv(position)] vtx_pos: &mut Vec4,
vtx_color: &mut Vec3,
) {
let speed = 0.4;
let time = constants.time * speed + vert_id as f32 * (2. * PI * 120. / 360.);
let position = vec2(f32::sin(time), f32::cos(time));
*vtx_pos = Vec4::from((position, 0.0, 1.0));
#[inline]
fn from_coefficients_arr(coefficients: [f32; 6]) -> Affine2 {
Affine2::from_coefficients(
coefficients[0],
coefficients[1],
coefficients[2],
coefficients[3],
coefficients[4],
coefficients[5],
)
}
*vtx_color = [vec3(1., 0., 0.), vec3(0., 1., 0.), vec3(0., 0., 1.)][vert_id as usize % 3];
fn a(&self) -> f32 {
self.matrix2.x_axis.x
}
fn b(&self) -> f32 {
self.matrix2.y_axis.x
}
fn c(&self) -> f32 {
self.translation.x
}
fn d(&self) -> f32 {
self.matrix2.x_axis.y
}
fn e(&self) -> f32 {
self.matrix2.y_axis.y
}
fn f(&self) -> f32 {
self.translation.y
}
}
+55
View File
@@ -0,0 +1,55 @@
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256StarStar;
/// Convert an RNG state buffer to an instance of [`Xoshiro256StarStar`].
///
/// While [`SeedableRng::from_seed`] is an infallible function,
/// it relies on some methods that can't be compiled by the SPIR-V
/// backend (specifically, formatting functions in the core crate).
///
/// In practice, the xoshiro RNG state is entirely defined by its seed,
/// so this function does the work of [`SeedableRng::from_seed`] by
/// transmuting the seed value to an RNG instance.
///
/// This function assumes a properly-initialized state array;
/// output may silently degenerate if the initial state is all zeros,
/// so this module is private to the crate.
pub(crate) fn xoshiro256starstar_from_seed(
rng_state: <Xoshiro256StarStar as SeedableRng>::Seed,
) -> Xoshiro256StarStar {
let mut rng_state_actual = [0u64; 4];
// 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() {
for j in 0..size_of::<u64>() {
rng_state_actual[i] |= (rng_state[i * size_of::<u64>() + j] as u64) << j * 8;
}
}
unsafe { core::mem::transmute(rng_state_actual) }
}
#[cfg(test)]
mod test {
use crate::rng::xoshiro256starstar_from_seed;
use core::iter::zip;
use rand::{RngExt, SeedableRng};
use rand_xoshiro::Xoshiro256StarStar;
#[test]
fn match_seeded() {
let mut seed: <Xoshiro256StarStar as SeedableRng>::Seed = [0u8; 32];
for i in 0..seed.len() {
seed[i] = i as u8;
}
let rng1 = Xoshiro256StarStar::from_seed(seed).random_iter::<u64>();
let rng2 = xoshiro256starstar_from_seed(seed).random_iter::<u64>();
zip(rng1, rng2)
.take(100)
.for_each(|(rng1_value, rng2_value)| assert_eq!(rng1_value, rng2_value));
}
}
+156
View File
@@ -0,0 +1,156 @@
//! # Transform
//!
//! Transforms are the "functions" in an iterated function system. They take in a point,
//! and generate a new point. For fractal flames, transforms are always affine,
//! but produce more interesting images once we add variations.
use crate::variation::Variation;
use bytemuck::{Pod, Zeroable};
use glam::{Affine2, FloatExt, UVec2, Vec2};
use rand::Rng;
/// Affine transform for use in the [`chaos_game`](crate::chaos_game).
#[derive(Copy, Clone, Pod, Zeroable)]
#[repr(C)]
pub struct Transform {
coefficients: Affine2,
variation_range: UVec2,
color: Vec2,
}
impl Transform {
/// Create a new transform from an affine transformation matrix
///
/// 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,
}
}
/// Apply this transform to a point in IFS coordinates, producing a new point
pub fn transform_point<R: Rng>(
&self,
rng: &mut R,
variations: &[Variation],
point: Vec2,
) -> Vec2 {
let point = self.coefficients.transform_point2(point);
let mut point_output = Vec2::ZERO;
let variation_start = self.variation_range.x;
let variation_end = self.variation_range.y;
for variation_index in variation_start..variation_end {
let ref variation = variations[variation_index as usize];
point_output += variation.transform_point(point, rng, &self.coefficients)
}
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<u32, Self::Error> {
Ok(0)
}
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
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);
}
}
+132
View File
@@ -0,0 +1,132 @@
//! # Variation
//!
//! Variations extend the fractal flame iterated function system
//! with non-linear transforms (as opposed to [`Transform`]s,
//! which are strictly affine transformations).
use crate::Coefficients2;
use bytemuck::{Pod, Zeroable};
use core::f32::consts::PI;
use glam::{Affine2, Vec2, vec2};
use libm::{atan2f, cosf, powf, sinf, sqrtf, tanf};
use rand::distr::StandardUniform;
use rand::{Rng, RngExt};
/// Generic variation parameters
///
/// Not all variations will use these parameters, but passing them
/// as an array per variation allows shaders to use a consistent struct size
/// no matter what the variation actually needs.
#[derive(Copy, Clone, Pod, Zeroable)]
#[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`
#[derive(Copy, Clone)]
#[repr(u32)]
#[allow(missing_docs)]
pub enum VariationKind {
/// Identity variation, returns the point as-is
Linear = 0,
Julia = 13,
Popcorn = 17,
Pdj = 24,
}
// UNSAFE: Sound because enum has guaranteed layout (u32) and defined zero-value
unsafe impl bytemuck::Zeroable for VariationKind {}
// UNSAFE: Sound because enum has guaranteed layout (u32) and defined zero-value
unsafe impl bytemuck::Pod for VariationKind {}
/// Parameters required for shaders to run the variation function.
///
/// Not all variations use the [`VariationParams`], but using the struct
/// makes it easy to provide parameters to the shader.
#[derive(Copy, Clone, Pod, Zeroable)]
#[repr(C)]
pub struct Variation {
kind: VariationKind,
weight: f32,
params: VariationParams,
}
impl Variation {
/// Identity variation; calling [`transform_point`] will yield
/// the same point as the input.
pub const IDENTITY: Variation = Variation {
kind: VariationKind::Linear,
weight: 1.0,
params: VariationParams([0f32; 4]),
};
/// Create a new variation by providing the variation kind, weight, and parameters.
pub fn new(kind: VariationKind, weight: f32, params: VariationParams) -> Variation {
Variation {
kind,
weight,
params,
}
}
/// Transform a point by applying this variation.
///
/// Output points are scaled by this variation's weight.
pub fn transform_point<R: Rng>(
&self,
point: Vec2,
rng: &mut R,
coefficients: &Affine2,
) -> Vec2 {
(match self.kind {
VariationKind::Linear => transform_point_linear(point),
VariationKind::Julia => transform_point_julia(point, rng),
VariationKind::Popcorn => transform_point_popcorn(point, coefficients),
VariationKind::Pdj => transform_point_pdj(point, &self.params),
}) * self.weight
}
}
fn transform_point_linear(point: Vec2) -> Vec2 {
point
}
fn transform_point_julia<R: Rng>(point: Vec2, rng: &mut R) -> Vec2 {
let x2 = powf(point.x, 2.0);
let y2 = powf(point.y, 2.0);
let r = sqrtf(x2 + y2);
let theta = atan2f(point.x, point.y);
let omega = if rng.sample::<f32, _>(StandardUniform) > 0.5 {
PI
} else {
0.0
};
let sqrt_r = sqrtf(r);
let theta_val = theta / 2.0 + omega;
vec2(sqrt_r * cosf(theta_val), sqrt_r * sinf(theta_val))
}
fn transform_point_popcorn(point: Vec2, coefficients: &Affine2) -> Vec2 {
vec2(
point.x * coefficients.c() * sinf(tanf(3.0 * point.y)),
point.y + coefficients.f() * sinf(tanf(3.0 * point.x)),
)
}
fn transform_point_pdj(point: Vec2, params: &VariationParams) -> Vec2 {
let (pdj_a, pdj_b, pdj_c, pdj_d) = (params.0[0], params.0[1], params.0[2], params.0[3]);
vec2(
sinf(pdj_a * point.y) - cosf(pdj_b * point.x),
sinf(pdj_c * point.x) - cosf(pdj_d * point.y),
)
}