5 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
bspeice 7ff19631ba Merge pull request 'Add clippy, fix up warnings' (#7) from clippy into main
CI / cargo fmt (push) Successful in 25s
CI / cargo test (push) Successful in 12m39s
CI / cargo test (GPU) (push) Successful in 16m24s
Reviewed-on: #7
2026-07-12 15:50:24 -04:00
bspeice 9ea4261a84 Add clippy, fix up warnings
CI / cargo fmt (push) Successful in 23s
CI / cargo test (push) Successful in 12m44s
CI / cargo test (GPU) (push) Successful in 16m32s
2026-07-12 14:46:06 -04:00
bspeice 81f23c1bd8 Merge pull request 'Implement post-transform coefficients' (#6) from post_transform into main
CI / cargo fmt (push) Successful in 27s
CI / cargo test (push) Successful in 12m43s
CI / cargo test (GPU) (push) Successful in 12m25s
Reviewed-on: #6
2026-07-12 13:43:22 -04:00
bspeice 08ada94bd2 Implement post-transform coefficients
CI / cargo fmt (push) Successful in 1m25s
CI / cargo test (push) Successful in 14m59s
CI / cargo test (GPU) (push) Successful in 16m50s
2026-07-12 10:05:19 -04:00
18 changed files with 1581 additions and 555 deletions
+4 -1
View File
@@ -21,7 +21,10 @@ jobs:
steps:
- uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
components: clippy
- run: cargo check --all-targets
- run: cargo clippy --all-targets
- run: cargo test
test-gpu:
@@ -30,5 +33,5 @@ jobs:
steps:
- 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 install --git https://github.com/rust-gpu/rust-gpu cargo-gpu --rev 67f1ff2
- run: cargo gpu check --auto-install-rust-toolchain -p enkou-shaders
Generated
+1057 -55
View File
File diff suppressed because it is too large Load Diff
+8 -2
View File
@@ -1,7 +1,8 @@
[workspace]
members = [
"enkou-shaders",
"enkou-shaders-tests",
"examples/image-runner",
"examples/image-binary",
]
resolver = "3"
@@ -13,6 +14,7 @@ license = "MIT"
repository = ""
[workspace.lints.rust]
missing_docs = { level = "warn" }
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
[workspace.dependencies]
@@ -21,10 +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 = { 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"
-73
View File
@@ -1,73 +0,0 @@
#[cfg(test)]
mod test {
use rspirv::binary::parse_bytes;
use rspirv::dr::{Module, Operand};
use rspirv::spirv::ExecutionModel;
use std::sync::OnceLock;
static SHADER_MODULE: OnceLock<Module> = OnceLock::new();
fn shader() -> &'static Module {
SHADER_MODULE.get_or_init(|| {
let shader_bytes = include_bytes!(env!("SHADER_SPV_PATH"));
let mut loader = rspirv::dr::Loader::new();
parse_bytes(shader_bytes, &mut loader).expect("Unable to parse shader");
loader.module()
})
}
fn has_entry_point(execution_model: ExecutionModel, name: &str) -> bool {
for ref entry_point in shader().entry_points.iter() {
let operands: Vec<Operand> = entry_point
.operands
.iter()
.filter(|op| match op {
Operand::ExecutionModel(_) | Operand::LiteralString(_) => true,
_ => false,
})
.map(|op| op.clone())
.collect();
assert_eq!(operands.len(), 2);
match &operands[0] {
Operand::ExecutionModel(actual) => {
if execution_model != *actual {
continue;
}
}
op => panic!("Unexpected operand; {}", op),
}
match &operands[1] {
Operand::LiteralString(actual) => {
if name != actual {
continue;
}
}
op => panic!("Unexpected operand; {}", op),
}
return true;
}
false
}
#[test]
pub fn has_entry_main_chaos_game() {
assert!(has_entry_point(
ExecutionModel::GLCompute,
"main_chaos_game"
))
}
#[test]
pub fn has_entry_main_image_render() {
assert!(has_entry_point(
ExecutionModel::GLCompute,
"main_image_render"
))
}
}
-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
-105
View File
@@ -1,105 +0,0 @@
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, Vec4, uvec2, vec2};
use image::{Rgba, Rgba32FImage};
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(ITERATIONS as usize, Vec4::ZERO);
main_image_render(
&camera,
palette,
&output_points_ifs,
&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 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")?;
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(())
}
+47 -137
View File
@@ -2,47 +2,8 @@
//!
//! 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};
/// 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 {}
use glam::{Affine2, IVec2, UVec2, Vec2, vec2};
use libm::powf;
/// Settings used to map IFS coordinates to pixel coordinates.
///
@@ -53,8 +14,6 @@ unsafe impl bytemuck::Pod for BlendMode {}
pub struct Camera {
dimensions: UVec2,
transform: Affine2,
blend_mode: BlendMode,
image_gamma: f32,
}
impl Camera {
@@ -67,14 +26,14 @@ impl Camera {
///
/// * `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.
/// 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.
/// `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.
/// `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.
/// 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)));
@@ -91,122 +50,73 @@ impl Camera {
Camera {
dimensions,
transform,
blend_mode: BlendMode::Linear,
image_gamma: 1.5,
}
}
fn transform_point(&self, point: Vec2) -> IVec2 {
/// 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 {
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(&self, point: Vec4, palette: &[Vec4]) -> Option<(usize, Vec4)> {
let pixel_coordinates = self.transform_point(point.xy());
/// 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<UVec2> {
let pixel_coordinates = self.transform_point(point);
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;
None
} else {
Some(pixel_coordinates.as_uvec2())
}
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))
}
}
#[allow(missing_docs)]
/// Shader entry point for running the camera transformation over a list of IFS coordinates
pub mod entry {
use crate::camera::Camera;
use glam::Vec4;
use libm::log10f;
use spirv_std::glam::{IVec2, Vec2};
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(
/// 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)] palette: &[Vec4],
#[spirv(storage_buffer, descriptor_set = 0, binding = 1)] coordinates_ifs: &[Vec4],
#[spirv(storage_buffer, descriptor_set = 1, binding = 0)] image: &mut [Vec4],
#[spirv(storage_buffer, descriptor_set = 0, binding = 1)] coordinates_ifs: &[Vec2],
#[spirv(storage_buffer, descriptor_set = 1, binding = 0)] coordinates_pixel: &mut [IVec2],
) {
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;
for i in 0..coordinates_ifs.len() {
coordinates_pixel[i] = camera.transform_point(coordinates_ifs[i])
}
}
}
#[cfg(test)]
mod test {
use crate::camera::{BlendMode, Camera};
use glam::{Affine2, Vec2, Vec4, ivec2, uvec2, vec2};
use crate::camera::Camera;
use glam::{Affine2, Vec2, 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() {
pub 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)
@@ -244,7 +154,7 @@ mod test {
}
#[test]
fn camera_point_outside_image() {
pub 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),
@@ -259,7 +169,7 @@ mod test {
}
#[test]
fn camera_point_outside_image_negative() {
pub 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),
@@ -274,7 +184,7 @@ mod test {
}
#[test]
fn camera_aspect_ratio() {
pub 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(
+9 -59
View File
@@ -12,6 +12,7 @@
//!
//! 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};
@@ -35,14 +36,13 @@ 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, usize) {
) -> (Vec2, u32) {
let mut choice_weight = rng.sample::<f32, _>(StandardUniform);
let mut transform_index: usize = 0;
let mut transform_index: u32 = 0;
for i in 0..weights.len() {
choice_weight -= weights[i];
@@ -53,10 +53,8 @@ pub fn step_chaos_game<R: Rng>(
transform_index += 1;
}
let ref transform = transforms[transform_index];
(
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],
@@ -82,9 +79,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: vec2(rng.sample(BiUnit), rng.sample(BiUnit)),
current_color: rng.sample(StandardUniform),
current_point,
rng,
transforms,
weights,
@@ -94,65 +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))
}
}
/// 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();
}
Some(next_point)
}
}
+5 -3
View File
@@ -1,10 +1,12 @@
//! # Enkou
#![no_std]
#![warn(missing_docs)]
#![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;
mod rng;
pub mod rng;
pub mod transform;
pub mod variation;
+6 -3
View File
@@ -1,3 +1,6 @@
//! # RNG
//!
//! Random number generation utilities for shaders
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256StarStar;
@@ -14,17 +17,17 @@ use rand_xoshiro::Xoshiro256StarStar;
/// 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(
pub 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:
// 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;
rng_state_actual[i] |= (rng_state[i * size_of::<u64>() + j] as u64) << (j * 8);
}
}
+33 -92
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).
@@ -13,22 +13,17 @@ use rand::Rng;
#[repr(C)]
pub struct Transform {
coefficients: Affine2,
coefficients_post: 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 {
pub fn new(coefficients: Affine2, coefficients_post: Affine2, variation_range: UVec2) -> Self {
Transform {
coefficients,
coefficients_post,
variation_range,
color,
}
}
@@ -46,111 +41,57 @@ impl Transform {
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];
let 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)
self.coefficients_post.transform_point2(point)
}
}
#[cfg(test)]
mod test {
use crate::Coefficients2;
use crate::rng::xoshiro256starstar_from_seed;
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(())
}
}
use glam::{Affine2, uvec2, vec2};
#[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() {
fn transform_scaling() {
let scale_coefficients = vec2(2.0, 0.5);
let transform = Transform::new(
Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.0),
Affine2::from_scale(scale_coefficients),
Affine2::IDENTITY,
uvec2(0, 1),
vec2(0.0, 0.0),
);
let mut rng = xoshiro256starstar_from_seed([0; 32]);
let variations = [Variation::IDENTITY];
let point = vec2(1.0, 1.0);
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);
}
assert_eq!(
transform.transform_point(&mut rng, &variations, point),
scale_coefficients
);
}
#[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())];
fn transform_scaling_post() {
let scale_coefficients = vec2(2.0, 0.5);
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),
);
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);
}
}
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);
#[test]
fn test_color_mixing() {
let transform = Transform::new(Affine2::IDENTITY, uvec2(0, 1), vec2(0.0, 0.5));
let point_pdj = transform_pdj.transform_point(&mut rng, &variations, point);
let point_pdj_post = transform_pdj_post.transform_point(&mut rng, &variations, point);
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);
assert_eq!(point_pdj * scale_coefficients, point_pdj_post);
}
}
+3 -3
View File
@@ -21,8 +21,8 @@ use rand::{Rng, RngExt};
pub struct VariationParams([f32; 4]);
impl From<[f32; 4]> for VariationParams {
fn from(value: [f32; 4]) -> Self {
VariationParams(value)
fn from(v: [f32; 4]) -> Self {
VariationParams(v)
}
}
@@ -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,
@@ -1,18 +1,16 @@
[package]
name = "enkou-shaders-tests"
publish = false
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
[dependencies]
rspirv.workspace = true
[build-dependencies]
anyhow.workspace = true
cargo-gpu-install.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
@@ -4,7 +4,7 @@ use std::path::PathBuf;
pub fn main() -> anyhow::Result<()> {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let crate_path = [manifest_dir, "..", "enkou-shaders"]
let crate_path = [manifest_dir, "..", "image-binary"]
.iter()
.copied()
.collect::<PathBuf>();
@@ -16,15 +16,13 @@ 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,
Capability::Float64,
];
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={}", spv_path.display());
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(())
}