wgpu now working

This commit is contained in:
STP
2023-11-15 19:50:13 -05:00
parent 4762edbe03
commit 362c5160f4
8 changed files with 451 additions and 1405 deletions

1364
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -13,9 +13,5 @@ anyhow = "1.0"
nalgebra = "0.32.3" nalgebra = "0.32.3"
roots = "0.0.8" roots = "0.0.8"
pyo3 = "0.20.0" pyo3 = "0.20.0"
imgui = "0.11" winit = "0.28"
imgui-wgpu = "0.24" wgpu = "0.18"
imgui-winit-support = "0.11"
winit_input_helper = "0.13"
winit = "0.29.3"
wgpu = "0.18.0"

View File

@@ -1,31 +1,26 @@
struct VertexInput { struct VertexInput {
@location(0) position: vec3<f32>, @location(0) position: vec3<f32>,
@location(1) tex_coords: vec2<f32>, @location(1) color: vec3<f32>,
} };
struct VertexOutput { struct VertexOutput {
@builtin(position) clip_position: vec4<f32>, @builtin(position) clip_position: vec4<f32>,
@location(0) tex_coords: vec2<f32>, @location(0) color: vec3<f32>,
} };
@vertex @vertex
fn vs_main( fn vs_main(
model: VertexInput, model: VertexInput,
) -> VertexOutput { ) -> VertexOutput {
var out: VertexOutput; var out: VertexOutput;
out.tex_coords = model.tex_coords; out.color = model.color;
out.clip_position = vec4<f32>(model.position, 1.0); out.clip_position = vec4<f32>(model.position, 1.0);
return out; return out;
} }
// Fragment shader // Fragment shader
@group(0) @binding(0)
var t_diffuse: texture_2d<f32>;
@group(0)@binding(1)
var s_diffuse: sampler;
@fragment @fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> { fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return textureSample(t_diffuse, s_diffuse, in.tex_coords); return vec4<f32>(in.color, 1.0);
} }

72
src/eventloop.rs Normal file
View File

@@ -0,0 +1,72 @@
use crate::state::State;
use core::iter;
use nalgebra::{Point3, Vector3};
use std::sync::Arc;
use std::time::Instant;
use pollster::block_on;
use wgpu::util::DeviceExt;
use winit::{
dpi::LogicalSize,
event::{ElementState, Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::Window,
};
use crate::light::Light;
use crate::primitive::Material;
use crate::{camera::Camera, primitive::*, raytracer, scene::Scene};
pub async fn run() {
env_logger::init();
// Set up window and GPU
let event_loop = EventLoop::new();
let window = Window::new(&event_loop).unwrap();
window.set_title(&format!("imgui-wgpu"));
let mut state = State::new(window).await;
event_loop.run(move |event, _, control_flow| {
match event {
Event::WindowEvent {
ref event,
window_id,
} if window_id == state.window().id() => {
if !state.input(event) {
match event {
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
WindowEvent::KeyboardInput { input, .. } => {
*control_flow = ControlFlow::Exit
}
WindowEvent::Resized(physical_size) => {
state.resize(*physical_size);
}
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
state.resize(**new_inner_size);
}
_ => {}
}
}
}
Event::RedrawRequested(window_id) if window_id == state.window().id() => {
state.update();
match state.render() {
Ok(_) => {}
// Reconfigure the surface if it's lost or outdated
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
state.resize(state.size)
}
// The system is out of memory, we should probably quit
Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit,
// We're ignoring timeouts
Err(wgpu::SurfaceError::Timeout) => log::warn!("Surface timeout"),
}
}
Event::MainEventsCleared => {
// RedrawRequested will only trigger once, unless we manually
// request it.
state.window().request_redraw();
}
_ => {}
}
});
}

7
src/gui.rs Normal file
View File

@@ -0,0 +1,7 @@
struct ImguiDemo {
canvas: framework::ShaderCanvas,
imgui: imgui::Context,
platform: imgui_winit_support::WinitPlatform,
renderer: Renderer,
last_cursor: Option<MouseCursor>,
}

View File

