Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 53d5ad1422 |
Generated
+1057
-55
File diff suppressed because it is too large
Load Diff
+7
-1
@@ -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,6 +23,7 @@ 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"
|
||||
@@ -28,3 +31,6 @@ 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"
|
||||
|
||||
@@ -1,62 +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 entry_point in shader().entry_points.iter() {
|
||||
let operands: Vec<Operand> = entry_point
|
||||
.operands
|
||||
.iter()
|
||||
.filter(|op| matches!(op, Operand::ExecutionModel(_) | Operand::LiteralString(_)))
|
||||
.cloned()
|
||||
.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]
|
||||
fn has_entry_main_camera() {
|
||||
assert!(has_entry_point(
|
||||
ExecutionModel::GLCompute,
|
||||
"main_image_accumulate"
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
use anyhow::{Context, Result};
|
||||
use enkou_shaders::Coefficients2;
|
||||
use enkou_shaders::camera::Camera;
|
||||
use enkou_shaders::chaos_game::ChaosGame;
|
||||
use enkou_shaders::image::{BlendMode, ImageSettings};
|
||||
use enkou_shaders::transform::Transform;
|
||||
use enkou_shaders::variation::Variation;
|
||||
use glam::{Affine2, UVec2, Vec2, uvec2, vec2};
|
||||
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 ITERATIONS: usize = 50_000;
|
||||
const IMAGE_DIMENSION: UVec2 = uvec2(600, 600);
|
||||
|
||||
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), vec2(0.0, 1.0))
|
||||
},
|
||||
{
|
||||
// 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), vec2(0.0, 1.0))
|
||||
},
|
||||
{
|
||||
// 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), vec2(0.0, 1.0))
|
||||
},
|
||||
];
|
||||
|
||||
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 image_settings = ImageSettings::new(BlendMode::Linear, IMAGE_DIMENSION);
|
||||
|
||||
let mut image = GrayImage::new(IMAGE_DIMENSION.x, IMAGE_DIMENSION.y);
|
||||
|
||||
let chaos_game = ChaosGame::new(&mut rng, &transforms, &weights, &variations);
|
||||
|
||||
chaos_game
|
||||
.skip(ITERATIONS_DISCARD)
|
||||
.take(ITERATIONS)
|
||||
.map(|(point_ifs, _)| camera.transform_point(point_ifs))
|
||||
.filter_map(|point_pixel| image_settings.transform_point_to_image(point_pixel))
|
||||
.for_each(|point_pixel| image.put_pixel(point_pixel.x, point_pixel.y, Luma([255])));
|
||||
|
||||
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 => "xdg-open",
|
||||
_ => panic!("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
-10
@@ -12,6 +12,7 @@ use libm::powf;
|
||||
#[derive(Copy, Clone, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct Camera {
|
||||
dimensions: UVec2,
|
||||
transform: Affine2,
|
||||
}
|
||||
|
||||
@@ -22,7 +23,7 @@ impl Camera {
|
||||
/// to express the transform steps individually.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `blend_mode` - Color blending mode for the output image
|
||||
///
|
||||
/// * `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.
|
||||
@@ -46,7 +47,10 @@ impl Camera {
|
||||
* zoom_transform
|
||||
* ifs_center_transform;
|
||||
|
||||
Camera { transform }
|
||||
Camera {
|
||||
dimensions,
|
||||
transform,
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a point from IFS coordinates to pixel coordinates.
|
||||
@@ -69,6 +73,40 @@ impl Camera {
|
||||
pub fn transform_point(&self, point: Vec2) -> IVec2 {
|
||||
self.transform.transform_point2(point).as_ivec2()
|
||||
}
|
||||
|
||||
/// Map a point from IFS coordinates to pixel coordinates (like [`transform_point`](Camera::transform_point)),
|
||||
/// and check that the result is within the provided image dimensions.
|
||||
pub fn transform_point_to_image(&self, point: Vec2) -> Option<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
|
||||
{
|
||||
None
|
||||
} else {
|
||||
Some(pixel_coordinates.as_uvec2())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shader entry point for running the camera transformation over a list of IFS coordinates
|
||||
pub mod entry {
|
||||
use crate::camera::Camera;
|
||||
use spirv_std::glam::{IVec2, Vec2};
|
||||
use spirv_std::spirv;
|
||||
|
||||
/// Transform IFS coordinates to pixel coordinates
|
||||
#[spirv(compute(entry_point_name = "main_camera", threads(1)))]
|
||||
pub fn main_camera(
|
||||
#[spirv(storage_buffer, descriptor_set = 0, binding = 0)] camera: &Camera,
|
||||
#[spirv(storage_buffer, descriptor_set = 0, binding = 1)] coordinates_ifs: &[Vec2],
|
||||
#[spirv(storage_buffer, descriptor_set = 1, binding = 0)] coordinates_pixel: &mut [IVec2],
|
||||
) {
|
||||
for i in 0..coordinates_ifs.len() {
|
||||
coordinates_pixel[i] = camera.transform_point(coordinates_ifs[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -78,7 +116,7 @@ mod test {
|
||||
use libm::powf;
|
||||
|
||||
#[test]
|
||||
fn manual_camera() {
|
||||
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)
|
||||
@@ -110,14 +148,13 @@ mod test {
|
||||
|
||||
// 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)
|
||||
.abs()
|
||||
.as_uvec2();
|
||||
assert!(error.x <= 1 && error.y <= 1);
|
||||
let error = camera.transform_point(starting_point) - point;
|
||||
assert!(error.x.abs() <= 1);
|
||||
assert!(error.y.abs() <= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_outside_camera() {
|
||||
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),
|
||||
@@ -132,7 +169,7 @@ mod test {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_outside_camera_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),
|
||||
@@ -147,7 +184,7 @@ mod test {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn 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(
|
||||
|
||||
@@ -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,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, u32) {
|
||||
) -> (Vec2, u32) {
|
||||
let mut choice_weight = rng.sample::<f32, _>(StandardUniform);
|
||||
let mut transform_index: u32 = 0;
|
||||
|
||||
@@ -53,11 +53,8 @@ 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,
|
||||
)
|
||||
}
|
||||
@@ -68,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],
|
||||
@@ -84,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,
|
||||
@@ -97,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
//! Image Accumulate
|
||||
|
||||
use crate::camera::Camera;
|
||||
use crate::chaos_game::ChaosGame;
|
||||
use crate::image::ImageSettings;
|
||||
use crate::rng::xoshiro256starstar_from_seed;
|
||||
use crate::transform::Transform;
|
||||
use crate::variation::Variation;
|
||||
use glam::{UVec2, Vec4};
|
||||
use spirv_std::spirv;
|
||||
|
||||
/// Run the chaos game and accumulate points into the output image buffer
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `iterations` - Controls the iteration count; the first `x` iterations are discarded,
|
||||
/// the next `y` iterations are accumulated into the output image
|
||||
/// * `rng_seed`
|
||||
/// * `transforms`
|
||||
/// * `weights`
|
||||
/// * `variations`
|
||||
/// * `camera` - Camera transformation to map IFS coordinates to pixel coordinates
|
||||
/// * `image_settings` - Settings to use for image accumulation
|
||||
/// * `palette` - List of colors to use for the image palette; assumed to be RGB values scaled to `[0-255]`, with an alpha of 255
|
||||
/// * `image` - Output image buffer
|
||||
#[spirv(compute(entry_point_name = "main_image_accumulate", threads(1)))]
|
||||
pub fn main_image_accumulate(
|
||||
#[spirv(storage_buffer, descriptor_set = 0, binding = 0)] iterations: &UVec2,
|
||||
#[spirv(storage_buffer, descriptor_set = 0, binding = 1)] rng_seed: &[u8],
|
||||
#[spirv(storage_buffer, descriptor_set = 0, binding = 2)] transforms: &[Transform],
|
||||
#[spirv(storage_buffer, descriptor_set = 0, binding = 3)] weights: &[f32],
|
||||
#[spirv(storage_buffer, descriptor_set = 0, binding = 4)] variations: &[Variation],
|
||||
#[spirv(storage_buffer, descriptor_set = 0, binding = 5)] camera: &Camera,
|
||||
#[spirv(storage_buffer, descriptor_set = 0, binding = 6)] image_settings: &ImageSettings,
|
||||
#[spirv(storage_buffer, descriptor_set = 0, binding = 7)] palette: &[Vec4],
|
||||
#[spirv(storage_buffer, descriptor_set = 1, binding = 0)] image: &mut [Vec4],
|
||||
) {
|
||||
let mut rng_seed_actual = [0u8; 32];
|
||||
for i in 0..rng_seed_actual.len() {
|
||||
rng_seed_actual[i] = rng_seed[i];
|
||||
}
|
||||
|
||||
let mut rng = xoshiro256starstar_from_seed(rng_seed_actual);
|
||||
|
||||
let chaos_game = ChaosGame::new(&mut rng, transforms, weights, variations);
|
||||
let (iterations_fuse, iterations_accumulate) = (iterations.x, iterations.y);
|
||||
|
||||
let ifs_to_image = |(ifs_point, ifs_color)| {
|
||||
let pixel_coordinates = camera.transform_point(ifs_point);
|
||||
let pixel_color = image_settings.transform_color(ifs_color, palette);
|
||||
image_settings
|
||||
.transform_point_to_index(pixel_coordinates)
|
||||
.map(|pixel_index| (pixel_index, pixel_color))
|
||||
};
|
||||
|
||||
for ifs_point in chaos_game
|
||||
.skip(iterations_fuse as usize)
|
||||
.take(iterations_accumulate as usize)
|
||||
{
|
||||
if let Some((pixel_index, pixel_color)) = ifs_to_image(ifs_point) {
|
||||
image[pixel_index as usize] = pixel_color;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
//! # Entry
|
||||
//!
|
||||
//! Entry points for Enkou shaders
|
||||
pub mod image_accumulate;
|
||||
@@ -1,155 +0,0 @@
|
||||
//! Image
|
||||
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use glam::{IVec2, UVec2, 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 {}
|
||||
|
||||
/// Settings to use for mapping the IFS coordinates to an output image
|
||||
#[derive(Copy, Clone, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct ImageSettings {
|
||||
blend_mode: BlendMode,
|
||||
dimensions: UVec2,
|
||||
}
|
||||
|
||||
impl ImageSettings {
|
||||
/// Create a new settings object
|
||||
pub fn new(blend_mode: BlendMode, dimensions: UVec2) -> Self {
|
||||
ImageSettings {
|
||||
blend_mode,
|
||||
dimensions,
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a point from camera coordinates to pixel coordinates,
|
||||
/// and check that the result is within the provided image dimensions.
|
||||
pub fn transform_point_to_image(&self, point: IVec2) -> Option<UVec2> {
|
||||
if 0 <= point.x
|
||||
&& (point.x as u32) < self.dimensions.x
|
||||
&& 0 <= point.y
|
||||
&& (point.y as u32) < self.dimensions.y
|
||||
{
|
||||
Some(point.as_uvec2())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a point from camera coordinates to a final pixel index
|
||||
pub fn transform_point_to_index(&self, point: IVec2) -> Option<u32> {
|
||||
self.transform_point_to_image(point)
|
||||
.map(|pixel| self.dimensions.with_x(1).dot(pixel))
|
||||
}
|
||||
|
||||
/// Map an IFS color coordinate to the palette RGB value
|
||||
pub fn transform_color(&self, color: f32, palette: &[Vec4]) -> Vec4 {
|
||||
self.blend_mode.ifs_to_rgb(color, palette)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::image::{BlendMode, ImageSettings};
|
||||
use glam::{Vec4, ivec2, uvec2};
|
||||
|
||||
#[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]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_bounds() {
|
||||
let image_settings = ImageSettings::new(BlendMode::Linear, uvec2(100, 100));
|
||||
|
||||
assert!(
|
||||
image_settings
|
||||
.transform_point_to_image(ivec2(-1, -1))
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
image_settings
|
||||
.transform_point_to_image(ivec2(0, 0))
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
image_settings
|
||||
.transform_point_to_image(ivec2(99, 99))
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
image_settings
|
||||
.transform_point_to_image(ivec2(100, 100))
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,12 @@
|
||||
//! # Enkou
|
||||
#![no_std]
|
||||
#![warn(missing_docs)]
|
||||
// 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)]
|
||||
#![allow(clippy::manual_memcpy)]
|
||||
// Shader entry points are expected to have a lot of arguments:
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
pub mod camera;
|
||||
pub mod chaos_game;
|
||||
pub mod entry;
|
||||
pub mod image;
|
||||
mod rng;
|
||||
pub mod rng;
|
||||
pub mod transform;
|
||||
pub mod variation;
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
//! # RNG
|
||||
//!
|
||||
//! Random number generation utilities for shaders
|
||||
use rand::SeedableRng;
|
||||
use rand_xoshiro::Xoshiro256StarStar;
|
||||
|
||||
@@ -14,9 +17,7 @@ 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.
|
||||
// Temporarily unused, will be required once the main image accumulation entry point is implemented
|
||||
#[allow(unused)]
|
||||
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];
|
||||
|
||||
@@ -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,22 +15,15 @@ pub struct Transform {
|
||||
coefficients: Affine2,
|
||||
coefficients_post: Affine2,
|
||||
variation_range: UVec2,
|
||||
color: Vec2,
|
||||
}
|
||||
|
||||
impl Transform {
|
||||
/// Create a new transform from an affine transformation matrix
|
||||
pub fn new(
|
||||
coefficients: Affine2,
|
||||
coefficients_post: 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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,11 +47,6 @@ impl Transform {
|
||||
|
||||
self.coefficients_post.transform_point2(point)
|
||||
}
|
||||
|
||||
/// Apply this transform to a color
|
||||
pub fn transform_color(&self, color: f32) -> f32 {
|
||||
color.lerp(self.color.x, self.color.y)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -66,7 +54,7 @@ mod test {
|
||||
use crate::rng::xoshiro256starstar_from_seed;
|
||||
use crate::transform::Transform;
|
||||
use crate::variation::{Variation, VariationKind};
|
||||
use glam::{Affine2, Vec2, uvec2, vec2};
|
||||
use glam::{Affine2, uvec2, vec2};
|
||||
|
||||
#[test]
|
||||
fn transform_scaling() {
|
||||
@@ -75,7 +63,6 @@ mod test {
|
||||
Affine2::from_scale(scale_coefficients),
|
||||
Affine2::IDENTITY,
|
||||
uvec2(0, 1),
|
||||
Vec2::ZERO,
|
||||
);
|
||||
|
||||
let mut rng = xoshiro256starstar_from_seed([0; 32]);
|
||||
@@ -91,17 +78,11 @@ 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),
|
||||
Vec2::ZERO,
|
||||
);
|
||||
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),
|
||||
Vec2::ZERO,
|
||||
);
|
||||
|
||||
let mut rng = xoshiro256starstar_from_seed([0; 32]);
|
||||
@@ -113,23 +94,4 @@ mod test {
|
||||
|
||||
assert_eq!(point_pdj * scale_coefficients, point_pdj_post);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_color() {
|
||||
// Color 0.5, color speed 1.0, so color value will always be 0.5 after transform
|
||||
let color = vec2(0.5, 1.0);
|
||||
let transform = Transform::new(Affine2::IDENTITY, Affine2::IDENTITY, uvec2(0, 1), color);
|
||||
|
||||
assert_eq!(transform.transform_color(0.0), 0.5);
|
||||
assert_eq!(transform.transform_color(1.0), 0.5);
|
||||
assert_eq!(transform.transform_color(2.0), 0.5);
|
||||
|
||||
// Color 1.0, color speed 0.5, so color value moves to halfway between current and 1.0
|
||||
let color = vec2(1.0, 0.5);
|
||||
let transform = Transform::new(Affine2::IDENTITY, Affine2::IDENTITY, uvec2(0, 1), color);
|
||||
|
||||
assert_eq!(transform.transform_color(0.0), 0.5);
|
||||
assert_eq!(transform.transform_color(1.0), 1.0);
|
||||
assert_eq!(transform.transform_color(2.0), 1.5);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -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,
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -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>();
|
||||
@@ -20,6 +20,9 @@ pub fn main() -> anyhow::Result<()> {
|
||||
|
||||
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(())
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
Reference in New Issue
Block a user