forked from StrafesNET/strafe-client
wgpu/examples/skybox
This commit is contained in:
parent
b99f1ef731
commit
68eda6546e
BIN
images/astc.dds
Normal file
BIN
images/astc.dds
Normal file
Binary file not shown.
BIN
images/bc1.dds
Normal file
BIN
images/bc1.dds
Normal file
Binary file not shown.
BIN
images/bgra.dds
Normal file
BIN
images/bgra.dds
Normal file
Binary file not shown.
BIN
images/etc2.dds
Normal file
BIN
images/etc2.dds
Normal file
Binary file not shown.
62
models/teslacyberv3.0.mtl
Normal file
62
models/teslacyberv3.0.mtl
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
# Blender MTL File: 'teslacyberv3.0.blend'
|
||||||
|
# Material Count: 6
|
||||||
|
|
||||||
|
newmtl Material
|
||||||
|
Ns 65.476285
|
||||||
|
Ka 1.000000 1.000000 1.000000
|
||||||
|
Kd 0.411568 0.411568 0.411568
|
||||||
|
Ks 0.614679 0.614679 0.614679
|
||||||
|
Ke 0.000000 0.000000 0.000000
|
||||||
|
Ni 36.750000
|
||||||
|
d 1.000000
|
||||||
|
illum 3
|
||||||
|
|
||||||
|
newmtl Материал
|
||||||
|
Ns 323.999994
|
||||||
|
Ka 1.000000 1.000000 1.000000
|
||||||
|
Kd 0.800000 0.800000 0.800000
|
||||||
|
Ks 0.500000 0.500000 0.500000
|
||||||
|
Ke 0.000000 0.000000 0.000000
|
||||||
|
Ni 1.000000
|
||||||
|
d 1.000000
|
||||||
|
illum 2
|
||||||
|
|
||||||
|
newmtl Материал.001
|
||||||
|
Ns 900.000000
|
||||||
|
Ka 1.000000 1.000000 1.000000
|
||||||
|
Kd 0.026240 0.026240 0.026240
|
||||||
|
Ks 0.000000 0.000000 0.000000
|
||||||
|
Ke 0.000000 0.000000 0.000000
|
||||||
|
Ni 1.450000
|
||||||
|
d 1.000000
|
||||||
|
illum 1
|
||||||
|
|
||||||
|
newmtl Материал.002
|
||||||
|
Ns 0.000000
|
||||||
|
Ka 1.000000 1.000000 1.000000
|
||||||
|
Kd 0.031837 0.032429 0.029425
|
||||||
|
Ks 0.169725 0.169725 0.169725
|
||||||
|
Ke 0.000000 0.000000 0.000000
|
||||||
|
Ni 0.000000
|
||||||
|
d 1.000000
|
||||||
|
illum 2
|
||||||
|
|
||||||
|
newmtl Материал.003
|
||||||
|
Ns 900.000000
|
||||||
|
Ka 1.000000 1.000000 1.000000
|
||||||
|
Kd 0.023585 0.083235 0.095923
|
||||||
|
Ks 1.000000 1.000000 1.000000
|
||||||
|
Ke 0.000000 0.000000 0.000000
|
||||||
|
Ni 45.049999
|
||||||
|
d 1.000000
|
||||||
|
illum 3
|
||||||
|
|
||||||
|
newmtl Материал.004
|
||||||
|
Ns 323.999994
|
||||||
|
Ka 1.000000 1.000000 1.000000
|
||||||
|
Kd 0.800000 0.800000 0.800000
|
||||||
|
Ks 0.500000 0.500000 0.500000
|
||||||
|
Ke 0.000000 0.000000 0.000000
|
||||||
|
Ni 1.000000
|
||||||
|
d 1.000000
|
||||||
|
illum 2
|
6617
models/teslacyberv3.0.obj
Normal file
6617
models/teslacyberv3.0.obj
Normal file
File diff suppressed because it is too large
Load Diff
639
src/framework.rs
Normal file
639
src/framework.rs
Normal file
@ -0,0 +1,639 @@
|
|||||||
|
use std::future::Future;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
use std::str::FromStr;
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
use std::time::Instant;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas};
|
||||||
|
use winit::{
|
||||||
|
event::{self, WindowEvent},
|
||||||
|
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, event: WindowEvent);
|
||||||
|
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 = wgpu::util::initialize_adapter_from_env_or_default(&instance, Some(&surface))
|
||||||
|
.await
|
||||||
|
.expect("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 optional_features = E::optional_features();
|
||||||
|
let required_features = E::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
|
||||||
|
);
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
let mut last_frame_inst = Instant::now();
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
let (mut frame_count, mut accum_time) = (0, 0.0);
|
||||||
|
|
||||||
|
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::R),
|
||||||
|
state: event::ElementState::Pressed,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
println!("{:#?}", instance.generate_report());
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
example.update(event);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
event::Event::RedrawRequested(_) => {
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
{
|
||||||
|
accum_time += last_frame_inst.elapsed().as_secs_f32();
|
||||||
|
last_frame_inst = Instant::now();
|
||||||
|
frame_count += 1;
|
||||||
|
if frame_count == 100 {
|
||||||
|
println!(
|
||||||
|
"Avg frame time {}ms",
|
||||||
|
accum_time * 1000.0 / frame_count as f32
|
||||||
|
);
|
||||||
|
accum_time = 0.0;
|
||||||
|
frame_count = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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::*, JsCast};
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
pub use wgpu_test::image::ComparisonType;
|
||||||
|
|
||||||
|
pub struct FrameworkRefTest {
|
||||||
|
// Path to the reference image, relative to the root of the repo.
|
||||||
|
pub image_path: &'static str,
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
pub optional_features: wgpu::Features,
|
||||||
|
pub base_test_parameters: wgpu_test::TestParameters,
|
||||||
|
/// Comparisons against FLIP statistics that determine if the test passes or fails.
|
||||||
|
pub comparisons: &'static [ComparisonType],
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn test<E: Example>(mut params: FrameworkRefTest) {
|
||||||
|
use std::mem;
|
||||||
|
|
||||||
|
assert_eq!(params.width % 64, 0, "width needs to be aligned 64");
|
||||||
|
|
||||||
|
let features = E::required_features() | params.optional_features;
|
||||||
|
|
||||||
|
wgpu_test::initialize_test(
|
||||||
|
mem::take(&mut params.base_test_parameters).features(features),
|
||||||
|
|ctx| {
|
||||||
|
let spawner = Spawner::new();
|
||||||
|
|
||||||
|
let dst_texture = ctx.device.create_texture(&wgpu::TextureDescriptor {
|
||||||
|
label: Some("destination"),
|
||||||
|
size: wgpu::Extent3d {
|
||||||
|
width: params.width,
|
||||||
|
height: params.height,
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
},
|
||||||
|
mip_level_count: 1,
|
||||||
|
sample_count: 1,
|
||||||
|
dimension: wgpu::TextureDimension::D2,
|
||||||
|
format: wgpu::TextureFormat::Rgba8UnormSrgb,
|
||||||
|
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||||
|
view_formats: &[],
|
||||||
|
});
|
||||||
|
|
||||||
|
let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||||
|
|
||||||
|
let dst_buffer = ctx.device.create_buffer(&wgpu::BufferDescriptor {
|
||||||
|
label: Some("image map buffer"),
|
||||||
|
size: params.width as u64 * params.height as u64 * 4,
|
||||||
|
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||||
|
mapped_at_creation: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut example = E::init(
|
||||||
|
&wgpu::SurfaceConfiguration {
|
||||||
|
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||||
|
format: wgpu::TextureFormat::Rgba8UnormSrgb,
|
||||||
|
width: params.width,
|
||||||
|
height: params.height,
|
||||||
|
present_mode: wgpu::PresentMode::Fifo,
|
||||||
|
alpha_mode: wgpu::CompositeAlphaMode::Auto,
|
||||||
|
view_formats: vec![wgpu::TextureFormat::Rgba8UnormSrgb],
|
||||||
|
},
|
||||||
|
&ctx.adapter,
|
||||||
|
&ctx.device,
|
||||||
|
&ctx.queue,
|
||||||
|
);
|
||||||
|
|
||||||
|
example.render(&dst_view, &ctx.device, &ctx.queue, &spawner);
|
||||||
|
|
||||||
|
// Handle specific case for bunnymark
|
||||||
|
#[allow(deprecated)]
|
||||||
|
if params.image_path == "/examples/bunnymark/screenshot.png" {
|
||||||
|
// Press spacebar to spawn bunnies
|
||||||
|
example.update(winit::event::WindowEvent::KeyboardInput {
|
||||||
|
input: winit::event::KeyboardInput {
|
||||||
|
scancode: 0,
|
||||||
|
state: winit::event::ElementState::Pressed,
|
||||||
|
virtual_keycode: Some(winit::event::VirtualKeyCode::Space),
|
||||||
|
modifiers: winit::event::ModifiersState::empty(),
|
||||||
|
},
|
||||||
|
device_id: unsafe { winit::event::DeviceId::dummy() },
|
||||||
|
is_synthetic: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Step 3 extra frames
|
||||||
|
for _ in 0..3 {
|
||||||
|
example.render(&dst_view, &ctx.device, &ctx.queue, &spawner);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut cmd_buf = ctx
|
||||||
|
.device
|
||||||
|
.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
|
||||||
|
|
||||||
|
cmd_buf.copy_texture_to_buffer(
|
||||||
|
wgpu::ImageCopyTexture {
|
||||||
|
texture: &dst_texture,
|
||||||
|
mip_level: 0,
|
||||||
|
origin: wgpu::Origin3d::ZERO,
|
||||||
|
aspect: wgpu::TextureAspect::All,
|
||||||
|
},
|
||||||
|
wgpu::ImageCopyBuffer {
|
||||||
|
buffer: &dst_buffer,
|
||||||
|
layout: wgpu::ImageDataLayout {
|
||||||
|
offset: 0,
|
||||||
|
bytes_per_row: Some(params.width * 4),
|
||||||
|
rows_per_image: None,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
wgpu::Extent3d {
|
||||||
|
width: params.width,
|
||||||
|
height: params.height,
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
ctx.queue.submit(Some(cmd_buf.finish()));
|
||||||
|
|
||||||
|
let dst_buffer_slice = dst_buffer.slice(..);
|
||||||
|
dst_buffer_slice.map_async(wgpu::MapMode::Read, |_| ());
|
||||||
|
ctx.device.poll(wgpu::Maintain::Wait);
|
||||||
|
let bytes = dst_buffer_slice.get_mapped_range().to_vec();
|
||||||
|
|
||||||
|
wgpu_test::image::compare_image_output(
|
||||||
|
env!("CARGO_MANIFEST_DIR").to_string() + "/../../" + params.image_path,
|
||||||
|
ctx.adapter_info.backend,
|
||||||
|
params.width,
|
||||||
|
params.height,
|
||||||
|
&bytes,
|
||||||
|
params.comparisons,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// This allows treating the framework as a standalone example,
|
||||||
|
// thus avoiding listing the example names in `Cargo.toml`.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn main() {}
|
1
src/lib.rs
Normal file
1
src/lib.rs
Normal file
@ -0,0 +1 @@
|
|||||||
|
pub mod framework;
|
524
src/main.rs
524
src/main.rs
@ -1,3 +1,523 @@
|
|||||||
fn main() {
|
use bytemuck::{Pod, Zeroable};
|
||||||
println!("Hello, world!");
|
use std::{borrow::Cow, f32::consts};
|
||||||
|
use wgpu::{util::DeviceExt, AstcBlock, AstcChannel};
|
||||||
|
|
||||||
|
const IMAGE_SIZE: u32 = 128;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||||
|
#[repr(C)]
|
||||||
|
struct Vertex {
|
||||||
|
pos: [f32; 3],
|
||||||
|
normal: [f32; 3],
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Entity {
|
||||||
|
vertex_count: u32,
|
||||||
|
vertex_buf: wgpu::Buffer,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note: we use the Y=up coordinate space in this example.
|
||||||
|
struct Camera {
|
||||||
|
screen_size: (u32, u32),
|
||||||
|
angle_y: f32,
|
||||||
|
angle_xz: f32,
|
||||||
|
dist: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
const MODEL_CENTER_Y: f32 = 2.0;
|
||||||
|
|
||||||
|
impl Camera {
|
||||||
|
fn to_uniform_data(&self) -> [f32; 16 * 3 + 4] {
|
||||||
|
let aspect = self.screen_size.0 as f32 / self.screen_size.1 as f32;
|
||||||
|
let proj = glam::Mat4::perspective_rh(consts::FRAC_PI_4, aspect, 1.0, 50.0);
|
||||||
|
let cam_pos = glam::Vec3::new(
|
||||||
|
self.angle_xz.cos() * self.angle_y.sin() * self.dist,
|
||||||
|
self.angle_xz.sin() * self.dist + MODEL_CENTER_Y,
|
||||||
|
self.angle_xz.cos() * self.angle_y.cos() * self.dist,
|
||||||
|
);
|
||||||
|
let view = glam::Mat4::look_at_rh(
|
||||||
|
cam_pos,
|
||||||
|
glam::Vec3::new(0f32, MODEL_CENTER_Y, 0.0),
|
||||||
|
glam::Vec3::Y,
|
||||||
|
);
|
||||||
|
let proj_inv = proj.inverse();
|
||||||
|
|
||||||
|
let mut raw = [0f32; 16 * 3 + 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..51].copy_from_slice(AsRef::<[f32; 3]>::as_ref(&cam_pos));
|
||||||
|
raw[51] = 1.0;
|
||||||
|
raw
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Skybox {
|
||||||
|
camera: Camera,
|
||||||
|
sky_pipeline: wgpu::RenderPipeline,
|
||||||
|
entity_pipeline: wgpu::RenderPipeline,
|
||||||
|
bind_group: wgpu::BindGroup,
|
||||||
|
uniform_buf: wgpu::Buffer,
|
||||||
|
entities: Vec<Entity>,
|
||||||
|
depth_view: wgpu::TextureView,
|
||||||
|
staging_belt: wgpu::util::StagingBelt,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Skybox {
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl wgpu_example::framework::Example for Skybox {
|
||||||
|
fn optional_features() -> wgpu::Features {
|
||||||
|
wgpu::Features::TEXTURE_COMPRESSION_ASTC
|
||||||
|
| wgpu::Features::TEXTURE_COMPRESSION_ETC2
|
||||||
|
| wgpu::Features::TEXTURE_COMPRESSION_BC
|
||||||
|
}
|
||||||
|
|
||||||
|
fn init(
|
||||||
|
config: &wgpu::SurfaceConfiguration,
|
||||||
|
_adapter: &wgpu::Adapter,
|
||||||
|
device: &wgpu::Device,
|
||||||
|
queue: &wgpu::Queue,
|
||||||
|
) -> Self {
|
||||||
|
let mut entities = Vec::new();
|
||||||
|
{
|
||||||
|
let source = include_bytes!("../models/teslacyberv3.0.obj");
|
||||||
|
let data = obj::ObjData::load_buf(&source[..]).unwrap();
|
||||||
|
let mut vertices = Vec::new();
|
||||||
|
for object in data.objects {
|
||||||
|
for group in object.groups {
|
||||||
|
vertices.clear();
|
||||||
|
for poly in group.polys {
|
||||||
|
for end_index in 2..poly.0.len() {
|
||||||
|
for &index in &[0, end_index - 1, end_index] {
|
||||||
|
let obj::IndexTuple(position_id, _texture_id, normal_id) =
|
||||||
|
poly.0[index];
|
||||||
|
vertices.push(Vertex {
|
||||||
|
pos: data.position[position_id],
|
||||||
|
normal: data.normal[normal_id.unwrap()],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let vertex_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some("Vertex"),
|
||||||
|
contents: bytemuck::cast_slice(&vertices),
|
||||||
|
usage: wgpu::BufferUsages::VERTEX,
|
||||||
|
});
|
||||||
|
entities.push(Entity {
|
||||||
|
vertex_count: vertices.len() as u32,
|
||||||
|
vertex_buf,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
|
label: None,
|
||||||
|
entries: &[
|
||||||
|
wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: 0,
|
||||||
|
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
|
||||||
|
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::Cube,
|
||||||
|
},
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: 2,
|
||||||
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||||
|
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create the render pipeline
|
||||||
|
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||||
|
label: None,
|
||||||
|
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
|
||||||
|
});
|
||||||
|
|
||||||
|
let camera = Camera {
|
||||||
|
screen_size: (config.width, config.height),
|
||||||
|
angle_xz: 0.2,
|
||||||
|
angle_y: 0.2,
|
||||||
|
dist: 20.0,
|
||||||
|
};
|
||||||
|
let raw_uniforms = camera.to_uniform_data();
|
||||||
|
let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some("Buffer"),
|
||||||
|
contents: bytemuck::cast_slice(&raw_uniforms),
|
||||||
|
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||||
|
});
|
||||||
|
|
||||||
|
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||||
|
label: None,
|
||||||
|
bind_group_layouts: &[&bind_group_layout],
|
||||||
|
push_constant_ranges: &[],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create the render pipelines
|
||||||
|
let sky_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||||
|
label: Some("Sky"),
|
||||||
|
layout: Some(&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 entity_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||||
|
label: Some("Entity"),
|
||||||
|
layout: Some(&pipeline_layout),
|
||||||
|
vertex: wgpu::VertexState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: "vs_entity",
|
||||||
|
buffers: &[wgpu::VertexBufferLayout {
|
||||||
|
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
|
||||||
|
step_mode: wgpu::VertexStepMode::Vertex,
|
||||||
|
attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3],
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
fragment: Some(wgpu::FragmentState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: "fs_entity",
|
||||||
|
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 sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||||
|
label: None,
|
||||||
|
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 device_features = device.features();
|
||||||
|
|
||||||
|
let skybox_format = if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC) {
|
||||||
|
log::info!("Using ASTC");
|
||||||
|
wgpu::TextureFormat::Astc {
|
||||||
|
block: AstcBlock::B4x4,
|
||||||
|
channel: AstcChannel::UnormSrgb,
|
||||||
|
}
|
||||||
|
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ETC2) {
|
||||||
|
log::info!("Using ETC2");
|
||||||
|
wgpu::TextureFormat::Etc2Rgb8UnormSrgb
|
||||||
|
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_BC) {
|
||||||
|
log::info!("Using BC");
|
||||||
|
wgpu::TextureFormat::Bc1RgbaUnormSrgb
|
||||||
|
} else {
|
||||||
|
log::info!("Using plain");
|
||||||
|
wgpu::TextureFormat::Bgra8UnormSrgb
|
||||||
|
};
|
||||||
|
|
||||||
|
let size = wgpu::Extent3d {
|
||||||
|
width: IMAGE_SIZE,
|
||||||
|
height: IMAGE_SIZE,
|
||||||
|
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);
|
||||||
|
|
||||||
|
log::debug!(
|
||||||
|
"Copying {:?} skybox images of size {}, {}, 6 with {} mips to gpu",
|
||||||
|
skybox_format,
|
||||||
|
IMAGE_SIZE,
|
||||||
|
IMAGE_SIZE,
|
||||||
|
max_mips,
|
||||||
|
);
|
||||||
|
|
||||||
|
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 image = ddsfile::Dds::read(&mut std::io::Cursor::new(&bytes)).unwrap();
|
||||||
|
|
||||||
|
let 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: None,
|
||||||
|
view_formats: &[],
|
||||||
|
},
|
||||||
|
&image.data,
|
||||||
|
);
|
||||||
|
|
||||||
|
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor {
|
||||||
|
label: None,
|
||||||
|
dimension: Some(wgpu::TextureViewDimension::Cube),
|
||||||
|
..wgpu::TextureViewDescriptor::default()
|
||||||
|
});
|
||||||
|
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
|
layout: &bind_group_layout,
|
||||||
|
entries: &[
|
||||||
|
wgpu::BindGroupEntry {
|
||||||
|
binding: 0,
|
||||||
|
resource: uniform_buf.as_entire_binding(),
|
||||||
|
},
|
||||||
|
wgpu::BindGroupEntry {
|
||||||
|
binding: 1,
|
||||||
|
resource: wgpu::BindingResource::TextureView(&texture_view),
|
||||||
|
},
|
||||||
|
wgpu::BindGroupEntry {
|
||||||
|
binding: 2,
|
||||||
|
resource: wgpu::BindingResource::Sampler(&sampler),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
label: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
let depth_view = Self::create_depth_texture(config, device);
|
||||||
|
|
||||||
|
Skybox {
|
||||||
|
camera,
|
||||||
|
sky_pipeline,
|
||||||
|
entity_pipeline,
|
||||||
|
bind_group,
|
||||||
|
uniform_buf,
|
||||||
|
entities,
|
||||||
|
depth_view,
|
||||||
|
staging_belt: wgpu::util::StagingBelt::new(0x100),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::single_match)]
|
||||||
|
fn update(&mut self, event: winit::event::WindowEvent) {
|
||||||
|
match event {
|
||||||
|
winit::event::WindowEvent::CursorMoved { position, .. } => {
|
||||||
|
let norm_x = position.x as f32 / self.camera.screen_size.0 as f32 - 0.5;
|
||||||
|
let norm_y = position.y as f32 / self.camera.screen_size.1 as f32 - 0.5;
|
||||||
|
self.camera.angle_y = norm_x * 5.0;
|
||||||
|
self.camera.angle_xz = norm_y;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resize(
|
||||||
|
&mut self,
|
||||||
|
config: &wgpu::SurfaceConfiguration,
|
||||||
|
device: &wgpu::Device,
|
||||||
|
_queue: &wgpu::Queue,
|
||||||
|
) {
|
||||||
|
self.depth_view = Self::create_depth_texture(config, device);
|
||||||
|
self.camera.screen_size = (config.width, config.height);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render(
|
||||||
|
&mut self,
|
||||||
|
view: &wgpu::TextureView,
|
||||||
|
device: &wgpu::Device,
|
||||||
|
queue: &wgpu::Queue,
|
||||||
|
_spawner: &wgpu_example::framework::Spawner,
|
||||||
|
) {
|
||||||
|
let mut encoder =
|
||||||
|
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
||||||
|
|
||||||
|
// update rotation
|
||||||
|
let raw_uniforms = self.camera.to_uniform_data();
|
||||||
|
self.staging_belt
|
||||||
|
.write_buffer(
|
||||||
|
&mut encoder,
|
||||||
|
&self.uniform_buf,
|
||||||
|
0,
|
||||||
|
wgpu::BufferSize::new((raw_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
|
||||||
|
device,
|
||||||
|
)
|
||||||
|
.copy_from_slice(bytemuck::cast_slice(&raw_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_group, &[]);
|
||||||
|
rpass.set_pipeline(&self.entity_pipeline);
|
||||||
|
|
||||||
|
for entity in self.entities.iter() {
|
||||||
|
rpass.set_vertex_buffer(0, entity.vertex_buf.slice(..));
|
||||||
|
rpass.draw(0..entity.vertex_count, 0..1);
|
||||||
|
}
|
||||||
|
|
||||||
|
rpass.set_pipeline(&self.sky_pipeline);
|
||||||
|
rpass.draw(0..3, 0..1);
|
||||||
|
}
|
||||||
|
|
||||||
|
queue.submit(std::iter::once(encoder.finish()));
|
||||||
|
|
||||||
|
self.staging_belt.recall();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
wgpu_example::framework::run::<Skybox>("skybox");
|
||||||
|
}
|
||||||
|
|
||||||
|
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[wasm_bindgen_test::wasm_bindgen_test]
|
||||||
|
fn skybox() {
|
||||||
|
wgpu_example::framework::test::<Skybox>(wgpu_example::framework::FrameworkRefTest {
|
||||||
|
image_path: "/examples/skybox/screenshot.png",
|
||||||
|
width: 1024,
|
||||||
|
height: 768,
|
||||||
|
optional_features: wgpu::Features::default(),
|
||||||
|
base_test_parameters: wgpu_test::TestParameters::default().specific_failure(
|
||||||
|
Some(wgpu::Backends::GL),
|
||||||
|
None,
|
||||||
|
Some("ANGLE"),
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
comparisons: &[wgpu_test::ComparisonType::Mean(0.015)],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[wasm_bindgen_test::wasm_bindgen_test]
|
||||||
|
fn skybox_bc1() {
|
||||||
|
wgpu_example::framework::test::<Skybox>(wgpu_example::framework::FrameworkRefTest {
|
||||||
|
image_path: "/examples/skybox/screenshot-bc1.png",
|
||||||
|
width: 1024,
|
||||||
|
height: 768,
|
||||||
|
optional_features: wgpu::Features::TEXTURE_COMPRESSION_BC,
|
||||||
|
base_test_parameters: wgpu_test::TestParameters::default(), // https://bugs.chromium.org/p/angleproject/issues/detail?id=7056
|
||||||
|
comparisons: &[wgpu_test::ComparisonType::Mean(0.02)],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[wasm_bindgen_test::wasm_bindgen_test]
|
||||||
|
fn skybox_etc2() {
|
||||||
|
wgpu_example::framework::test::<Skybox>(wgpu_example::framework::FrameworkRefTest {
|
||||||
|
image_path: "/examples/skybox/screenshot-etc2.png",
|
||||||
|
width: 1024,
|
||||||
|
height: 768,
|
||||||
|
optional_features: wgpu::Features::TEXTURE_COMPRESSION_ETC2,
|
||||||
|
base_test_parameters: wgpu_test::TestParameters::default(), // https://bugs.chromium.org/p/angleproject/issues/detail?id=7056
|
||||||
|
comparisons: &[wgpu_test::ComparisonType::Mean(0.015)],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[wasm_bindgen_test::wasm_bindgen_test]
|
||||||
|
fn skybox_astc() {
|
||||||
|
wgpu_example::framework::test::<Skybox>(wgpu_example::framework::FrameworkRefTest {
|
||||||
|
image_path: "/examples/skybox/screenshot-astc.png",
|
||||||
|
width: 1024,
|
||||||
|
height: 768,
|
||||||
|
optional_features: wgpu::Features::TEXTURE_COMPRESSION_ASTC,
|
||||||
|
base_test_parameters: wgpu_test::TestParameters::default(), // https://bugs.chromium.org/p/angleproject/issues/detail?id=7056
|
||||||
|
comparisons: &[wgpu_test::ComparisonType::Mean(0.016)],
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
80
src/shader.wgsl
Normal file
80
src/shader.wgsl
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
struct SkyOutput {
|
||||||
|
@builtin(position) position: vec4<f32>,
|
||||||
|
@location(0) uv: vec3<f32>,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Data {
|
||||||
|
// from camera to screen
|
||||||
|
proj: mat4x4<f32>,
|
||||||
|
// from screen to camera
|
||||||
|
proj_inv: mat4x4<f32>,
|
||||||
|
// from world to camera
|
||||||
|
view: mat4x4<f32>,
|
||||||
|
// camera position
|
||||||
|
cam_pos: vec4<f32>,
|
||||||
|
};
|
||||||
|
@group(0)
|
||||||
|
@binding(0)
|
||||||
|
var<uniform> r_data: Data;
|
||||||
|
|
||||||
|
@vertex
|
||||||
|
fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
|
||||||
|
// hacky way to draw a large triangle
|
||||||
|
let tmp1 = i32(vertex_index) / 2;
|
||||||
|
let tmp2 = i32(vertex_index) & 1;
|
||||||
|
let pos = vec4<f32>(
|
||||||
|
f32(tmp1) * 4.0 - 1.0,
|
||||||
|
f32(tmp2) * 4.0 - 1.0,
|
||||||
|
1.0,
|
||||||
|
1.0
|
||||||
|
);
|
||||||
|
|
||||||
|
// transposition = inversion for this orthonormal matrix
|
||||||
|
let inv_model_view = transpose(mat3x3<f32>(r_data.view[0].xyz, r_data.view[1].xyz, r_data.view[2].xyz));
|
||||||
|
let unprojected = r_data.proj_inv * pos;
|
||||||
|
|
||||||
|
var result: SkyOutput;
|
||||||
|
result.uv = inv_model_view * unprojected.xyz;
|
||||||
|
result.position = pos;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EntityOutput {
|
||||||
|
@builtin(position) position: vec4<f32>,
|
||||||
|
@location(1) normal: vec3<f32>,
|
||||||
|
@location(3) view: vec3<f32>,
|
||||||
|
};
|
||||||
|
|
||||||
|
@vertex
|
||||||
|
fn vs_entity(
|
||||||
|
@location(0) pos: vec3<f32>,
|
||||||
|
@location(1) normal: vec3<f32>,
|
||||||
|
) -> EntityOutput {
|
||||||
|
var result: EntityOutput;
|
||||||
|
result.normal = normal;
|
||||||
|
result.view = pos - r_data.cam_pos.xyz;
|
||||||
|
result.position = r_data.proj * r_data.view * vec4<f32>(pos, 1.0);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@group(0)
|
||||||
|
@binding(1)
|
||||||
|
var r_texture: texture_cube<f32>;
|
||||||
|
@group(0)
|
||||||
|
@binding(2)
|
||||||
|
var r_sampler: sampler;
|
||||||
|
|
||||||
|
@fragment
|
||||||
|
fn fs_sky(vertex: SkyOutput) -> @location(0) vec4<f32> {
|
||||||
|
return textureSample(r_texture, r_sampler, vertex.uv);
|
||||||
|
}
|
||||||
|
|
||||||
|
@fragment
|
||||||
|
fn fs_entity(vertex: EntityOutput) -> @location(0) vec4<f32> {
|
||||||
|
let incident = normalize(vertex.view);
|
||||||
|
let normal = normalize(vertex.normal);
|
||||||
|
let reflected = incident - 2.0 * dot(normal, incident) * normal;
|
||||||
|
|
||||||
|
let reflected_color = textureSample(r_texture, r_sampler, reflected).rgb;
|
||||||
|
return vec4<f32>(vec3<f32>(0.1) + 0.5 * reflected_color, 1.0);
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user