@@ -2,16 +2,17 @@
#![allow(unused_imports)] #![allow(unused_imports)]
#![allow(unused_variables)] #![allow(unused_variables)]
//Use linear algebra module //Use linear algebra module
use window::run; use eventloop::run;
//Cameras //Cameras
mod camera; mod camera;
mod eventloop;
mod light; mod light;
mod primitive; mod primitive;
mod ray; mod ray;
mod raytracer; mod raytracer;
mod scene; mod scene;
mod window; mod state;
// mod state; // mod state;
// mod texture; // mod texture;
// mod vertex; // mod vertex;
@@ -20,5 +21,5 @@ const EPSILON: f32 = 1e-7;
const INFINITY: f32 = 1e7; const INFINITY: f32 = 1e7;
fn main() { fn main() {
run().expect("YEY"); pollster::block_on(run());
} }

266
src/state.rs Normal file
View File

@@ -0,0 +1,266 @@
use core::iter;
use nalgebra::{Point3, Vector3};
use std::sync::Arc;
use std::time::Instant;
use pollster::block_on;
use wgpu::util::DeviceExt;
use winit::{
dpi::LogicalSize,
event::{ElementState, Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::Window,
};
use crate::light::Light;
use crate::primitive::Material;
use crate::{camera::Camera, primitive::*, raytracer, scene::Scene};
struct Vertex {
position: [f32; 3],
color: [f32; 3],
}
impl Vertex {
fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
],
}
}
}
pub struct State {
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
config: wgpu::SurfaceConfiguration,
pub size: winit::dpi::PhysicalSize<u32>,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
window: Window,
}
impl State {
pub async fn new(window: Window) -> Self {
let size = window.inner_size();
// The instance is a handle to our GPU
// BackendBit::PRIMARY => Vulkan + Metal + DX12 + Browser WebGPU
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
..Default::default()
});
// # Safety
//
// The surface needs to live as long as the window that created it.
// State owns the window so this should be safe.
let surface = unsafe { instance.create_surface(&window) }.unwrap();
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
compatible_surface: Some(&surface),
force_fallback_adapter: false,
})
.await
.unwrap();
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
label: None,
features: wgpu::Features::empty(),
// WebGL doesn't support all of wgpu's features, so if
// we're building for the web we'll have to disable some.
limits: if cfg!(target_arch = "wasm32") {
wgpu::Limits::downlevel_webgl2_defaults()
} else {
wgpu::Limits::default()
},
},
None, // Trace path
)
.await
.unwrap();
let surface_caps = surface.get_capabilities(&adapter);
// Shader code in this tutorial assumes an Srgb surface texture. Using a different
// one will result all the colors comming out darker. If you want to support non
// Srgb surfaces, you'll need to account for that when drawing to the frame.
//
let surface_format = surface_caps
.formats
.iter()
.copied()
.find(|f| f.is_srgb())
.unwrap_or(surface_caps.formats[0]);
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
width: size.width,
height: size.height,
present_mode: surface_caps.present_modes[0],
alpha_mode: surface_caps.alpha_modes[0],
view_formats: vec![],
};
surface.configure(&device, &config);
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("2d.wgsl").into()),
});
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main",
buffers: &[Vertex::desc()],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
targets: &[Some(wgpu::ColorTargetState {
format: config.format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent::REPLACE,
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Back),
// Setting this to anything other than Fill requires Features::POLYGON_MODE_LINE
// or Features::POLYGON_MODE_POINT
polygon_mode: wgpu::PolygonMode::Fill,
// Requires Features::DEPTH_CLIP_CONTROL
unclipped_depth: false,
// Requires Features::CONSERVATIVE_RASTERIZATION
conservative: false,
},
depth_stencil: None,
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
// If the pipeline will be used with a multiview render pass, this
// indicates how many array layers the attachments will have.
multiview: None,
});
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Vertex Buffer"),
contents: &[1],
usage: wgpu::BufferUsages::VERTEX,
});
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Index Buffer"),
contents: &[1],
usage: wgpu::BufferUsages::INDEX,
});
Self {
surface,
device,
queue,
config,
size,
render_pipeline,
vertex_buffer,
index_buffer,
window,
}
}
pub fn window(&self) -> &Window {
&self.window
}
pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
if new_size.width > 0 && new_size.height > 0 {
self.size = new_size;
self.config.width = new_size.width;
self.config.height = new_size.height;
self.surface.configure(&self.device, &self.config);
}
}
#[allow(unused_variables)]
pub fn input(&mut self, event: &WindowEvent) -> bool {
false
}
pub fn update(&mut self) {}
pub fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
let output = self.surface.get_current_texture()?;
let view = output
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
{
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.3,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
}
self.queue.submit(iter::once(encoder.finish()));
output.present();
Ok(())
}
}

