Compare commits

..

No commits in common. "two-way" and "master" have entirely different histories.

20 changed files with 251 additions and 1590 deletions

View File

@ -1,9 +0,0 @@
BasedOnStyle: LLVM
UseTab: Always
TabWidth: 4
IndentWidth: 4
AccessModifierOffset: -4
IndentCaseLabels: false
ColumnLimit: 0
PointerAlignment: Left
PackConstructorInitializers: Never

1
.gitignore vendored
View File

@ -1,2 +1 @@
/target /target
/build

View File

@ -1,14 +0,0 @@
cmake_minimum_required(VERSION 3.18)
project(photon_light VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Qt6 REQUIRED COMPONENTS Gui Widgets)
find_program(CARGO cargo REQUIRED)
set(CARGO_TARGET_DIR "${CMAKE_BINARY_DIR}/cargo")
qt_standard_project_setup()
add_subdirectory(ui)

11
Cargo.lock generated
View File

@ -1165,17 +1165,6 @@ dependencies = [
"winit", "winit",
] ]
[[package]]
name = "photon-light-impl"
version = "0.1.0"
dependencies = [
"glam",
"photon-light",
"pollster",
"raw-window-handle",
"wgpu",
]
[[package]] [[package]]
name = "pin-project" name = "pin-project"
version = "1.1.10" version = "1.1.10"

View File

@ -1,6 +1,3 @@
[workspace]
members = ["ui"]
[package] [package]
name = "photon-light" name = "photon-light"
version = "0.1.0" version = "0.1.0"

View File

