forked from StrafesNET/strafe-client
Compare commits
63 Commits
master
...
graphics-t
Author | SHA1 | Date | |
---|---|---|---|
14f3b4fb0d | |||
6377885d6d | |||
f81a1c82bf | |||
2ee70138d1 | |||
f14b30138b | |||
2116621672 | |||
e2fdf9442c | |||
75f958348c | |||
b5a0cf7045 | |||
657e5dff7f | |||
5d9308eccc | |||
b7844bb308 | |||
8113ede3e0 | |||
4cf10dad78 | |||
de063f4d74 | |||
83cdb0413c | |||
4655f43f5f | |||
9c9d8f8f8f | |||
cbc7b56f28 | |||
44831bd14b | |||
099915c980 | |||
62e8953ba9 | |||
03a4a60db2 | |||
c4ad4fbdf9 | |||
b445277346 | |||
f6f2995ae0 | |||
4cad20da09 | |||
7805c4db6d | |||
3775fd0b14 | |||
2356286dc2 | |||
8cc86d88fc | |||
c1bc67fd3a | |||
d2c896031c | |||
d27187aa53 | |||
2e13d9b74e | |||
431611b62a | |||
b55a35c488 | |||
cb6102b9dc | |||
6eaec7d6a6 | |||
407b322664 | |||
d4c4d9e7d6 | |||
ff8c61ee32 | |||
00eb1ce19c | |||
168091408e | |||
ad0130db74 | |||
ee8f9ba9e4 | |||
1af8468e5b | |||
f8320c9df5 | |||
eb376c1e68 | |||
0bf253aa11 | |||
85b70331fd | |||
7fd592329e | |||
5260c2b40d | |||
b5febfad14 | |||
d1b491b6e7 | |||
8043862c99 | |||
b760a4bc65 | |||
124139274f | |||
7130eafc06 | |||
ab276b517b | |||
3721995791 | |||
72258d3549 | |||
02170bd91a |
817
Cargo.lock
generated
817
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -6,14 +6,11 @@ edition = "2021"
|
|||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-executor = "1.5.1"
|
|
||||||
bytemuck = { version = "1.13.1", features = ["derive"] }
|
bytemuck = { version = "1.13.1", features = ["derive"] }
|
||||||
configparser = "3.0.2"
|
configparser = "3.0.2"
|
||||||
ddsfile = "0.5.1"
|
ddsfile = "0.5.1"
|
||||||
env_logger = "0.10.0"
|
|
||||||
glam = "0.24.1"
|
glam = "0.24.1"
|
||||||
lazy-regex = "3.0.2"
|
lazy-regex = "3.0.2"
|
||||||
log = "0.4.20"
|
|
||||||
obj = "0.10.2"
|
obj = "0.10.2"
|
||||||
parking_lot = "0.12.1"
|
parking_lot = "0.12.1"
|
||||||
pollster = "0.3.0"
|
pollster = "0.3.0"
|
||||||
@ -22,7 +19,7 @@ rbx_dom_weak = "2.5.0"
|
|||||||
rbx_reflection_database = "0.2.7"
|
rbx_reflection_database = "0.2.7"
|
||||||
rbx_xml = "0.13.1"
|
rbx_xml = "0.13.1"
|
||||||
wgpu = "0.17.0"
|
wgpu = "0.17.0"
|
||||||
winit = "0.28.6"
|
winit = { version = "0.29.2", features = ["rwh_05"] }
|
||||||
|
|
||||||
#[profile.release]
|
#[profile.release]
|
||||||
#lto = true
|
#lto = true
|
||||||
|
21
src/compat_worker.rs
Normal file
21
src/compat_worker.rs
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
pub type QNWorker<'a,Task>=CompatNWorker<'a,Task>;
|
||||||
|
pub type INWorker<'a,Task>=CompatNWorker<'a,Task>;
|
||||||
|
|
||||||
|
pub struct CompatNWorker<'a,Task>{
|
||||||
|
data:std::marker::PhantomData<Task>,
|
||||||
|
f:Box<dyn FnMut(Task)+'a>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a,Task> CompatNWorker<'a,Task>{
|
||||||
|
pub fn new(f:impl FnMut(Task)+'a)->CompatNWorker<'a,Task>{
|
||||||
|
Self{
|
||||||
|
data:std::marker::PhantomData,
|
||||||
|
f:Box::new(f),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send(&mut self,task:Task)->Result<(),()>{
|
||||||
|
(self.f)(task);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
516
src/framework.rs
516
src/framework.rs
@ -1,516 +0,0 @@
|
|||||||
use std::future::Future;
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
use std::str::FromStr;
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas};
|
|
||||||
use winit::{
|
|
||||||
event::{self, WindowEvent, DeviceEvent},
|
|
||||||
event_loop::{ControlFlow, EventLoop},
|
|
||||||
};
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn cast_slice<T>(data: &[T]) -> &[u8] {
|
|
||||||
use std::{mem::size_of, slice::from_raw_parts};
|
|
||||||
|
|
||||||
unsafe { from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::<T>()) }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub enum ShaderStage {
|
|
||||||
Vertex,
|
|
||||||
Fragment,
|
|
||||||
Compute,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait Example: 'static + Sized {
|
|
||||||
fn optional_features() -> wgpu::Features {
|
|
||||||
wgpu::Features::empty()
|
|
||||||
}
|
|
||||||
fn required_features() -> wgpu::Features {
|
|
||||||
wgpu::Features::empty()
|
|
||||||
}
|
|
||||||
fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities {
|
|
||||||
wgpu::DownlevelCapabilities {
|
|
||||||
flags: wgpu::DownlevelFlags::empty(),
|
|
||||||
shader_model: wgpu::ShaderModel::Sm5,
|
|
||||||
..wgpu::DownlevelCapabilities::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn required_limits() -> wgpu::Limits {
|
|
||||||
wgpu::Limits::downlevel_webgl2_defaults() // These downlevel limits will allow the code to run on all possible hardware
|
|
||||||
}
|
|
||||||
fn init(
|
|
||||||
config: &wgpu::SurfaceConfiguration,
|
|
||||||
adapter: &wgpu::Adapter,
|
|
||||||
device: &wgpu::Device,
|
|
||||||
queue: &wgpu::Queue,
|
|
||||||
) -> Self;
|
|
||||||
fn resize(
|
|
||||||
&mut self,
|
|
||||||
config: &wgpu::SurfaceConfiguration,
|
|
||||||
device: &wgpu::Device,
|
|
||||||
queue: &wgpu::Queue,
|
|
||||||
);
|
|
||||||
fn update(&mut self, window: &winit::window::Window, device: &wgpu::Device, queue: &wgpu::Queue, event: WindowEvent);
|
|
||||||
fn device_event(&mut self, window: &winit::window::Window, event: DeviceEvent);
|
|
||||||
fn load_file(&mut self, path:std::path::PathBuf, device: &wgpu::Device, queue: &wgpu::Queue);
|
|
||||||
fn render(
|
|
||||||
&mut self,
|
|
||||||
view: &wgpu::TextureView,
|
|
||||||
device: &wgpu::Device,
|
|
||||||
queue: &wgpu::Queue,
|
|
||||||
spawner: &Spawner,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Setup {
|
|
||||||
window: winit::window::Window,
|
|
||||||
event_loop: EventLoop<()>,
|
|
||||||
instance: wgpu::Instance,
|
|
||||||
size: winit::dpi::PhysicalSize<u32>,
|
|
||||||
surface: wgpu::Surface,
|
|
||||||
adapter: wgpu::Adapter,
|
|
||||||
device: wgpu::Device,
|
|
||||||
queue: wgpu::Queue,
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
offscreen_canvas_setup: Option<OffscreenCanvasSetup>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
struct OffscreenCanvasSetup {
|
|
||||||
offscreen_canvas: OffscreenCanvas,
|
|
||||||
bitmap_renderer: ImageBitmapRenderingContext,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn setup<E: Example>(title: &str) -> Setup {
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
|
||||||
{
|
|
||||||
env_logger::init();
|
|
||||||
};
|
|
||||||
|
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
let mut builder = winit::window::WindowBuilder::new();
|
|
||||||
builder = builder.with_title(title);
|
|
||||||
#[cfg(windows_OFF)] // TODO
|
|
||||||
{
|
|
||||||
use winit::platform::windows::WindowBuilderExtWindows;
|
|
||||||
builder = builder.with_no_redirection_bitmap(true);
|
|
||||||
}
|
|
||||||
let window = builder.build(&event_loop).unwrap();
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
{
|
|
||||||
use winit::platform::web::WindowExtWebSys;
|
|
||||||
let query_string = web_sys::window().unwrap().location().search().unwrap();
|
|
||||||
let level: log::Level = parse_url_query_string(&query_string, "RUST_LOG")
|
|
||||||
.and_then(|x| x.parse().ok())
|
|
||||||
.unwrap_or(log::Level::Error);
|
|
||||||
console_log::init_with_level(level).expect("could not initialize logger");
|
|
||||||
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
|
|
||||||
// On wasm, append the canvas to the document body
|
|
||||||
web_sys::window()
|
|
||||||
.and_then(|win| win.document())
|
|
||||||
.and_then(|doc| doc.body())
|
|
||||||
.and_then(|body| {
|
|
||||||
body.append_child(&web_sys::Element::from(window.canvas()))
|
|
||||||
.ok()
|
|
||||||
})
|
|
||||||
.expect("couldn't append canvas to document body");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
let mut offscreen_canvas_setup: Option<OffscreenCanvasSetup> = None;
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
{
|
|
||||||
use wasm_bindgen::JsCast;
|
|
||||||
use winit::platform::web::WindowExtWebSys;
|
|
||||||
|
|
||||||
let query_string = web_sys::window().unwrap().location().search().unwrap();
|
|
||||||
if let Some(offscreen_canvas_param) =
|
|
||||||
parse_url_query_string(&query_string, "offscreen_canvas")
|
|
||||||
{
|
|
||||||
if FromStr::from_str(offscreen_canvas_param) == Ok(true) {
|
|
||||||
log::info!("Creating OffscreenCanvasSetup");
|
|
||||||
|
|
||||||
let offscreen_canvas =
|
|
||||||
OffscreenCanvas::new(1024, 768).expect("couldn't create OffscreenCanvas");
|
|
||||||
|
|
||||||
let bitmap_renderer = window
|
|
||||||
.canvas()
|
|
||||||
.get_context("bitmaprenderer")
|
|
||||||
.expect("couldn't create ImageBitmapRenderingContext (Result)")
|
|
||||||
.expect("couldn't create ImageBitmapRenderingContext (Option)")
|
|
||||||
.dyn_into::<ImageBitmapRenderingContext>()
|
|
||||||
.expect("couldn't convert into ImageBitmapRenderingContext");
|
|
||||||
|
|
||||||
offscreen_canvas_setup = Some(OffscreenCanvasSetup {
|
|
||||||
offscreen_canvas,
|
|
||||||
bitmap_renderer,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
log::info!("Initializing the surface...");
|
|
||||||
|
|
||||||
let backends = wgpu::util::backend_bits_from_env().unwrap_or_else(wgpu::Backends::all);
|
|
||||||
let dx12_shader_compiler = wgpu::util::dx12_shader_compiler_from_env().unwrap_or_default();
|
|
||||||
|
|
||||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
|
||||||
backends,
|
|
||||||
dx12_shader_compiler,
|
|
||||||
});
|
|
||||||
let (size, surface) = unsafe {
|
|
||||||
let size = window.inner_size();
|
|
||||||
|
|
||||||
#[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))]
|
|
||||||
let surface = instance.create_surface(&window).unwrap();
|
|
||||||
#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
|
|
||||||
let surface = {
|
|
||||||
if let Some(offscreen_canvas_setup) = &offscreen_canvas_setup {
|
|
||||||
log::info!("Creating surface from OffscreenCanvas");
|
|
||||||
instance.create_surface_from_offscreen_canvas(
|
|
||||||
offscreen_canvas_setup.offscreen_canvas.clone(),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
instance.create_surface(&window)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
(size, surface)
|
|
||||||
};
|
|
||||||
|
|
||||||
let adapter;
|
|
||||||
|
|
||||||
let optional_features = E::optional_features();
|
|
||||||
let required_features = E::required_features();
|
|
||||||
|
|
||||||
//no helper function smh gotta write it myself
|
|
||||||
let adapters = instance.enumerate_adapters(backends);
|
|
||||||
|
|
||||||
let mut chosen_adapter = None;
|
|
||||||
let mut chosen_adapter_score=0;
|
|
||||||
for adapter in adapters {
|
|
||||||
if !adapter.is_surface_supported(&surface) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let score=match adapter.get_info().device_type{
|
|
||||||
wgpu::DeviceType::IntegratedGpu=>3,
|
|
||||||
wgpu::DeviceType::DiscreteGpu=>4,
|
|
||||||
wgpu::DeviceType::VirtualGpu=>2,
|
|
||||||
wgpu::DeviceType::Other|wgpu::DeviceType::Cpu=>1,
|
|
||||||
};
|
|
||||||
|
|
||||||
let adapter_features = adapter.features();
|
|
||||||
if chosen_adapter_score<score&&adapter_features.contains(required_features) {
|
|
||||||
chosen_adapter_score=score;
|
|
||||||
chosen_adapter=Some(adapter);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(maybe_chosen_adapter) = chosen_adapter{
|
|
||||||
adapter=maybe_chosen_adapter;
|
|
||||||
}else{
|
|
||||||
panic!("No suitable GPU adapters found on the system!");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
|
||||||
{
|
|
||||||
let adapter_info = adapter.get_info();
|
|
||||||
println!("Using {} ({:?})", adapter_info.name, adapter_info.backend);
|
|
||||||
}
|
|
||||||
|
|
||||||
let required_downlevel_capabilities = E::required_downlevel_capabilities();
|
|
||||||
let downlevel_capabilities = adapter.get_downlevel_capabilities();
|
|
||||||
assert!(
|
|
||||||
downlevel_capabilities.shader_model >= required_downlevel_capabilities.shader_model,
|
|
||||||
"Adapter does not support the minimum shader model required to run this example: {:?}",
|
|
||||||
required_downlevel_capabilities.shader_model
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
downlevel_capabilities
|
|
||||||
.flags
|
|
||||||
.contains(required_downlevel_capabilities.flags),
|
|
||||||
"Adapter does not support the downlevel capabilities required to run this example: {:?}",
|
|
||||||
required_downlevel_capabilities.flags - downlevel_capabilities.flags
|
|
||||||
);
|
|
||||||
|
|
||||||
// Make sure we use the texture resolution limits from the adapter, so we can support images the size of the surface.
|
|
||||||
let needed_limits = E::required_limits().using_resolution(adapter.limits());
|
|
||||||
|
|
||||||
let trace_dir = std::env::var("WGPU_TRACE");
|
|
||||||
let (device, queue) = adapter
|
|
||||||
.request_device(
|
|
||||||
&wgpu::DeviceDescriptor {
|
|
||||||
label: None,
|
|
||||||
features: (optional_features & adapter.features()) | required_features,
|
|
||||||
limits: needed_limits,
|
|
||||||
},
|
|
||||||
trace_dir.ok().as_ref().map(std::path::Path::new),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.expect("Unable to find a suitable GPU adapter!");
|
|
||||||
|
|
||||||
Setup {
|
|
||||||
window,
|
|
||||||
event_loop,
|
|
||||||
instance,
|
|
||||||
size,
|
|
||||||
surface,
|
|
||||||
adapter,
|
|
||||||
device,
|
|
||||||
queue,
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
offscreen_canvas_setup,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn start<E: Example>(
|
|
||||||
#[cfg(not(target_arch = "wasm32"))] Setup {
|
|
||||||
window,
|
|
||||||
event_loop,
|
|
||||||
instance,
|
|
||||||
size,
|
|
||||||
surface,
|
|
||||||
adapter,
|
|
||||||
device,
|
|
||||||
queue,
|
|
||||||
}: Setup,
|
|
||||||
#[cfg(target_arch = "wasm32")] Setup {
|
|
||||||
window,
|
|
||||||
event_loop,
|
|
||||||
instance,
|
|
||||||
size,
|
|
||||||
surface,
|
|
||||||
adapter,
|
|
||||||
device,
|
|
||||||
queue,
|
|
||||||
offscreen_canvas_setup,
|
|
||||||
}: Setup,
|
|
||||||
) {
|
|
||||||
let spawner = Spawner::new();
|
|
||||||
let mut config = surface
|
|
||||||
.get_default_config(&adapter, size.width, size.height)
|
|
||||||
.expect("Surface isn't supported by the adapter.");
|
|
||||||
let surface_view_format = config.format.add_srgb_suffix();
|
|
||||||
config.view_formats.push(surface_view_format);
|
|
||||||
surface.configure(&device, &config);
|
|
||||||
|
|
||||||
log::info!("Initializing the example...");
|
|
||||||
let mut example = E::init(&config, &adapter, &device, &queue);
|
|
||||||
|
|
||||||
log::info!("Entering render loop...");
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
|
||||||
let _ = (&instance, &adapter); // force ownership by the closure
|
|
||||||
*control_flow = if cfg!(feature = "metal-auto-capture") {
|
|
||||||
ControlFlow::Exit
|
|
||||||
} else {
|
|
||||||
ControlFlow::Poll
|
|
||||||
};
|
|
||||||
match event {
|
|
||||||
event::Event::RedrawEventsCleared => {
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
|
||||||
spawner.run_until_stalled();
|
|
||||||
|
|
||||||
window.request_redraw();
|
|
||||||
}
|
|
||||||
event::Event::WindowEvent {
|
|
||||||
event:
|
|
||||||
WindowEvent::Resized(size)
|
|
||||||
| WindowEvent::ScaleFactorChanged {
|
|
||||||
new_inner_size: &mut size,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
// Once winit is fixed, the detection conditions here can be removed.
|
|
||||||
// https://github.com/rust-windowing/winit/issues/2876
|
|
||||||
let max_dimension = adapter.limits().max_texture_dimension_2d;
|
|
||||||
if size.width > max_dimension || size.height > max_dimension {
|
|
||||||
log::warn!(
|
|
||||||
"The resizing size {:?} exceeds the limit of {}.",
|
|
||||||
size,
|
|
||||||
max_dimension
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
log::info!("Resizing to {:?}", size);
|
|
||||||
config.width = size.width.max(1);
|
|
||||||
config.height = size.height.max(1);
|
|
||||||
example.resize(&config, &device, &queue);
|
|
||||||
surface.configure(&device, &config);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
event::Event::WindowEvent { event, .. } => match event {
|
|
||||||
WindowEvent::KeyboardInput {
|
|
||||||
input:
|
|
||||||
event::KeyboardInput {
|
|
||||||
virtual_keycode: Some(event::VirtualKeyCode::Escape),
|
|
||||||
state: event::ElementState::Pressed,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
}
|
|
||||||
| WindowEvent::CloseRequested => {
|
|
||||||
*control_flow = ControlFlow::Exit;
|
|
||||||
}
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
|
||||||
WindowEvent::KeyboardInput {
|
|
||||||
input:
|
|
||||||
event::KeyboardInput {
|
|
||||||
virtual_keycode: Some(event::VirtualKeyCode::Scroll),
|
|
||||||
state: event::ElementState::Pressed,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
println!("{:#?}", instance.generate_report());
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
example.update(&window,&device,&queue,event);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
event::Event::DeviceEvent {
|
|
||||||
event,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
example.device_event(&window,event);
|
|
||||||
},
|
|
||||||
event::Event::RedrawRequested(_) => {
|
|
||||||
|
|
||||||
let frame = match surface.get_current_texture() {
|
|
||||||
Ok(frame) => frame,
|
|
||||||
Err(_) => {
|
|
||||||
surface.configure(&device, &config);
|
|
||||||
surface
|
|
||||||
.get_current_texture()
|
|
||||||
.expect("Failed to acquire next surface texture!")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor {
|
|
||||||
format: Some(surface_view_format),
|
|
||||||
..wgpu::TextureViewDescriptor::default()
|
|
||||||
});
|
|
||||||
|
|
||||||
example.render(&view, &device, &queue, &spawner);
|
|
||||||
|
|
||||||
frame.present();
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
{
|
|
||||||
if let Some(offscreen_canvas_setup) = &offscreen_canvas_setup {
|
|
||||||
let image_bitmap = offscreen_canvas_setup
|
|
||||||
.offscreen_canvas
|
|
||||||
.transfer_to_image_bitmap()
|
|
||||||
.expect("couldn't transfer offscreen canvas to image bitmap.");
|
|
||||||
offscreen_canvas_setup
|
|
||||||
.bitmap_renderer
|
|
||||||
.transfer_from_image_bitmap(&image_bitmap);
|
|
||||||
|
|
||||||
log::info!("Transferring OffscreenCanvas to ImageBitmapRenderer");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
|
||||||
pub struct Spawner<'a> {
|
|
||||||
executor: async_executor::LocalExecutor<'a>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
|
||||||
impl<'a> Spawner<'a> {
|
|
||||||
fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
executor: async_executor::LocalExecutor::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn spawn_local(&self, future: impl Future<Output = ()> + 'a) {
|
|
||||||
self.executor.spawn(future).detach();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_until_stalled(&self) {
|
|
||||||
while self.executor.try_tick() {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
pub struct Spawner {}
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
impl Spawner {
|
|
||||||
fn new() -> Self {
|
|
||||||
Self {}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn spawn_local(&self, future: impl Future<Output = ()> + 'static) {
|
|
||||||
wasm_bindgen_futures::spawn_local(future);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
|
||||||
pub fn run<E: Example>(title: &str) {
|
|
||||||
let setup = pollster::block_on(setup::<E>(title));
|
|
||||||
start::<E>(setup);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
pub fn run<E: Example>(title: &str) {
|
|
||||||
use wasm_bindgen::prelude::*;
|
|
||||||
|
|
||||||
let title = title.to_owned();
|
|
||||||
wasm_bindgen_futures::spawn_local(async move {
|
|
||||||
let setup = setup::<E>(&title).await;
|
|
||||||
let start_closure = Closure::once_into_js(move || start::<E>(setup));
|
|
||||||
|
|
||||||
// make sure to handle JS exceptions thrown inside start.
|
|
||||||
// Otherwise wasm_bindgen_futures Queue would break and never handle any tasks again.
|
|
||||||
// This is required, because winit uses JS exception for control flow to escape from `run`.
|
|
||||||
if let Err(error) = call_catch(&start_closure) {
|
|
||||||
let is_control_flow_exception = error.dyn_ref::<js_sys::Error>().map_or(false, |e| {
|
|
||||||
e.message().includes("Using exceptions for control flow", 0)
|
|
||||||
});
|
|
||||||
|
|
||||||
if !is_control_flow_exception {
|
|
||||||
web_sys::console::error_1(&error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen]
|
|
||||||
extern "C" {
|
|
||||||
#[wasm_bindgen(catch, js_namespace = Function, js_name = "prototype.call.call")]
|
|
||||||
fn call_catch(this: &JsValue) -> Result<(), JsValue>;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
/// Parse the query string as returned by `web_sys::window()?.location().search()?` and get a
|
|
||||||
/// specific key out of it.
|
|
||||||
pub fn parse_url_query_string<'a>(query: &'a str, search_key: &str) -> Option<&'a str> {
|
|
||||||
let query_string = query.strip_prefix('?')?;
|
|
||||||
|
|
||||||
for pair in query_string.split('&') {
|
|
||||||
let mut pair = pair.split('=');
|
|
||||||
let key = pair.next()?;
|
|
||||||
let value = pair.next()?;
|
|
||||||
|
|
||||||
if key == search_key {
|
|
||||||
return Some(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
// This allows treating the framework as a standalone example,
|
|
||||||
// thus avoiding listing the example names in `Cargo.toml`.
|
|
||||||
#[allow(dead_code)]
|
|
||||||
fn main() {}
|
|
993
src/graphics.rs
Normal file
993
src/graphics.rs
Normal file
@ -0,0 +1,993 @@
|
|||||||
|
use std::borrow::Cow;
|
||||||
|
use wgpu::{util::DeviceExt,AstcBlock,AstcChannel};
|
||||||
|
use crate::model_graphics::{GraphicsVertex,ModelGraphicsColor4,ModelGraphicsInstance,ModelGraphicsSingleTexture,IndexedModelGraphicsSingleTexture,IndexedGroupFixedTexture};
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ModelUpdate{
|
||||||
|
transform:Option<glam::Mat4>,
|
||||||
|
color:Option<glam::Vec4>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Entity {
|
||||||
|
index_count: u32,
|
||||||
|
index_buf: wgpu::Buffer,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ModelGraphics {
|
||||||
|
instances: Vec<ModelGraphicsInstance>,
|
||||||
|
vertex_buf: wgpu::Buffer,
|
||||||
|
entities: Vec<Entity>,
|
||||||
|
bind_group: wgpu::BindGroup,
|
||||||
|
model_buf: wgpu::Buffer,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct GraphicsSamplers{
|
||||||
|
repeat: wgpu::Sampler,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct GraphicsBindGroupLayouts{
|
||||||
|
model: wgpu::BindGroupLayout,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct GraphicsBindGroups {
|
||||||
|
camera: wgpu::BindGroup,
|
||||||
|
skybox_texture: wgpu::BindGroup,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct GraphicsPipelines{
|
||||||
|
skybox: wgpu::RenderPipeline,
|
||||||
|
model: wgpu::RenderPipeline,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct GraphicsCamera{
|
||||||
|
screen_size: glam::UVec2,
|
||||||
|
fov: glam::Vec2,//slope
|
||||||
|
//camera angles and such are extrapolated and passed in every time
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
|
||||||
|
//glam_assert!(z_near > 0.0 && z_far > 0.0);
|
||||||
|
let r = z_far / (z_near - z_far);
|
||||||
|
glam::Mat4::from_cols(
|
||||||
|
glam::Vec4::new(1.0/fov_x_slope, 0.0, 0.0, 0.0),
|
||||||
|
glam::Vec4::new(0.0, 1.0/fov_y_slope, 0.0, 0.0),
|
||||||
|
glam::Vec4::new(0.0, 0.0, r, -1.0),
|
||||||
|
glam::Vec4::new(0.0, 0.0, r * z_near, 0.0),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
impl GraphicsCamera{
|
||||||
|
pub fn new(screen_size:glam::UVec2,fov:glam::Vec2)->Self{
|
||||||
|
Self{
|
||||||
|
screen_size,
|
||||||
|
fov,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn proj(&self)->glam::Mat4{
|
||||||
|
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
|
||||||
|
}
|
||||||
|
pub fn world(&self,pos:glam::Vec3,angles:glam::Vec2)->glam::Mat4{
|
||||||
|
//f32 good enough for view matrix
|
||||||
|
glam::Mat4::from_translation(pos) * glam::Mat4::from_euler(glam::EulerRot::YXZ, angles.x, angles.y, 0f32)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_uniform_data(&self,(pos,angles): (glam::Vec3,glam::Vec2)) -> [f32; 16 * 4] {
|
||||||
|
let proj=self.proj();
|
||||||
|
let proj_inv = proj.inverse();
|
||||||
|
let view_inv=self.world(pos,angles);
|
||||||
|
let view=view_inv.inverse();
|
||||||
|
|
||||||
|
let mut raw = [0f32; 16 * 4];
|
||||||
|
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
|
||||||
|
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
|
||||||
|
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view)[..]);
|
||||||
|
raw[48..64].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
|
||||||
|
raw
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl std::default::Default for GraphicsCamera{
|
||||||
|
fn default()->Self{
|
||||||
|
Self{
|
||||||
|
screen_size:glam::UVec2::ONE,
|
||||||
|
fov:glam::Vec2::ONE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct GraphicsState{
|
||||||
|
pipelines: GraphicsPipelines,
|
||||||
|
bind_groups: GraphicsBindGroups,
|
||||||
|
bind_group_layouts: GraphicsBindGroupLayouts,
|
||||||
|
samplers: GraphicsSamplers,
|
||||||
|
camera:GraphicsCamera,
|
||||||
|
camera_buf: wgpu::Buffer,
|
||||||
|
temp_squid_texture_view: wgpu::TextureView,
|
||||||
|
models: Vec<ModelGraphics>,
|
||||||
|
depth_view: wgpu::TextureView,
|
||||||
|
staging_belt: wgpu::util::StagingBelt,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphicsState{
|
||||||
|
const DEPTH_FORMAT: wgpu::TextureFormat=wgpu::TextureFormat::Depth24Plus;
|
||||||
|
fn create_depth_texture(
|
||||||
|
config: &wgpu::SurfaceConfiguration,
|
||||||
|
device: &wgpu::Device,
|
||||||
|
) -> wgpu::TextureView {
|
||||||
|
let depth_texture=device.create_texture(&wgpu::TextureDescriptor {
|
||||||
|
size: wgpu::Extent3d {
|
||||||
|
width: config.width,
|
||||||
|
height: config.height,
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
},
|
||||||
|
mip_level_count: 1,
|
||||||
|
sample_count: 1,
|
||||||
|
dimension: wgpu::TextureDimension::D2,
|
||||||
|
format: Self::DEPTH_FORMAT,
|
||||||
|
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||||
|
label: None,
|
||||||
|
view_formats: &[],
|
||||||
|
});
|
||||||
|
|
||||||
|
depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
|
||||||
|
}
|
||||||
|
pub fn clear(&mut self){
|
||||||
|
self.models.clear();
|
||||||
|
}
|
||||||
|
pub fn load_user_settings(&mut self,user_settings:&crate::settings::UserSettings){
|
||||||
|
self.camera.fov=user_settings.calculate_fov(1.0,&self.camera.screen_size).as_vec2();
|
||||||
|
}
|
||||||
|
pub fn generate_models(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:crate::model::IndexedModelInstances){
|
||||||
|
//generate texture view per texture
|
||||||
|
|
||||||
|
//idk how to do this gooder lol
|
||||||
|
let mut double_map=std::collections::HashMap::<u32,u32>::new();
|
||||||
|
let mut texture_loading_threads=Vec::new();
|
||||||
|
let num_textures=indexed_models.textures.len();
|
||||||
|
for (i,texture_id) in indexed_models.textures.into_iter().enumerate(){
|
||||||
|
if let Ok(mut file) = std::fs::File::open(std::path::Path::new(&format!("textures/{}.dds",texture_id))){
|
||||||
|
double_map.insert(i as u32, texture_loading_threads.len() as u32);
|
||||||
|
texture_loading_threads.push((texture_id,std::thread::spawn(move ||{
|
||||||
|
ddsfile::Dds::read(&mut file).unwrap()
|
||||||
|
})));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let texture_views:Vec<wgpu::TextureView>=texture_loading_threads.into_iter().map(|(texture_id,thread)|{
|
||||||
|
let image=thread.join().unwrap();
|
||||||
|
|
||||||
|
let (mut width,mut height)=(image.get_width(),image.get_height());
|
||||||
|
|
||||||
|
let format=match image.header10.unwrap().dxgi_format{
|
||||||
|
ddsfile::DxgiFormat::R8G8B8A8_UNorm_sRGB => wgpu::TextureFormat::Rgba8UnormSrgb,
|
||||||
|
ddsfile::DxgiFormat::BC7_UNorm_sRGB => {
|
||||||
|
//floor(w,4), should be ceil(w,4)
|
||||||
|
width=width/4*4;
|
||||||
|
height=height/4*4;
|
||||||
|
wgpu::TextureFormat::Bc7RgbaUnormSrgb
|
||||||
|
},
|
||||||
|
other=>panic!("unsupported format {:?}",other),
|
||||||
|
};
|
||||||
|
|
||||||
|
let size = wgpu::Extent3d {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
let layer_size = wgpu::Extent3d {
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
..size
|
||||||
|
};
|
||||||
|
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
|
||||||
|
|
||||||
|
let texture = device.create_texture_with_data(
|
||||||
|
queue,
|
||||||
|
&wgpu::TextureDescriptor {
|
||||||
|
size,
|
||||||
|
mip_level_count: max_mips,
|
||||||
|
sample_count: 1,
|
||||||
|
dimension: wgpu::TextureDimension::D2,
|
||||||
|
format,
|
||||||
|
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||||
|
label: Some(format!("Texture{}",texture_id).as_str()),
|
||||||
|
view_formats: &[],
|
||||||
|
},
|
||||||
|
&image.data,
|
||||||
|
);
|
||||||
|
texture.create_view(&wgpu::TextureViewDescriptor {
|
||||||
|
label: Some(format!("Texture{} View",texture_id).as_str()),
|
||||||
|
dimension: Some(wgpu::TextureViewDimension::D2),
|
||||||
|
..wgpu::TextureViewDescriptor::default()
|
||||||
|
})
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
//split groups with different textures into separate models
|
||||||
|
//the models received here are supposed to be tightly packed, i.e. no code needs to check if two models are using the same groups.
|
||||||
|
let indexed_models_len=indexed_models.models.len();
|
||||||
|
let mut unique_texture_models=Vec::with_capacity(indexed_models_len);
|
||||||
|
for model in indexed_models.models.into_iter(){
|
||||||
|
//convert ModelInstance into ModelGraphicsInstance
|
||||||
|
let instances:Vec<ModelGraphicsInstance>=model.instances.into_iter().filter_map(|instance|{
|
||||||
|
if instance.color.w==0.0{
|
||||||
|
None
|
||||||
|
}else{
|
||||||
|
Some(ModelGraphicsInstance{
|
||||||
|
transform: instance.transform.into(),
|
||||||
|
normal_transform: Into::<glam::Mat3>::into(instance.transform.matrix3).inverse().transpose(),
|
||||||
|
color:ModelGraphicsColor4::from(instance.color),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}).collect();
|
||||||
|
//skip pushing a model if all instances are invisible
|
||||||
|
if instances.len()==0{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
//check each group, if it's using a new texture then make a new clone of the model
|
||||||
|
let id=unique_texture_models.len();
|
||||||
|
let mut unique_textures=Vec::new();
|
||||||
|
for group in model.groups.into_iter(){
|
||||||
|
//ignore zero copy optimization for now
|
||||||
|
let texture_index=if let Some(texture_index)=unique_textures.iter().position(|&texture|texture==group.texture){
|
||||||
|
texture_index
|
||||||
|
}else{
|
||||||
|
//create new texture_index
|
||||||
|
let texture_index=unique_textures.len();
|
||||||
|
unique_textures.push(group.texture);
|
||||||
|
unique_texture_models.push(IndexedModelGraphicsSingleTexture{
|
||||||
|
unique_pos:model.unique_pos.iter().map(|&v|*Into::<glam::Vec3>::into(v).as_ref()).collect(),
|
||||||
|
unique_tex:model.unique_tex.iter().map(|v|*v.as_ref()).collect(),
|
||||||
|
unique_normal:model.unique_normal.iter().map(|&v|*Into::<glam::Vec3>::into(v).as_ref()).collect(),
|
||||||
|
unique_color:model.unique_color.iter().map(|v|*v.as_ref()).collect(),
|
||||||
|
unique_vertices:model.unique_vertices.clone(),
|
||||||
|
texture:group.texture,
|
||||||
|
groups:Vec::new(),
|
||||||
|
instances:instances.clone(),
|
||||||
|
});
|
||||||
|
texture_index
|
||||||
|
};
|
||||||
|
unique_texture_models[id+texture_index].groups.push(IndexedGroupFixedTexture{
|
||||||
|
polys:group.polys,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//check every model to see if it's using the same (texture,color) but has few instances, if it is combine it into one model
|
||||||
|
//1. collect unique instances of texture and color, note model id
|
||||||
|
//2. for each model id, check if removing it from the pool decreases both the model count and instance count by more than one
|
||||||
|
//3. transpose all models that stay in the set
|
||||||
|
|
||||||
|
//best plan: benchmark set_bind_group, set_vertex_buffer, set_index_buffer and draw_indexed
|
||||||
|
//check if the estimated render performance is better by transposing multiple model instances into one model instance
|
||||||
|
|
||||||
|
//for now: just deduplicate single models...
|
||||||
|
let mut deduplicated_models=Vec::with_capacity(indexed_models_len);//use indexed_models_len because the list will likely get smaller instead of bigger
|
||||||
|
let mut unique_texture_color=std::collections::HashMap::new();//texture->color->vec![(model_id,instance_id)]
|
||||||
|
for (model_id,model) in unique_texture_models.iter().enumerate(){
|
||||||
|
//for now: filter out models with more than one instance
|
||||||
|
if 1<model.instances.len(){
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
//populate hashmap
|
||||||
|
let unique_color=if let Some(unique_color)=unique_texture_color.get_mut(&model.texture){
|
||||||
|
unique_color
|
||||||
|
}else{
|
||||||
|
//make new hashmap
|
||||||
|
let unique_color=std::collections::HashMap::new();
|
||||||
|
unique_texture_color.insert(model.texture,unique_color);
|
||||||
|
unique_texture_color.get_mut(&model.texture).unwrap()
|
||||||
|
};
|
||||||
|
//separate instances by color
|
||||||
|
for (instance_id,instance) in model.instances.iter().enumerate(){
|
||||||
|
let model_instance_list=if let Some(model_instance_list)=unique_color.get_mut(&instance.color){
|
||||||
|
model_instance_list
|
||||||
|
}else{
|
||||||
|
//make new hashmap
|
||||||
|
let model_instance_list=Vec::new();
|
||||||
|
unique_color.insert(instance.color.clone(),model_instance_list);
|
||||||
|
unique_color.get_mut(&instance.color).unwrap()
|
||||||
|
};
|
||||||
|
//add model instance to list
|
||||||
|
model_instance_list.push((model_id,instance_id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//populate a hashset of models selected for transposition
|
||||||
|
//construct transposed models
|
||||||
|
let mut selected_model_instances=std::collections::HashSet::new();
|
||||||
|
for (texture,unique_color) in unique_texture_color.into_iter(){
|
||||||
|
for (color,model_instance_list) in unique_color.into_iter(){
|
||||||
|
//world transforming one model does not meet the definition of deduplicaiton
|
||||||
|
if 1<model_instance_list.len(){
|
||||||
|
//create model
|
||||||
|
let mut unique_pos=Vec::new();
|
||||||
|
let mut pos_id_from=std::collections::HashMap::new();
|
||||||
|
let mut unique_tex=Vec::new();
|
||||||
|
let mut tex_id_from=std::collections::HashMap::new();
|
||||||
|
let mut unique_normal=Vec::new();
|
||||||
|
let mut normal_id_from=std::collections::HashMap::new();
|
||||||
|
let mut unique_color=Vec::new();
|
||||||
|
let mut color_id_from=std::collections::HashMap::new();
|
||||||
|
let mut unique_vertices=Vec::new();
|
||||||
|
let mut vertex_id_from=std::collections::HashMap::new();
|
||||||
|
|
||||||
|
let mut polys=Vec::new();
|
||||||
|
//transform instance vertices
|
||||||
|
for (model_id,instance_id) in model_instance_list.into_iter(){
|
||||||
|
//populate hashset to prevent these models from being copied
|
||||||
|
selected_model_instances.insert(model_id);
|
||||||
|
//there is only one instance per model
|
||||||
|
let model=&unique_texture_models[model_id];
|
||||||
|
let instance=&model.instances[instance_id];
|
||||||
|
//just hash word slices LOL
|
||||||
|
let map_pos_id:Vec<u32>=model.unique_pos.iter().map(|untransformed_pos|{
|
||||||
|
let pos=instance.transform.transform_point3(glam::Vec3::from_array(untransformed_pos.clone())).to_array();
|
||||||
|
let h=pos.map(|v|bytemuck::cast::<f32,u32>(v));
|
||||||
|
(if let Some(&pos_id)=pos_id_from.get(&h){
|
||||||
|
pos_id
|
||||||
|
}else{
|
||||||
|
let pos_id=unique_pos.len();
|
||||||
|
unique_pos.push(pos.clone());
|
||||||
|
pos_id_from.insert(h,pos_id);
|
||||||
|
pos_id
|
||||||
|
}) as u32
|
||||||
|
}).collect();
|
||||||
|
let map_tex_id:Vec<u32>=model.unique_tex.iter().map(|tex|{
|
||||||
|
let h=tex.map(|v|bytemuck::cast::<f32,u32>(v));
|
||||||
|
(if let Some(&tex_id)=tex_id_from.get(&h){
|
||||||
|
tex_id
|
||||||
|
}else{
|
||||||
|
let tex_id=unique_tex.len();
|
||||||
|
unique_tex.push(tex.clone());
|
||||||
|
tex_id_from.insert(h,tex_id);
|
||||||
|
tex_id
|
||||||
|
}) as u32
|
||||||
|
}).collect();
|
||||||
|
let map_normal_id:Vec<u32>=model.unique_normal.iter().map(|untransformed_normal|{
|
||||||
|
let normal=(instance.normal_transform*glam::Vec3::from_array(untransformed_normal.clone())).to_array();
|
||||||
|
let h=normal.map(|v|bytemuck::cast::<f32,u32>(v));
|
||||||
|
(if let Some(&normal_id)=normal_id_from.get(&h){
|
||||||
|
normal_id
|
||||||
|
}else{
|
||||||
|
let normal_id=unique_normal.len();
|
||||||
|
unique_normal.push(normal.clone());
|
||||||
|
normal_id_from.insert(h,normal_id);
|
||||||
|
normal_id
|
||||||
|
}) as u32
|
||||||
|
}).collect();
|
||||||
|
let map_color_id:Vec<u32>=model.unique_color.iter().map(|color|{
|
||||||
|
let h=color.map(|v|bytemuck::cast::<f32,u32>(v));
|
||||||
|
(if let Some(&color_id)=color_id_from.get(&h){
|
||||||
|
color_id
|
||||||
|
}else{
|
||||||
|
let color_id=unique_color.len();
|
||||||
|
unique_color.push(color.clone());
|
||||||
|
color_id_from.insert(h,color_id);
|
||||||
|
color_id
|
||||||
|
}) as u32
|
||||||
|
}).collect();
|
||||||
|
//map the indexed vertices onto new indices
|
||||||
|
//creating the vertex map is slightly different because the vertices are directly hashable
|
||||||
|
let map_vertex_id:Vec<u32>=model.unique_vertices.iter().map(|unmapped_vertex|{
|
||||||
|
let vertex=crate::model::IndexedVertex{
|
||||||
|
pos:map_pos_id[unmapped_vertex.pos as usize] as u32,
|
||||||
|
tex:map_tex_id[unmapped_vertex.tex as usize] as u32,
|
||||||
|
normal:map_normal_id[unmapped_vertex.normal as usize] as u32,
|
||||||
|
color:map_color_id[unmapped_vertex.color as usize] as u32,
|
||||||
|
};
|
||||||
|
(if let Some(&vertex_id)=vertex_id_from.get(&vertex){
|
||||||
|
vertex_id
|
||||||
|
}else{
|
||||||
|
let vertex_id=unique_vertices.len();
|
||||||
|
unique_vertices.push(vertex.clone());
|
||||||
|
vertex_id_from.insert(vertex,vertex_id);
|
||||||
|
vertex_id
|
||||||
|
}) as u32
|
||||||
|
}).collect();
|
||||||
|
for group in &model.groups{
|
||||||
|
for poly in &group.polys{
|
||||||
|
polys.push(crate::model::IndexedPolygon{vertices:poly.vertices.iter().map(|&vertex_id|map_vertex_id[vertex_id as usize]).collect()});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//push model into dedup
|
||||||
|
deduplicated_models.push(IndexedModelGraphicsSingleTexture{
|
||||||
|
unique_pos,
|
||||||
|
unique_tex,
|
||||||
|
unique_normal,
|
||||||
|
unique_color,
|
||||||
|
unique_vertices,
|
||||||
|
texture,
|
||||||
|
groups:vec![IndexedGroupFixedTexture{
|
||||||
|
polys
|
||||||
|
}],
|
||||||
|
instances:vec![ModelGraphicsInstance{
|
||||||
|
transform:glam::Mat4::IDENTITY,
|
||||||
|
normal_transform:glam::Mat3::IDENTITY,
|
||||||
|
color
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//fill untouched models
|
||||||
|
for (model_id,model) in unique_texture_models.into_iter().enumerate(){
|
||||||
|
if !selected_model_instances.contains(&model_id){
|
||||||
|
deduplicated_models.push(model);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//de-index models
|
||||||
|
let deduplicated_models_len=deduplicated_models.len();
|
||||||
|
let models:Vec<ModelGraphicsSingleTexture>=deduplicated_models.into_iter().map(|model|{
|
||||||
|
let mut vertices = Vec::new();
|
||||||
|
let mut index_from_vertex = std::collections::HashMap::new();//::<IndexedVertex,usize>
|
||||||
|
let mut entities = Vec::new();
|
||||||
|
//this mut be combined in a more complex way if the models use different render patterns per group
|
||||||
|
let mut indices = Vec::new();
|
||||||
|
for group in model.groups {
|
||||||
|
for poly in group.polys {
|
||||||
|
for end_index in 2..poly.vertices.len() {
|
||||||
|
for &index in &[0, end_index - 1, end_index] {
|
||||||
|
let vertex_index = poly.vertices[index];
|
||||||
|
if let Some(&i)=index_from_vertex.get(&vertex_index){
|
||||||
|
indices.push(i);
|
||||||
|
}else{
|
||||||
|
let i=vertices.len() as u16;
|
||||||
|
let vertex=&model.unique_vertices[vertex_index as usize];
|
||||||
|
vertices.push(GraphicsVertex{
|
||||||
|
pos: model.unique_pos[vertex.pos as usize],
|
||||||
|
tex: model.unique_tex[vertex.tex as usize],
|
||||||
|
normal: model.unique_normal[vertex.normal as usize],
|
||||||
|
color:model.unique_color[vertex.color as usize],
|
||||||
|
});
|
||||||
|
index_from_vertex.insert(vertex_index,i);
|
||||||
|
indices.push(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entities.push(indices);
|
||||||
|
ModelGraphicsSingleTexture{
|
||||||
|
instances:model.instances,
|
||||||
|
vertices,
|
||||||
|
entities,
|
||||||
|
texture:model.texture,
|
||||||
|
}
|
||||||
|
}).collect();
|
||||||
|
//.into_iter() the modeldata vec so entities can be /moved/ to models.entities
|
||||||
|
let mut model_count=0;
|
||||||
|
let mut instance_count=0;
|
||||||
|
let uniform_buffer_binding_size=crate::setup::required_limits().max_uniform_buffer_binding_size as usize;
|
||||||
|
let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES;
|
||||||
|
self.models.reserve(models.len());
|
||||||
|
for model in models.into_iter() {
|
||||||
|
instance_count+=model.instances.len();
|
||||||
|
for instances_chunk in model.instances.rchunks(chunk_size){
|
||||||
|
model_count+=1;
|
||||||
|
let model_uniforms = get_instances_buffer_data(instances_chunk);
|
||||||
|
let model_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some(format!("Model{} Buf",model_count).as_str()),
|
||||||
|
contents: bytemuck::cast_slice(&model_uniforms),
|
||||||
|
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||||
|
});
|
||||||
|
let texture_view=match model.texture{
|
||||||
|
Some(texture_id)=>{
|
||||||
|
match double_map.get(&texture_id){
|
||||||
|
Some(&mapped_texture_id)=>&texture_views[mapped_texture_id as usize],
|
||||||
|
None=>&self.temp_squid_texture_view,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None=>&self.temp_squid_texture_view,
|
||||||
|
};
|
||||||
|
let model_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
|
layout: &self.bind_group_layouts.model,
|
||||||
|
entries: &[
|
||||||
|
wgpu::BindGroupEntry {
|
||||||
|
binding: 0,
|
||||||
|
resource: model_buf.as_entire_binding(),
|
||||||
|
},
|
||||||
|
wgpu::BindGroupEntry {
|
||||||
|
binding: 1,
|
||||||
|
resource: wgpu::BindingResource::TextureView(texture_view),
|
||||||
|
},
|
||||||
|
wgpu::BindGroupEntry {
|
||||||
|
binding: 2,
|
||||||
|
resource: wgpu::BindingResource::Sampler(&self.samplers.repeat),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
label: Some(format!("Model{} Bind Group",model_count).as_str()),
|
||||||
|
});
|
||||||
|
let vertex_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some("Vertex"),
|
||||||
|
contents: bytemuck::cast_slice(&model.vertices),
|
||||||
|
usage: wgpu::BufferUsages::VERTEX,
|
||||||
|
});
|
||||||
|
//all of these are being moved here
|
||||||
|
self.models.push(ModelGraphics{
|
||||||
|
instances:instances_chunk.to_vec(),
|
||||||
|
vertex_buf,
|
||||||
|
entities: model.entities.iter().map(|indices|{
|
||||||
|
let index_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some("Index"),
|
||||||
|
contents: bytemuck::cast_slice(&indices),
|
||||||
|
usage: wgpu::BufferUsages::INDEX,
|
||||||
|
});
|
||||||
|
Entity {
|
||||||
|
index_buf,
|
||||||
|
index_count: indices.len() as u32,
|
||||||
|
}
|
||||||
|
}).collect(),
|
||||||
|
bind_group: model_bind_group,
|
||||||
|
model_buf,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println!("Texture References={}",num_textures);
|
||||||
|
println!("Textures Loaded={}",texture_views.len());
|
||||||
|
println!("Indexed Models={}",indexed_models_len);
|
||||||
|
println!("Deduplicated Models={}",deduplicated_models_len);
|
||||||
|
println!("Graphics Objects: {}",self.models.len());
|
||||||
|
println!("Graphics Instances: {}",instance_count);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new(
|
||||||
|
device:&wgpu::Device,
|
||||||
|
queue:&wgpu::Queue,
|
||||||
|
config:&wgpu::SurfaceConfiguration,
|
||||||
|
)->Self{
|
||||||
|
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
|
label: None,
|
||||||
|
entries: &[
|
||||||
|
wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: 0,
|
||||||
|
visibility: wgpu::ShaderStages::VERTEX,
|
||||||
|
ty: wgpu::BindingType::Buffer {
|
||||||
|
ty: wgpu::BufferBindingType::Uniform,
|
||||||
|
has_dynamic_offset: false,
|
||||||
|
min_binding_size: None,
|
||||||
|
},
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
let skybox_texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
|
label: Some("Skybox Texture Bind Group Layout"),
|
||||||
|
entries: &[
|
||||||
|
wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: 0,
|
||||||
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||||
|
ty: wgpu::BindingType::Texture {
|
||||||
|
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||||
|
multisampled: false,
|
||||||
|
view_dimension: wgpu::TextureViewDimension::Cube,
|
||||||
|
},
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: 1,
|
||||||
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||||
|
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
let model_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
|
label: Some("Model Bind Group Layout"),
|
||||||
|
entries: &[
|
||||||
|
wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: 0,
|
||||||
|
visibility: wgpu::ShaderStages::VERTEX,
|
||||||
|
ty: wgpu::BindingType::Buffer {
|
||||||
|
ty: wgpu::BufferBindingType::Uniform,
|
||||||
|
has_dynamic_offset: false,
|
||||||
|
min_binding_size: None,
|
||||||
|
},
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: 1,
|
||||||
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||||
|
ty: wgpu::BindingType::Texture {
|
||||||
|
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||||
|
multisampled: false,
|
||||||
|
view_dimension: wgpu::TextureViewDimension::D2,
|
||||||
|
},
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: 2,
|
||||||
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||||
|
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
let clamp_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||||
|
label: Some("Clamp Sampler"),
|
||||||
|
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||||
|
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
||||||
|
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
||||||
|
mag_filter: wgpu::FilterMode::Linear,
|
||||||
|
min_filter: wgpu::FilterMode::Linear,
|
||||||
|
mipmap_filter: wgpu::FilterMode::Linear,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let repeat_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||||
|
label: Some("Repeat Sampler"),
|
||||||
|
address_mode_u: wgpu::AddressMode::Repeat,
|
||||||
|
address_mode_v: wgpu::AddressMode::Repeat,
|
||||||
|
address_mode_w: wgpu::AddressMode::Repeat,
|
||||||
|
mag_filter: wgpu::FilterMode::Linear,
|
||||||
|
min_filter: wgpu::FilterMode::Linear,
|
||||||
|
mipmap_filter: wgpu::FilterMode::Linear,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create the render pipeline
|
||||||
|
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||||
|
label: None,
|
||||||
|
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
|
||||||
|
});
|
||||||
|
|
||||||
|
//load textures
|
||||||
|
let device_features = device.features();
|
||||||
|
|
||||||
|
let skybox_texture_view={
|
||||||
|
let skybox_format = if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC) {
|
||||||
|
println!("Using ASTC");
|
||||||
|
wgpu::TextureFormat::Astc {
|
||||||
|
block: AstcBlock::B4x4,
|
||||||
|
channel: AstcChannel::UnormSrgb,
|
||||||
|
}
|
||||||
|
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ETC2) {
|
||||||
|
println!("Using ETC2");
|
||||||
|
wgpu::TextureFormat::Etc2Rgb8UnormSrgb
|
||||||
|
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_BC) {
|
||||||
|
println!("Using BC");
|
||||||
|
wgpu::TextureFormat::Bc1RgbaUnormSrgb
|
||||||
|
} else {
|
||||||
|
println!("Using plain");
|
||||||
|
wgpu::TextureFormat::Bgra8UnormSrgb
|
||||||
|
};
|
||||||
|
|
||||||
|
let bytes = match skybox_format {
|
||||||
|
wgpu::TextureFormat::Astc {
|
||||||
|
block: AstcBlock::B4x4,
|
||||||
|
channel: AstcChannel::UnormSrgb,
|
||||||
|
} => &include_bytes!("../images/astc.dds")[..],
|
||||||
|
wgpu::TextureFormat::Etc2Rgb8UnormSrgb => &include_bytes!("../images/etc2.dds")[..],
|
||||||
|
wgpu::TextureFormat::Bc1RgbaUnormSrgb => &include_bytes!("../images/bc1.dds")[..],
|
||||||
|
wgpu::TextureFormat::Bgra8UnormSrgb => &include_bytes!("../images/bgra.dds")[..],
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let skybox_image = ddsfile::Dds::read(&mut std::io::Cursor::new(bytes)).unwrap();
|
||||||
|
|
||||||
|
let size = wgpu::Extent3d {
|
||||||
|
width: skybox_image.get_width(),
|
||||||
|
height: skybox_image.get_height(),
|
||||||
|
depth_or_array_layers: 6,
|
||||||
|
};
|
||||||
|
|
||||||
|
let layer_size = wgpu::Extent3d {
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
..size
|
||||||
|
};
|
||||||
|
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
|
||||||
|
|
||||||
|
let skybox_texture = device.create_texture_with_data(
|
||||||
|
queue,
|
||||||
|
&wgpu::TextureDescriptor {
|
||||||
|
size,
|
||||||
|
mip_level_count: max_mips,
|
||||||
|
sample_count: 1,
|
||||||
|
dimension: wgpu::TextureDimension::D2,
|
||||||
|
format: skybox_format,
|
||||||
|
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||||
|
label: Some("Skybox Texture"),
|
||||||
|
view_formats: &[],
|
||||||
|
},
|
||||||
|
&skybox_image.data,
|
||||||
|
);
|
||||||
|
|
||||||
|
skybox_texture.create_view(&wgpu::TextureViewDescriptor {
|
||||||
|
label: Some("Skybox Texture View"),
|
||||||
|
dimension: Some(wgpu::TextureViewDimension::Cube),
|
||||||
|
..wgpu::TextureViewDescriptor::default()
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
//squid
|
||||||
|
let squid_texture_view={
|
||||||
|
let bytes = include_bytes!("../images/squid.dds");
|
||||||
|
|
||||||
|
let image = ddsfile::Dds::read(&mut std::io::Cursor::new(bytes)).unwrap();
|
||||||
|
|
||||||
|
let size = wgpu::Extent3d {
|
||||||
|
width: image.get_width(),
|
||||||
|
height: image.get_height(),
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
let layer_size = wgpu::Extent3d {
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
..size
|
||||||
|
};
|
||||||
|
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
|
||||||
|
|
||||||
|
let texture = device.create_texture_with_data(
|
||||||
|
queue,
|
||||||
|
&wgpu::TextureDescriptor {
|
||||||
|
size,
|
||||||
|
mip_level_count: max_mips,
|
||||||
|
sample_count: 1,
|
||||||
|
dimension: wgpu::TextureDimension::D2,
|
||||||
|
format: wgpu::TextureFormat::Bc7RgbaUnorm,
|
||||||
|
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||||
|
label: Some("Squid Texture"),
|
||||||
|
view_formats: &[],
|
||||||
|
},
|
||||||
|
&image.data,
|
||||||
|
);
|
||||||
|
|
||||||
|
texture.create_view(&wgpu::TextureViewDescriptor {
|
||||||
|
label: Some("Squid Texture View"),
|
||||||
|
dimension: Some(wgpu::TextureViewDimension::D2),
|
||||||
|
..wgpu::TextureViewDescriptor::default()
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
let model_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||||
|
label: None,
|
||||||
|
bind_group_layouts: &[
|
||||||
|
&camera_bind_group_layout,
|
||||||
|
&skybox_texture_bind_group_layout,
|
||||||
|
&model_bind_group_layout,
|
||||||
|
],
|
||||||
|
push_constant_ranges: &[],
|
||||||
|
});
|
||||||
|
let sky_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||||
|
label: None,
|
||||||
|
bind_group_layouts: &[
|
||||||
|
&camera_bind_group_layout,
|
||||||
|
&skybox_texture_bind_group_layout,
|
||||||
|
],
|
||||||
|
push_constant_ranges: &[],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create the render pipelines
|
||||||
|
let sky_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||||
|
label: Some("Sky Pipeline"),
|
||||||
|
layout: Some(&sky_pipeline_layout),
|
||||||
|
vertex: wgpu::VertexState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: "vs_sky",
|
||||||
|
buffers: &[],
|
||||||
|
},
|
||||||
|
fragment: Some(wgpu::FragmentState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: "fs_sky",
|
||||||
|
targets: &[Some(config.view_formats[0].into())],
|
||||||
|
}),
|
||||||
|
primitive: wgpu::PrimitiveState {
|
||||||
|
front_face: wgpu::FrontFace::Cw,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
depth_stencil: Some(wgpu::DepthStencilState {
|
||||||
|
format: Self::DEPTH_FORMAT,
|
||||||
|
depth_write_enabled: false,
|
||||||
|
depth_compare: wgpu::CompareFunction::LessEqual,
|
||||||
|
stencil: wgpu::StencilState::default(),
|
||||||
|
bias: wgpu::DepthBiasState::default(),
|
||||||
|
}),
|
||||||
|
multisample: wgpu::MultisampleState::default(),
|
||||||
|
multiview: None,
|
||||||
|
});
|
||||||
|
let model_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||||
|
label: Some("Model Pipeline"),
|
||||||
|
layout: Some(&model_pipeline_layout),
|
||||||
|
vertex: wgpu::VertexState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: "vs_entity_texture",
|
||||||
|
buffers: &[wgpu::VertexBufferLayout {
|
||||||
|
array_stride: std::mem::size_of::<GraphicsVertex>() as wgpu::BufferAddress,
|
||||||
|
step_mode: wgpu::VertexStepMode::Vertex,
|
||||||
|
attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2, 2 => Float32x3, 3 => Float32x4],
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
fragment: Some(wgpu::FragmentState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: "fs_entity_texture",
|
||||||
|
targets: &[Some(config.view_formats[0].into())],
|
||||||
|
}),
|
||||||
|
primitive: wgpu::PrimitiveState {
|
||||||
|
front_face: wgpu::FrontFace::Cw,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
depth_stencil: Some(wgpu::DepthStencilState {
|
||||||
|
format: Self::DEPTH_FORMAT,
|
||||||
|
depth_write_enabled: true,
|
||||||
|
depth_compare: wgpu::CompareFunction::LessEqual,
|
||||||
|
stencil: wgpu::StencilState::default(),
|
||||||
|
bias: wgpu::DepthBiasState::default(),
|
||||||
|
}),
|
||||||
|
multisample: wgpu::MultisampleState::default(),
|
||||||
|
multiview: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
let camera=GraphicsCamera::default();
|
||||||
|
let camera_uniforms = camera.to_uniform_data(crate::physics::PhysicsOutputState::default().extrapolate(glam::IVec2::ZERO,crate::integer::Time::ZERO));
|
||||||
|
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some("Camera"),
|
||||||
|
contents: bytemuck::cast_slice(&camera_uniforms),
|
||||||
|
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||||
|
});
|
||||||
|
let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
|
layout: &camera_bind_group_layout,
|
||||||
|
entries: &[
|
||||||
|
wgpu::BindGroupEntry {
|
||||||
|
binding: 0,
|
||||||
|
resource: camera_buf.as_entire_binding(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
label: Some("Camera"),
|
||||||
|
});
|
||||||
|
|
||||||
|
let skybox_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
|
layout: &skybox_texture_bind_group_layout,
|
||||||
|
entries: &[
|
||||||
|
wgpu::BindGroupEntry {
|
||||||
|
binding: 0,
|
||||||
|
resource: wgpu::BindingResource::TextureView(&skybox_texture_view),
|
||||||
|
},
|
||||||
|
wgpu::BindGroupEntry {
|
||||||
|
binding: 1,
|
||||||
|
resource: wgpu::BindingResource::Sampler(&clamp_sampler),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
label: Some("Sky Texture"),
|
||||||
|
});
|
||||||
|
|
||||||
|
let depth_view = Self::create_depth_texture(config, device);
|
||||||
|
|
||||||
|
Self{
|
||||||
|
pipelines:GraphicsPipelines{
|
||||||
|
skybox:sky_pipeline,
|
||||||
|
model:model_pipeline
|
||||||
|
},
|
||||||
|
bind_groups:GraphicsBindGroups{
|
||||||
|
camera:camera_bind_group,
|
||||||
|
skybox_texture:skybox_texture_bind_group,
|
||||||
|
},
|
||||||
|
camera,
|
||||||
|
camera_buf,
|
||||||
|
models: Vec::new(),
|
||||||
|
depth_view,
|
||||||
|
staging_belt: wgpu::util::StagingBelt::new(0x100),
|
||||||
|
bind_group_layouts: GraphicsBindGroupLayouts { model: model_bind_group_layout },
|
||||||
|
samplers: GraphicsSamplers { repeat: repeat_sampler },
|
||||||
|
temp_squid_texture_view: squid_texture_view,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn resize(
|
||||||
|
&mut self,
|
||||||
|
device:&wgpu::Device,
|
||||||
|
config:&wgpu::SurfaceConfiguration,
|
||||||
|
user_settings:&crate::settings::UserSettings,
|
||||||
|
) {
|
||||||
|
self.depth_view = Self::create_depth_texture(config,device);
|
||||||
|
self.camera.screen_size=glam::uvec2(config.width, config.height);
|
||||||
|
self.load_user_settings(user_settings);
|
||||||
|
}
|
||||||
|
pub fn render(
|
||||||
|
&mut self,
|
||||||
|
view:&wgpu::TextureView,
|
||||||
|
device:&wgpu::Device,
|
||||||
|
queue:&wgpu::Queue,
|
||||||
|
physics_output:crate::physics::PhysicsOutputState,
|
||||||
|
predicted_time:crate::integer::Time,
|
||||||
|
mouse_pos:glam::IVec2,
|
||||||
|
) {
|
||||||
|
//TODO: use scheduled frame times to create beautiful smoothing simulation physics extrapolation assuming no input
|
||||||
|
|
||||||
|
let mut encoder =
|
||||||
|
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
||||||
|
|
||||||
|
// update rotation
|
||||||
|
let camera_uniforms = self.camera.to_uniform_data(physics_output.extrapolate(mouse_pos,predicted_time));
|
||||||
|
self.staging_belt
|
||||||
|
.write_buffer(
|
||||||
|
&mut encoder,
|
||||||
|
&self.camera_buf,
|
||||||
|
0,
|
||||||
|
wgpu::BufferSize::new((camera_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
|
||||||
|
device,
|
||||||
|
)
|
||||||
|
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
|
||||||
|
//This code only needs to run when the uniforms change
|
||||||
|
/*
|
||||||
|
for model in self.models.iter() {
|
||||||
|
let model_uniforms = get_instances_buffer_data(&model.instances);
|
||||||
|
self.staging_belt
|
||||||
|
.write_buffer(
|
||||||
|
&mut encoder,
|
||||||
|
&model.model_buf,//description of where data will be written when command is executed
|
||||||
|
0,//offset in staging belt?
|
||||||
|
wgpu::BufferSize::new((model_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
|
||||||
|
device,
|
||||||
|
)
|
||||||
|
.copy_from_slice(bytemuck::cast_slice(&model_uniforms));
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
self.staging_belt.finish();
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||||
|
label: None,
|
||||||
|
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||||
|
view,
|
||||||
|
resolve_target: None,
|
||||||
|
ops: wgpu::Operations {
|
||||||
|
load: wgpu::LoadOp::Clear(wgpu::Color {
|
||||||
|
r: 0.1,
|
||||||
|
g: 0.2,
|
||||||
|
b: 0.3,
|
||||||
|
a: 1.0,
|
||||||
|
}),
|
||||||
|
store: true,
|
||||||
|
},
|
||||||
|
})],
|
||||||
|
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||||
|
view: &self.depth_view,
|
||||||
|
depth_ops: Some(wgpu::Operations {
|
||||||
|
load: wgpu::LoadOp::Clear(1.0),
|
||||||
|
store: false,
|
||||||
|
}),
|
||||||
|
stencil_ops: None,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
|
||||||
|
rpass.set_bind_group(1, &self.bind_groups.skybox_texture, &[]);
|
||||||
|
|
||||||
|
rpass.set_pipeline(&self.pipelines.model);
|
||||||
|
for model in self.models.iter() {
|
||||||
|
rpass.set_bind_group(2, &model.bind_group, &[]);
|
||||||
|
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
|
||||||
|
|
||||||
|
for entity in model.entities.iter() {
|
||||||
|
rpass.set_index_buffer(entity.index_buf.slice(..), wgpu::IndexFormat::Uint16);
|
||||||
|
rpass.draw_indexed(0..entity.index_count, 0, 0..model.instances.len() as u32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rpass.set_pipeline(&self.pipelines.skybox);
|
||||||
|
rpass.draw(0..3, 0..1);
|
||||||
|
}
|
||||||
|
|
||||||
|
queue.submit(std::iter::once(encoder.finish()));
|
||||||
|
|
||||||
|
self.staging_belt.recall();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const MODEL_BUFFER_SIZE:usize=4*4 + 12 + 4;//let size=std::mem::size_of::<ModelInstance>();
|
||||||
|
const MODEL_BUFFER_SIZE_BYTES:usize=MODEL_BUFFER_SIZE*4;
|
||||||
|
fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
|
||||||
|
let mut raw = Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
|
||||||
|
for (i,mi) in instances.iter().enumerate(){
|
||||||
|
let mut v = raw.split_off(MODEL_BUFFER_SIZE*i);
|
||||||
|
//model transform
|
||||||
|
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
|
||||||
|
//normal transform
|
||||||
|
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.x_axis));
|
||||||
|
raw.extend_from_slice(&[0.0]);
|
||||||
|
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.y_axis));
|
||||||
|
raw.extend_from_slice(&[0.0]);
|
||||||
|
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.z_axis));
|
||||||
|
raw.extend_from_slice(&[0.0]);
|
||||||
|
//color
|
||||||
|
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color.get()));
|
||||||
|
raw.append(&mut v);
|
||||||
|
}
|
||||||
|
raw
|
||||||
|
}
|
62
src/graphics_worker.rs
Normal file
62
src/graphics_worker.rs
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
pub enum Instruction{
|
||||||
|
Render(crate::physics::PhysicsOutputState,crate::integer::Time,glam::IVec2),
|
||||||
|
//UpdateModel(crate::graphics::ModelUpdate),
|
||||||
|
Resize(winit::dpi::PhysicalSize<u32>,crate::settings::UserSettings),
|
||||||
|
GenerateModels(crate::model::IndexedModelInstances),
|
||||||
|
ClearModels,
|
||||||
|
}
|
||||||
|
|
||||||
|
//Ideally the graphics thread worker description is:
|
||||||
|
/*
|
||||||
|
WorkerDescription{
|
||||||
|
input:Immediate,
|
||||||
|
output:Realtime(PoolOrdering::Ordered(3)),
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
//up to three frames in flight, dropping new frame requests when all three are busy, and dropping output frames when one renders out of order
|
||||||
|
|
||||||
|
pub fn new<'a>(
|
||||||
|
mut graphics:crate::graphics::GraphicsState,
|
||||||
|
mut config:wgpu::SurfaceConfiguration,
|
||||||
|
surface:wgpu::Surface,
|
||||||
|
device:wgpu::Device,
|
||||||
|
queue:wgpu::Queue,
|
||||||
|
)->crate::compat_worker::INWorker<'a,Instruction>{
|
||||||
|
crate::compat_worker::INWorker::new(move |ins:Instruction|{
|
||||||
|
match ins{
|
||||||
|
Instruction::GenerateModels(indexed_model_instances)=>{
|
||||||
|
graphics.generate_models(&device,&queue,indexed_model_instances);
|
||||||
|
},
|
||||||
|
Instruction::ClearModels=>{
|
||||||
|
graphics.clear();
|
||||||
|
},
|
||||||
|
Instruction::Resize(size,user_settings)=>{
|
||||||
|
println!("Resizing to {:?}",size);
|
||||||
|
config.width=size.width.max(1);
|
||||||
|
config.height=size.height.max(1);
|
||||||
|
surface.configure(&device,&config);
|
||||||
|
graphics.resize(&device,&config,&user_settings);
|
||||||
|
}
|
||||||
|
Instruction::Render(physics_output,predicted_time,mouse_pos)=>{
|
||||||
|
//this has to go deeper somehow
|
||||||
|
let frame=match surface.get_current_texture(){
|
||||||
|
Ok(frame)=>frame,
|
||||||
|
Err(_)=>{
|
||||||
|
surface.configure(&device,&config);
|
||||||
|
surface
|
||||||
|
.get_current_texture()
|
||||||
|
.expect("Failed to acquire next surface texture!")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let view=frame.texture.create_view(&wgpu::TextureViewDescriptor{
|
||||||
|
format:Some(config.view_formats[0]),
|
||||||
|
..wgpu::TextureViewDescriptor::default()
|
||||||
|
});
|
||||||
|
|
||||||
|
graphics.render(&view,&device,&queue,physics_output,predicted_time,mouse_pos);
|
||||||
|
|
||||||
|
frame.present();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
@ -41,6 +41,11 @@ impl std::fmt::Display for Time{
|
|||||||
write!(f,"{}s+{:09}ns",self.0/Self::ONE_SECOND.0,self.0%Self::ONE_SECOND.0)
|
write!(f,"{}s+{:09}ns",self.0/Self::ONE_SECOND.0,self.0%Self::ONE_SECOND.0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
impl std::default::Default for Time{
|
||||||
|
fn default()->Self{
|
||||||
|
Self(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
impl std::ops::Neg for Time{
|
impl std::ops::Neg for Time{
|
||||||
type Output=Time;
|
type Output=Time;
|
||||||
#[inline]
|
#[inline]
|
||||||
|
1311
src/main.rs
1311
src/main.rs
File diff suppressed because it is too large
Load Diff
145
src/physics.rs
145
src/physics.rs
@ -30,26 +30,13 @@ pub enum PhysicsInputInstruction {
|
|||||||
SetJump(bool),
|
SetJump(bool),
|
||||||
SetZoom(bool),
|
SetZoom(bool),
|
||||||
Reset,
|
Reset,
|
||||||
Idle,
|
|
||||||
}
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum InputInstruction {
|
|
||||||
MoveMouse(glam::IVec2),
|
|
||||||
MoveRight(bool),
|
|
||||||
MoveUp(bool),
|
|
||||||
MoveBack(bool),
|
|
||||||
MoveLeft(bool),
|
|
||||||
MoveDown(bool),
|
|
||||||
MoveForward(bool),
|
|
||||||
Jump(bool),
|
|
||||||
Zoom(bool),
|
|
||||||
Reset,
|
|
||||||
Idle,
|
Idle,
|
||||||
//Idle: there were no input events, but the simulation is safe to advance to this timestep
|
//Idle: there were no input events, but the simulation is safe to advance to this timestep
|
||||||
//for interpolation / networking / playback reasons, most playback heads will always want
|
//for interpolation / networking / playback reasons, most playback heads will always want
|
||||||
//to be 1 instruction ahead to generate the next state for interpolation.
|
//to be 1 instruction ahead to generate the next state for interpolation.
|
||||||
}
|
}
|
||||||
#[derive(Clone,Hash)]
|
|
||||||
|
#[derive(Clone,Hash,Default)]
|
||||||
pub struct Body {
|
pub struct Body {
|
||||||
position: Planar64Vec3,//I64 where 2^32 = 1 u
|
position: Planar64Vec3,//I64 where 2^32 = 1 u
|
||||||
velocity: Planar64Vec3,//I64 where 2^32 = 1 u/s
|
velocity: Planar64Vec3,//I64 where 2^32 = 1 u/s
|
||||||
@ -257,6 +244,19 @@ impl PhysicsCamera {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl std::default::Default for PhysicsCamera{
|
||||||
|
fn default()->Self{
|
||||||
|
Self{
|
||||||
|
offset:Planar64Vec3::ZERO,//TODO: delete this from PhysicsCamera, it should be GraphicsCamera only
|
||||||
|
sensitivity:Ratio64Vec2::ONE*200_000,
|
||||||
|
mouse:MouseState::default(),//t=0 does not cause divide by zero because it's immediately replaced
|
||||||
|
clamped_mouse_pos:glam::IVec2::ZERO,
|
||||||
|
angle_pitch_lower_limit:-Angle32::FRAC_PI_2,
|
||||||
|
angle_pitch_upper_limit:Angle32::FRAC_PI_2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct GameMechanicsState{
|
pub struct GameMechanicsState{
|
||||||
pub stage_id:u32,
|
pub stage_id:u32,
|
||||||
//jump_counts:HashMap<u32,u32>,
|
//jump_counts:HashMap<u32,u32>,
|
||||||
@ -523,15 +523,15 @@ enum MoveState{
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct PhysicsState{
|
pub struct PhysicsState{
|
||||||
pub time:Time,
|
time:Time,
|
||||||
body:Body,
|
body:Body,
|
||||||
world:WorldState,//currently there is only one state the world can be in
|
world:WorldState,//currently there is only one state the world can be in
|
||||||
pub game:GameMechanicsState,
|
game:GameMechanicsState,
|
||||||
style:StyleModifiers,
|
style:StyleModifiers,
|
||||||
touching:TouchingState,
|
touching:TouchingState,
|
||||||
//camera must exist in state because wormholes modify the camera, also camera punch
|
//camera must exist in state because wormholes modify the camera, also camera punch
|
||||||
camera:PhysicsCamera,
|
camera:PhysicsCamera,
|
||||||
next_mouse:MouseState,//Where is the mouse headed next
|
pub next_mouse:MouseState,//Where is the mouse headed next
|
||||||
controls:u32,
|
controls:u32,
|
||||||
move_state:MoveState,
|
move_state:MoveState,
|
||||||
//all models
|
//all models
|
||||||
@ -541,16 +541,16 @@ pub struct PhysicsState{
|
|||||||
modes:Modes,
|
modes:Modes,
|
||||||
//the spawn point is where you spawn when you load into the map.
|
//the spawn point is where you spawn when you load into the map.
|
||||||
//This is not the same as Reset which teleports you to Spawn0
|
//This is not the same as Reset which teleports you to Spawn0
|
||||||
pub spawn_point:Planar64Vec3,
|
spawn_point:Planar64Vec3,
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
#[derive(Clone,Default)]
|
||||||
pub struct PhysicsOutputState{
|
pub struct PhysicsOutputState{
|
||||||
camera:PhysicsCamera,
|
camera:PhysicsCamera,
|
||||||
body:Body,
|
body:Body,
|
||||||
}
|
}
|
||||||
impl PhysicsOutputState{
|
impl PhysicsOutputState{
|
||||||
pub fn adjust_mouse(&self,mouse:&MouseState)->(glam::Vec3,glam::Vec2){
|
pub fn extrapolate(&self,mouse_pos:glam::IVec2,time:Time)->(glam::Vec3,glam::Vec2){
|
||||||
((self.body.extrapolated_position(mouse.time)+self.camera.offset).into(),self.camera.simulate_move_angles(mouse.pos))
|
((self.body.extrapolated_position(time)+self.camera.offset).into(),self.camera.simulate_move_angles(mouse_pos))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -734,93 +734,7 @@ impl PhysicsState {
|
|||||||
self.models.clear();
|
self.models.clear();
|
||||||
self.modes.clear();
|
self.modes.clear();
|
||||||
self.touching.clear();
|
self.touching.clear();
|
||||||
}
|
self.bvh=crate::bvh::BvhNode::default();
|
||||||
|
|
||||||
pub fn into_worker(mut self)->crate::worker::CompatWorker<TimedInstruction<InputInstruction>,PhysicsOutputState,Box<dyn FnMut(TimedInstruction<InputInstruction>)->PhysicsOutputState>>{
|
|
||||||
let mut mouse_blocking=true;
|
|
||||||
let mut last_mouse_time=self.next_mouse.time;
|
|
||||||
let mut timeline=std::collections::VecDeque::new();
|
|
||||||
crate::worker::CompatWorker::new(self.output(),Box::new(move |ins:TimedInstruction<InputInstruction>|{
|
|
||||||
if if let Some(phys_input)=match ins.instruction{
|
|
||||||
InputInstruction::MoveMouse(m)=>{
|
|
||||||
if mouse_blocking{
|
|
||||||
//tell the game state which is living in the past about its future
|
|
||||||
timeline.push_front(TimedInstruction{
|
|
||||||
time:last_mouse_time,
|
|
||||||
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:m}),
|
|
||||||
});
|
|
||||||
}else{
|
|
||||||
//mouse has just started moving again after being still for longer than 10ms.
|
|
||||||
//replace the entire mouse interpolation state to avoid an intermediate state with identical m0.t m1.t timestamps which will divide by zero
|
|
||||||
timeline.push_front(TimedInstruction{
|
|
||||||
time:last_mouse_time,
|
|
||||||
instruction:PhysicsInputInstruction::ReplaceMouse(
|
|
||||||
MouseState{time:last_mouse_time,pos:self.next_mouse.pos},
|
|
||||||
MouseState{time:ins.time,pos:m}
|
|
||||||
),
|
|
||||||
});
|
|
||||||
//delay physics execution until we have an interpolation target
|
|
||||||
mouse_blocking=true;
|
|
||||||
}
|
|
||||||
last_mouse_time=ins.time;
|
|
||||||
None
|
|
||||||
},
|
|
||||||
InputInstruction::MoveForward(s)=>Some(PhysicsInputInstruction::SetMoveForward(s)),
|
|
||||||
InputInstruction::MoveLeft(s)=>Some(PhysicsInputInstruction::SetMoveLeft(s)),
|
|
||||||
InputInstruction::MoveBack(s)=>Some(PhysicsInputInstruction::SetMoveBack(s)),
|
|
||||||
InputInstruction::MoveRight(s)=>Some(PhysicsInputInstruction::SetMoveRight(s)),
|
|
||||||
InputInstruction::MoveUp(s)=>Some(PhysicsInputInstruction::SetMoveUp(s)),
|
|
||||||
InputInstruction::MoveDown(s)=>Some(PhysicsInputInstruction::SetMoveDown(s)),
|
|
||||||
InputInstruction::Jump(s)=>Some(PhysicsInputInstruction::SetJump(s)),
|
|
||||||
InputInstruction::Zoom(s)=>Some(PhysicsInputInstruction::SetZoom(s)),
|
|
||||||
InputInstruction::Reset=>Some(PhysicsInputInstruction::Reset),
|
|
||||||
InputInstruction::Idle=>Some(PhysicsInputInstruction::Idle),
|
|
||||||
}{
|
|
||||||
//non-mouse event
|
|
||||||
timeline.push_back(TimedInstruction{
|
|
||||||
time:ins.time,
|
|
||||||
instruction:phys_input,
|
|
||||||
});
|
|
||||||
|
|
||||||
if mouse_blocking{
|
|
||||||
//assume the mouse has stopped moving after 10ms.
|
|
||||||
//shitty mice are 125Hz which is 8ms so this should cover that.
|
|
||||||
//setting this to 100us still doesn't print even though it's 10x lower than the polling rate,
|
|
||||||
//so mouse events are probably not handled separately from drawing and fire right before it :(
|
|
||||||
if Time::from_millis(10)<ins.time-self.next_mouse.time{
|
|
||||||
//push an event to extrapolate no movement from
|
|
||||||
timeline.push_front(TimedInstruction{
|
|
||||||
time:last_mouse_time,
|
|
||||||
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:self.next_mouse.pos}),
|
|
||||||
});
|
|
||||||
last_mouse_time=ins.time;
|
|
||||||
//stop blocking. the mouse is not moving so the physics does not need to live in the past and wait for interpolation targets.
|
|
||||||
mouse_blocking=false;
|
|
||||||
true
|
|
||||||
}else{
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}else{
|
|
||||||
//keep this up to date so that it can be used as a known-timestamp
|
|
||||||
//that the mouse was not moving when the mouse starts moving again
|
|
||||||
last_mouse_time=ins.time;
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}else{
|
|
||||||
//mouse event
|
|
||||||
true
|
|
||||||
}{
|
|
||||||
//empty queue
|
|
||||||
while let Some(instruction)=timeline.pop_front(){
|
|
||||||
self.run(instruction.time);
|
|
||||||
self.process_instruction(TimedInstruction{
|
|
||||||
time:instruction.time,
|
|
||||||
instruction:PhysicsInstruction::Input(instruction.instruction),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.output()
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn output(&self)->PhysicsOutputState{
|
pub fn output(&self)->PhysicsOutputState{
|
||||||
@ -830,6 +744,15 @@ impl PhysicsState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn spawn(&mut self,spawn_point:Planar64Vec3){
|
||||||
|
self.game.stage_id=0;
|
||||||
|
self.spawn_point=spawn_point;
|
||||||
|
self.process_instruction(crate::instruction::TimedInstruction{
|
||||||
|
time:self.time,
|
||||||
|
instruction: PhysicsInstruction::Input(PhysicsInputInstruction::Reset),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
pub fn generate_models(&mut self,indexed_models:&crate::model::IndexedModelInstances){
|
pub fn generate_models(&mut self,indexed_models:&crate::model::IndexedModelInstances){
|
||||||
let mut starts=Vec::new();
|
let mut starts=Vec::new();
|
||||||
let mut spawns=Vec::new();
|
let mut spawns=Vec::new();
|
||||||
@ -1357,12 +1280,12 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
|||||||
}
|
}
|
||||||
//selectively update body
|
//selectively update body
|
||||||
match &ins.instruction {
|
match &ins.instruction {
|
||||||
//PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
|
PhysicsInstruction::Input(PhysicsInputInstruction::Idle)=>self.time=ins.time,//idle simply updates time
|
||||||
PhysicsInstruction::Input(_)
|
PhysicsInstruction::Input(_)
|
||||||
|PhysicsInstruction::ReachWalkTargetVelocity
|
|PhysicsInstruction::ReachWalkTargetVelocity
|
||||||
|PhysicsInstruction::CollisionStart(_)
|
|PhysicsInstruction::CollisionStart(_)
|
||||||
|PhysicsInstruction::CollisionEnd(_)
|
|PhysicsInstruction::CollisionEnd(_)
|
||||||
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time),
|
|PhysicsInstruction::StrafeTick=>self.advance_time(ins.time),
|
||||||
}
|
}
|
||||||
match ins.instruction {
|
match ins.instruction {
|
||||||
PhysicsInstruction::CollisionStart(c) => {
|
PhysicsInstruction::CollisionStart(c) => {
|
||||||
|
133
src/physics_worker.rs
Normal file
133
src/physics_worker.rs
Normal file
@ -0,0 +1,133 @@
|
|||||||
|
use crate::integer::Time;
|
||||||
|
use crate::physics::{MouseState,PhysicsInputInstruction};
|
||||||
|
use crate::instruction::{TimedInstruction,InstructionConsumer};
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum InputInstruction {
|
||||||
|
MoveMouse(glam::IVec2),
|
||||||
|
MoveRight(bool),
|
||||||
|
MoveUp(bool),
|
||||||
|
MoveBack(bool),
|
||||||
|
MoveLeft(bool),
|
||||||
|
MoveDown(bool),
|
||||||
|
MoveForward(bool),
|
||||||
|
Jump(bool),
|
||||||
|
Zoom(bool),
|
||||||
|
Reset,
|
||||||
|
}
|
||||||
|
pub enum Instruction{
|
||||||
|
Input(InputInstruction),
|
||||||
|
Render,
|
||||||
|
Resize(winit::dpi::PhysicalSize<u32>,crate::settings::UserSettings),
|
||||||
|
GenerateModels(crate::model::IndexedModelInstances),
|
||||||
|
ClearModels,
|
||||||
|
//Graphics(crate::graphics_worker::Instruction),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new(mut physics:crate::physics::PhysicsState,mut graphics_worker:crate::compat_worker::INWorker<crate::graphics_worker::Instruction>)->crate::compat_worker::QNWorker<TimedInstruction<Instruction>>{
|
||||||
|
let mut mouse_blocking=true;
|
||||||
|
let mut last_mouse_time=physics.next_mouse.time;
|
||||||
|
let mut timeline=std::collections::VecDeque::new();
|
||||||
|
crate::compat_worker::QNWorker::new(move |ins:TimedInstruction<Instruction>|{
|
||||||
|
if if let Some(phys_input)=match &ins.instruction{
|
||||||
|
Instruction::Input(input_instruction)=>match input_instruction{
|
||||||
|
&InputInstruction::MoveMouse(m)=>{
|
||||||
|
if mouse_blocking{
|
||||||
|
//tell the game state which is living in the past about its future
|
||||||
|
timeline.push_front(TimedInstruction{
|
||||||
|
time:last_mouse_time,
|
||||||
|
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:m}),
|
||||||
|
});
|
||||||
|
}else{
|
||||||
|
//mouse has just started moving again after being still for longer than 10ms.
|
||||||
|
//replace the entire mouse interpolation state to avoid an intermediate state with identical m0.t m1.t timestamps which will divide by zero
|
||||||
|
timeline.push_front(TimedInstruction{
|
||||||
|
time:last_mouse_time,
|
||||||
|
instruction:PhysicsInputInstruction::ReplaceMouse(
|
||||||
|
MouseState{time:last_mouse_time,pos:physics.next_mouse.pos},
|
||||||
|
MouseState{time:ins.time,pos:m}
|
||||||
|
),
|
||||||
|
});
|
||||||
|
//delay physics execution until we have an interpolation target
|
||||||
|
mouse_blocking=true;
|
||||||
|
}
|
||||||
|
last_mouse_time=ins.time;
|
||||||
|
None
|
||||||
|
},
|
||||||
|
&InputInstruction::MoveForward(s)=>Some(PhysicsInputInstruction::SetMoveForward(s)),
|
||||||
|
&InputInstruction::MoveLeft(s)=>Some(PhysicsInputInstruction::SetMoveLeft(s)),
|
||||||
|
&InputInstruction::MoveBack(s)=>Some(PhysicsInputInstruction::SetMoveBack(s)),
|
||||||
|
&InputInstruction::MoveRight(s)=>Some(PhysicsInputInstruction::SetMoveRight(s)),
|
||||||
|
&InputInstruction::MoveUp(s)=>Some(PhysicsInputInstruction::SetMoveUp(s)),
|
||||||
|
&InputInstruction::MoveDown(s)=>Some(PhysicsInputInstruction::SetMoveDown(s)),
|
||||||
|
&InputInstruction::Jump(s)=>Some(PhysicsInputInstruction::SetJump(s)),
|
||||||
|
&InputInstruction::Zoom(s)=>Some(PhysicsInputInstruction::SetZoom(s)),
|
||||||
|
InputInstruction::Reset=>Some(PhysicsInputInstruction::Reset),
|
||||||
|
},
|
||||||
|
Instruction::GenerateModels(_)=>Some(PhysicsInputInstruction::Idle),
|
||||||
|
Instruction::ClearModels=>Some(PhysicsInputInstruction::Idle),
|
||||||
|
Instruction::Resize(_,_)=>Some(PhysicsInputInstruction::Idle),
|
||||||
|
Instruction::Render=>Some(PhysicsInputInstruction::Idle),
|
||||||
|
}{
|
||||||
|
//non-mouse event
|
||||||
|
timeline.push_back(TimedInstruction{
|
||||||
|
time:ins.time,
|
||||||
|
instruction:phys_input,
|
||||||
|
});
|
||||||
|
|
||||||
|
if mouse_blocking{
|
||||||
|
//assume the mouse has stopped moving after 10ms.
|
||||||
|
//shitty mice are 125Hz which is 8ms so this should cover that.
|
||||||
|
//setting this to 100us still doesn't print even though it's 10x lower than the polling rate,
|
||||||
|
//so mouse events are probably not handled separately from drawing and fire right before it :(
|
||||||
|
if Time::from_millis(10)<ins.time-physics.next_mouse.time{
|
||||||
|
//push an event to extrapolate no movement from
|
||||||
|
timeline.push_front(TimedInstruction{
|
||||||
|
time:last_mouse_time,
|
||||||
|
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:physics.next_mouse.pos}),
|
||||||
|
});
|
||||||
|
last_mouse_time=ins.time;
|
||||||
|
//stop blocking. the mouse is not moving so the physics does not need to live in the past and wait for interpolation targets.
|
||||||
|
mouse_blocking=false;
|
||||||
|
true
|
||||||
|
}else{
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
//keep this up to date so that it can be used as a known-timestamp
|
||||||
|
//that the mouse was not moving when the mouse starts moving again
|
||||||
|
last_mouse_time=ins.time;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
//mouse event
|
||||||
|
true
|
||||||
|
}{
|
||||||
|
//empty queue
|
||||||
|
while let Some(instruction)=timeline.pop_front(){
|
||||||
|
physics.run(instruction.time);
|
||||||
|
physics.process_instruction(TimedInstruction{
|
||||||
|
time:instruction.time,
|
||||||
|
instruction:crate::physics::PhysicsInstruction::Input(instruction.instruction),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match ins.instruction{
|
||||||
|
Instruction::Render=>{
|
||||||
|
graphics_worker.send(crate::graphics_worker::Instruction::Render(physics.output(),ins.time,physics.next_mouse.pos)).unwrap();
|
||||||
|
},
|
||||||
|
Instruction::Resize(size,user_settings)=>{
|
||||||
|
graphics_worker.send(crate::graphics_worker::Instruction::Resize(size,user_settings)).unwrap();
|
||||||
|
},
|
||||||
|
Instruction::GenerateModels(indexed_model_instances)=>{
|
||||||
|
physics.generate_models(&indexed_model_instances);
|
||||||
|
physics.spawn(indexed_model_instances.spawn_point);
|
||||||
|
graphics_worker.send(crate::graphics_worker::Instruction::GenerateModels(indexed_model_instances)).unwrap();
|
||||||
|
},
|
||||||
|
Instruction::ClearModels=>{
|
||||||
|
physics.clear();
|
||||||
|
graphics_worker.send(crate::graphics_worker::Instruction::ClearModels).unwrap();
|
||||||
|
},
|
||||||
|
_=>(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
@ -1,11 +1,14 @@
|
|||||||
use crate::integer::{Ratio64,Ratio64Vec2};
|
use crate::integer::{Ratio64,Ratio64Vec2};
|
||||||
|
#[derive(Clone)]
|
||||||
struct Ratio{
|
struct Ratio{
|
||||||
ratio:f64,
|
ratio:f64,
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum DerivedFov{
|
enum DerivedFov{
|
||||||
FromScreenAspect,
|
FromScreenAspect,
|
||||||
FromAspect(Ratio),
|
FromAspect(Ratio),
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum Fov{
|
enum Fov{
|
||||||
Exactly{x:f64,y:f64},
|
Exactly{x:f64,y:f64},
|
||||||
SpecifyXDeriveY{x:f64,y:DerivedFov},
|
SpecifyXDeriveY{x:f64,y:DerivedFov},
|
||||||
@ -16,9 +19,11 @@ impl Default for Fov{
|
|||||||
Fov::SpecifyYDeriveX{x:DerivedFov::FromScreenAspect,y:1.0}
|
Fov::SpecifyYDeriveX{x:DerivedFov::FromScreenAspect,y:1.0}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum DerivedSensitivity{
|
enum DerivedSensitivity{
|
||||||
FromRatio(Ratio64),
|
FromRatio(Ratio64),
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum Sensitivity{
|
enum Sensitivity{
|
||||||
Exactly{x:Ratio64,y:Ratio64},
|
Exactly{x:Ratio64,y:Ratio64},
|
||||||
SpecifyXDeriveY{x:Ratio64,y:DerivedSensitivity},
|
SpecifyXDeriveY{x:Ratio64,y:DerivedSensitivity},
|
||||||
@ -30,7 +35,7 @@ impl Default for Sensitivity{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default,Clone)]
|
||||||
pub struct UserSettings{
|
pub struct UserSettings{
|
||||||
fov:Fov,
|
fov:Fov,
|
||||||
sensitivity:Sensitivity,
|
sensitivity:Sensitivity,
|
||||||
|
300
src/setup.rs
Normal file
300
src/setup.rs
Normal file
@ -0,0 +1,300 @@
|
|||||||
|
use crate::instruction::TimedInstruction;
|
||||||
|
use crate::window::WindowInstruction;
|
||||||
|
|
||||||
|
fn optional_features()->wgpu::Features{
|
||||||
|
wgpu::Features::TEXTURE_COMPRESSION_ASTC
|
||||||
|
|wgpu::Features::TEXTURE_COMPRESSION_ETC2
|
||||||
|
}
|
||||||
|
fn required_features()->wgpu::Features{
|
||||||
|
wgpu::Features::TEXTURE_COMPRESSION_BC
|
||||||
|
}
|
||||||
|
fn required_downlevel_capabilities()->wgpu::DownlevelCapabilities{
|
||||||
|
wgpu::DownlevelCapabilities{
|
||||||
|
flags:wgpu::DownlevelFlags::empty(),
|
||||||
|
shader_model:wgpu::ShaderModel::Sm5,
|
||||||
|
..wgpu::DownlevelCapabilities::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn required_limits()->wgpu::Limits{
|
||||||
|
wgpu::Limits::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SetupContextPartial1{
|
||||||
|
backends:wgpu::Backends,
|
||||||
|
instance:wgpu::Instance,
|
||||||
|
}
|
||||||
|
fn create_window(title:&str,event_loop:&winit::event_loop::EventLoop<()>)->Result<winit::window::Window,winit::error::OsError>{
|
||||||
|
let mut builder = winit::window::WindowBuilder::new();
|
||||||
|
builder = builder.with_title(title);
|
||||||
|
#[cfg(windows_OFF)] // TODO
|
||||||
|
{
|
||||||
|
use winit::platform::windows::WindowBuilderExtWindows;
|
||||||
|
builder = builder.with_no_redirection_bitmap(true);
|
||||||
|
}
|
||||||
|
builder.build(event_loop)
|
||||||
|
}
|
||||||
|
fn create_instance()->SetupContextPartial1{
|
||||||
|
let backends=wgpu::util::backend_bits_from_env().unwrap_or_else(wgpu::Backends::all);
|
||||||
|
let dx12_shader_compiler=wgpu::util::dx12_shader_compiler_from_env().unwrap_or_default();
|
||||||
|
SetupContextPartial1{
|
||||||
|
backends,
|
||||||
|
instance:wgpu::Instance::new(wgpu::InstanceDescriptor{
|
||||||
|
backends,
|
||||||
|
dx12_shader_compiler,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl SetupContextPartial1{
|
||||||
|
fn create_surface(self,window:&winit::window::Window)->Result<SetupContextPartial2,wgpu::CreateSurfaceError>{
|
||||||
|
Ok(SetupContextPartial2{
|
||||||
|
backends:self.backends,
|
||||||
|
surface:unsafe{self.instance.create_surface(window)}?,
|
||||||
|
instance:self.instance,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct SetupContextPartial2{
|
||||||
|
backends:wgpu::Backends,
|
||||||
|
instance:wgpu::Instance,
|
||||||
|
surface:wgpu::Surface,
|
||||||
|
}
|
||||||
|
impl SetupContextPartial2{
|
||||||
|
fn pick_adapter(self)->SetupContextPartial3{
|
||||||
|
let adapter;
|
||||||
|
|
||||||
|
let optional_features=optional_features();
|
||||||
|
let required_features=required_features();
|
||||||
|
|
||||||
|
//no helper function smh gotta write it myself
|
||||||
|
let adapters=self.instance.enumerate_adapters(self.backends);
|
||||||
|
|
||||||
|
let mut chosen_adapter=None;
|
||||||
|
let mut chosen_adapter_score=0;
|
||||||
|
for adapter in adapters {
|
||||||
|
if !adapter.is_surface_supported(&self.surface) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let score=match adapter.get_info().device_type{
|
||||||
|
wgpu::DeviceType::IntegratedGpu=>3,
|
||||||
|
wgpu::DeviceType::DiscreteGpu=>4,
|
||||||
|
wgpu::DeviceType::VirtualGpu=>2,
|
||||||
|
wgpu::DeviceType::Other|wgpu::DeviceType::Cpu=>1,
|
||||||
|
};
|
||||||
|
|
||||||
|
let adapter_features=adapter.features();
|
||||||
|
if chosen_adapter_score<score&&adapter_features.contains(required_features) {
|
||||||
|
chosen_adapter_score=score;
|
||||||
|
chosen_adapter=Some(adapter);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(maybe_chosen_adapter)=chosen_adapter{
|
||||||
|
adapter=maybe_chosen_adapter;
|
||||||
|
}else{
|
||||||
|
panic!("No suitable GPU adapters found on the system!");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
let adapter_info=adapter.get_info();
|
||||||
|
println!("Using {} ({:?})", adapter_info.name, adapter_info.backend);
|
||||||
|
|
||||||
|
let required_downlevel_capabilities=required_downlevel_capabilities();
|
||||||
|
let downlevel_capabilities=adapter.get_downlevel_capabilities();
|
||||||
|
assert!(
|
||||||
|
downlevel_capabilities.shader_model >= required_downlevel_capabilities.shader_model,
|
||||||
|
"Adapter does not support the minimum shader model required to run this example: {:?}",
|
||||||
|
required_downlevel_capabilities.shader_model
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
downlevel_capabilities
|
||||||
|
.flags
|
||||||
|
.contains(required_downlevel_capabilities.flags),
|
||||||
|
"Adapter does not support the downlevel capabilities required to run this example: {:?}",
|
||||||
|
required_downlevel_capabilities.flags - downlevel_capabilities.flags
|
||||||
|
);
|
||||||
|
SetupContextPartial3{
|
||||||
|
instance:self.instance,
|
||||||
|
surface:self.surface,
|
||||||
|
adapter,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct SetupContextPartial3{
|
||||||
|
instance:wgpu::Instance,
|
||||||
|
surface:wgpu::Surface,
|
||||||
|
adapter:wgpu::Adapter,
|
||||||
|
}
|
||||||
|
impl SetupContextPartial3{
|
||||||
|
fn request_device(self)->SetupContextPartial4{
|
||||||
|
let optional_features=optional_features();
|
||||||
|
let required_features=required_features();
|
||||||
|
|
||||||
|
// Make sure we use the texture resolution limits from the adapter, so we can support images the size of the surface.
|
||||||
|
let needed_limits=required_limits().using_resolution(self.adapter.limits());
|
||||||
|
|
||||||
|
let trace_dir=std::env::var("WGPU_TRACE");
|
||||||
|
let (device, queue)=pollster::block_on(self.adapter
|
||||||
|
.request_device(
|
||||||
|
&wgpu::DeviceDescriptor {
|
||||||
|
label: None,
|
||||||
|
features: (optional_features & self.adapter.features()) | required_features,
|
||||||
|
limits: needed_limits,
|
||||||
|
},
|
||||||
|
trace_dir.ok().as_ref().map(std::path::Path::new),
|
||||||
|
))
|
||||||
|
.expect("Unable to find a suitable GPU adapter!");
|
||||||
|
|
||||||
|
SetupContextPartial4{
|
||||||
|
instance:self.instance,
|
||||||
|
surface:self.surface,
|
||||||
|
adapter:self.adapter,
|
||||||
|
device,
|
||||||
|
queue,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct SetupContextPartial4{
|
||||||
|
instance:wgpu::Instance,
|
||||||
|
surface:wgpu::Surface,
|
||||||
|
adapter:wgpu::Adapter,
|
||||||
|
device:wgpu::Device,
|
||||||
|
queue:wgpu::Queue,
|
||||||
|
}
|
||||||
|
impl SetupContextPartial4{
|
||||||
|
fn configure_surface(self,size:&winit::dpi::PhysicalSize<u32>)->SetupContext{
|
||||||
|
let mut config=self.surface
|
||||||
|
.get_default_config(&self.adapter, size.width, size.height)
|
||||||
|
.expect("Surface isn't supported by the adapter.");
|
||||||
|
let surface_view_format=config.format.add_srgb_suffix();
|
||||||
|
config.view_formats.push(surface_view_format);
|
||||||
|
self.surface.configure(&self.device, &config);
|
||||||
|
|
||||||
|
SetupContext{
|
||||||
|
instance:self.instance,
|
||||||
|
surface:self.surface,
|
||||||
|
device:self.device,
|
||||||
|
queue:self.queue,
|
||||||
|
config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub struct SetupContext{
|
||||||
|
pub instance:wgpu::Instance,
|
||||||
|
pub surface:wgpu::Surface,
|
||||||
|
pub device:wgpu::Device,
|
||||||
|
pub queue:wgpu::Queue,
|
||||||
|
pub config:wgpu::SurfaceConfiguration,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn setup(title:&str)->SetupContextSetup{
|
||||||
|
let event_loop=winit::event_loop::EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window=create_window(title,&event_loop).unwrap();
|
||||||
|
|
||||||
|
println!("Initializing the surface...");
|
||||||
|
|
||||||
|
let partial_1=create_instance();
|
||||||
|
|
||||||
|
let partial_2=partial_1.create_surface(&window).unwrap();
|
||||||
|
|
||||||
|
let partial_3=partial_2.pick_adapter();
|
||||||
|
|
||||||
|
let partial_4=partial_3.request_device();
|
||||||
|
|
||||||
|
SetupContextSetup{
|
||||||
|
window,
|
||||||
|
event_loop,
|
||||||
|
partial_context:partial_4,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SetupContextSetup{
|
||||||
|
window:winit::window::Window,
|
||||||
|
event_loop:winit::event_loop::EventLoop<()>,
|
||||||
|
partial_context:SetupContextPartial4,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SetupContextSetup{
|
||||||
|
fn into_split(self)->(winit::window::Window,winit::event_loop::EventLoop<()>,SetupContext){
|
||||||
|
let size=self.window.inner_size();
|
||||||
|
//Steal values and drop self
|
||||||
|
(
|
||||||
|
self.window,
|
||||||
|
self.event_loop,
|
||||||
|
self.partial_context.configure_surface(&size),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
pub fn start(self){
|
||||||
|
let (window,event_loop,setup_context)=self.into_split();
|
||||||
|
|
||||||
|
//dedicated thread to ping request redraw back and resize the window doesn't seem logical
|
||||||
|
|
||||||
|
let window=crate::window::WindowContextSetup::new(&setup_context,window);
|
||||||
|
//the thread that spawns the physics thread
|
||||||
|
let window_thread=window.into_worker(setup_context);
|
||||||
|
|
||||||
|
println!("Entering event loop...");
|
||||||
|
let root_time=std::time::Instant::now();
|
||||||
|
run_event_loop(event_loop,window_thread,root_time).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_event_loop(
|
||||||
|
event_loop:winit::event_loop::EventLoop<()>,
|
||||||
|
mut window_thread:crate::compat_worker::QNWorker<TimedInstruction<WindowInstruction>>,
|
||||||
|
root_time:std::time::Instant
|
||||||
|
)->Result<(),winit::error::EventLoopError>{
|
||||||
|
event_loop.run(move |event,elwt|{
|
||||||
|
let time=crate::integer::Time::from_nanos(root_time.elapsed().as_nanos() as i64);
|
||||||
|
// *control_flow=if cfg!(feature="metal-auto-capture"){
|
||||||
|
// winit::event_loop::ControlFlow::Exit
|
||||||
|
// }else{
|
||||||
|
// winit::event_loop::ControlFlow::Poll
|
||||||
|
// };
|
||||||
|
match event{
|
||||||
|
winit::event::Event::AboutToWait=>{
|
||||||
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::RequestRedraw}).unwrap();
|
||||||
|
}
|
||||||
|
winit::event::Event::WindowEvent {
|
||||||
|
event:
|
||||||
|
// WindowEvent::Resized(size)
|
||||||
|
// | WindowEvent::ScaleFactorChanged {
|
||||||
|
// new_inner_size: &mut size,
|
||||||
|
// ..
|
||||||
|
// },
|
||||||
|
winit::event::WindowEvent::Resized(size),//ignoring scale factor changed for now because mutex bruh
|
||||||
|
window_id:_,
|
||||||
|
} => {
|
||||||
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::Resize(size)}).unwrap();
|
||||||
|
}
|
||||||
|
winit::event::Event::WindowEvent{event,..}=>match event{
|
||||||
|
winit::event::WindowEvent::KeyboardInput{
|
||||||
|
event:
|
||||||
|
winit::event::KeyEvent {
|
||||||
|
logical_key: winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape),
|
||||||
|
state: winit::event::ElementState::Pressed,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
..
|
||||||
|
}
|
||||||
|
|winit::event::WindowEvent::CloseRequested=>{
|
||||||
|
elwt.exit();
|
||||||
|
}
|
||||||
|
winit::event::WindowEvent::RedrawRequested=>{
|
||||||
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::Render}).unwrap();
|
||||||
|
}
|
||||||
|
_=>{
|
||||||
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::WindowEvent(event)}).unwrap();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
winit::event::Event::DeviceEvent{
|
||||||
|
event,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::DeviceEvent(event)}).unwrap();
|
||||||
|
},
|
||||||
|
_=>{}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
243
src/window.rs
Normal file
243
src/window.rs
Normal file
@ -0,0 +1,243 @@
|
|||||||
|
use crate::instruction::TimedInstruction;
|
||||||
|
use crate::physics_worker::InputInstruction;
|
||||||
|
|
||||||
|
pub enum WindowInstruction{
|
||||||
|
Resize(winit::dpi::PhysicalSize<u32>),
|
||||||
|
WindowEvent(winit::event::WindowEvent),
|
||||||
|
DeviceEvent(winit::event::DeviceEvent),
|
||||||
|
RequestRedraw,
|
||||||
|
Render,
|
||||||
|
}
|
||||||
|
|
||||||
|
//holds thread handles to dispatch to
|
||||||
|
struct WindowContext<'a>{
|
||||||
|
manual_mouse_lock:bool,
|
||||||
|
mouse:crate::physics::MouseState,//std::sync::Arc<std::sync::Mutex<>>
|
||||||
|
screen_size:glam::UVec2,
|
||||||
|
user_settings:crate::settings::UserSettings,
|
||||||
|
window:winit::window::Window,
|
||||||
|
physics_thread:crate::compat_worker::QNWorker<'a, TimedInstruction<crate::physics_worker::Instruction>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowContext<'_>{
|
||||||
|
fn get_middle_of_screen(&self)->winit::dpi::PhysicalPosition<f32>{
|
||||||
|
winit::dpi::PhysicalPosition::new(self.screen_size.x as f32/2.0, self.screen_size.y as f32/2.0)
|
||||||
|
}
|
||||||
|
fn window_event(&mut self,time:crate::integer::Time,event: winit::event::WindowEvent) {
|
||||||
|
match event {
|
||||||
|
winit::event::WindowEvent::DroppedFile(path)=>{
|
||||||
|
//blocking because it's simpler...
|
||||||
|
if let Some(indexed_model_instances)=crate::load_file(path){
|
||||||
|
self.physics_thread.send(TimedInstruction{time,instruction:crate::physics_worker::Instruction::ClearModels}).unwrap();
|
||||||
|
self.physics_thread.send(TimedInstruction{time,instruction:crate::physics_worker::Instruction::GenerateModels(indexed_model_instances)}).unwrap();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
winit::event::WindowEvent::Focused(state)=>{
|
||||||
|
//pause unpause
|
||||||
|
//recalculate pressed keys on focus
|
||||||
|
},
|
||||||
|
winit::event::WindowEvent::KeyboardInput{
|
||||||
|
event:winit::event::KeyEvent{state,logical_key,repeat:false,..},
|
||||||
|
..
|
||||||
|
}=>{
|
||||||
|
let s=match state{
|
||||||
|
winit::event::ElementState::Pressed=>true,
|
||||||
|
winit::event::ElementState::Released=>false,
|
||||||
|
};
|
||||||
|
match logical_key{
|
||||||
|
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Tab)=>{
|
||||||
|
if s{
|
||||||
|
self.manual_mouse_lock=false;
|
||||||
|
match self.window.set_cursor_position(self.get_middle_of_screen()){
|
||||||
|
Ok(())=>(),
|
||||||
|
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
||||||
|
}
|
||||||
|
match self.window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
||||||
|
Ok(())=>(),
|
||||||
|
Err(e)=>println!("Could not release cursor: {:?}",e),
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
//if cursor is outside window don't lock but apparently there's no get pos function
|
||||||
|
//let pos=window.get_cursor_pos();
|
||||||
|
match self.window.set_cursor_grab(winit::window::CursorGrabMode::Locked){
|
||||||
|
Ok(())=>(),
|
||||||
|
Err(_)=>{
|
||||||
|
match self.window.set_cursor_grab(winit::window::CursorGrabMode::Confined){
|
||||||
|
Ok(())=>(),
|
||||||
|
Err(e)=>{
|
||||||
|
self.manual_mouse_lock=true;
|
||||||
|
println!("Could not confine cursor: {:?}",e)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.window.set_cursor_visible(s);
|
||||||
|
},
|
||||||
|
winit::keyboard::Key::Named(winit::keyboard::NamedKey::F11)=>{
|
||||||
|
if s{
|
||||||
|
if self.window.fullscreen().is_some(){
|
||||||
|
self.window.set_fullscreen(None);
|
||||||
|
}else{
|
||||||
|
self.window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape)=>{
|
||||||
|
if s{
|
||||||
|
self.manual_mouse_lock=false;
|
||||||
|
match self.window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
||||||
|
Ok(())=>(),
|
||||||
|
Err(e)=>println!("Could not release cursor: {:?}",e),
|
||||||
|
}
|
||||||
|
self.window.set_cursor_visible(true);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
keycode=>{
|
||||||
|
if let Some(input_instruction)=match keycode{
|
||||||
|
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Space)=>Some(InputInstruction::Jump(s)),
|
||||||
|
winit::keyboard::Key::Character(key)=>match key.as_str(){
|
||||||
|
"w"=>Some(InputInstruction::MoveForward(s)),
|
||||||
|
"a"=>Some(InputInstruction::MoveLeft(s)),
|
||||||
|
"s"=>Some(InputInstruction::MoveBack(s)),
|
||||||
|
"d"=>Some(InputInstruction::MoveRight(s)),
|
||||||
|
"e"=>Some(InputInstruction::MoveUp(s)),
|
||||||
|
"q"=>Some(InputInstruction::MoveDown(s)),
|
||||||
|
"z"=>Some(InputInstruction::Zoom(s)),
|
||||||
|
"r"=>if s{Some(InputInstruction::Reset)}else{None},
|
||||||
|
_=>None,
|
||||||
|
},
|
||||||
|
_=>None,
|
||||||
|
}{
|
||||||
|
self.physics_thread.send(TimedInstruction{
|
||||||
|
time,
|
||||||
|
instruction:crate::physics_worker::Instruction::Input(input_instruction),
|
||||||
|
}).unwrap();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_=>(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn device_event(&mut self,time:crate::integer::Time,event: winit::event::DeviceEvent) {
|
||||||
|
match event {
|
||||||
|
winit::event::DeviceEvent::MouseMotion {
|
||||||
|
delta,//these (f64,f64) are integers on my machine
|
||||||
|
} => {
|
||||||
|
if self.manual_mouse_lock{
|
||||||
|
match self.window.set_cursor_position(self.get_middle_of_screen()){
|
||||||
|
Ok(())=>(),
|
||||||
|
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//do not step the physics because the mouse polling rate is higher than the physics can run.
|
||||||
|
//essentially the previous input will be overwritten until a true step runs
|
||||||
|
//which is fine because they run all the time.
|
||||||
|
let delta=glam::ivec2(delta.0 as i32,delta.1 as i32);
|
||||||
|
self.mouse.pos+=delta;
|
||||||
|
self.physics_thread.send(TimedInstruction{
|
||||||
|
time,
|
||||||
|
instruction:crate::physics_worker::Instruction::Input(InputInstruction::MoveMouse(self.mouse.pos)),
|
||||||
|
}).unwrap();
|
||||||
|
},
|
||||||
|
winit::event::DeviceEvent::MouseWheel {
|
||||||
|
delta,
|
||||||
|
} => {
|
||||||
|
println!("mousewheel {:?}",delta);
|
||||||
|
if false{//self.physics.style.use_scroll{
|
||||||
|
self.physics_thread.send(TimedInstruction{
|
||||||
|
time,
|
||||||
|
instruction:crate::physics_worker::Instruction::Input(InputInstruction::Jump(true)),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
|
||||||
|
}).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_=>(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct WindowContextSetup{
|
||||||
|
user_settings:crate::settings::UserSettings,
|
||||||
|
window:winit::window::Window,
|
||||||
|
physics:crate::physics::PhysicsState,
|
||||||
|
graphics:crate::graphics::GraphicsState,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowContextSetup{
|
||||||
|
pub fn new(context:&crate::setup::SetupContext,window:winit::window::Window)->Self{
|
||||||
|
//wee
|
||||||
|
let user_settings=crate::settings::read_user_settings();
|
||||||
|
|
||||||
|
let args:Vec<String>=std::env::args().collect();
|
||||||
|
let indexed_model_instances=if args.len()==2{
|
||||||
|
crate::load_file(std::path::PathBuf::from(&args[1]))
|
||||||
|
}else{
|
||||||
|
None
|
||||||
|
}.unwrap_or(crate::default_models());
|
||||||
|
|
||||||
|
let mut physics=crate::physics::PhysicsState::default();
|
||||||
|
physics.load_user_settings(&user_settings);
|
||||||
|
physics.generate_models(&indexed_model_instances);
|
||||||
|
physics.spawn(indexed_model_instances.spawn_point);
|
||||||
|
|
||||||
|
let mut graphics=crate::graphics::GraphicsState::new(&context.device,&context.queue,&context.config);
|
||||||
|
graphics.load_user_settings(&user_settings);
|
||||||
|
graphics.generate_models(&context.device,&context.queue,indexed_model_instances);
|
||||||
|
|
||||||
|
Self{
|
||||||
|
user_settings,
|
||||||
|
window,
|
||||||
|
graphics,
|
||||||
|
physics,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn into_context<'a>(self,setup_context:crate::setup::SetupContext)->WindowContext<'a>{
|
||||||
|
let screen_size=glam::uvec2(setup_context.config.width,setup_context.config.height);
|
||||||
|
let graphics_thread=crate::graphics_worker::new(self.graphics,setup_context.config,setup_context.surface,setup_context.device,setup_context.queue);
|
||||||
|
WindowContext{
|
||||||
|
manual_mouse_lock:false,
|
||||||
|
mouse:crate::physics::MouseState::default(),
|
||||||
|
//make sure to update this!!!!!
|
||||||
|
screen_size,
|
||||||
|
user_settings:self.user_settings,
|
||||||
|
window:self.window,
|
||||||
|
physics_thread:crate::physics_worker::new(self.physics,graphics_thread),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn into_worker<'a>(self,setup_context:crate::setup::SetupContext)->crate::compat_worker::QNWorker<'a,TimedInstruction<WindowInstruction>>{
|
||||||
|
let mut window_context=self.into_context(setup_context);
|
||||||
|
crate::compat_worker::QNWorker::new(move |ins:TimedInstruction<WindowInstruction>|{
|
||||||
|
match ins.instruction{
|
||||||
|
WindowInstruction::RequestRedraw=>{
|
||||||
|
window_context.window.request_redraw();
|
||||||
|
}
|
||||||
|
WindowInstruction::WindowEvent(window_event)=>{
|
||||||
|
window_context.window_event(ins.time,window_event);
|
||||||
|
},
|
||||||
|
WindowInstruction::DeviceEvent(device_event)=>{
|
||||||
|
window_context.device_event(ins.time,device_event);
|
||||||
|
},
|
||||||
|
WindowInstruction::Resize(size)=>{
|
||||||
|
window_context.physics_thread.send(
|
||||||
|
TimedInstruction{
|
||||||
|
time:ins.time,
|
||||||
|
instruction:crate::physics_worker::Instruction::Resize(size,window_context.user_settings.clone())
|
||||||
|
}
|
||||||
|
).unwrap();
|
||||||
|
}
|
||||||
|
WindowInstruction::Render=>{
|
||||||
|
window_context.physics_thread.send(
|
||||||
|
TimedInstruction{
|
||||||
|
time:ins.time,
|
||||||
|
instruction:crate::physics_worker::Instruction::Render
|
||||||
|
}
|
||||||
|
).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
143
src/worker.rs
143
src/worker.rs
@ -1,17 +1,69 @@
|
|||||||
use std::thread;
|
use std::thread;
|
||||||
use std::sync::{mpsc,Arc};
|
use std::sync::{mpsc,Arc};
|
||||||
use parking_lot::Mutex;
|
use parking_lot::{Mutex,Condvar};
|
||||||
|
|
||||||
|
//WorkerPool
|
||||||
|
struct Pool(u32);
|
||||||
|
enum PoolOrdering{
|
||||||
|
Single,//single thread cannot get out of order
|
||||||
|
Ordered(u32),//order matters and should be buffered/dropped according to ControlFlow
|
||||||
|
Unordered(u32),//order does not matter
|
||||||
|
}
|
||||||
|
//WorkerInput
|
||||||
|
enum Input{
|
||||||
|
//no input, workers have everything needed at creation
|
||||||
|
None,
|
||||||
|
//Immediate input to any available worker, dropped if they are overflowing (all workers are busy)
|
||||||
|
Immediate,
|
||||||
|
//Queued input is ordered, but serial jobs that mutate state (such as running physics) can only be done with a single worker
|
||||||
|
Queued,//"Fifo"
|
||||||
|
//Query a function to get next input when a thread becomes available
|
||||||
|
//worker stops querying when Query function returns None and dies after all threads complete
|
||||||
|
//lifetimes sound crazy on this one
|
||||||
|
Query,
|
||||||
|
//Queue of length one, the input is replaced if it is submitted twice before the current work finishes
|
||||||
|
Mailbox,
|
||||||
|
}
|
||||||
|
//WorkerOutput
|
||||||
|
enum Output{
|
||||||
|
None(Pool),
|
||||||
|
Realtime(PoolOrdering),//outputs are dropped if they are out of order and order is demanded
|
||||||
|
Buffered(PoolOrdering),//outputs are held back internally if they are out of order and order is demanded
|
||||||
|
}
|
||||||
|
|
||||||
|
//It would be possible to implement all variants
|
||||||
|
//with a query input function and callback output function but I'm not sure if that's worth it.
|
||||||
|
//Immediate = Condvar
|
||||||
|
//Queued = receiver.recv()
|
||||||
|
//a callback function would need to use an async runtime!
|
||||||
|
|
||||||
|
//realtime output is an arc mutex of the output value that is assigned every time a worker completes a job
|
||||||
|
//buffered output produces a receiver object that can be passed to the creation of another worker
|
||||||
|
//when ordering is requested, output is ordered by the order each thread is run
|
||||||
|
//which is the same as the order that the input data is processed except for Input::None which has no input data
|
||||||
|
//WorkerDescription
|
||||||
|
struct Description{
|
||||||
|
input:Input,
|
||||||
|
output:Output,
|
||||||
|
}
|
||||||
|
|
||||||
//The goal here is to have a worker thread that parks itself when it runs out of work.
|
//The goal here is to have a worker thread that parks itself when it runs out of work.
|
||||||
//The worker thread publishes the result of its work back to the worker object for every item in the work queue.
|
//The worker thread publishes the result of its work back to the worker object for every item in the work queue.
|
||||||
|
//Previous values do not matter as soon as a new value is produced, which is why it's called "Realtime"
|
||||||
//The physics (target use case) knows when it has not changed the body, so not updating the value is also an option.
|
//The physics (target use case) knows when it has not changed the body, so not updating the value is also an option.
|
||||||
|
|
||||||
pub struct Worker<Task:Send,Value:Clone> {
|
/*
|
||||||
|
QR = WorkerDescription{
|
||||||
|
input:Queued,
|
||||||
|
output:Realtime(Single),
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
pub struct QRWorker<Task:Send,Value:Clone>{
|
||||||
sender: mpsc::Sender<Task>,
|
sender: mpsc::Sender<Task>,
|
||||||
value:Arc<Mutex<Value>>,
|
value:Arc<Mutex<Value>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
|
impl<Task:Send+'static,Value:Clone+Send+'static> QRWorker<Task,Value>{
|
||||||
pub fn new<F:FnMut(Task)->Value+Send+'static>(value:Value,mut f:F) -> Self {
|
pub fn new<F:FnMut(Task)->Value+Send+'static>(value:Value,mut f:F) -> Self {
|
||||||
let (sender, receiver) = mpsc::channel::<Task>();
|
let (sender, receiver) = mpsc::channel::<Task>();
|
||||||
let ret=Self {
|
let ret=Self {
|
||||||
@ -45,28 +97,79 @@ impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct CompatWorker<Task,Value:Clone,F>{
|
/*
|
||||||
data:std::marker::PhantomData<Task>,
|
QN = WorkerDescription{
|
||||||
f:F,
|
input:Queued,
|
||||||
value:Value,
|
output:None(Single),
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
//None Output Worker does all its work internally from the perspective of the work submitter
|
||||||
|
pub struct QNWorker<'a,Task:Send>{
|
||||||
|
sender: mpsc::Sender<Task>,
|
||||||
|
handle:thread::ScopedJoinHandle<'a,()>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Task,Value:Clone,F:FnMut(Task)->Value> CompatWorker<Task,Value,F> {
|
impl<'a,Task:Send+'a> QNWorker<'a,Task>{
|
||||||
pub fn new(value:Value,f:F) -> Self {
|
pub fn new<F:FnMut(Task)+Send+'a>(scope:&'a thread::Scope<'a,'_>,mut f:F)->QNWorker<'a,Task>{
|
||||||
Self {
|
let (sender,receiver)=mpsc::channel::<Task>();
|
||||||
f,
|
let handle=scope.spawn(move ||{
|
||||||
value,
|
loop {
|
||||||
data:std::marker::PhantomData,
|
match receiver.recv() {
|
||||||
|
Ok(task)=>f(task),
|
||||||
|
Err(_)=>{
|
||||||
|
println!("Worker stopping.",);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Self{
|
||||||
|
sender,
|
||||||
|
handle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn send(&self,task:Task)->Result<(),mpsc::SendError<Task>>{
|
||||||
|
self.sender.send(task)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn send(&mut self,task:Task)->Result<(),()>{
|
/*
|
||||||
self.value=(self.f)(task);
|
IN = WorkerDescription{
|
||||||
Ok(())
|
input:Immediate,
|
||||||
}
|
output:None(Single),
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
//Inputs are dropped if the worker is busy
|
||||||
|
pub struct INWorker<'a,Task:Send>{
|
||||||
|
sender: mpsc::SyncSender<Task>,
|
||||||
|
handle:thread::ScopedJoinHandle<'a,()>,
|
||||||
|
}
|
||||||
|
|
||||||
pub fn grab_clone(&self)->Value{
|
impl<'a,Task:Send+'a> INWorker<'a,Task>{
|
||||||
self.value.clone()
|
pub fn new<F:FnMut(Task)+Send+'a>(scope:&'a thread::Scope<'a,'_>,mut f:F)->INWorker<'a,Task>{
|
||||||
|
let (sender,receiver)=mpsc::sync_channel::<Task>(1);
|
||||||
|
let handle=scope.spawn(move ||{
|
||||||
|
loop {
|
||||||
|
match receiver.recv() {
|
||||||
|
Ok(task)=>f(task),
|
||||||
|
Err(_)=>{
|
||||||
|
println!("Worker stopping.",);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Self{
|
||||||
|
sender,
|
||||||
|
handle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//blocking!
|
||||||
|
pub fn blocking_send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
|
||||||
|
self.sender.send(task)
|
||||||
|
}
|
||||||
|
pub fn send(&self,task:Task)->Result<(), mpsc::TrySendError<Task>>{
|
||||||
|
self.sender.try_send(task)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,7 +177,7 @@ impl<Task,Value:Clone,F:FnMut(Task)->Value> CompatWorker<Task,Value,F> {
|
|||||||
fn test_worker() {
|
fn test_worker() {
|
||||||
println!("hiiiii");
|
println!("hiiiii");
|
||||||
// Create the worker thread
|
// Create the worker thread
|
||||||
let worker = Worker::new(crate::physics::Body::with_pva(crate::integer::Planar64Vec3::ZERO,crate::integer::Planar64Vec3::ZERO,crate::integer::Planar64Vec3::ZERO),
|
let worker=QRWorker::new(crate::physics::Body::with_pva(crate::integer::Planar64Vec3::ZERO,crate::integer::Planar64Vec3::ZERO,crate::integer::Planar64Vec3::ZERO),
|
||||||
|_|crate::physics::Body::with_pva(crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE)
|
|_|crate::physics::Body::with_pva(crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user