1 Commits

Author SHA1 Message Date
bspeice 53d5ad1422 First attempt at a GPU runner
CI / cargo fmt (push) Failing after 1m5s
CI / cargo test (push) Failing after 2m15s
CI / cargo test (GPU) (push) Successful in 16m58s
Currently failing with an error I don't understand:

```
wgpu error: Validation Error

Caused by:
  In Device::create_shader_module, label = '...\image_binary.spv'

Shader '...\image_binary.spv' parsing error: InvalidTypeWidth(1)
```
2026-07-29 11:12:52 -04:00
17 changed files with 2240 additions and 383 deletions
Generated
+1716 -30
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -1,6 +1,8 @@
[workspace]
members = [
"enkou-shaders",
"examples/image-runner",
"examples/image-binary",
]
resolver = "3"
@@ -21,9 +23,14 @@ spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "67f1ff2"
anyhow = "1.0.102"
bytemuck = { version = "1.25.0", features = ["derive"] }
futures = "0.3.32"
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"
thiserror = "2.0.19"
wgpu = { version = "30.0.0", features = ["spirv"] }
xflags = "0.3.2"
-5
View File
@@ -16,8 +16,3 @@ 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
-106
View File
@@ -1,106 +0,0 @@
//! # Fractal flame
//!
//! The `flam3` sources include example parameters (`test.flam3`) to demonstrate the fractal flame algorithm,
//! which are copied here and used to generate an image that can be compared against the reference `flam3` renderer
use anyhow::Result;
use enkou_shaders::chaos_game::ChaosGame;
use enkou_shaders::transform::Transform;
use enkou_shaders::variation::{Variation, VariationKind};
use glam::{UVec2, UVec3, UVec4, Vec2, Vec2Swizzles, Vec4};
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256StarStar;
use enkou_shaders::camera::Camera;
use enkou_shaders::image::BlendMode;
const ITERATIONS_DISCARD: usize = 100;
const IMAGE_DIMENSIONS: UVec2 = UVec2::new(640, 480);
const IMAGE_QUALITY: f32 = 10.0;
// Palette data copied from `flam3-palettes.xml`.
// Palettes are ASCII hexadecimal strings; two characters form a byte,
// and bytes are grouped in triplets to get a single RGB color.
const PALETTE: &'static str = "\
00dadebc00eee6c500eef2ce00eef2cf00e6eee100eaeed800f2f1eb00f2f5d8
00e6f2ce00deeac500d6dac600ced2bc00c2caa900becaa000ced6aa00dee2c5
00eaedce00eaf2c500dee2c500c2caaa00aebeaa00a5b29600a2a98d0096a284
008d8d7a0085897100858d710085856700797d6700797d670071795e00656d55
004d5d4200344025003040250030381c002c3c1c002c341c00242c1200242400
00242c0900283409003840120030401c0040502f0055694200657555006c7d5e
00748d710074898400748d8400788d840079897a0079857100757d670071795e
006c715e006d705e006c795e0068755e00697155006d7555006d755500697155
0065715500696d550064715e006870670068706700686c67006c6c5e0071715e
0079796700818571007d91710085927a0085927a007d9284007992840078928d
00788d8d00748d84007492840075927a006c85670064795e0059694b00aa5700
0038441c00303c1c002c3c1c003440250050614b005d6d5e0064715e0060715e
0060755e0068755e006c795e006c795e0071796700707967006c7d6700687967
006c7967006c75670071755e0071755e0075795e00757d5e00818d5e008d925e
008d9267009a9a71009aa27a009aa27a009aa17a00929a71008992670081855e
007d7d550069794b00616d4200444c250038441c0040512500454d2500716d42
00797d4b00817d5500797955006d755500697d55006c795e006579540068795e
00647967006479670068755e0064715e00646c5e00656d55004d584200344025
002c381c0020281c001c1409001818000004140000081000000c1800001c2809
00243012003c4425005d6555007579550085895e008991710096a271009aa27a
009eaa7a009eaa7a00aaae7100a6aa7a00a2aa7a00a1a57a00969e7a0085967a
0081927a0078927a0075927a00758d7a00708167007d7d670089896700929a71
009eaa7a00aab68400b2b68d00b6ba9700c2ca9700b2be8d00b2b68d00aab28d
00a2ae84009aa67a00929e7a00859a7a007d967a007d927a007d9284007d9284
0081968400859684008596840081928400859a8400859a84008d9a8400929684
009ea98400aeb28400aaba8400b2be8d00b6c2a000c6caa000c6ceaa00d6dab3
00dae2c500d2d6bc00bec2a000aab68d009ea67a00929a710089897100817d67
007d7d6700817867007d7d5e0079795e0079815e00817d6700817d6700818167
008189710085917a0089927a00969d7a00969e7a0092968400969a8d00929284
0089918400819284007d928d0078928d0074928d0078928d007896970081968d
0081968d00819a8d00859a8d00899e8d00899e8d008da2970095a297008da297
0096a68d009aa18d009ea984009ea67a00a2a571009ea671009aa67100959d71";
/// Generate an image
pub fn main() -> Result<()> {
let transforms: &[Transform] = &[];
let weights = [0.25; 4];
let variations = [Variation::new(
VariationKind::Spherical,
1.0,
[0.0; 4].into(),
)];
let camera = Camera::new(IMAGE_DIMENSIONS, Vec2::ZERO, 0.0, Vec2::ZERO, (IMAGE_DIMENSIONS / 2).as_vec2());
let palette_chars: String = PALETTE.chars().filter(|c| c.is_alphanumeric()).collect();
let palette_bytes: Vec<u8> = (0..palette_chars.len())
.step_by(2)
.map(|i| {
let s = &palette_chars[i..i + 2];
let b = u8::from_str_radix(s, 16).expect("illegal palette value");
b
})
.collect();
let palette_colors: Vec<Vec4> = palette_bytes
.chunks(3)
.map(|chunk| [chunk[0] as f32, chunk[1] as f32, chunk[2] as f32, 255.0].into())
.collect();
let mut rng = Xoshiro256StarStar::from_seed([4u8; 32]);
let chaos_game = ChaosGame::new(&mut rng, transforms, &weights, &variations);
let mut image_accum: Vec<Vec4> = Vec::new();
image_accum.resize(IMAGE_DIMENSIONS.element_product() as usize, Vec4::ZERO);
let iterations: usize = (IMAGE_DIMENSIONS.element_product() as f32 * IMAGE_QUALITY) as usize;
chaos_game.skip(ITERATIONS_DISCARD).take(iterations).for_each(|(ifs_point, ifs_color)| {
let pixel_point = camera.transform_point_to_image(ifs_point);
if pixel_point.is_none() {
return;
}
let pixel_point = pixel_point.unwrap();
let pixel_index = pixel_point.y * IMAGE_DIMENSIONS.x + pixel_point.x;
let pixel_color = BlendMode::Linear.ifs_to_rgb(ifs_color, palette_colors.as_ref());
image_accum[pixel_index as usize] += pixel_color;
});
Ok(())
}
-86
View File
@@ -1,86 +0,0 @@
//! # Sierpinski Gasket
//!
//! The Sierpinski Gasket is a simple iterated function system (IFS) that demonstrates
//! the basic principles of using the "chaos game" to generate images. Using a set of three
//! transforms, generate new points in the function system using the chaos game,
//! then plot those points and display the resulting image.
use anyhow::{Context, Result};
use enkou_shaders::Coefficients2;
use enkou_shaders::camera::Camera;
use enkou_shaders::chaos_game::ChaosGame;
use enkou_shaders::transform::Transform;
use enkou_shaders::variation::Variation;
use glam::{Affine2, UVec2, Vec2, uvec2};
use image::{GrayImage, Luma};
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256StarStar;
use std::mem;
use std::process::Command;
use tempfile::NamedTempFile;
const ITERATIONS_DISCARD: usize = 20;
const IMAGE_DIMENSION: UVec2 = uvec2(600, 600);
const IMAGE_QUALITY: f32 = 1.0;
/// Build and display a simple fractal - the Sierpinski Gasket
pub fn main() -> Result<()> {
let mut rng = Xoshiro256StarStar::from_seed([4u8; 32]);
let transforms = [
{
// F_0: (x / 2, y / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.0);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1), 0.0, 0.5)
},
{
// F_1: ((x + 1) / 2, y / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.5, 0.0, 0.5, 0.0);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1), 0.5, 0.5)
},
{
// F_2: (x / 2, (y + 1) / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.5);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1), 1.0, 0.5)
},
];
let weights = [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0];
let variations = [Variation::IDENTITY];
// 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 mut image = GrayImage::new(IMAGE_DIMENSION.x, IMAGE_DIMENSION.y);
let chaos_game = ChaosGame::new(&mut rng, &transforms, &weights, &variations);
let iterations = (IMAGE_DIMENSION.element_product() as f32 * IMAGE_QUALITY) as usize;
chaos_game
.skip(ITERATIONS_DISCARD)
.take(iterations)
.for_each(|(ifs_point, _)| {
if let Some(pixel_point) = camera.transform_point_to_image(ifs_point) {
image.put_pixel(pixel_point.x, pixel_point.y, Luma([255u8]));
}
});
let temp = NamedTempFile::with_suffix(".png").context("Unable to create file for image")?;
image.save(temp.path()).context("Unable to save image")?;
let mut command = cfg_select! {
unix => Command::new("xdg-open").arg(temp.path()).spawn(),
windows => Command::new("PowerShell").arg("-Command").arg(format!("start {}", temp.path().display())).spawn(),
_ => Err(anyhow::anyhow!("No available program to open images"))?
}?;
command.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(())
}
+6 -13
View File
@@ -36,12 +36,11 @@ impl Distribution<f32> for BiUnit {
/// * `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) {
) -> (Vec2, u32) {
let mut choice_weight = rng.sample::<f32, _>(StandardUniform);
let mut transform_index: u32 = 0;
@@ -54,10 +53,9 @@ pub fn step_chaos_game<R: Rng>(
transform_index += 1;
}
let transform = &transforms[transform_index as usize];
(
transform.transform_point(rng, variations, point),
transform.transform_color(color),
transforms[transform_index as usize].transform_point(rng, variations, point),
transform_index,
)
}
@@ -67,7 +65,6 @@ pub fn step_chaos_game<R: Rng>(
/// 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],
@@ -83,10 +80,8 @@ impl<'a, R: Rng> ChaosGame<'a, R> {
variations: &'a [Variation],
) -> Self {
let current_point = vec2(rng.sample(BiUnit), rng.sample(BiUnit));
let current_color = rng.sample(StandardUniform);
ChaosGame {
current_point,
current_color,
rng,
transforms,
weights,
@@ -96,20 +91,18 @@ impl<'a, R: Rng> ChaosGame<'a, R> {
}
impl<'a, R: Rng> Iterator for ChaosGame<'a, R> {
type Item = (Vec2, f32);
type Item = Vec2;
fn next(&mut self) -> Option<Self::Item> {
let (next_point, next_color) = step_chaos_game(
let (next_point, _) = 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))
Some(next_point)
}
}
-84
View File
@@ -1,84 +0,0 @@
//! Image
use glam::Vec4;
use libm::floorf;
/// Blending modes for mapping IFS color values (which are on a scale `[0, 1]`)
/// to RGBA colors.
#[derive(Copy, Clone, Default)]
#[repr(u32)]
pub enum BlendMode {
/// Map IFS color values to a linear blend of the nearest two palette colors
#[default]
Linear = 0,
/// Map IFS color values to the nearest single palette color
Step = 1,
}
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 {}
#[cfg(test)]
mod test {
use crate::image::BlendMode;
use glam::Vec4;
#[test]
fn blend_linear() {
let ifs_to_rgb = |color, palette| BlendMode::Linear.ifs_to_rgb(color, palette);
let palette = &[Vec4::splat(0.0), Vec4::splat(1.0)];
assert_eq!(ifs_to_rgb(0.0, palette), Vec4::splat(0.0));
assert_eq!(ifs_to_rgb(0.5, palette), Vec4::splat(0.5));
assert_eq!(ifs_to_rgb(1.0, palette), Vec4::splat(1.0));
let palette = &[Vec4::splat(1.0), Vec4::splat(2.0), Vec4::splat(3.0)];
assert_eq!(ifs_to_rgb(0.0, palette), Vec4::splat(1.0));
assert_eq!(ifs_to_rgb(0.5, palette), Vec4::splat(2.0));
assert_eq!(ifs_to_rgb(1.0, palette), Vec4::splat(3.0));
let palette = &[
Vec4::splat(1.0),
Vec4::splat(2.0),
Vec4::splat(3.0),
Vec4::splat(4.0),
];
assert_eq!(ifs_to_rgb(0.0, palette), Vec4::splat(1.0));
assert_eq!(ifs_to_rgb(0.5, palette), Vec4::splat(2.5));
assert_eq!(ifs_to_rgb(1.0, palette), Vec4::splat(4.0));
}
#[test]
fn blend_step() {
let ifs_to_rgb = |color, palette| BlendMode::Step.ifs_to_rgb(color, palette);
let palette = &[Vec4::splat(0.0), Vec4::splat(1.0)];
assert_eq!(ifs_to_rgb(0.5, palette), Vec4::splat(0.0));
let palette = &[Vec4::splat(1.0), Vec4::splat(2.0), Vec4::splat(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]);
}
}
+5 -3
View File
@@ -1,10 +1,12 @@
//! # Enkou
#![no_std]
#![allow(clippy::needless_range_loop)] // SPIR-V backend has issues with iteration over items
#![cfg_attr(target_arch = "spirv", no_std)]
// SPIR-V backend is unable to compile iteration over items
#![allow(clippy::needless_range_loop)]
pub mod camera;
pub mod chaos_game;
pub mod image;
pub mod rng;
pub mod transform;
pub mod variation;
+58
View File
@@ -0,0 +1,58 @@
//! # RNG
//!
//! Random number generation utilities for shaders
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 fn xoshiro256starstar_from_seed(
rng_state: <Xoshiro256StarStar as SeedableRng>::Seed,
) -> Xoshiro256StarStar {
let mut rng_state_actual = [0u64; 4];
// NOTE: Bit shifting is bad, 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));
}
}
+6 -47
View File
@@ -5,7 +5,7 @@
//! but produce more interesting images once we add variations.
use crate::variation::Variation;
use bytemuck::{Pod, Zeroable};
use glam::{Affine2, FloatExt, UVec2, Vec2};
use glam::{Affine2, UVec2, Vec2};
use rand::Rng;
/// Affine transform for use in the [`chaos_game`](crate::chaos_game).
@@ -15,25 +15,15 @@ pub struct Transform {
coefficients: Affine2,
coefficients_post: Affine2,
variation_range: UVec2,
color: f32,
color_speed: f32,
}
impl Transform {
/// Create a new transform from an affine transformation matrix
pub fn new(
coefficients: Affine2,
coefficients_post: Affine2,
variation_range: UVec2,
color: f32,
color_speed: f32,
) -> Self {
pub fn new(coefficients: Affine2, coefficients_post: Affine2, variation_range: UVec2) -> Self {
Transform {
coefficients,
coefficients_post,
variation_range,
color,
color_speed,
}
}
@@ -57,20 +47,14 @@ impl Transform {
self.coefficients_post.transform_point2(point)
}
/// Apply this transform to a color in IFS coordinates, producing a new color
pub fn transform_color(&self, color: f32) -> f32 {
self.color.lerp(color, self.color_speed)
}
}
#[cfg(test)]
mod test {
use crate::rng::xoshiro256starstar_from_seed;
use crate::transform::Transform;
use crate::variation::{Variation, VariationKind};
use glam::{Affine2, uvec2, vec2};
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256StarStar;
#[test]
fn transform_scaling() {
@@ -79,11 +63,9 @@ mod test {
Affine2::from_scale(scale_coefficients),
Affine2::IDENTITY,
uvec2(0, 1),
0.0,
0.0,
);
let mut rng = Xoshiro256StarStar::from_seed([0u8; 32]);
let mut rng = xoshiro256starstar_from_seed([0; 32]);
let variations = [Variation::IDENTITY];
let point = vec2(1.0, 1.0);
@@ -96,17 +78,14 @@ mod test {
#[test]
fn transform_scaling_post() {
let scale_coefficients = vec2(2.0, 0.5);
let transform_pdj =
Transform::new(Affine2::IDENTITY, Affine2::IDENTITY, uvec2(0, 1), 0.0, 0.0);
let transform_pdj = Transform::new(Affine2::IDENTITY, Affine2::IDENTITY, uvec2(0, 1));
let transform_pdj_post = Transform::new(
Affine2::IDENTITY,
Affine2::from_scale(scale_coefficients),
uvec2(0, 1),
0.0,
0.0,
);
let mut rng = Xoshiro256StarStar::from_seed([0; 32]);
let mut rng = xoshiro256starstar_from_seed([0; 32]);
let variations = [Variation::new(VariationKind::Pdj, 1.0, [0.0f32; 4].into())];
let point = vec2(1.0, 1.0);
@@ -115,24 +94,4 @@ mod test {
assert_eq!(point_pdj * scale_coefficients, point_pdj_post);
}
#[test]
fn transform_color() {
let starting_color = 0.0;
let transform_color = 1.0;
let transform_speed = 0.5;
let transform = Transform::new(
Affine2::IDENTITY,
Affine2::IDENTITY,
uvec2(0, 1),
starting_color,
transform_speed,
);
assert_eq!(
transform.transform_color(starting_color),
starting_color * (1.0 - transform_speed) + transform_color * transform_speed
);
}
}
+2 -9
View File
@@ -35,7 +35,7 @@ impl From<[f32; 4]> for VariationParams {
pub enum VariationKind {
/// Identity variation, returns the point as-is
Linear = 0,
Spherical = 2,
Julia = 13,
Popcorn = 17,
Pdj = 24,
@@ -68,7 +68,7 @@ impl Variation {
};
/// Create a new variation by providing the variation kind, weight, and parameters.
pub fn new(kind: VariationKind, weight: f32, params: VariationParams) -> Variation {
pub const fn new(kind: VariationKind, weight: f32, params: VariationParams) -> Variation {
Variation {
kind,
weight,
@@ -87,7 +87,6 @@ impl Variation {
) -> Vec2 {
(match self.kind {
VariationKind::Linear => transform_point_linear(point),
VariationKind::Spherical => transform_point_spherical(point),
VariationKind::Julia => transform_point_julia(point, rng),
VariationKind::Popcorn => transform_point_popcorn(point, coefficients),
VariationKind::Pdj => transform_point_pdj(point, &self.params),
@@ -99,12 +98,6 @@ fn transform_point_linear(point: Vec2) -> Vec2 {
point
}
fn transform_point_spherical(point: Vec2) -> Vec2 {
let r2 = (point * point).element_sum();
let r2_inv = 1.0 / r2;
point * Vec2::splat(r2_inv)
}
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);
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "image-binary"
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
enkou-shaders = { path = "../../enkou-shaders" }
glam.workspace = true
spirv-std.workspace = true
wgpu = { workspace = true, optional = true }
[lints]
workspace = true
+82
View File
@@ -0,0 +1,82 @@
//! # Binary image
#![cfg_attr(target_arch = "spirv", no_std)]
use enkou_shaders::camera::Camera;
use enkou_shaders::chaos_game::ChaosGame;
use enkou_shaders::rng::xoshiro256starstar_from_seed;
use enkou_shaders::transform::Transform;
use enkou_shaders::variation::Variation;
use glam::{UVec2, UVec4};
use spirv_std::spirv;
#[cfg(feature = "wgpu")]
pub use wgpu::*;
const IMAGE_QUALITY: f32 = 1.0;
const ITERATIONS_FUSE: u32 = 20;
/// Sierpinski Gasket
#[spirv(compute(entry_point_name = "main_image_binary", threads(1)))]
pub fn main_image_binary(
#[spirv(storage_buffer, descriptor_set = 0, binding = 0)] image_dimensions: &UVec2,
#[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 = 0, binding = 4)] camera: &Camera,
#[spirv(storage_buffer, descriptor_set = 0, binding = 5)] image_buffer: &mut [UVec4],
) {
// Initialize RNG and run the chaos game
let mut rng = xoshiro256starstar_from_seed([4; 32]);
let mut chaos_game = ChaosGame::new(&mut rng, transforms, weights, variations);
// Discard the first few iterations
for _ in 0..ITERATIONS_FUSE {
chaos_game.next().unwrap();
}
// Plot the remaining points generated by the chaos game
let iterations = (image_dimensions.as_vec2().element_product() * IMAGE_QUALITY) as u32;
for _ in 0..iterations {
let ifs_point = chaos_game.next().unwrap();
let pixel_point = camera.transform_point_to_image(ifs_point);
if let Some(pixel_point) = pixel_point {
let pixel_index = pixel_point.y * image_dimensions.x + pixel_point.x;
image_buffer[pixel_index as usize] = UVec4::splat(255);
}
}
}
#[cfg(feature = "wgpu")]
pub mod wgpu {
const fn bgle(binding: u32, read_only: bool) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}
}
pub const BGLE_IMAGE_DIMENSIONS: wgpu::BindGroupLayoutEntry = bgle(0, true);
pub const BGLE_TRANSFORMS: wgpu::BindGroupLayoutEntry = bgle(1, true);
pub const BGLE_WEIGHTS: wgpu::BindGroupLayoutEntry = bgle(2, true);
pub const BGLE_VARIATIONS: wgpu::BindGroupLayoutEntry = bgle(3, true);
pub const BGLE_CAMERA: wgpu::BindGroupLayoutEntry = bgle(4, true);
pub const BGLE_IMAGE_BUFFER: wgpu::BindGroupLayoutEntry = bgle(5, false);
pub const BIND_GROUP_IMAGE_BINARY: wgpu::BindGroupLayoutDescriptor = wgpu::BindGroupLayoutDescriptor {
label: Some("main_image_binary"),
entries: &[
BGLE_IMAGE_DIMENSIONS,
BGLE_TRANSFORMS,
BGLE_WEIGHTS,
BGLE_VARIATIONS,
BGLE_CAMERA,
BGLE_IMAGE_BUFFER,
],
};
}
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "image-runner"
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
enkou-shaders = { path = "../../enkou-shaders" }
image-binary = { path = "../image-binary", features = ["wgpu"] }
anyhow.workspace = true
bytemuck.workspace = true
futures.workspace = true
glam = { workspace = true, features = ["u8"] }
image.workspace = true
tempfile.workspace = true
wgpu.workspace = true
xflags.workspace = true
[build-dependencies]
anyhow.workspace = true
cargo-gpu-install.workspace = true
[lints]
workspace = true
+28
View File
@@ -0,0 +1,28 @@
use cargo_gpu_install::install::Install;
use cargo_gpu_install::spirv_builder::{Capability, ShaderPanicStrategy, SpirvMetadata};
use std::path::PathBuf;
pub fn main() -> anyhow::Result<()> {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let crate_path = [manifest_dir, "..", "image-binary"]
.iter()
.copied()
.collect::<PathBuf>();
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];
let compile_result = builder.build()?;
let spv_path = compile_result.module.unwrap_single();
println!(
"cargo::rustc-env=SHADER_SPV_PATH_IMAGE_BINARY={}",
spv_path.display()
);
Ok(())
}
+210
View File
@@ -0,0 +1,210 @@
use enkou_shaders::Coefficients2;
use enkou_shaders::transform::Transform;
use enkou_shaders::variation::Variation;
use futures::channel::oneshot;
use futures::executor::block_on;
use glam::{uvec2, Affine2, UVec2, UVec4, Vec2};
use image::{Rgba, RgbaImage};
use image_binary::{main_image_binary, BIND_GROUP_IMAGE_BINARY, BGLE_IMAGE_DIMENSIONS, BGLE_TRANSFORMS, BGLE_WEIGHTS, BGLE_CAMERA, BGLE_IMAGE_BUFFER, BGLE_VARIATIONS};
use std::path::Path;
use wgpu::util::DeviceExt;
use enkou_shaders::camera::Camera;
fn transforms() -> [Transform; 3] {
[
{
// F_0: (x / 2, y / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.0);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1))
},
{
// F_1: ((x + 1) / 2, y / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.5, 0.0, 0.5, 0.0);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1))
},
{
// F_2: (x / 2, (y + 1) / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.5);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1))
},
]
}
fn weights() -> [f32; 3] {
[1.0 / 3.0; 3]
}
fn variations() -> [Variation; 1] {
[Variation::IDENTITY]
}
fn camera(image_dimensions: UVec2) -> Camera {
Camera::new(
image_dimensions,
Vec2::ONE * 0.5,
0.0,
Vec2::ZERO,
Vec2::splat(image_dimensions.min_element() as f32),
)
}
pub(crate) fn main_cpu(image_dimensions: UVec2, output_path: &Path) -> Result<(), anyhow::Error> {
let mut image_buffer = Vec::<UVec4>::new();
image_buffer.resize(image_dimensions.element_product() as usize, UVec4::ZERO);
main_image_binary(
&image_dimensions,
&transforms(),
&weights(),
&variations(),
&camera(image_dimensions),
&mut image_buffer,
);
let mut image = RgbaImage::new(image_dimensions.x, image_dimensions.y);
for (i, color) in image_buffer.into_iter().enumerate() {
let image_x = i as u32 % image_dimensions.x;
let image_y = i as u32 / image_dimensions.x;
image.put_pixel(image_x, image_y, color.as_u8vec4().to_array().into());
}
image.save(output_path)?;
Ok(())
}
const SHADER_MODULE: wgpu::ShaderModuleDescriptor = wgpu::include_spirv!(env!("SHADER_SPV_PATH_IMAGE_BINARY"));
fn bge<'a>(entry: &'a wgpu::BindGroupLayoutEntry, buffer: &'a wgpu::Buffer) -> wgpu::BindGroupEntry<'a> {
wgpu::BindGroupEntry {
binding: entry.binding,
resource: buffer.as_entire_binding(),
}
}
pub(crate) fn main_gpu(device: &wgpu::Device, queue: &wgpu::Queue, image_dimensions: UVec2, output_path: &Path) -> Result<(), anyhow::Error> {
let bind_group_layout = device.create_bind_group_layout(&BIND_GROUP_IMAGE_BINARY);
let image_dimensions_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("image_dimensions"),
contents: bytemuck::bytes_of(&image_dimensions),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::STORAGE,
});
let transforms_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("transforms"),
contents: bytemuck::cast_slice(&transforms()),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::STORAGE,
});
let weights_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("weights"),
contents: bytemuck::cast_slice(&weights()),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::STORAGE,
});
let variations_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("variations"),
contents: bytemuck::cast_slice(&variations()),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::STORAGE,
});
let camera_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("camera"),
contents: bytemuck::bytes_of(&camera(image_dimensions)),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::STORAGE,
});
let image_buffer_elements = image_dimensions.element_product() as u64;
let image_buffer_size = image_buffer_elements * size_of::<UVec4>() as u64;
let image_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("image_buffer"),
size: image_buffer_size,
usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::STORAGE,
mapped_at_creation: false,
});
let image_staging = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("image_buffer_staging"),
size: image_buffer_size,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("main_image_binary"),
layout: &bind_group_layout,
entries: &[
bge(&BGLE_IMAGE_DIMENSIONS, &image_dimensions_buffer),
bge(&BGLE_TRANSFORMS, &transforms_buffer),
bge(&BGLE_WEIGHTS, &weights_buffer),
bge(&BGLE_VARIATIONS, &variations_buffer),
bge(&BGLE_CAMERA, &camera_buffer),
bge(&BGLE_IMAGE_BUFFER, &image_buffer),
],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("main_image_binary"),
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let module = device.create_shader_module(SHADER_MODULE);
let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("main_image_binary"),
layout: Some(&layout),
module: &module,
entry_point: Some("main_image_binary"),
compilation_options: Default::default(),
cache: None,
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("main_image_binary"),
});
{
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("main_image_binary"),
timestamp_writes: None,
});
compute_pass.set_pipeline(&compute_pipeline);
compute_pass.set_bind_group(0, &bind_group, &[]);
}
encoder.copy_buffer_to_buffer(&image_buffer, 0, &image_staging, 0, Some(image_buffer_size));
let (sender, receiver) = oneshot::channel();
let image_staging_capturable = image_staging.clone();
encoder.map_buffer_on_submit(&image_buffer, wgpu::MapMode::Read, .., move |result| {
result.expect("unable to map buffer");
let staging_buffer_view = image_staging_capturable.get_mapped_range(..).expect("Unable to map staging buffer");
let mut image = RgbaImage::new(image_dimensions.x, image_dimensions.y);
let image_buffer_elements = bytemuck::cast_slice::<u8, UVec4>(staging_buffer_view.as_ref());
for (i, element) in image_buffer_elements.iter().enumerate() {
let image_x = i as u32 % image_dimensions.x;
let image_y = i as u32 / image_dimensions.x;
let pixel_colors = element.as_u8vec4();
image.put_pixel(image_x, image_y, Rgba(*pixel_colors.as_ref()))
}
sender.send(image).expect("Unable to send image");
});
queue.submit(Some(encoder.finish()));
device.poll(wgpu::PollType::wait_indefinitely())?;
let image = block_on(receiver)?;
image_staging.unmap();
image.save(output_path)?;
Ok(())
}
+77
View File
@@ -0,0 +1,77 @@
use glam::{uvec2};
use std::mem;
use std::process::Command;
use std::path::PathBuf;
use futures::executor::block_on;
use tempfile::NamedTempFile;
mod image_binary;
fn main() -> Result<(), anyhow::Error> {
let instance_future = wgpu::util::new_instance_with_webgpu_detection(wgpu::InstanceDescriptor {
backends: Default::default(),
flags: Default::default(),
memory_budget_thresholds: Default::default(),
backend_options: Default::default(),
display: None,
});
let instance = block_on(instance_future);
let adapter_future = instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: Default::default(),
force_fallback_adapter: false,
compatible_surface: None,
apply_limit_buckets: false,
});
let adapter = block_on(adapter_future)?;
let device_future = adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("image-runner"),
required_features: Default::default(),
required_limits: Default::default(),
experimental_features: Default::default(),
memory_hints: Default::default(),
trace: Default::default(),
});
let (device, queue) = block_on(device_future)?;
let flags = xflags::parse_or_exit! {
/// Image dimensions to output, as `width,height`
optional -d, --dimensions dimensions: String
/// Output pathname to use
optional -o, --output output: PathBuf
/// Image type to generate
required image: String
};
let dimensions = if let Some(dimensions) = flags.dimensions {
let (width_str, height_str) = dimensions.split_once(",").ok_or(anyhow::anyhow!("Invalid format for image dimensions"))?;
uvec2(width_str.parse()?, height_str.parse()?)
} else {
uvec2(1600, 900)
};
let output = if let Some(output) = flags.output { output } else {
let path = NamedTempFile::with_suffix(".png")?;
let pathbuf: PathBuf = path.path().into();
mem::forget(path);
pathbuf
};
match flags.image.as_ref() {
"binary_cpu" => image_binary::main_cpu(dimensions, output.as_ref()),
"binary_gpu" => image_binary::main_gpu(&device, &queue, dimensions, output.as_ref()),
_ => Err(anyhow::anyhow!("Unrecognized image type"))
}?;
let mut command = cfg_select! {
unix => Command::new("xdg-open").arg(temp.path()).spawn(),
windows => Command::new("PowerShell").arg("-Command").arg(format!("start {}", output.display())).spawn(),
_ => Err(anyhow::anyhow!("No available program to open images"))?
}?;
command.wait()?;
Ok(())
}