@ -1,401 +0,0 @@
#![feature(gen_blocks)]
use std::{convert::identity, error::Error, f32::consts::PI};
use glam::{Mat4, UVec2, Vec2, Vec3, vec3};
use rand_distr::Distribution as _;
use crate::{
camera::OrbitalCamera,
ray::Ray,
render::lines::{LookParams, Mesh, Pipeline, Vertex},
trace::{Hit, Lambertian, Reflector, Scene, Source, Sphere},
};
mod camera;
mod ray;
mod render;
mod trace;
const OUTPUT_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8UnormSrgb;
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub struct SphericalPosition {
pub yaw: f32,
pub pitch: f32,
pub distance: f32,
}
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct RedrawArgs {
pub camera_position: SphericalPosition,
pub light_position: SphericalPosition,
pub light_radius: f32,
pub light_spread: f32,
pub accum_sigma: f32,
pub accum_scale: f32,
pub reflections: u32,
pub show_axes: bool,
pub show_shapes: bool,
pub show_hit_emission: bool,
pub show_miss_emission: bool,
pub show_direct_hit: bool,
pub show_indirect_hit: bool,
pub show_light: bool,
}
pub struct Gpu {
device: wgpu::Device,
queue: wgpu::Queue,
surface: wgpu::Surface<'static>,
}
pub struct Core {
device: wgpu::Device,
queue: wgpu::Queue,
surface: wgpu::Surface<'static>,
pipeline: Pipeline,
tripod: Mesh,
}
pub fn new_tripod(device: &wgpu::Device) -> Mesh {
Mesh::new(
device,
&[
Vertex::new(vec3(0., 0., 0.), vec3(1., 0., 0.)),
Vertex::new(vec3(1., 0., 0.), vec3(1., 0., 0.)),
Vertex::new(vec3(0., 0., 0.), vec3(0., 1., 0.)),
Vertex::new(vec3(0., 1., 0.), vec3(0., 1., 0.)),
Vertex::new(vec3(0., 0., 0.), vec3(0., 0., 1.)),
Vertex::new(vec3(0., 0., 1.), vec3(0., 0., 1.)),
],
)
}
fn loop_list<T: Clone>(iter: impl IntoIterator<Item = T>) -> impl Iterator<Item = T> {
loop_list_ex(iter, identity, identity)
}
fn loop_list_ex<T: Clone, U>(
iter: impl IntoIterator<Item = T>,
mut fa: impl FnMut(T) -> U,
mut fb: impl FnMut(T) -> U,
) -> impl Iterator<Item = U> {
gen move {
let mut iter = iter.into_iter();
let Some(first) = iter.next() else { return };
yield fa(first.clone());
for item in iter {
yield fb(item.clone());
yield fa(item);
}
yield fb(first);
}
}
impl OrbitalCamera {
fn make_ray(&self, rng: &mut impl rand::Rng) -> Ray {
let off: f32 = rand_distr::StandardUniform.sample(rng);
let side: Vec2 = rand_distr::UnitCircle.sample(rng).into();
let m = self.transform().inverse();
let fwd = 1. - 0.1 * off;
let side_scale = (1. - fwd.powi(2)).sqrt();
let dir = Vec3::from((side_scale * side, fwd));
Ray {
base: self.position(),
dir: m.transform_vector3(dir),
}
}
}
impl Core {
pub fn new(gpu: Gpu) -> Self {
let Gpu {
device,
queue,
surface,
} = gpu;
let pipeline = Pipeline::new(&device, OUTPUT_FORMAT);
let tripod = new_tripod(&device);
queue.submit([]); // flush buffer updates
Self {
device,
queue,
surface,
pipeline,
tripod,
}
}
fn render(&self, output: &wgpu::Texture, args: &RedrawArgs) {
let camera = OrbitalCamera {
position_yaw: args.camera_position.yaw,
position_pitch: args.camera_position.pitch,
distance: args.camera_position.distance,
};
let aspect = {
let size = output.size();
let w = size.width as f32;
let h = size.height as f32;
w / h
};
let perspective = Mat4::perspective_lh(PI / 3., aspect, 1e-2, 1e2);
self.pipeline.set_look(
&self.queue,
LookParams {
m: perspective * camera.transform(),
},
);
self.queue.submit([]); // flush buffer updates
let view = output.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
..Default::default()
});
if args.show_axes {
self.pipeline.render(&mut pass, [&self.tripod]);
}
let source = Source {
position_yaw: args.light_position.yaw,
position_pitch: args.light_position.pitch,
distance: args.light_position.distance,
radius: args.light_radius,
spread: args.light_spread,
};
if args.show_shapes {
let contour: Vec<Vertex> = loop_list(source.contour(17))
.map(|pos| Vertex {
pos,
color: vec3(1., 1., 1.),
})
.collect();
self.pipeline
.render(&mut pass, [&Mesh::new(&self.device, &contour)]);
}
const BASE_R: f32 = 2.;
const BASE_POS: Vec3 = vec3(0., 0., -BASE_R);
const BASE: Sphere = Sphere {
position: vec3(0., 0., -BASE_R),
radius: BASE_R,
};
fn sphere(pos: Vec3) -> Sphere {
Sphere {
position: pos,
radius: BASE_POS.distance(pos) - BASE_R,
}
}
let scene = Scene {
objects: vec![
BASE,
sphere(vec3(0., 0., 0.1)),
sphere(vec3(0.3, 0., 0.1)),
sphere(vec3(0.1, 0.3, 0.1)),
],
};
let mut prng = rand_pcg::Pcg64::new(42, 0);
let source_rays: Vec<Ray> = (0..10240).map(|_| source.make_ray(&mut prng)).collect();
let camera_rays: Vec<Ray> = (0..10240).map(|_| camera.make_ray(&mut prng)).collect();
let mut source_ray_display: Vec<Vertex> = Vec::with_capacity(source_rays.len());
let mut hits: Vec<Hit> = Vec::with_capacity(source_rays.len());
for ray in source_rays {
if let Some(hit) = scene.trace_ray(ray) {
hits.push(hit);
if args.show_hit_emission {
source_ray_display.extend([
Vertex {
pos: ray.base,
color: vec3(1., 1., 1.),
},
Vertex {
pos: ray.base + 0.1 * ray.dir,
color: vec3(0., 1., 0.),
},
]);
}
if args.show_direct_hit {
source_ray_display.extend([
Vertex {
pos: hit.incident.base - 0.02 * hit.incident.dir,
color: vec3(0., 0., 1.),
},
Vertex {
pos: hit.incident.base,
color: vec3(1., 1., 1.),
},
]);
}
} else {
if args.show_miss_emission {
source_ray_display.extend([
Vertex {
pos: ray.base,
color: vec3(1., 1., 1.),
},
Vertex {
pos: ray.base + 0.1 * ray.dir,
color: vec3(1., 0., 0.),
},
]);
}
}
}
if args.reflections > 0 {
let mut hits1 = hits.clone();
for _ in 0..args.reflections {
let mut hits2: Vec<Hit> = Vec::with_capacity(hits1.len());
for hit in &hits1 {
let reflector = Lambertian;
let reflected = reflector.reflect(&mut prng, hit.normal, hit.incident.dir);
let ray = Ray::new(hit.incident.base, reflected);
let Some(hit2) = scene.trace_ray(ray) else {
continue;
};
hits2.push(hit2);
if args.show_indirect_hit {
source_ray_display.extend([
Vertex {
pos: hit2.incident.base - 0.02 * hit2.incident.dir,
color: vec3(1., 0., 1.),
},
Vertex {
pos: hit2.incident.base,
color: vec3(1., 1., 1.),
},
]);
}
}
hits.extend(&hits2);
hits1 = hits2;
}
}
let mut camera_ray_display: Vec<Vertex> = Vec::with_capacity(camera_rays.len());
if args.show_light {
let sigma2 = args.accum_sigma.powi(2);
let accum_normalizator = (2. * PI * sigma2).sqrt().recip();
for ray in camera_rays {
let Some(hit) = scene.trace_ray(ray) else {
continue;
};
let mut total_cd = 0.0f32;
for light_hit in &hits {
let d2 = hit.incident.base.distance_squared(light_hit.incident.base);
if d2 > 9. * sigma2 {
continue;
}
assert!(hit.normal.is_normalized());
assert!(hit.incident.dir.is_normalized());
let reflector = Lambertian;
let in_lm = 1.0;
let out_cd = in_lm
* hit.normal.dot(-hit.incident.dir)
* reflector.brdf(hit.normal, hit.incident.dir, -ray.dir);
let weight = accum_normalizator * (-0.5 * d2 / sigma2).exp();
total_cd += weight * out_cd;
}
let brightness = 3. * (1. - (1. + total_cd * args.accum_scale).recip());
let r = args.accum_sigma;
let color = vec3(brightness, brightness - 1., brightness - 2.)
.clamp(Vec3::splat(0.), Vec3::splat(1.));
let vertex = |off: Vec3| Vertex {
pos: hit.incident.base + r * off,
color,
};
camera_ray_display.extend([
vertex(-Vec3::X),
vertex(Vec3::X),
vertex(-Vec3::Y),
vertex(Vec3::Y),
vertex(-Vec3::Z),
vertex(Vec3::Z),
]);
}
}
if !source_ray_display.is_empty() {
self.pipeline
.render(&mut pass, [&Mesh::new(&self.device, &source_ray_display)]);
}
if !camera_ray_display.is_empty() {
self.pipeline
.render(&mut pass, [&Mesh::new(&self.device, &camera_ray_display)]);
}
drop(pass);
self.queue.submit(std::iter::once(encoder.finish()));
}
/// Configures the renderer for a given target size.
pub fn configure(&mut self, pixel_size: UVec2) {
self.surface.configure(
&self.device,
&wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
format: OUTPUT_FORMAT,
width: pixel_size.x,
height: pixel_size.y,
present_mode: wgpu::PresentMode::Fifo,
alpha_mode: wgpu::CompositeAlphaMode::Auto,
view_formats: vec![],
desired_maximum_frame_latency: 2,
},
);
}
/// Redraws the entire surface.
///
/// [`Self::configure`] must be called at least once before this.
pub fn redraw(&mut self, args: &RedrawArgs) {
let output = self.surface.get_current_texture().unwrap();
self.render(&output.texture, args);
output.present();
}
}
pub async fn init_gpu_inner<E: Error + 'static>(
make_surface: impl FnOnce(&wgpu::Instance) -> Result<wgpu::Surface<'static>, E>,
) -> Result<Gpu, Box<dyn Error>> {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::PRIMARY,
..Default::default()
});
let surface = make_surface(&instance)?;
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::default())
.await
.unwrap();
Ok(Gpu {
device,
queue,
surface,
})
}

