diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 7ea9519f9..4d16ebca6 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -6,7 +6,7 @@ labels: bug assignees: "" --- - **Description** diff --git a/AGENTS.md b/AGENTS.md index c451abc37..9b2933380 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -88,7 +88,7 @@ behavior in the WebGPU or WGSL specification. # Overview of the Code -See `docs/big-picture.png` for an overview of the system. +See `wgpu/src/documentation/images/big-picture.webp` for an overview of the system. The major components are: @@ -116,7 +116,7 @@ The major components are: apply to other clients, the issue should probably be fixed in `wgpu-core`. For a more detailed discussion of the `wgpu` architecture, refer to -. +wgpu/src/documentation/internals/architecture.rs ## Naga diff --git a/README.md b/README.md index f31db0387..fdeb73783 100644 --- a/README.md +++ b/README.md @@ -24,9 +24,9 @@ Additionally, [WebGPU Fundamentals] is a tutorial for WebGPU which is very simil [Learn Wgpu]: https://sotrh.github.io/learn-wgpu/ [WebGPU Fundamentals]: https://webgpufundamentals.org/ -### Wiki +### Documentation Guides -We have a [wiki](https://github.com/gfx-rs/wgpu/wiki) which has information on useful architecture patterns, debugging tips, and more getting started information. +We ship a set of [documentation modules](https://docs.rs/wgpu/latest/wgpu/documentation/index.html) with information on useful architecture patterns, debugging tips, and more getting started information. ### Need Help? Want to Contribute? @@ -75,7 +75,7 @@ Contributors are welcome! See [CONTRIBUTING.md][contrib] for more information. ✅ = First Class Support 🆗 = Downlevel/Best Effort Support -📐 = Requires the [ANGLE](https://github.com/gfx-rs/wgpu/wiki/Running-on-ANGLE) translation layer (GL ES 3.0 only). On macOS/iOS, use the `angle` feature. On Windows, `gles` uses WGL by default; build with `cfg(windows_angle)` to use ANGLE instead. +📐 = Requires the [ANGLE](https://docs.rs/wgpu/latest/wgpu/documentation/platforms/angle/index.html) translation layer (GL ES 3.0 only). On macOS/iOS, use the `angle` feature. On Windows, `gles` uses WGL by default; build with `cfg(windows_angle)` to use ANGLE instead. 🌋 = Requires the [MoltenVK](https://vulkan.lunarg.com/sdk/home#mac) translation layer 🛠️ = Unsupported, though open to contributions @@ -93,7 +93,7 @@ When running the CTS, use the variables `DENO_WEBGPU_ADAPTER_NAME`, `DENO_WEBGPU ## Repo Overview -For an overview of all the components in the gfx-rs ecosystem, see [the big picture](./docs/big-picture.png). +For an overview of all the components in the gfx-rs ecosystem, see [the big picture](./wgpu/src/documentation/images/big-picture.webp). ## MSRV policy diff --git a/deno_webgpu/README.md b/deno_webgpu/README.md index 3cedd111c..d0d90e351 100644 --- a/deno_webgpu/README.md +++ b/deno_webgpu/README.md @@ -11,7 +11,7 @@ spec becomes more concrete, we will implement to follow the spec more closely. In addition, setting the `DENO_WEBGPU_TRACE` environmental variable will output a -[wgpu trace](https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications#tracing-infrastructure) +[wgpu trace](https://docs.rs/wgpu/latest/wgpu/documentation/debugging/debugging_applications/index.html#tracing-infrastructure) to the specified directory. This op crate is tested primarily by running the diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..327f51b75 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,3 @@ +# `wgpu` Contributor Documentation + +This folder contains documentation for contributors of wgpu. If you're looking for user facing documentation, look at for documentation on `trunk` and for the latest release. diff --git a/docs/big-picture.png b/docs/big-picture.png deleted file mode 100644 index 86d754da9..000000000 Binary files a/docs/big-picture.png and /dev/null differ diff --git a/docs/managing-cargo-dependencies.md b/docs/managing-cargo-dependencies.md new file mode 100644 index 000000000..1afd82d24 --- /dev/null +++ b/docs/managing-cargo-dependencies.md @@ -0,0 +1,65 @@ +# Managing Cargo dependencies + +In general, `wgpu` tries to stay up-to-date with the current Rust ecosystem; we are interested in keeping the version of dependency crates we use up-to-date. However, there are some considerations to keep in mind when upgrading or adding dependencies to `wgpu`. + +## Adding or upgrading dependencies may cause dependency duplication downstream + +Some crates in the Rust ecosystem are useful for both `wgpu` and its downstream consumers. Popular crates—like those in the `serde` ecosystem, for example—are often used in multiple places in a Rust crate's dependency tree. Normally, Cargo can unify dependencies behind a single SemVer-compatible version. When one or more, but not all, of these places consume a [SemVer-incompatible upgrade][semver-summary], Cargo uses both in the new dependency tree (see The Cargo Book's section titled [`Version-incompatibility hazards`](https://doc.rust-lang.org/cargo/reference/resolver.html#version-incompatibility-hazards)). These are often referred to as "duplicate dependencies"[^1]. + +[semver-summary]: https://semver.org/spec/v2.0.0.html#summary + +[^1]: One can detect such duplicates with [`cargo tree --duplicates`](https://doc.rust-lang.org/cargo/commands/cargo-tree.html#option-cargo-tree---duplicates). + +There exist many Rust projects that, for some reason or another, are sensitive to duplicate dependencies. The most common reason for this is to minimize the number of built dependencies, but there are other reasons for doing so, like projects that prefer to [vendor in their dependencies' source code](https://doc.rust-lang.org/cargo/commands/cargo-vendor.html) and keep diffs easy to inspect. **When a dependency of `wgpu` releases a SemVer-incompatible change and `wgpu` consumes it (even if it's new _to `wgpu`_), it may cause conflicts for projects that avoid duplicate dependencies.** + +> [!TIP] +> Downstreams like Firefox can and do work around Cargo's (well-motivated) refusal to unify SemVer-incompatible versions of crates, but this happens only on a case-by-case basis. In general, this requires source compatibility for the APIs actually consumed between both versions. + +## Firefox needs to audit every dependency + +In addition to the above, Firefox has unusual sensitivities to updates because of required auditing via [`cargo-vet`](https://github.com/mozilla/cargo-vet). **Firefox contributors _cannot_ bring in a Rust dependency—including new versions of dependencies already in use—without an audit indicating that the dependency meets [`safe-to-deploy`] criteria for _all_ of its feature combinations.** One can ask the following questions to determine whether an upgrade is feasible for Firefox; "yes" answers are significantly easier cases to deal with: + +1. If the dependency had to be audited for [`safe-to-deploy`], would it take less than an hour to review? + + One can use to quickly gauge the answer to this question for upgrades. Example: [`serde` 1.0.218 → 1.0.219](https://diff.rs/serde/1.0.218/1.0.219/src%2Flib.rs) + +1. Does the same code work between the two dependency's versions without needing to be changed (viz., are they "source-compatible")? + + NOTE: This is somewhat different from [SemVer compatibility][semver-summary], because it deals with code already written, rather than SemVer's dealing with code that _might_ be written. + +1. Does the dependency already have an audit in Mozilla's [`supply-chain/audits.toml`](https://searchfox.org/mozilla-central/source/supply-chain/audits.toml) or in the other audit databases it `import`s in [`supply-chain/config.toml`](https://searchfox.org/mozilla-central/source/supply-chain/config.toml)? + +[`safe-to-deploy`]: https://mozilla.github.io/cargo-vet/built-in-criteria.html#safe-to-deploy + +> [!TIP] +> [Searchfox](https://searchfox.org) can be used to answer question (3) and other simple questions with just a web browser. For example: +> +> - "Does Firefox use the `itertools` crate?" can be answered by a case-sensitive search scoped to files with the `rs` extension: https://searchfox.org/mozilla-central/search?q=itertools&path=*.rs&case=true®exp=false +> - "Is `serde` 1.0.143 already audited?" can be answered by examining `supply-chain/audits.toml` ([permalink](https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/supply-chain/audits.toml#4730-4733)). + +> [!TIP] +> For more complicated questions like, "What features does Mozilla use in the `hashbrown` crate?" the best known way to satisfy the question is using Cargo's CLI, i.e., `cargo tree` or `cargo metadata`, in tandem with editing Cargo manifests directly. A Git mirror of Firefox's source code can be found at [`mozilla/gecko-dev`](https://github.com/mozilla/gecko-dev). +> +> A full checkout of `gecko-dev` fills multiple gigabytes, and is not recommended to make one locally unless you plan on doing work directly on Firefox. However, we can optimize to somewhat less than 1 GiB of storage, and speed up the checkout process by using `git sparse-checkout`: +> +> ```sh +> git clone --sparse --depth=1 'https://github.com/mozilla/gecko-dev.git' +> cd gecko-dev +> git sparse-checkout set --no-cone +> git sparse-checkout add \ +> '**/Cargo.toml' \ +> '**/lib.rs' \ +> '**/main.rs' \ +> '**/src/bin/*.rs' \ +> ; +> ``` +> +> From here, you can invoke Cargo with the `--locked` flag, i.e: +> +> ```sh +> cargo --locked tree -i itertools +> ``` +> +> ```sh +> cargo --locked metadata --format-version=1 +> ``` diff --git a/docs/render_coordinates.png b/docs/render_coordinates.png deleted file mode 100644 index c8f544fb9..000000000 Binary files a/docs/render_coordinates.png and /dev/null differ diff --git a/docs/running-tests-on-android-and-ios.md b/docs/running-tests-on-android-and-ios.md new file mode 100644 index 000000000..697279a77 --- /dev/null +++ b/docs/running-tests-on-android-and-ios.md @@ -0,0 +1,165 @@ +# Running the tests on Android and iOS + +An approach of cross-compiling the binaries on a host, then using various tools such as `adb` and `ssh` to transfer the test binaries over to run them, can be used. + +Below are example configuration and runner scripts that can be used to perform this yourself. + +## Android + +
+.cargo/config.toml + +```toml +[target.aarch64-linux-android] +# Runner script is written in powershell +runner = ["pwsh", "-File", "run-on-android.ps1"] +rustflags = [ + "-C", "linker=clang", + "-C", "link-arg=-fuse-ld=lld", + "-C", "link-arg=--target=aarch64-linux-android", + "-C", "link-arg=--sysroot=", + "-C", "link-arg=-B/usr/lib/aarch64-linux-android/", + "-C", "link-arg=-L/usr/lib/aarch64-linux-android/", + "-C", "link-arg=-L/usr/lib/aarch64-linux-android", + "-C", "link-arg=-L/toolchains/llvm/prebuilt//lib/clang/20/lib/linux/aarch64" +] +``` + +
+ +
+run-on-android.ps1 + +```powershell +param( + [string]$BinaryPath +) + +$ErrorActionPreference = "Stop" + +# /data/local/tmp is the most common directory where arbitrary binaries can be run +$RemoteDir = "/data/local/tmp/runner" +$BinaryName = Split-Path -Leaf $BinaryPath +$RemotePath = "$RemoteDir/$BinaryName" + +adb push --sync "$BinaryPath" "$RemotePath" *>$null + +adb shell "chmod 755 $RemotePath" + +$EscapedArgs = $args | ForEach-Object { + if ($_ -match " ") { + "`"$_`"" + } else { + $_ + } +} + +$LinuxArgs = $EscapedArgs -join " " +# Set LD_LIBRARY_PATH to the location of libc++_shared.so +$DeviceCmd = "cd $RemoteDir && LD_LIBRARY_PATH=$RemoteDir ./$BinaryName $LinuxArgs" + +adb shell "$DeviceCmd" +exit $LASTEXITCODE +``` + +
+ +All Android binaries link to `libc++_shared.so`. Remember to put a copy alongside the binaries. + +## iOS + +Apple does not normally provide shell access and `sshd` on their operating system, so jailbreaking the system is required. + +Only a copy of the iOS sysroot is required to cross-compile, so Linux and Windows can also try this. + +
+.cargo/config.toml + +```toml +[target.aarch64-apple-ios] +# Runner script is written in powershell +runner = ["pwsh", "-File", "run-on-ios.ps1"] +rustflags = [ + "-C", "linker=clang", + "-C", "link-arg=-fuse-ld=lld", + "-C", "link-arg=--target=aarch64-apple-ios", + "-C", "link-arg=--sysroot=", + "-C", "link-arg=-miphoneos-version-min=", + "-C", "link-arg=-rpath", + "-C", "link-arg=@executable_path/Frameworks", + "-Lnative=/usr/lib", + "-Lframework=/System/Library/Frameworks", +] +``` + +
+ +If you're on a platform other than macOS, set an environment variable of `SDKROOT` to your sysroot location. + +This avoids `cc-rs` trying to run `xcrun`. + +
+run-on-ios.ps1 + +```powershell +param( + [string]$BinaryPath +) + +$SshTarget = "@" +$BinaryName = Split-Path -Leaf $BinaryPath +# Select one of the following paths depending on rootless or rootful jailbreak +$RemoteDir = "/var/jb/var/mobile/runner" +#$RemoteDir = "/var/root/runner" +$RemotePath = "$RemoteDir/$BinaryName" + +$EscapedArgs = $args | ForEach-Object { + if ($_ -match " ") { + "`"$_`"" + } else { + $_ + } +} + +$LinuxArgs = $EscapedArgs -join " " +$DeviceCmd = "./$BinaryName $LinuxArgs" + +ssh $SshTarget "test -f $RemotePath" + +if ($LASTEXITCODE -ne 0) { + scp -q "$BinaryPath" "$SshTarget`:$RemotePath" + $DeviceCmd = "chmod 755 $BinaryName && ldid -Sent.xml $BinaryName && $DeviceCmd" +} + +ssh $SshTarget "cd $RemoteDir && $DeviceCmd" +exit $LASTEXITCODE +``` + +
+ +Due to iOS security measures, a binary needs to contain specific entitlements to run without a container and access IOKit, so it is required to have the `ldid` tool installed on your target device to set the entitlements with `ent.xml`. It should be placed in your runner directory. + +
+ent.xml + +```xml + + + + platform-application + + com.apple.private.security.container-required + + com.apple.security.iokit-user-client-class + + AGXCommandQueue + AGXDevice + AGXDeviceUserClient + AGXSharedUserClient + IOSurfaceRootUserClient + + + +``` + +
diff --git a/docs/texture_coordinates.png b/docs/texture_coordinates.png deleted file mode 100644 index f3fbbca08..000000000 Binary files a/docs/texture_coordinates.png and /dev/null differ diff --git a/examples/features/src/cooperative_matrix/README.md b/examples/features/src/cooperative_matrix/README.md index 79583dde1..fd6a0f934 100644 --- a/examples/features/src/cooperative_matrix/README.md +++ b/examples/features/src/cooperative_matrix/README.md @@ -4,7 +4,7 @@ This example demonstrates how to use cooperative matrix operations (also known a For the full description of the cooperative matrix feature (supported configurations, WGSL types and operations, validation rules, and backend support), see the central API spec: -- `docs/api-specs/cooperative_matrix.md` +- [`wgpu::documentation::extensions::cooperative_matrices`](https://docs.rs/wgpu/latest/wgpu/documentation/extensions/cooperative_matrices/index.html) ## Example specifics @@ -23,7 +23,7 @@ The example: - A GPU and backend that expose `Features::EXPERIMENTAL_COOPERATIVE_MATRIX` - A configuration returned from `adapter.cooperative_matrix_properties()` that matches the tile size and element types used by this example -- See `docs/api-specs/cooperative_matrix.md` for details on hardware / backend support +- See [`wgpu::documentation::extensions::cooperative_matrices`](https://docs.rs/wgpu/latest/wgpu/documentation/extensions/cooperative_matrices/index.html) for details on hardware / backend support ## Running diff --git a/typos.toml b/typos.toml index 329a0bffd..32df2bad1 100644 --- a/typos.toml +++ b/typos.toml @@ -5,9 +5,10 @@ extend-exclude = [ '/.git', # spirv-asm isn't real source code '*.spvasm', - 'docs/big-picture.xml', + 'wgpu/src/documentation/images/big-picture.xml', # This test has weird pattern-derived variable names. 'naga/tests/in/wgsl/abstract-types-builtins.wgsl', + '*.excalidraw', ] # Corrections take the form of a key/value pair. The key is the incorrect word @@ -40,6 +41,7 @@ D3DCOLORtoUBYTE4 = "D3DCOLORtoUBYTE4" Derivate = "Derivate" inout = "inout" Ect = "Ect" +bve = "bve" [type.wgsl] extend-glob = ["*.wgsl"] diff --git a/wgpu-hal/README.md b/wgpu-hal/README.md index 1ea2f44a3..a4975d8f4 100644 --- a/wgpu-hal/README.md +++ b/wgpu-hal/README.md @@ -112,8 +112,8 @@ secondary backends, so the latter may impose more overhead. ## Debugging -Most of the information on the wiki [Debugging wgpu Applications][wiki-debug] -page still applies to this API, with the exception of API tracing/replay -functionality, which is only available in `wgpu-core`. +Most of the information in the [Debugging wgpu Applications][debug-docs] +documentation still applies to this API, with the exception of API +tracing/replay functionality, which is only available in `wgpu-core`. -[wiki-debug]: https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications +[debug-docs]: https://docs.rs/wgpu/latest/wgpu/documentation/debugging/debugging_applications/index.html diff --git a/wgpu-hal/src/lib.rs b/wgpu-hal/src/lib.rs index 39bc8681c..55174c21a 100644 --- a/wgpu-hal/src/lib.rs +++ b/wgpu-hal/src/lib.rs @@ -196,11 +196,11 @@ //! //! ## Debugging //! -//! Most of the information on the wiki [Debugging wgpu Applications][wiki-debug] -//! page still applies to this API, with the exception of API tracing/replay -//! functionality, which is only available in `wgpu-core`. +//! Most of the information in the [Debugging wgpu Applications][debug-docs] +//! documentation still applies to this API, with the exception of API +//! tracing/replay functionality, which is only available in `wgpu-core`. //! -//! [wiki-debug]: https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications +//! [debug-docs]: https://docs.rs/wgpu/latest/wgpu/documentation/debugging/debugging_applications/index.html #![no_std] #![cfg_attr(docsrs, feature(doc_cfg))] diff --git a/wgpu-types/src/tokens.rs b/wgpu-types/src/tokens.rs index 4472dea43..57dccb212 100644 --- a/wgpu-types/src/tokens.rs +++ b/wgpu-types/src/tokens.rs @@ -1,6 +1,6 @@ use macro_rules_attribute::derive; -use crate::{link_to_wgpu_item, ConstDefault}; +use crate::{link_to_wgpu_docs, link_to_wgpu_item, ConstDefault}; /// Token of the user agreeing to access experimental features. #[derive(Debug, ConstDefault!, Copy, Clone, Eq, PartialEq)] @@ -25,7 +25,7 @@ impl ExperimentalFeatures { /// access to newer technology sooner, and we can work with users /// to fix bugs quicker. /// - /// Look inside our repo at the [`api-specs`] for more information + /// See the [extension documentation][extensions] for more information /// on various experimental apis. /// /// # Safety @@ -35,7 +35,7 @@ impl ExperimentalFeatures { /// - You agree to report any such bugs to us, if you find them. /// #[doc = link_to_wgpu_item!(struct Features)] - /// [`api-specs`]: https://github.com/gfx-rs/wgpu/tree/trunk/docs/api-specs + #[doc = link_to_wgpu_docs!(["extensions"]: "documentation/extensions/index.html")] pub const unsafe fn enabled() -> Self { Self { enabled: true } } diff --git a/wgpu/build.rs b/wgpu/build.rs index cd5316fbd..1198608f2 100644 --- a/wgpu/build.rs +++ b/wgpu/build.rs @@ -62,4 +62,77 @@ fn main() { ) }, no_std: { not(std) } } + + // Expose a `file://` base URL pointing at the crate's + // `src/documentation/images/` directory so that local documentation builds + // resolve images from disk. Because these images live inside the crate, they + // are packaged on publish and this path also resolves when a downstream user + // builds the docs of `wgpu` as a dependency. `docsrs` builds ignore this and + // use an HTTP URL instead; see the `doc_image!` macro in `src/macros/mod.rs`. + // Resolving the path here lets us normalize to forward slashes and pick the + // right number of leading slashes for the host. + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); + let docs_dir = std::path::Path::new(&manifest_dir) + .join("src") + .join("documentation") + .join("images"); + let docs_dir = docs_dir.to_string_lossy().replace('\\', "/"); + let docs_url = if docs_dir.starts_with('/') { + format!("file://{docs_dir}") + } else { + format!("file:///{docs_dir}") + }; + println!("cargo::rustc-env=WGPU_DOCS_URL_BASE={docs_url}"); + + // Pin hosted documentation image URLs (docs.rs and the self-hosted trunk + // docs) to the exact commit being built rather than the moving `trunk` + // branch, so the images never drift from the prose. Only the `docsrs` arm of + // the `doc_image!` macro reads this; local builds use the on-disk path above + // and ignore it, so we deliberately don't add a `rerun-if-changed` on the + // git HEAD — recomputing it on the build script's normal re-runs is enough. + println!( + "cargo::rustc-env=WGPU_DOCS_COMMIT={}", + docs_commit(&manifest_dir) + ); +} + +/// Best-effort lookup of the commit this build corresponds to, for pinning +/// documentation image URLs. +/// +/// Tries `git` first (a local checkout, and the self-hosted trunk docs CI), then +/// the `.cargo_vcs_info.json` that `cargo publish` embeds in the packaged crate +/// (the docs.rs case, where there is no `.git`), and finally falls back to +/// `trunk` so the URLs still resolve. +fn docs_commit(manifest_dir: &str) -> String { + commit_from_git(manifest_dir) + .or_else(|| commit_from_vcs_info(manifest_dir)) + .unwrap_or_else(|| "trunk".to_owned()) +} + +fn commit_from_git(manifest_dir: &str) -> Option { + let output = std::process::Command::new("git") + .args(["rev-parse", "HEAD"]) + .current_dir(manifest_dir) + .output() + .ok()?; + if !output.status.success() { + return None; + } + let sha = String::from_utf8(output.stdout).ok()?.trim().to_owned(); + (!sha.is_empty()).then_some(sha) +} + +fn commit_from_vcs_info(manifest_dir: &str) -> Option { + let path = std::path::Path::new(manifest_dir).join(".cargo_vcs_info.json"); + let contents = std::fs::read_to_string(path).ok()?; + // Minimal extraction of `"sha1": ""`, to avoid pulling a JSON parser + // into the build script. + let sha = contents + .split_once("\"sha1\"")? + .1 + .split_once('"')? + .1 + .split_once('"')? + .0; + (!sha.is_empty()).then(|| sha.to_owned()) } diff --git a/wgpu/src/documentation/best_practices/dos_and_donts.rs b/wgpu/src/documentation/best_practices/dos_and_donts.rs new file mode 100644 index 000000000..812d994d1 --- /dev/null +++ b/wgpu/src/documentation/best_practices/dos_and_donts.rs @@ -0,0 +1,36 @@ +/*! +# Dos and Don'ts + +A short list of common performance pitfalls and the patterns that avoid +them. + +### Don't: create temporary mapped buffers when updating data + +Instead, [`Queue::write_buffer`] and [`Queue::write_texture`] can be used +conveniently. If you are uploading a lot of data that is generated (as +opposed to already sitting in a data vector), it may be more efficient to +recycle staging buffers in a pool. + +### Do: group resource bindings by change frequency, starting from the lowest + +For example, put per-frame resources into bind group 0, per-pass resources +into bind group 1, and per-material resources into bind group 2. This allows +the WebGPU implementation to keep the other bindings intact, reducing state +changes. + +### Don't: create many resources (buffers or textures) per frame + +This puts pressure on the WebGPU memory allocator and tracker. Prefer +coalescing smaller resources into larger ones. For buffers, you can create a +large buffer and use different parts of it for different purposes. For +textures, consider texture atlases and arrays. + +### Don't: submit many times per frame + +There is a visible CPU cost per submission, and resources are tracked per +submission by the implementation. It is fine to have multiple +[`CommandBuffer`]s per submission, but the number of [`Queue::submit`] calls +should be limited to a few per frame (e.g. 1–5). +*/ + +use crate::{CommandBuffer, Queue}; diff --git a/wgpu/src/documentation/best_practices/middleware.rs b/wgpu/src/documentation/best_practices/middleware.rs new file mode 100644 index 000000000..557489c85 --- /dev/null +++ b/wgpu/src/documentation/best_practices/middleware.rs @@ -0,0 +1,104 @@ +/*! +# Encapsulating Graphics Work: the Middleware Pattern + +Whether you are designing a library to be used by others or modularizing +your own code, it is important to be able to encapsulate graphics code in a +way that offers the calling code as much flexibility as possible. + +The following pattern is called the "middleware pattern" and works well both +in separate libraries and in regular modules. + +## Middleware libraries + +Middleware is a piece of software that fits unobtrusively into an existing +application, giving it some extra functionality. In the case of `wgpu`, +middleware are libraries that use the `wgpu` context the user provides to do +their work. If a library creates the `wgpu` adapter, device, etc. for you, +it isn't middleware — it would more likely be called a framework. + +## API design + +This does not have to be the extent of the API; you may have more (or +different) arguments or more functions, but this is the gist of the +interactions with `wgpu`. + +```ignore +impl MiddlewareRenderer { + /// Create all unchanging resources here. + pub fn new(device: &Device, format: &TextureFormat, ..) -> Self; + + /// Prepare for rendering this frame; create all resources that will be + /// used during the next render that do not already exist. + pub fn prepare(&mut self, ..); + + /// Render using a caller-provided render pass. + pub fn render(&self, render_pass: &mut RenderPass<'_>); +} +``` + +The goal of this API is to use as few render passes and submissions as +possible. + +- On GPUs that use _tiled rendering_, there is significant cost to ending a + render pass. Therefore, the middleware should accept an existing + [`RenderPass`] (presuming it is rendering to a surface/texture provided by + the user). + +- [`Queue::submit`] is expensive for `wgpu` to execute. Therefore, if the + middleware generates a [`CommandBuffer`] when preparing, it should hand + that buffer back to the caller to become part of a larger submission, + instead of submitting it alone. + +## Functions + +### New + +```ignore +fn new(device: &Device, format: &TextureFormat, ..) -> Self; +``` + +This is where you create your renderer and set up all the static resources. +Things like pipelines, buffers, or textures should be created and uploaded +here. When the middleware needs to know the parameters of what it is +rendering to, favor accepting a [`TextureFormat`], `width`, and `height` +over a [`SurfaceConfiguration`], as the user may not be rendering to the +surface but to another texture. + +### Prepare + +```ignore +fn prepare(&mut self, ..); +``` + +Ideally there should be a minimal amount of resources created per frame, but +that is often hard to avoid. `prepare()` should create those resources and +do any other computation required to be ready to render. + +### Render + +```ignore +fn render(&self, render_pass: &mut RenderPass<'_>); +``` + +This is where the magic happens! Using the resources created during `new()` +and `prepare()`, render everything using the provided render pass. + +The split between `prepare()` and `render()` is not critical but improves +flexibility. By avoiding borrowing the middleware object exclusively +(`&mut`) during `render()`, the user has more options for organizing their +code; for example, they might want to perform command encoding — including +the middleware's `render()` — in parallel into multiple command buffers, and +this may be easier if the middleware (and therefore whatever owns it) does +not have to be exclusively borrowed. It also means that the order of calls +to `prepare()` of different middleware can be independent of the order of +drawing. + +## Multiple render targets + +If your piece of middleware has to render to multiple targets, it is pretty +unavoidable to have multiple render passes. As much as possible, this +pattern should be used as a guideline for the design of your API, but it +doesn't work for every possible piece of middleware out there. +*/ + +use crate::{CommandBuffer, Queue, RenderPass, SurfaceConfiguration, TextureFormat}; diff --git a/wgpu/src/documentation/best_practices/mod.rs b/wgpu/src/documentation/best_practices/mod.rs new file mode 100644 index 000000000..975588f21 --- /dev/null +++ b/wgpu/src/documentation/best_practices/mod.rs @@ -0,0 +1,8 @@ +/*! +Best Practices + +Patterns and pitfalls for writing efficient, well-structured `wgpu` code. +*/ + +pub mod dos_and_donts; +pub mod middleware; diff --git a/wgpu/src/documentation/color/hdr_surfaces.rs b/wgpu/src/documentation/color/hdr_surfaces.rs new file mode 100644 index 000000000..ac1884c06 --- /dev/null +++ b/wgpu/src/documentation/color/hdr_surfaces.rs @@ -0,0 +1,149 @@ +/*! +# HDR Surfaces + +A surface can present in different color spaces to get HDR or wide-gamut +output onto the screen. This is configured through +[`SurfaceConfiguration::color_space`], and the rest of this section is a +concept primer on how it works. + +### HDR output in a nutshell + +By default a surface is standard dynamic range (SDR) with the sRGB gamut: the +value `1.0` is the brightest white, anything above it clips, and only colors +within sRGB are expressible. Other [`SurfaceColorSpace`]s opt into a **wider +gamut** (for example [`DisplayP3`](SurfaceColorSpace::DisplayP3), still SDR +but with more saturated colors than sRGB), **high dynamic range** (values +above `1.0` drive brighter-than-white output), or both (for example +[`Bt2100Pq`](SurfaceColorSpace::Bt2100Pq), aka HDR10), on platforms that +support it. + +Three ideas carry most of the weight: + +* **Reference white and headroom.** Brightness is measured in *nits* + (cd/m²). On HDR-capable monitors, SDR reference white (plain white, `(1.0, 1.0, 1.0)` in the + extended color spaces) sits *below* the display's peak output on purpose, so + highlights have room above it. That gap is the display's *headroom*. +* **The transfer function is a round-trip.** Your shader applies an + encoding transfer function (the OETF) to turn the light it computed into a + stored signal, and the display applies the inverse decoding transfer + function (the EOTF) to turn it back into light. Choosing a color space + chooses which transfer functions both ends use. +* **Who applies the encoding transfer function.** wgpu applies it for you + **only** when you render to an `*Srgb` texture view format, where the GPU + runs the sRGB OETF when a value is stored to a texture. For every other + color space (linear extended sRGB, encoded extended sRGB or P3, PQ, HLG) + **the values your shader writes to the surface texture must already be + encoded by you**, along with any gamut conversion; in a typical renderer + this happens in a final tone-mapping or post-processing pass. wgpu hands + the signal to the compositor unchanged; getting this wrong produces a + wrong image with no error. + +wgpu does **not** tonemap or gamut-map for you. It gives you the surface +and, through [`DisplayHdrInfo`], the display's advisory capabilities; +*choosing* and *applying* a tone curve is your application's job. + +### The practical path + +1. **Query capabilities.** Call [`Surface::get_capabilities`]. To use HDR or + wide-gamut output, read [`SurfaceCapabilities::format_capabilities`] (each + format and the [`SurfaceColorSpaces`] it supports), **not** + [`SurfaceCapabilities::formats`]: the latter lists only formats usable + with [`Auto`](SurfaceColorSpace::Auto), which never selects HDR. + [`SurfaceCapabilities::color_spaces`] is a convenience lookup for one + format. +2. **Optionally query the display.** Call [`Surface::display_hdr_info`] for the + current [`DisplayHdrInfo`] (peak and SDR-white nits, EDR headroom, + primaries, and a coarse dynamic-range/gamut bucket). Use it to pick a + tone-map target ([`DisplayHdrInfo::tone_map_headroom`]); *whether* HDR is + worthwhile is the capability question from step 1, not this live value. + Every field is advisory and optional; `None` means "cannot tell here", + never "SDR". +3. **Choose a format and color space.** Intersect what you want with what + step 1 advertises, in your own preference order (for example HDR10, then + linear extended sRGB, then encoded extended sRGB, then SDR + [`Srgb`](SurfaceColorSpace::Srgb)). Keep an SDR fallback for when nothing + HDR is advertised, such as when OS HDR is off. +4. **Configure the surface.** Set [`SurfaceConfiguration::color_space`] and + `format`. [`Auto`](SurfaceColorSpace::Auto) (the default) reproduces + wgpu's historical behavior and never picks HDR; any other value must be in + that format's advertised set or configuration fails validation. +5. **Encode what you write to the surface texture.** For an `*Srgb` format, + output linear and the hardware encodes for you. Otherwise the values your + shader writes to the surface texture must already carry the encoding the + chosen color space expects (sRGB, extended sRGB, PQ, or HLG) **and** any + gamut conversion (for example outputting in the BT.2020 gamut for HDR10); + in a typical renderer you do this in a final tone-mapping or + post-processing pass. See the table below. +6. **Present** as usual. If OS HDR is toggled mid-run, you'll see it on the + next [`Surface::display_hdr_info`] poll; re-query [`Surface::get_capabilities`] + and re-run the steps above. + +The standalone [HDR surface example] implements every step, including the +encoding transfer function for each color space. + +### What to output from your fragment shader + +What the values your shader writes to the surface texture must contain for +each color space, and whether wgpu applies the transfer function for you: + +| Color space | Typical format | You write | wgpu encodes? | +| ----------- | -------------- | --------- | ------------- | +| `Srgb`, `*Srgb` format | `{Rgba,Bgra}8UnormSrgb` | linear | **yes** (hardware sRGB OETF on store) | +| `Srgb`, non-srgb format | `{Rgba,Bgra}8Unorm` | sRGB-encoded | no; apply the sRGB OETF yourself or use `*Srgb` instead | +| `ExtendedSrgbLinear` (scRGB) | `Rgba16Float` | linear, `1.0` = SDR white | no, but no encoding is necessary | +| `ExtendedSrgb` | `Rgba16Float` | extended sRGB-encoded | no; apply the extended sRGB OETF yourself | +| `DisplayP3` | `Bgra8Unorm` | sRGB-encoded, P3 primaries | no; apply the sRGB OETF (after gamut-mapping to P3) | +| `ExtendedDisplayP3` | `Rgba16Float` | extended sRGB-encoded, P3 primaries | no; apply the extended sRGB OETF (after gamut-mapping to P3) | +| `Bt2100Pq` (HDR10) | `Rgb10a2Unorm` | PQ-encoded, BT.2020 primaries | no; apply the PQ OETF (after gamut-mapping to BT.2020) | +| `Bt2100Hlg` | `Rgb10a2Unorm` | HLG-encoded, BT.2020 primaries | no; apply the HLG OETF (after gamut-mapping to BT.2020) | + +In short, wgpu applies the transfer function for you only when you render to +an `*Srgb` format. In every other case the values your shader writes to the +surface texture must already carry both the transfer function and any gamut +conversion. The [HDR surface example] implements every encoder in WGSL. + +### Glossary + +* **Chromaticity** --- a color's hue and saturation independent of its + brightness, given as an `(x, y)` coordinate on the CIE 1931 diagram. +* **Primaries / gamut** --- the chromaticities of the red, green, and blue a + color space addresses, and so the range of colors it can express. [BT.709] + is the sRGB gamut, [Display P3] is wider, and [BT.2020] is wider still. +* **White point** --- the chromaticity of `R = G = B` (what "white" looks + like). Every color space here uses [D65], standard daylight. +* **Transfer function (OETF / EOTF)** --- how stored values map to light. The + *OETF* is the encoding transfer function your application applies; the + *EOTF* is the inverse decoding transfer function the display applies. +* **SDR / HDR** --- standard dynamic range clips at `1.0` (reference white); + high dynamic range lets values above `1.0` drive brighter-than-white + output. +* **Nits and reference white** --- a *nit* (cd/m²) is a unit of brightness; + *reference white* (also called *paper white*, especially on Windows) is the + brightness of SDR plain white, set below the panel's peak so highlights have + room above it. +* **Headroom (EDR)** --- how much brighter than current SDR white the display + can go right now, as a multiplier (`1.0` means none). Dynamic; see + [`DisplayHdrInfo::tone_map_headroom`]. +* **PQ / HLG** --- the two HDR transfer functions: [PQ] (SMPTE ST 2084, + HDR10) encodes absolute luminance, [HLG] (BT.2100) encodes relative + luminance. +* **scRGB / extended-range sRGB** --- sRGB extended past 0.0..=1.0 for + HDR: [scRGB] is *linear* + ([`ExtendedSrgbLinear`](SurfaceColorSpace::ExtendedSrgbLinear)), while + [`ExtendedSrgb`](SurfaceColorSpace::ExtendedSrgb) is the same range but + sRGB-*encoded* (gamma), the web's HDR path. + +[HDR surface example]: https://github.com/gfx-rs/wgpu/tree/v29/examples/standalone/03_hdr_surface +[BT.709]: https://www.itu.int/rec/R-REC-BT.709 +[BT.2020]: https://www.itu.int/rec/R-REC-BT.2020 +[Display P3]: https://en.wikipedia.org/wiki/DCI-P3#Display_P3 +[D65]: https://en.wikipedia.org/wiki/Standard_illuminant#D65_values +[PQ]: https://en.wikipedia.org/wiki/Perceptual_quantizer +[HLG]: https://www.itu.int/rec/R-REC-BT.2100 +[scRGB]: https://en.wikipedia.org/wiki/ScRGB +*/ + +use crate::{ + DisplayHdrInfo, Surface, SurfaceCapabilities, SurfaceColorSpace, SurfaceColorSpaces, + SurfaceConfiguration, +}; diff --git a/wgpu/src/documentation/color/mod.rs b/wgpu/src/documentation/color/mod.rs new file mode 100644 index 000000000..d3067a435 --- /dev/null +++ b/wgpu/src/documentation/color/mod.rs @@ -0,0 +1,6 @@ +/*! +Articles about HDR, color, and color spaces. +*/ + +pub mod hdr_surfaces; +pub mod srgb; diff --git a/wgpu/src/documentation/color/srgb.rs b/wgpu/src/documentation/color/srgb.rs new file mode 100644 index 000000000..7a5f180a2 --- /dev/null +++ b/wgpu/src/documentation/color/srgb.rs @@ -0,0 +1,119 @@ +/*! +# Texture Color Formats and sRGB Conversions + +Tips and common misconceptions about color formats. For surface output, +wide-gamut, and high-dynamic-range color, see +[HDR and Wide-Gamut Color Spaces](crate::documentation::color::hdr_surfaces). + +_(The following is adapted from conversations on the `wgpu` users Matrix +channel, saved here as a useful resource for future `wgpu` developers.)_ + +Digital color can be an extremely confusing topic, and the resources in +common circulation aren't always great. Modern low-level graphics APIs (such +as those under the hood of `wgpu`) give us powerful tools to manipulate color +data, though this comes at the cost of having to understand several low-level +principles in how digital color works. + +The best place to start is to have an understanding of the problems and +history of gamma correction. This page won't go deeply into the topic, but +some useful links can be found here: + +- [What every coder should know about gamma](https://blog.johnnovak.net/2016/09/21/what-every-coder-should-know-about-gamma/) +- [Hitchhiker's Guide to Digital Color](https://hg2dc.com/) +- [Learn OpenGL — Gamma Correction](https://learnopengl.com/Advanced-Lighting/Gamma-Correction) + +## What do `TextureFormat`s do? + +There are many different texture formats you can specify for the format of +your color data. This can be image data you upload from the CPU, shaded +geometry rendered to intermediate textures (what we used to call frame +buffers in OpenGL), compute shader targets, or geometry shaded to the window +surface itself. + +We won't go into all the different formats here, but it's useful to talk +about two of the most commonly used formats and some misconceptions about +what they do (and don't) do. + +## What are Unorm and UnormSrgb? + +Some of the most common formats you will see used for texture data, render +targets, etc. are [`Rgba8Unorm`](TextureFormat::Rgba8Unorm) and +[`Rgba8UnormSrgb`](TextureFormat::Rgba8UnormSrgb). So what are they, and how +do they relate to the issues of gamma correction, perceptually-linear "sRGB" +space, and physically-accurate "linear" space (as described in detail in the +links above)? + +First of all, it will be useful to clarify some terminology, as the words +"linear" and "sRGB" can be overloaded and lead to confusion: + +- **sRGB space** is a set of color primaries — this defines what red, green, + and blue are. + +In this sense (and perhaps counter-intuitively), texture formats ending in +"Unorm" and "UnormSrgb" are BOTH in the sRGB color space, and encode their +data in the same way without losing precision (as might be implied by some +descriptions of "linear" vs. "sRGB"); more on this later. + +Here is some useful terminology to help avoid "linear" and "sRGB" confusion: + +- What we traditionally called "linear space" is more accurately called + "scene-referred color". +- What we traditionally called "sRGB space" is more accurately called + "monitor-referred color". +- The conversion from scene-referred color to monitor-referred color is done + by the sRGB OETF (opto-electrical transfer function \[light → bits\]). +- The conversion from monitor-referred color to scene-referred color is done + by the sRGB EOTF (electro-optical transfer function \[bits → light\]). + +Let's walk our way up the color pipeline. The OS assumes that the bits you +are sending to the screen are monitor-referred and in the sRGB space (unless +otherwise specified). It will interpret the bits this way no matter what. + +- If you write/shade to a texture which is in a **Unorm** format, it will + take the output of your shader and do a float → int conversion, and that's + it (Unorm floats are written as ints under the hood, though you don't need + to worry about this). + + This means that if you're using this **Unorm** texture as a surface, *the + floats you are writing from your shader need to be **monitor-referred*** (i.e. + numbers that the OS can safely assume are already in sRGB space). + +- If you write/shade to a texture which is in a **UnormSrgb** format, it will + take the output of your shader and then apply the sRGB OETF to it, then + afterwards do the float → int conversion to store the data. + + This means that if you're using this **UnormSrgb** texture as a surface, + *the floats you are writing from your shader need to be **scene-referred***, + as the GPU will do the conversion to monitor-referred as part of the write! + +The inverse happens when you read from a texture: + +- a **Unorm** texture just does int → float on read. +- a **UnormSrgb** texture applies the sRGB EOTF to do monitor → scene and + then does the int → float read. + +## Common misconceptions + +**Q: So Unorm textures are in "linear" space and UnormSrgb textures are in +"sRGB" space?** + +**A:** No. Despite the naming, you are responsible for whether the outputs of +your shader represent "scene"- or "monitor"-referred values. The "Srgb" tag on +the texture format just lets the shader know that you want it to do a +conversion from sRGB to linear (or, more specifically, "monitor" to "scene") +when you sample it, or the inverse when you write to it. + +## Tips + +- Think of texture formats as a combination of data resolution and data + conversion functions. For example: + [`Rgba8UnormSrgb`](TextureFormat::Rgba8UnormSrgb) = `Rgba8` data + + `UnormSrgb` conversion step. +- Let the GPU do the conversion work for you. Historically in WebGL, for + example, if you wanted to do physically-accurate lighting you would need to + convert from linear to sRGB manually (often with an approximation like + `pow(col, 2.2)`). By being aware of the textures you are sampling and + writing to, you should be able to avoid manual conversions. +*/ + +use crate::TextureFormat; diff --git a/wgpu/src/documentation/debugging/debugging_applications.rs b/wgpu/src/documentation/debugging/debugging_applications.rs new file mode 100644 index 000000000..3a4778300 --- /dev/null +++ b/wgpu/src/documentation/debugging/debugging_applications.rs @@ -0,0 +1,178 @@ +/*! +# Debugging wgpu Applications + +This page describes the tricks and tools aimed at investigating issues +related to `wgpu`. + +## Native API validation + +`wgpu`'s goal is to guarantee that only valid workloads reach the low-level +APIs under the hood. If anything is not correct, we are going to complain +about it. You should never need to listen to the low-level API's complaints. + +This is a big [work-in-progress](https://github.com/gfx-rs/wgpu/labels/area%3A%20validation), +however. So in the meantime, it's useful to hear what the low-level +validation has to say. + +### Vulkan and OpenGL + +On Khronos APIs we redirect all the validation output to the console. You +will see it as long as: + +1. you run a debug build, +2. you have the validation layers installed (i.e. the LunarG SDK), and +3. you capture logging (with something like + [`env_logger`](https://crates.io/crates/env_logger)). + +To enable the validation layers in non-debug builds, manually turn on +validation in the [`InstanceDescriptor`] with [`InstanceFlags::VALIDATION`]. +See also [Enabling Vulkan Validation Layers](crate::documentation::debugging::vulkan_validation_layers). + +### D3D + +#### COM + +The refcount of a COM object is 9 32-bit words behind the pointer's +destination and is 4 bytes. As such, subtract 36 from the pointer's address +to get a pointer to that object's refcount. This allows you to use data +breakpoints to see all changes to the object's refcount, useful for +detecting leaks and other such things. + +### Metal + +You can either set `METAL_DEVICE_WRAPPER_TYPE=1` in the environment, or +launch from Xcode, where validation options are configurable in the project +menus (and enabled by default). To launch from Xcode, you can create a +project of "External Build System" type, picking `cargo` or any other +command as the build system. Then you'd need to edit the target +configuration and select the executable. + +A full guide that explains how to launch from Xcode is available in +[Debugging with Xcode](crate::documentation::debugging::xcode). + +#### Mac leaks + +To look for leaks using "Instruments", you need to add a special entitlement +to your executable's signature. Write the following to `entitle.xml`: + +```xml + + + + + com.apple.security.get-task-allow + + + +``` + +Then run `codesign -s - -v -f --entitlements=entitle.xml /path/to/my/app`. + +([Source](https://stackoverflow.com/questions/74262518/why-required-kernel-recording-resources-are-in-use-by-another-document-error-i).) + +## GPU debugging + +If the validation is clean, and you are getting incorrect rendering or +computing, it's time to dive into GPU debugging. Many tools exist today: + +- RenderDoc can be used on Windows and Linux to capture Vulkan, D3D, and + OpenGL. + - If RenderDoc is used with a compute shader without any normal rendering + components, wrap the work in [`Device::start_graphics_debugger_capture`] + and [`Device::stop_graphics_debugger_capture`] so RenderDoc picks up the + pipeline. + - Vulkan initialization may fail in RenderDoc under Wayland (see + [issue 3889](https://github.com/gfx-rs/wgpu/issues/3889)). To work around + it, force winit to use X11 by setting the `WAYLAND_DISPLAY` environment + variable to an empty string for winit versions `0.28.2` and onward, or + the `WINIT_UNIX_BACKEND` environment variable to `"x11"` for winit + versions up to `0.29.1`. When in doubt, do both. +- PIX can be used on Windows to capture D3D12. +- Xcode has powerful Metal GPU capture support with full shader debugging. + +In order to run your application from Xcode, you can create an empty project, +select your executable binary, and provide the command-line parameters in +the project settings. + +### Capturing WebGPU in Chrome with PIX + + + +### Capturing WebGPU in Chrome with Xcode + + + +## CPU debugging + +As `wgpu` is a Rust project, all the regular methods of debugging work. It's +convenient to launch an application from Xcode (e.g. as an "External Build +System" type project), or Visual Studio (just go to "Open Project" and +select the executable, adjusting the path and parameters). + +When looking at a crash/panic, the first step is typically enabling +`RUST_BACKTRACE=1` in the environment. This will spew out the stack trace, +which helps you locate the problem. + +## Rubber-duck debugging + +Hop on to [`#wgpu:matrix.org`](https://matrix.to/#/#wgpu:matrix.org) and try +to explain what happens and why. Maybe we listen. Maybe you'll figure out +the answer by then ;) + +## Tracing infrastructure + +API tracing is built into `wgpu-core` under the `trace` feature. To record a +trace, first make sure this feature is enabled, then set the `trace` field +of the [`DeviceDescriptor`] to [`Trace::Directory`](crate::Trace) with an existing folder +path when calling [`Adapter::request_device`]. The device will then record a +trace of everything that's going on to that folder. + +Once the trace is recorded, you can zip the folder and attach it to an +issue. This should allow anyone, including the developers, to reproduce the +issue on their machines, using the `player`: + +```bash +cd player +cargo run --features winit -- +``` + +If the program crashed or was interrupted in the midst of recording, you may +need to edit the trace folder's `trace.ron` file and add a closing `]` +bracket to the end. When that bracket is missing, the player exits with a +message like: + +```text +thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: +Error { code: Eof, position: Position { line: 96233, col: 1 } }', player/src/bin/play.rs:28:70 +``` + +### Running in Gecko + +If you encounter a problem with something that runs fine outside of Gecko +but fails to run in Gecko, there is a way to trace the API use by the +browser. Simply run Firefox Nightly (with prefs enabled for WebGPU, +obviously) under `WGPU_TRACE` pointing to a writable folder, and it will +record the API trace. Setting `MOZ_DISABLE_GPU_SANDBOX=1` might also be +required if the GPU process is sandboxed by default. This trace can be +replayed as usual, or even compared to a trace you get by running the same +application natively, to find out what the browser doesn't do right. + +To replay a capture from Firefox and inspect it in RenderDoc or similar +tools, it is best not to build the player with the `winit` cargo feature. + +When Firefox renders a WebGPU canvas, the result is done in a texture rather +than a window's swapchain, and that texture is then shared and put onto the +screen via other means that aren't part of the `wgpu` trace. Since there is +no window swapchain involved, RenderDoc can't guess when a frame starts and +ends, so it has to be helped by manually inserting begin/end capture +markers. When built without the `winit` feature, the player replays the +commands without rendering them into a window, and adds these markers at the +beginning and end of the trace; it doesn't when the `winit` feature is +enabled, since it then assumes the trace will eventually render into the +winit window's swapchain. + +This applies to Firefox as well as any other software using `wgpu` to render +content into a texture but not to present that texture into a window. +*/ + +use crate::{Adapter, Device, DeviceDescriptor, InstanceDescriptor, InstanceFlags, Trace}; diff --git a/wgpu/src/documentation/debugging/mod.rs b/wgpu/src/documentation/debugging/mod.rs new file mode 100644 index 000000000..d3924c351 --- /dev/null +++ b/wgpu/src/documentation/debugging/mod.rs @@ -0,0 +1,11 @@ +/*! +Debugging + +Tools and techniques for investigating correctness, validation, and +performance problems in `wgpu` applications. +*/ + +pub mod debugging_applications; +pub mod performance; +pub mod vulkan_validation_layers; +pub mod xcode; diff --git a/wgpu/src/documentation/debugging/performance.rs b/wgpu/src/documentation/debugging/performance.rs new file mode 100644 index 000000000..7888ab5be --- /dev/null +++ b/wgpu/src/documentation/debugging/performance.rs @@ -0,0 +1,16 @@ +/*! +# Debugging Performance Issues + +If you're encountering performance problems, here's a checklist: + +- Are you building with `--release`? (Don't laugh!) Development-profile + builds trade overhead for diagnostic ability: + - [`InstanceFlags::DEBUG`] is set by default in development builds, which + enables platform-level validation, like the Vulkan validation layers. + - The Rust compiler doesn't optimize the generated machine code. + - Development builds have more assertions enabled. + +Please add more checklist items, based on your experience. +*/ + +use crate::InstanceFlags; diff --git a/wgpu/src/documentation/debugging/vulkan_validation_layers.rs b/wgpu/src/documentation/debugging/vulkan_validation_layers.rs new file mode 100644 index 000000000..20acbe16f --- /dev/null +++ b/wgpu/src/documentation/debugging/vulkan_validation_layers.rs @@ -0,0 +1,57 @@ +/*! +# Enabling Vulkan Validation Layers + +When developing an application it is often useful to enable Vulkan's +validation layers. They can catch errors when you are using the API +incorrectly or exceeding device limits. You can read more about validation +layers here: . + +Validation layers are a Vulkan-only feature, so they cannot be used with +other backends. You can restrict which backends `wgpu` uses via +[`InstanceDescriptor`] and [`Backends`]. + +## Installation + +For validation layers to work you need to install the Vulkan SDK: + +### Linux + +Visit to install the Vulkan SDK along with +some validation layers. Click the "Latest Supported Release" button (which +looks like it's just a header, but it is in fact a button) and follow the +instructions. + +### Other operating systems + +TODO. + +## Enabling validation layers + +`wgpu` enables validation layers automatically in most cases when the +application is compiled in debug mode (that is, if the `--release` flag is +*not* passed to `cargo`), because [`InstanceFlags::DEBUG`] is set by default +in development builds. You can also enable them explicitly with +[`InstanceFlags::VALIDATION`], or by setting the environment variable +`VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation`. + +The validation layers use normal Rust logging functionality, which also +needs to be enabled. The `wgpu` examples use the +[`env_logger`](https://crates.io/crates/env_logger) crate for logging, which +means you can enable validation-layer logging by setting an environment +variable: + +```bash +env RUST_LOG=trace cargo run --bin wgpu-examples cube +``` + +There are several logging levels (see for +more info), with `trace` being the highest. If you choose a lower level such +as `info`, then fewer messages will be logged. + +If you want to enable validation layers in your own application, make sure +it has logging configured. The +[`env_logger`](https://crates.io/crates/env_logger) crate is one possible +way to do this. +*/ + +use crate::{Backends, InstanceDescriptor, InstanceFlags}; diff --git a/wgpu/src/documentation/debugging/xcode.rs b/wgpu/src/documentation/debugging/xcode.rs new file mode 100644 index 000000000..c7cb7eb0f --- /dev/null +++ b/wgpu/src/documentation/debugging/xcode.rs @@ -0,0 +1,80 @@ +#![doc = crate::macros::doc_image!("xcode-new-project.webp")] +#![doc = crate::macros::doc_image!("xcode-project-type.webp")] +#![doc = crate::macros::doc_image!("xcode-build-tool.webp")] +#![doc = crate::macros::doc_image!("xcode-edit-scheme.webp")] +#![doc = crate::macros::doc_image!("xcode-scheme-options.webp")] +#![doc = crate::macros::doc_image!("xcode-scheme-arguments.webp")] +#![doc = crate::macros::doc_image!("xcode-select-binary.webp")] +#![doc = crate::macros::doc_image!("xcode-play-button.webp")] +#![doc = crate::macros::doc_image!("xcode-attached.webp")] +#![doc = crate::macros::doc_image!("xcode-start-capture.webp")] +/*! +# Debugging with Xcode (Metal GPU Capture) + +Xcode provides powerful Metal GPU capture and shader debugging tools. This +page walks through attaching Xcode to a `wgpu` application so you can enable +Metal validation and capture frames. + +A Chinese version is also available: +[使用 Xcode 调试 wgpu 程序](https://jinleili.github.io/learn-wgpu-zh/integration-and-debugging/ios/#xcode-%E4%B8%8E-metal). + +First we'll start by opening Xcode and creating a new project using the menu +or "Create a new Xcode project" in the startup dialog. + +![Xcode startup dialog][xcode-new-project.webp] + +Select "External Build System" as the project type. + +![Xcode project type][xcode-project-type.webp] + +Choose which build tool to use in the "Build Tool" field. This will be +called whenever we build in Xcode. + +We can write our `cargo` build command here if we'd like Xcode to run it, +but we could also skip the build step to avoid Xcode building the project +for us. + +It's possible to skip the build step by specifying our build command as +`ls`, `echo`, or anything else that exits successfully (note: `:` doesn't +appear to work here). + +The rest of the fields don't actually matter to us, so we can put any values +there. + +![Xcode build tool][xcode-build-tool.webp] + +Click on the project name and then click "Edit Scheme". + +![Xcode edit scheme][xcode-edit-scheme.webp] + +Under the "Options" tab we can choose the level of validation for Metal and +whether to enable GPU frame capture. + +![Xcode scheme options][xcode-scheme-options.webp] + +Under the "Arguments" tab we'll choose which executable to run. We want this +to be the binary created by `cargo`. We'll select "Other" and then find the +binary in the target directory. + +![Xcode scheme arguments][xcode-scheme-arguments.webp] + +![Xcode select binary][xcode-select-binary.webp] + +Next we'll click the play button to run our binary and attach Xcode to it. + +![Xcode play button][xcode-play-button.webp] + +Now we should see our application running and some output telling us that +Metal validation has been enabled. + +![Xcode attached][xcode-attached.webp] + +To start a GPU capture, click the camera button while Xcode is attached to +our running application. + +![Xcode start capture][xcode-start-capture.webp] + +After a frame has been captured, we will be able to use all the regular +Metal tools (e.g. shader debugging, GPU statistics, etc.). + +*/ diff --git a/docs/api-specs/cooperative_matrix.md b/wgpu/src/documentation/extensions/cooperative_matrices.rs similarity index 95% rename from docs/api-specs/cooperative_matrix.md rename to wgpu/src/documentation/extensions/cooperative_matrices.rs index 20dbd3a39..335c11482 100644 --- a/docs/api-specs/cooperative_matrix.md +++ b/wgpu/src/documentation/extensions/cooperative_matrices.rs @@ -1,8 +1,7 @@ -# Cooperative Matrix Extensions +/*! +# 🧪Experimental🧪 Cooperative Matrix Extensions -🧪Experimental🧪 - -`wgpu` supports an experimental cooperative matrix feature when `Features::EXPERIMENTAL_COOPERATIVE_MATRIX` is enabled. +`wgpu` supports an experimental cooperative matrix feature when [`Features::EXPERIMENTAL_COOPERATIVE_MATRIX`] is enabled. This exposes hardware-accelerated matrix multiply-accumulate (MMA) operations (for example, NVIDIA tensor cores, Metal SIMD-group matrices, and Vulkan `VK_KHR_cooperative_matrix`). @@ -63,7 +62,7 @@ Each `CooperativeMatrixProperties` describes a single supported configuration. F Example usage: -```/dev/null/cooperative-matrix-host.rs#L1-40 +```ignore let coop_props = adapter.cooperative_matrix_properties(); for prop in &coop_props { println!( @@ -77,7 +76,7 @@ for prop in &coop_props { You **must**: -1. Enable `Features::EXPERIMENTAL_COOPERATIVE_MATRIX` on the `Device`. +1. Enable [`Features::EXPERIMENTAL_COOPERATIVE_MATRIX`] on the `Device`. 2. Query `adapter.cooperative_matrix_properties()` and ensure that the configuration(s) you intend to use in WGSL are actually available on the running adapter/backend. 3. Treat the sizes and types as a contract between your shaders and the underlying hardware implementation. @@ -90,7 +89,7 @@ You **must**: ### `wgpu` feature - Using cooperative matrices requires enabling: - - `Features::EXPERIMENTAL_COOPERATIVE_MATRIX` + - [`Features::EXPERIMENTAL_COOPERATIVE_MATRIX`] This feature may be restricted to certain backends and hardware. @@ -107,7 +106,7 @@ These are general guidelines, not a complete compatibility matrix: - Requires the `VK_KHR_cooperative_matrix` extension. - Many NVIDIA and AMD GPUs support `f16` at 16×16 tile sizes and similar. - 8×8 `f32` support is hardware-dependent. - - Exact configurations are enumerated by `Adapter::cooperative_matrix_properties()`. + - Exact configurations are enumerated by [`Adapter::cooperative_matrix_properties()`]. - **Other backends**: - May not support cooperative matrices at all. In that case the feature will not be exposed, and @@ -156,7 +155,7 @@ may change; the details below describe the intended semantics. Any WGSL program using cooperative matrices must declare an extension at the top of the shader, for example: -```/dev/null/example.wgsl#L1-3 +```wgsl enable wgpu_cooperative_matrix; ``` @@ -175,7 +174,7 @@ A cooperative matrix is a value type parameterized by: Conceptually: -```/dev/null/example.wgsl#L1-8 +```wgsl // A: MxK, B: KxN, C: MxN type coop_matMxN; type coop_matMxN; @@ -185,7 +184,7 @@ type coop_matMxN; Concrete examples (sizes and types must match a supported configuration from `Adapter::cooperative_matrix_properties`): -```/dev/null/example.wgsl#L10-20 +```wgsl // 8x8 single-precision tiles alias CoopMatA = coop_mat8x8; alias CoopMatB = coop_mat8x8; @@ -233,7 +232,7 @@ select the memory layout: `stride` is the number of elements between adjacent rows. This is the natural fit for C-style `ptr[i * num_cols + j]` storage. -```/dev/null/example.wgsl#L1-10 +```wgsl fn coopLoad( ptr: ptr, // base pointer to scalar or vector elements stride: u32 // elements between adjacent columns @@ -260,7 +259,7 @@ selection mirrors the load builtins: - `coopStore` — writes **column-major**; `stride` between columns. - `coopStoreT` — writes **row-major**; `stride` between rows. -```/dev/null/example.wgsl#L12-23 +```wgsl fn coopStore( value: coop_matMxN, ptr: ptr, @@ -282,7 +281,7 @@ fn coopStoreT( Perform a matrix multiply-accumulate operation on cooperative matrices: -```/dev/null/example.wgsl#L15-23 +```wgsl fn coopMultiplyAdd( a: coop_matMAxKA, // A: MAxKA tile b: coop_matKBxNB, // B: KBxNB tile (KB == KA) @@ -302,7 +301,7 @@ Semantics: For example, with a supported configuration: -```/dev/null/example.wgsl#L25-39 +```wgsl enable wgpu_cooperative_matrix; alias MatA = coop_mat8x8; @@ -354,7 +353,7 @@ For portable code: Example: -```/dev/null/example.wgsl#L1-42 +```wgsl enable wgpu_cooperative_matrix; struct Matrices { @@ -405,7 +404,7 @@ Implementations must validate the following where possible: - The `wgpu_cooperative_matrix` WGSL extension is enabled if any cooperative matrix types or builtins are used. - Tile sizes `(M, N, K)` and scalar types `(ab_type, cr_type)` match at least one - `CooperativeMatrixProperties` entry for the current adapter/backend. + [`CooperativeMatrixProperties`] entry for the current adapter/backend. - Workgroup size, shader stage, and other pipeline configuration constraints required by the backend are satisfied. @@ -413,7 +412,7 @@ The following are examples of **undefined behavior** (non-exhaustive): - Using cooperative matrix operations without enabling the WGSL extension. - Using a cooperative matrix type `(M, N, T, R)` not supported by - `Adapter::cooperative_matrix_properties()`. + [`Adapter::cooperative_matrix_properties()`]. - Mismatching sizes or roles in `coopMultiplyAdd` (e.g. incompatible M/N/K, or incorrect roles). - Executing `coopLoad` / `coopLoadT`, `coopStore` / `coopStoreT`, or `coopMultiplyAdd` in divergent control flow within the cooperating execution group. @@ -451,7 +450,7 @@ Key points from the example: - Workgroup size is chosen so that all cooperative operations are well-defined and efficient for 8×8 tiles. - Host-side code: - - Enables `Features::EXPERIMENTAL_COOPERATIVE_MATRIX`. + - Enables [`Features::EXPERIMENTAL_COOPERATIVE_MATRIX`]. - Queries `cooperative_matrix_properties` and verifies that 8×8 `f32` or chosen configuration is supported. - Dispatches the compute pipeline with appropriate grid dimensions. @@ -466,3 +465,7 @@ Key points from the example: - Avoid divergent control flow around cooperative operations. - Consider providing a fallback non-cooperative implementation for devices that do not support the feature. - This is an experimental extension; API and semantics may change across versions of `wgpu` and `naga`. + +*/ + +use crate::{Adapter, CooperativeMatrixProperties, Features}; diff --git a/docs/api-specs/mesh_shading.md b/wgpu/src/documentation/extensions/mesh_shading.rs similarity index 90% rename from docs/api-specs/mesh_shading.md rename to wgpu/src/documentation/extensions/mesh_shading.rs index 4b9e7a741..d0ef2762a 100644 --- a/docs/api-specs/mesh_shading.md +++ b/wgpu/src/documentation/extensions/mesh_shading.rs @@ -1,8 +1,7 @@ -# Mesh Shader Extensions +/*! +# 🧪Experimental🧪 Mesh Shading -🧪Experimental🧪 - -`wgpu` supports an experimental version of mesh shading when `Features::EXPERIMENTAL_MESH_SHADER` is enabled. +`wgpu` supports an experimental version of mesh shading when [`Features::EXPERIMENTAL_MESH_SHADER`] is enabled. The status of the implementation is documented in [the mesh-shading issue](https://github.com/gfx-rs/wgpu/issues/7197). **Note**: The features documented here may have major bugs in them and are expected to be subject @@ -69,19 +68,20 @@ With the current pipeline set to a mesh pipeline, a draw command like ### New `wgpu` functions -`Device::create_mesh_pipeline` - Creates a mesh shader pipeline. This is very similar to creating a standard render pipeline, except that it takes a mesh shader state and optional task shader state instead of a vertex state. If the task state is omitted, during rendering the number of workgroups is passed directly from the draw call to the mesh shader state, with an empty payload. +[`Device::create_mesh_pipeline`] - Creates a mesh shader pipeline. This is very similar to creating a standard render pipeline, except that it takes a mesh shader state and optional task shader state instead of a vertex state. If the task state is omitted, during rendering the number of workgroups is passed directly from the draw call to the mesh shader state, with an empty payload. -`RenderPass::draw_mesh_tasks` - Dispatches the mesh shader pipeline. This ignores render pipeline specific information, such as vertex buffer bindings and index buffer bindings. The dispatch size must adhere to the limits described below. +[`RenderPass::draw_mesh_tasks`] - Dispatches the mesh shader pipeline. This ignores render pipeline specific information, such as vertex buffer bindings and index buffer bindings. The dispatch size must adhere to the limits described below. -`RenderPass::draw_mesh_tasks_indirect`, `RenderPass::multi_draw_mesh_tasks_indirect` and `RenderPass::multi_draw_mesh_tasks_indirect_count` - Dispatches the mesh shader pipeline with dispatch size taken from a buffer. This ignores render pipeline specific information, such as vertex buffer bindings and index buffer bindings. The dispatch size must adhere to the limits described below. Analogous to `draw_indirect`, `multi_draw_indirect` and `multi_draw_indirect_count`. Requires the corresponding indirect feature to be enabled. +[`RenderPass::draw_mesh_tasks_indirect`], [`RenderPass::multi_draw_mesh_tasks_indirect`] and [`RenderPass::multi_draw_mesh_tasks_indirect_count`] - Dispatches the mesh shader pipeline with dispatch size taken from a buffer. This ignores render pipeline specific information, such as vertex buffer bindings and index buffer bindings. The dispatch size must adhere to the limits described below. Analogous to `draw_indirect`, `multi_draw_indirect` and `multi_draw_indirect_count`. Requires the corresponding indirect feature to be enabled. -An example of using mesh shaders to render a single triangle can be seen [here](../../examples/features/src/mesh_shader). +An example of using mesh shaders to render a single triangle can be seen +[here](https://github.com/gfx-rs/wgpu/tree/trunk/examples/features/src/mesh_shader). ### Features -- Using mesh shaders requires enabling `Features::EXPERIMENTAL_MESH_SHADER`. -- Using mesh shaders with multiview requires enabling `Features::EXPERIMENTAL_MESH_SHADER_MULTIVIEW`. -- Using mesh shaders with point primitives requires enabling `Features::EXPERIMENTAL_MESH_SHADER_POINTS`. +- Using mesh shaders requires enabling [`Features::EXPERIMENTAL_MESH_SHADER`]. +- Using mesh shaders with multiview requires enabling [`Features::EXPERIMENTAL_MESH_SHADER_MULTIVIEW`]. +- Using mesh shaders with point primitives requires enabling [`Features::EXPERIMENTAL_MESH_SHADER_POINTS`]. - Queries are unsupported - Primitive index support will be added once support lands in for them in general. @@ -280,3 +280,7 @@ fn fs_main(vertex: VertexOutput, primitive: PrimitiveInput) -> @location(0) vec4 return vertex.color * primitive.colorMask; } ``` + +*/ + +use crate::{Device, Features, RenderPass}; diff --git a/wgpu/src/documentation/extensions/mod.rs b/wgpu/src/documentation/extensions/mod.rs new file mode 100644 index 000000000..eb34702f8 --- /dev/null +++ b/wgpu/src/documentation/extensions/mod.rs @@ -0,0 +1,7 @@ +/*! +Extensions to the WebGPU API +*/ + +pub mod cooperative_matrices; +pub mod mesh_shading; +pub mod ray_tracing; diff --git a/docs/api-specs/ray_tracing.md b/wgpu/src/documentation/extensions/ray_tracing.rs similarity index 91% rename from docs/api-specs/ray_tracing.md rename to wgpu/src/documentation/extensions/ray_tracing.rs index 10842d93d..9976c7516 100644 --- a/docs/api-specs/ray_tracing.md +++ b/wgpu/src/documentation/extensions/ray_tracing.rs @@ -1,10 +1,9 @@ -# Ray Tracing Extensions - -🧪Experimental🧪 +/*! +# 🧪Experimental🧪 Ray Tracing `wgpu` supports an experimental version of ray tracing which is subject to change. The extensions allow for acceleration structures to be created and built (with -`Features::EXPERIMENTAL_RAY_QUERY` enabled) and interacted with in shaders. Currently `naga` only supports ray queries -(accessible with `Features::EXPERIMENTAL_RAY_QUERY` enabled in wgpu). +[`Features::EXPERIMENTAL_RAY_QUERY`] enabled) and interacted with in shaders. Currently `naga` only supports ray queries +(accessible with [`Features::EXPERIMENTAL_RAY_QUERY`] enabled in wgpu). **Note**: The features documented here may have major bugs in them and are expected to be subject to breaking changes, suggestions for the API exposed by this should be posted on [the ray-tracing issue](https://github.com/gfx-rs/wgpu/issues/1040). @@ -18,7 +17,7 @@ an [introduction](https://developer.nvidia.com/blog/introduction-nvidia-rtx-dire The documentation and specific details of the functions and structures provided can be found with their definitions. -Acceleration structures do not have a separate feature, instead they are enabled by `Features::EXPERIMENTAL_RAY_QUERY`, unlike vulkan. +Acceleration structures do not have a separate feature, instead they are enabled by [`Features::EXPERIMENTAL_RAY_QUERY`], unlike vulkan. When ray tracing pipelines are added, that feature will also enable acceleration structures. A [`Blas`] can be created with [`Device::create_blas`]. @@ -72,7 +71,7 @@ Some memory is allocated when building to be "scratch" data (a temporary buffer the build) and instance staging memory (to copy the instances to the GPU). The some of this can be reused for between the [`Blas`] and [`Tlas`] builds so in general it is advisable to try and integrate the builds together. Because building is slow, it should be done as few times as possible. For moving geometry (players, particles, etc.), use -[`PREFER_FAST_BUILD`](https://wgpu.rs/doc/wgpu_hal/struct.AccelerationStructureBuildFlags.html#associatedconstant.PREFER_FAST_BUILD) +[`AccelerationStructureFlags::PREFER_FAST_BUILD`](wgt::AccelerationStructureFlags::PREFER_FAST_BUILD) to speed up builds. Updating (performing a partial rebuild) is currently unsupported, but may be implemented in the future. You should compact any geometry which will not change (e.g. static level geometry) once it has been built. @@ -80,7 +79,7 @@ future. You should compact any geometry which will not change (e.g. static level Once a [`Blas`] has been built, it can be compacted. Acceleration structures are allocated conservatively, without knowing the exact data that is inside them. Once a [`Blas`] has been built, the driver can make data specific -optimisations to make the [`BLAS`] smaller. To begin compaction call [`Blas::prepare_compaction_async`] on it. This +optimisations to make the [`Blas`] smaller. To begin compaction call [`Blas::prepare_compaction_async`] on it. This method waits until all builds operating on the [`Blas`] are finished, prepares the [`Blas`] to be compacted, and runs the given callback. To check whether the [`Blas`] is ready, you can also call [`Blas::ready_for_compaction`] instead of waiting for the callback (useful if you are asynchronously compacting a large number of [`Blas`]es). Submitting a @@ -95,44 +94,38 @@ An example of compaction being run when [`Blas`]es are ready, this would be in a problem, otherwise (e.g. if you get an out of memory error) you should compact immediately (and switching all non-compacted [`Blas`]es to compacted ones). -```rust +```no_run +# let queue: wgpu::Queue = unimplemented!(); +# let device: wgpu::Device = unimplemented!(); +# let mut tlas: wgpu::Tlas = unimplemented!(); use std::iter; use wgpu::Blas; struct BlasToBeCompacted { blas: Blas, - /// The index into the TlasInstance this BLAS is used in. + /// The index into the TLAS instance this BLAS is used in. tlas_index: usize, } -fn render(/*whatever args you need to render*/) { - /* additional code to prepare the renderer */ - //An iterator of whatever BLASes you have called `prepare_compaction_async` on. - let blas_s_pending_compaction: impl Iterator = iter::empty(); - for blas_to_be_compacted in blas_s_pending_compaction { +// An iterator over whatever BLASes you have called `prepare_compaction_async` on. +let blas_s_pending_compaction = iter::empty::(); +for blas_to_be_compacted in blas_s_pending_compaction { if blas_to_be_compacted.blas.ready_for_compaction() { let compacted_blas = queue.compact_blas(&blas_to_be_compacted.blas); - tlas_instance[blas_to_be_compacted.tlas_index].set_blas(&compacted_blas); + tlas[blas_to_be_compacted.tlas_index] + .as_mut() + .unwrap() + .set_blas(&compacted_blas); } - } - let mut encoder = - device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); - /* do other preparations on the TlasInstance.*/ - encoder.build_acceleration_structures(iter::empty(), iter::once(&tlas_package)); - /* more render code */ - queue.submit([encoder.finish()]); } +let mut encoder = + device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); +// do any other preparations on the TLAS here +encoder.build_acceleration_structures(iter::empty(), iter::once(&tlas)); +// more render code +queue.submit([encoder.finish()]); ``` -[`Device::create_blas`]: https://wgpu.rs/doc/wgpu/struct.Device.html#method.create_blas -[`CommandEncoder::build_acceleration_structures`]: https://wgpu.rs/doc/wgpu/struct.CommandEncoder.html#method.build_acceleration_structures -[`Device::create_tlas`]: https://wgpu.rs/doc/wgpu/struct.Device.html#method.create_tlas -[`Tlas`]: https://wgpu.rs/doc/wgpu/struct.Tlas.html -[`Blas`]: https://wgpu.rs/doc/wgpu/struct.Blas.html -[`TlasInstance`]: https://wgpu.rs/doc/wgpu/struct.TlasInstance.html -[`Blas::prepare_compaction_async`]: https://wgpu.rs/doc/wgpu/struct.Blas.html#method.prepare_compaction_async -[`Blas::ready_for_compaction`]: https://wgpu.rs/doc/wgpu/struct.Blas.html#method.ready_for_compaction -[`Queue::compact_blas`]: https://wgpu.rs/doc/wgpu/struct.Queue.html#method.compact_blas ## `naga`'s raytracing API: @@ -409,3 +402,7 @@ These are tags that can be added to a acceleration structure (`acceleration_stru | Tag | Requirements | Description | | --------------- | ------------------------------------- | ---------------------------------------------------------------------- | | `vertex_return` | `enable wgpu_ray_query_vertex_return` | Allows getting the vertices of the hit triangle when using ray queries | + +*/ + +use crate::{Blas, CommandEncoder, Device, Features, Queue, Tlas, TlasInstance}; diff --git a/wgpu/src/documentation/features.rs b/wgpu/src/documentation/features.rs new file mode 100644 index 000000000..9c177b14e --- /dev/null +++ b/wgpu/src/documentation/features.rs @@ -0,0 +1,16 @@ +/*! +## Feature flags +*/ +#![doc = document_features::document_features!()] +/*! + +### Feature Aliases + +These features aren't actually features on the crate itself, but a convenient shorthand for +complicated cases. + +- **`wgpu_core`** --- Enabled when there is any non-webgpu backend enabled on the platform. +- **`naga`** --- Enabled when target `glsl` or `spirv` input is enabled, or when `wgpu_core` is enabled. +*/ + +use crate::Adapter; diff --git a/wgpu/src/documentation/getting_started/learning_wgpu.rs b/wgpu/src/documentation/getting_started/learning_wgpu.rs new file mode 100644 index 000000000..86e25179a --- /dev/null +++ b/wgpu/src/documentation/getting_started/learning_wgpu.rs @@ -0,0 +1,80 @@ +/*! +# Learning wgpu: Key Concepts and Resources + +If you are new to `wgpu` and graphics programming, this page collects +external learning resources and a primer on the core concepts of the API. + +## External resources + +Learning materials: + +- [Learn Wgpu tutorial](https://sotrh.github.io/learn-wgpu/) +- [Draw You a Triangle for Great Good](https://github.com/dwbrite/wgpu-rendering-project/wiki/Draw-You-a-Triangle-for-Great-Good) +- Chinese version of [学习 wgpu](https://jinleili.github.io/learn-wgpu-zh/) +- [GPU Architecture](https://docs.google.com/presentation/d/1qi2j-SZuzew7Rrf5VKEPDZAQQEitV40k9fKvwJNyicM/edit), + a presentation by Kangz on how GPUs work under the hood. + +Reference material: + +- The `wgpu` examples; see + [Running the Examples](crate::documentation::getting_started::running_the_examples). +- The [WebGPU specification](https://www.w3.org/TR/webgpu/), which `wgpu` + follows closely. + +Runtimes: + +- The [Deno](https://deno.land/) JS/TS runtime. + +## Important concepts + +### Device and Queue + +- [`Device`] + - All resource creation. + - All of its methods take `&self` (no `&mut`!). +- [`Queue`] + - All GPU work submission. + +_Typically_ both are created once on startup, one of each. A [`Device`] is +created with a set of [`Features`] and [`Limits`], which are enforced +independently of the underlying hardware's actual capabilities (e.g. texture +size and formats, number of bound resources, native extensions, …). + +### Relationship of [`RenderPipeline`]s and resource binding + +A slightly simplified overview of what you need to set up before rendering a +frame. + +*/ +#![doc = include_str!("../images/render-pipeline-and-resource-binding.svg")] +/*! + +- _Round boxes:_ temporary descriptor structs. +- _Cornered boxes:_ resources created from a [`Device`]. +- _Bold:_ what you deal with on a per-frame basis. + +Each [`BindGroupLayoutEntry`] has a (mostly) corresponding +[`BindingResource`]. Compute pipelines follow a similar pattern. + +### Drawing a "frame" + +A simplified overview of what you need to do to draw a frame. + +*/ +#![doc = include_str!("../images/life-of-a-frame.svg")] +/*! + +- _Full lines:_ needed for creation. +- _Dashed lines:_ provided as "information". + +[`CommandEncoder::finish`] consumes a [`CommandEncoder`] and produces a +[`CommandBuffer`]; [`Queue::submit`] consumes [`CommandBuffer`]s. The +[`TextureView`] on a [`RenderPassColorAttachment`] can come from a +[`Surface`] — a special target for the final output. + +*/ + +use crate::{ + BindGroupLayoutEntry, BindingResource, CommandBuffer, CommandEncoder, Device, Features, Limits, + Queue, RenderPassColorAttachment, RenderPipeline, Surface, TextureView, +}; diff --git a/wgpu/src/documentation/getting_started/mod.rs b/wgpu/src/documentation/getting_started/mod.rs new file mode 100644 index 000000000..5dc30681e --- /dev/null +++ b/wgpu/src/documentation/getting_started/mod.rs @@ -0,0 +1,9 @@ +/*! +Getting Started + +First steps for new `wgpu` users: running the bundled examples and learning +the core concepts of the API. +*/ + +pub mod learning_wgpu; +pub mod running_the_examples; diff --git a/wgpu/src/documentation/getting_started/running_the_examples.rs b/wgpu/src/documentation/getting_started/running_the_examples.rs new file mode 100644 index 000000000..78f52c839 --- /dev/null +++ b/wgpu/src/documentation/getting_started/running_the_examples.rs @@ -0,0 +1,39 @@ +/*! +# Running the Examples + +This section shows you how to get the dependencies needed to run the +examples included in the `wgpu` repository. + +## Dependencies + +The examples require: + +- The Rust compiler ([installation instructions](https://www.rust-lang.org/)). +- Drivers for your graphics card. Note that some platforms have multiple + possible driver backends (e.g. D3D12 or Vulkan on Windows). +- Git ([installation instructions](https://git-scm.com/downloads)). + +## Cloning + +Once you have the tools above, clone the repository: + +```bash +git clone --depth 1 https://github.com/gfx-rs/wgpu.git +cd wgpu +``` + +## Running the examples + +You can run the examples using the `wgpu-examples` binary: + +```bash +# Show a list of all examples +cargo run --bin wgpu-examples + +# Run the cube example +cargo run --bin wgpu-examples cube +``` + +To run an example in a browser, see +[Running on the Web](crate::documentation::platforms::web). +*/ diff --git a/wgpu/src/documentation/images/architecture.excalidraw b/wgpu/src/documentation/images/architecture.excalidraw new file mode 100644 index 000000000..1bd827d23 --- /dev/null +++ b/wgpu/src/documentation/images/architecture.excalidraw @@ -0,0 +1,1309 @@ +{ + "type": "excalidraw", + "version": 2, + "source": "https://excalidraw.com", + "elements": [ + { + "id": "gSlk-KZ0az3xLtYVwpV6n", + "type": "rectangle", + "x": 762.5, + "y": 67.5, + "width": 284.5, + "height": 79.5, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "a0", + "roundness": { + "type": 3 + }, + "seed": 2055822768, + "version": 94, + "versionNonce": 1654394288, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "EOJeNDRI9VCo58buyL0ht" + } + ], + "updated": 1761262529866, + "link": null, + "locked": false + }, + { + "id": "EOJeNDRI9VCo58buyL0ht", + "type": "text", + "x": 811.4166641235352, + "y": 82.25, + "width": 186.6666717529297, + "height": 50, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "a0V", + "roundness": null, + "seed": 1480859472, + "version": 78, + "versionNonce": 432754096, + "isDeleted": false, + "boundElements": null, + "updated": 1761262464679, + "link": null, + "locked": false, + "text": "wgpu:\nidiomatic Rust API", + "fontSize": 20, + "fontFamily": 5, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "gSlk-KZ0az3xLtYVwpV6n", + "originalText": "wgpu:\nidiomatic Rust API", + "autoResize": true, + "lineHeight": 1.25 + }, + { + "id": "FexGSk3-7wSIZh1r6oK_B", + "type": "rectangle", + "x": 426, + "y": 222.484375, + "width": 493, + "height": 135, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "a3", + "roundness": { + "type": 3 + }, + "seed": 1995068752, + "version": 515, + "versionNonce": 1165187920, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "UouP4CTsZUCXlkRHTlbuY" + }, + { + "id": "_CcUJ7FiICG5sRW4dEznb", + "type": "arrow" + }, + { + "id": "e4IIKq6IKfX_zal-YK48U", + "type": "arrow" + }, + { + "id": "jBIVwmVeHfZE3pROh984s", + "type": "arrow" + } + ], + "updated": 1761263008536, + "link": null, + "locked": false + }, + { + "id": "UouP4CTsZUCXlkRHTlbuY", + "type": "text", + "x": 565.0500030517578, + "y": 239.984375, + "width": 214.89999389648438, + "height": 100, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "a3V", + "roundness": null, + "seed": 330572208, + "version": 580, + "versionNonce": 218960304, + "isDeleted": false, + "boundElements": null, + "updated": 1761264516061, + "link": null, + "locked": false, + "text": "wgpu_core:\nbullet-proof validation\nresource tracking\nFFI-friendly API", + "fontSize": 20, + "fontFamily": 5, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "FexGSk3-7wSIZh1r6oK_B", + "originalText": "wgpu_core:\nbullet-proof validation\nresource tracking\nFFI-friendly API", + "autoResize": true, + "lineHeight": 1.25 + }, + { + "id": "G8sPC5weFJhSc7UjcJaLU", + "type": "rectangle", + "x": 1060.5, + "y": 224.484375, + "width": 379.5, + "height": 80.99999999999999, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "a5", + "roundness": { + "type": 3 + }, + "seed": 228774832, + "version": 404, + "versionNonce": 1105650096, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "0bdIE_MQ-mrOJpOh8iswL" + }, + { + "id": "jaDpPhStncec9MyqMnCVB", + "type": "arrow" + } + ], + "updated": 1761262545685, + "link": null, + "locked": false + }, + { + "id": "0bdIE_MQ-mrOJpOh8iswL", + "type": "text", + "x": 1073.4166717529297, + "y": 239.984375, + "width": 353.6666564941406, + "height": 50, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "a6", + "roundness": null, + "seed": 1939502512, + "version": 390, + "versionNonce": 2147429296, + "isDeleted": false, + "boundElements": null, + "updated": 1761262545685, + "link": null, + "locked": false, + "text": "WebGPU backend\n(in browser, when compiled to WASM)", + "fontSize": 20, + "fontFamily": 5, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "G8sPC5weFJhSc7UjcJaLU", + "originalText": "WebGPU backend\n(in browser, when compiled to WASM)", + "autoResize": true, + "lineHeight": 1.25 + }, + { + "id": "_CcUJ7FiICG5sRW4dEznb", + "type": "arrow", + "x": 829.7597162706998, + "y": 145.734375, + "width": 189.7063666979443, + "height": 74.49999999999997, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "a7", + "roundness": { + "type": 2 + }, + "seed": 1846275504, + "version": 499, + "versionNonce": 1681612112, + "isDeleted": false, + "boundElements": null, + "updated": 1761263008538, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + -34.072216270699755, + 39.5 + ], + [ + -128.57221627069976, + 28 + ], + [ + -189.7063666979443, + 74.49999999999997 + ] + ], + "lastCommittedPoint": null, + "startBinding": null, + "endBinding": { + "elementId": "FexGSk3-7wSIZh1r6oK_B", + "focus": -0.3703219188512025, + "gap": 2.25 + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false + }, + { + "id": "jaDpPhStncec9MyqMnCVB", + "type": "arrow", + "x": 980.1875, + "y": 146.734375, + "width": 180.75718517925202, + "height": 75.99999999999997, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "a8", + "roundness": { + "type": 2 + }, + "seed": 148690352, + "version": 428, + "versionNonce": 439287120, + "isDeleted": false, + "boundElements": null, + "updated": 1761262567378, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + 41, + 36 + ], + [ + 120, + 36.5 + ], + [ + 180.75718517925202, + 75.99999999999997 + ] + ], + "lastCommittedPoint": null, + "startBinding": null, + "endBinding": { + "elementId": "G8sPC5weFJhSc7UjcJaLU", + "focus": 0.039085649989101766, + "gap": 1.75 + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false + }, + { + "id": "h7LUtpI8Df6yQ3UQt0bOk", + "type": "rectangle", + "x": 446.6875, + "y": 647.234375, + "width": 448.5, + "height": 140, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "a9", + "roundness": { + "type": 3 + }, + "seed": 1256970160, + "version": 308, + "versionNonce": 1539189072, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "ONs3bXwavVHVxI9l73lNw" + }, + { + "id": "e4IIKq6IKfX_zal-YK48U", + "type": "arrow" + }, + { + "id": "ZDQ74d9lauVZFTgku5F04", + "type": "arrow" + }, + { + "id": "2QeIhXNaY_JMfvtOyabKq", + "type": "arrow" + }, + { + "id": "HlAC2LtmtzcQGUTbYq9ri", + "type": "arrow" + }, + { + "id": "BHimquNEempTwqRFeLWmp", + "type": "arrow" + }, + { + "id": "Zq6XQM9FnCBckSs8jjrma", + "type": "arrow" + } + ], + "updated": 1761263229447, + "link": null, + "locked": false + }, + { + "id": "ONs3bXwavVHVxI9l73lNw", + "type": "text", + "x": 532.7208404541016, + "y": 679.734375, + "width": 276.4333190917969, + "height": 75, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aA", + "roundness": null, + "seed": 930322864, + "version": 357, + "versionNonce": 1888357712, + "isDeleted": false, + "boundElements": null, + "updated": 1761264525235, + "link": null, + "locked": false, + "text": "wgpu_hal:\nportable cross-platform API\nwildly unsafe", + "fontSize": 20, + "fontFamily": 5, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "h7LUtpI8Df6yQ3UQt0bOk", + "originalText": "wgpu_hal:\nportable cross-platform API\nwildly unsafe", + "autoResize": true, + "lineHeight": 1.25 + }, + { + "id": "e4IIKq6IKfX_zal-YK48U", + "type": "arrow", + "x": 566.1875000000001, + "y": 360.234375, + "width": 65.50000000000011, + "height": 285.9999999999998, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aB", + "roundness": { + "type": 2 + }, + "seed": 30269776, + "version": 872, + "versionNonce": 1592818608, + "isDeleted": false, + "boundElements": null, + "updated": 1761263229448, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + -6.500000000000114, + 93.5 + ], + [ + -65.50000000000011, + 205 + ], + [ + -40.93721207248859, + 285.9999999999998 + ] + ], + "lastCommittedPoint": null, + "startBinding": { + "elementId": "FexGSk3-7wSIZh1r6oK_B", + "focus": 0.4037891448278799, + "gap": 2.75 + }, + "endBinding": { + "elementId": "h7LUtpI8Df6yQ3UQt0bOk", + "focus": -0.5057777966092336, + "gap": 1.0000000000001137 + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false + }, + { + "id": "5fw7aivimOm_Y0eNBBFCs", + "type": "rectangle", + "x": 727.1875, + "y": 370.234375, + "width": 486.00000000000006, + "height": 109.50000000000003, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aC", + "roundness": { + "type": 3 + }, + "seed": 251127632, + "version": 432, + "versionNonce": 1743327664, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "8Ej1_bAepMvcsQPl1KG1P" + }, + { + "id": "jBIVwmVeHfZE3pROh984s", + "type": "arrow" + } + ], + "updated": 1761262997358, + "link": null, + "locked": false + }, + { + "id": "8Ej1_bAepMvcsQPl1KG1P", + "type": "text", + "x": 756.0708312988281, + "y": 387.484375, + "width": 428.23333740234375, + "height": 75, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aD", + "roundness": null, + "seed": 1198376272, + "version": 453, + "versionNonce": 1105794896, + "isDeleted": false, + "boundElements": null, + "updated": 1761263723835, + "link": null, + "locked": false, + "text": "Naga front ends:\nparse WGSL, SPIR-V, or GLSL to IR Module\nbullet-proof validation", + "fontSize": 20, + "fontFamily": 5, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "5fw7aivimOm_Y0eNBBFCs", + "originalText": "Naga front ends:\nparse WGSL, SPIR-V, or GLSL to IR Module\nbullet-proof validation", + "autoResize": true, + "lineHeight": 1.25 + }, + { + "id": "BpumVh8D-EaEg_Q_CSATV", + "type": "rectangle", + "x": 727.1875, + "y": 515.484375, + "width": 511.00000000000006, + "height": 107.50000000000004, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aE", + "roundness": { + "type": 3 + }, + "seed": 868560304, + "version": 856, + "versionNonce": 507786160, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "jHNe21eMlLGqsOmVWocpV" + }, + { + "id": "ZDQ74d9lauVZFTgku5F04", + "type": "arrow" + } + ], + "updated": 1761263744496, + "link": null, + "locked": false + }, + { + "id": "jHNe21eMlLGqsOmVWocpV", + "type": "text", + "x": 734.7375030517578, + "y": 531.734375, + "width": 495.8999938964844, + "height": 75, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aF", + "roundness": null, + "seed": 942929840, + "version": 983, + "versionNonce": 2106398128, + "isDeleted": false, + "boundElements": [], + "updated": 1761263761525, + "link": null, + "locked": false, + "text": "Naga back ends:\ngenerate SPIR-V, HLSL, MSL, GLSL from IR Module\ncan inject run-time validation", + "fontSize": 20, + "fontFamily": 5, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "BpumVh8D-EaEg_Q_CSATV", + "originalText": "Naga back ends:\ngenerate SPIR-V, HLSL, MSL, GLSL from IR Module\ncan inject run-time validation", + "autoResize": true, + "lineHeight": 1.25 + }, + { + "id": "jBIVwmVeHfZE3pROh984s", + "type": "arrow", + "x": 921.1875, + "y": 271.09102225030887, + "width": 68.01251687072329, + "height": 96.64335274969113, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aG", + "roundness": { + "type": 2 + }, + "seed": 749384528, + "version": 218, + "versionNonce": 874947920, + "isDeleted": false, + "boundElements": null, + "updated": 1761263068970, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + 41, + 34.14335274969113 + ], + [ + 68.01251687072329, + 96.64335274969113 + ] + ], + "lastCommittedPoint": null, + "startBinding": { + "elementId": "FexGSk3-7wSIZh1r6oK_B", + "focus": -0.8284860511669349, + "gap": 2.1875 + }, + "endBinding": { + "elementId": "5fw7aivimOm_Y0eNBBFCs", + "focus": 0.16408721158789183, + "gap": 2.5 + }, + "startArrowhead": "arrow", + "endArrowhead": "arrow", + "elbowed": false + }, + { + "id": "ZDQ74d9lauVZFTgku5F04", + "type": "arrow", + "x": 1044.780494368418, + "y": 627.234375, + "width": 146.90018348207195, + "height": 90.04235032134864, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aH", + "roundness": { + "type": 2 + }, + "seed": 1405992368, + "version": 484, + "versionNonce": 1194264496, + "isDeleted": false, + "boundElements": null, + "updated": 1761263744497, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + -81.09299436841798, + 74 + ], + [ + -146.90018348207195, + 90.04235032134864 + ] + ], + "lastCommittedPoint": null, + "startBinding": { + "elementId": "BpumVh8D-EaEg_Q_CSATV", + "focus": -0.3996551100727328, + "gap": 4.25 + }, + "endBinding": { + "elementId": "h7LUtpI8Df6yQ3UQt0bOk", + "focus": 0.44411054346969303, + "gap": 2.692810886346024 + }, + "startArrowhead": "arrow", + "endArrowhead": "arrow", + "elbowed": false + }, + { + "id": "6Hq-kz6tFvyf02RO2Nnns", + "type": "rectangle", + "x": 440.390625, + "y": 846.8125, + "width": 163.00000000000003, + "height": 55.500000000000014, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aI", + "roundness": { + "type": 3 + }, + "seed": 1751719248, + "version": 196, + "versionNonce": 1514496848, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "B_kPXx-OkEPJMUThIJKrp" + }, + { + "id": "2QeIhXNaY_JMfvtOyabKq", + "type": "arrow" + } + ], + "updated": 1761263196356, + "link": null, + "locked": false + }, + { + "id": "B_kPXx-OkEPJMUThIJKrp", + "type": "text", + "x": 462.6572914123535, + "y": 862.0625, + "width": 118.46666717529297, + "height": 25, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aJ", + "roundness": null, + "seed": 1618275664, + "version": 100, + "versionNonce": 437471568, + "isDeleted": false, + "boundElements": null, + "updated": 1761263173206, + "link": null, + "locked": false, + "text": "Direct3D 12", + "fontSize": 20, + "fontFamily": 5, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "6Hq-kz6tFvyf02RO2Nnns", + "originalText": "Direct3D 12", + "autoResize": true, + "lineHeight": 1.25 + }, + { + "id": "RwcuXXgiWjYpjyYPqjjzL", + "type": "rectangle", + "x": 627.390625, + "y": 846.5625, + "width": 163.00000000000003, + "height": 55.500000000000014, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aL", + "roundness": { + "type": 3 + }, + "seed": 1103486288, + "version": 220, + "versionNonce": 1201785776, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "EQ2j_Tvkp3ctGzAV2jdvk" + }, + { + "id": "HlAC2LtmtzcQGUTbYq9ri", + "type": "arrow" + } + ], + "updated": 1761263206975, + "link": null, + "locked": false + }, + { + "id": "EQ2j_Tvkp3ctGzAV2jdvk", + "type": "text", + "x": 682.3072910308838, + "y": 861.8125, + "width": 53.16666793823242, + "height": 25, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aM", + "roundness": null, + "seed": 230536016, + "version": 129, + "versionNonce": 523168592, + "isDeleted": false, + "boundElements": [], + "updated": 1761263176192, + "link": null, + "locked": false, + "text": "Metal", + "fontSize": 20, + "fontFamily": 5, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "RwcuXXgiWjYpjyYPqjjzL", + "originalText": "Metal", + "autoResize": true, + "lineHeight": 1.25 + }, + { + "id": "6KJBZm7xuDfhk8_IERv9R", + "type": "rectangle", + "x": 991.390625, + "y": 851.0625, + "width": 163.00000000000003, + "height": 55.500000000000014, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aP", + "roundness": { + "type": 3 + }, + "seed": 1765068624, + "version": 240, + "versionNonce": 1105507152, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "6M9sWfktMLnkwnvSIter4" + }, + { + "id": "Zq6XQM9FnCBckSs8jjrma", + "type": "arrow" + } + ], + "updated": 1761263217869, + "link": null, + "locked": false + }, + { + "id": "6M9sWfktMLnkwnvSIter4", + "type": "text", + "x": 1036.1906242370605, + "y": 866.3125, + "width": 73.4000015258789, + "height": 25, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aQ", + "roundness": null, + "seed": 243164496, + "version": 164, + "versionNonce": 464954192, + "isDeleted": false, + "boundElements": [], + "updated": 1761263183292, + "link": null, + "locked": false, + "text": "OpenGL", + "fontSize": 20, + "fontFamily": 5, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "6KJBZm7xuDfhk8_IERv9R", + "originalText": "OpenGL", + "autoResize": true, + "lineHeight": 1.25 + }, + { + "id": "9V_EeI74SHitV49zxvGDE", + "type": "rectangle", + "x": 808.890625, + "y": 848.0625, + "width": 163.00000000000003, + "height": 55.500000000000014, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aR", + "roundness": { + "type": 3 + }, + "seed": 781782448, + "version": 258, + "versionNonce": 1580686160, + "isDeleted": false, + "boundElements": [ + { + "type": "text", + "id": "VggrEqSBa_L00q-xPcBn2" + }, + { + "id": "BHimquNEempTwqRFeLWmp", + "type": "arrow" + } + ], + "updated": 1761263210602, + "link": null, + "locked": false + }, + { + "id": "VggrEqSBa_L00q-xPcBn2", + "type": "text", + "x": 860.8739585876465, + "y": 863.3125, + "width": 59.03333282470703, + "height": 25, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aS", + "roundness": null, + "seed": 1837881264, + "version": 173, + "versionNonce": 322670928, + "isDeleted": false, + "boundElements": [], + "updated": 1761263180087, + "link": null, + "locked": false, + "text": "Vulkan", + "fontSize": 20, + "fontFamily": 5, + "textAlign": "center", + "verticalAlign": "middle", + "containerId": "9V_EeI74SHitV49zxvGDE", + "originalText": "Vulkan", + "autoResize": true, + "lineHeight": 1.25 + }, + { + "id": "2QeIhXNaY_JMfvtOyabKq", + "type": "arrow", + "x": 556.390625, + "y": 791.3125, + "width": 21.5, + "height": 53.5, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aT", + "roundness": { + "type": 2 + }, + "seed": 1739146160, + "version": 103, + "versionNonce": 1869172656, + "isDeleted": false, + "boundElements": null, + "updated": 1761263229449, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + -21.5, + 53.5 + ] + ], + "lastCommittedPoint": null, + "startBinding": { + "elementId": "h7LUtpI8Df6yQ3UQt0bOk", + "focus": 0.33590965478295476, + "gap": 4.078125 + }, + "endBinding": { + "elementId": "6Hq-kz6tFvyf02RO2Nnns", + "focus": 0.011272222922709026, + "gap": 2 + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false + }, + { + "id": "HlAC2LtmtzcQGUTbYq9ri", + "type": "arrow", + "x": 664.3906249999999, + "y": 792.3125, + "width": 26.500000000000114, + "height": 52, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aU", + "roundness": { + "type": 2 + }, + "seed": 2098281296, + "version": 76, + "versionNonce": 1862523312, + "isDeleted": false, + "boundElements": null, + "updated": 1761263229449, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + 26.500000000000114, + 52 + ] + ], + "lastCommittedPoint": null, + "startBinding": { + "elementId": "h7LUtpI8Df6yQ3UQt0bOk", + "focus": 0.17238885857502215, + "gap": 5.078125 + }, + "endBinding": { + "elementId": "RwcuXXgiWjYpjyYPqjjzL", + "focus": -0.028350968909443285, + "gap": 2.25 + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false + }, + { + "id": "BHimquNEempTwqRFeLWmp", + "type": "arrow", + "x": 752.1523437499998, + "y": 788.234375, + "width": 96.73828125, + "height": 53.578125, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aV", + "roundness": { + "type": 2 + }, + "seed": 687371088, + "version": 97, + "versionNonce": 1857889200, + "isDeleted": false, + "boundElements": null, + "updated": 1761263229449, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + 96.73828125, + 53.578125 + ] + ], + "lastCommittedPoint": null, + "startBinding": { + "elementId": "h7LUtpI8Df6yQ3UQt0bOk", + "focus": 0.13398285867068108, + "gap": 1 + }, + "endBinding": { + "elementId": "9V_EeI74SHitV49zxvGDE", + "focus": 0.15112658962587633, + "gap": 6.25 + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false + }, + { + "id": "Zq6XQM9FnCBckSs8jjrma", + "type": "arrow", + "x": 851.390625, + "y": 789.8124999999999, + "width": 164.4999999999999, + "height": 57.50000000000023, + "angle": 0, + "strokeColor": "#1e1e1e", + "backgroundColor": "transparent", + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 1, + "opacity": 100, + "groupIds": [], + "frameId": null, + "index": "aW", + "roundness": { + "type": 2 + }, + "seed": 1662653872, + "version": 214, + "versionNonce": 2092772784, + "isDeleted": false, + "boundElements": null, + "updated": 1761263229449, + "link": null, + "locked": false, + "points": [ + [ + 0, + 0 + ], + [ + 164.4999999999999, + 57.50000000000023 + ] + ], + "lastCommittedPoint": null, + "startBinding": { + "elementId": "h7LUtpI8Df6yQ3UQt0bOk", + "focus": 0.06403469466137489, + "gap": 2.578125 + }, + "endBinding": { + "elementId": "6KJBZm7xuDfhk8_IERv9R", + "focus": 0.20583983029091066, + "gap": 3.75 + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false + } + ], + "appState": { + "gridSize": 20, + "gridStep": 5, + "gridModeEnabled": false, + "viewBackgroundColor": "#ffffff", + "lockedMultiSelections": {} + }, + "files": {} +} \ No newline at end of file diff --git a/wgpu/src/documentation/images/architecture.webp b/wgpu/src/documentation/images/architecture.webp new file mode 100644 index 000000000..8da3cd1fd Binary files /dev/null and b/wgpu/src/documentation/images/architecture.webp differ diff --git a/wgpu/src/documentation/images/big-picture.webp b/wgpu/src/documentation/images/big-picture.webp new file mode 100644 index 000000000..bd4c32f66 Binary files /dev/null and b/wgpu/src/documentation/images/big-picture.webp differ diff --git a/docs/big-picture.xml b/wgpu/src/documentation/images/big-picture.xml similarity index 100% rename from docs/big-picture.xml rename to wgpu/src/documentation/images/big-picture.xml diff --git a/wgpu/src/documentation/images/life-of-a-frame.svg b/wgpu/src/documentation/images/life-of-a-frame.svg new file mode 100644 index 000000000..fd6c9d365 --- /dev/null +++ b/wgpu/src/documentation/images/life-of-a-frame.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/wgpu/src/documentation/images/render-pipeline-and-resource-binding.svg b/wgpu/src/documentation/images/render-pipeline-and-resource-binding.svg new file mode 100644 index 000000000..f7acbd053 --- /dev/null +++ b/wgpu/src/documentation/images/render-pipeline-and-resource-binding.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/wgpu/src/documentation/images/render_coordinates.webp b/wgpu/src/documentation/images/render_coordinates.webp new file mode 100644 index 000000000..3aa748105 Binary files /dev/null and b/wgpu/src/documentation/images/render_coordinates.webp differ diff --git a/wgpu/src/documentation/images/texture_coordinates.webp b/wgpu/src/documentation/images/texture_coordinates.webp new file mode 100644 index 000000000..87eb875c9 Binary files /dev/null and b/wgpu/src/documentation/images/texture_coordinates.webp differ diff --git a/wgpu/src/documentation/images/xcode-attached.webp b/wgpu/src/documentation/images/xcode-attached.webp new file mode 100644 index 000000000..a8d1ed308 Binary files /dev/null and b/wgpu/src/documentation/images/xcode-attached.webp differ diff --git a/wgpu/src/documentation/images/xcode-build-tool.webp b/wgpu/src/documentation/images/xcode-build-tool.webp new file mode 100644 index 000000000..561236ff6 Binary files /dev/null and b/wgpu/src/documentation/images/xcode-build-tool.webp differ diff --git a/wgpu/src/documentation/images/xcode-edit-scheme.webp b/wgpu/src/documentation/images/xcode-edit-scheme.webp new file mode 100644 index 000000000..50a3ec995 Binary files /dev/null and b/wgpu/src/documentation/images/xcode-edit-scheme.webp differ diff --git a/wgpu/src/documentation/images/xcode-new-project.webp b/wgpu/src/documentation/images/xcode-new-project.webp new file mode 100644 index 000000000..7a02a507c Binary files /dev/null and b/wgpu/src/documentation/images/xcode-new-project.webp differ diff --git a/wgpu/src/documentation/images/xcode-play-button.webp b/wgpu/src/documentation/images/xcode-play-button.webp new file mode 100644 index 000000000..ab3da67fc Binary files /dev/null and b/wgpu/src/documentation/images/xcode-play-button.webp differ diff --git a/wgpu/src/documentation/images/xcode-project-type.webp b/wgpu/src/documentation/images/xcode-project-type.webp new file mode 100644 index 000000000..bb3dd5221 Binary files /dev/null and b/wgpu/src/documentation/images/xcode-project-type.webp differ diff --git a/wgpu/src/documentation/images/xcode-scheme-arguments.webp b/wgpu/src/documentation/images/xcode-scheme-arguments.webp new file mode 100644 index 000000000..d2d0560ce Binary files /dev/null and b/wgpu/src/documentation/images/xcode-scheme-arguments.webp differ diff --git a/wgpu/src/documentation/images/xcode-scheme-options.webp b/wgpu/src/documentation/images/xcode-scheme-options.webp new file mode 100644 index 000000000..4a5d986a7 Binary files /dev/null and b/wgpu/src/documentation/images/xcode-scheme-options.webp differ diff --git a/wgpu/src/documentation/images/xcode-select-binary.webp b/wgpu/src/documentation/images/xcode-select-binary.webp new file mode 100644 index 000000000..62b2d78a3 Binary files /dev/null and b/wgpu/src/documentation/images/xcode-select-binary.webp differ diff --git a/wgpu/src/documentation/images/xcode-start-capture.webp b/wgpu/src/documentation/images/xcode-start-capture.webp new file mode 100644 index 000000000..93f06cf0a Binary files /dev/null and b/wgpu/src/documentation/images/xcode-start-capture.webp differ diff --git a/wgpu/src/documentation/internals/architecture.rs b/wgpu/src/documentation/internals/architecture.rs new file mode 100644 index 000000000..744f8fa76 --- /dev/null +++ b/wgpu/src/documentation/internals/architecture.rs @@ -0,0 +1,269 @@ +#![doc = crate::macros::doc_image!("architecture.webp")] +#![doc = crate::macros::doc_image!("big-picture.webp")] +/*! +# Architecture: wgpu, wgpu-core, and wgpu-hal + +Here's an overview of `wgpu`'s architecture. + +![wgpu architecture][architecture.webp] + +Working through this diagram from the bottom up: + +- Each operating system provides its own API (or APIs) for getting at the + GPU: + + - On Windows, [Direct3D] is the primary GPU programming API, but [Vulkan] + and [OpenGL] are often also available. + + - On macOS, [Metal] is the official GPU programming API, although OpenGL is + still around for legacy programs, and the [MoltenVK] open-source project + implements the Vulkan API on top of Metal. + + - On Linux, the [Mesa] library supports Vulkan and OpenGL. + + If you want to write an application that runs on all three of these + platforms, you have a few options: + + - You could target Vulkan, and for macOS support embed MoltenVK, or + require your users to install it. + + - You could target OpenGL, which is no longer being developed and is + missing many modern features, and worry that macOS will drop support for + it altogether. + + - You could port it to all three native platform APIs: Direct3D, Vulkan, + and Metal. This would be a lot of code. + + - Or, you could just use `wgpu`! + +- The [`wgpu_hal`] crate implements a portable Rust API that can use any of + the platform-specific APIs mentioned above as a backend: a program that + uses `wgpu_hal` correctly should behave consistently regardless of what + platform you're running on. + + However, `wgpu_hal`'s interface is completely unsafe; you must follow all + of its safety requirements to the letter to avoid provoking undefined + behavior from the underlying platforms. These requirements are complex, + and not well documented. And `wgpu_hal` performs almost no validation + beyond the minimum necessary to ensure portability. + +- The [`wgpu_core`] crate builds on `wgpu_hal` to provide an API with a + similar flavor, preserving its portability, and adding full bullet-proof + validation. By "bullet-proof", we mean that `wgpu_core` is intended to be + driven by untrusted code, like web content using the [WebGPU] API. + `wgpu_core` only assumes that Rust's safety rules are respected. Safe Rust + code should not be able to cause a crash using `wgpu_core`. + + This means that `wgpu_core` is fully responsible for things like tracking + resource lifetimes, generating barriers for usage transitions, checking + parameters, and so on. We cover its duties in more detail below. + + The `wgpu_core` crate's API is designed to be easy to use from other + languages via foreign function interfaces (FFI). This restricts the Rust + features we can use in the API somewhat. But this makes `wgpu_core` the + best dependency for crates like `wgpu_native` and applications like Deno + and Firefox that have their own binding systems. + +- The [`wgpu`](crate) crate provides an idiomatic Rust API on top of + `wgpu_core`, inheriting its validation and portability. This is what most + users in the Rust ecosystem will want. + + You can also compile `wgpu` to WebAssembly and run it in a web browser, + having it drive the browser's [WebGPU] implementation. In this mode of use, + `wgpu_core` and `wgpu_hal` are not present. This can help you share code + between in-browser and native versions of your app, by providing a single + API for both versions to use. + +[WebGPU]: https://www.w3.org/TR/webgpu/ +[Direct3D]: https://learn.microsoft.com/en-us/windows/win32/direct3d +[Vulkan]: https://www.vulkan.org/ +[Metal]: https://developer.apple.com/metal/ +[OpenGL]: https://www.opengl.org/ +[MoltenVK]: https://github.com/KhronosGroup/MoltenVK +[Mesa]: https://mesa3d.org/ +[`wgpu_hal`]: https://docs.rs/wgpu-hal/latest/wgpu_hal/ +[`wgpu_core`]: https://docs.rs/wgpu-core/latest/wgpu_core/ + +## wgpu + +The `wgpu` crate provides an idiomatic Rust API for cross-platform GPU-based +graphics and computation, modeled after the [WebGPU] JavaScript API. + +The `wgpu` crate itself doesn't contain much interesting graphics-related +code. It is mostly concerned with providing a consistent, idiomatic API that +applications can use to drive any one of several implementations: + +- The [`wgpu::backend::wgpu_core`][w:cwc] module is available in native or + Emscripten environments. It forwards all operations to `wgpu_core`. Most + [`Backend`] values, like `Vulkan` or `Metal`, go through this module. + +- The [`wgpu::backend::webgpu`][w:cwg] module, available when `wgpu` has been + compiled to WebAssembly, forwards calls to a browser's WebGPU + implementation. The [`Backend::BrowserWebGpu`] backend selects this module. + +- The [`wgpu::backend::custom`][w:cc] module uses dynamic dispatch to let the + user supply their own implementation. These are created via a separate + mechanism, so they don't use any [`Backend`] value. + +[w:cwc]: https://github.com/gfx-rs/wgpu/blob/trunk/wgpu/src/backend/wgpu_core.rs +[w:cwg]: https://github.com/gfx-rs/wgpu/blob/trunk/wgpu/src/backend/webgpu.rs +[w:cc]: https://github.com/gfx-rs/wgpu/blob/trunk/wgpu/src/backend/custom.rs + +## wgpu_core + +The `wgpu_core` crate implements a safe, cross-platform API on top of +`wgpu_hal`'s unsafe, cross-platform API. Almost every method in `wgpu_hal`'s +API is marked `unsafe`; it is `wgpu_core`'s job to satisfy or enforce every +requirement in `wgpu_hal`'s safety contracts. Then, `wgpu_hal`'s only +responsibility is to get consistent behavior across all its backends. This +relationship is explained more in +[`wgpu_hal`'s documentation][hal safety]. + +Beyond safety, `wgpu_core` also implements a few convenience APIs (for +example, mapped-at-creation buffers) on top of `wgpu_hal`'s more primitive +features. + +[hal safety]: https://docs.rs/wgpu-hal/latest/wgpu_hal/#validation-is-the-calling-codes-responsibility-not-wgpu-hals + +### Lifetime tracking + +The `wgpu_hal` API requires some objects to outlive others. For example, a +[`wgpu_hal::Device`] must outlive all resources (`wgpu_hal::Buffer`, +`wgpu_hal::CommandEncoder`, etc.) created from it. The `wgpu_core` types +ensure that these requirements are upheld, mostly just by using `Arc`. + +TODO: Command-buffer resource usage through submission probably counts as +"lifetime tracking" too. + +This `wgpu_hal` requirement arises mostly from the Vulkan backend. Direct3D +and Metal both use reference counting internally for most operations, but +Vulkan foists the entire problem off on its users. + +[`wgpu_hal::Device`]: https://docs.rs/wgpu-hal/latest/wgpu_hal/trait.Device.html + +### Synchronization + +Some types in the `wgpu_hal` API cannot be accessed simultaneously by +multiple threads. For example, most [`wgpu_hal::CommandEncoder`] methods take +`&mut self`. `wgpu_core` protects these hal types with `Mutex` as +appropriate. + +There are a few other interesting requirements; for example, calls to +[`wgpu_hal::Queue::submit`] on a given `Queue` that could occur +simultaneously must use different `Fence`s. `wgpu_core` addresses this by +simply wrapping `wgpu_hal::Queue` in a `Mutex`. + +[`wgpu_hal::CommandEncoder`]: https://docs.rs/wgpu-hal/latest/wgpu_hal/trait.CommandEncoder.html +[`wgpu_hal::Queue::submit`]: https://docs.rs/wgpu-hal/latest/wgpu_hal/trait.Queue.html#tymethod.submit + +### Barrier generation + +Vulkan and Direct3D require the user to include barriers in the command +stream to notify the driver when a particular buffer or texture is +transitioning from one kind of use to another. For example, if a texture is +used as a render target and then sampled by a shader, Direct3D 12 requires a +[ResourceBarrier] command between the two uses. Similarly, Vulkan requires +[VkCmdPipelineBarrier] commands in some cases to ensure that values written +to a resource by one operation will be seen by reads in a subsequent +operation. + +The `wgpu_hal` API passes these backends' requirements through to its own +users, requiring calls to [`transition_buffers`] and [`transition_textures`] +between different kinds of access to such resources. But, following the lead +of [WebGPU], the `wgpu` API does not require its users to record barriers. +This means that `wgpu_core` must track how each resource was last used, and +generate the barriers itself. + +Since `wgpu` encourages users to record `CommandBuffer`s in advance (ideally +in multiple threads), and then submit them in whatever order they please, +`wgpu_core` cannot know what states the resources that a `CommandBuffer` uses +will be in until it is actually submitted. Thus, each +`wgpu_core::CommandBuffer` merely records what states it expects the +resources it uses to be in initially, and which states it will leave those +resources in when it is done. Submission is then responsible for comparing +resources' actual states with those expected by each +`wgpu_core::CommandBuffer`, and recording the necessary barriers in a fresh +`wgpu_hal::CommandBuffer` submitted ahead of it. + +When recording a command buffer, since the commands are only being recorded +for later execution, and not executed immediately, a `CommandEncoder` tracks +the state each resource *will be in* when the given commands are executed, +and adds barriers to the recorded stream as appropriate. Naturally, the +`CommandEncoder` must treat each resource's initial state as unknown, as it +has no way to know what other commands will be submitted ahead of it. + +Note that, within a single `wgpu_hal::Texture`, individual array elements and +mip levels can be in different states. `wgpu_hal::Buffer`s, however, have only +a single state. + +Within `wgpu_core`, the `Tracker` type records a set of resources, their +current states, and (for command buffers being recorded) the initial state +they should be in. `Tracker` also notes which stateless resources (samplers; +render pipelines) a `CommandBuffer` uses, in order to keep them alive until +the commands have been submitted and finished running. + +[ResourceBarrier]: https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12graphicscommandlist-resourcebarrier +[VkCmdPipelineBarrier]: https://docs.vulkan.org/refpages/latest/refpages/source/vkCmdPipelineBarrier.html +[`transition_buffers`]: https://docs.rs/wgpu-hal/latest/wgpu_hal/trait.DynCommandEncoder.html#tymethod.transition_buffers +[`transition_textures`]: https://docs.rs/wgpu-hal/latest/wgpu_hal/trait.DynCommandEncoder.html#tymethod.transition_textures + +### MemoryInitTracker + +Tracks the memory-initialization state of buffer resources, i.e. whether +they have been written to either by the user or by `wgpu` previously +zero-initializing them (WebGPU requires all buffers to behave *as if* they +are zero-initialized). A `MemoryInitTracker` tracks a single buffer and +allows inserting zero-initialization lazily on use. Zero-init is inserted if +necessary at: + +- memory mapping, and +- `queue_submit` (for all bindings). + +### Device maintain + +TODO (what/why). + +### Cross-device use + +The `wgpu_hal` API requires that a resource created with one +[`wgpu_hal::Device`] may not be used with a different `Device`. `wgpu_core` +tracks the `Device` to which each resource belongs, and checks for +cross-device use where necessary. + +### General parameter validation + +The `wgpu_core` crate is responsible for all the usual parameter validation +for graphics operations: a texture's format must be supported by the device; +copies must not exceed the bounds of the buffers or textures involved; bind +groups need to have the right layout for the pipeline; and so on. + +## API tracing + +Enabled via a feature flag. Allows recording all usage (WebGPU API functions, +essentially) to a `.ron` file. Any additional data (data uploaded to a +buffer, etc.) is stored in additional files. A trace can be replayed with the +`player` compiled from the same `wgpu` revision. Used for testing and bug +reporting. See +[Debugging wgpu Applications](crate::documentation::debugging::debugging_applications#tracing-infrastructure). + +## Other WebGPU implementations + +Note that `wgpu` represents only one possible way to implement the +[WebGPU][WebGPU API] API; Google's [Dawn] and +[WebKit's WebGPU module][webkit] are other WebGPU implementations used in +production. + +[WebGPU API]: https://www.w3.org/TR/webgpu/ +[Dawn]: https://dawn.googlesource.com/dawn +[webkit]: https://github.com/WebKit/WebKit/tree/main/Source/WebCore/Modules/WebGPU + +## The wider gfx-rs ecosystem + +`wgpu` is one piece of the larger gfx-rs ecosystem. For a map of all the +components and how they fit together, see the big picture: + +![The gfx-rs big picture][big-picture.webp] + +*/ + +use crate::Backend; diff --git a/wgpu/src/documentation/internals/known_driver_issues.rs b/wgpu/src/documentation/internals/known_driver_issues.rs new file mode 100644 index 000000000..423845599 --- /dev/null +++ b/wgpu/src/documentation/internals/known_driver_issues.rs @@ -0,0 +1,194 @@ +/*! +# Known Driver Issues + +This page lists known issues with drivers that are not, or cannot, be worked +around by `wgpu`. + +Issues are categorized by GPU vendor and backend. Where details such as +"driver version" are recorded, they are not intended to be exhaustive: these +are just the values where the issue has been observed. Just because your +combination is not explicitly listed does not mean you aren't susceptible to +the same issue. + +## WGSL / All + +- **WGSL draft spec compliance** + + As outlined in the README, section + [Tracking the WebGPU and WGSL draft specifications](https://github.com/gfx-rs/wgpu#tracking-the-webgpu-and-wgsl-draft-specifications), + the version of WGSL implemented by `wgpu` will likely differ from what is + in the up-to-date spec. + +## Intel / Vulkan + +- **Integrated GPU not visible to programs named `cube`** + + | Property | Values observed | + | ---------------- | ----------------- | + | Operating System | Windows 10 64-bit | + | Driver OEM | Intel, Microsoft | + | Driver Version | 27.20.100.8935 | + + In a dual-GPU system, the driver for the Intel GPU will hide itself from + programs named `cube`. The issue can be worked around by disabling the + discrete GPU or by renaming the program to something other than `cube`. + +- **Hangs when the same semaphore is signaled and waited upon** + + | Property | Values observed | + | ---------------- | --------------- | + | Operating System | Linux 5.14 | + | Driver OEM | Intel | + | Driver Version | Mesa 21.2.3 | + + Using a "relay" semaphore confuses the Intel driver in Mesa. Reported in + . Can be worked + around by only doing one submission per frame. + +- **`cmd_begin_debug_utils_label_ext` pointer is NULL** + + | Property | Values observed | + | ---------------- | ------------------- | + | Operating System | Windows 10 Pro 21H1 | + | Driver OEM | UHD Graphics 630 | + | Driver Version | 24.20.100.6287 | + + The extension is supported, but the pointer to the function is NULL. + Escalated in . Still needs an + upstream report. + +## Intel / DirectX 12 + +- **Offset after resizing window** — + [wgpu-rs#647](https://github.com/gfx-rs/wgpu-rs/issues/647) + + | Property | Values observed | + | ---------------- | ----------------- | + | Operating System | Windows 10 64-bit | + | Driver OEM | Microsoft | + | Driver Version | 26.20.100.7639 | + + This issue affects programs running on any GPU if the Intel GPU is being + used by the compositor. This would typically be the case in dual-GPU + systems. It can be worked around by replacing the Microsoft OEM driver with + the generic Intel driver. + +- **`CreatePlacedResource` TDRs** — + [wgpu#1319](https://github.com/gfx-rs/wgpu/issues/1319) + + | Property | Values observed | + | ---------------- | ------------------------------ | + | Operating System | Windows 10 64-bit, build 19042 | + | GPU | HD Graphics 4600 | + | Driver Version | 20.19.15.5171 | + + Reported in + . + +## Intel / DX11 + +- **Buffer write not synchronized with draw** — + [wgpu#1060](https://github.com/gfx-rs/wgpu/issues/1060) + + | Property | Values observed | + | ---------------- | --------------- | + | Operating System | Windows | + + Buffer upload isn't being properly synchronized with the draw call that is + using it. This is entirely on the driver to get right; there is no way to + do manual sync. + +## Intel / All + +- **Cannot combine MSAA with sRGB resolve** — + [wgpu#725](https://github.com/gfx-rs/wgpu/issues/725) + + | Property | Values observed | + | ---------------- | --------------- | + | Operating System | Linux | + + Attempting to do MSAA resolve at the same time as sRGB resolve will cause + MSAA to not work and the clear color to not be properly converted into + sRGB. + +## Nvidia / Vulkan + +- **Hang/panic/device loss after specific render sequence** — + [wgpu#983](https://github.com/gfx-rs/wgpu/issues/983) + + | Property | Values observed | + | ---------------- | ------------------------- | + | Operating System | Windows 10 64-bit | + | GPU | GeForce RTX 2080 Ti | + | Driver Name | GeForce Game Ready Driver | + | Driver Version | 456.38, 457.09, 457.30 | + + Does not occur on driver version 452.06. After submitting a frame to + `wgpu`, Vulkan seems to become unstable and this manifests itself in a few + ways. + +- **`write_buffer` only works when aligned to 16** — + [wgpu#1323](https://github.com/gfx-rs/wgpu/issues/1323) + + | Property | Values observed | + | ---------------- | ---------------------------- | + | Operating System | Windows 10 64-bit | + | GPU | GeForce GTX 1050, 1070 | + | Driver Version | 27.21.14.5256, 27.21.14.6589 | + + We issue `vkCmdFillBuffer` for the uninitialized area of a buffer. If only + the first 40 bytes were filled, the fill buffer is called with an offset of + 40, but the driver ends up erasing all the data starting with offset 32. + Issue reported directly to the NVIDIA level-2 support team, ticket + 210412-000661. + +- **Flat-interpolated integers come out as zeroes** — + [wgpu#1775](https://github.com/gfx-rs/wgpu/issues/1775) + + | Property | Values observed | + | ---------------- | ---------------- | + | Operating System | Linux | + | GPU | GeForce GTX 1050 | + | Driver Version | 390 | + + Fragment shader sees interpolated values as 0. Issue reported to NVIDIA + Vulkan support. + +## WARP / D3D12 + +- **CPU descriptors are used after `CopyDescriptors`** — + [wgpu#1002](https://github.com/gfx-rs/wgpu/issues/1002) + + | Property | Values observed | + | ---------------- | ----------------- | + | Operating System | Windows 10 64-bit | + +## AMD / D3D12 + +- **Updating partial texture data doesn't show up** — + [wgpu#1306](https://github.com/gfx-rs/wgpu/issues/1306) + + | Property | Values observed | + | ---------------- | ----------------- | + | Operating System | Windows 10 64-bit | + | GPU | Ryzen 3500U | + | Driver Name | ? | + | Driver Version | ? | + + When a texture only gets partially updated, sampling from it returns + zeroes. Issue has been reported directly to AMD. + +## Mesa / Vulkan + +- **Integer overflow with very large buffers** — + [wgpu#2796](https://github.com/gfx-rs/wgpu/pull/2796) + + | Property | Values observed | + | ---------------- | ----------------- | + | Operating System | Linux | + | Driver Name | Mesa/lavapipe | + + When a buffer size or range parameter does not fit a 32-bit signed integer, + Mesa runs into integer overflows. + +*/ diff --git a/wgpu/src/documentation/internals/mod.rs b/wgpu/src/documentation/internals/mod.rs new file mode 100644 index 000000000..c91531133 --- /dev/null +++ b/wgpu/src/documentation/internals/mod.rs @@ -0,0 +1,10 @@ +/*! +Internals and Architecture + +How `wgpu` is put together internally, and the driver-level issues it has to +contend with. +*/ + +pub mod architecture; +pub mod known_driver_issues; +pub mod reporting_driver_bugs; diff --git a/wgpu/src/documentation/internals/reporting_driver_bugs.rs b/wgpu/src/documentation/internals/reporting_driver_bugs.rs new file mode 100644 index 000000000..15978bb7a --- /dev/null +++ b/wgpu/src/documentation/internals/reporting_driver_bugs.rs @@ -0,0 +1,35 @@ +/*! +# Reporting Driver Bugs + +It can sometimes be hard to figure out where to report driver bugs to the +vendor. Here is a collection of known places for issues to go, and whether +reports have been successful. + +Proprietary: + +- NVIDIA Windows/Linux: + [forum](https://forums.developer.nvidia.com/c/gaming-and-visualization-technologies/apis/489) + (success) +- AMD (Windows — GL/VK): + [forum](https://community.amd.com/t5/opengl-vulkan/bd-p/opengl-and-vulkan-discussions) + (unknown) +- Intel (Windows): + [GitHub](https://github.com/IGCIT/Intel-GPU-Community-Issue-Tracker-IGCIT) + (unknown) +- Qualcomm: + [forum](https://developer.qualcomm.com/forums/software/adreno-gpu-sdk) + (success) +- WARP: ping `@soldieroflight` in `#dx12-developers` on the + [DX12 Discord](https://discord.gg/directx) + +Open source: + +- AMDVLK (Linux): [GitHub](https://github.com/GPUOpen-Drivers/AMDVLK) +- Mesa: [GitLab](https://gitlab.freedesktop.org/mesa/mesa) + - AMD (Linux) RADV + - Intel (Linux) + - Raspberry Pi + - llvmpipe + - lavapipe +- MoltenVK: [GitHub](https://github.com/KhronosGroup/MoltenVK) +*/ diff --git a/wgpu/src/documentation/mod.rs b/wgpu/src/documentation/mod.rs new file mode 100644 index 000000000..7175e1596 --- /dev/null +++ b/wgpu/src/documentation/mod.rs @@ -0,0 +1,19 @@ +#![cfg_attr(not(doc), expect(unused_imports))] + +/*! +General documentation and guides for the `wgpu` crate. + +Each module here is documentation only (it contains no runtime code) and +collects concept primers, best practices, debugging tips, platform notes, +and explanations of `wgpu`'s internals that don't belong on any single API item. +*/ + +pub mod best_practices; +pub mod color; +pub mod debugging; +pub mod extensions; +pub mod features; +pub mod getting_started; +pub mod internals; +pub mod platforms; +pub mod shaders; diff --git a/wgpu/src/documentation/platforms/android.rs b/wgpu/src/documentation/platforms/android.rs new file mode 100644 index 000000000..e184b28ea --- /dev/null +++ b/wgpu/src/documentation/platforms/android.rs @@ -0,0 +1,24 @@ +/*! +# Running on Android + +## Surface creation + +On Android, surface creation should happen on the resume event of the +window, and surface cleanup on the suspend event. A valid surface cannot be +created beforehand. This means that, when using `winit`, `sdl2`, or anything +similar, surface creation should happen in the resume handler, roughly like +this: + +```ignore +// winit's `ApplicationHandler::resumed`: +fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let window = event_loop.create_window(Window::default_attributes()).unwrap(); + let surface = instance.create_surface(window).unwrap(); + // ... +} +``` + +Correspondingly, drop the [`Surface`] when the window is suspended. +*/ + +use crate::Surface; diff --git a/wgpu/src/documentation/platforms/angle.rs b/wgpu/src/documentation/platforms/angle.rs new file mode 100644 index 000000000..d809b58d7 --- /dev/null +++ b/wgpu/src/documentation/platforms/angle.rs @@ -0,0 +1,20 @@ +/*! +# Running on ANGLE + +[ANGLE](https://angleproject.org) is a translation layer from GLES to other +backends, developed by Google. We support running our GLES3 backend over it +in order to reach platforms with D3D11 support, which aren't accessible +otherwise. + +In order to run with ANGLE, the `angle` feature has to be enabled, and ANGLE +libraries placed in a location visible to the application. These binaries +can be downloaded from +[gfbuild-angle](https://github.com/DileSoft/gfbuild-angle) artifacts; +[manual compilation](https://github.com/google/angle/blob/main/doc/DevSetup.md) +may be required on Macs with Apple silicon. + +On Windows, you generally need to copy the libraries into the working +directory, into the same directory as the executable, or somewhere in your +`PATH`. On Linux, you can point to them using the `LD_LIBRARY_PATH` +environment variable. +*/ diff --git a/wgpu/src/documentation/platforms/emscripten.rs b/wgpu/src/documentation/platforms/emscripten.rs new file mode 100644 index 000000000..749c8c22f --- /dev/null +++ b/wgpu/src/documentation/platforms/emscripten.rs @@ -0,0 +1,33 @@ +/*! +# Running on the Web with Emscripten + +At the moment `wgpu` has one example meant to run under Emscripten: +`wgpu-hal/examples/raw-gles.rs`. + +In the workspace's top directory, build the example as follows: + +```bash +cargo clean +EMCC_CFLAGS="-g -s ERROR_ON_UNDEFINED_SYMBOLS=0 --no-entry -s FULL_ES3=1" \ + cargo build --example raw-gles --target wasm32-unknown-emscripten --features gles,emscripten,webgl +``` + +Then copy the HTML page that loads the compiled example into the target +directory alongside the WebAssembly: + +```bash +cp wgpu-hal/examples/raw-gles.em.html target/wasm32-unknown-emscripten/debug/examples/ +``` + +Finally, start an HTTP server publishing the contents of that directory: + +```bash +cd target/wasm32-unknown-emscripten/debug/examples/ +python -m http.server +``` + +Then visit `localhost:8000/` in your browser. + +If you get other, more interesting examples working with Emscripten, please +update this page! +*/ diff --git a/wgpu/src/documentation/platforms/mobile_app_integration.rs b/wgpu/src/documentation/platforms/mobile_app_integration.rs new file mode 100644 index 000000000..723ba5281 --- /dev/null +++ b/wgpu/src/documentation/platforms/mobile_app_integration.rs @@ -0,0 +1,29 @@ +/*! +# Integrating wgpu into Existing iOS and Android Apps + +`wgpu` does not depend on any windowing library, so it does not provide +window creation and management functions. Only when creating a window-based +[`Surface`] may an argument that implements the +[`raw-window-handle`](https://github.com/rust-windowing/raw-window-handle) +abstract interface be required. The +[`winit`](https://github.com/rust-windowing/winit) crate used by the `wgpu` +examples is a cross-platform window creation and management crate that +implements that interface; it takes over the window management and event +loop of the entire app. + +There is no doubt that, for game apps, the combination of `wgpu` + `winit` +is very suitable. However, a large number of non-game apps also often need +to use graphics APIs (for charts, image filters, etc.). These apps need to +use a lot of system UI components and interactions, and `winit`'s way of +taking over the entire app window is not suitable. So, it would be very +useful to integrate `wgpu` into existing iOS and Android apps without using +third-party window-management libraries. + +[wgpu-in-app](https://github.com/jinleili/wgpu-in-app) is a complete doc and +example of how to do it. The doc section also has two Chinese versions: +[与 iOS App 集成](https://jinleili.github.io/learn-wgpu-zh/integration-and-debugging/ios/) +and +[与 Android App 集成](https://jinleili.github.io/learn-wgpu-zh/integration-and-debugging/android/). +*/ + +use crate::Surface; diff --git a/wgpu/src/documentation/platforms/mod.rs b/wgpu/src/documentation/platforms/mod.rs new file mode 100644 index 000000000..29885a6aa --- /dev/null +++ b/wgpu/src/documentation/platforms/mod.rs @@ -0,0 +1,13 @@ +/*! +Platform-Specific Guides + +Notes on running `wgpu` on specific platforms and targets: the web, mobile, +ANGLE, and the requirements `wgpu` places on the Vulkan backend. +*/ + +pub mod android; +pub mod angle; +pub mod emscripten; +pub mod mobile_app_integration; +pub mod vulkan_requirements; +pub mod web; diff --git a/wgpu/src/documentation/platforms/vulkan_requirements.rs b/wgpu/src/documentation/platforms/vulkan_requirements.rs new file mode 100644 index 000000000..346a02105 --- /dev/null +++ b/wgpu/src/documentation/platforms/vulkan_requirements.rs @@ -0,0 +1,12 @@ +/*! +# Vulkan Requirements + +`wgpu`'s Vulkan backend requires the following from a physical device: + +- `fragmentStoresAndAtomics` must be enabled (see + ). +- `independentBlending` must be enabled (see + [wgpu#2498](https://github.com/gfx-rs/wgpu/pull/2498)). +- The `maxDrawIndexedIndexValue` limit must be 32-bit. +- `VK_KHR_storage_buffer_storage_class` must be supported. +*/ diff --git a/wgpu/src/documentation/platforms/web.rs b/wgpu/src/documentation/platforms/web.rs new file mode 100644 index 000000000..213fcc5da --- /dev/null +++ b/wgpu/src/documentation/platforms/web.rs @@ -0,0 +1,111 @@ +/*! +# Running on the Web (WebGPU and WebGL) + +`wgpu` can run in the browser by compiling to WebAssembly, targeting either +WebGPU (where available) or the WebGL2 backend as a fallback. The WebGL2 +backend is still missing some features compared to the native and WebGPU +backends. + +## Running the examples + +### Installing the Rust WebAssembly target + +To build the `wgpu` examples for execution in a browser, you must first +install the Rust toolchain for the `wasm32-unknown-unknown` target. Using +`rustup`: + +```bash +rustup target add wasm32-unknown-unknown +``` + +### Using `cargo xtask run-wasm` + +The simplest way to run the examples on the web is the `run-wasm` xtask: + +```bash +cargo xtask run-wasm +``` + +This builds the `wgpu-examples` crate for `wasm32-unknown-unknown` (both the +WebGPU and WebGL2 variants), runs `wasm-bindgen` on the output, and serves +the result. It requires +[`wasm-bindgen-cli`](https://crates.io/crates/wasm-bindgen-cli) and +[`simple-http-server`](https://crates.io/crates/simple-http-server) to be +installed. Once it's running, open in your browser +and pick an example. + +> **Note:** the server binds to `127.0.0.1` on purpose. WebGPU requires a +> [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts), +> which `127.0.0.1` satisfies but `0.0.0.0` does not. + +### WebGPU browser support + +WebGPU is available in current versions of Chrome and other Chromium-based +browsers, and is shipping or in progress elsewhere. For up-to-date +implementation status, check [webgpu.io](https://webgpu.io) or +[caniuse.com/webgpu](https://caniuse.com/webgpu). Note that `wgpu` is often +ahead of browsers in catching up with upstream WebGPU API changes. + +## Manual compilation with `wasm-bindgen-cli` + +If you'd rather not use the xtask, you can reproduce what it does by hand. +First install the version of `wasm-bindgen-cli` that matches the version +used by `wgpu` (check the workspace `Cargo.lock`): + +```bash +cargo install -f wasm-bindgen-cli --version +``` + +Then build the examples for `wasm32-unknown-unknown` and run `wasm-bindgen` +on the output. For WebGPU: + +```bash +cargo build --target wasm32-unknown-unknown -p wgpu-examples --no-default-features --features webgpu +wasm-bindgen target/wasm32-unknown-unknown/debug/wgpu-examples.wasm \ + --target web --no-typescript --out-dir target/generated --out-name webgpu +``` + +For WebGL2, swap the `webgpu` feature for `webgl` and the `--out-name` +accordingly: + +```bash +cargo build --target wasm32-unknown-unknown -p wgpu-examples --no-default-features --features webgl +wasm-bindgen target/wasm32-unknown-unknown/debug/wgpu-examples.wasm \ + --target web --no-typescript --out-dir target/generated --out-name webgl2 +``` + +### Setting up the page + +Create an `index.html` file in the `target/generated` directory that loads +the generated module: + +```html + + + + + + + + + + +``` + +### Running the code + +Now run a web server locally inside the `target/generated` directory to view +the example in the browser. A secure context is required for WebGPU, so +serve from `127.0.0.1` (or `localhost`), for example with +[`simple-http-server`](https://crates.io/crates/simple-http-server): + +```bash +simple-http-server target/generated -c wasm,html,js -i --coep --coop --ip 127.0.0.1 +``` + +The `--coep` and `--coop` flags set the cross-origin isolation headers some +features require. +*/ diff --git a/wgpu/src/documentation/shaders.rs b/wgpu/src/documentation/shaders.rs new file mode 100644 index 000000000..745b1167a --- /dev/null +++ b/wgpu/src/documentation/shaders.rs @@ -0,0 +1,16 @@ +/*! +## Shader Support + +`wgpu` can consume shaders in [WGSL](https://gpuweb.github.io/gpuweb/wgsl/), SPIR-V, and GLSL. +Both [HLSL](https://github.com/Microsoft/DirectXShaderCompiler) and [GLSL](https://github.com/KhronosGroup/glslang) +have compilers to target SPIR-V. All of these shader languages can be used with any backend as we handle all of the conversions. Additionally, support for these shader inputs is not going away. + +While WebGPU does not support any shading language other than WGSL, we will automatically convert your +non-WGSL shaders if you're running on WebGPU. + +WGSL is always supported by default, but GLSL and SPIR-V need features enabled to compile in support. + +To enable WGSL shaders, enable the `wgsl` feature of `wgpu` (enabled by default). +To enable SPIR-V shaders, enable the `spirv` feature of `wgpu`. +To enable GLSL shaders, enable the `glsl` feature of `wgpu`. +*/ diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index 9e855a43b..a342c5f6f 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -1,8 +1,9 @@ //! `wgpu` is a cross-platform, safe, pure-Rust graphics API. It runs natively on //! Vulkan, Metal, D3D12, and OpenGL; and on top of WebGL2 and WebGPU on wasm. //! -//! The API is based on the [WebGPU standard][webgpu], but is a fully native Rust library. -//! It serves as the core of the WebGPU integration in Firefox, Servo, and Deno. +//! The API is based on the [WebGPU standard][webgpu], but is a fully native Rust library +//! and includes many extensions specific to the native backends. It serves as the core of +//! the WebGPU integration in Firefox, Servo, and Deno. //! //! [webgpu]: https://gpuweb.github.io/gpuweb/ //! @@ -15,7 +16,7 @@ //! //! Additionally, [WebGPU Fundamentals] is a tutorial for WebGPU which is very similar to our API, minus differences between Rust and Javascript. //! -//! We have a [wiki](https://github.com/gfx-rs/wgpu/wiki) which has information on useful architecture patterns, debugging tips, and more getting started information. +//! Most types and functions are documented, but for more general guides and explanations, see the [documentation modules][documentation]. //! //! There are examples for this version [available on GitHub](https://github.com/gfx-rs/wgpu/tree/v30/examples#readme). //! @@ -24,197 +25,16 @@ //! //! `wgpu` uses the coordinate systems of D3D and Metal. Depth ranges from [0, 1]. //! -//! | Render | Texture | -//! | --------------------- | ---------------------- | -//! | ![render_coordinates] | ![texture_coordinates] | +//! | Render | Texture | +//! | --- | --- | +//! | ![Render coordinates][render_coordinates.webp] | ![Texture coordinates][texture_coordinates.webp] | //! //! `wgpu`'s MSRV is **1.87**. //! //! [Learn Wgpu]: https://sotrh.github.io/learn-wgpu/ //! [WebGPU Fundamentals]: https://webgpufundamentals.org/ -//! [render_coordinates]: https://raw.githubusercontent.com/gfx-rs/wgpu/refs/heads/v30/docs/render_coordinates.png -//! [texture_coordinates]: https://raw.githubusercontent.com/gfx-rs/wgpu/refs/heads/v30/docs/texture_coordinates.png -//! -//! ## Extension Specifications -//! -//! While the core of `wgpu` is based on the WebGPU standard, we also support extensions that allow for features that the standard does not have yet. -//! For high-level documentation on how to use these extensions, see documentation on [`Features`] or the relevant specification: -//! -//! 🧪EXPERIMENTAL🧪 APIs are subject to change and may allow undefined behavior if used incorrectly. -//! -//! - 🧪EXPERIMENTAL🧪 [Ray Tracing](https://github.com/gfx-rs/wgpu/blob/v30/docs/api-specs/ray_tracing.md). -//! - 🧪EXPERIMENTAL🧪 [Mesh Shading](https://github.com/gfx-rs/wgpu/blob/v30/docs/api-specs/mesh_shading.md). -//! -//! ## Shader Support -//! -//! `wgpu` can consume shaders in [WGSL](https://gpuweb.github.io/gpuweb/wgsl/), SPIR-V, and GLSL. -//! Both [HLSL](https://github.com/Microsoft/DirectXShaderCompiler) and [GLSL](https://github.com/KhronosGroup/glslang) -//! have compilers to target SPIR-V. All of these shader languages can be used with any backend as we handle all of the conversions. Additionally, support for these shader inputs is not going away. -//! -//! While WebGPU does not support any shading language other than WGSL, we will automatically convert your -//! non-WGSL shaders if you're running on WebGPU. -//! -//! WGSL is always supported by default, but GLSL and SPIR-V need features enabled to compile in support. -//! -//! To enable WGSL shaders, enable the `wgsl` feature of `wgpu` (enabled by default). -//! To enable SPIR-V shaders, enable the `spirv` feature of `wgpu`. -//! To enable GLSL shaders, enable the `glsl` feature of `wgpu`. -//! -//! ## Feature flags -#![doc = document_features::document_features!()] -//! -//! ### Feature Aliases -//! -//! These features aren't actually features on the crate itself, but a convenient shorthand for -//! complicated cases. -//! -//! - **`wgpu_core`** --- Enabled when there is any non-webgpu backend enabled on the platform. -//! - **`naga`** --- Enabled when target `glsl` or `spirv` input is enabled, or when `wgpu_core` is enabled. -//! -//! ## Surface color spaces and HDR output -//! -//! A surface can present in different color spaces to get HDR or wide-gamut -//! output onto the screen. This is configured through -//! [`SurfaceConfiguration::color_space`], and the rest of this section is a -//! concept primer on how it works. -//! -//! ### HDR output in a nutshell -//! -//! By default a surface is standard dynamic range (SDR) with the sRGB gamut: the -//! value `1.0` is the brightest white, anything above it clips, and only colors -//! within sRGB are expressible. Other [`SurfaceColorSpace`]s opt into a **wider -//! gamut** (for example [`DisplayP3`](SurfaceColorSpace::DisplayP3), still SDR -//! but with more saturated colors than sRGB), **high dynamic range** (values -//! above `1.0` drive brighter-than-white output), or both (for example -//! [`Bt2100Pq`](SurfaceColorSpace::Bt2100Pq), aka HDR10), on platforms that -//! support it. -//! -//! Three ideas carry most of the weight: -//! -//! * **Reference white and headroom.** Brightness is measured in *nits* -//! (cd/m²). On HDR-capable monitors, SDR reference white (plain white, `(1.0, 1.0, 1.0)` in the -//! extended color spaces) sits *below* the display's peak output on purpose, so -//! highlights have room above it. That gap is the display's *headroom*. -//! * **The transfer function is a round-trip.** Your shader applies an -//! encoding transfer function (the OETF) to turn the light it computed into a -//! stored signal, and the display applies the inverse decoding transfer -//! function (the EOTF) to turn it back into light. Choosing a color space -//! chooses which transfer functions both ends use. -//! * **Who applies the encoding transfer function.** wgpu applies it for you -//! **only** when you render to an `*Srgb` texture view format, where the GPU -//! runs the sRGB OETF when a value is stored to a texture. For every other -//! color space (linear extended sRGB, encoded extended sRGB or P3, PQ, HLG) -//! **the values your shader writes to the surface texture must already be -//! encoded by you**, along with any gamut conversion; in a typical renderer -//! this happens in a final tone-mapping or post-processing pass. wgpu hands -//! the signal to the compositor unchanged; getting this wrong produces a -//! wrong image with no error. -//! -//! wgpu does **not** tonemap or gamut-map for you. It gives you the surface -//! and, through [`DisplayHdrInfo`], the display's advisory capabilities; -//! *choosing* and *applying* a tone curve is your application's job. -//! -//! ### The practical path -//! -//! 1. **Query capabilities.** Call `Surface::get_capabilities`. To use HDR or -//! wide-gamut output, read [`SurfaceCapabilities::format_capabilities`] (each -//! format and the [`SurfaceColorSpaces`] it supports), **not** -//! [`SurfaceCapabilities::formats`]: the latter lists only formats usable -//! with [`Auto`](SurfaceColorSpace::Auto), which never selects HDR. -//! [`SurfaceCapabilities::color_spaces`] is a convenience lookup for one -//! format. -//! 2. **Optionally query the display.** Call `Surface::display_hdr_info` for the -//! current [`DisplayHdrInfo`] (peak and SDR-white nits, EDR headroom, -//! primaries, and a coarse dynamic-range/gamut bucket). Use it to pick a -//! tone-map target ([`DisplayHdrInfo::tone_map_headroom`]); *whether* HDR is -//! worthwhile is the capability question from step 1, not this live value. -//! Every field is advisory and optional; `None` means "cannot tell here", -//! never "SDR". -//! 3. **Choose a format and color space.** Intersect what you want with what -//! step 1 advertises, in your own preference order (for example HDR10, then -//! linear extended sRGB, then encoded extended sRGB, then SDR -//! [`Srgb`](SurfaceColorSpace::Srgb)). Keep an SDR fallback for when nothing -//! HDR is advertised, such as when OS HDR is off. -//! 4. **Configure the surface.** Set [`SurfaceConfiguration::color_space`] and -//! `format`. [`Auto`](SurfaceColorSpace::Auto) (the default) reproduces -//! wgpu's historical behavior and never picks HDR; any other value must be in -//! that format's advertised set or configuration fails validation. -//! 5. **Encode what you write to the surface texture.** For an `*Srgb` format, -//! output linear and the hardware encodes for you. Otherwise the values your -//! shader writes to the surface texture must already carry the encoding the -//! chosen color space expects (sRGB, extended sRGB, PQ, or HLG) **and** any -//! gamut conversion (for example outputting in the BT.2020 gamut for HDR10); -//! in a typical renderer you do this in a final tone-mapping or -//! post-processing pass. See the table below. -//! 6. **Present** as usual. If OS HDR is toggled mid-run, you'll see it on the -//! next `Surface::display_hdr_info` poll; re-query `Surface::get_capabilities` -//! and re-run the steps above. -//! -//! The standalone [HDR surface example] implements every step, including the -//! encoding transfer function for each color space. -//! -//! ### What to output from your fragment shader -//! -//! What the values your shader writes to the surface texture must contain for -//! each color space, and whether wgpu applies the transfer function for you: -//! -//! | Color space | Typical format | You write | wgpu encodes? | -//! | ----------- | -------------- | --------- | ------------- | -//! | `Srgb`, `*Srgb` format | `{Rgba,Bgra}8UnormSrgb` | linear | **yes** (hardware sRGB OETF on store) | -//! | `Srgb`, non-srgb format | `{Rgba,Bgra}8Unorm` | sRGB-encoded | no; apply the sRGB OETF yourself or use `*Srgb` instead | -//! | `ExtendedSrgbLinear` (scRGB) | `Rgba16Float` | linear, `1.0` = SDR white | no, but no encoding is necessary | -//! | `ExtendedSrgb` | `Rgba16Float` | extended sRGB-encoded | no; apply the extended sRGB OETF yourself | -//! | `DisplayP3` | `Bgra8Unorm` | sRGB-encoded, P3 primaries | no; apply the sRGB OETF (after gamut-mapping to P3) | -//! | `ExtendedDisplayP3` | `Rgba16Float` | extended sRGB-encoded, P3 primaries | no; apply the extended sRGB OETF (after gamut-mapping to P3) | -//! | `Bt2100Pq` (HDR10) | `Rgb10a2Unorm` | PQ-encoded, BT.2020 primaries | no; apply the PQ OETF (after gamut-mapping to BT.2020) | -//! | `Bt2100Hlg` | `Rgb10a2Unorm` | HLG-encoded, BT.2020 primaries | no; apply the HLG OETF (after gamut-mapping to BT.2020) | -//! -//! In short, wgpu applies the transfer function for you only when you render to -//! an `*Srgb` format. In every other case the values your shader writes to the -//! surface texture must already carry both the transfer function and any gamut -//! conversion. The [HDR surface example] implements every encoder in WGSL. -//! -//! ### Glossary -//! -//! * **Chromaticity** --- a color's hue and saturation independent of its -//! brightness, given as an `(x, y)` coordinate on the CIE 1931 diagram. -//! * **Primaries / gamut** --- the chromaticities of the red, green, and blue a -//! color space addresses, and so the range of colors it can express. [BT.709] -//! is the sRGB gamut, [Display P3] is wider, and [BT.2020] is wider still. -//! * **White point** --- the chromaticity of `R = G = B` (what "white" looks -//! like). Every color space here uses [D65], standard daylight. -//! * **Transfer function (OETF / EOTF)** --- how stored values map to light. The -//! *OETF* is the encoding transfer function your application applies; the -//! *EOTF* is the inverse decoding transfer function the display applies. -//! * **SDR / HDR** --- standard dynamic range clips at `1.0` (reference white); -//! high dynamic range lets values above `1.0` drive brighter-than-white -//! output. -//! * **Nits and reference white** --- a *nit* (cd/m²) is a unit of brightness; -//! *reference white* (also called *paper white*, especially on Windows) is the -//! brightness of SDR plain white, set below the panel's peak so highlights have -//! room above it. -//! * **Headroom (EDR)** --- how much brighter than current SDR white the display -//! can go right now, as a multiplier (`1.0` means none). Dynamic; see -//! [`DisplayHdrInfo::tone_map_headroom`]. -//! * **PQ / HLG** --- the two HDR transfer functions: [PQ] (SMPTE ST 2084, -//! HDR10) encodes absolute luminance, [HLG] (BT.2100) encodes relative -//! luminance. -//! * **scRGB / extended-range sRGB** --- sRGB extended past 0.0..=1.0 for -//! HDR: [scRGB] is *linear* -//! ([`ExtendedSrgbLinear`](SurfaceColorSpace::ExtendedSrgbLinear)), while -//! [`ExtendedSrgb`](SurfaceColorSpace::ExtendedSrgb) is the same range but -//! sRGB-*encoded* (gamma), the web's HDR path. -//! -//! [HDR surface example]: https://github.com/gfx-rs/wgpu/tree/v30/examples/standalone/03_hdr_surface -//! [BT.709]: https://www.itu.int/rec/R-REC-BT.709 -//! [BT.2020]: https://www.itu.int/rec/R-REC-BT.2020 -//! [Display P3]: https://en.wikipedia.org/wiki/DCI-P3#Display_P3 -//! [D65]: https://en.wikipedia.org/wiki/Standard_illuminant#D65_values -//! [PQ]: https://en.wikipedia.org/wiki/Perceptual_quantizer -//! [HLG]: https://www.itu.int/rec/R-REC-BT.2100 -//! [scRGB]: https://en.wikipedia.org/wiki/ScRGB -//! - +#![doc = crate::macros::doc_image!("render_coordinates.webp")] +#![doc = crate::macros::doc_image!("texture_coordinates.webp")] #![no_std] // `-Znext-solver` requires deeper recursion limits (at least for now) to prove Send/Sync #![recursion_limit = "256"] @@ -259,6 +79,7 @@ mod api; mod backend; mod cmp; mod dispatch; +pub mod documentation; mod macros; pub mod util; diff --git a/wgpu/src/macros/mod.rs b/wgpu/src/macros/mod.rs index 95979796e..d338f0603 100644 --- a/wgpu/src/macros/mod.rs +++ b/wgpu/src/macros/mod.rs @@ -255,6 +255,50 @@ macro_rules! hal_type_gles { } pub(crate) use hal_type_gles; +// Reference an image from the crate's `src/documentation/images/` directory. Put +// the expansion in a `#[doc]` attribute and reference the image by file name +// elsewhere in the same docs: +// +// #![doc = crate::macros::doc_image!("foo.png")] +// //! ![alt text][foo.png] +// +// Local builds resolve the image from the on-disk `src/documentation/images/` +// directory (which, because it lives inside the crate, is also present when a +// downstream user builds `wgpu`'s docs as a dependency); `docsrs` builds resolve +// it from the repository over HTTP, pinned to the commit being built. Both base +// URLs are set in `build.rs`. The expansion must be a single line, as it is used +// in a `#[doc]` attribute. +// +// Place these attributes *before* the module's doc comment, as shown above. +// rustdoc strips trailing blank lines from each doc fragment and joins the +// fragments with a single newline, so a definition placed after a doc comment +// that ends in a paragraph is swallowed by that paragraph as a lazy +// continuation, and every image reference in the module silently fails to +// resolve. + +/// Expands to a Markdown reference-style link definition for a `src/documentation/images/` image. +#[cfg(docsrs)] +macro_rules! doc_image { + ($name:literal) => { + concat!( + "[", + $name, + "]: https://raw.githubusercontent.com/gfx-rs/wgpu/", + env!("WGPU_DOCS_COMMIT"), + "/wgpu/src/documentation/images/", + $name + ) + }; +} +/// Expands to a Markdown reference-style link definition for a `src/documentation/images/` image. +#[cfg(not(docsrs))] +macro_rules! doc_image { + ($name:literal) => { + concat!("[", $name, "]: ", env!("WGPU_DOCS_URL_BASE"), "/", $name) + }; +} +pub(crate) use doc_image; + #[doc(hidden)] pub mod helpers { pub use alloc::{borrow::Cow, string::String};