Skip to content

Commit

Permalink
Merge branch 'trunk' of https://github.com/gfx-rs/wgpu into wgpu/master
Browse files Browse the repository at this point in the history
  • Loading branch information
gents83 committed Nov 18, 2023
2 parents ff042c4 + fd53ea9 commit 24393a4
Show file tree
Hide file tree
Showing 47 changed files with 792 additions and 683 deletions.
22 changes: 16 additions & 6 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
**Checklist**

- [ ] Run `cargo clippy`.
- [ ] Run `cargo clippy --target wasm32-unknown-unknown` if applicable.
- [ ] Add change to CHANGELOG.md. See simple instructions inside file.

**Connections**
_Link to the issues addressed by this PR, or dependent PRs in other repositories_

Expand All @@ -12,3 +6,19 @@ _Describe what problem this is solving, and how it's solved._

**Testing**
_Explain how this change is tested._

<!--
Thanks for filing! The codeowners file will automatically request reviews from the appropriate teams.
After you get a review and have addressed any comments, please explicitly re-request a review from the
person(s) who reviewed your changes. This will make sure it gets re-added to their review queue - you're no bothering us!
-->

**Checklist**

- [ ] Run `cargo fmt`.
- [ ] Run `cargo clippy`. If applicable, add:
- [ ] `--target wasm32-unknown-unknown`
- [ ] `--target wasm32-unknown-emscripten`
- [ ] Run `cargo xtask test` to run tests.
- [ ] Add change to `CHANGELOG.md`. See simple instructions inside file.
14 changes: 13 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,19 @@ removed 'RefCount' and 'MultiRefCount' in favour of using only 'Arc' internal re
- Log vulkan validation layer messages during instance creation and destruction: By @exrook in [#4586](https://github.com/gfx-rs/wgpu/pull/4586)
- `TextureFormat::block_size` is deprecated, use `TextureFormat::block_copy_size` instead: By @wumpf in [#4647](https://github.com/gfx-rs/wgpu/pull/4647)

#### Safe `Surface` creation

It is now possible to safely create a `wgpu::Surface` with `Surface::create_surface()` by letting `Surface` hold a lifetime to `window`.

Passing an owned value `window` to `Surface` will return a `Surface<'static>`. Shared ownership over `window` can still be achieved with e.g. an `Arc`. Alternatively a reference could be passed, which will return a `Surface<'window>`.

`Surface::create_surface_from_raw()` can be used to continue producing a `Surface<'static>` without any lifetime requirements over `window`, which also remains `unsafe`.

#### Naga

- Remove `span` and `validate` features. Always fully validate shader modules, and always track source positions for use in error messages. By @teoxoy in [#4706](https://github.com/gfx-rs/wgpu/pull/4706)
- Introduce a new `Scalar` struct type for use in Naga's IR, and update all frontend, middle, and backend code appropriately. By @jimblandy in [#4673](https://github.com/gfx-rs/wgpu/pull/4673).
- Add more metal keywords. By @fornwall in [#4707](https://github.com/gfx-rs/wgpu/pull/4707).

### Bug Fixes

Expand All @@ -68,6 +78,8 @@ removed 'RefCount' and 'MultiRefCount' in favour of using only 'Arc' internal re

- When evaluating const-expressions and generating SPIR-V, properly handle `Compose` expressions whose operands are `Splat` expressions. Such expressions are created and marked as constant by the constant evaluator. By @jimblandy in [#4695](https://github.com/gfx-rs/wgpu/pull/4695).

- Preserve the source spans for constants and expressions correctly across module compaction. By @jimblandy in [#4696](https://github.com/gfx-rs/wgpu/pull/4696).

### Examples

- remove winit dependency from hello-compute example by @psvri in [#4699](https://github.com/gfx-rs/wgpu/pull/4699)
Expand All @@ -84,7 +96,7 @@ removed 'RefCount' and 'MultiRefCount' in favour of using only 'Arc' internal re
- Passing a naga module directly to `Device::create_shader_module`.
- `InstanceFlags::DEBUG` is enabled.

#### DX12
#### DX12
- Always use HLSL 2018 when using DXC to compile HLSL shaders. By @daxpedda in [#4629](https://github.com/gfx-rs/wgpu/pull/4629)

#### Metal
Expand Down
27 changes: 14 additions & 13 deletions examples/common/src/framework.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use wgpu::{Instance, Surface, WasmNotSend, WasmNotSync};
use std::sync::Arc;

use wgpu::{Instance, Surface, WasmNotSendSync};
use wgpu_test::GpuTestConfiguration;
use winit::{
dpi::PhysicalSize,
Expand Down Expand Up @@ -90,15 +92,15 @@ fn init_logger() {

struct EventLoopWrapper {
event_loop: EventLoop<()>,
window: Window,
window: Arc<Window>,
}

impl EventLoopWrapper {
pub fn new(title: &str) -> Self {
let event_loop = EventLoop::new().unwrap();
let mut builder = winit::window::WindowBuilder::new();
builder = builder.with_title(title);
let window = builder.build(&event_loop).unwrap();
let window = Arc::new(builder.build(&event_loop).unwrap());

#[cfg(target_arch = "wasm32")]
{
Expand All @@ -121,7 +123,7 @@ impl EventLoopWrapper {
///
/// As surface usage varies per platform, wrapping this up cleans up the event loop code.
struct SurfaceWrapper {
surface: Option<wgpu::Surface>,
surface: Option<wgpu::Surface<'static>>,
config: Option<wgpu::SurfaceConfiguration>,
}

Expand All @@ -141,9 +143,9 @@ impl SurfaceWrapper {
///
/// We cannot unconditionally create a surface here, as Android requires
/// us to wait until we recieve the `Resumed` event to do so.
fn pre_adapter(&mut self, instance: &Instance, window: &Window) {
fn pre_adapter(&mut self, instance: &Instance, window: Arc<Window>) {
if cfg!(target_arch = "wasm32") {
self.surface = Some(unsafe { instance.create_surface(&window).unwrap() });
self.surface = Some(instance.create_surface(window).unwrap());
}
}

Expand All @@ -163,7 +165,7 @@ impl SurfaceWrapper {
/// On all native platforms, this is where we create the surface.
///
/// Additionally, we configure the surface based on the (now valid) window size.
fn resume(&mut self, context: &ExampleContext, window: &Window, srgb: bool) {
fn resume(&mut self, context: &ExampleContext, window: Arc<Window>, srgb: bool) {
// Window size is only actually valid after we enter the event loop.
let window_size = window.inner_size();
let width = window_size.width.max(1);
Expand All @@ -173,7 +175,7 @@ impl SurfaceWrapper {

// We didn't create the surface in pre_adapter, so we need to do so now.
if !cfg!(target_arch = "wasm32") {
self.surface = Some(unsafe { context.instance.create_surface(&window).unwrap() });
self.surface = Some(context.instance.create_surface(window).unwrap());
}

// From here on, self.surface should be Some.
Expand Down Expand Up @@ -252,7 +254,7 @@ struct ExampleContext {
}
impl ExampleContext {
/// Initializes the example context.
async fn init_async<E: Example>(surface: &mut SurfaceWrapper, window: &Window) -> Self {
async fn init_async<E: Example>(surface: &mut SurfaceWrapper, window: Arc<Window>) -> Self {
log::info!("Initializing wgpu...");

let backends = wgpu::util::backend_bits_from_env().unwrap_or_default();
Expand Down Expand Up @@ -357,8 +359,7 @@ async fn start<E: Example>(title: &str) {
init_logger();
let window_loop = EventLoopWrapper::new(title);
let mut surface = SurfaceWrapper::new();
let context = ExampleContext::init_async::<E>(&mut surface, &window_loop.window).await;

let context = ExampleContext::init_async::<E>(&mut surface, window_loop.window.clone()).await;
let mut frame_counter = FrameCounter::new();

// We wait to create the example until we have a valid surface.
Expand All @@ -384,7 +385,7 @@ async fn start<E: Example>(title: &str) {

match event {
ref e if SurfaceWrapper::start_condition(e) => {
surface.resume(&context, &window_loop.window, E::SRGB);
surface.resume(&context, window_loop.window.clone(), E::SRGB);

// If we haven't created the example yet, do so now.
if example.is_none() {
Expand Down Expand Up @@ -503,7 +504,7 @@ pub struct ExampleTestParams<E> {
pub _phantom: std::marker::PhantomData<E>,
}

impl<E: Example + WasmNotSend + WasmNotSync> From<ExampleTestParams<E>> for GpuTestConfiguration {
impl<E: Example + WasmNotSendSync> From<ExampleTestParams<E>> for GpuTestConfiguration {
fn from(params: ExampleTestParams<E>) -> Self {
GpuTestConfiguration::new()
.name(params.name)
Expand Down
3 changes: 2 additions & 1 deletion examples/hello-triangle/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ async fn run(event_loop: EventLoop<()>, window: Window) {

let instance = wgpu::Instance::default();

let surface = unsafe { instance.create_surface(&window) }.unwrap();
let surface = instance.create_surface(&window).unwrap();
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
Expand Down Expand Up @@ -84,6 +84,7 @@ async fn run(event_loop: EventLoop<()>, window: Window) {

surface.configure(&device, &config);

let window = &window;
event_loop
.run(move |event, target| {
// Have the closure take ownership of the resources.
Expand Down
13 changes: 7 additions & 6 deletions examples/hello-windows/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
#![cfg_attr(target_arch = "wasm32", allow(dead_code))]

use std::collections::HashMap;
use std::{collections::HashMap, sync::Arc};
use winit::{
event::{Event, WindowEvent},
event_loop::EventLoop,
window::{Window, WindowId},
};

struct ViewportDesc {
window: Window,
window: Arc<Window>,
background: wgpu::Color,
surface: wgpu::Surface,
surface: wgpu::Surface<'static>,
}

struct Viewport {
Expand All @@ -19,8 +19,8 @@ struct Viewport {
}

impl ViewportDesc {
fn new(window: Window, background: wgpu::Color, instance: &wgpu::Instance) -> Self {
let surface = unsafe { instance.create_surface(&window) }.unwrap();
fn new(window: Arc<Window>, background: wgpu::Color, instance: &wgpu::Instance) -> Self {
let surface = instance.create_surface(window.clone()).unwrap();
Self {
window,
background,
Expand Down Expand Up @@ -62,7 +62,7 @@ impl Viewport {
}
}

async fn run(event_loop: EventLoop<()>, viewports: Vec<(Window, wgpu::Color)>) {
async fn run(event_loop: EventLoop<()>, viewports: Vec<(Arc<Window>, wgpu::Color)>) {
let instance = wgpu::Instance::default();
let viewports: Vec<_> = viewports
.into_iter()
Expand Down Expand Up @@ -180,6 +180,7 @@ fn main() {
.with_inner_size(winit::dpi::PhysicalSize::new(WINDOW_SIZE, WINDOW_SIZE))
.build(&event_loop)
.unwrap();
let window = Arc::new(window);
window.set_outer_position(winit::dpi::PhysicalPosition::new(
WINDOW_PADDING + column * WINDOW_OFFSET,
WINDOW_PADDING + row * (WINDOW_OFFSET + WINDOW_TITLEBAR),
Expand Down
12 changes: 7 additions & 5 deletions examples/uniform-values/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
//! The usage of the uniform buffer within the shader itself is pretty self-explanatory given
//! some understanding of WGSL.

use std::sync::Arc;
// We won't bring StorageBuffer into scope as that might be too easy to confuse
// with actual GPU-allocated WGPU storage buffers.
use encase::ShaderType;
Expand Down Expand Up @@ -84,8 +85,8 @@ impl Default for AppState {
}

struct WgpuContext {
pub window: Window,
pub surface: wgpu::Surface,
pub window: Arc<Window>,
pub surface: wgpu::Surface<'static>,
pub surface_config: wgpu::SurfaceConfiguration,
pub device: wgpu::Device,
pub queue: wgpu::Queue,
Expand All @@ -95,11 +96,11 @@ struct WgpuContext {
}

impl WgpuContext {
async fn new(window: Window) -> WgpuContext {
async fn new(window: Arc<Window>) -> WgpuContext {
let size = window.inner_size();

let instance = wgpu::Instance::default();
let surface = unsafe { instance.create_surface(&window) }.unwrap();
let surface = instance.create_surface(window.clone()).unwrap();
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
Expand Down Expand Up @@ -223,7 +224,7 @@ impl WgpuContext {
}
}

async fn run(event_loop: EventLoop<()>, window: Window) {
async fn run(event_loop: EventLoop<()>, window: Arc<Window>) {
let mut wgpu_context = Some(WgpuContext::new(window).await);
// (6)
let mut state = Some(AppState::default());
Expand Down Expand Up @@ -351,6 +352,7 @@ fn main() {
.with_inner_size(winit::dpi::LogicalSize::new(900, 900))
.build(&event_loop)
.unwrap();
let window = Arc::new(window);
#[cfg(not(target_arch = "wasm32"))]
{
env_logger::builder().format_timestamp_nanos().init();
Expand Down
2 changes: 0 additions & 2 deletions naga-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ argh = "0.1.5"
version = "0.14"
path = "../naga"
features = [
"validate",
"compact",
"span",
"wgsl-in",
"wgsl-out",
"glsl-in",
Expand Down
8 changes: 3 additions & 5 deletions naga/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,9 @@ deserialize = ["serde", "bitflags/serde", "indexmap/serde"]
arbitrary = ["dep:arbitrary", "bitflags/arbitrary", "indexmap/arbitrary"]
spv-in = ["petgraph", "spirv"]
spv-out = ["spirv"]
wgsl-in = ["codespan-reporting", "hexf-parse", "termcolor", "unicode-xid"]
wgsl-in = ["hexf-parse", "unicode-xid"]
wgsl-out = []
hlsl-out = []
span = ["codespan-reporting", "termcolor"]
validate = []
compact = []

[[bench]]
Expand All @@ -41,11 +39,11 @@ harness = false
arbitrary = { version = "1.3", features = ["derive"], optional = true }
bitflags = "2.2"
bit-set = "0.5"
termcolor = { version = "1.4.0", optional = true }
termcolor = { version = "1.4.0" }
# remove termcolor dep when updating to the next version of codespan-reporting
# termcolor minimum version was wrong and was fixed in
# https://github.com/brendanzab/codespan/commit/e99c867339a877731437e7ee6a903a3d03b5439e
codespan-reporting = { version = "0.11.0", optional = true }
codespan-reporting = { version = "0.11.0" }
rustc-hash = "1.1.0"
indexmap = { version = "2", features = ["std"] }
log = "0.4"
Expand Down
5 changes: 0 additions & 5 deletions naga/benches/criterion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ fn gather_modules() -> Vec<naga::Module> {
fn validation(c: &mut Criterion) {
let inputs = gather_modules();
let mut group = c.benchmark_group("valid");
#[cfg(feature = "validate")]
group.bench_function("safe", |b| {
let mut validator = naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
Expand All @@ -131,7 +130,6 @@ fn validation(c: &mut Criterion) {
}
});
});
#[cfg(feature = "validate")]
group.bench_function("unsafe", |b| {
let mut validator = naga::valid::Validator::new(
naga::valid::ValidationFlags::empty(),
Expand All @@ -146,7 +144,6 @@ fn validation(c: &mut Criterion) {
}

fn backends(c: &mut Criterion) {
#[cfg(feature = "validate")]
let inputs = {
let mut validator = naga::valid::Validator::new(
naga::valid::ValidationFlags::empty(),
Expand All @@ -158,8 +155,6 @@ fn backends(c: &mut Criterion) {
.flat_map(|module| validator.validate(&module).ok().map(|info| (module, info)))
.collect::<Vec<_>>()
};
#[cfg(not(feature = "validate"))]
let inputs = Vec::<(naga::Module, naga::valid::ModuleInfo)>::new();

let mut group = c.benchmark_group("back");
#[cfg(feature = "wgsl-out")]
Expand Down
2 changes: 1 addition & 1 deletion naga/fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ libfuzzer-sys = "0.4"
[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios")))'.dependencies.naga]
path = ".."
version = "0.14.0"
features = ["arbitrary", "spv-in", "wgsl-in", "glsl-in", "validate"]
features = ["arbitrary", "spv-in", "wgsl-in", "glsl-in"]

[[bin]]
name = "spv_parser"
Expand Down
Loading

0 comments on commit 24393a4

Please sign in to comment.