View File

@ -1,7 +1,8 @@
use std::{f32::consts::PI, sync::Arc}; #![feature(gen_blocks)]
use glam::uvec2; use std::{convert::identity, error::Error, f32::consts::PI, sync::Arc};
use photon_light::{Core, RedrawArgs, SphericalPosition, init_gpu_inner};
use glam::{Mat4, Vec3, vec3};
use winit::{ use winit::{
application::ApplicationHandler, application::ApplicationHandler,
event::WindowEvent, event::WindowEvent,
@ -9,58 +10,236 @@ use winit::{
window::Window, window::Window,
}; };
use crate::{
camera::OrbitalCamera,
render::lines::{LookParams, Mesh, Pipeline, Vertex},
trace::{Scene, Source, Sphere},
};
mod camera;
mod ray;
mod render;
mod trace;
const TITLE: &str = "WGPU example"; const TITLE: &str = "WGPU example";
const OUTPUT_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8UnormSrgb;
struct MainWindow { struct MainWindow {
window: Arc<Window>, handle: Arc<Window>,
core: Core, device: wgpu::Device,
queue: wgpu::Queue,
surface: wgpu::Surface<'static>,
surface_configured: bool,
pipeline: Pipeline,
tripod: Mesh,
}
pub fn new_tripod(device: &wgpu::Device) -> Mesh {
Mesh::new(
device,
&[
Vertex::new(vec3(0., 0., 0.), vec3(1., 0., 0.)),
Vertex::new(vec3(1., 0., 0.), vec3(1., 0., 0.)),
Vertex::new(vec3(0., 0., 0.), vec3(0., 1., 0.)),
Vertex::new(vec3(0., 1., 0.), vec3(0., 1., 0.)),
Vertex::new(vec3(0., 0., 0.), vec3(0., 0., 1.)),
Vertex::new(vec3(0., 0., 1.), vec3(0., 0., 1.)),
],
)
}
fn loop_list<T: Clone>(iter: impl IntoIterator<Item = T>) -> impl Iterator<Item = T> {
loop_list_ex(iter, identity, identity)
}
fn loop_list_ex<T: Clone, U>(
iter: impl IntoIterator<Item = T>,
mut fa: impl FnMut(T) -> U,
mut fb: impl FnMut(T) -> U,
) -> impl Iterator<Item = U> {
gen move {
let mut iter = iter.into_iter();
let Some(first) = iter.next() else { return };
yield fa(first.clone());
for item in iter {
yield fb(item.clone());
yield fa(item);
}
yield fb(first);
}
} }
impl MainWindow { impl MainWindow {
fn new(event_loop: &ActiveEventLoop) -> Self { fn new(event_loop: &ActiveEventLoop) -> Self {
let window = event_loop let handle = event_loop
.create_window(Window::default_attributes().with_title(TITLE)) .create_window(Window::default_attributes().with_title(TITLE))
.unwrap(); .unwrap();
let window = Arc::new(window); let handle = Arc::new(handle);
let gpu = pollster::block_on(init_gpu_inner(|instance| {
instance.create_surface(Arc::clone(&window)) let (device, queue, surface) = pollster::block_on(init_gpu(Arc::clone(&handle))).unwrap();
})) let pipeline = Pipeline::new(&device, OUTPUT_FORMAT);
.unwrap(); let tripod = new_tripod(&device);
let mut core = Core::new(gpu); queue.submit([]); // flush buffer updates
core.configure(uvec2(1, 1));
Self { window, core } Self {
handle,
device,
queue,
surface,
surface_configured: false,
pipeline,
tripod,
}
}
fn render(&self, output: &wgpu::Texture) {
let camera = OrbitalCamera {
position_yaw: PI / 4.,
position_pitch: 0.5f32.sqrt().atan(),
distance: 3.0,
};
let aspect = {
let size = output.size();
let w = size.width as f32;
let h = size.height as f32;
w / h
};
let perspective = Mat4::perspective_lh(PI / 3., aspect, 1e-2, 1e2);
self.pipeline.set_look(
&self.queue,
LookParams {
m: perspective * camera.transform(),
},
);
self.queue.submit([]); // flush buffer updates
let view = output.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.8,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
..Default::default()
});
self.pipeline.render(&mut pass, [&self.tripod]);
let source = Source {
position_yaw: 0.0,
position_pitch: PI / 3.,
distance: 1.0,
radius: 0.125,
spread: 0.125,
};
let contour: Vec<Vertex> = loop_list(source.contour(17))
.map(|pos| Vertex {
pos,
color: vec3(1., 1., 1.),
})
.collect();
self.pipeline
.render(&mut pass, [&Mesh::new(&self.device, &contour)]);
const BASE_R: f32 = 2.;
const BASE_POS: Vec3 = vec3(0., 0., -BASE_R);
const BASE: Sphere = Sphere {
position: vec3(0., 0., -BASE_R),
radius: BASE_R,
};
fn sphere(pos: Vec3) -> Sphere {
Sphere {
position: pos,
radius: BASE_POS.distance(pos) - BASE_R,
}
}
let scene = Scene {
objects: vec![
BASE,
sphere(vec3(0., 0., 0.1)),
sphere(vec3(0.3, 0., 0.1)),
sphere(vec3(0.1, 0.3, 0.1)),
],
};
let mut prng = rand_pcg::Pcg64::new(42, 0);
let rays: Vec<Vertex> = (0..10000)
.flat_map(|_| {
let ray = source.make_ray(&mut prng);
if let Some(ray) = scene.trace_ray(ray) {
[
Vertex {
pos: ray.base - 0.02 * ray.dir,
color: vec3(1., 1., 1.),
},
Vertex {
pos: ray.base,
color: vec3(0., 1., 0.),
},
]
} else {
[
Vertex {
pos: ray.base,
color: vec3(1., 1., 1.),
},
Vertex {
pos: ray.base + 0.1 * ray.dir,
color: vec3(1., 0., 0.),
},
]
}
})
.collect();
self.pipeline
.render(&mut pass, [&Mesh::new(&self.device, &rays)]);
drop(pass);
self.queue.submit(std::iter::once(encoder.finish()));
} }
fn event(&mut self, event_loop: &ActiveEventLoop, event: WindowEvent) { fn event(&mut self, event_loop: &ActiveEventLoop, event: WindowEvent) {
match event { match event {
WindowEvent::CloseRequested => event_loop.exit(), WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::Resized(physical_size) => self WindowEvent::Resized(physical_size) => {
.core self.surface.configure(
.configure(uvec2(physical_size.width, physical_size.height)), &self.device,
WindowEvent::RedrawRequested => self.core.redraw(&RedrawArgs { &wgpu::SurfaceConfiguration {
camera_position: SphericalPosition { usage: wgpu::TextureUsages::RENDER_ATTACHMENT
yaw: PI / 4., | wgpu::TextureUsages::COPY_DST,
pitch: 0.5f32.sqrt().atan(), format: OUTPUT_FORMAT,
distance: 3.0, width: physical_size.width,
}, height: physical_size.height,
light_position: SphericalPosition { present_mode: wgpu::PresentMode::Fifo,
yaw: 0.0, alpha_mode: wgpu::CompositeAlphaMode::Auto,
pitch: PI / 3., view_formats: vec![],
distance: 1.0, desired_maximum_frame_latency: 2,
}, },
light_radius: 0.125, );
light_spread: 0.125, self.surface_configured = true;
accum_sigma: 0.025, }
accum_scale: 0.01, WindowEvent::RedrawRequested => {
reflections: 2, if !self.surface_configured {
show_axes: true, return;
show_shapes: true, }
show_hit_emission: false, let output = self.surface.get_current_texture().unwrap();
show_miss_emission: false, self.render(&output.texture);
show_direct_hit: false, output.present();
show_indirect_hit: false, }
show_light: true,
}),
_ => {} _ => {}
} }
} }
@ -91,11 +270,34 @@ impl ApplicationHandler for Application {
.main_window .main_window
.as_mut() .as_mut()
.expect("window must exist to recieve events"); .expect("window must exist to recieve events");
assert_eq!(window.window.id(), window_id); assert_eq!(window.handle.id(), window_id);
window.event(event_loop, event); window.event(event_loop, event);
} }
} }
async fn init_gpu<'window>(
wnd: impl wgpu::WindowHandle + 'window,
) -> Result<(wgpu::Device, wgpu::Queue, wgpu::Surface<'window>), Box<dyn Error>> {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::PRIMARY,
..Default::default()
});
let surface = instance.create_surface(wnd)?;
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::default())
.await
.unwrap();
Ok((device, queue, surface))
}
fn main() { fn main() {
let event_loop = EventLoop::new().unwrap(); let event_loop = EventLoop::new().unwrap();
event_loop.set_control_flow(ControlFlow::Wait); event_loop.set_control_flow(ControlFlow::Wait);

View File

@ -1,7 +1,7 @@
use std::f32::consts::PI; use std::f32::consts::PI;
use glam::{Mat4, Vec2, Vec3, vec3}; use glam::{Mat4, Vec2, Vec3, vec3};
use rand_distr::{Distribution, UnitSphere}; use rand_distr::Distribution;
use crate::{camera::OrbitalCamera, ray::Ray}; use crate::{camera::OrbitalCamera, ray::Ray};
@ -78,14 +78,8 @@ pub struct Sphere {
pub radius: f32, pub radius: f32,
} }
struct Hit1 {
pos: Vec3,
dist: f32,
normal: Vec3,
}
impl Sphere { impl Sphere {
fn trace_ray(&self, ray: Ray) -> Option<Hit1> { fn trace_ray(&self, ray: Ray) -> Option<f32> {
// let t: f32; // let t: f32;
// let hit = ray.base + t * ray.dir; // let hit = ray.base + t * ray.dir;
// (hit - self.position).length() == self.radius; // (hit - self.position).length() == self.radius;
@ -100,10 +94,7 @@ impl Sphere {
if d4 < 0. { if d4 < 0. {
return None; return None;
} }
let dist = (-b2 - d4.sqrt()) / a; Some((-b2 - d4.sqrt()) / a)
let pos = ray.advance(dist).base;
let normal = (pos - self.position).normalize();
Some(Hit1 { pos, dist, normal })
} }
} }
@ -112,51 +103,13 @@ pub struct Scene {
pub objects: Vec<Sphere>, pub objects: Vec<Sphere>,
} }
#[derive(Debug, Clone, Copy)]
pub struct Hit {
pub incident: Ray,
pub normal: Vec3,
}
impl Scene { impl Scene {
pub fn trace_ray(&self, ray: Ray) -> Option<Hit> { pub fn trace_ray(&self, ray: Ray) -> Option<Ray> {
const EPS: f32 = -1e-3; let dist = self
let hit = self
.objects .objects
.iter() .iter()
.filter_map(|obj| obj.trace_ray(ray)) .filter_map(|obj| obj.trace_ray(ray))
.filter(|h| h.dist >= EPS) .min_by(f32::total_cmp);
.min_by(|a, b| f32::total_cmp(&a.dist, &b.dist))?; Some(ray.advance(dist?))
Some(Hit {
incident: Ray {
base: hit.pos,
dir: ray.dir,
},
normal: hit.normal,
})
}
}
pub trait Reflector {
fn brdf(&self, normal: Vec3, incident: Vec3, reflected: Vec3) -> f32 /* 1/sr */;
fn reflect(&self, rgen: &mut impl rand::Rng, normal: Vec3, incident: Vec3) -> Vec3;
}
pub struct Lambertian;
impl Reflector for Lambertian {
fn brdf(&self, _normal: Vec3, _incident: Vec3, _reflected: Vec3) -> f32 {
1. / PI
}
fn reflect(&self, rgen: &mut impl rand::Rng, normal: Vec3, _incident: Vec3) -> Vec3 {
let sphere: Vec3 = UnitSphere.sample(rgen).into();
let sphere_n = normal.dot(sphere); // uniform on [-1, 1]!
let sphere_t = sphere - sphere_n * normal;
let out_n_len2 = sphere_n.abs();
let out_t = (1. + out_n_len2).recip().sqrt() * sphere_t;
let out_n = out_n_len2.sqrt() * normal;
out_t + out_n
} }
} }

View File

@ -1,13 +0,0 @@
include(impl.cmake)
qt_add_executable(photon_light
src/api.cxx
src/main.cxx
src/main_window.cxx
src/main_window.ui
src/viewport.cxx
)
target_link_libraries(photon_light PRIVATE Qt6::Gui Qt6::Widgets)
target_link_libraries(photon_light PRIVATE photon_light_impl)
target_include_directories(photon_light PRIVATE src)

View File

@ -1,15 +0,0 @@
[package]
name = "photon-light-impl"
version = "0.1.0"
edition = "2024"
[lib]
crate-type = ["staticlib"]
[dependencies]
photon-light = {path = "../"}
glam = { version = "0.30" }
pollster = "0.4.0"
raw-window-handle = "0.6.2"
wgpu = "27.0.1"

View File

@ -1,22 +0,0 @@
set(impl_basename "${CARGO_TARGET_DIR}/release/libphoton_light_impl")
add_custom_command(
OUTPUT ${impl_basename}.a
COMMAND env CARGO_TARGET_DIR=${CARGO_TARGET_DIR} ${CARGO} build --release --package photon-light-impl
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
DEPFILE ${impl_basename}.d
USES_TERMINAL
JOB_SERVER_AWARE
DEPENDS_EXPLICIT_ONLY
)
# HACK ensure CMake *actually adds* the command above
add_custom_target(build_impl
DEPENDS ${impl_basename}.a
)
add_library(photon_light_impl STATIC IMPORTED)
set_target_properties(photon_light_impl PROPERTIES
IMPORTED_LOCATION ${impl_basename}.a
)

View File

@ -1,57 +0,0 @@
#include "api.hxx"
#include <stdexcept>
#include <utility>
namespace ffi {
extern "C" Core* rt4_viewport_create(xcb_connection_t* connection, std::uint32_t window);
extern "C" void rt4_viewport_destroy(Core* viewport);
extern "C" void rt4_viewport_configure(Core* viewport, std::uint32_t width, std::uint32_t height);
extern "C" void rt4_viewport_redraw(Core* viewport, const RedrawArgs* args);
} // namespace ffi
BoxCore::BoxCore(BoxCore&& b)
: ptr(std::exchange(b.ptr, {})) {
}
BoxCore::~BoxCore() {
reset();
}
BoxCore& BoxCore::operator=(BoxCore&& b) {
if (&b == this)
return *this;
std::swap(ptr, b.ptr);
b.reset();
return *this;
}
BoxCore BoxCore::from_xcb(xcb_connection_t* connection, std::uint32_t window) {
if (!connection)
throw std::logic_error("attempt to use a null connection");
if (!window)
throw std::logic_error("attempt to use a null window");
BoxCore out;
out.ptr.ptr = ffi::rt4_viewport_create(connection, window);
return out;
}
void BoxCore::reset() {
auto viewport = std::exchange(ptr, {});
if (viewport)
ffi::rt4_viewport_destroy(viewport.use());
}
ffi::Core* MutCore::use() const {
if (!ptr)
throw std::logic_error("attempt to use a null Core");
return ptr;
}
void MutCore::configure(std::uint32_t width, std::uint32_t height) const {
rt4_viewport_configure(use(), width, height);
}
void MutCore::redraw(const RedrawArgs& args) const {
rt4_viewport_redraw(use(), &args);
}

View File

@ -1,69 +0,0 @@
#pragma once
#include <cstdint>
struct xcb_connection_t;
namespace ffi {
struct Core;
struct SphericalPosition {
float yaw = 0.;
float pitch = 0.;
float distance = 1.;
};
struct RedrawArgs {
SphericalPosition camera_position;
SphericalPosition light_position;
float light_radius = 1.;
float light_spread = 0.;
float accum_sigma = 1.;
float accum_scale = 1.;
std::uint32_t reflections = 0;
bool show_axes = true;
bool show_shapes = true;
bool show_hit_emission = true;
bool show_miss_emission = true;
bool show_direct_hit = true;
bool show_indirect_hit = true;
bool show_light = true;
};
} // namespace ffi
using ffi::RedrawArgs;
using ffi::SphericalPosition;
class MutCore {
friend class BoxCore;
public:
explicit operator bool() const { return ptr; }
void configure(std::uint32_t width, std::uint32_t height) const;
void redraw(const RedrawArgs& args) const;
private:
ffi::Core* ptr = nullptr;
ffi::Core* use() const;
};
class BoxCore {
public:
BoxCore() = default;
BoxCore(const BoxCore&) = delete;
BoxCore(BoxCore&&);
BoxCore& operator=(const BoxCore&) = delete;
BoxCore& operator=(BoxCore&&);
~BoxCore();
explicit operator bool() const { return !!ptr; }
const MutCore* operator->() const { return &ptr; }
void reset();
static BoxCore from_xcb(xcb_connection_t* connection, std::uint32_t window);
private:
MutCore ptr;
};

View File

@ -1,45 +0,0 @@
use std::{ffi::c_void, num::NonZero, ptr::NonNull};
use glam::uvec2;
use photon_light::{Core, RedrawArgs, init_gpu_inner};
use raw_window_handle::{RawDisplayHandle, RawWindowHandle, XcbDisplayHandle, XcbWindowHandle};
unsafe fn create_viewport(
display: impl Into<RawDisplayHandle>,
window: impl Into<RawWindowHandle>,
) -> Box<Core> {
let target = wgpu::SurfaceTargetUnsafe::RawHandle {
raw_display_handle: display.into(),
raw_window_handle: window.into(),
};
let gpu = pollster::block_on(init_gpu_inner(|instance| unsafe {
instance.create_surface_unsafe(target)
}))
.unwrap();
Box::new(Core::new(gpu))
}
#[unsafe(no_mangle)]
unsafe extern "C" fn rt4_viewport_create(
connection: NonNull<c_void>,
window: NonZero<u32>,
) -> Box<Core> {
let display = XcbDisplayHandle::new(Some(connection), 0);
let window = XcbWindowHandle::new(window);
unsafe { create_viewport(display, window) }
}
#[unsafe(no_mangle)]
unsafe extern "C" fn rt4_viewport_destroy(viewport: Box<Core>) {
drop(viewport);
}
#[unsafe(no_mangle)]
unsafe extern "C" fn rt4_viewport_configure(viewport: &mut Core, width: u32, height: u32) {
viewport.configure(uvec2(width, height));
}
#[unsafe(no_mangle)]
unsafe extern "C" fn rt4_viewport_redraw(viewport: &mut Core, args: &RedrawArgs) {
viewport.redraw(args);
}

View File

@ -1,12 +0,0 @@
#include "main_window.hxx"
#include <QApplication>
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
auto w = new PhotonLight;
w->show();
return app.exec();
}

