formatting: Using canonical formatting on whole project

This commit is contained in:
2026-11-22 17:16:32 +01:00
parent 2910314df3
commit dd0e102348
44 changed files with 1526 additions and 3376 deletions
+17 -34
View File
@@ -7,8 +7,7 @@ use glam::Vec3;
use winit::event::WindowEvent;
use winit::keyboard::KeyCode;
pub struct Camera
{
pub struct Camera {
pub position: Vec3,
pitch: f32,
yaw: f32,
@@ -22,10 +21,8 @@ pub struct Camera
pub pressed_keyset: HashSet<KeyCode>,
}
impl Default for Camera
{
fn default() -> Self
{
impl Default for Camera {
fn default() -> Self {
Self {
position: Vec3::new(0., 0., 0.),
pitch: Default::default(),
@@ -41,47 +38,35 @@ impl Default for Camera
}
}
impl Camera
{
pub fn handle_input(&mut self, event: &WindowEvent)
{
if let WindowEvent::KeyboardInput { event, .. } = event
{
match (event.state, event.physical_key)
{
(winit::event::ElementState::Pressed, winit::keyboard::PhysicalKey::Code(c)) =>
{
impl Camera {
pub fn handle_input(&mut self, event: &WindowEvent) {
if let WindowEvent::KeyboardInput { event, .. } = event {
match (event.state, event.physical_key) {
(winit::event::ElementState::Pressed, winit::keyboard::PhysicalKey::Code(c)) => {
self.pressed_keyset.insert(c);
}
(winit::event::ElementState::Released, winit::keyboard::PhysicalKey::Code(c)) =>
{
(winit::event::ElementState::Released, winit::keyboard::PhysicalKey::Code(c)) => {
self.pressed_keyset.remove(&c);
}
_ =>
{}
_ => {}
}
}
}
pub fn update(&mut self)
{
pub fn update(&mut self) {
let mut movement = Vec3::new(0., 0., 0.);
if self.pressed_keyset.contains(&KeyCode::KeyW)
{
if self.pressed_keyset.contains(&KeyCode::KeyW) {
movement.z += self.speed;
}
if self.pressed_keyset.contains(&KeyCode::KeyS)
{
if self.pressed_keyset.contains(&KeyCode::KeyS) {
movement.z -= self.speed;
}
// Left right
if self.pressed_keyset.contains(&KeyCode::KeyA)
{
if self.pressed_keyset.contains(&KeyCode::KeyA) {
movement.x += self.speed;
}
if self.pressed_keyset.contains(&KeyCode::KeyD)
{
if self.pressed_keyset.contains(&KeyCode::KeyD) {
movement.x -= self.speed;
}
@@ -91,8 +76,7 @@ impl Camera
self.position -= rot_movement;
}
pub fn cursor_moved(&mut self, x: f32, y: f32)
{
pub fn cursor_moved(&mut self, x: f32, y: f32) {
const SENSITIVITY: f32 = 0.0004;
let position = Vec2::new(x, y);
let offset = position * SENSITIVITY;
@@ -101,8 +85,7 @@ impl Camera
self.pitch += offset.y;
}
pub fn view_proj(&self) -> Mat4
{
pub fn view_proj(&self) -> Mat4 {
let view = glam::Mat4::from_translation(self.position)
* glam::Mat4::from_rotation_y(-self.yaw)
* glam::Mat4::from_rotation_x(-self.pitch);
+15 -23
View File
@@ -12,23 +12,22 @@ use wgpu::TextureView;
use winit::event::WindowEvent;
use winit::window::Window;
pub struct EguiRenderer
{
pub struct EguiRenderer {
state: State,
pub renderer: Renderer,
frame_started: bool,
}
impl EguiRenderer
{
pub fn context(&self) -> &Context
{
impl EguiRenderer {
pub fn context(&self) -> &Context {
self.state.egui_ctx()
}
pub fn new(device: &Device, output_color_format: TextureFormat, window: &Window)
-> EguiRenderer
{
pub fn new(
device: &Device,
output_color_format: TextureFormat,
window: &Window,
) -> EguiRenderer {
let egui_context = Context::default();
let egui_state = State::new(
@@ -49,18 +48,15 @@ impl EguiRenderer
}
}
pub fn handle_input(&mut self, window: &Window, event: &WindowEvent)
{
pub fn handle_input(&mut self, window: &Window, event: &WindowEvent) {
let _ = self.state.on_window_event(window, event);
}
pub fn ppp(&mut self, v: f32)
{
pub fn ppp(&mut self, v: f32) {
self.context().set_pixels_per_point(v);
}
pub fn begin_frame(&mut self, window: &Window)
{
pub fn begin_frame(&mut self, window: &Window) {
let raw_input = self.state.take_egui_input(window);
self.state.egui_ctx().begin_pass(raw_input);
self.frame_started = true;
@@ -74,10 +70,8 @@ impl EguiRenderer
window: &Window,
window_surface_view: &TextureView,
screen_descriptor: ScreenDescriptor,
)
{
if !self.frame_started
{
) {
if !self.frame_started {
panic!("begin_frame must be called before.");
}
@@ -92,8 +86,7 @@ impl EguiRenderer
.egui_ctx()
.tessellate(full_output.shapes, self.state.egui_ctx().pixels_per_point());
for (id, image_delta) in &full_output.textures_delta.set
{
for (id, image_delta) in &full_output.textures_delta.set {
self.renderer
.update_texture(device, queue, *id, &image_delta[0]);
}
@@ -121,8 +114,7 @@ impl EguiRenderer
self.renderer
.render(&mut rpass.forget_lifetime(), &tris, &screen_descriptor);
for x in &full_output.textures_delta.free
{
for x in &full_output.textures_delta.free {
self.renderer.free_texture(x);
}
+70 -132
View File
@@ -23,6 +23,9 @@ use itertools::Itertools;
use rand::random_range;
use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator;
use vxls_production::sparse_tree::Color;
use vxls_production::sparse_tree::NTree;
use vxls_production::sparse_tree::load_ply;
use wgpu::BindGroupLayout;
use wgpu::BufferUsages;
use wgpu::ComputePipeline;
@@ -53,8 +56,6 @@ use winit::window::WindowId;
use crate::camera::Camera;
use crate::egui_renderer::EguiRenderer;
use crate::producers::SdfGenerator;
use crate::sparse_tree::NTree;
use crate::sparse_tree::load_ply;
use vxls_bvh::BvhHandle;
use vxls_bvh::BvhObject;
use vxls_bvh::BvhStructureTable;
@@ -85,10 +86,8 @@ use vxls_voxel_cache::schema::LocationPage;
mod camera;
mod egui_renderer;
mod producers;
mod sparse_tree;
enum DisplayTexture
{
enum DisplayTexture {
Target,
Normal,
Pos,
@@ -105,8 +104,7 @@ where
location_page: LocationPage,
}
struct State
{
struct State {
instance: wgpu::Instance,
window: Arc<Window>,
device: wgpu::Device,
@@ -161,15 +159,13 @@ struct State
bvh_objs: Vec<(BvhHandle, Vec3)>,
}
pub unsafe fn as_raw_bytes<T: Sized>(slice: &[T]) -> &[u8]
{
pub unsafe fn as_raw_bytes<T: Sized>(slice: &[T]) -> &[u8] {
let size = slice.len() * size_of::<T>();
unsafe { std::slice::from_raw_parts(slice.as_ptr() as *const u8, size) }
}
#[derive(Clone, Copy)]
struct Immediates
{
struct Immediates {
view_proj: Mat4,
cam_pos: Vec3,
frame_timestamp: u32,
@@ -185,18 +181,15 @@ struct Immediates
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
#[repr(C)]
struct InstanceAttribute
{
struct InstanceAttribute {
x: f32,
y: f32,
z: f32,
id: u32,
}
impl State
{
async fn new(display: OwnedDisplayHandle, window: Arc<Window>) -> State
{
impl State {
async fn new(display: OwnedDisplayHandle, window: Arc<Window>) -> State {
let instance = wgpu::Instance::new(InstanceDescriptor {
backends: wgpu::Backends::VULKAN,
display: Some(Box::new(display)),
@@ -365,7 +358,7 @@ impl State
*/
// Load dragon ply
let tree: NTree<4> = load_ply("../../dragon.txt");
let tree: NTree<4, Color> = load_ply("../../dragon.txt");
// let mut arrays = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
// for ((x, y), z) in (0..256).cartesian_product(0..256).cartesian_product(0..256)
// {
@@ -425,8 +418,7 @@ impl State
let mut bvh = BvhStructureTable::new(&device, 128, 128);
let extent = Aabb::new(-10. * Vec3::ONE, 10. * Vec3::ONE);
let mut bvh_objs = Vec::new();
for _ in 0..1000
{
for _ in 0..1000 {
let transform = Mat4::from_rotation_translation(
Quat::from_euler(
glam::EulerRot::XYZ,
@@ -742,15 +734,12 @@ impl State
let request_queue_1 = request_queue.clone();
let (wakeup_tx, wakeup_rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
loop
{
if !wakeup_rx.recv().is_ok()
{
loop {
if !wakeup_rx.recv().is_ok() {
break;
}
loop
{
loop {
// Try to get some work from the queue
let mut work = vec![];
{
@@ -762,8 +751,7 @@ impl State
}
}
if work.is_empty()
{
if work.is_empty() {
break;
}
@@ -870,8 +858,7 @@ impl State
width: u32,
height: u32,
format: wgpu::TextureFormat,
) -> (Texture, TextureView)
{
) -> (Texture, TextureView) {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Target texture"),
size: Extent3d {
@@ -891,8 +878,7 @@ impl State
(texture, texture_view)
}
fn create_target_texture(device: &Device, width: u32, height: u32) -> (Texture, TextureView)
{
fn create_target_texture(device: &Device, width: u32, height: u32) -> (Texture, TextureView) {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Target texture"),
size: Extent3d {
@@ -912,13 +898,11 @@ impl State
(texture, texture_view)
}
fn get_window(&self) -> &Window
{
fn get_window(&self) -> &Window {
&self.window
}
fn handle_event(&mut self, event: &WindowEvent)
{
fn handle_event(&mut self, event: &WindowEvent) {
self.egui_renderer.handle_input(&self.window, event);
self.camera.handle_input(event);
@@ -966,23 +950,18 @@ impl State
}
}
fn handle_device_event(&mut self, event: &DeviceEvent)
{
fn handle_device_event(&mut self, event: &DeviceEvent) {
#[allow(clippy::single_match)]
match event
{
winit::event::DeviceEvent::MouseMotion { delta } if self.cursor_grabed =>
{
match event {
winit::event::DeviceEvent::MouseMotion { delta } if self.cursor_grabed => {
self.camera.cursor_moved(delta.0 as f32, delta.1 as f32);
}
_ =>
{}
_ => {}
}
}
fn create_depth_buffer(device: &Device, width: u32, height: u32) -> (Texture, TextureView)
{
fn create_depth_buffer(device: &Device, width: u32, height: u32) -> (Texture, TextureView) {
let texture = device.create_texture(&wgpu::wgt::TextureDescriptor {
label: Some("Depth buffer"),
size: Extent3d {
@@ -1004,8 +983,7 @@ impl State
(texture, texture_view)
}
fn configure_surface(&self)
{
fn configure_surface(&self) {
let surface_config = wgpu::SurfaceConfiguration {
color_space: wgpu::SurfaceColorSpace::Auto,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
@@ -1022,8 +1000,7 @@ impl State
self.surface.configure(&self.device, &surface_config);
}
fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>)
{
fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
self.size = new_size;
self.camera.aspect = new_size.width as f32 / new_size.height as f32;
self.configure_surface();
@@ -1054,16 +1031,13 @@ impl State
);
}
fn render(&mut self)
{
fn render(&mut self) {
self.camera.update();
let mut locked_table = self.structure_table.lock();
for (hndl, dir) in self.bvh_objs.iter_mut()
{
for (hndl, dir) in self.bvh_objs.iter_mut() {
let obj = locked_table.get_mut(hndl);
if let Some(obj) = obj
{
if let Some(obj) = obj {
let (scale, mut rot, mut trans) = obj.transform.to_scale_rotation_translation();
let speed = 0.01;
rot = rot.mul_quat(Quat::from_axis_angle(*dir, speed));
@@ -1084,27 +1058,22 @@ impl State
// NOTE: We must handle Timeout because the surface may be unavailable
// (e.g., when the window is occluded on macOS).
// ~~ Texture view creation ~~
let surface_texture = match self.surface.get_current_texture()
{
let surface_texture = match self.surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(texture) => texture,
wgpu::CurrentSurfaceTexture::Occluded | wgpu::CurrentSurfaceTexture::Timeout => return,
wgpu::CurrentSurfaceTexture::Suboptimal(texture) =>
{
wgpu::CurrentSurfaceTexture::Suboptimal(texture) => {
drop(texture);
self.configure_surface();
return;
}
wgpu::CurrentSurfaceTexture::Outdated =>
{
wgpu::CurrentSurfaceTexture::Outdated => {
self.configure_surface();
return;
}
wgpu::CurrentSurfaceTexture::Validation =>
{
wgpu::CurrentSurfaceTexture::Validation => {
unreachable!("No error scope registered, so validation errors will panic")
}
wgpu::CurrentSurfaceTexture::Lost =>
{
wgpu::CurrentSurfaceTexture::Lost => {
self.surface = self.instance.create_surface(self.window.clone()).unwrap();
self.configure_surface();
return;
@@ -1240,8 +1209,7 @@ impl State
encoder.end_scope();
}
let target_view = match self.display
{
let target_view = match self.display {
DisplayTexture::Target => &self.target_texture.1,
DisplayTexture::Normal => &self.normal_gbuffer.1,
DisplayTexture::Pos => &self.position_gbuffer.1,
@@ -1367,8 +1335,7 @@ impl State
let slice = slice.unwrap();
let cache_slice: &[u32] = bytemuck::cast_slice(&slice);
let mut v = vec![0; 100];
for x in cache_slice.iter()
{
for x in cache_slice.iter() {
let diff = (time_stamp - x).min(99);
v[diff as usize] += 1;
}
@@ -1470,13 +1437,10 @@ impl State
&self.queue,
move |request_informations, request_metas| {
let done = request_buffer_done_1.load(std::sync::atomic::Ordering::Relaxed);
if !done
{
if !done {
request_buffer_done_1.store(true, std::sync::atomic::Ordering::Relaxed);
finshed_1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
else
{
} else {
return;
}
@@ -1575,14 +1539,11 @@ impl State
move |request_informations, request_metas| {
let done = structure_table_request_buffer_done_1
.load(std::sync::atomic::Ordering::Relaxed);
if !done
{
if !done {
structure_table_request_buffer_done_1
.store(true, std::sync::atomic::Ordering::Relaxed);
finshed_2.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
else
{
} else {
return;
}
@@ -1669,10 +1630,8 @@ impl State
self.wakeup.send(()).unwrap();
loop
{
if finished.load(std::sync::atomic::Ordering::Relaxed) >= 2
{
loop {
if finished.load(std::sync::atomic::Ordering::Relaxed) >= 2 {
break;
}
let _ = self.device.poll(wgpu::wgt::PollType::Poll);
@@ -1712,25 +1671,20 @@ impl State
}
}
pub fn mouse_wheel(&mut self, delta: MouseScrollDelta)
{
if let MouseScrollDelta::LineDelta(_, y) = delta
{
pub fn mouse_wheel(&mut self, delta: MouseScrollDelta) {
if let MouseScrollDelta::LineDelta(_, y) = delta {
self.camera.speed += y * (self.camera.speed * 0.05);
}
}
}
#[derive(Default)]
struct App
{
struct App {
state: Option<State>,
}
impl ApplicationHandler for App
{
fn resumed(&mut self, event_loop: &ActiveEventLoop)
{
impl ApplicationHandler for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
// Create window object
let window = Arc::new(
event_loop
@@ -1754,31 +1708,25 @@ impl ApplicationHandler for App
.or_else(|_| window.set_cursor_grab(winit::window::CursorGrabMode::Confined));
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent)
{
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
let state = self.state.as_mut().unwrap();
state.handle_event(&event);
match event
{
WindowEvent::CloseRequested =>
{
match event {
WindowEvent::CloseRequested => {
println!("The close button was pressed; stopping");
event_loop.exit();
}
WindowEvent::RedrawRequested =>
{
WindowEvent::RedrawRequested => {
state.render();
// Emits a new redraw requested event.
state.get_window().request_redraw();
}
WindowEvent::Resized(size) =>
{
WindowEvent::Resized(size) => {
// Reconfigures the size of the surface. We do not re-render
// here as this event is always followed up by redraw request.
state.resize(size);
}
WindowEvent::MouseWheel { delta, .. } =>
{
WindowEvent::MouseWheel { delta, .. } => {
state.mouse_wheel(delta);
}
@@ -1791,15 +1739,13 @@ impl ApplicationHandler for App
_event_loop: &event_loop::ActiveEventLoop,
_device_id: winit::event::DeviceId,
event: winit::event::DeviceEvent,
)
{
) {
let state = self.state.as_mut().unwrap();
state.handle_device_event(&event);
}
}
fn main()
{
fn main() {
// wgpu uses `log` for all of our logging, so we initialize a logger with the `env_logger` crate.
//
// To change the log level, set the `RUST_LOG` environment variable. See the `env_logger`
@@ -1826,8 +1772,7 @@ fn main()
}
#[derive(AsStd140)]
pub struct ChunkImmediate
{
pub struct ChunkImmediate {
mvp: Mat4,
eye_pos: Vec3,
root_color: Vec4,
@@ -1836,32 +1781,28 @@ pub struct ChunkImmediate
}
fn fullfill_request_tree<const N: usize>(
tree: &NTree<N>,
tree: &NTree<N, Color>,
request: &RequestKey,
) -> (
[u32; N * N * N],
[[f32; 3]; N * N * N],
InsertionInformation<N>,
LocationPage,
)
{
match request.target
{
RequestTarget::Root =>
{
) {
match request.target {
RequestTarget::Root => {
let root = tree
.get_by_loc(TreeLocator::root())
.expect("Root must exist");
if !root.subdivided
{
if !root.subdivided {
// Produce little node of constant
(
[root.color.as_packed_u32(); N * N * N],
[root.attribute.as_packed_u32(); N * N * N],
//[sparse_tree::Color(1., 1., 1., 1.).as_packed_u32(); N * N * N],
[Default::default(); N * N * N],
InsertionInformation {
children: [ChildInformation::new(false, root.color.3 != 0.); N * N * N],
children: [ChildInformation::new(false, root.attribute.3 != 0.); N * N * N],
},
LocationPage {
node_id: StructureLocator::from(TreeLocator::<N>::root()),
@@ -1869,17 +1810,15 @@ fn fullfill_request_tree<const N: usize>(
anchor: StructureAnchor::zeroed(),
},
)
}
else
{
} else {
let mut colors = vec![];
let mut children = vec![];
TreeLocator::root().children().for_each(|loc| {
let node = tree.get_by_loc(loc).unwrap();
colors.push(node.color.as_packed_u32());
colors.push(node.attribute.as_packed_u32());
children.push(ChildInformation::new(
node.subdivided,
node.subdivided || node.color.3 != 0.,
node.subdivided || node.attribute.3 != 0.,
));
});
@@ -1900,8 +1839,7 @@ fn fullfill_request_tree<const N: usize>(
RequestTarget::Child {
parent,
children_index,
} =>
{
} => {
let child_z = children_index / (4 * 4);
let child_y = (children_index % (4 * 4)) / 4;
let child_x = children_index % 4;
@@ -1913,10 +1851,10 @@ fn fullfill_request_tree<const N: usize>(
let mut children = vec![];
loc.children().for_each(|child_loc| {
let node = tree.get_by_loc(child_loc).unwrap();
colors.push(node.color.as_packed_u32());
colors.push(node.attribute.as_packed_u32());
children.push(ChildInformation::new(
node.subdivided,
node.subdivided || node.color.3 != 0.,
node.subdivided || node.attribute.3 != 0.,
));
});
+45 -98
View File
@@ -11,7 +11,7 @@ use noise::NoiseFn;
use noise::Simplex;
use rand::random;
use crate::sparse_tree::Color;
use vxls_production::sparse_tree::Color;
use vxls_voxel_cache::schema::ChildInformation;
/// The voxel attributes used by the demo cache.
@@ -21,8 +21,7 @@ use vxls_voxel_cache::schema::ChildInformation;
/// `shaders/voxel.slang`.
#[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, vxls_production::Attributes, Debug)]
#[repr(C)]
pub struct VoxelAttributes
{
pub struct VoxelAttributes {
#[attribute(label = "color", semantic = "color")]
pub color: u32,
@@ -30,13 +29,11 @@ pub struct VoxelAttributes
pub normal: [f32; 3],
}
pub struct BallGenerator<const N: usize>
{
pub struct BallGenerator<const N: usize> {
chunk_power: usize,
}
pub fn map(x: f32, x_min: f32, x_max: f32, y_min: f32, y_max: f32) -> f32
{
pub fn map(x: f32, x_min: f32, x_max: f32, y_min: f32, y_max: f32) -> f32 {
//((x - x_min) / (x_max - x_min)) * (y_max - y_min) + y_min
let input_range = x_max.algebraic_sub(x_min);
let output_range = y_max.algebraic_sub(y_min);
@@ -57,8 +54,7 @@ impl<const N: usize> BallGenerator<N>
where
[(); N * N * N]:,
{
pub fn new(chunk_power: usize) -> Self
{
pub fn new(chunk_power: usize) -> Self {
BallGenerator { chunk_power }
}
}
@@ -67,8 +63,7 @@ impl<const N: usize> Producer<N> for BallGenerator<N>
where
[(); N * N * N]:,
{
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk<N>
{
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk<N> {
let node_size = N.pow((self.chunk_power - depth) as u32);
let child_size = node_size / N;
let global_size = N.pow(self.chunk_power as u32);
@@ -81,8 +76,7 @@ where
let gny = ny * node_size;
let gnz = nz * node_size;
// Iterate on children of this node
for ((cx, cy), cz) in (0..N).cartesian_product(0..N).cartesian_product(0..N)
{
for ((cx, cy), cz) in (0..N).cartesian_product(0..N).cartesian_product(0..N) {
let gvx = gnx + cx * child_size + (child_size / 2);
let gvy = gny + cy * child_size + (child_size / 2);
let gvz = gnz + cz * child_size + (child_size / 2);
@@ -97,19 +91,14 @@ where
let alpha;
let subdivided;
if (dist - (global_size as f32 / 2.)).abs() <= child_diagonal_length
{
if (dist - (global_size as f32 / 2.)).abs() <= child_diagonal_length {
//children.push(StructurePointer::new(depth <= 3, false, 0));
subdivided = depth < (self.chunk_power - 1);
alpha = if dist > 128. { 0. } else { 1. };
}
else if dist > (global_size as f32 / 2.)
{
} else if dist > (global_size as f32 / 2.) {
subdivided = false;
alpha = 0.;
}
else
{
} else {
subdivided = false;
alpha = 1.;
}
@@ -169,8 +158,7 @@ where
height_path: P,
height_factor: f32,
color_path: P,
) -> Self
{
) -> Self {
println!("Starting terrain producer");
println!("Loading height map.");
let mut tiff_dec = tiff::decoder::Decoder::new(File::open(height_path).unwrap()).unwrap();
@@ -178,8 +166,7 @@ where
let (heightmap_width, heightmap_height) =
(heightmap_width as usize, heightmap_height as usize);
let mut heightmap = match tiff_dec.read_image().unwrap()
{
let mut heightmap = match tiff_dec.read_image().unwrap() {
tiff::decoder::DecodingResult::F32(vec) => vec,
_ => panic!("Unsupported format"),
};
@@ -229,16 +216,12 @@ where
let mut heightmap_low = vec![(0., 0.); heightmap_low_height * heightmap_low_width];
for y in 0..heightmap_low_height
{
for x in 0..heightmap_low_width
{
for y in 0..heightmap_low_height {
for x in 0..heightmap_low_width {
let mut min = heightmap_max;
let mut max = heightmap_min;
for sy in (y * 8)..(y * 8 + 8)
{
for sx in (x * 8)..(x * 8 + 8)
{
for sy in (y * 8)..(y * 8 + 8) {
for sx in (x * 8)..(x * 8 + 8) {
min = min.min(heightmap[sx + sy * heightmap_width]);
max = max.max(heightmap[sx + sy * heightmap_width]);
}
@@ -254,17 +237,13 @@ where
let mut colormap_mip = vec![0u8; colormap_low_width * colormap_low_height * 3];
for y in 0..colormap_low_height
{
for x in 0..colormap_low_width
{
for y in 0..colormap_low_height {
for x in 0..colormap_low_width {
let mut r = 0u32;
let mut g = 0u32;
let mut b = 0u32;
for sy in (y * 8)..(y * 8 + 8)
{
for sx in (x * 8)..(x * 8 + 8)
{
for sy in (y * 8)..(y * 8 + 8) {
for sx in (x * 8)..(x * 8 + 8) {
r += colormap[(sx + sy * terrain_width) * 3] as u32;
g += colormap[(sx + sy * terrain_width) * 3 + 1] as u32;
b += colormap[(sx + sy * terrain_width) * 3 + 2] as u32;
@@ -318,8 +297,7 @@ where
ny: usize,
nz: usize,
chunk_pos: (usize, usize, usize),
) -> ProducedChunk<N>
{
) -> ProducedChunk<N> {
let node_size = N.pow((self.chunk_power - depth) as u32);
let child_size = node_size / N;
let global_size = N.pow(self.chunk_power as u32);
@@ -332,8 +310,7 @@ where
let gny = chunk_pos.1 * global_size + ny * node_size;
let gnz = chunk_pos.2 * global_size + nz * node_size;
// Iterate on children of this node
for (cx, cz) in (0..N).cartesian_product(0..N)
{
for (cx, cz) in (0..N).cartesian_product(0..N) {
let gcx = gnx + cx * child_size;
let gcz = gnz + cz * child_size;
@@ -345,14 +322,11 @@ where
let mut color_avg = Color(0., 0., 0., 0.);
let mut count = 0;
if depth <= 2
{
for (z, x) in (0..(child_size / 8)).cartesian_product(0..(child_size / 8))
{
if depth <= 2 {
for (z, x) in (0..(child_size / 8)).cartesian_product(0..(child_size / 8)) {
let gvx = (gcx + x * 8) / 8;
let gvz = (gcz + z * 8) / 8;
if gvx < self.colormap_low_width && gvz < self.colormap_low_height
{
if gvx < self.colormap_low_width && gvz < self.colormap_low_height {
// Height sample
let height_x = (gvx * self.heightmap_low_width) / self.colormap_low_width;
let height_z = (gvz * self.heightmap_low_height) / self.colormap_low_height;
@@ -376,15 +350,11 @@ where
}
//let gvy = gcy;
}
}
else
{
for (z, x) in (0..child_size).cartesian_product(0..child_size)
{
} else {
for (z, x) in (0..child_size).cartesian_product(0..child_size) {
let gvx = gcx + x;
let gvz = gcz + z;
if gvx < self.terrain_width && gvz < self.terrain_height
{
if gvx < self.terrain_width && gvz < self.terrain_height {
// Height sample
let height_x = (gvx * self.heightmap_width) / self.terrain_width;
let height_z = (gvz * self.heightmap_height) / self.terrain_height;
@@ -427,32 +397,23 @@ where
(self.chunk_alt * global_size) as f32,
) as usize;
for cy in 0..N
{
for cy in 0..N {
let gcy = gny + cy * child_size;
let index = cz * N * N + cy * N + cx;
let alpha;
let subdivided;
if gcy > sample_max
{
if gcy > sample_max {
subdivided = false;
alpha = 0.;
}
else if gcy + child_size < sample_min
{
} else if gcy + child_size < sample_min {
subdivided = false;
alpha = 1.;
}
else
{
} else {
subdivided = depth < (self.chunk_power - 1);
//children.push(StructurePointer(0));
alpha = if (sample_max + sample_min / 2) > gcy + (child_size / 2)
{
alpha = if (sample_max + sample_min / 2) > gcy + (child_size / 2) {
1.
}
else
{
} else {
0.
};
}
@@ -495,17 +456,14 @@ where
) -> ProducedChunk<N>;
}
pub struct SdfGenerator<const N: usize>
{
pub struct SdfGenerator<const N: usize> {
chunk_power: usize,
perlin: Fbm<Simplex>,
//perlin: Cylinders,
}
impl<const N: usize> SdfGenerator<N>
{
pub fn new(chunk_power: usize) -> Self
{
impl<const N: usize> SdfGenerator<N> {
pub fn new(chunk_power: usize) -> Self {
Self {
chunk_power,
perlin: Fbm::new(67),
@@ -525,10 +483,8 @@ where
ny: usize,
nz: usize,
chunk_pos: (usize, usize, usize),
) -> ProducedChunk<N>
{
fn hash(mut p: [f32; 3]) -> f32
{
) -> ProducedChunk<N> {
fn hash(mut p: [f32; 3]) -> f32 {
p[0] = (p[0] * 127.1 + p[1] * 311.7 + p[2] * 74.7).sin() * 43758.5453123;
p[0].fract()
}
@@ -613,8 +569,7 @@ where
let gny = ny * node_size + cy;
let gnz = nz * node_size + cz;
// Iterate on children of this node
for ((cz, cy), cx) in (0..N).cartesian_product(0..N).cartesian_product(0..N)
{
for ((cz, cy), cx) in (0..N).cartesian_product(0..N).cartesian_product(0..N) {
let gvx = gnx + cx * child_size + (child_size / 2);
let gvy = gny + cy * child_size + (child_size / 2);
let gvz = gnz + cz * child_size + (child_size / 2);
@@ -624,20 +579,15 @@ where
let alpha;
let subdivided;
if dist.abs() < child_diagonal_length
{
if dist.abs() < child_diagonal_length {
//children.push(StructurePointer::new(depth <= 3, false, 0));
subdivided = depth < (self.chunk_power - 1);
alpha = if dist >= 0. { 0. } else { 1. };
//alpha = 0.;
}
else if dist >= 0.
{
} else if dist >= 0. {
subdivided = false;
alpha = 0.;
}
else
{
} else {
subdivided = false;
alpha = 1.;
}
@@ -667,12 +617,9 @@ where
let normal = Vec3::new(a - b - c + d, -a - b + c + d, -a + b - c + d);
let normal = if normal.length() <= f32::EPSILON
{
let normal = if normal.length() <= f32::EPSILON {
Vec3::new(1., 0., 0.)
}
else
{
} else {
normal.normalize()
};
-464
View File
@@ -1,464 +0,0 @@
use std::collections::HashMap;
use std::collections::VecDeque;
use bytemuck::Pod;
use bytemuck::Zeroable;
use itertools::Itertools;
use noise::Terrace;
use vxls_production::tree_locator::TreeLocator;
#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct Color(pub f32, pub f32, pub f32, pub f32);
impl Color
{
pub fn average<I: Iterator<Item = Color>>(iter: I) -> Self
{
let mut c = Color(0., 0., 0., 0.);
let mut count = 0;
for Color(r, g, b, a) in iter
{
count += 1;
c.0 += r;
c.1 += g;
c.2 += b;
c.3 += a;
}
c.0 /= count as f32;
c.1 /= count as f32;
c.2 /= count as f32;
c.3 /= count as f32;
c
}
pub fn as_packed_u32(&self) -> u32
{
let mapped_r = (self.0 * 255.0).clamp(0., 255.0) as u32;
let mapped_g = (self.1 * 255.0).clamp(0., 255.0) as u32;
let mapped_b = (self.2 * 255.0).clamp(0., 255.0) as u32;
let mapped_a = (self.3 * 255.0).clamp(0., 255.0) as u32;
mapped_r | (mapped_g << 8) | (mapped_b << 16) | (mapped_a << 24)
}
}
#[derive(Debug, Clone)]
pub struct NTree<const N: usize>
{
map: HashMap<TreeLocator<N>, NTreeNode>,
// Depth is the parameter such that
// N^depth == max_number_of_voxels
// one root => depth = 1
depth: usize,
}
pub struct NTreeIter<'a, const N: usize>
{
tree: &'a NTree<N>,
dfs_stack: Vec<TreeLocator<N>>,
}
#[derive(Debug, Clone, Copy)]
pub struct NTreeNode
{
pub color: Color,
pub subdivided: bool,
}
impl<const N: usize> NTree<N>
where
[(); N * N * N]:,
{
pub fn constant(color: Color, depth: usize) -> Self
{
let mut map = HashMap::new();
let root = NTreeNode {
color,
subdivided: false,
};
map.insert(TreeLocator::<N>::root(), root);
Self { map, depth }
}
pub fn set(&mut self, x: usize, y: usize, z: usize, color: Color)
{
self.set_at_depth(x, y, z, self.depth, color);
}
pub fn get(&self, x: usize, y: usize, z: usize) -> Color
{
assert!(x < N.pow(self.depth as u32));
assert!(y < N.pow(self.depth as u32));
assert!(z < N.pow(self.depth as u32));
// Try to walk down the tree, and create necessary nodes
let mut current_node_loc = TreeLocator::<N>::root();
let mut current_node_size = N.pow(self.depth as u32);
let mut current_node = self.map.get(&current_node_loc).unwrap();
loop
{
if !current_node.subdivided
{
return current_node.color;
}
// Descend to relevant node,
let child_node_size = current_node_size / N;
let child_x = (x % current_node_size) / child_node_size;
let child_y = (y % current_node_size) / child_node_size;
let child_z = (z % current_node_size) / child_node_size;
current_node_size = child_node_size;
current_node_loc =
current_node_loc.child(child_x as u32, child_y as u32, child_z as u32);
current_node = self.map.get(&current_node_loc).unwrap();
}
}
pub fn set_at_depth(&mut self, x: usize, y: usize, z: usize, depth: usize, color: Color)
{
assert!(x < N.pow(depth as u32));
assert!(y < N.pow(depth as u32));
assert!(z < N.pow(depth as u32));
// Try to walk down the tree, and create necessary nodes
let mut current_node_loc = TreeLocator::<N>::root();
let mut current_node_size = N.pow(self.depth as u32);
let mut current_depth = 0;
let mut current_node = self.map.get_mut(&current_node_loc).unwrap();
while current_depth != depth
{
if current_node.color == color
{
// Color is already correct, work is finished
return;
}
// Current is not subdivided, and color is different => subdivide
if !current_node.subdivided
{
current_node.subdivided = true;
let new_nodes = NTreeNode {
color: current_node.color,
subdivided: false,
};
current_node_loc.children().for_each(|child| {
self.map.insert(child, new_nodes);
});
}
// Descend to relevant node,
let child_node_size = current_node_size / N;
let child_x = (x % current_node_size) / child_node_size;
let child_y = (y % current_node_size) / child_node_size;
let child_z = (z % current_node_size) / child_node_size;
current_node_size = child_node_size;
current_depth += 1;
current_node_loc =
current_node_loc.child(child_x as u32, child_y as u32, child_z as u32);
current_node = self.map.get_mut(&current_node_loc).unwrap();
}
if current_node.subdivided
{
self.make_constant(current_node_loc, color);
}
else
{
current_node.color = color;
}
// We need to go back up the hierarchy to combine nodes
// current_node is the modified node, go one up
loop
{
// Go one node up
current_depth -= 1;
current_node_loc = current_node_loc.parent().unwrap();
//current_node_size *= N;
// Access all children's colors
let children_color_avg = current_node_loc
.children()
.map(|child_loc| self.map.get(&child_loc).unwrap().color)
// AGGREGATE AND AVERAGE HERE !!
.next()
.unwrap();
current_node = self.map.get_mut(&current_node_loc).unwrap();
current_node.color = children_color_avg;
if current_depth == 0
{
break;
}
}
}
fn make_constant(&mut self, locator: TreeLocator<N>, color: Color)
{
let mut dfs_stack = Vec::new();
dfs_stack.push(locator);
while let Some(current) = dfs_stack.pop()
{
// Remove element
let removed = self.map.remove(&current);
let handle_children = removed.is_some_and(|x| x.subdivided);
// If children have to be handled, push on stack
if handle_children
{
dfs_stack.extend(current.children());
}
}
self.map.insert(
locator,
NTreeNode {
color,
subdivided: false,
},
);
}
pub fn from_array(array: &[Color], depth: usize) -> Self
{
let mut structure = HashMap::new();
// Per voxel in the array :
// 0 -> Voxel not merged yet
// _ -> size of the block in which the voxel was merged
let mut merged_size = vec![0; array.len()];
let width = N.pow(depth as u32);
for (z, y) in (0..width).cartesian_product(0..width)
{
let mut x = 0;
while x < width
{
if merged_size[x + y * width + z * width * width] != 0
{
// If current voxel has already been accounted for -> skip
// We stumbled on a big merged block, we can skip it as a whole on the inner
// dimension
x += merged_size[x + y * width + z * width * width];
continue;
}
// Check smallest depth aligned with current position
let x_trailing = base_trailing_zeroes::<N>(x).unwrap_or(depth as u32);
let y_trailing = base_trailing_zeroes::<N>(y).unwrap_or(depth as u32);
let z_trailing = base_trailing_zeroes::<N>(z).unwrap_or(depth as u32);
// Biggest block size power of which this voxel can be a lower corner
let block_power = x_trailing.min(y_trailing.min(z_trailing));
// Try to merge for each depth
let mut max_power_merge = 0; // Single voxel can always be merged
let color = array[x + y * width + z * width * width];
let mut locator =
TreeLocator::<N>::from_node_coords(depth as u32, x as u32, y as u32, z as u32);
'power_search: for power in 1..=block_power
{
let block_size = N.pow(power);
// Check if candidate block has the same color
for ((merge_z, merge_y), merge_x) in (0..block_size)
.cartesian_product(0..block_size)
.cartesian_product(0..block_size)
{
if array
[(x + merge_x) + (y + merge_y) * width + (z + merge_z) * width * width]
!= color
{
break 'power_search;
}
}
// Update biggest candidate block
locator = locator.parent().unwrap();
max_power_merge = power;
}
// We know which size we can know merge
// Say we accounted for those voxels :
let block_size = N.pow(max_power_merge);
for ((merge_z, merge_y), merge_x) in (0..block_size)
.cartesian_product(0..block_size)
.cartesian_product(0..block_size)
{
merged_size
[(x + merge_x) + (y + merge_y) * width + (z + merge_z) * width * width] =
block_size;
}
// Add new found block in our structure
// If power is depth, this is the whole structure, thus depth is 0
let node = NTreeNode {
color,
subdivided: false,
};
structure.insert(locator, node);
x += block_size;
}
}
// The structure now consists of the leaf most nodes, we need to rebuild the hierarchy
// bottom up
for current_power in 1..=depth
{
// Iterate on the blocks of this size
let block_size = N.pow(current_power as u32);
let block_count = width / block_size;
for ((block_x, block_y), block_z) in (0..block_count)
.cartesian_product(0..block_count)
.cartesian_product(0..block_count)
{
// Check the lower corner of this block
let corner = merged_size[(block_x * block_size)
+ (block_y * block_size) * width
+ (block_z * block_size) * width * width];
if corner >= block_size
{
// Children are merged in bigger block
continue;
}
// Add hierarchy node
let locator = TreeLocator::<N>::from_node_coords(
(depth - current_power) as u32,
block_x as u32,
block_y as u32,
block_z as u32,
);
// Get average color of children
let color = Color::average(
locator
.children()
.map(|child_loc| structure.get(&child_loc).unwrap().color),
);
let hierarchy_node = NTreeNode {
color,
subdivided: true,
};
structure.insert(locator, hierarchy_node);
}
}
Self {
map: structure,
depth,
}
}
pub fn get_by_loc(&self, locator: TreeLocator<N>) -> Option<NTreeNode>
{
self.map.get(&locator).copied()
}
}
fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32>
{
if number == 0
{
return None;
}
let mut trailing_zeroes = 0;
while number % N == 0
{
number /= N;
trailing_zeroes += 1;
}
Some(trailing_zeroes)
}
pub fn load_ply<P: AsRef<std::path::Path>, const N: usize>(path: P) -> NTree<N>
where
[(); N * N * N]:,
{
let file = std::fs::read_to_string(path).unwrap();
let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
for line in file.lines()
{
let coords = line
.split(',')
.take(3)
.map(|s| s.trim_end().trim_start().parse::<u32>().unwrap())
.collect::<Vec<_>>();
let (x, y, z) = (coords[0], coords[1], coords[2]);
let index = x + z * 256 + y * 256 * 256;
colors[index as usize] = Color(1., 1., 1., 1.);
}
NTree::from_array(&colors, 4)
}
mod test
{
use glam::Vec3;
use rand::random;
use vxls_production::tree_locator::TreeLocator;
use crate::sparse_tree::Color;
use crate::sparse_tree::NTree;
#[test]
fn constant_set()
{
let mut tree = NTree::<4>::constant(Color(0., 0., 0., 0.), 4);
assert!(tree.get(0, 0, 0) == Color(0., 0., 0., 0.));
tree.set(0, 0, 0, Color(1., 1., 1., 1.));
assert!(tree.get(0, 0, 0) == Color(1., 1., 1., 1.));
}
#[test]
fn load_read_same()
{
let file = std::fs::read_to_string(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../dragon.txt"
))
.unwrap();
let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
for line in file.lines()
{
let coords = line
.split(',')
.take(3)
.map(|s| s.trim_end().trim_start().parse::<u32>().unwrap())
.collect::<Vec<_>>();
let (x, y, z) = (coords[0], coords[1], coords[2]);
let index = x + z * 256 + y * 256 * 256;
colors[index as usize] = Color(1., 1., 1., 1.);
}
println!("building tree");
let tree = NTree::<4>::from_array(&colors, 4);
println!("ok");
for x in 0..256
{
for y in 0..256
{
for z in 0..256
{
let index = x + y * 256 + z * 256 * 256;
let color = colors[index];
let t = tree.get(x, y, z);
assert!(t == color);
}
}
}
}
}