View File

@@ -1,115 +0,0 @@
use nalgebra::{Point3, Vector3};
use std::sync::Arc;
use std::time::Instant;
use wgpu::util::DeviceExt;
use winit::{
error::EventLoopError,
event::*,
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
};
use crate::light::Light;
use crate::primitive::Material;
use crate::{camera::Camera, primitive::*, raytracer, scene::Scene};
pub fn run() -> Result<(), EventLoopError> {
// Create an event loop and window using winit
let event_loop = EventLoop::new().expect("Could not make event loop");
let window = WindowBuilder::new().build(&event_loop).unwrap();
let window_size = &window.inner_size();
//Environment variables
let mut height = window_size.height;
let mut width = window_size.width;
event_loop.run(move |event, elwt| {
match event {
Event::WindowEvent {
ref event,
window_id,
} if window_id == window.id() => {
match event {
WindowEvent::CloseRequested => elwt.exit(),
WindowEvent::Resized(physical_size) => {
width = physical_size.width;
height = physical_size.height;
// draw_pixels(&mut pixels, 400, 400);
}
WindowEvent::ScaleFactorChanged {
inner_size_writer, ..
} => {}
WindowEvent::KeyboardInput { event, .. } => {
println!("{}", event.logical_key.to_text().unwrap());
}
WindowEvent::RedrawRequested => {}
_ => {}
}
}
_ => {}
}
})
}
// fn clear_pixels(pixels: &mut Pixels) {
// let frame = pixels.frame_mut();
// for pixel in frame.chunks_exact_mut(4) {
// pixel[0] = 0x00; // R
// pixel[1] = 0x00; // G
// pixel[2] = 0x00; // B
// pixel[3] = 0xff; // A
// }
// if pixels.render().is_err() {
// eprintln!("Failed to render frame");
// }
// }
//
// fn draw_pixels(pixels: &mut Pixels, width: u32, height: u32) {
// //Create our scene
// let eye = Point3::new(0.0, 0.0, -1.0);
// let target = Point3::new(0.0, 0.0, 0.0);
// let up = Vector3::new(0.0, 1.0, 0.0);
// let arc_camera = Arc::new(Camera::new(eye, target, up, 90.0, (width / height) as f32));
// let cameras: Vec<Arc<Camera>> = vec![arc_camera.clone()];
//
// let arc_material = Arc::new(Material::magenta());
// let arc_cone = Arc::new(Cone::unit(arc_material));
// let primitives: Vec<Arc<dyn Primitive>> = vec![arc_cone]
// .into_iter()
// .map(|arc| arc as Arc<dyn Primitive>)
// .collect();
//
// let light: Arc<Light>;
// let light = Arc::new(Light::white());
// let lights = vec![light];
//
// let ambient_light = Arc::new(Vector3::new(1.0, 1.0, 1.0));
//
// let scene = Scene::new(primitives, lights, cameras, ambient_light);
//
// let rays = arc_camera.as_ref().cast_rays(width, height);
//
// let colours = raytracer::shade_rays(&scene, &rays, width, height);
//
// print!("{}", colours.len());
//
// let pixels = pixels.frame().chunks_exact_mut(4);
// for (i, colour) in colours.iter().enumerate() {
// let colour = colours[i];
// let pixel = &mut pixels[i];
// pixel[0] = colour.x;
// pixel[1] = colour.y;
// pixel[2] = colour.z;
// }
//
// // Render the frame
// if pixels.render().is_err() {
// eprintln!("Failed to render frame");
// }
// }
// // Create a Pixels instance for drawing
// let mut pixels = {
// let surface_texture = SurfaceTexture::new(window_size.width, window_size.height, &window);
// Pixels::new(width, height, surface_texture).unwrap()
// };