View File

@ -1,54 +0,0 @@
#include "main_window.hxx"
#include "ui_main_window.h"
PhotonLight::PhotonLight(QWidget* parent)
: QMainWindow(parent),
m_ui(new Ui::MainWindow) {
m_ui->setupUi(this);
updateView();
}
PhotonLight::~PhotonLight() = default;
float deg_to_rad(float val) {
return val * float(M_PI / 180);
}
void PhotonLight::updateView() {
RedrawArgs args{
.camera_position = SphericalPosition{
.yaw = deg_to_rad(m_ui->cameraYaw->value()),
.pitch = deg_to_rad(m_ui->cameraPitch->value()),
.distance = m_ui->cameraDistance->value() / 10.0f,
},
.light_position = SphericalPosition{
.yaw = deg_to_rad(m_ui->lightYaw->value()),
.pitch = deg_to_rad(m_ui->lightPitch->value()),
.distance = m_ui->lightDistance->value() / 10.0f,
},
.light_radius = 0.125,
.light_spread = 0.125,
.accum_sigma = exp10f(m_ui->accumSigma->value() / 25.0),
.accum_scale = exp10f(m_ui->accumScale->value() / 25.0),
.reflections = std::uint32_t(m_ui->reflections->value()),
.show_axes = m_ui->displayAxes->isChecked(),
.show_shapes = m_ui->displayShapes->isChecked(),
.show_hit_emission = m_ui->displayEmitted->isChecked(),
.show_miss_emission = m_ui->displayEmitted->isChecked(),
.show_direct_hit = m_ui->displayDirectHits->isChecked(),
.show_indirect_hit = m_ui->displayIndirectHits->isChecked(),
.show_light = m_ui->displayResult->isChecked(),
};
m_ui->cameraYawLabel->setText(tr("Yaw: %1 deg").arg(QString::number(qRadiansToDegrees(args.camera_position.yaw))));
m_ui->cameraPitchLabel->setText(tr("Pitch: %1 deg").arg(QString::number(qRadiansToDegrees(args.camera_position.pitch))));
m_ui->cameraDistanceLabel->setText(tr("Distance: %1").arg(QString::number(args.camera_position.distance)));
m_ui->lightYawLabel->setText(tr("Yaw: %1 deg").arg(QString::number(qRadiansToDegrees(args.light_position.yaw))));
m_ui->lightPitchLabel->setText(tr("Pitch: %1 deg").arg(QString::number(qRadiansToDegrees(args.light_position.pitch))));
m_ui->lightDistanceLabel->setText(tr("Distance: %1").arg(QString::number(args.light_position.distance)));
m_ui->accumSigmaLabel->setText(tr("Averaging radius: %1").arg(QString::number(args.accum_sigma, 'f', 3)));
m_ui->accumScaleLabel->setText(tr("Brightness: %1").arg(QString::number(args.accum_scale, 'f', 3)));
m_ui->viewport->setView(args);
}
#include "moc_main_window.cpp"

