Initial compute/vertex/fragment render system
This commit is contained in:
commit
203435ca72
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
.idea/
|
||||
.vscode/
|
||||
target/
|
2955
Cargo.lock
generated
Normal file
2955
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
30
Cargo.toml
Normal file
30
Cargo.toml
Normal file
@ -0,0 +1,30 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"crates/flare",
|
||||
"crates/flare-shader",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
authors = []
|
||||
edition = "2021"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
|
||||
|
||||
[workspace.dependencies]
|
||||
anyhow = "1.0"
|
||||
bytemuck = { version = "1.21", features = ["derive"] }
|
||||
env_logger = "0.11"
|
||||
futures-executor = "0.3"
|
||||
glam = { version = "0.29", features = ["bytemuck", "libm"], default-features = false }
|
||||
spirv-std = { git = "https://github.com/rust-gpu/rust-gpu", rev = "854e9ba7da26d52ca0038ab2c7b252652e4d6b1e" }
|
||||
#spirv-builder = { git = "https://github.com/rust-gpu/rust-gpu", rev = "854e9ba7da26d52ca0038ab2c7b252652e4d6b1e"}
|
||||
spirv-builder = { git = "https://github.com/rust-gpu/rust-gpu", rev = "854e9ba7da26d52ca0038ab2c7b252652e4d6b1e", features = ["use-installed-tools"], default-features = false }
|
||||
wgpu = { version = "24.0", features = ["spirv"] }
|
||||
winit = "0.30"
|
||||
|
||||
[profile.release.build-override]
|
||||
opt-level = 3
|
201
LICENSE-APACHE
Normal file
201
LICENSE-APACHE
Normal file
@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
23
LICENSE-MIT
Normal file
23
LICENSE-MIT
Normal file
@ -0,0 +1,23 @@
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
1
clippy.toml
Normal file
1
clippy.toml
Normal file
@ -0,0 +1 @@
|
||||
avoid-breaking-exported-api = false
|
17
crates/flare-shader/Cargo.toml
Normal file
17
crates/flare-shader/Cargo.toml
Normal file
@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "flare-shader"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
crate-type = ["dylib", "lib"]
|
||||
|
||||
[dependencies]
|
||||
bytemuck.workspace = true
|
||||
glam.workspace = true
|
||||
spirv-std.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
141
crates/flare-shader/src/lib.rs
Normal file
141
crates/flare-shader/src/lib.rs
Normal file
@ -0,0 +1,141 @@
|
||||
#![cfg_attr(target_arch = "spirv", no_std)]
|
||||
|
||||
use glam::{UVec2, Vec4, Vec4Swizzles, uvec2, vec2, vec4};
|
||||
use spirv_std::spirv;
|
||||
|
||||
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct IfsConstants {
|
||||
accum_width: u32,
|
||||
accum_height: u32,
|
||||
viewport_width: u32,
|
||||
viewport_height: u32,
|
||||
background_color: Vec4,
|
||||
}
|
||||
|
||||
impl IfsConstants {
|
||||
pub fn new(
|
||||
accum_width: u32,
|
||||
accum_height: u32,
|
||||
viewport_width: u32,
|
||||
viewport_height: u32,
|
||||
background_color: Vec4,
|
||||
) -> Self {
|
||||
Self {
|
||||
accum_width,
|
||||
accum_height,
|
||||
viewport_width,
|
||||
viewport_height,
|
||||
background_color,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn viewport_dimensions(&self) -> UVec2 {
|
||||
uvec2(self.viewport_width, self.viewport_height)
|
||||
}
|
||||
|
||||
pub fn with_accumulate(&mut self, width: u32, height: u32) {
|
||||
self.accum_width = width;
|
||||
self.accum_height = height;
|
||||
}
|
||||
|
||||
pub fn with_viewport(&mut self, width: u32, height: u32) {
|
||||
self.viewport_width = width;
|
||||
self.viewport_height = height;
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Color {
|
||||
type Element;
|
||||
const BLACK: Self;
|
||||
|
||||
const WHITE: Self;
|
||||
}
|
||||
|
||||
impl Color for Vec4 {
|
||||
type Element = f32;
|
||||
|
||||
const BLACK: Self = vec4(0., 0., 0., 1.);
|
||||
const WHITE: Self = vec4(1., 1., 1., 1.);
|
||||
}
|
||||
|
||||
pub(crate) fn image_index(pixel_x: usize, pixel_y: usize, image_width: u32) -> usize {
|
||||
pixel_x + pixel_y * image_width as usize
|
||||
}
|
||||
|
||||
#[spirv(compute(threads(1)))]
|
||||
pub fn main_cs(
|
||||
#[spirv(push_constant)] constants: &IfsConstants,
|
||||
#[spirv(storage_buffer, descriptor_set = 0, binding = 0)] accum_image: &mut [Vec4],
|
||||
) {
|
||||
let block_size = 64;
|
||||
for i_width in 0..constants.accum_width as usize {
|
||||
for i_height in 0..constants.accum_height as usize {
|
||||
let color = if (i_width / block_size % 2 == 1) != (i_height / block_size % 2 == 1) {
|
||||
Vec4::BLACK
|
||||
} else {
|
||||
Vec4::WHITE
|
||||
};
|
||||
|
||||
accum_image[image_index(i_width, i_height, constants.accum_width)] = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[spirv(vertex)]
|
||||
pub fn main_vs(
|
||||
#[spirv(vertex_index)] vert_id: u32,
|
||||
#[spirv(position, invariant)] position: &mut Vec4,
|
||||
) {
|
||||
// Create a "quad" that fills the viewport for the fragment shader.
|
||||
// The `draw` call issued by the main application will be for three vertex ID's (0, 1, 2).
|
||||
// This code maps them to the points (-1, -1), (3, -1), and (-1, 3) respectively.
|
||||
// Because the interior of that triangle covers the entire viewport,
|
||||
// the GPU clips to the viewport and invokes the fragment shader for each pixel.
|
||||
// https://stackoverflow.com/a/59739538
|
||||
// https://www.saschawillems.de/blog/2016/08/13/vulkan-tutorial-on-rendering-a-fullscreen-quad-without-buffers/
|
||||
let output_uv = vec2(((vert_id << 1) & 2) as f32, (vert_id & 2) as f32);
|
||||
*position = (output_uv * 2.0 - 1.0, 0.0, 1.0).into();
|
||||
}
|
||||
|
||||
#[spirv(fragment)]
|
||||
pub fn main_fs(
|
||||
#[spirv(frag_coord)] frag_coord: Vec4,
|
||||
#[spirv(push_constant)] ifs_constants: &IfsConstants,
|
||||
#[spirv(storage_buffer, descriptor_set = 0, binding = 0)] accum_image: &[Vec4],
|
||||
output: &mut Vec4,
|
||||
) {
|
||||
// Bootleg texture sampling; map from viewport image pixel coordinates to accumulator image
|
||||
// pixel coordinates
|
||||
let viewport_coordinate = frag_coord.xy().as_uvec2();
|
||||
|
||||
let a_width = ifs_constants.accum_width as f32;
|
||||
let a_height = ifs_constants.accum_height as f32;
|
||||
let v_width = ifs_constants.viewport_width as f32;
|
||||
let v_height = ifs_constants.viewport_height as f32;
|
||||
|
||||
// Scale both width and height by the same factor; preserves aspect ratio
|
||||
let scale_width = a_width / v_width;
|
||||
let scale_height = a_height / v_height;
|
||||
let scale = scale_width.max(scale_height);
|
||||
|
||||
// Re-center the image in the viewport after scale
|
||||
let offset_x = (v_width * scale - a_width) / 2.0;
|
||||
let offset_y = (v_height * scale - a_height) / 2.0;
|
||||
|
||||
let accum_coordinate = viewport_coordinate.as_vec2() * scale - vec2(offset_x, offset_y);
|
||||
|
||||
if accum_coordinate.x < 0.0
|
||||
|| accum_coordinate.x >= ifs_constants.accum_width as f32
|
||||
|| accum_coordinate.y < 0.0
|
||||
|| accum_coordinate.y >= ifs_constants.accum_height as f32
|
||||
{
|
||||
*output = ifs_constants.background_color;
|
||||
} else {
|
||||
*output = accum_image[image_index(
|
||||
accum_coordinate.x as usize,
|
||||
accum_coordinate.y as usize,
|
||||
ifs_constants.accum_width,
|
||||
)];
|
||||
}
|
||||
}
|
22
crates/flare/Cargo.toml
Normal file
22
crates/flare/Cargo.toml
Normal file
@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "flare"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
bytemuck.workspace = true
|
||||
env_logger.workspace = true
|
||||
flare-shader = { path = "../flare-shader" }
|
||||
futures-executor.workspace = true
|
||||
glam.workspace = true
|
||||
wgpu.workspace = true
|
||||
winit.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
spirv-builder.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
18
crates/flare/build.rs
Normal file
18
crates/flare/build.rs
Normal file
@ -0,0 +1,18 @@
|
||||
use spirv_builder::{MetadataPrintout, SpirvBuilder};
|
||||
use std::path::PathBuf;
|
||||
use std::{env, fs};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let result = SpirvBuilder::new("../flare-shader", "spirv-unknown-vulkan1.1")
|
||||
.print_metadata(MetadataPrintout::Full)
|
||||
.release(false)
|
||||
.build()?;
|
||||
|
||||
// Copy the SPIR-V to this crate's output directory
|
||||
let shader_path = result.module.unwrap_single();
|
||||
let output_path = PathBuf::from(env::var("OUT_DIR")?).join("flare.spv");
|
||||
fs::copy(shader_path, &output_path)?;
|
||||
|
||||
println!("Generated shader; path={}", output_path.display());
|
||||
Ok(())
|
||||
}
|
421
crates/flare/src/main.rs
Normal file
421
crates/flare/src/main.rs
Normal file
@ -0,0 +1,421 @@
|
||||
use flare_shader::{Color, IfsConstants};
|
||||
use futures_executor::block_on;
|
||||
use glam::Vec4;
|
||||
use std::sync::Arc;
|
||||
use wgpu::{
|
||||
Adapter, Device, Features, Instance, Queue, ShaderModule, Surface, SurfaceConfiguration,
|
||||
};
|
||||
use winit::event::MouseButton;
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
dpi::LogicalSize,
|
||||
event::WindowEvent,
|
||||
event_loop::{ActiveEventLoop, EventLoop},
|
||||
window::{Window, WindowAttributes, WindowId},
|
||||
};
|
||||
|
||||
struct AccumulatePipeline {
|
||||
pipeline: wgpu::ComputePipeline,
|
||||
}
|
||||
|
||||
impl AccumulatePipeline {
|
||||
pub fn new(device: &Device, module: &ShaderModule) -> Self {
|
||||
let bindgroup_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("accumulate"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
count: None,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
},
|
||||
}],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("accumulate"),
|
||||
bind_group_layouts: &[&bindgroup_layout],
|
||||
push_constant_ranges: &[wgpu::PushConstantRange {
|
||||
stages: wgpu::ShaderStages::COMPUTE,
|
||||
range: 0..size_of::<IfsConstants>() as u32,
|
||||
}],
|
||||
});
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("accumulate"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module,
|
||||
entry_point: Some("main_cs"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self { pipeline }
|
||||
}
|
||||
}
|
||||
|
||||
struct AccumulatePass {
|
||||
accum_buffer: wgpu::Buffer,
|
||||
bind_group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
impl AccumulatePass {
|
||||
pub fn new(device: &Device, pipeline: &AccumulatePipeline, dimensions: (u32, u32)) -> Self {
|
||||
let pixels = dimensions.0 * dimensions.1;
|
||||
let elements = pixels * 4;
|
||||
let accum_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("accumulate"),
|
||||
size: elements as u64 * size_of::<f32>() as u64,
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("accumulate"),
|
||||
layout: &pipeline.pipeline.get_bind_group_layout(0),
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: accum_buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
Self {
|
||||
accum_buffer,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RenderPipeline {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
}
|
||||
|
||||
impl RenderPipeline {
|
||||
pub fn new(device: &Device, module: &ShaderModule, format: wgpu::TextureFormat) -> Self {
|
||||
let bindgroup_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("render"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
count: None,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: true },
|
||||
},
|
||||
}],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("render"),
|
||||
bind_group_layouts: &[&bindgroup_layout],
|
||||
push_constant_ranges: &[wgpu::PushConstantRange {
|
||||
stages: wgpu::ShaderStages::FRAGMENT,
|
||||
range: 0..size_of::<IfsConstants>() as u32,
|
||||
}],
|
||||
});
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("render"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module,
|
||||
entry_point: Some("main_vs"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
primitive: Default::default(),
|
||||
depth_stencil: None,
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module,
|
||||
entry_point: Some("main_fs"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: None,
|
||||
write_mask: Default::default(),
|
||||
})],
|
||||
}),
|
||||
multiview: None,
|
||||
cache: None,
|
||||
});
|
||||
Self { pipeline }
|
||||
}
|
||||
}
|
||||
|
||||
struct RenderPass {
|
||||
bind_group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
impl RenderPass {
|
||||
pub fn new(device: &Device, pipeline: &RenderPipeline, accum_buffer: &wgpu::Buffer) -> Self {
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("render"),
|
||||
layout: &pipeline.pipeline.get_bind_group_layout(0),
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: accum_buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
Self { bind_group }
|
||||
}
|
||||
}
|
||||
|
||||
struct Flare {
|
||||
instance: Instance,
|
||||
adapter: Adapter,
|
||||
device: Device,
|
||||
queue: Queue,
|
||||
module: ShaderModule,
|
||||
}
|
||||
|
||||
impl Flare {
|
||||
pub fn new() -> Self {
|
||||
let backends = wgpu::Backends::from_env().unwrap_or_default();
|
||||
let instance = Instance::new(&wgpu::InstanceDescriptor {
|
||||
backends,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::HighPerformance,
|
||||
force_fallback_adapter: false,
|
||||
compatible_surface: None,
|
||||
});
|
||||
let adapter = block_on(adapter).expect("Failed to find GPU adapter");
|
||||
|
||||
let required_limits = wgpu::Limits {
|
||||
max_push_constant_size: size_of::<IfsConstants>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let device = adapter.request_device(
|
||||
&wgpu::DeviceDescriptor {
|
||||
label: Some("flare"),
|
||||
required_features: Features::TIMESTAMP_QUERY | Features::PUSH_CONSTANTS,
|
||||
required_limits,
|
||||
memory_hints: Default::default(),
|
||||
},
|
||||
None,
|
||||
);
|
||||
let (device, queue) = block_on(device).expect("Failed to find GPU device");
|
||||
let module = device
|
||||
.create_shader_module(wgpu::include_spirv!(concat!(env!("OUT_DIR"), "/flare.spv")));
|
||||
|
||||
Flare {
|
||||
instance,
|
||||
adapter,
|
||||
device,
|
||||
queue,
|
||||
module,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FlareRender<'window> {
|
||||
flare: Arc<Flare>,
|
||||
surface: Surface<'window>,
|
||||
surface_configuration: SurfaceConfiguration,
|
||||
accumulate_pipeline: AccumulatePipeline,
|
||||
accumulate_pass: AccumulatePass,
|
||||
render_pipeline: RenderPipeline,
|
||||
render_pass: RenderPass,
|
||||
ifs_constants: IfsConstants,
|
||||
}
|
||||
|
||||
impl FlareRender<'_> {
|
||||
pub fn new(flare: Arc<Flare>, window: Arc<Window>) -> Self {
|
||||
let window_size = window.inner_size();
|
||||
|
||||
let surface = flare
|
||||
.instance
|
||||
.create_surface(window.clone())
|
||||
.expect("Unable to create surface");
|
||||
let mut surface_configuration = surface
|
||||
.get_default_config(&flare.adapter, window_size.width, window_size.height)
|
||||
.expect("Unable to get surface config");
|
||||
surface_configuration.present_mode = wgpu::PresentMode::AutoVsync;
|
||||
surface.configure(&flare.device, &surface_configuration);
|
||||
|
||||
let accumulate_pipeline = AccumulatePipeline::new(&flare.device, &flare.module);
|
||||
let accumulate_pass = AccumulatePass::new(
|
||||
&flare.device,
|
||||
&accumulate_pipeline,
|
||||
(window_size.width, window_size.height),
|
||||
);
|
||||
let render_pipeline =
|
||||
RenderPipeline::new(&flare.device, &flare.module, surface_configuration.format);
|
||||
let render_pass = RenderPass::new(
|
||||
&flare.device,
|
||||
&render_pipeline,
|
||||
&accumulate_pass.accum_buffer,
|
||||
);
|
||||
let ifs_constants = IfsConstants::new(
|
||||
window_size.width,
|
||||
window_size.height,
|
||||
window_size.width,
|
||||
window_size.height,
|
||||
Vec4::BLACK,
|
||||
);
|
||||
|
||||
Self {
|
||||
flare,
|
||||
surface,
|
||||
surface_configuration,
|
||||
accumulate_pipeline,
|
||||
accumulate_pass,
|
||||
render_pipeline,
|
||||
render_pass,
|
||||
ifs_constants,
|
||||
}
|
||||
}
|
||||
|
||||
fn begin_accumulate(&self, encoder: &mut wgpu::CommandEncoder) {
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("accumulate"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
pass.set_pipeline(&self.accumulate_pipeline.pipeline);
|
||||
pass.set_push_constants(0, bytemuck::cast_slice(&[self.ifs_constants]));
|
||||
pass.set_bind_group(0, &self.accumulate_pass.bind_group, &[]);
|
||||
pass.dispatch_workgroups(1, 1, 1);
|
||||
}
|
||||
|
||||
fn begin_render(&self, encoder: &mut wgpu::CommandEncoder, output_view: &wgpu::TextureView) {
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("render"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: output_view,
|
||||
resolve_target: None,
|
||||
ops: Default::default(),
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
});
|
||||
|
||||
pass.set_pipeline(&self.render_pipeline.pipeline);
|
||||
pass.set_push_constants(
|
||||
wgpu::ShaderStages::FRAGMENT,
|
||||
0,
|
||||
bytemuck::cast_slice(&[self.ifs_constants]),
|
||||
);
|
||||
pass.set_bind_group(0, &self.render_pass.bind_group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
|
||||
pub fn render(&self, run_accumulate: bool) {
|
||||
let output = self
|
||||
.surface
|
||||
.get_current_texture()
|
||||
.expect("Failed to get current texture");
|
||||
let output_view = output.texture.create_view(&Default::default());
|
||||
let mut encoder = self
|
||||
.flare
|
||||
.device
|
||||
.create_command_encoder(&Default::default());
|
||||
|
||||
if run_accumulate {
|
||||
self.begin_accumulate(&mut encoder);
|
||||
}
|
||||
self.begin_render(&mut encoder, &output_view);
|
||||
|
||||
self.flare.queue.submit(Some(encoder.finish()));
|
||||
output.present();
|
||||
}
|
||||
|
||||
pub fn resize_accumulate(&mut self) {
|
||||
let vp_dimensions = self.ifs_constants.viewport_dimensions();
|
||||
self.accumulate_pass = AccumulatePass::new(
|
||||
&self.flare.device,
|
||||
&self.accumulate_pipeline,
|
||||
(vp_dimensions.x, vp_dimensions.y),
|
||||
);
|
||||
self.render_pass = RenderPass::new(
|
||||
&self.flare.device,
|
||||
&self.render_pipeline,
|
||||
&self.accumulate_pass.accum_buffer,
|
||||
);
|
||||
self.ifs_constants
|
||||
.with_accumulate(vp_dimensions.x, vp_dimensions.y);
|
||||
}
|
||||
|
||||
pub fn resize_viewport(&mut self, width: u32, height: u32) {
|
||||
self.surface_configuration.width = width;
|
||||
self.surface_configuration.height = height;
|
||||
self.surface
|
||||
.configure(&self.flare.device, &self.surface_configuration);
|
||||
self.ifs_constants.with_viewport(width, height);
|
||||
}
|
||||
}
|
||||
|
||||
struct Application<'window> {
|
||||
flare: Arc<Flare>,
|
||||
window: Option<Arc<Window>>,
|
||||
flare_render: Option<FlareRender<'window>>,
|
||||
}
|
||||
|
||||
impl Application<'_> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
flare: Arc::new(Flare::new()),
|
||||
window: None,
|
||||
flare_render: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler for Application<'_> {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let attributes = WindowAttributes::default()
|
||||
.with_title("Flare")
|
||||
.with_inner_size(LogicalSize::new(1024, 768));
|
||||
|
||||
let window = Arc::new(
|
||||
event_loop
|
||||
.create_window(attributes)
|
||||
.expect("Failed to create window"),
|
||||
);
|
||||
|
||||
self.window = Some(window.clone());
|
||||
|
||||
let flare_render = FlareRender::new(self.flare.clone(), window);
|
||||
flare_render.render(true);
|
||||
|
||||
self.flare_render = Some(flare_render);
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
_window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
match event {
|
||||
WindowEvent::Resized(size) => {
|
||||
let flare_render = self.flare_render.as_mut().unwrap();
|
||||
flare_render.resize_viewport(size.width, size.height);
|
||||
flare_render.render(false);
|
||||
}
|
||||
WindowEvent::MouseInput {
|
||||
button: MouseButton::Left,
|
||||
..
|
||||
} => {
|
||||
let flare_render = self.flare_render.as_mut().unwrap();
|
||||
flare_render.resize_accumulate();
|
||||
flare_render.render(true);
|
||||
}
|
||||
WindowEvent::CloseRequested => event_loop.exit(),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn main() -> anyhow::Result<()> {
|
||||
env_logger::init();
|
||||
let _module = wgpu::include_spirv!(concat!(env!("OUT_DIR"), "/flare.spv"));
|
||||
|
||||
let event_loop = EventLoop::new()?;
|
||||
let mut application = Application::new();
|
||||
event_loop.run_app(&mut application)?;
|
||||
|
||||
Ok(())
|
||||
}
|
4
rust-toolchain.toml
Normal file
4
rust-toolchain.toml
Normal file
@ -0,0 +1,4 @@
|
||||
[toolchain]
|
||||
channel = "nightly-2024-11-22"
|
||||
components = ["rust-src", "rustc-dev", "llvm-tools"]
|
||||
# commit_hash = b19329a37cedf2027517ae22c87cf201f93d776e
|
1
rustfmt.toml
Normal file
1
rustfmt.toml
Normal file
@ -0,0 +1 @@
|
||||
style_edition = "2024"
|
Loading…
Reference in New Issue
Block a user