diff --git a/src/main.rs b/src/main.rs index cf8029d..774b608 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,9 +2,12 @@ #![feature(float_algebraic)] use std::collections::HashMap; +use std::marker::PhantomData; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU32; +use std::sync::mpsc::Sender; +use std::thread::Thread; use bytemuck::Pod; use bytemuck::Zeroable; @@ -59,6 +62,12 @@ use crate::gpu_profiler::ProfilingEncoder; use crate::producers::ChunkedProducer; use crate::producers::SdfGenerator; use crate::producers::TerrainGenerator; +use crate::production::request_queue::FrameId; +use crate::production::request_queue::IncomingRequest; +use crate::production::request_queue::QueueConfig; +use crate::production::request_queue::RequestKey; +use crate::production::request_queue::RequestQueue; +use crate::production::request_queue::RequestTarget; use crate::sparse_tree::NTreeNodeLocator; use crate::terrain::ToroidalStructureTable; use crate::voxel_cache::VoxelCache; @@ -93,6 +102,16 @@ enum DisplayTexture Albedo, } +struct VoxelPayload +where + [(); N * N * N]:, +{ + color: [u32; N * N * N], + normal: [[f32; 3]; N * N * N], + insertion_information: InsertionInformation, + location_page: LocationPage, +} + struct State { instance: wgpu::Instance, @@ -118,6 +137,7 @@ struct State gi_bg_layout: BindGroupLayout, voxel_cache: Arc>>, + request_queue: Arc>>>, request_buffer: Arc, cache_insertion: Arc>, @@ -125,8 +145,6 @@ struct State structure_table: Arc>, structure_table_request_buffer: Arc, structure_table_cache_insertion: Arc>, - terrain_generator: Arc>, - //terrain_generator: Arc>, chunk_pos_map: Arc>, instance_buffer: Buffer, instance_count: usize, @@ -144,6 +162,9 @@ struct State camera: Camera, cursor_grabed: bool, + + // Producers workers + wakeup: Sender<()>, } pub unsafe fn as_raw_bytes(slice: &[T]) -> &[u8] @@ -662,6 +683,67 @@ impl State cache: None, }); + let structure_table = Arc::new(Mutex::new(structure_table)); + let structure_table_1 = structure_table.clone(); + let request_queue = Arc::new(Mutex::new(RequestQueue::new(QueueConfig::default()))); + 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() + { + break; + } + + loop + { + // Try to get some work from the queue + let mut work = vec![]; + { + let mut locked = request_queue_1.lock(); + while let Some(work_item) = locked.pop() + && work.len() < 128 + { + work.push(work_item); + } + } + + if work.is_empty() + { + break; + } + + let finshed = work + .par_iter() + .map(|work_item| { + let d = fullfill_request( + &terrain_generator, + &work_item.key, + &Default::default(), + &structure_table_1, + ); + ( + work_item, + VoxelPayload { + color: d.0, + normal: d.1, + insertion_information: d.2, + location_page: d.3, + }, + ) + }) + .collect::>(); + + { + let mut locked = request_queue_1.lock(); + finshed.into_iter().for_each(|(work_item, payload)| { + locked.complete(*work_item, payload); + }); + } + } + } + }); let state = State { instance, window, @@ -701,10 +783,11 @@ impl State usage_vec: Arc::new(Mutex::new(vec![])), pipeline: chunk_pipeline, voxel_cache: Arc::new(Mutex::new(voxel_cache)), + request_queue, request_buffer: Arc::new(request_buffer), cache_insertion: Arc::new(insertion_data), - structure_table: Arc::new(Mutex::new(structure_table)), + structure_table, structure_table_cache_insertion: Arc::new(structure_table_insertion_data), structure_table_request_buffer: Arc::new(structure_table_request_buffer), @@ -712,7 +795,6 @@ impl State camera: Default::default(), instance_buffer, instance_count, - terrain_generator: Arc::new(terrain_generator), chunk_pos_map: chunk_pos_map.into(), rm_time: Arc::new(Mutex::new(0.)), frame_time: Arc::new(Mutex::new(0.)), @@ -722,6 +804,7 @@ impl State profile: Arc::new(Mutex::new(Profile::default())), insert_profile: Arc::new(Mutex::new(Profile::default())), cursor_grabed: true, + wakeup: wakeup_tx, }; // Configure surface for the first time @@ -1284,8 +1367,8 @@ impl State .contains(&winit::keyboard::KeyCode::KeyF) { self.insertion_debounce = true; + let frame_id: FrameId = self.voxel_cache.lock().current_timestamp().into(); let cloned_queue = self.queue.clone(); - let cloned_generator = self.terrain_generator.clone(); let cloned_map = self.chunk_pos_map.clone(); let finished = Arc::new(AtomicU32::new(0)); @@ -1294,7 +1377,7 @@ impl State let request_buffer_done = Arc::new(AtomicBool::new(false)); let request_buffer_done_1 = request_buffer_done.clone(); let finshed_1 = finished.clone(); - let cloned_table_1 = self.structure_table.clone(); + let request_queue_1 = self.request_queue.clone(); self.request_buffer.host_download_requests( &self.device, &self.queue, @@ -1310,7 +1393,19 @@ impl State return; } - //println!("Cache : {} requests", request_informations.len()); + request_queue_1.lock().ingest( + frame_id, + request_informations + .iter() + .zip(request_metas.iter()) + .map(|(info, meta)| IncomingRequest::from_wire(info, meta)), + ); + //println!("Structure table: {} requests", request_informations.len()); + + let drained = + request_queue_1 + .lock() + .drain_ready_matching(frame_id, 1024, |key| !key.is_root()); let mut insertion_infos = vec![]; let mut color_attributes = vec![]; @@ -1318,27 +1413,13 @@ impl State let mut location_pages = vec![]; let mut insertion_parents = vec![]; - request_informations - .par_iter() - .zip(request_metas.par_iter()) - .map(|(request, meta)| { - fullfill_request( - cloned_generator.as_ref(), - request, - meta, - cloned_map.as_ref(), - &cloned_table_1, - ) - }) - .collect::>() - .into_iter() - .for_each(|(colors, normals, insertion_info, location, parent)| { - insertion_infos.push(insertion_info); - color_attributes.push(colors); - normal_attributes.push(std::array::from_fn(|i| normals[i].into())); - location_pages.push(location); - insertion_parents.push(parent); - }); + drained.into_iter().for_each(|payload| { + insertion_infos.push(payload.payload.insertion_information); + color_attributes.push(payload.payload.color); + normal_attributes.push(payload.payload.normal); + location_pages.push(payload.payload.location_page); + insertion_parents.push(payload.insertion_parent()); + }); let request_count = request_informations.len() as u32; @@ -1393,7 +1474,6 @@ impl State ); let cloned_queue = self.queue.clone(); - let cloned_generator = self.terrain_generator.clone(); let cloned_map = self.chunk_pos_map.clone(); // Structure table requests @@ -1402,6 +1482,7 @@ impl State let structure_table_request_buffer_done_1 = structure_table_request_buffer_done.clone(); let finshed_2 = finished.clone(); let cloned_table_2 = self.structure_table.clone(); + let request_queue_2 = self.request_queue.clone(); self.structure_table_request_buffer.host_download_requests( &self.device, &self.queue, @@ -1419,6 +1500,19 @@ impl State return; } + request_queue_2.lock().ingest( + frame_id, + request_informations + .iter() + .zip(request_metas.iter()) + .map(|(info, meta)| IncomingRequest::from_wire(info, meta)), + ); + + let drained = + request_queue_2 + .lock() + .drain_ready_matching(frame_id, 128, |key| key.is_root()); + //println!("Structure table: {} requests", request_informations.len()); let mut insertion_infos = vec![]; @@ -1427,27 +1521,13 @@ impl State let mut location_pages = vec![]; let mut insertion_parents = vec![]; - request_informations - .par_iter() - .zip(request_metas.par_iter()) - .map(|(request, meta)| { - fullfill_request( - cloned_generator.as_ref(), - request, - meta, - cloned_map.as_ref(), - &cloned_table_2, - ) - }) - .collect::>() - .into_iter() - .for_each(|(colors, normals, insertion_info, location, parent)| { - insertion_infos.push(insertion_info); - color_attributes.push(colors); - normal_attributes.push(std::array::from_fn(|i| normals[i].into())); - location_pages.push(location); - insertion_parents.push(parent); - }); + drained.into_iter().for_each(|payload| { + insertion_infos.push(payload.payload.insertion_information); + color_attributes.push(payload.payload.color); + normal_attributes.push(payload.payload.normal); + location_pages.push(payload.payload.location_page); + insertion_parents.push(payload.insertion_parent()); + }); let request_count = request_informations.len() as u32; @@ -1501,148 +1581,8 @@ impl State }, ); - // ~~ Download request buffer, fullfill requests, writeback to cache ~~ - /* - DownloadBuffer::read_buffer( - &self.device.clone(), - &self.queue.clone(), - &self.request_buffer.requests_buffer().slice(..), - move |buffer| { - if tx.try_send(()).is_err() - { - return; - } + self.wakeup.send(()).unwrap(); - let cache_node_requests: Vec = - bytemuck::pod_collect_to_vec(&buffer.unwrap()); - - let generator = cloned_generator; - //let gen_test = SineGenerator::<4>::new(5); - - let mut structure_nodes: Vec> = vec![]; - let mut color_nodes: Vec<[ColorBytes; 64]> = vec![]; - let mut normal_nodes: Vec<[(f32, f32, f32); 64]> = vec![]; - let mut location_nodes = vec![]; - - cache_node_requests - .par_iter() - .take(request_count as usize) - .map(|request| { - // Unpack structure id - let (chunk_x, chunk_y, chunk_z) = - *cloned_map.get(&request.structure_id).unwrap(); - - let location; - let node; - if request.locator == 0 - { - // Produce root node - node = - generator.produce_node(0, 0, 0, 0, (chunk_x, chunk_y, chunk_z)); - location = LocationPoolElement { - structure_id: request.structure_id, - structure_locator: NTreeNodeLocator::<4>::root().as_usize() - as u32, - }; - } - else - { - // Figure out depth of request - let locator = - NTreeNodeLocator::<4>::from_usize(request.locator as usize); - let depth = locator.depth(); - //let (x, y, z) = locator.node_location(); - - let child_z = request.child_index / (4 * 4); - let child_y = (request.child_index % (4 * 4)) / 4; - let child_x = request.child_index % 4; - - let child_locator = locator.child( - child_x as usize, - child_y as usize, - child_z as usize, - ); - - let (nx, ny, nz) = child_locator.node_location(); - - node = generator.produce_node( - depth + 1, - nx, - ny, - nz, - (chunk_x, chunk_y, chunk_z), - ); - - location = LocationPoolElement { - structure_id: request.structure_id, - structure_locator: child_locator.as_usize() as u32, - }; - } - - ( - StructurePoolElement { - occupancy_low: 0, - occupancy_high: 0, - pointers: node.structure, - }, - node.colors, - node.normals, - location, - ) - }) - .collect::>() - .into_iter() - .for_each(|data| { - structure_nodes.push(data.0); - color_nodes.push(std::array::from_fn(|i| data.1[i].into())); - normal_nodes.push(data.2); - location_nodes.push(data.3); - }); - - if structure_nodes.len() != 0 - { - cloned_queue.write_buffer( - cloned_cache_interface.structure_nodes_buffer(), - 0, - unsafe { as_raw_bytes(structure_nodes.as_slice()) }, - ); - cloned_queue.write_buffer( - &cloned_cache_interface.attributes_buffers()[0], - 0, - unsafe { as_raw_bytes(color_nodes.as_slice()) }, - ); - cloned_queue.write_buffer( - &cloned_cache_interface.attributes_buffers()[1], - 0, - unsafe { as_raw_bytes(normal_nodes.as_slice()) }, - ); - cloned_queue.write_buffer( - cloned_cache_interface.location_nodes_buffer(), - 0, - unsafe { as_raw_bytes(location_nodes.as_slice()) }, - ); - - let mut encoder = cloned_device.create_command_encoder(&Default::default()); - let mut profiled_encoder = - ProfilingEncoder::new(&cloned_device, &mut encoder); - { - gpu_profiler::begin_frame!(profiled_encoder, "Cache insertion"); - { - cloned_cache - .lock() - .cache_insert(&mut profiled_encoder, &cloned_cache_interface); - } - } - let profile = profiled_encoder.finish_profiler(); - cloned_queue.submit([encoder.finish()]); - profile.read_back(&cloned_device, &cloned_queue, move |mut profile| { - *cloned_insert_profile.lock() = profile; - }); - } - }, - ); - */ - //println!("Total request count: {}", request_count); loop { if finished.load(std::sync::atomic::Ordering::Relaxed) >= 2 @@ -1666,9 +1606,7 @@ impl State &self.structure_table_cache_insertion, &mut *locked_st, ), - &mut VoxelCacheInsertion::InternalRequest( - &self.cache_insertion, - ), + &mut VoxelCacheInsertion::InternalRequest(&self.cache_insertion), ], ); @@ -1813,8 +1751,7 @@ pub struct ChunkImmediate fn fullfill_request( generator: &dyn ChunkedProducer, - request: &RequestInformation, - meta: &RequestMeta, + request: &RequestKey, map: &HashMap, table: &Arc>, ) -> ( @@ -1822,14 +1759,13 @@ fn fullfill_request( [[f32; 3]; N * N * N], InsertionInformation, LocationPage, - InsertionParent, ) where [(); N * N * N]:, { // Unpack structure id //let (chunk_x, chunk_y, chunk_z) = *map.get(&request.structure_id).unwrap(); - let (chunk_x, chunk_y, chunk_z) = table.lock().get_request_position(request.structure_id); + let (chunk_x, chunk_y, chunk_z) = table.lock().get_request_position(request.structure_id.0); // let (chunk_x, chunk_y, chunk_z) = ( // (u32::MAX as isize + chunk_x) as usize, @@ -1849,30 +1785,36 @@ where let location; let node; - let parent; - if meta.page_index == NO_PARENT_PAGE + if request.is_root() { // Produce root node. An external (structure-table) request is the only // one without a parent page; `node_id == 0` also happens for child 0 of // the root, so it cannot be used to detect roots. node = generator.produce_node(0, 0, 0, 0, (chunk_x, chunk_y, chunk_z)); location = LocationPage { - structure_id: request.structure_id, + structure_id: request.structure_id.0, node_id: NTreeNodeLocator::<4>::root().as_usize() as u32, - producer_id: request.producer_id, + producer_id: request.producer_id.0, }; - parent = InsertionParent::external(request.structure_id, request.producer_id); } else { + let RequestTarget::Child { + parent, + children_index, + } = &request.target + else + { + unreachable!(); + }; // Figure out depth of request - let locator = NTreeNodeLocator::<4>::from_usize(request.node_id as usize); + let locator = NTreeNodeLocator::<4>::from_usize(parent.0 as usize); let depth = locator.depth(); //let (x, y, z) = locator.node_location(); - let child_z = request.children_index / (4 * 4); - let child_y = (request.children_index % (4 * 4)) / 4; - let child_x = request.children_index % 4; + let child_z = children_index / (4 * 4); + let child_y = (children_index % (4 * 4)) / 4; + let child_x = children_index % 4; let child_locator = locator.child(child_x as usize, child_y as usize, child_z as usize); @@ -1881,16 +1823,10 @@ where node = generator.produce_node(depth + 1, nx, ny, nz, (chunk_x, chunk_y, chunk_z)); location = LocationPage { - structure_id: request.structure_id, + structure_id: request.structure_id.0, node_id: child_locator.as_usize() as u32, - producer_id: request.producer_id, + producer_id: request.producer_id.0, }; - parent = InsertionParent::internal( - meta, - request.structure_id, - request.node_id, - request.producer_id, - ); } ( @@ -1900,6 +1836,5 @@ where children: node.children, }, location, - parent, ) }