View File

@ -1,22 +0,0 @@
#pragma once
#include <QMainWindow>
#include <memory>
namespace Ui {
class MainWindow;
}
class PhotonLight : public QMainWindow {
Q_OBJECT
public:
explicit PhotonLight(QWidget* parent = nullptr);
~PhotonLight() override;
public slots:
void updateView();
private:
const std::unique_ptr<Ui::MainWindow> m_ui;
};

View File

@ -1,644 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1600</width>
<height>1200</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="Viewport" name="viewport" native="true"/>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1600</width>
<height>38</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<widget class="QDockWidget" name="dockWidget">
<property name="features">
<set>QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable</set>
</property>
<attribute name="dockWidgetArea">
<number>2</number>
</attribute>
<widget class="QWidget" name="dockWidgetContents">
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>Camera</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="cameraYawLabel">
<property name="text">
<string>Yaw</string>
</property>
<property name="buddy">
<cstring>cameraYaw</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="cameraYaw">
<property name="minimum">
<number>-180</number>
</property>
<property name="maximum">
<number>180</number>
</property>
<property name="pageStep">
<number>15</number>
</property>
<property name="value">
<number>45</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="cameraPitchLabel">
<property name="text">
<string>Pitch</string>
</property>
<property name="buddy">
<cstring>cameraPitch</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="cameraPitch">
<property name="minimum">
<number>-90</number>
</property>
<property name="maximum">
<number>90</number>
</property>
<property name="pageStep">
<number>15</number>
</property>
<property name="value">
<number>35</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="cameraDistanceLabel">
<property name="text">
<string>Distance</string>
</property>
<property name="buddy">
<cstring>cameraDistance</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="cameraDistance">
<property name="maximum">
<number>50</number>
</property>
<property name="value">
<number>30</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_2">
<property name="title">
<string>Light</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QLabel" name="lightYawLabel">
<property name="text">
<string>Yaw</string>
</property>
<property name="buddy">
<cstring>lightYaw</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="lightYaw">
<property name="minimum">
<number>-180</number>
</property>
<property name="maximum">
<number>180</number>
</property>
<property name="pageStep">
<number>15</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="lightPitchLabel">
<property name="text">
<string>Pitch</string>
</property>
<property name="buddy">
<cstring>lightPitch</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="lightPitch">
<property name="minimum">
<number>-90</number>
</property>
<property name="maximum">
<number>90</number>
</property>
<property name="pageStep">
<number>15</number>
</property>
<property name="value">
<number>60</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="invertedAppearance">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="lightDistanceLabel">
<property name="text">
<string>Distance</string>
</property>
<property name="buddy">
<cstring>lightDistance</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="lightDistance">
<property name="maximum">
<number>50</number>
</property>
<property name="value">
<number>10</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_3">
<property name="title">
<string>Lighting</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<widget class="QLabel" name="accumSigmaLabel">
<property name="text">
<string>Averaging radius</string>
</property>
<property name="buddy">
<cstring>accumSigma</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="accumSigma">
<property name="minimum">
<number>-100</number>
</property>
<property name="maximum">
<number>0</number>
</property>
<property name="value">
<number>-40</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="accumScaleLabel">
<property name="text">
<string>Brightness</string>
</property>
<property name="buddy">
<cstring>accumScale</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="accumScale">
<property name="minimum">
<number>-100</number>
</property>
<property name="maximum">
<number>0</number>
</property>
<property name="value">
<number>-50</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Reflections</string>
</property>
<property name="buddy">
<cstring>reflections</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="reflections">
<property name="maximum">
<number>20</number>
</property>
<property name="value">
<number>2</number>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_4">
<property name="title">
<string>Show</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_5">
<item>
<widget class="QCheckBox" name="displayAxes">
<property name="text">
<string>Axes</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="displayShapes">
<property name="text">
<string>Shapes</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="displayEmitted">
<property name="text">
<string>Emitted rays</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="displayDirectHits">
<property name="text">
<string>Direct incident rays</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="displayIndirectHits">
<property name="text">
<string>Indirect incident rays</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="displayResult">
<property name="text">
<string>Average light</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>385</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</widget>
<customwidgets>
<customwidget>
<class>Viewport</class>
<extends>QWidget</extends>
<header>viewport.hxx</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>cameraYaw</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1585</x>
<y>169</y>
</hint>
<hint type="destinationlabel">
<x>403</x>
<y>362</y>
</hint>
</hints>
</connection>
<connection>
<sender>cameraPitch</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1585</x>
<y>225</y>
</hint>
<hint type="destinationlabel">
<x>403</x>
<y>362</y>
</hint>
</hints>
</connection>
<connection>
<sender>lightYaw</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1585</x>
<y>385</y>
</hint>
<hint type="destinationlabel">
<x>403</x>
<y>362</y>
</hint>
</hints>
</connection>
<connection>
<sender>lightPitch</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1585</x>
<y>441</y>
</hint>
<hint type="destinationlabel">
<x>403</x>
<y>362</y>
</hint>
</hints>
</connection>
<connection>
<sender>accumSigma</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1585</x>
<y>601</y>
</hint>
<hint type="destinationlabel">
<x>399</x>
<y>299</y>
</hint>
</hints>
</connection>
<connection>
<sender>accumScale</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1585</x>
<y>657</y>
</hint>
<hint type="destinationlabel">
<x>399</x>
<y>299</y>
</hint>
</hints>
</connection>
<connection>
<sender>cameraDistance</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1489</x>
<y>271</y>
</hint>
<hint type="destinationlabel">
<x>799</x>
<y>599</y>
</hint>
</hints>
</connection>
<connection>
<sender>lightDistance</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1489</x>
<y>487</y>
</hint>
<hint type="destinationlabel">
<x>799</x>
<y>599</y>
</hint>
</hints>
</connection>
<connection>
<sender>displayAxes</sender>
<signal>stateChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1489</x>
<y>799</y>
</hint>
<hint type="destinationlabel">
<x>799</x>
<y>599</y>
</hint>
</hints>
</connection>
<connection>
<sender>displayDirectHits</sender>
<signal>stateChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1489</x>
<y>901</y>
</hint>
<hint type="destinationlabel">
<x>799</x>
<y>599</y>
</hint>
</hints>
</connection>
<connection>
<sender>displayEmitted</sender>
<signal>stateChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1489</x>
<y>867</y>
</hint>
<hint type="destinationlabel">
<x>799</x>
<y>599</y>
</hint>
</hints>
</connection>
<connection>
<sender>displayIndirectHits</sender>
<signal>stateChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1489</x>
<y>935</y>
</hint>
<hint type="destinationlabel">
<x>799</x>
<y>599</y>
</hint>
</hints>
</connection>
<connection>
<sender>displayResult</sender>
<signal>stateChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1489</x>
<y>969</y>
</hint>
<hint type="destinationlabel">
<x>799</x>
<y>599</y>
</hint>
</hints>
</connection>
<connection>
<sender>displayShapes</sender>
<signal>stateChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1489</x>
<y>833</y>
</hint>
<hint type="destinationlabel">
<x>799</x>
<y>599</y>
</hint>
</hints>
</connection>
<connection>
<sender>reflections</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>1489</x>
<y>712</y>
</hint>
<hint type="destinationlabel">
<x>799</x>
<y>599</y>
</hint>
</hints>
</connection>
</connections>
<slots>
<slot>updateView()</slot>
</slots>
</ui>

