You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

319 lines
9.2 KiB

extern crate tobj;
extern crate winit;
4 years ago
use std::{iter, mem, num::NonZeroU32, ops::Range, rc::Rc};
#[cfg(not(target_arch = "wasm32"))]
use std::time::{Duration, Instant};
4 years ago
use bytemuck::{Pod, Zeroable};
use futures::task::LocalSpawn;
use wgpu::util::DeviceExt;
use wgpu_subscriber;
use winit::{
event::{self, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};
4 years ago
use crate::render::Renderer;
4 years ago
4 years ago
mod framework;
mod geometry;
mod light;
mod render;
mod runtime;
4 years ago
/*
4 years ago
Collision detection
https://crates.io/crates/mgf
4 years ago
Obj file format
http://paulbourke.net/dataformats/obj/
4 years ago
tobj obj loader
https://docs.rs/tobj/2.0.3/tobj/index.html
4 years ago
mesh generator lib, might be useful
https://docs.rs/genmesh/0.6.2/genmesh/
4 years ago
legion ECS
https://github.com/amethyst/legion
4 years ago
4 years ago
mvp:
4 years ago
ECS
animation
render 3d
input/io
collision / physics
entities & behaviours
4 years ago
*/
4 years ago
#[cfg_attr(rustfmt, rustfmt_skip)]
#[allow(unused)]
pub const OPENGL_TO_WGPU_MATRIX: cgmath::Matrix4<f32> = cgmath::Matrix4::new(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.0, 0.0, 0.5, 1.0,
);
4 years ago
#[allow(dead_code)]
pub fn cast_slice<T>(data: &[T]) -> &[u8] {
use std::{mem::size_of, slice::from_raw_parts};
4 years ago
unsafe { from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::<T>()) }
4 years ago
}
#[allow(dead_code)]
pub enum ShaderStage {
Vertex,
Fragment,
Compute,
4 years ago
}
/*
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,
*/
4 years ago
fn main() {
4 years ago
// #[cfg(not(target_arch = "wasm32"))]
// {
// let chrome_tracing_dir = std::env::var("WGPU_CHROME_TRACE");
// wgpu_subscriber::initialize_default_subscriber(
// chrome_tracing_dir.as_ref().map(std::path::Path::new).ok(),
// );
// };
// #[cfg(target_arch = "wasm32")]
// console_log::init().expect("could not initialize logger");
4 years ago
4 years ago
let event_loop = EventLoop::new();
let mut builder = winit::window::WindowBuilder::new();
builder = builder.with_title(title);
4 years ago
// I don't know what they are doing here
#[cfg(windows_OFF)] // TODO
{
use winit::platform::windows::WindowBuilderExtWindows;
builder = builder.with_no_redirection_bitmap(true);
}
4 years ago
let window = builder.build(&event_loop).unwrap();
log::info!("Initializing the surface...");
// Grab the GPU instance, and query its features
let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY);
let (size, surface) = unsafe {
let size = window.inner_size();
let surface = instance.create_surface(&window);
(size, surface)
4 years ago
};
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
})
.unwrap();
4 years ago
let optional_features = Renderer::optional_features();
let required_features = Renderer::required_features();
let adapter_features = adapter.features();
assert!(
adapter_features.contains(required_features),
"Adapter does not support required features for this example: {:?}",
required_features - adapter_features
);
4 years ago
let needed_limits = wgpu::Limits::default();//Renderer::required_limits();
// Maybe for debug tracing???
let trace_dir = std::env::var("WGPU_TRACE");
// And then get the device we want
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
features: (optional_features & adapter_features) | required_features,
limits: needed_limits,
shader_validation: true,
4 years ago
},
trace_dir.ok().as_ref().map(std::path::Path::new),
)
.unwrap();
4 years ago
4 years ago
#[cfg(not(target_arch = "wasm32"))]
let (mut pool, spawner) = {
let local_pool = futures::executor::LocalPool::new();
let spawner = local_pool.spawner();
(local_pool, spawner)
};
// This is some gross-ass web shit
/*#[cfg(target_arch = "wasm32")]
let spawner = {
use futures::{future::LocalFutureObj, task::SpawnError};
use winit::platform::web::WindowExtWebSys;
struct WebSpawner {}
impl LocalSpawn for WebSpawner {
fn spawn_local_obj(
&self,
future: LocalFutureObj<'static, ()>,
) -> Result<(), SpawnError> {
Ok(wasm_bindgen_futures::spawn_local(future))
}
4 years ago
}
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()
4 years ago
})
.expect("couldn't append canvas to document body");
WebSpawner {}
};*/
4 years ago
let mut sc_desc = wgpu::SwapChainDescriptor {
// Allows a texture to be a output attachment of a renderpass.
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
format: if cfg!(target_arch = "wasm32") {
wgpu::TextureFormat::Bgra8Unorm
} else {
wgpu::TextureFormat::Bgra8UnormSrgb
},
width: size.width,
height: size.height,
// The presentation engine waits for the next vertical blanking period to update
present_mode: wgpu::PresentMode::Mailbox,
};
4 years ago
let mut swap_chain = device.create_swap_chain(&surface, &sc_desc);
log::info!("Done doing the loading part...");
4 years ago
// Init
let mut runtime = runtime::Runtime::init(&sc_desc, &device, &queue);
4 years ago
// Not sure why this is guarded, maybe we don't handle the event loop timing?
#[cfg(not(target_arch = "wasm32"))]
let mut last_update_inst = Instant::now();
log::info!("Entering render loop...");
4 years ago
4 years ago
let mut renderer = render::Renderer::init(&device, &sd_desc);
4 years ago
4 years ago
// This is just an winit event loop
event_loop.run(move |event, _, control_flow| {
let _ = (&instance, &adapter); // force ownership by the closure (wtf??)
// Override the control flow behaviour based on our system
*control_flow = if cfg!(feature = "metal-auto-capture") {
ControlFlow::Exit
} else {
#[cfg(not(target_arch = "wasm32"))]
{
// Artificially slows the loop rate to 10 millis
// This is called after redraw events cleared
ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(10))
}
#[cfg(target_arch = "wasm32")]
{
ControlFlow::Poll
4 years ago
}
};
match event {
event::Event::MainEventsCleared => {
#[cfg(not(target_arch = "wasm32"))]
{
// ask for a redraw every 20 millis
if last_update_inst.elapsed() > Duration::from_millis(20) {
window.request_redraw();
last_update_inst = Instant::now();
}
pool.run_until_stalled();
}
#[cfg(target_arch = "wasm32")]
window.request_redraw();
4 years ago
}
// Resizing will queue a request_redraw
event::Event::WindowEvent {
event: WindowEvent::Resized(size),
..
} => {
log::info!("Resizing to {:?}", size);
sc_desc.width = size.width;
sc_desc.height = size.height;
4 years ago
4 years ago
renderer.resize(&sc_desc, &device, &queue);
swap_chain = device.create_swap_chain(&surface, &sc_desc);
}
event::Event::WindowEvent { event, .. } => match event {
WindowEvent::KeyboardInput {
input:
event::KeyboardInput {
virtual_keycode: Some(event::VirtualKeyCode::Escape),
state: event::ElementState::Pressed,
..
4 years ago
},
..
}
| WindowEvent::CloseRequested => {
*control_flow = ControlFlow::Exit;
}
_ => {
4 years ago
renderer.update(event);
}
},
event::Event::RedrawRequested(_) => {
let frame = match swap_chain.get_current_frame() {
Ok(frame) => frame,
Err(_) => {
swap_chain = device.create_swap_chain(&surface, &sc_desc);
swap_chain
.get_current_frame()
.expect("Failed to acquire next swap chain texture!")
}
};
4 years ago
renderer.render(&frame.output, &device, &queue, &spawner);
4 years ago
}
_ => {}
4 years ago
}
});
4 years ago
//framework::run::<Example>("shadow");
4 years ago
}