Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 53d5ad1422 | |||
| 7ff19631ba | |||
| 9ea4261a84 | |||
| 81f23c1bd8 | |||
| 08ada94bd2 | |||
| 4005e14ab0 | |||
| 3bd01da563 | |||
| 616bd2ae6d | |||
| 86ef0887e3 | |||
| 3c5563c940 | |||
| c3224fadd8 | |||
| 44b71c2692 | |||
| 6671475c75 | |||
| df747855b6 | |||
| 55cece063f | |||
| 344ecc3450 | |||
| a9da463041 | |||
| 67b94522d0 | |||
| beb1c8526f | |||
| 90f886f971 | |||
| 1709336062 | |||
| bb4e0aa669 | |||
| 5603f19c22 | |||
| 35784514d6 | |||
| 24a40adcad | |||
| 0a17b24451 | |||
| 3652de9fd1 | |||
| bf82670f9e |
@@ -1,7 +1,6 @@
|
|||||||
name: "CI"
|
name: "CI"
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
pull_request:
|
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
@@ -22,7 +21,10 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v6
|
- uses: actions/checkout@v6
|
||||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||||
- run: cargo check
|
with:
|
||||||
|
components: clippy
|
||||||
|
- run: cargo check --all-targets
|
||||||
|
- run: cargo clippy --all-targets
|
||||||
- run: cargo test
|
- run: cargo test
|
||||||
|
|
||||||
test-gpu:
|
test-gpu:
|
||||||
@@ -31,5 +33,5 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v6
|
- uses: actions/checkout@v6
|
||||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
- 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 -p enkou-shaders
|
- run: cargo gpu check --auto-install-rust-toolchain -p enkou-shaders
|
||||||
|
|||||||
Generated
+1959
-32
File diff suppressed because it is too large
Load Diff
+13
-3
@@ -1,7 +1,8 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"enkou-shaders",
|
"enkou-shaders",
|
||||||
"enkou-shaders-tests",
|
"examples/image-runner",
|
||||||
|
"examples/image-binary",
|
||||||
]
|
]
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
|
|
||||||
@@ -13,6 +14,7 @@ license = "MIT"
|
|||||||
repository = ""
|
repository = ""
|
||||||
|
|
||||||
[workspace.lints.rust]
|
[workspace.lints.rust]
|
||||||
|
missing_docs = { level = "warn" }
|
||||||
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
|
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
@@ -21,6 +23,14 @@ spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "67f1ff2"
|
|||||||
|
|
||||||
anyhow = "1.0.102"
|
anyhow = "1.0.102"
|
||||||
bytemuck = { version = "1.25.0", features = ["derive"] }
|
bytemuck = { version = "1.25.0", features = ["derive"] }
|
||||||
glam = { version = "0.33.1", default-features = false, features = ["libm"] }
|
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"
|
rspirv = "0.13.0"
|
||||||
|
tempfile = "3.27.0"
|
||||||
|
thiserror = "2.0.19"
|
||||||
|
wgpu = { version = "30.0.0", features = ["spirv"] }
|
||||||
|
xflags = "0.3.2"
|
||||||
|
|||||||
@@ -1,67 +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_fs() {
|
|
||||||
assert!(has_entry_point(ExecutionModel::Fragment, "main_fs"))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
pub fn has_entry_main_vs() {
|
|
||||||
assert!(has_entry_point(ExecutionModel::Vertex, "main_vs"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,6 +10,9 @@ repository.workspace = true
|
|||||||
workspace = true
|
workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
spirv-std.workspace = true
|
|
||||||
glam.workspace = true
|
|
||||||
bytemuck.workspace = true
|
bytemuck.workspace = true
|
||||||
|
glam.workspace = true
|
||||||
|
libm.workspace = true
|
||||||
|
rand.workspace = true
|
||||||
|
rand_xoshiro.workspace = true
|
||||||
|
spirv-std.workspace = true
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
//! # Camera
|
||||||
|
//!
|
||||||
|
//! Map points from the IFS coordinate system to pixel coordinates. This is a lossy transformation.
|
||||||
|
use bytemuck::{Pod, Zeroable};
|
||||||
|
use glam::{Affine2, IVec2, UVec2, Vec2, vec2};
|
||||||
|
use libm::powf;
|
||||||
|
|
||||||
|
/// Settings used to map IFS coordinates to pixel coordinates.
|
||||||
|
///
|
||||||
|
/// The camera is itself an affine transformation, capable of zoom, rotation, and translation
|
||||||
|
/// of the IFS coordinates before rendering to the final image.
|
||||||
|
#[derive(Copy, Clone, Pod, Zeroable)]
|
||||||
|
#[repr(C)]
|
||||||
|
pub struct Camera {
|
||||||
|
dimensions: UVec2,
|
||||||
|
transform: Affine2,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Camera {
|
||||||
|
/// Construct a new camera for translating IFS coordinates to pixel coordinates.
|
||||||
|
///
|
||||||
|
/// While the camera is implemented as a single affine transformation, it's helpful
|
||||||
|
/// to express the transform steps individually.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `dimensions` - Width and height of the output image (in pixels).
|
||||||
|
/// * `center` - Location of the origin in IFS coordinates. Positive `x` shifts the image
|
||||||
|
/// left, and positive `y` position shifts the image up.
|
||||||
|
/// * `rotate` - Rotation angle (in radians) of IFS coordinates. Rotation is applied after the
|
||||||
|
/// `center` translation, so it is about the new origin.
|
||||||
|
/// * `zoom` - Zoom factor applied to IFS coordinates. IFS coordinates are scaled by
|
||||||
|
/// `pow(2, zoom)`, so a zoom factor of 0 is the identity.
|
||||||
|
/// * `scale` - Pixels per unit of IFS coordinates. This parameter is usually chosen such
|
||||||
|
/// that the largest dimension will cover the range `[-2, 2]`, but values higher or lower
|
||||||
|
/// can be used as a secondary zoom.
|
||||||
|
pub fn new(dimensions: UVec2, center: Vec2, rotate: f32, zoom: Vec2, scale: Vec2) -> Camera {
|
||||||
|
let ifs_center_transform = Affine2::from_translation(-center);
|
||||||
|
let zoom_transform = Affine2::from_scale(vec2(powf(2.0, zoom.x), powf(2.0, zoom.y)));
|
||||||
|
let scale_transform = Affine2::from_scale(scale);
|
||||||
|
let rotate_transform = Affine2::from_angle(rotate);
|
||||||
|
let image_center_transform = Affine2::from_translation((dimensions / 2).as_vec2());
|
||||||
|
|
||||||
|
let transform = image_center_transform
|
||||||
|
* rotate_transform
|
||||||
|
* scale_transform
|
||||||
|
* zoom_transform
|
||||||
|
* ifs_center_transform;
|
||||||
|
|
||||||
|
Camera {
|
||||||
|
dimensions,
|
||||||
|
transform,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 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)]
|
||||||
|
mod test {
|
||||||
|
use crate::camera::Camera;
|
||||||
|
use glam::{Affine2, Vec2, ivec2, uvec2, vec2};
|
||||||
|
use libm::powf;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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)
|
||||||
|
let center = vec2(-1.0, -1.0);
|
||||||
|
let point = starting_point - center;
|
||||||
|
|
||||||
|
// Rotate about the new origin; points move counter-clockwise, giving us (-2.0, 2.0)
|
||||||
|
let rotate = 90.0f32.to_radians();
|
||||||
|
let point = Affine2::from_angle(rotate).transform_point2(point);
|
||||||
|
|
||||||
|
// Zoom in by a factor of 1; points will be twice as far from the origin,
|
||||||
|
// giving us (-4.0, 4.0)
|
||||||
|
let zoom = vec2(1.0, 1.0);
|
||||||
|
let point = point * vec2(powf(2.0, zoom.x), powf(2.0, zoom.y));
|
||||||
|
|
||||||
|
// Apply scaling; scale 100 in a 1000 x 1000 image is an effective range
|
||||||
|
// of [-5, 5] in IFS coordinates.
|
||||||
|
// After scaling, the point is (-400.0, 400.0)
|
||||||
|
let scale = vec2(100.0, 100.0);
|
||||||
|
let point = point * scale;
|
||||||
|
|
||||||
|
// Move the origin from (0, 0) to image center,
|
||||||
|
// giving us (100.0, 900.0)
|
||||||
|
let dimensions = uvec2(1000, 1000);
|
||||||
|
let point = point.as_ivec2() + dimensions.as_ivec2() / 2;
|
||||||
|
|
||||||
|
// Check that the camera implementation ends up at the same point
|
||||||
|
let camera = Camera::new(dimensions, center, rotate, zoom, scale);
|
||||||
|
|
||||||
|
// The camera is implemented by composing affine transforms,
|
||||||
|
// which ends up with a slightly different result because of rounding.
|
||||||
|
let error = camera.transform_point(starting_point) - point;
|
||||||
|
assert!(error.x.abs() <= 1);
|
||||||
|
assert!(error.y.abs() <= 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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),
|
||||||
|
Vec2::ZERO,
|
||||||
|
0.0,
|
||||||
|
Vec2::ZERO,
|
||||||
|
vec2(250.0, 250.0),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Converting a point outside the effective range is legal, but outside the image bounds
|
||||||
|
assert_eq!(camera.transform_point(vec2(3.0, 3.0)), ivec2(1250, 1250));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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),
|
||||||
|
Vec2::ZERO,
|
||||||
|
0.0,
|
||||||
|
Vec2::ZERO,
|
||||||
|
vec2(250.0, 250.0),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Converting a point outside the effective range is legal, but outside the image bounds
|
||||||
|
assert_eq!(camera.transform_point(vec2(-3.0, -3.0)), ivec2(-250, -250));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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(
|
||||||
|
uvec2(1600, 900),
|
||||||
|
Vec2::ZERO,
|
||||||
|
0.0,
|
||||||
|
Vec2::ZERO,
|
||||||
|
vec2(100.0, 100.0),
|
||||||
|
);
|
||||||
|
|
||||||
|
// This point is inside the image width, but outside its height
|
||||||
|
assert_eq!(camera.transform_point(vec2(6.0, 6.0)), ivec2(1400, 1050));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
//! # Chaos Game
|
||||||
|
//!
|
||||||
|
//! Fractal flames are a class of
|
||||||
|
//! [iterated function systems](https://en.wikipedia.org/wiki/Iterated_function_system)
|
||||||
|
//! that generate images following a simple algorithm:
|
||||||
|
//!
|
||||||
|
//! - Pick a starting point `(x, y)`
|
||||||
|
//! - Iterate:
|
||||||
|
//! - Pick a [`Transform`] from the set of available transforms
|
||||||
|
//! - Apply the current point to the chosen transform, generating a new point `(x, y)`
|
||||||
|
//! - Plot the new point `(x, y)`
|
||||||
|
//!
|
||||||
|
//! This algorithm is also known as the ["chaos game"](https://en.wikipedia.org/wiki/Chaos_game),
|
||||||
|
//! and it forms the basic system for producing images.
|
||||||
|
|
||||||
|
use crate::transform::Transform;
|
||||||
|
use crate::variation::Variation;
|
||||||
|
use rand::distr::{Distribution, StandardUniform};
|
||||||
|
use rand::{Rng, RngExt};
|
||||||
|
use spirv_std::glam::{Vec2, vec2};
|
||||||
|
|
||||||
|
struct BiUnit;
|
||||||
|
impl Distribution<f32> for BiUnit {
|
||||||
|
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f32 {
|
||||||
|
rng.sample::<f32, _>(StandardUniform) * 2.0 - 1.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Iterate one step in the chaos game; choose the next transform, apply it,
|
||||||
|
/// and return the resulting point. Also returns the transform index so that
|
||||||
|
/// path-dependent weights (the "Xaos" table in Apophysis) can be chosen
|
||||||
|
/// for the next iteration step.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `weights` - Weights are assumed to be normalized; adding all elements together should return the value 1
|
||||||
|
pub fn step_chaos_game<R: Rng>(
|
||||||
|
point: Vec2,
|
||||||
|
rng: &mut R,
|
||||||
|
transforms: &[Transform],
|
||||||
|
weights: &[f32],
|
||||||
|
variations: &[Variation],
|
||||||
|
) -> (Vec2, u32) {
|
||||||
|
let mut choice_weight = rng.sample::<f32, _>(StandardUniform);
|
||||||
|
let mut transform_index: u32 = 0;
|
||||||
|
|
||||||
|
for i in 0..weights.len() {
|
||||||
|
choice_weight -= weights[i];
|
||||||
|
if choice_weight <= 0.0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
transform_index += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
(
|
||||||
|
transforms[transform_index as usize].transform_point(rng, variations, point),
|
||||||
|
transform_index,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Iterator for chaos game state. Holds the current point and references to all other data
|
||||||
|
/// necessary to generate fractal flame images.
|
||||||
|
///
|
||||||
|
/// New points in the chaos game are produced by iterating on the chaos game.
|
||||||
|
pub struct ChaosGame<'a, R: Rng> {
|
||||||
|
current_point: Vec2,
|
||||||
|
rng: &'a mut R,
|
||||||
|
transforms: &'a [Transform],
|
||||||
|
weights: &'a [f32],
|
||||||
|
variations: &'a [Variation],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, R: Rng> ChaosGame<'a, R> {
|
||||||
|
/// Create a new chaos game iterator
|
||||||
|
pub fn new(
|
||||||
|
rng: &'a mut R,
|
||||||
|
transforms: &'a [Transform],
|
||||||
|
weights: &'a [f32],
|
||||||
|
variations: &'a [Variation],
|
||||||
|
) -> Self {
|
||||||
|
let current_point = vec2(rng.sample(BiUnit), rng.sample(BiUnit));
|
||||||
|
ChaosGame {
|
||||||
|
current_point,
|
||||||
|
rng,
|
||||||
|
transforms,
|
||||||
|
weights,
|
||||||
|
variations,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, R: Rng> Iterator for ChaosGame<'a, R> {
|
||||||
|
type Item = Vec2;
|
||||||
|
|
||||||
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
|
let (next_point, _) = step_chaos_game(
|
||||||
|
self.current_point,
|
||||||
|
self.rng,
|
||||||
|
self.transforms,
|
||||||
|
self.weights,
|
||||||
|
self.variations,
|
||||||
|
);
|
||||||
|
self.current_point = next_point;
|
||||||
|
|
||||||
|
Some(next_point)
|
||||||
|
}
|
||||||
|
}
|
||||||
+104
-29
@@ -1,36 +1,111 @@
|
|||||||
#![no_std]
|
//! # Enkou
|
||||||
|
#![cfg_attr(target_arch = "spirv", no_std)]
|
||||||
|
|
||||||
use bytemuck::{Pod, Zeroable};
|
// SPIR-V backend is unable to compile iteration over items
|
||||||
use core::f32::consts::PI;
|
#![allow(clippy::needless_range_loop)]
|
||||||
use glam::{Vec3, Vec4, vec2, vec3};
|
|
||||||
#[cfg(target_arch = "spirv")]
|
|
||||||
use spirv_std::num_traits::Float;
|
|
||||||
use spirv_std::spirv;
|
|
||||||
|
|
||||||
#[derive(Copy, Clone, Pod, Zeroable)]
|
pub mod camera;
|
||||||
#[repr(C)]
|
pub mod chaos_game;
|
||||||
pub struct ShaderConstants {
|
pub mod rng;
|
||||||
pub width: u32,
|
pub mod transform;
|
||||||
pub height: u32,
|
pub mod variation;
|
||||||
pub time: f32,
|
|
||||||
|
use glam::Affine2;
|
||||||
|
|
||||||
|
/// Utility trait to convert between `flam3` notation and [`glam`].
|
||||||
|
#[allow(missing_docs)]
|
||||||
|
pub trait Coefficients2 {
|
||||||
|
/// Convert affine transformation coefficients to the [`glam`] representation.
|
||||||
|
/// Parameters use the following form:
|
||||||
|
///
|
||||||
|
/// ```text
|
||||||
|
/// (a * x + b * y + c, d * x + e * y + f)
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # use glam::{Affine2, vec2};
|
||||||
|
/// # use crate::enkou_shaders::Coefficients2;
|
||||||
|
/// let coefs = Affine2::from_coefficients(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
|
||||||
|
/// let (x, y) = (7.0, 8.0);
|
||||||
|
/// assert_eq!(
|
||||||
|
/// coefs.transform_point2(vec2(x, y)),
|
||||||
|
/// vec2(
|
||||||
|
/// coefs.a() * x + coefs.b() * y + coefs.c(),
|
||||||
|
/// coefs.d() * x + coefs.e() * y + coefs.f()
|
||||||
|
/// )
|
||||||
|
/// );
|
||||||
|
/// ```
|
||||||
|
fn from_coefficients(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Affine2;
|
||||||
|
|
||||||
|
/// Convert affine transformation coefficients to the [`glam`] representation.
|
||||||
|
/// Parameters use the following form:
|
||||||
|
///
|
||||||
|
/// ```text
|
||||||
|
/// (a * x + b * y + c, d * x + e * y + f)
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # use glam::{Affine2, vec2};
|
||||||
|
/// # use crate::enkou_shaders::Coefficients2;
|
||||||
|
/// let coefs = Affine2::from_coefficients_arr([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
|
||||||
|
/// let (x, y) = (7.0, 8.0);
|
||||||
|
/// assert_eq!(
|
||||||
|
/// coefs.transform_point2(vec2(x, y)),
|
||||||
|
/// vec2(
|
||||||
|
/// coefs.a() * x + coefs.b() * y + coefs.c(),
|
||||||
|
/// coefs.d() * x + coefs.e() * y + coefs.f()
|
||||||
|
/// )
|
||||||
|
/// );
|
||||||
|
/// ```
|
||||||
|
fn from_coefficients_arr(coefficients: [f32; 6]) -> Affine2;
|
||||||
|
|
||||||
|
fn a(&self) -> f32;
|
||||||
|
fn b(&self) -> f32;
|
||||||
|
fn c(&self) -> f32;
|
||||||
|
fn d(&self) -> f32;
|
||||||
|
fn e(&self) -> f32;
|
||||||
|
fn f(&self) -> f32;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[spirv(fragment)]
|
impl Coefficients2 for Affine2 {
|
||||||
pub fn main_fs(vtx_color: Vec3, output: &mut Vec4) {
|
#[inline]
|
||||||
*output = Vec4::from((vtx_color, 1.));
|
fn from_coefficients(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Affine2 {
|
||||||
}
|
Affine2::from_cols_array(&[a, d, b, e, c, f])
|
||||||
|
}
|
||||||
|
|
||||||
#[spirv(vertex)]
|
#[inline]
|
||||||
pub fn main_vs(
|
fn from_coefficients_arr(coefficients: [f32; 6]) -> Affine2 {
|
||||||
#[spirv(vertex_index)] vert_id: i32,
|
Affine2::from_coefficients(
|
||||||
#[spirv(descriptor_set = 0, binding = 0, storage_buffer)] constants: &ShaderConstants,
|
coefficients[0],
|
||||||
#[spirv(position)] vtx_pos: &mut Vec4,
|
coefficients[1],
|
||||||
vtx_color: &mut Vec3,
|
coefficients[2],
|
||||||
) {
|
coefficients[3],
|
||||||
let speed = 0.4;
|
coefficients[4],
|
||||||
let time = constants.time * speed + vert_id as f32 * (2. * PI * 120. / 360.);
|
coefficients[5],
|
||||||
let position = vec2(f32::sin(time), f32::cos(time));
|
)
|
||||||
*vtx_pos = Vec4::from((position, 0.0, 1.0));
|
}
|
||||||
|
|
||||||
*vtx_color = [vec3(1., 0., 0.), vec3(0., 1., 0.), vec3(0., 0., 1.)][vert_id as usize % 3];
|
fn a(&self) -> f32 {
|
||||||
|
self.matrix2.x_axis.x
|
||||||
|
}
|
||||||
|
|
||||||
|
fn b(&self) -> f32 {
|
||||||
|
self.matrix2.y_axis.x
|
||||||
|
}
|
||||||
|
|
||||||
|
fn c(&self) -> f32 {
|
||||||
|
self.translation.x
|
||||||
|
}
|
||||||
|
|
||||||
|
fn d(&self) -> f32 {
|
||||||
|
self.matrix2.x_axis.y
|
||||||
|
}
|
||||||
|
|
||||||
|
fn e(&self) -> f32 {
|
||||||
|
self.matrix2.y_axis.y
|
||||||
|
}
|
||||||
|
|
||||||
|
fn f(&self) -> f32 {
|
||||||
|
self.translation.y
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
//! # Transform
|
||||||
|
//!
|
||||||
|
//! Transforms are the "functions" in an iterated function system. They take in a point,
|
||||||
|
//! and generate a new point. For fractal flames, transforms are always affine,
|
||||||
|
//! but produce more interesting images once we add variations.
|
||||||
|
use crate::variation::Variation;
|
||||||
|
use bytemuck::{Pod, Zeroable};
|
||||||
|
use glam::{Affine2, UVec2, Vec2};
|
||||||
|
use rand::Rng;
|
||||||
|
|
||||||
|
/// Affine transform for use in the [`chaos_game`](crate::chaos_game).
|
||||||
|
#[derive(Copy, Clone, Pod, Zeroable)]
|
||||||
|
#[repr(C)]
|
||||||
|
pub struct Transform {
|
||||||
|
coefficients: Affine2,
|
||||||
|
coefficients_post: Affine2,
|
||||||
|
variation_range: UVec2,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Transform {
|
||||||
|
/// Create a new transform from an affine transformation matrix
|
||||||
|
pub fn new(coefficients: Affine2, coefficients_post: Affine2, variation_range: UVec2) -> Self {
|
||||||
|
Transform {
|
||||||
|
coefficients,
|
||||||
|
coefficients_post,
|
||||||
|
variation_range,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply this transform to a point in IFS coordinates, producing a new point
|
||||||
|
pub fn transform_point<R: Rng>(
|
||||||
|
&self,
|
||||||
|
rng: &mut R,
|
||||||
|
variations: &[Variation],
|
||||||
|
point: Vec2,
|
||||||
|
) -> Vec2 {
|
||||||
|
let point = self.coefficients.transform_point2(point);
|
||||||
|
|
||||||
|
let mut point_output = Vec2::ZERO;
|
||||||
|
|
||||||
|
let variation_start = self.variation_range.x;
|
||||||
|
let variation_end = self.variation_range.y;
|
||||||
|
for variation_index in variation_start..variation_end {
|
||||||
|
let variation = &variations[variation_index as usize];
|
||||||
|
point_output += variation.transform_point(point, rng, &self.coefficients)
|
||||||
|
}
|
||||||
|
|
||||||
|
self.coefficients_post.transform_point2(point)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use crate::rng::xoshiro256starstar_from_seed;
|
||||||
|
use crate::transform::Transform;
|
||||||
|
use crate::variation::{Variation, VariationKind};
|
||||||
|
use glam::{Affine2, uvec2, vec2};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn transform_scaling() {
|
||||||
|
let scale_coefficients = vec2(2.0, 0.5);
|
||||||
|
let transform = Transform::new(
|
||||||
|
Affine2::from_scale(scale_coefficients),
|
||||||
|
Affine2::IDENTITY,
|
||||||
|
uvec2(0, 1),
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut rng = xoshiro256starstar_from_seed([0; 32]);
|
||||||
|
let variations = [Variation::IDENTITY];
|
||||||
|
let point = vec2(1.0, 1.0);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
transform.transform_point(&mut rng, &variations, point),
|
||||||
|
scale_coefficients
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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));
|
||||||
|
let transform_pdj_post = Transform::new(
|
||||||
|
Affine2::IDENTITY,
|
||||||
|
Affine2::from_scale(scale_coefficients),
|
||||||
|
uvec2(0, 1),
|
||||||
|
);
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
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!(point_pdj * scale_coefficients, point_pdj_post);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
//! # Variation
|
||||||
|
//!
|
||||||
|
//! Variations extend the fractal flame iterated function system
|
||||||
|
//! with non-linear transforms (as opposed to [`Transform`]s,
|
||||||
|
//! which are strictly affine transformations).
|
||||||
|
use crate::Coefficients2;
|
||||||
|
use bytemuck::{Pod, Zeroable};
|
||||||
|
use core::f32::consts::PI;
|
||||||
|
use glam::{Affine2, Vec2, vec2};
|
||||||
|
use libm::{atan2f, cosf, powf, sinf, sqrtf, tanf};
|
||||||
|
use rand::distr::StandardUniform;
|
||||||
|
use rand::{Rng, RngExt};
|
||||||
|
|
||||||
|
/// Generic variation parameters
|
||||||
|
///
|
||||||
|
/// Not all variations will use these parameters, but passing them
|
||||||
|
/// as an array per variation allows shaders to use a consistent struct size
|
||||||
|
/// no matter what the variation actually needs.
|
||||||
|
#[derive(Copy, Clone, Pod, Zeroable)]
|
||||||
|
#[repr(C)]
|
||||||
|
pub struct VariationParams([f32; 4]);
|
||||||
|
|
||||||
|
impl From<[f32; 4]> for VariationParams {
|
||||||
|
fn from(v: [f32; 4]) -> Self {
|
||||||
|
VariationParams(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enum for all supported variation types
|
||||||
|
///
|
||||||
|
/// ID numbers are chosen to match the variation identifier also used by `flam3`
|
||||||
|
#[derive(Copy, Clone)]
|
||||||
|
#[repr(u32)]
|
||||||
|
#[allow(missing_docs)]
|
||||||
|
pub enum VariationKind {
|
||||||
|
/// Identity variation, returns the point as-is
|
||||||
|
Linear = 0,
|
||||||
|
|
||||||
|
Julia = 13,
|
||||||
|
Popcorn = 17,
|
||||||
|
Pdj = 24,
|
||||||
|
}
|
||||||
|
|
||||||
|
// UNSAFE: Sound because enum has guaranteed layout (u32) and defined zero-value
|
||||||
|
unsafe impl bytemuck::Zeroable for VariationKind {}
|
||||||
|
// UNSAFE: Sound because enum has guaranteed layout (u32) and defined zero-value
|
||||||
|
unsafe impl bytemuck::Pod for VariationKind {}
|
||||||
|
|
||||||
|
/// Parameters required for shaders to run the variation function.
|
||||||
|
///
|
||||||
|
/// Not all variations use the [`VariationParams`], but using the struct
|
||||||
|
/// makes it easy to provide parameters to the shader.
|
||||||
|
#[derive(Copy, Clone, Pod, Zeroable)]
|
||||||
|
#[repr(C)]
|
||||||
|
pub struct Variation {
|
||||||
|
kind: VariationKind,
|
||||||
|
weight: f32,
|
||||||
|
params: VariationParams,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Variation {
|
||||||
|
/// Identity variation; calling [`transform_point`] will yield
|
||||||
|
/// the same point as the input.
|
||||||
|
pub const IDENTITY: Variation = Variation {
|
||||||
|
kind: VariationKind::Linear,
|
||||||
|
weight: 1.0,
|
||||||
|
params: VariationParams([0f32; 4]),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Create a new variation by providing the variation kind, weight, and parameters.
|
||||||
|
pub const fn new(kind: VariationKind, weight: f32, params: VariationParams) -> Variation {
|
||||||
|
Variation {
|
||||||
|
kind,
|
||||||
|
weight,
|
||||||
|
params,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Transform a point by applying this variation.
|
||||||
|
///
|
||||||
|
/// Output points are scaled by this variation's weight.
|
||||||
|
pub fn transform_point<R: Rng>(
|
||||||
|
&self,
|
||||||
|
point: Vec2,
|
||||||
|
rng: &mut R,
|
||||||
|
coefficients: &Affine2,
|
||||||
|
) -> Vec2 {
|
||||||
|
(match self.kind {
|
||||||
|
VariationKind::Linear => transform_point_linear(point),
|
||||||
|
VariationKind::Julia => transform_point_julia(point, rng),
|
||||||
|
VariationKind::Popcorn => transform_point_popcorn(point, coefficients),
|
||||||
|
VariationKind::Pdj => transform_point_pdj(point, &self.params),
|
||||||
|
}) * self.weight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transform_point_linear(point: Vec2) -> Vec2 {
|
||||||
|
point
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transform_point_julia<R: Rng>(point: Vec2, rng: &mut R) -> Vec2 {
|
||||||
|
let x2 = powf(point.x, 2.0);
|
||||||
|
let y2 = powf(point.y, 2.0);
|
||||||
|
let r = sqrtf(x2 + y2);
|
||||||
|
|
||||||
|
let theta = atan2f(point.x, point.y);
|
||||||
|
let omega = if rng.sample::<f32, _>(StandardUniform) > 0.5 {
|
||||||
|
PI
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
};
|
||||||
|
|
||||||
|
let sqrt_r = sqrtf(r);
|
||||||
|
let theta_val = theta / 2.0 + omega;
|
||||||
|
|
||||||
|
vec2(sqrt_r * cosf(theta_val), sqrt_r * sinf(theta_val))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transform_point_popcorn(point: Vec2, coefficients: &Affine2) -> Vec2 {
|
||||||
|
vec2(
|
||||||
|
point.x * coefficients.c() * sinf(tanf(3.0 * point.y)),
|
||||||
|
point.y + coefficients.f() * sinf(tanf(3.0 * point.x)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transform_point_pdj(point: Vec2, params: &VariationParams) -> Vec2 {
|
||||||
|
let (pdj_a, pdj_b, pdj_c, pdj_d) = (params.0[0], params.0[1], params.0[2], params.0[3]);
|
||||||
|
vec2(
|
||||||
|
sinf(pdj_a * point.y) - cosf(pdj_b * point.x),
|
||||||
|
sinf(pdj_c * point.x) - cosf(pdj_d * point.y),
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,18 +1,16 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "enkou-shaders-tests"
|
name = "image-binary"
|
||||||
publish = false
|
|
||||||
version.workspace = true
|
version.workspace = true
|
||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
license.workspace = true
|
license.workspace = true
|
||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
enkou-shaders = { path = "../../enkou-shaders" }
|
||||||
|
glam.workspace = true
|
||||||
|
spirv-std.workspace = true
|
||||||
|
wgpu = { workspace = true, optional = true }
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
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
|
||||||
@@ -1,26 +1,28 @@
|
|||||||
use cargo_gpu_install::install::Install;
|
use cargo_gpu_install::install::Install;
|
||||||
use cargo_gpu_install::spirv_builder::{ShaderPanicStrategy, SpirvMetadata};
|
use cargo_gpu_install::spirv_builder::{Capability, ShaderPanicStrategy, SpirvMetadata};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
pub fn main() -> anyhow::Result<()> {
|
pub fn main() -> anyhow::Result<()> {
|
||||||
let manifest_dir = env!("CARGO_MANIFEST_DIR");
|
let manifest_dir = env!("CARGO_MANIFEST_DIR");
|
||||||
let crate_path = [manifest_dir, "..", "enkou-shaders"]
|
let crate_path = [manifest_dir, "..", "image-binary"]
|
||||||
.iter()
|
.iter()
|
||||||
.copied()
|
.copied()
|
||||||
.collect::<PathBuf>();
|
.collect::<PathBuf>();
|
||||||
|
|
||||||
let mut install = Install::from_shader_crate(crate_path.clone());
|
let install = Install::from_shader_crate(crate_path.clone())
|
||||||
install.build_script = true;
|
.within_build_script()
|
||||||
install.auto_install_rust_toolchain = true;
|
.run()?;
|
||||||
let install = install.run()?;
|
|
||||||
|
|
||||||
let mut builder = install.to_spirv_builder(crate_path, "spirv-unknown-vulkan1.3");
|
let mut builder = install.to_spirv_builder(crate_path, "spirv-unknown-vulkan1.3");
|
||||||
builder.build_script.defaults = true;
|
builder.build_script.defaults = true;
|
||||||
builder.shader_panic_strategy = ShaderPanicStrategy::SilentExit;
|
builder.shader_panic_strategy = ShaderPanicStrategy::SilentExit;
|
||||||
builder.spirv_metadata = SpirvMetadata::Full;
|
builder.spirv_metadata = SpirvMetadata::Full;
|
||||||
|
builder.capabilities = vec![Capability::Int8, Capability::Int16, Capability::Int64];
|
||||||
|
|
||||||
let compile_result = builder.build()?;
|
let compile_result = builder.build()?;
|
||||||
let spv_path = compile_result.module.unwrap_single();
|
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(())
|
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