Compare commits
58 Commits
graphics-t
...
integer-un
| Author | SHA1 | Date | |
|---|---|---|---|
| 22fa3ee81b | |||
| 3a8655c343 | |||
| 691c3e0482 | |||
| 1dfc566453 | |||
| 762f10fb01 | |||
| 8fba543684 | |||
| 8c90eb1d94 | |||
| b9e200e070 | |||
| e0e55c6883 | |||
| 0195511e49 | |||
| 7b09b3333b | |||
| cf202f52f0 | |||
| 35e8856e0f | |||
| 1271797a66 | |||
| 6bb9db739c | |||
| 9152237f2c | |||
| 282329fb33 | |||
| c88451c0f0 | |||
| 5f1d732b59 | |||
| d33b830338 | |||
| 80b1d25a13 | |||
| bf6f37fa00 | |||
| fa8ea26ddc | |||
| f5d6280e0a | |||
| 4e98e9a577 | |||
| 8fea9e0025 | |||
| ac2f1d3eac | |||
| bcab0d92fd | |||
| 36a5298b6d | |||
| cea85a099d | |||
| 9cc1674624 | |||
| 7d33f69a47 | |||
| 9cb42009cb | |||
| bcd421c4dd | |||
| 4d62042549 | |||
| fcf4d05baa | |||
| 2f33a28c95 | |||
| d939fbff94 | |||
| 9ca2f0a194 | |||
| 4bbd11dbb6 | |||
| 10a293e789 | |||
| 01b5769dc0 | |||
| 7f7b0d92e6 | |||
| 3b7a1d5dff | |||
| 7309949dd0 | |||
| 43a0eef5d1 | |||
| 76cd82967a | |||
| 69712847e3 | |||
| a8f82a14a9 | |||
| 101c92cba4 | |||
| 54ec21c490 | |||
| f16bc043c4 | |||
| 4616fd7b3b | |||
| b6b63b4c85 | |||
| c21c587edc | |||
| 9a12265881 | |||
| 3ff73ed0bc | |||
| 57386334af |
811
Cargo.lock
generated
811
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -6,11 +6,14 @@ 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"
|
||||||
@@ -19,7 +22,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 = { version = "0.29.2", features = ["rwh_05"] }
|
winit = "0.28.6"
|
||||||
|
|
||||||
#[profile.release]
|
#[profile.release]
|
||||||
#lto = true
|
#lto = true
|
||||||
|
|||||||
@@ -12,12 +12,12 @@ use crate::aabb::Aabb;
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct BvhNode{
|
pub struct BvhNode{
|
||||||
children:Vec<Self>,
|
children:Vec<Self>,
|
||||||
models:Vec<usize>,
|
models:Vec<u32>,
|
||||||
aabb:Aabb,
|
aabb:Aabb,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BvhNode{
|
impl BvhNode{
|
||||||
pub fn the_tester<F:FnMut(usize)>(&self,aabb:&Aabb,f:&mut F){
|
pub fn the_tester<F:FnMut(u32)>(&self,aabb:&Aabb,f:&mut F){
|
||||||
for &model in &self.models{
|
for &model in &self.models{
|
||||||
f(model);
|
f(model);
|
||||||
}
|
}
|
||||||
@@ -37,7 +37,7 @@ fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
|
|||||||
let n=boxen.len();
|
let n=boxen.len();
|
||||||
if n<20{
|
if n<20{
|
||||||
let mut aabb=Aabb::default();
|
let mut aabb=Aabb::default();
|
||||||
let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0}).collect();
|
let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0 as u32}).collect();
|
||||||
BvhNode{
|
BvhNode{
|
||||||
children:Vec::new(),
|
children:Vec::new(),
|
||||||
models,
|
models,
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
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
Normal file
516
src/framework.rs
Normal file
@@ -0,0 +1,516 @@
|
|||||||
|
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
993
src/graphics.rs
@@ -1,993 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
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,11 +41,6 @@ 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]
|
||||||
@@ -426,17 +421,14 @@ impl Planar64{
|
|||||||
pub const fn get(&self)->i64{
|
pub const fn get(&self)->i64{
|
||||||
self.0
|
self.0
|
||||||
}
|
}
|
||||||
pub fn sqrt(&self)->Self{
|
|
||||||
Planar64(unsafe{(((self.0 as i128)<<32) as f64).sqrt().to_int_unchecked()})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
const PLANAR64_ONE_FLOAT32:f32=(1u64<<32) as f32;
|
const PLANAR64_FLOAT32_ONE:f32=(1u64<<32) as f32;
|
||||||
const PLANAR64_CONVERT_TO_FLOAT32:f32=1.0/PLANAR64_ONE_FLOAT32;
|
const PLANAR64_FLOAT32_MUL:f32=1.0/PLANAR64_FLOAT32_ONE;
|
||||||
const PLANAR64_ONE_FLOAT64:f64=(1u64<<32) as f64;
|
const PLANAR64_FLOAT64_ONE:f64=(1u64<<32) as f64;
|
||||||
impl Into<f32> for Planar64{
|
impl Into<f32> for Planar64{
|
||||||
#[inline]
|
#[inline]
|
||||||
fn into(self)->f32{
|
fn into(self)->f32{
|
||||||
self.0 as f32*PLANAR64_CONVERT_TO_FLOAT32
|
self.0 as f32*PLANAR64_FLOAT32_MUL
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl From<Ratio64> for Planar64{
|
impl From<Ratio64> for Planar64{
|
||||||
@@ -536,14 +528,7 @@ impl std::ops::Mul<Planar64> for Planar64{
|
|||||||
type Output=Planar64;
|
type Output=Planar64;
|
||||||
#[inline]
|
#[inline]
|
||||||
fn mul(self, rhs: Self) -> Self::Output {
|
fn mul(self, rhs: Self) -> Self::Output {
|
||||||
Planar64(((self.0 as i128*rhs.0 as i128)>>32) as i64)
|
Planar64((((self.0 as i128)*(rhs.0 as i128))>>32) as i64)
|
||||||
}
|
|
||||||
}
|
|
||||||
impl std::ops::Mul<Time> for Planar64{
|
|
||||||
type Output=Planar64;
|
|
||||||
#[inline]
|
|
||||||
fn mul(self,rhs:Time)->Self::Output{
|
|
||||||
Planar64(((self.0 as i128*rhs.0 as i128)/1_000_000_000) as i64)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl std::ops::Div<i64> for Planar64{
|
impl std::ops::Div<i64> for Planar64{
|
||||||
@@ -586,10 +571,6 @@ impl Planar64Vec3{
|
|||||||
Self(glam::i64vec3((x as i64)<<32,(y as i64)<<32,(z as i64)<<32))
|
Self(glam::i64vec3((x as i64)<<32,(y as i64)<<32,(z as i64)<<32))
|
||||||
}
|
}
|
||||||
#[inline]
|
#[inline]
|
||||||
pub const fn raw(x:i64,y:i64,z:i64)->Self{
|
|
||||||
Self(glam::i64vec3(x,y,z))
|
|
||||||
}
|
|
||||||
#[inline]
|
|
||||||
pub fn x(&self)->Planar64{
|
pub fn x(&self)->Planar64{
|
||||||
Planar64(self.0.x)
|
Planar64(self.0.x)
|
||||||
}
|
}
|
||||||
@@ -659,7 +640,7 @@ impl Into<glam::Vec3> for Planar64Vec3{
|
|||||||
self.0.x as f32,
|
self.0.x as f32,
|
||||||
self.0.y as f32,
|
self.0.y as f32,
|
||||||
self.0.z as f32,
|
self.0.z as f32,
|
||||||
)*PLANAR64_CONVERT_TO_FLOAT32
|
)*PLANAR64_FLOAT32_MUL
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl TryFrom<[f32;3]> for Planar64Vec3{
|
impl TryFrom<[f32;3]> for Planar64Vec3{
|
||||||
@@ -824,27 +805,10 @@ impl Planar64Mat3{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn from_rotation_yx(yaw:Angle32,pitch:Angle32)->Self{
|
|
||||||
let xtheta=yaw.0 as f64*ANGLE32_TO_FLOAT64_RADIANS;
|
|
||||||
let (xs,xc)=xtheta.sin_cos();
|
|
||||||
let (xc,xs)=(xc*PLANAR64_ONE_FLOAT64,xs*PLANAR64_ONE_FLOAT64);
|
|
||||||
let ytheta=pitch.0 as f64*ANGLE32_TO_FLOAT64_RADIANS;
|
|
||||||
let (ys,yc)=ytheta.sin_cos();
|
|
||||||
let (yc,ys)=(yc*PLANAR64_ONE_FLOAT64,ys*PLANAR64_ONE_FLOAT64);
|
|
||||||
//TODO: fix this rounding towards 0
|
|
||||||
let (xc,xs):(i64,i64)=(unsafe{xc.to_int_unchecked()},unsafe{xs.to_int_unchecked()});
|
|
||||||
let (yc,ys):(i64,i64)=(unsafe{yc.to_int_unchecked()},unsafe{ys.to_int_unchecked()});
|
|
||||||
Self::from_cols(
|
|
||||||
Planar64Vec3(glam::i64vec3(xc,0,-xs)),
|
|
||||||
Planar64Vec3(glam::i64vec3(((xs as i128*ys as i128)>>32) as i64,yc,((xc as i128*ys as i128)>>32) as i64)),
|
|
||||||
Planar64Vec3(glam::i64vec3(((xs as i128*yc as i128)>>32) as i64,-ys,((xc as i128*yc as i128)>>32) as i64)),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
#[inline]
|
|
||||||
pub fn from_rotation_y(angle:Angle32)->Self{
|
pub fn from_rotation_y(angle:Angle32)->Self{
|
||||||
let theta=angle.0 as f64*ANGLE32_TO_FLOAT64_RADIANS;
|
let theta=angle.0 as f64*ANGLE32_TO_FLOAT64_RADIANS;
|
||||||
let (s,c)=theta.sin_cos();
|
let (s,c)=theta.sin_cos();
|
||||||
let (c,s)=(c*PLANAR64_ONE_FLOAT64,s*PLANAR64_ONE_FLOAT64);
|
let (c,s)=(c*PLANAR64_FLOAT64_ONE,s*PLANAR64_FLOAT64_ONE);
|
||||||
//TODO: fix this rounding towards 0
|
//TODO: fix this rounding towards 0
|
||||||
let (c,s):(i64,i64)=(unsafe{c.to_int_unchecked()},unsafe{s.to_int_unchecked()});
|
let (c,s):(i64,i64)=(unsafe{c.to_int_unchecked()},unsafe{s.to_int_unchecked()});
|
||||||
Self::from_cols(
|
Self::from_cols(
|
||||||
@@ -925,8 +889,8 @@ impl Into<glam::Mat4> for Planar64Affine3{
|
|||||||
self.matrix3.x_axis.0.x as f32,self.matrix3.x_axis.0.y as f32,self.matrix3.x_axis.0.z as f32,0.0,
|
self.matrix3.x_axis.0.x as f32,self.matrix3.x_axis.0.y as f32,self.matrix3.x_axis.0.z as f32,0.0,
|
||||||
self.matrix3.y_axis.0.x as f32,self.matrix3.y_axis.0.y as f32,self.matrix3.y_axis.0.z as f32,0.0,
|
self.matrix3.y_axis.0.x as f32,self.matrix3.y_axis.0.y as f32,self.matrix3.y_axis.0.z as f32,0.0,
|
||||||
self.matrix3.z_axis.0.x as f32,self.matrix3.z_axis.0.y as f32,self.matrix3.z_axis.0.z as f32,0.0,
|
self.matrix3.z_axis.0.x as f32,self.matrix3.z_axis.0.y as f32,self.matrix3.z_axis.0.z as f32,0.0,
|
||||||
self.translation.0.x as f32,self.translation.0.y as f32,self.translation.0.z as f32,PLANAR64_ONE_FLOAT32
|
self.translation.0.x as f32,self.translation.0.y as f32,self.translation.0.z as f32,PLANAR64_FLOAT32_ONE
|
||||||
])*PLANAR64_CONVERT_TO_FLOAT32
|
])*PLANAR64_FLOAT32_MUL
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl TryFrom<glam::Affine3A> for Planar64Affine3{
|
impl TryFrom<glam::Affine3A> for Planar64Affine3{
|
||||||
@@ -947,12 +911,4 @@ impl std::fmt::Display for Planar64Affine3{
|
|||||||
Into::<f32>::into(self.matrix3.z_axis.x()),Into::<f32>::into(self.matrix3.z_axis.y()),Into::<f32>::into(self.matrix3.z_axis.z()),
|
Into::<f32>::into(self.matrix3.z_axis.x()),Into::<f32>::into(self.matrix3.z_axis.y()),Into::<f32>::into(self.matrix3.z_axis.z()),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_sqrt(){
|
|
||||||
let r=Planar64::int(400);
|
|
||||||
println!("r{}",r.get());
|
|
||||||
let s=r.sqrt();
|
|
||||||
println!("s{}",s.get());
|
|
||||||
}
|
}
|
||||||
@@ -50,29 +50,20 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
|
|||||||
let mut contacting=crate::model::ContactingAttributes::default();
|
let mut contacting=crate::model::ContactingAttributes::default();
|
||||||
let mut force_can_collide=can_collide;
|
let mut force_can_collide=can_collide;
|
||||||
match name{
|
match name{
|
||||||
"Water"=>{
|
//"Water"=>intersecting.water=Some(crate::model::IntersectingWater{density:1.0,drag:1.0}),
|
||||||
force_can_collide=false;
|
"Accelerator"=>{force_can_collide=false;intersecting.accelerator=Some(crate::model::IntersectingAccelerator{acceleration:velocity})},
|
||||||
//TODO: read stupid CustomPhysicalProperties
|
|
||||||
intersecting.water=Some(crate::model::IntersectingWater{density:Planar64::ONE,viscosity:Planar64::ONE/10,current:velocity});
|
|
||||||
},
|
|
||||||
"Accelerator"=>{
|
|
||||||
//although the new game supports collidable accelerators, this is a roblox compatability map loader
|
|
||||||
force_can_collide=false;
|
|
||||||
general.accelerator=Some(crate::model::GameMechanicAccelerator{acceleration:velocity});
|
|
||||||
},
|
|
||||||
"SetVelocity"=>general.trajectory=Some(crate::model::GameMechanicSetTrajectory::Velocity(velocity)),
|
|
||||||
"MapFinish"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Finish})},
|
"MapFinish"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Finish})},
|
||||||
"MapAnticheat"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Anitcheat})},
|
"MapAnticheat"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Anitcheat})},
|
||||||
"Platform"=>general.teleport_behaviour=Some(crate::model::TeleportBehaviour::StageElement(crate::model::GameMechanicStageElement{
|
"Platform"=>general.stage_element=Some(crate::model::GameMechanicStageElement{
|
||||||
mode_id:0,
|
mode_id:0,
|
||||||
stage_id:0,
|
stage_id:0,
|
||||||
force:false,
|
force:false,
|
||||||
behaviour:crate::model::StageElementBehaviour::Platform,
|
behaviour:crate::model::StageElementBehaviour::Platform,
|
||||||
})),
|
}),
|
||||||
other=>{
|
other=>{
|
||||||
if let Some(captures)=lazy_regex::regex!(r"^(Force)?(Spawn|SpawnAt|Trigger|Teleport|Platform)(\d+)$")
|
if let Some(captures)=lazy_regex::regex!(r"^(Force)?(Spawn|SpawnAt|Trigger|Teleport|Platform)(\d+)$")
|
||||||
.captures(other){
|
.captures(other){
|
||||||
general.teleport_behaviour=Some(crate::model::TeleportBehaviour::StageElement(crate::model::GameMechanicStageElement{
|
general.stage_element=Some(crate::model::GameMechanicStageElement{
|
||||||
mode_id:0,
|
mode_id:0,
|
||||||
stage_id:captures[3].parse::<u32>().unwrap(),
|
stage_id:captures[3].parse::<u32>().unwrap(),
|
||||||
force:match captures.get(1){
|
force:match captures.get(1){
|
||||||
@@ -81,28 +72,12 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
|
|||||||
},
|
},
|
||||||
behaviour:match &captures[2]{
|
behaviour:match &captures[2]{
|
||||||
"Spawn"|"SpawnAt"=>crate::model::StageElementBehaviour::SpawnAt,
|
"Spawn"|"SpawnAt"=>crate::model::StageElementBehaviour::SpawnAt,
|
||||||
//cancollide false so you don't hit the side
|
|
||||||
//NOT a decoration
|
|
||||||
"Trigger"=>{force_can_collide=false;crate::model::StageElementBehaviour::Trigger},
|
"Trigger"=>{force_can_collide=false;crate::model::StageElementBehaviour::Trigger},
|
||||||
"Teleport"=>{force_can_collide=false;crate::model::StageElementBehaviour::Teleport},
|
"Teleport"=>{force_can_collide=false;crate::model::StageElementBehaviour::Teleport},
|
||||||
"Platform"=>crate::model::StageElementBehaviour::Platform,
|
"Platform"=>crate::model::StageElementBehaviour::Platform,
|
||||||
_=>panic!("regex1[2] messed up bad"),
|
_=>panic!("regex1[2] messed up bad"),
|
||||||
}
|
}
|
||||||
}));
|
})
|
||||||
}else if let Some(captures)=lazy_regex::regex!(r"^(Force)?(Jump)(\d+)$")
|
|
||||||
.captures(other){
|
|
||||||
general.teleport_behaviour=Some(crate::model::TeleportBehaviour::StageElement(crate::model::GameMechanicStageElement{
|
|
||||||
mode_id:0,
|
|
||||||
stage_id:0,
|
|
||||||
force:match captures.get(1){
|
|
||||||
Some(m)=>m.as_str()=="Force",
|
|
||||||
None=>false,
|
|
||||||
},
|
|
||||||
behaviour:match &captures[2]{
|
|
||||||
"Jump"=>crate::model::StageElementBehaviour::JumpLimit(captures[3].parse::<u32>().unwrap()),
|
|
||||||
_=>panic!("regex4[1] messed up bad"),
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
}else if let Some(captures)=lazy_regex::regex!(r"^Bonus(Finish|Anticheat)(\d+)$")
|
}else if let Some(captures)=lazy_regex::regex!(r"^Bonus(Finish|Anticheat)(\d+)$")
|
||||||
.captures(other){
|
.captures(other){
|
||||||
force_can_collide=false;
|
force_can_collide=false;
|
||||||
@@ -111,33 +86,35 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
|
|||||||
"Anticheat"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:captures[2].parse::<u32>().unwrap(),behaviour:crate::model::ZoneBehaviour::Anitcheat}),
|
"Anticheat"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:captures[2].parse::<u32>().unwrap(),behaviour:crate::model::ZoneBehaviour::Anitcheat}),
|
||||||
_=>panic!("regex2[1] messed up bad"),
|
_=>panic!("regex2[1] messed up bad"),
|
||||||
}
|
}
|
||||||
}else if let Some(captures)=lazy_regex::regex!(r"^(WormholeIn)(\d+)$")
|
|
||||||
.captures(other){
|
|
||||||
force_can_collide=false;
|
|
||||||
match &captures[1]{
|
|
||||||
"WormholeIn"=>general.teleport_behaviour=Some(crate::model::TeleportBehaviour::Wormhole(crate::model::GameMechanicWormhole{destination_model_id:captures[2].parse::<u32>().unwrap()})),
|
|
||||||
_=>panic!("regex3[1] messed up bad"),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//need some way to skip this
|
//need some way to skip this
|
||||||
if velocity!=Planar64Vec3::ZERO{
|
if velocity!=Planar64Vec3::ZERO{
|
||||||
general.booster=Some(crate::model::GameMechanicBooster::Velocity(velocity));
|
general.booster=Some(crate::model::GameMechanicBooster{velocity});
|
||||||
}
|
}
|
||||||
match force_can_collide{
|
match force_can_collide{
|
||||||
true=>{
|
true=>{
|
||||||
match name{
|
match name{
|
||||||
"Bounce"=>contacting.contact_behaviour=Some(crate::model::ContactingBehaviour::Elastic(u32::MAX)),
|
//"Bounce"=>(),
|
||||||
"Surf"=>contacting.contact_behaviour=Some(crate::model::ContactingBehaviour::Surf),
|
"Surf"=>contacting.surf=Some(crate::model::ContactingSurf{}),
|
||||||
"Ladder"=>contacting.contact_behaviour=Some(crate::model::ContactingBehaviour::Ladder(crate::model::ContactingLadder{sticky:true})),
|
"Ladder"=>contacting.ladder=Some(crate::model::ContactingLadder{sticky:true}),
|
||||||
_=>(),
|
other=>{
|
||||||
|
//REGEX!!!!
|
||||||
|
//Jump#
|
||||||
|
//WormholeIn#
|
||||||
|
}
|
||||||
}
|
}
|
||||||
crate::model::CollisionAttributes::Contact{contacting,general}
|
crate::model::CollisionAttributes::Contact{contacting,general}
|
||||||
},
|
},
|
||||||
false=>if force_intersecting
|
false=>if force_intersecting
|
||||||
||general.any()
|
||general.jump_limit.is_some()
|
||||||
||intersecting.any()
|
||general.booster.is_some()
|
||||||
|
||general.zone.is_some()
|
||||||
|
||general.stage_element.is_some()
|
||||||
|
||general.wormhole.is_some()
|
||||||
|
||intersecting.water.is_some()
|
||||||
|
||intersecting.accelerator.is_some()
|
||||||
{
|
{
|
||||||
crate::model::CollisionAttributes::Intersect{intersecting,general}
|
crate::model::CollisionAttributes::Intersect{intersecting,general}
|
||||||
}else{
|
}else{
|
||||||
@@ -263,17 +240,16 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
if let Some(attr)=match &object.name[..]{
|
if let Some(attr)=match &object.name[..]{
|
||||||
"MapStart"=>{
|
"MapStart"=>{
|
||||||
spawn_point=model_transform.transform_point3(Planar64Vec3::ZERO)+Planar64Vec3::Y*5/2;
|
spawn_point=model_transform.transform_point3(Planar64Vec3::ZERO)+Planar64Vec3::Y*5/2;
|
||||||
Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:0}))
|
Some(crate::model::TempIndexedAttributes::Start{mode_id:0})
|
||||||
},
|
},
|
||||||
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint(crate::model::TempAttrUnorderedCheckpoint{mode_id:0})),
|
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id:0}),
|
||||||
other=>{
|
other=>{
|
||||||
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint|WormholeOut)(\d+)$");
|
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint)(\d+)$");
|
||||||
if let Some(captures) = regman.captures(other) {
|
if let Some(captures) = regman.captures(other) {
|
||||||
match &captures[1]{
|
match &captures[1]{
|
||||||
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:captures[2].parse::<u32>().unwrap()})),
|
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start{mode_id:captures[2].parse::<u32>().unwrap()}),
|
||||||
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn(crate::model::TempAttrSpawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()})),
|
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()}),
|
||||||
"OrderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::OrderedCheckpoint(crate::model::TempAttrOrderedCheckpoint{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()})),
|
"OrderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::OrderedCheckpoint{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()}),
|
||||||
"WormholeOut"=>Some(crate::model::TempIndexedAttributes::Wormhole(crate::model::TempAttrWormhole{wormhole_id:captures[2].parse::<u32>().unwrap()})),
|
|
||||||
_=>None,
|
_=>None,
|
||||||
}
|
}
|
||||||
}else{
|
}else{
|
||||||
|
|||||||
1249
src/main.rs
1249
src/main.rs
File diff suppressed because it is too large
Load Diff
162
src/model.rs
162
src/model.rs
@@ -1,4 +1,4 @@
|
|||||||
use crate::integer::{Time,Planar64,Planar64Vec3,Planar64Affine3};
|
use crate::integer::{Planar64,Planar64Vec3,Planar64Affine3};
|
||||||
pub type TextureCoordinate=glam::Vec2;
|
pub type TextureCoordinate=glam::Vec2;
|
||||||
pub type Color4=glam::Vec4;
|
pub type Color4=glam::Vec4;
|
||||||
#[derive(Clone,Hash,PartialEq,Eq)]
|
#[derive(Clone,Hash,PartialEq,Eq)]
|
||||||
@@ -50,63 +50,53 @@ pub struct IndexedModelInstances{
|
|||||||
}
|
}
|
||||||
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
|
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
|
||||||
pub struct ModeDescription{
|
pub struct ModeDescription{
|
||||||
pub start:usize,//start=model_id
|
pub start:u32,//start=model_id
|
||||||
pub spawns:Vec<usize>,//spawns[spawn_id]=model_id
|
pub spawns:Vec<u32>,//spawns[spawn_id]=model_id
|
||||||
pub ordered_checkpoints:Vec<usize>,//ordered_checkpoints[checkpoint_id]=model_id
|
pub ordered_checkpoints:Vec<u32>,//ordered_checkpoints[checkpoint_id]=model_id
|
||||||
pub unordered_checkpoints:Vec<usize>,//unordered_checkpoints[checkpoint_id]=model_id
|
pub unordered_checkpoints:Vec<u32>,//unordered_checkpoints[checkpoint_id]=model_id
|
||||||
pub spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
|
pub spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
|
||||||
pub ordered_checkpoint_from_checkpoint_id:std::collections::HashMap::<u32,usize>,
|
pub ordered_checkpoint_from_checkpoint_id:std::collections::HashMap::<u32,usize>,
|
||||||
}
|
}
|
||||||
impl ModeDescription{
|
impl ModeDescription{
|
||||||
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&usize>{
|
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&u32>{
|
||||||
self.spawns.get(*self.spawn_from_stage_id.get(&stage_id)?)
|
if let Some(&spawn)=self.spawn_from_stage_id.get(&stage_id){
|
||||||
|
self.spawns.get(spawn)
|
||||||
|
}else{
|
||||||
|
None
|
||||||
|
}
|
||||||
}
|
}
|
||||||
pub fn get_ordered_checkpoint_model_id(&self,checkpoint_id:u32)->Option<&usize>{
|
pub fn get_ordered_checkpoint_model_id(&self,checkpoint_id:u32)->Option<&u32>{
|
||||||
self.ordered_checkpoints.get(*self.ordered_checkpoint_from_checkpoint_id.get(&checkpoint_id)?)
|
if let Some(&checkpoint)=self.ordered_checkpoint_from_checkpoint_id.get(&checkpoint_id){
|
||||||
|
self.ordered_checkpoints.get(checkpoint)
|
||||||
|
}else{
|
||||||
|
None
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//I don't want this code to exist!
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct TempAttrStart{
|
|
||||||
pub mode_id:u32,
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct TempAttrSpawn{
|
|
||||||
pub mode_id:u32,
|
|
||||||
pub stage_id:u32,
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct TempAttrOrderedCheckpoint{
|
|
||||||
pub mode_id:u32,
|
|
||||||
pub checkpoint_id:u32,
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct TempAttrUnorderedCheckpoint{
|
|
||||||
pub mode_id:u32,
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct TempAttrWormhole{
|
|
||||||
pub wormhole_id:u32,
|
|
||||||
}
|
|
||||||
pub enum TempIndexedAttributes{
|
pub enum TempIndexedAttributes{
|
||||||
Start(TempAttrStart),
|
Start{
|
||||||
Spawn(TempAttrSpawn),
|
mode_id:u32,
|
||||||
OrderedCheckpoint(TempAttrOrderedCheckpoint),
|
},
|
||||||
UnorderedCheckpoint(TempAttrUnorderedCheckpoint),
|
Spawn{
|
||||||
Wormhole(TempAttrWormhole),
|
mode_id:u32,
|
||||||
|
stage_id:u32,
|
||||||
|
},
|
||||||
|
OrderedCheckpoint{
|
||||||
|
mode_id:u32,
|
||||||
|
checkpoint_id:u32,
|
||||||
|
},
|
||||||
|
UnorderedCheckpoint{
|
||||||
|
mode_id:u32,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
//you have this effect while in contact
|
//you have this effect while in contact
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
|
pub struct ContactingSurf{}
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct ContactingLadder{
|
pub struct ContactingLadder{
|
||||||
pub sticky:bool
|
pub sticky:bool
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
|
||||||
pub enum ContactingBehaviour{
|
|
||||||
Surf,
|
|
||||||
Ladder(ContactingLadder),
|
|
||||||
Elastic(u32),//[1/2^32,1] 0=None (elasticity+1)/2^32
|
|
||||||
}
|
|
||||||
//you have this effect while intersecting
|
//you have this effect while intersecting
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct IntersectingWater{
|
pub struct IntersectingWater{
|
||||||
@@ -114,37 +104,18 @@ pub struct IntersectingWater{
|
|||||||
pub density:Planar64,
|
pub density:Planar64,
|
||||||
pub current:Planar64Vec3,
|
pub current:Planar64Vec3,
|
||||||
}
|
}
|
||||||
//All models can be given these attributes
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct GameMechanicAccelerator{
|
pub struct IntersectingAccelerator{
|
||||||
pub acceleration:Planar64Vec3
|
pub acceleration:Planar64Vec3
|
||||||
}
|
}
|
||||||
|
//All models can be given these attributes
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub enum GameMechanicBooster{
|
pub struct GameMechanicJumpLimit{
|
||||||
Affine(Planar64Affine3),//capable of SetVelocity,DotVelocity,normal booster,bouncy part,redirect velocity, and much more
|
pub count:u32,
|
||||||
Velocity(Planar64Vec3),//straight up boost velocity adds to your current velocity
|
|
||||||
Energy{direction:Planar64Vec3,energy:Planar64},//increase energy in direction
|
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub enum TrajectoryChoice{
|
pub struct GameMechanicBooster{
|
||||||
HighArcLongDuration,//underhand lob at target: less horizontal speed and more air time
|
pub velocity:Planar64Vec3,
|
||||||
LowArcShortDuration,//overhand throw at target: more horizontal speed and less air time
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub enum GameMechanicSetTrajectory{
|
|
||||||
AirTime(Time),//air time (relative to gravity direction) is invariant across mass and gravity changes
|
|
||||||
Height(Planar64),//boost height (relative to gravity direction) is invariant across mass and gravity changes
|
|
||||||
TargetPointTime{//launch on a trajectory that will land at a target point in a set amount of time
|
|
||||||
target_point:Planar64Vec3,
|
|
||||||
time:Time,//short time = fast and direct, long time = launch high in the air, negative time = wrong way
|
|
||||||
},
|
|
||||||
TrajectoryTargetPoint{//launch at a fixed speed and land at a target point
|
|
||||||
target_point:Planar64Vec3,
|
|
||||||
speed:Planar64,//if speed is too low this will fail to reach the target. The closest-passing trajectory will be chosen instead
|
|
||||||
trajectory_choice:TrajectoryChoice,
|
|
||||||
},
|
|
||||||
Velocity(Planar64Vec3),//SetVelocity
|
|
||||||
DotVelocity{direction:Planar64Vec3,dot:Planar64},//set your velocity in a specific direction without touching other directions
|
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub enum ZoneBehaviour{
|
pub enum ZoneBehaviour{
|
||||||
@@ -159,10 +130,10 @@ pub struct GameMechanicZone{
|
|||||||
pub behaviour:ZoneBehaviour,
|
pub behaviour:ZoneBehaviour,
|
||||||
}
|
}
|
||||||
// enum TrapCondition{
|
// enum TrapCondition{
|
||||||
// FasterThan(Planar64),
|
// FasterThan(i64),
|
||||||
// SlowerThan(Planar64),
|
// SlowerThan(i64),
|
||||||
// InRange(Planar64,Planar64),
|
// InRange(i64,i64),
|
||||||
// OutsideRange(Planar64,Planar64),
|
// OutsideRange(i64,i64),
|
||||||
// }
|
// }
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub enum StageElementBehaviour{
|
pub enum StageElementBehaviour{
|
||||||
@@ -171,7 +142,6 @@ pub enum StageElementBehaviour{
|
|||||||
Trigger,
|
Trigger,
|
||||||
Teleport,
|
Teleport,
|
||||||
Platform,
|
Platform,
|
||||||
JumpLimit(u32),
|
|
||||||
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
|
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -182,54 +152,28 @@ pub struct GameMechanicStageElement{
|
|||||||
pub behaviour:StageElementBehaviour
|
pub behaviour:StageElementBehaviour
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct GameMechanicWormhole{
|
pub struct GameMechanicWormhole{//(position,angles)*=origin.transform.inverse()*destination.transform
|
||||||
//destination does not need to be another wormhole
|
pub model_id:u32,
|
||||||
//this defines a one way portal to a destination model transform
|
|
||||||
//two of these can create a two way wormhole
|
|
||||||
pub destination_model_id:u32,
|
|
||||||
//(position,angles)*=origin.transform.inverse()*destination.transform
|
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
|
||||||
pub enum TeleportBehaviour{
|
|
||||||
StageElement(GameMechanicStageElement),
|
|
||||||
Wormhole(GameMechanicWormhole),
|
|
||||||
}
|
|
||||||
//attributes listed in order of handling
|
|
||||||
#[derive(Default,Clone)]
|
#[derive(Default,Clone)]
|
||||||
pub struct GameMechanicAttributes{
|
pub struct GameMechanicAttributes{
|
||||||
pub zone:Option<GameMechanicZone>,
|
pub jump_limit:Option<GameMechanicJumpLimit>,
|
||||||
pub booster:Option<GameMechanicBooster>,
|
pub booster:Option<GameMechanicBooster>,
|
||||||
pub trajectory:Option<GameMechanicSetTrajectory>,
|
pub zone:Option<GameMechanicZone>,
|
||||||
pub teleport_behaviour:Option<TeleportBehaviour>,
|
pub stage_element:Option<GameMechanicStageElement>,
|
||||||
pub accelerator:Option<GameMechanicAccelerator>,
|
pub wormhole:Option<GameMechanicWormhole>,//stage_element and wormhole are in conflict
|
||||||
}
|
|
||||||
impl GameMechanicAttributes{
|
|
||||||
pub fn any(&self)->bool{
|
|
||||||
self.booster.is_some()
|
|
||||||
||self.trajectory.is_some()
|
|
||||||
||self.zone.is_some()
|
|
||||||
||self.teleport_behaviour.is_some()
|
|
||||||
||self.accelerator.is_some()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
#[derive(Default,Clone)]
|
#[derive(Default,Clone)]
|
||||||
pub struct ContactingAttributes{
|
pub struct ContactingAttributes{
|
||||||
|
pub elasticity:Option<u32>,//[1/2^32,1] 0=None (elasticity+1)/2^32
|
||||||
//friction?
|
//friction?
|
||||||
pub contact_behaviour:Option<ContactingBehaviour>,
|
pub surf:Option<ContactingSurf>,
|
||||||
}
|
pub ladder:Option<ContactingLadder>,
|
||||||
impl ContactingAttributes{
|
|
||||||
pub fn any(&self)->bool{
|
|
||||||
self.contact_behaviour.is_some()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
#[derive(Default,Clone)]
|
#[derive(Default,Clone)]
|
||||||
pub struct IntersectingAttributes{
|
pub struct IntersectingAttributes{
|
||||||
pub water:Option<IntersectingWater>,
|
pub water:Option<IntersectingWater>,
|
||||||
}
|
pub accelerator:Option<IntersectingAccelerator>,
|
||||||
impl IntersectingAttributes{
|
|
||||||
pub fn any(&self)->bool{
|
|
||||||
self.water.is_some()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
//Spawn(u32) NO! spawns are indexed in the map header instead of marked with attibutes
|
//Spawn(u32) NO! spawns are indexed in the map header instead of marked with attibutes
|
||||||
pub enum CollisionAttributes{
|
pub enum CollisionAttributes{
|
||||||
|
|||||||
@@ -27,29 +27,9 @@ pub struct ModelGraphicsSingleTexture{
|
|||||||
pub entities: Vec<Vec<u16>>,
|
pub entities: Vec<Vec<u16>>,
|
||||||
pub texture: Option<u32>,
|
pub texture: Option<u32>,
|
||||||
}
|
}
|
||||||
#[derive(Clone,PartialEq)]
|
|
||||||
pub struct ModelGraphicsColor4(glam::Vec4);
|
|
||||||
impl ModelGraphicsColor4{
|
|
||||||
pub const fn get(&self)->glam::Vec4{
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl From<glam::Vec4> for ModelGraphicsColor4{
|
|
||||||
fn from(value:glam::Vec4)->Self{
|
|
||||||
Self(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl std::hash::Hash for ModelGraphicsColor4{
|
|
||||||
fn hash<H: std::hash::Hasher>(&self,state:&mut H) {
|
|
||||||
for &f in self.0.as_ref(){
|
|
||||||
bytemuck::cast::<f32,u32>(f).hash(state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl Eq for ModelGraphicsColor4{}
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ModelGraphicsInstance{
|
pub struct ModelGraphicsInstance{
|
||||||
pub transform:glam::Mat4,
|
pub transform:glam::Mat4,
|
||||||
pub normal_transform:glam::Mat3,
|
pub normal_transform:glam::Mat3,
|
||||||
pub color:ModelGraphicsColor4,
|
pub color:glam::Vec4,
|
||||||
}
|
}
|
||||||
1002
src/physics.rs
1002
src/physics.rs
File diff suppressed because it is too large
Load Diff
@@ -1,133 +0,0 @@
|
|||||||
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();
|
|
||||||
},
|
|
||||||
_=>(),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -174,7 +174,7 @@ pub fn unit_cornerwedge()->crate::model::IndexedModel{
|
|||||||
generate_partial_unit_cornerwedge(t)
|
generate_partial_unit_cornerwedge(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Copy,Clone)]
|
||||||
pub struct FaceDescription{
|
pub struct FaceDescription{
|
||||||
pub texture:Option<u32>,
|
pub texture:Option<u32>,
|
||||||
pub transform:glam::Affine2,
|
pub transform:glam::Affine2,
|
||||||
|
|||||||
@@ -1,14 +1,11 @@
|
|||||||
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},
|
||||||
@@ -19,11 +16,9 @@ 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},
|
||||||
@@ -35,7 +30,7 @@ impl Default for Sensitivity{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default,Clone)]
|
#[derive(Default)]
|
||||||
pub struct UserSettings{
|
pub struct UserSettings{
|
||||||
fov:Fov,
|
fov:Fov,
|
||||||
sensitivity:Sensitivity,
|
sensitivity:Sensitivity,
|
||||||
|
|||||||
300
src/setup.rs
300
src/setup.rs
@@ -1,300 +0,0 @@
|
|||||||
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
243
src/window.rs
@@ -1,243 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
145
src/worker.rs
145
src/worker.rs
@@ -1,69 +1,17 @@
|
|||||||
use std::thread;
|
use std::thread;
|
||||||
use std::sync::{mpsc,Arc};
|
use std::sync::{mpsc,Arc};
|
||||||
use parking_lot::{Mutex,Condvar};
|
use parking_lot::Mutex;
|
||||||
|
|
||||||
//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> QRWorker<Task,Value>{
|
impl<Task:Send+'static,Value:Clone+Send+'static> Worker<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 {
|
||||||
@@ -97,79 +45,28 @@ impl<Task:Send+'static,Value:Clone+Send+'static> QRWorker<Task,Value>{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
pub struct CompatWorker<Task,Value:Clone,F>{
|
||||||
QN = WorkerDescription{
|
data:std::marker::PhantomData<Task>,
|
||||||
input:Queued,
|
f:F,
|
||||||
output:None(Single),
|
value:Value,
|
||||||
}
|
|
||||||
*/
|
|
||||||
//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<'a,Task:Send+'a> QNWorker<'a,Task>{
|
impl<Task,Value:Clone,F:FnMut(Task)->Value> CompatWorker<Task,Value,F> {
|
||||||
pub fn new<F:FnMut(Task)+Send+'a>(scope:&'a thread::Scope<'a,'_>,mut f:F)->QNWorker<'a,Task>{
|
pub fn new(value:Value,f:F) -> Self {
|
||||||
let (sender,receiver)=mpsc::channel::<Task>();
|
Self {
|
||||||
let handle=scope.spawn(move ||{
|
f,
|
||||||
loop {
|
value,
|
||||||
match receiver.recv() {
|
data:std::marker::PhantomData,
|
||||||
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<(),()>{
|
||||||
IN = WorkerDescription{
|
self.value=(self.f)(task);
|
||||||
input:Immediate,
|
Ok(())
|
||||||
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,()>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a,Task:Send+'a> INWorker<'a,Task>{
|
pub fn grab_clone(&self)->Value{
|
||||||
pub fn new<F:FnMut(Task)+Send+'a>(scope:&'a thread::Scope<'a,'_>,mut f:F)->INWorker<'a,Task>{
|
self.value.clone()
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,7 +74,7 @@ impl<'a,Task:Send+'a> INWorker<'a,Task>{
|
|||||||
fn test_worker() {
|
fn test_worker() {
|
||||||
println!("hiiiii");
|
println!("hiiiii");
|
||||||
// Create the worker thread
|
// Create the worker thread
|
||||||
let worker=QRWorker::new(crate::physics::Body::with_pva(crate::integer::Planar64Vec3::ZERO,crate::integer::Planar64Vec3::ZERO,crate::integer::Planar64Vec3::ZERO),
|
let worker = Worker::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)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -203,7 +100,7 @@ fn test_worker() {
|
|||||||
};
|
};
|
||||||
worker.send(task).unwrap();
|
worker.send(task).unwrap();
|
||||||
|
|
||||||
println!("value={}",worker.grab_clone());
|
println!("value={:?}",worker.grab_clone());
|
||||||
|
|
||||||
// wait long enough to see print from final task
|
// wait long enough to see print from final task
|
||||||
thread::sleep(std::time::Duration::from_secs(1));
|
thread::sleep(std::time::Duration::from_secs(1));
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ pub fn zeroes2(a0:Planar64,a1:Planar64,a2:Planar64) -> Vec<Planar64>{
|
|||||||
if a2==Planar64::ZERO{
|
if a2==Planar64::ZERO{
|
||||||
return zeroes1(a0, a1);
|
return zeroes1(a0, a1);
|
||||||
}
|
}
|
||||||
let radicand=a1.get() as i128*a1.get() as i128-a2.get() as i128*a0.get() as i128*4;
|
let mut radicand=a1.get() as i128*a1.get() as i128-a2.get() as i128*a0.get() as i128*4;
|
||||||
if 0<radicand {
|
if 0<radicand {
|
||||||
//start with f64 sqrt
|
//start with f64 sqrt
|
||||||
let planar_radicand=Planar64::raw(unsafe{(radicand as f64).sqrt().to_int_unchecked()});
|
let planar_radicand=Planar64::raw(unsafe{(radicand as f64).sqrt().to_int_unchecked()});
|
||||||
|
|||||||
Reference in New Issue
Block a user