Something went wrong. Try again.
Ray Tracing in One Weekend + Ray Tracing GPU Edition
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148use std::sync::Arc;
use anyhow::Context;use anyhow::Result;
use wgpu::CurrentSurfaceTexture;use winit::{ application::ApplicationHandler, event::WindowEvent, event_loop::{ActiveEventLoop, ControlFlow, EventLoop}, window::{Window, WindowId},};
use raytracing::PathTracer;
const WIDTH: u32 = 800;const HEIGHT: u32 = 600;
struct RenderState<'a> { // Surface must live as long as the window it was created from window: Arc<Window>, surface: wgpu::Surface<'a>, renderer: PathTracer,}
#[derive(Default)]struct App<'a> { state: Option<RenderState<'a>>,}
async fn connect_to_gpu( window: Arc<Window>,) -> Result<(wgpu::Device, wgpu::Queue, wgpu::Surface<'static>)> { use wgpu::TextureFormat::{Bgra8Unorm, Rgba8Unorm}; let instance = wgpu::Instance::default();
let surface = instance .create_surface(window.clone()) .expect("Create surface.");
let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, force_fallback_adapter: false, compatible_surface: Some(&surface), }) .await .context("failed to find a compatible adapter")?;
let (device, queue) = adapter .request_device(&wgpu::DeviceDescriptor::default()) .await .context("failed to connect to the GPU")?;
let caps = surface.get_capabilities(&adapter);
let format = caps .formats .into_iter() .find(|it| matches!(it, Rgba8Unorm | Bgra8Unorm)) .context("could not find preferred texture format (Rgba8Unorm or Bgra8Unorm)")?;
let size = window.inner_size(); let config = wgpu::SurfaceConfiguration { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format, width: size.width, height: size.height, present_mode: wgpu::PresentMode::AutoVsync, alpha_mode: caps.alpha_modes[0], view_formats: vec![], desired_maximum_frame_latency: 3, }; surface.configure(&device, &config);
Ok((device, queue, surface))}
impl<'a> ApplicationHandler for App<'a> { fn resumed(&mut self, event_loop: &ActiveEventLoop) { if self.state.is_none() { let window_size = winit::dpi::PhysicalSize::new(WIDTH, HEIGHT); let attributes = Window::default_attributes() .with_inner_size(window_size) .with_resizable(false) .with_title("GPU Path Tracer");
let window = Arc::new( event_loop .create_window(attributes) .expect("Create window."), );
let (device, queue, surface) = pollster::block_on(connect_to_gpu(window.clone())).expect("Connect to GPU."); let renderer = PathTracer::new(device, queue, WIDTH, HEIGHT);
self.state = Some(RenderState { window, surface, renderer, }) } }
fn window_event( &mut self, event_loop: &ActiveEventLoop, _window_id: WindowId, event: WindowEvent, ) { match event { WindowEvent::CloseRequested => event_loop.exit(), WindowEvent::RedrawRequested => { if let Some(state) = &self.state { match state.surface.get_current_texture() { CurrentSurfaceTexture::Success(frame) | CurrentSurfaceTexture::Suboptimal(frame) => { let render_target = frame .texture .create_view(&wgpu::TextureViewDescriptor::default()); state.renderer.render_frame(&render_target); frame.present(); state.window.request_redraw(); } CurrentSurfaceTexture::Outdated => {} CurrentSurfaceTexture::Lost => {} CurrentSurfaceTexture::Timeout | CurrentSurfaceTexture::Occluded => {} CurrentSurfaceTexture::Validation => {} } } } _ => (), } }}
#[pollster::main]async fn main() -> Result<()> { let event_loop = EventLoop::new()?; event_loop.set_control_flow(ControlFlow::Poll);
let mut app = App::default(); event_loop.run_app(&mut app)?;
Ok(())}