View File

@ -1,74 +0,0 @@
#include "viewport.hxx"
#include <QApplication>
#include <QEvent>
#include <QGuiApplication>
Viewport::Viewport(QWidget* parent, Qt::WindowFlags f)
: QWidget(parent, f) {
setAttribute(Qt::WA_DontCreateNativeAncestors);
setAttribute(Qt::WA_NativeWindow);
setAttribute(Qt::WA_PaintOnScreen);
setAttribute(Qt::WA_NoSystemBackground);
}
Viewport::~Viewport() = default;
void Viewport::setView(RedrawArgs new_args) {
args = new_args;
update();
}
QPaintEngine* Viewport::paintEngine() const {
return nullptr;
}
bool Viewport::event(QEvent* event) {
switch (event->type()) {
case QEvent::Type::WinIdChange:
recreate();
break;
default:
break;
}
return QWidget::event(event);
}
void Viewport::paintEvent(QPaintEvent* event) {
if (!core)
recreate();
core->redraw(args);
}
void Viewport::resizeEvent(QResizeEvent* event) {
if (!core)
return;
updateSize();
QWidget::resizeEvent(event);
}
void Viewport::recreate() try {
auto* app = qobject_cast<QGuiApplication*>(QApplication::instance());
if (!app)
throw std::runtime_error("not a GUI application (WTF?)");
auto* native = app->nativeInterface<QNativeInterface::QX11Application>();
if (!native)
throw std::runtime_error("X11 interface is not available");
auto* xcb_connection = native->connection();
std::uint32_t x11_window = winId();
fprintf(stderr, "connection %p, window %#08x\n", xcb_connection, x11_window);
core.reset();
core = BoxCore::from_xcb(xcb_connection, x11_window);
updateSize();
} catch (const std::exception& e) {
fprintf(stderr, "failed to recreate the viewport: %s", e.what());
}
void Viewport::updateSize() {
const QSize device_size = size() * devicePixelRatio();
core->configure(device_size.width(), device_size.height());
}

View File

@ -1,28 +0,0 @@
#pragma once
#include <QWidget>
#include "api.hxx"
class Viewport : public QWidget {
Q_OBJECT
public:
explicit Viewport(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags());
~Viewport() override;
QPaintEngine* paintEngine() const override;
void setView(RedrawArgs new_args);
protected:
bool event(QEvent* event) override;
void paintEvent(QPaintEvent* event) override;
void resizeEvent(QResizeEvent* event) override;
private:
BoxCore core;
RedrawArgs args = {};
void recreate();
void updateSize();
};