163: Remove Rust wrapper and examples r=kvark a=kvark

Fixes #160 
Closes #60

Everything specific to Rust API is about to be moved to https://github.com/gfx-rs/wgpu-rs
It would let this project to be a proper mirror of mozilla-central piece, and it would encourage other authors to experiment with different approaches to Rust wrappers (i.e. borrowing versus non-borrowing).

cc @jdashg

Co-authored-by: Dzmitry Malyshau <kvarkus@gmail.com>
This commit is contained in:
bors[bot] 2019-05-11 01:57:01 +00:00
commit 7b0217d51c
31 changed files with 105 additions and 3145 deletions

View File

@ -1,4 +1,6 @@
language: rust
sudo: false
dist: xenial
matrix:
include:
@ -6,9 +8,11 @@ matrix:
- os: linux
rust: stable
compiler: gcc
- os: linux
rust: nightly
compiler: gcc
#TODO: unlock when libglfw3 on Ubuntu comes with Vulkan support
# or when we add a GL backend.
#- os: linux
# rust: nightly
# compiler: gcc
# Windows 64bit
- os: windows
rust: stable
@ -19,11 +23,11 @@ matrix:
rust: stable
osx_image: xcode9.4
compiler: clang
#- env: MACOSX_DEPLOYMENT_TARGET=10.9
# os: osx
# rust: nightly
# osx_image: xcode9.4
# compiler: clang
- env: MACOSX_DEPLOYMENT_TARGET=10.9
os: osx
rust: nightly
osx_image: xcode9.4
compiler: clang
# iPhoneOS 64bit
#- env: TARGET=aarch64-apple-ios
@ -31,16 +35,27 @@ matrix:
# osx_image: xcode9.4
# rust: nightly
addons:
apt:
packages:
- cmake
- libglfw3-dev
homebrew:
update: true
packages:
- cmake
- glfw3
choco:
packages:
- make
branches:
except:
- staging.tmp
before_install:
# Do not run bors builds against the nightly compiler.
# We want to find out about nightly bugs, so they're done in master, but we don't block on them.
- if [[ $TRAVIS_RUST_VERSION == "nightly" && $TRAVIS_BRANCH == "staging" ]]; then exit; fi
- if [[ $TRAVIS_OS_NAME == "windows" ]]; then choco install make; fi
script:
- cargo test
- if [[ $TRAVIS_OS_NAME == "osx" ]]; then (brew update && brew upgrade cmake && brew install glfw3 && cargo install cbindgen && make ffi-examples); fi
- if [[ $TRAVIS_RUST_VERSION == "nightly" ]]; then cargo +nightly install cbindgen && make VERBOSE=1; fi

266
Cargo.lock generated
View File

@ -1,13 +1,5 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "aho-corasick"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"memchr 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "andrew"
version = "0.2.1"
@ -34,11 +26,6 @@ dependencies = [
"num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "arrayref"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "arrayvec"
version = "0.4.10"
@ -57,16 +44,6 @@ dependencies = [
"shared_library 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "atty"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)",
"termion 1.5.2 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "autocfg"
version = "0.1.2"
@ -114,20 +91,6 @@ name = "block"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "block-buffer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"arrayref 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"byte-tools 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "byte-tools"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "byteorder"
version = "1.3.1"
@ -143,16 +106,6 @@ name = "cfg-if"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "cgmath"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"approx 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
"num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "cloudabi"
version = "0.0.3"
@ -161,14 +114,6 @@ dependencies = [
"bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "cmake"
version = "0.1.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cc 1.0.36 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "cocoa"
version = "0.18.4"
@ -250,14 +195,6 @@ dependencies = [
"syn 0.15.33 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "digest"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"generic-array 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "dlib"
version = "0.4.1"
@ -271,27 +208,6 @@ name = "downcast-rs"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "env_logger"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
"humantime 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 1.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
"termcolor 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "examples"
version = "0.1.0"
dependencies = [
"env_logger 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
"wgpu 0.2.2",
"wgpu-native 0.2.6",
]
[[package]]
name = "failure"
version = "0.1.5"
@ -312,11 +228,6 @@ dependencies = [
"synstructure 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "fake-simd"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "fnv"
version = "1.0.6"
@ -367,14 +278,6 @@ name = "gcc"
version = "0.3.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "generic-array"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "gfx-backend-dx11"
version = "0.1.1"
@ -458,17 +361,6 @@ dependencies = [
"xcb 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "gfx-examples"
version = "0.1.0"
dependencies = [
"cgmath 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)",
"env_logger 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
"glsl-to-spirv 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"wgpu 0.2.2",
]
[[package]]
name = "gfx-hal"
version = "0.1.0"
@ -479,24 +371,6 @@ dependencies = [
"fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "glsl-to-spirv"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cmake 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)",
"sha2 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
"tempfile 3.0.7 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "humantime"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "iovec"
version = "0.1.2"
@ -602,11 +476,6 @@ dependencies = [
"libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "memchr"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "memmap"
version = "0.7.0"
@ -694,11 +563,6 @@ name = "num-traits"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "numtoa"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "objc"
version = "0.2.6"
@ -835,11 +699,6 @@ dependencies = [
"unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "quick-error"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "quote"
version = "0.6.12"
@ -974,34 +833,6 @@ name = "redox_syscall"
version = "0.1.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "redox_termios"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"redox_syscall 0.1.54 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "regex"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"aho-corasick 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)",
"memchr 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"regex-syntax 0.6.6 (registry+https://github.com/rust-lang/crates.io-index)",
"thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
"utf8-ranges 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "regex-syntax"
version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"ucd-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "remove_dir_all"
version = "0.5.1"
@ -1083,17 +914,6 @@ dependencies = [
"syn 0.15.33 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "sha2"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"block-buffer 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"byte-tools 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"digest 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)",
"fake-simd 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "shared_library"
version = "0.1.9"
@ -1192,53 +1012,11 @@ dependencies = [
"winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "termcolor"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"wincolor 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "termion"
version = "1.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)",
"numtoa 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"redox_syscall 0.1.54 (registry+https://github.com/rust-lang/crates.io-index)",
"redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "thread_local"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "typenum"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "ucd-util"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "unicode-xid"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "utf8-ranges"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "uuid"
version = "0.7.4"
@ -1321,14 +1099,6 @@ dependencies = [
"lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "wgpu"
version = "0.2.2"
dependencies = [
"arrayvec 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)",
"wgpu-native 0.2.6",
]
[[package]]
name = "wgpu-native"
version = "0.2.6"
@ -1398,15 +1168,6 @@ name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "wincolor"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "winit"
version = "0.18.1"
@ -1485,28 +1246,21 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[metadata]
"checksum aho-corasick 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e6f484ae0c99fec2e858eb6134949117399f222608d84cadb3f58c1f97c2364c"
"checksum andrew 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9b7f09f89872c2b6b29e319377b1fbe91c6f5947df19a25596e121cf19a7b35e"
"checksum android_glue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "000444226fcff248f2bc4c7625be32c63caccfecc2723a2b9f78a7487a49c407"
"checksum approx 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f0e60b75072ecd4168020818c0107f2857bb6c4e64252d8d3983f6263b40a5c3"
"checksum arrayref 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "0d382e583f07208808f6b1249e60848879ba3543f57c32277bf52d69c2f0f0ee"
"checksum arrayvec 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)" = "92c7fb76bc8826a8b33b4ee5bb07a247a81e76764ab4d55e8f73e3a4d8808c71"
"checksum ash 0.24.4 (registry+https://github.com/rust-lang/crates.io-index)" = "11f080bc0414ee1b6b959442cb36478d56c6e6b9bb2b04079a5048d9acc91a30"
"checksum atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "9a7d5b8723950951411ee34d271d99dddcc2035a16ab25310ea2c8cfd4369652"
"checksum autocfg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a6d640bee2da49f60a4068a7fae53acde8982514ab7bae8b8cea9e88cbcfd799"
"checksum backtrace 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)" = "f106c02a3604afcdc0df5d36cc47b44b55917dbaf3d808f71c163a0ddba64637"
"checksum backtrace-sys 0.1.28 (registry+https://github.com/rust-lang/crates.io-index)" = "797c830ac25ccc92a7f8a7b9862bde440715531514594a6154e3d4a54dd769b6"
"checksum bincode 1.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "959c8e54c1ad412ffeeb95f05a9cade02d2d40a7b3c2f852d3353148f4beff35"
"checksum bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12"
"checksum block 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
"checksum block-buffer 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a076c298b9ecdb530ed9d967e74a6027d6a7478924520acddcddc24c1c8ab3ab"
"checksum byte-tools 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "560c32574a12a89ecd91f5e742165893f86e3ab98d21f8ea548658eb9eef5f40"
"checksum byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a019b10a2a7cdeb292db131fc8113e57ea2a908f6e7894b0c3c671893b65dbeb"
"checksum cc 1.0.36 (registry+https://github.com/rust-lang/crates.io-index)" = "a0c56216487bb80eec9c4516337b2588a4f2a2290d72a1416d930e4dcdb0c90d"
"checksum cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "11d43355396e872eefb45ce6342e4374ed7bc2b3a502d1b28e36d6e23c05d1f4"
"checksum cgmath 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)" = "283944cdecc44bf0b8dd010ec9af888d3b4f142844fdbe026c20ef68148d6fe7"
"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f"
"checksum cmake 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)" = "d9fc5523427cb1451da064f7db483d18bf8957e471baabf140ff683c37a86536"
"checksum cocoa 0.18.4 (registry+https://github.com/rust-lang/crates.io-index)" = "cf79daa4e11e5def06e55306aa3601b87de6b5149671529318da048f67cdd77b"
"checksum copyless 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "59de7722d3b5c7b35dd519d617fe5116c9b879a0f145dc5431d78ab1f61d7c23"
"checksum core-foundation 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)" = "25b9e03f145fd4f2bf705e07b900cd41fc636598fe5dc452fd0db1441c3f496d"
@ -1516,13 +1270,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "f8306fcef4a7b563b76b7dd949ca48f52bc1141aa067d2ea09565f3e2652aa5c"
"checksum d3d12 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4fda5547c55c93b070d59108464bbfd7d9da9563b2ce78fceefc6430e972a420"
"checksum derivative 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6073e9676dbebdddeabaeb63e3b7cefd23c86f5c41d381ee1237cc77b1079898"
"checksum digest 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)" = "03b072242a8cbaf9c145665af9d250c59af3b958f83ed6824e13533cf76d5b90"
"checksum dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "77e51249a9d823a4cb79e3eca6dcd756153e8ed0157b6c04775d04bf1b13b76a"
"checksum downcast-rs 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "f2b92dfd5c2f75260cbf750572f95d387e7ca0ba5e3fbe9e1a33f23025be020f"
"checksum env_logger 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b61fa891024a945da30a9581546e8cfaf5602c7b3f4c137a2805cf388f92075a"
"checksum failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "795bd83d3abeb9220f257e597aa0080a508b27533824adf336529648f6abf7e2"
"checksum failure_derive 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "ea1063915fd7ef4309e222a5a07cf9c319fb9c7836b1f89b85458672dbb127e1"
"checksum fake-simd 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed"
"checksum fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3"
"checksum foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
"checksum foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
@ -1531,15 +1282,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7"
"checksum fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c"
"checksum gcc 0.3.55 (registry+https://github.com/rust-lang/crates.io-index)" = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2"
"checksum generic-array 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ef25c5683767570c2bbd7deba372926a55eaae9982d7726ee2a1050239d45b9d"
"checksum gfx-backend-dx11 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fe0bc43f1be34bfa182ed3575812848d72fb6e32315406adb98eeb0713f2a11a"
"checksum gfx-backend-dx12 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "15d8bb2edd39dba0e87c2058d665364d45efd08cdf8bfa895be792491a95fcb4"
"checksum gfx-backend-empty 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "590c15369f88b88e4ea748da52b27a521a758a947b4aee995539c9f0cc1beb4c"
"checksum gfx-backend-metal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "66a0fa897619ea7f05e8841fe6214cf1b4e3f52d6a88ed51c2fbc6635a2d5517"
"checksum gfx-backend-vulkan 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "982c618fd9ddeea7e68b2d872b9b6cf13024fc7d4033ba90f0e54ac0d33c798f"
"checksum gfx-hal 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "84c470bce77fcaaea6854858682a99026ff796b880b0ca30511593a6b2bc77c0"
"checksum glsl-to-spirv 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "28caebc98746d507603a2d3df66dcbe04e41d4febad0320f3eec1ef72b6bbef1"
"checksum humantime 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3ca7e5f2e110db35f93b837c81797f3714500b81d517bf20c431b16d3ca4f114"
"checksum iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dbe6e417e7d0975db6512b90796e8ce223145ac4e33c377e4a42882a0e88bb08"
"checksum ipc-channel 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "79d98ee7dd1d2e796d254807fd86ea7189d07571aeaa74007603e29a79d15217"
"checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d"
@ -1553,7 +1301,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum lock_api 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ed946d4529956a20f2d63ebe1b69996d5a2137c91913fe3ebbeff957f5bca7ff"
"checksum log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c84ec4b527950aa83a329754b01dbe3f58361d1c5efacd1f6d68c494d08a17c6"
"checksum malloc_buf 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"
"checksum memchr 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2efc7bc57c883d4a4d6e3246905283d8dae951bb3bd32f49d6ef297f546e1c39"
"checksum memmap 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b"
"checksum metal 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cd3f21d259068945192293b7a98b1c6844af9eb7602e393c405198b229efc157"
"checksum mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)" = "71646331f2619b1026cc302f87a2b8b648d5c6dd6937846a16cc8ce0f347f432"
@ -1562,7 +1309,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum nix 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)" = "46f0f3210768d796e8fa79ec70ee6af172dacbe7147f5e69be5240a47778302b"
"checksum nodrop 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "2f9667ddcc6cc8a43afc9b7917599d7216aa09c463919ea32c59ed6cac8bc945"
"checksum num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0b3a5d7cc97d6d30d8b9bc8fa19bf45349ffe46241e8816f50f62f6d6aaabee1"
"checksum numtoa 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b8f8bdf33df195859076e54ab11ee78a1b208382d3a26ec40d142ffc1ecc49ef"
"checksum objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "31d20fd2b37e07cf5125be68357b588672e8cefe9a96f8c17a9d46053b3e590d"
"checksum objc-foundation 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9"
"checksum objc_exception 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "098cd29a2fa3c230d3463ae069cecccc3fdfd64c0d2496ab5b96f82dab6a00dc"
@ -1578,7 +1324,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831"
"checksum pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)" = "676e8eb2b1b4c9043511a9b7bea0915320d7e502b0a079fb03f9635a5252b18c"
"checksum proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)" = "64c827cea7a7ab30ce4593e5e04d7a11617ad6ece2fa230605a78b00ff965316"
"checksum quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0"
"checksum quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)" = "faf4799c5d274f3868a4aae320a0a182cbd2baee377b378f080e16a23e9d80db"
"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9"
"checksum rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca"
@ -1594,9 +1339,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum range-alloc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "dd5927936723a9e8b715d37d7e4b390455087c4bdf25b9f702309460577b14f9"
"checksum rdrand 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2"
"checksum redox_syscall 0.1.54 (registry+https://github.com/rust-lang/crates.io-index)" = "12229c14a0f65c4f1cb046a3b52047cdd9da1f4b30f8a39c5063c8bae515e252"
"checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76"
"checksum regex 1.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "8f0a0bcab2fd7d1d7c54fa9eae6f43eddeb9ce2e7352f8518a814a4f65d60c58"
"checksum regex-syntax 0.6.6 (registry+https://github.com/rust-lang/crates.io-index)" = "dcfd8681eebe297b81d98498869d4aae052137651ad7b96822f09ceb690d0a96"
"checksum remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5"
"checksum rustc-demangle 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)" = "ccc78bfd5acd7bf3e89cffcf899e5cb1a52d6fafa8dec2739ad70c9577a57288"
"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
@ -1608,7 +1350,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
"checksum serde 1.0.91 (registry+https://github.com/rust-lang/crates.io-index)" = "a72e9b96fa45ce22a4bc23da3858dfccfd60acd28a25bcd328a98fdd6bea43fd"
"checksum serde_derive 1.0.91 (registry+https://github.com/rust-lang/crates.io-index)" = "101b495b109a3e3ca8c4cbe44cf62391527cdfb6ba15821c5ce80bcd5ea23f9f"
"checksum sha2 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9eb6be24e4c23a84d7184280d2722f7f2731fcdd4a9d886efbfe4413e4847ea0"
"checksum shared_library 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11"
"checksum slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8"
"checksum smallvec 0.6.9 (registry+https://github.com/rust-lang/crates.io-index)" = "c4488ae950c49d403731982257768f48fada354a5203fe81f9bb6f43ca9002be"
@ -1620,13 +1361,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum syn 0.15.33 (registry+https://github.com/rust-lang/crates.io-index)" = "ec52cd796e5f01d0067225a5392e70084acc4c0013fa71d55166d38a8b307836"
"checksum synstructure 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "73687139bf99285483c96ac0add482c3776528beac1d97d444f6e91f203a2015"
"checksum tempfile 3.0.7 (registry+https://github.com/rust-lang/crates.io-index)" = "b86c784c88d98c801132806dadd3819ed29d8600836c4088e855cdf3e178ed8a"
"checksum termcolor 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "4096add70612622289f2fdcdbd5086dc81c1e2675e6ae58d6c4f62a16c6d7f2f"
"checksum termion 1.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dde0593aeb8d47accea5392b39350015b5eccb12c0d98044d856983d89548dea"
"checksum thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b"
"checksum typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "612d636f949607bdf9b123b4a6f6d966dedf3ff669f7f045890d3a4a73948169"
"checksum ucd-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "535c204ee4d8434478593480b8f86ab45ec9aae0e83c568ca81abf0fd0e88f86"
"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"
"checksum utf8-ranges 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "796f7e48bef87609f7ade7e06495a87d5cd06c7866e6a5cbfceffc558a243737"
"checksum uuid 0.7.4 (registry+https://github.com/rust-lang/crates.io-index)" = "90dbc611eb48397705a6b0f6e917da23ae517e4d127123d2cf7674206627d32a"
"checksum vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a"
"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"
@ -1642,7 +1377,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
"checksum winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7168bab6e1daee33b4557efd0e95d5ca70a03706d39fa5f3fe7a236f584b03c9"
"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
"checksum wincolor 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "561ed901ae465d6185fa7864d63fbd5720d0ef718366c9a4dc83cf6170d7e9ba"
"checksum winit 0.18.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c57c15bd4c0ef18dff33e263e452abe32d00e2e05771cacaa410a14cc1c0776"
"checksum wio 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5"
"checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e"

View File

@ -2,7 +2,4 @@
members = [
"wgpu-native",
"wgpu-remote",
"wgpu-rs",
"examples",
"gfx-examples",
]

View File

@ -30,9 +30,9 @@ else
endif
.PHONY: all check test doc clear lib-native lib-remote lib-rust examples-rust examples-gfx gfx ffi-examples
.PHONY: all check test doc clear lib-native lib-remote examples-native examples-remote
all: examples-rust examples-gfx ffi-examples
all: examples-native examples-remote
check:
cargo check --all
@ -45,7 +45,7 @@ doc:
clear:
cargo clean
rm wgpu-bindings/wgpu.h
rm wgpu-bindings/wgpu.h wgpu-bindings/wgpu-remote.h
lib-native: Cargo.lock wgpu-native/Cargo.toml $(wildcard wgpu-native/**/*.rs)
cargo build --manifest-path wgpu-native/Cargo.toml --features "local,$(FEATURE_NATIVE)"
@ -53,27 +53,14 @@ lib-native: Cargo.lock wgpu-native/Cargo.toml $(wildcard wgpu-native/**/*.rs)
lib-remote: Cargo.lock wgpu-remote/Cargo.toml $(wildcard wgpu-native/**/*.rs wgpu-remote/**/*.rs)
cargo build --manifest-path wgpu-remote/Cargo.toml --features $(FEATURE_RUST)
lib-rust: Cargo.lock wgpu-rs/Cargo.toml $(wildcard wgpu-rs/**/*.rs)
cargo build --manifest-path wgpu-rs/Cargo.toml --features $(FEATURE_RUST)
ffi/wgpu.h: wgpu-native/cbindgen.toml $(wildcard wgpu-native/**/*.rs)
cbindgen wgpu-native >ffi/wgpu.h
rustup run nightly cbindgen wgpu-native >ffi/wgpu.h
ffi/wgpu-remote.h: wgpu-remote/cbindgen.toml $(wildcard wgpu-native/**/*.rs wgpu-remote/**/*.rs)
cbindgen wgpu-remote >ffi/wgpu-remote.h
rustup run nightly cbindgen wgpu-remote >ffi/wgpu-remote.h
wgpu-bindings/*.h: Cargo.lock $(wildcard wgpu-bindings/src/*.rs) lib-native lib-remote
cargo +nightly run --manifest-path wgpu-bindings/Cargo.toml
ffi-examples: lib-native lib-remote ffi/wgpu.h ffi/wgpu-remote.h
examples-native: lib-native ffi/wgpu.h examples/hello_triangle_c/main.c
cd examples/hello_triangle_c && mkdir -p build && cd build && cmake .. && make
examples-remote: lib-remote ffi/wgpu-remote.h examples/hello_remote_c/main.c
cd examples/hello_remote_c && mkdir -p build && cd build && cmake .. && make
examples-rust: examples/Cargo.toml $(wildcard wgpu-native/**/*.rs wgpu-rs/**/*.rs)
cargo build --manifest-path examples/Cargo.toml --features $(FEATURE_RUST)
examples-gfx: examples-rust gfx-examples/Cargo.toml $(wildcard gfx-examples/*.rs)
cargo build --manifest-path gfx-examples/Cargo.toml --features $(FEATURE_RUST)
gfx:
cargo run --manifest-path gfx-examples/Cargo.toml --bin $(name) --features $(FEATURE_RUST)

View File

@ -1,45 +1,25 @@
This is an active Github mirror of the WebGPU native implementation in Rust, which now lives in [Mozilla-central](https://hg.mozilla.org/mozilla-central). Issues and pull requests are accepted, but we merge them in m-c manually and then sync to Github instead of landing directly here.
---
# WebGPU
[![Build Status](https://travis-ci.org/gfx-rs/wgpu.svg)](https://travis-ci.org/gfx-rs/wgpu)
[![Crates.io](https://img.shields.io/crates/v/wgpu.svg)](https://crates.io/crates/wgpu)
[![Crates.io](https://img.shields.io/crates/v/wgpu-native.svg?label=wgpu-native)](https://crates.io/crates/wgpu-native)
[![Gitter](https://badges.gitter.im/gfx-rs/webgpu.svg)](https://gitter.im/gfx-rs/webgpu)
This is an experimental [WebGPU](https://www.w3.org/community/gpu/) implementation as a native static library. It's written in Rust and is based on [gfx-hal](https://github.com/gfx-rs/gfx) and [satellite](https://github.com/gfx-rs/gfx-memory) libraries. The corresponding WebIDL specification can be found at [gpuweb project](https://github.com/gpuweb/gpuweb/blob/master/spec/index.bs).
This is an experimental [WebGPU](https://www.w3.org/community/gpu/) implementation as a native static library. It's written in Rust and is based on [gfx-hal](https://github.com/gfx-rs/gfx) and [Rendy](https://github.com/amethyst/rendy) libraries. The corresponding WebIDL specification can be found at [gpuweb project](https://github.com/gpuweb/gpuweb/blob/master/spec/index.bs).
The implementation consists of the following parts:
- `wgpu-native` - the native implementation of WebGPU as a C API library
- `wgpu-remote` - remoting layer to work with WebGPU across the process boundary
- `wgpu-rs` - idiomatic Rust wrapper of the native library
1. `wgpu-native` - the native implementation of WebGPU as a C API library
2. `wgpu-remote` - remoting layer to work with WebGPU across the process boundary
3. `ffi` - the C headers generated by [cbindgen](https://github.com/eqrion/cbindgen) for both of the libraries
Supported platforms:
- Vulkan on Windows and Linux
- D3D12 and D3D11 on Windows
- Metal on macOS and iOS
## Examples
## Usage
![Cube](etc/gfx-cube.png) ![Shadow](etc/gfx-shadow.png)
This repository contains C-language examples that link to the native library targets and perform basic rendering and computation. You can test them with `make`.
To run an example, simply `cd` to the `examples` or `gfx-examples` directory, then use `cargo run` with `--features {backend}` to specify the backend (where `{backend}` is either `vulkan`, `dx12`, `dx11` or `metal`). For example:
```bash
# Clone the wgpu repository
git clone https://github.com/gfx-rs/wgpu
# Change directory to `examples`
cd wgpu/examples
# Vulkan (Linux/Windows)
cargo run --bin hello_triangle --features vulkan
# Metal (macOS/iOS)
cargo run --bin hello_triangle --features metal
# DirectX12 (Windows)
cargo run --bin hello_triangle --features dx12
cd ../gfx-examples
# Vulkan (Linux/Windows)
cargo run --bin cube --features vulkan
# Metal (macOS/iOS)
cargo run --bin cube --features metal
# DirectX12 (Windows)
cargo run --bin cube --features dx12
```
These examples assume that necessary dependencies for the graphics backend are already installed. For more information about installation and usage, refer to the [Getting Started](https://github.com/gfx-rs/gfx/blob/master/info/getting_started.md) gfx-rs guide.
The idiomatic Rust wrapper lives in https://github.com/gfx-rs/wgpu-rs and provides a number of more complex examples to get a feel of the API.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

View File

@ -1,30 +0,0 @@
[package]
name = "examples"
version = "0.1.0"
authors = [
"Dzmitry Malyshau <kvark@mozilla.com>",
"Joshua Groves <josh@joshgroves.com>",
]
edition = "2018"
publish = false
[[bin]]
name = "hello_triangle"
path = "hello_triangle_rust/main.rs"
[[bin]]
name = "hello_compute"
path = "hello_compute_rust/main.rs"
[features]
default = []
local = ["wgpu-native/local"]
metal = ["wgpu/metal"]
dx11 = ["wgpu/dx11"]
dx12 = ["wgpu/dx12"]
vulkan = ["wgpu/vulkan"]
[dependencies]
wgpu-native = { path = "../wgpu-native" }
wgpu = { path = "../wgpu-rs" }
env_logger = "0.6"

View File

@ -1,94 +0,0 @@
use std::str::FromStr;
fn main() {
env_logger::init();
// For now this just panics if you didn't pass numbers. Could add proper error handling.
if std::env::args().len() == 1 {
panic!("You must pass a list of positive integers!")
}
let numbers: Vec<u32> = std::env::args()
.skip(1)
.map(|s| u32::from_str(&s).expect("You must pass a list of positive integers!"))
.collect();
let size = (numbers.len() * std::mem::size_of::<u32>()) as u32;
let instance = wgpu::Instance::new();
let adapter = instance.get_adapter(&wgpu::AdapterDescriptor {
power_preference: wgpu::PowerPreference::Default,
});
let mut device = adapter.create_device(&wgpu::DeviceDescriptor {
extensions: wgpu::Extensions {
anisotropic_filtering: false,
},
});
let cs_bytes = include_bytes!("./../data/collatz.comp.spv");
let cs_module = device.create_shader_module(cs_bytes);
let staging_buffer = device
.create_buffer_mapped(
numbers.len(),
wgpu::BufferUsageFlags::MAP_READ
| wgpu::BufferUsageFlags::TRANSFER_DST
| wgpu::BufferUsageFlags::TRANSFER_SRC,
)
.fill_from_slice(&numbers);
let storage_buffer = device.create_buffer(&wgpu::BufferDescriptor {
size,
usage: wgpu::BufferUsageFlags::STORAGE
| wgpu::BufferUsageFlags::TRANSFER_DST
| wgpu::BufferUsageFlags::TRANSFER_SRC,
});
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[wgpu::BindGroupLayoutBinding {
binding: 0,
visibility: wgpu::ShaderStageFlags::COMPUTE,
ty: wgpu::BindingType::StorageBuffer,
}],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &bind_group_layout,
bindings: &[wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &storage_buffer,
range: 0..size,
},
}],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[&bind_group_layout],
});
let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
layout: &pipeline_layout,
compute_stage: wgpu::PipelineStageDescriptor {
module: &cs_module,
entry_point: "main",
},
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
encoder.copy_buffer_to_buffer(&staging_buffer, 0, &storage_buffer, 0, size);
{
let mut cpass = encoder.begin_compute_pass();
cpass.set_pipeline(&compute_pipeline);
cpass.set_bind_group(0, &bind_group, &[]);
cpass.dispatch(numbers.len() as u32, 1, 1);
}
encoder.copy_buffer_to_buffer(&storage_buffer, 0, &staging_buffer, 0, size);
device.get_queue().submit(&[encoder.finish()]);
staging_buffer.map_read_async(0, size, |result: wgpu::BufferMapAsyncResult<&[u32]>| {
if let Ok(mapping) = result {
println!("Times: {:?}", mapping.data);
}
});
}

View File

@ -7,17 +7,17 @@ set(TARGET_NAME hello_triangle)
add_executable(hello_triangle main.c)
if(MSVC)
add_definitions(-DWGPU_TARGET=WGPU_TARGET_WINDOWS)
target_compile_options(${TARGET_NAME} PRIVATE /W4)
add_compile_definitions(WGPU_TARGET=WGPU_TARGET_WINDOWS)
set(GLFW_LIBRARY glfw3)
elseif(APPLE)
add_compile_definitions(WGPU_TARGET=WGPU_TARGET_MACOS)
add_definitions(-DWGPU_TARGET=WGPU_TARGET_MACOS)
set(OS_LIBRARIES "-framework Cocoa" "-framework CoreVideo" "-framework IOKit" "-framework QuartzCore")
target_compile_options(${TARGET_NAME} PRIVATE -x objective-c)
set(GLFW_LIBRARY glfw)
else(MSVC)
add_definitions(-DWGPU_TARGET=WGPU_TARGET_LINUX)
target_compile_options(${TARGET_NAME} PRIVATE -Wall -Wextra -pedantic)
add_compile_definitions(WGPU_TARGET=WGPU_TARGET_LINUX)
set(GLFW_LIBRARY glfw)
endif(MSVC)

View File

@ -1,5 +1,6 @@
#include "./../../ffi/wgpu.h"
#include <stdio.h>
#include <stdlib.h>
#define WGPU_TARGET_MACOS 1
#define WGPU_TARGET_LINUX 2

View File

@ -1,128 +0,0 @@
fn main() {
env_logger::init();
let instance = wgpu::Instance::new();
let adapter = instance.get_adapter(&wgpu::AdapterDescriptor {
power_preference: wgpu::PowerPreference::LowPower,
});
let mut device = adapter.create_device(&wgpu::DeviceDescriptor {
extensions: wgpu::Extensions {
anisotropic_filtering: false,
},
});
let vs_bytes = include_bytes!("./../data/hello_triangle.vert.spv");
let vs_module = device.create_shader_module(vs_bytes);
let fs_bytes = include_bytes!("./../data/hello_triangle.frag.spv");
let fs_module = device.create_shader_module(fs_bytes);
let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { bindings: &[] });
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &bind_group_layout,
bindings: &[],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[&bind_group_layout],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
layout: &pipeline_layout,
vertex_stage: wgpu::PipelineStageDescriptor {
module: &vs_module,
entry_point: "main",
},
fragment_stage: wgpu::PipelineStageDescriptor {
module: &fs_module,
entry_point: "main",
},
rasterization_state: wgpu::RasterizationStateDescriptor {
front_face: wgpu::FrontFace::Ccw,
cull_mode: wgpu::CullMode::None,
depth_bias: 0,
depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0,
},
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[wgpu::ColorStateDescriptor {
format: wgpu::TextureFormat::Bgra8Unorm,
color: wgpu::BlendDescriptor::REPLACE,
alpha: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWriteFlags::ALL,
}],
depth_stencil_state: None,
index_format: wgpu::IndexFormat::Uint16,
vertex_buffers: &[],
sample_count: 1,
});
use wgpu::winit::{
ElementState,
Event,
EventsLoop,
KeyboardInput,
VirtualKeyCode,
Window,
WindowEvent,
};
let mut events_loop = EventsLoop::new();
let window = Window::new(&events_loop).unwrap();
let size = window
.get_inner_size()
.unwrap()
.to_physical(window.get_hidpi_factor());
let surface = instance.create_surface(&window);
let mut swap_chain = device.create_swap_chain(
&surface,
&wgpu::SwapChainDescriptor {
usage: wgpu::TextureUsageFlags::OUTPUT_ATTACHMENT,
format: wgpu::TextureFormat::Bgra8Unorm,
width: size.width.round() as u32,
height: size.height.round() as u32,
},
);
let mut running = true;
while running {
events_loop.poll_events(|event| match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::KeyboardInput {
input:
KeyboardInput {
virtual_keycode: Some(code),
state: ElementState::Pressed,
..
},
..
} => match code {
VirtualKeyCode::Escape => running = false,
_ => {}
},
WindowEvent::CloseRequested => running = false,
_ => {}
},
_ => {}
});
let frame = swap_chain.get_next_texture();
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
{
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
attachment: &frame.view,
load_op: wgpu::LoadOp::Clear,
store_op: wgpu::StoreOp::Store,
clear_color: wgpu::Color::GREEN,
}],
depth_stencil_attachment: None,
});
rpass.set_pipeline(&render_pipeline);
rpass.set_bind_group(0, &bind_group, &[]);
rpass.draw(0..3, 0..1);
}
device.get_queue().submit(&[encoder.finish()]);
}
}

View File

@ -1,19 +0,0 @@
lunarg_core_validation.debug_action = VK_DBG_LAYER_ACTION_LOG_MSG
lunarg_core_validation.report_flags = error,warn,perf
lunarg_core_validation.log_filename = stdout
lunarg_object_tracker.debug_action = VK_DBG_LAYER_ACTION_LOG_MSG
lunarg_object_tracker.report_flags = error,warn,perf
lunarg_object_tracker.log_filename = stdout
lunarg_parameter_validation.debug_action = VK_DBG_LAYER_ACTION_LOG_MSG
lunarg_parameter_validation.report_flags = error,warn,perf
lunarg_parameter_validation.log_filename = stdout
google_threading.debug_action = VK_DBG_LAYER_ACTION_LOG_MSG
google_threading.report_flags = error,warn,perf
google_threading.log_filename = stdout
google_unique_objects.debug_action = VK_DBG_LAYER_ACTION_LOG_MSG
google_unique_objects.report_flags = error,warn,perf
google_unique_objects.log_filename = stdout

View File

@ -1,6 +1,6 @@
/* Generated with cbindgen:0.8.3 */
/* Generated with cbindgen:0.8.6 */
#include <stdarg.h>
#include <stdbool.h>

View File

@ -1,6 +1,6 @@
#define WGPU_LOCAL
/* Generated with cbindgen:0.8.3 */
/* Generated with cbindgen:0.8.6 */
#include <stdarg.h>
#include <stdbool.h>
@ -630,7 +630,9 @@ typedef struct {
#if defined(WGPU_LOCAL)
WGPUDeviceId wgpu_adapter_create_device(WGPUAdapterId adapter_id, const WGPUDeviceDescriptor *desc);
#endif
void wgpu_bind_group_destroy(WGPUBindGroupId bind_group_id);
@ -672,10 +674,14 @@ void wgpu_command_buffer_copy_texture_to_texture(WGPUCommandBufferId command_buf
const WGPUTextureCopyView *destination,
WGPUExtent3d copy_size);
#if defined(WGPU_LOCAL)
WGPUComputePassId wgpu_command_encoder_begin_compute_pass(WGPUCommandEncoderId command_encoder_id);
#endif
#if defined(WGPU_LOCAL)
WGPURenderPassId wgpu_command_encoder_begin_render_pass(WGPUCommandEncoderId command_encoder_id,
WGPURenderPassDescriptor desc);
#endif
WGPUCommandBufferId wgpu_command_encoder_finish(WGPUCommandEncoderId command_encoder_id);
@ -691,42 +697,68 @@ void wgpu_compute_pass_set_bind_group(WGPUComputePassId pass_id,
void wgpu_compute_pass_set_pipeline(WGPUComputePassId pass_id, WGPUComputePipelineId pipeline_id);
#if defined(WGPU_LOCAL)
WGPUInstanceId wgpu_create_instance(void);
#endif
#if defined(WGPU_LOCAL)
WGPUBindGroupId wgpu_device_create_bind_group(WGPUDeviceId device_id,
const WGPUBindGroupDescriptor *desc);
#endif
#if defined(WGPU_LOCAL)
WGPUBindGroupLayoutId wgpu_device_create_bind_group_layout(WGPUDeviceId device_id,
const WGPUBindGroupLayoutDescriptor *desc);
#endif
#if defined(WGPU_LOCAL)
WGPUBufferId wgpu_device_create_buffer(WGPUDeviceId device_id, const WGPUBufferDescriptor *desc);
#endif
#if defined(WGPU_LOCAL)
WGPUBufferId wgpu_device_create_buffer_mapped(WGPUDeviceId device_id,
const WGPUBufferDescriptor *desc,
uint8_t **mapped_ptr_out);
#endif
#if defined(WGPU_LOCAL)
WGPUCommandEncoderId wgpu_device_create_command_encoder(WGPUDeviceId device_id,
const WGPUCommandEncoderDescriptor *desc);
#endif
#if defined(WGPU_LOCAL)
WGPUComputePipelineId wgpu_device_create_compute_pipeline(WGPUDeviceId device_id,
const WGPUComputePipelineDescriptor *desc);
#endif
#if defined(WGPU_LOCAL)
WGPUPipelineLayoutId wgpu_device_create_pipeline_layout(WGPUDeviceId device_id,
const WGPUPipelineLayoutDescriptor *desc);
#endif
#if defined(WGPU_LOCAL)
WGPURenderPipelineId wgpu_device_create_render_pipeline(WGPUDeviceId device_id,
const WGPURenderPipelineDescriptor *desc);
#endif
#if defined(WGPU_LOCAL)
WGPUSamplerId wgpu_device_create_sampler(WGPUDeviceId device_id, const WGPUSamplerDescriptor *desc);
#endif
#if defined(WGPU_LOCAL)
WGPUShaderModuleId wgpu_device_create_shader_module(WGPUDeviceId device_id,
const WGPUShaderModuleDescriptor *desc);
#endif
#if defined(WGPU_LOCAL)
WGPUSwapChainId wgpu_device_create_swap_chain(WGPUDeviceId device_id,
WGPUSurfaceId surface_id,
const WGPUSwapChainDescriptor *desc);
#endif
#if defined(WGPU_LOCAL)
WGPUTextureId wgpu_device_create_texture(WGPUDeviceId device_id, const WGPUTextureDescriptor *desc);
#endif
void wgpu_device_destroy(WGPUDeviceId device_id);
@ -734,24 +766,27 @@ WGPUQueueId wgpu_device_get_queue(WGPUDeviceId device_id);
void wgpu_device_poll(WGPUDeviceId device_id, bool force_wait);
#if defined(WGPU_LOCAL)
WGPUSurfaceId wgpu_instance_create_surface_from_macos_layer(WGPUInstanceId instance_id,
void *layer);
#endif
#if defined(WGPU_LOCAL)
WGPUSurfaceId wgpu_instance_create_surface_from_windows_hwnd(WGPUInstanceId instance_id,
void *hinstance,
void *hwnd);
#if defined(WGPU_WINDOW_WINIT)
WGPUSurfaceId wgpu_instance_create_surface_from_winit(WGPUInstanceId instance_id,
const WGPUWindow *window);
#endif
#if defined(WGPU_LOCAL)
WGPUSurfaceId wgpu_instance_create_surface_from_xlib(WGPUInstanceId instance_id,
const void **display,
uint64_t window);
#endif
#if defined(WGPU_LOCAL)
WGPUAdapterId wgpu_instance_get_adapter(WGPUInstanceId instance_id,
const WGPUAdapterDescriptor *desc);
#endif
void wgpu_queue_submit(WGPUQueueId queue_id,
const WGPUCommandBufferId *command_buffer_ptr,
@ -801,10 +836,14 @@ WGPUSwapChainOutput wgpu_swap_chain_get_next_texture(WGPUSwapChainId swap_chain_
void wgpu_swap_chain_present(WGPUSwapChainId swap_chain_id);
#if defined(WGPU_LOCAL)
WGPUTextureViewId wgpu_texture_create_default_view(WGPUTextureId texture_id);
#endif
#if defined(WGPU_LOCAL)
WGPUTextureViewId wgpu_texture_create_view(WGPUTextureId texture_id,
const WGPUTextureViewDescriptor *desc);
#endif
void wgpu_texture_destroy(WGPUTextureId texture_id);

View File

@ -1,32 +0,0 @@
[package]
name = "gfx-examples"
version = "0.1.0"
authors = [
"Dzmitry Malyshau <kvark@mozilla.com>",
"Joshua Groves <josh@joshgroves.com>",
]
edition = "2018"
publish = false
[[bin]]
name = "cube"
path = "src/cube.rs"
[[bin]]
name = "shadow"
path = "src/shadow.rs"
[features]
default = []
metal-auto-capture = ["wgpu/metal-auto-capture"]
metal = ["wgpu/metal"]
dx11 = ["wgpu/dx11"]
dx12 = ["wgpu/dx12"]
vulkan = ["wgpu/vulkan"]
[dependencies]
wgpu = { path = "../wgpu-rs" }
cgmath = "0.17"
env_logger = "0.6"
glsl-to-spirv = "0.1"
log = "0.4"

View File

@ -1,6 +0,0 @@
# gfx pre-ll examples
The original gfx-rs examples had grown over several years, but then were abandoned when the gfx API was changed to match Vulkan:
https://github.com/gfx-rs/gfx/tree/pre-ll/examples
wgpu-rs is considered to be the spiritual successor of gfx pre-ll, so this is the new home for the examples.

View File

@ -1,12 +0,0 @@
#version 450
layout(location = 0) in vec2 v_TexCoord;
layout(location = 0) out vec4 o_Target;
layout(set = 0, binding = 1) uniform texture2D t_Color;
layout(set = 0, binding = 2) uniform sampler s_Color;
void main() {
vec4 tex = texture(sampler2D(t_Color, s_Color), v_TexCoord);
float mag = length(v_TexCoord-vec2(0.5));
o_Target = mix(tex, vec4(0.0), mag*mag);
}

View File

@ -1,16 +0,0 @@
#version 450
layout(location = 0) in vec4 a_Pos;
layout(location = 1) in vec2 a_TexCoord;
layout(location = 0) out vec2 v_TexCoord;
layout(set = 0, binding = 0) uniform Locals {
mat4 u_Transform;
};
void main() {
v_TexCoord = a_TexCoord;
gl_Position = u_Transform * a_Pos;
// convert from -1,1 Z to 0,1
gl_Position.z = 0.5 * (gl_Position.z + gl_Position.w);
}

View File

@ -1,4 +0,0 @@
#version 450
void main() {
}

View File

@ -1,18 +0,0 @@
#version 450
layout(location = 0) in ivec4 a_Pos;
layout(set = 0, binding = 0) uniform Globals {
mat4 u_ViewProj;
};
layout(set = 1, binding = 0) uniform Entity {
mat4 u_World;
vec4 u_Color;
};
void main() {
gl_Position = u_ViewProj * u_World * vec4(a_Pos);
// convert from -1,1 Z to 0,1
gl_Position.z = 0.5 * (gl_Position.z + gl_Position.w);
}

View File

@ -1,54 +0,0 @@
#version 450
const int MAX_LIGHTS = 10;
layout(location = 0) in vec3 v_Normal;
layout(location = 1) in vec4 v_Position;
layout(location = 0) out vec4 o_Target;
struct Light {
mat4 proj;
vec4 pos;
vec4 color;
};
layout(set = 0, binding = 0) uniform Globals {
mat4 u_ViewProj;
uvec4 u_NumLights;
};
layout(set = 0, binding = 1) uniform Lights {
Light u_Lights[MAX_LIGHTS];
};
layout(set = 0, binding = 2) uniform texture2DArray t_Shadow;
layout(set = 0, binding = 3) uniform samplerShadow s_Shadow;
layout(set = 1, binding = 0) uniform Entity {
mat4 u_World;
vec4 u_Color;
};
void main() {
vec3 normal = normalize(v_Normal);
vec3 ambient = vec3(0.05, 0.05, 0.05);
// accumulate color
vec3 color = ambient;
for (int i=0; i<int(u_NumLights.x) && i<MAX_LIGHTS; ++i) {
Light light = u_Lights[i];
// project into the light space
vec4 light_local = light.proj * v_Position;
// compute texture coordinates for shadow lookup
light_local.xyw = (light_local.xyz/light_local.w + 1.0) / 2.0;
light_local.z = i;
// do the lookup, using HW PCF and comparison
float shadow = texture(sampler2DArrayShadow(t_Shadow, s_Shadow), light_local);
// compute Lambertian diffuse term
vec3 light_dir = normalize(light.pos.xyz - v_Position.xyz);
float diffuse = max(0.0, dot(normal, light_dir));
// add light contribution
color += shadow * diffuse * light.color.xyz;
}
// multiply the light by material color
o_Target = vec4(color, 1.0) * u_Color;
}

View File

@ -1,24 +0,0 @@
#version 450
layout(location = 0) in ivec4 a_Pos;
layout(location = 1) in ivec4 a_Normal;
layout(location = 0) out vec3 v_Normal;
layout(location = 1) out vec4 v_Position;
layout(set = 0, binding = 0) uniform Globals {
mat4 u_ViewProj;
uvec4 u_NumLights;
};
layout(set = 1, binding = 0) uniform Entity {
mat4 u_World;
vec4 u_Color;
};
void main() {
v_Normal = mat3(u_World) * vec3(a_Normal.xyz);
v_Position = u_World * vec4(a_Pos);
gl_Position = u_ViewProj * v_Position;
// convert from -1,1 Z to 0,1
gl_Position.z = 0.5 * (gl_Position.z + gl_Position.w);
}

View File

@ -1,345 +0,0 @@
mod framework;
#[derive(Clone, Copy)]
struct Vertex {
_pos: [f32; 4],
_tex_coord: [f32; 2],
}
fn vertex(pos: [i8; 3], tc: [i8; 2]) -> Vertex {
Vertex {
_pos: [pos[0] as f32, pos[1] as f32, pos[2] as f32, 1.0],
_tex_coord: [tc[0] as f32, tc[1] as f32],
}
}
fn create_vertices() -> (Vec<Vertex>, Vec<u16>) {
let vertex_data = [
// top (0, 0, 1)
vertex([-1, -1, 1], [0, 0]),
vertex([1, -1, 1], [1, 0]),
vertex([1, 1, 1], [1, 1]),
vertex([-1, 1, 1], [0, 1]),
// bottom (0, 0, -1)
vertex([-1, 1, -1], [1, 0]),
vertex([1, 1, -1], [0, 0]),
vertex([1, -1, -1], [0, 1]),
vertex([-1, -1, -1], [1, 1]),
// right (1, 0, 0)
vertex([1, -1, -1], [0, 0]),
vertex([1, 1, -1], [1, 0]),
vertex([1, 1, 1], [1, 1]),
vertex([1, -1, 1], [0, 1]),
// left (-1, 0, 0)
vertex([-1, -1, 1], [1, 0]),
vertex([-1, 1, 1], [0, 0]),
vertex([-1, 1, -1], [0, 1]),
vertex([-1, -1, -1], [1, 1]),
// front (0, 1, 0)
vertex([1, 1, -1], [1, 0]),
vertex([-1, 1, -1], [0, 0]),
vertex([-1, 1, 1], [0, 1]),
vertex([1, 1, 1], [1, 1]),
// back (0, -1, 0)
vertex([1, -1, 1], [0, 0]),
vertex([-1, -1, 1], [1, 0]),
vertex([-1, -1, -1], [1, 1]),
vertex([1, -1, -1], [0, 1]),
];
let index_data: &[u16] = &[
0, 1, 2, 2, 3, 0, // top
4, 5, 6, 6, 7, 4, // bottom
8, 9, 10, 10, 11, 8, // right
12, 13, 14, 14, 15, 12, // left
16, 17, 18, 18, 19, 16, // front
20, 21, 22, 22, 23, 20, // back
];
(vertex_data.to_vec(), index_data.to_vec())
}
fn create_texels(size: usize) -> Vec<u8> {
use std::iter;
(0..size * size)
.flat_map(|id| {
// get high five for recognizing this ;)
let cx = 3.0 * (id % size) as f32 / (size - 1) as f32 - 2.0;
let cy = 2.0 * (id / size) as f32 / (size - 1) as f32 - 1.0;
let (mut x, mut y, mut count) = (cx, cy, 0);
while count < 0xFF && x * x + y * y < 4.0 {
let old_x = x;
x = x * x - y * y + cx;
y = 2.0 * old_x * y + cy;
count += 1;
}
iter::once(0xFF - (count * 5) as u8)
.chain(iter::once(0xFF - (count * 15) as u8))
.chain(iter::once(0xFF - (count * 50) as u8))
.chain(iter::once(1))
})
.collect()
}
struct Example {
vertex_buf: wgpu::Buffer,
index_buf: wgpu::Buffer,
index_count: usize,
bind_group: wgpu::BindGroup,
uniform_buf: wgpu::Buffer,
pipeline: wgpu::RenderPipeline,
}
impl Example {
fn generate_matrix(aspect_ratio: f32) -> cgmath::Matrix4<f32> {
let mx_projection = cgmath::perspective(cgmath::Deg(45f32), aspect_ratio, 1.0, 10.0);
let mx_view = cgmath::Matrix4::look_at(
cgmath::Point3::new(1.5f32, -5.0, 3.0),
cgmath::Point3::new(0f32, 0.0, 0.0),
-cgmath::Vector3::unit_z(),
);
mx_projection * mx_view
}
}
impl framework::Example for Example {
fn init(sc_desc: &wgpu::SwapChainDescriptor, device: &mut wgpu::Device) -> Self {
use std::mem;
let mut init_encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
// Create the vertex and index buffers
let vertex_size = mem::size_of::<Vertex>();
let (vertex_data, index_data) = create_vertices();
let vertex_buf = device
.create_buffer_mapped(vertex_data.len(), wgpu::BufferUsageFlags::VERTEX)
.fill_from_slice(&vertex_data);
let index_buf = device
.create_buffer_mapped(index_data.len(), wgpu::BufferUsageFlags::INDEX)
.fill_from_slice(&index_data);
// Create pipeline layout
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[
wgpu::BindGroupLayoutBinding {
binding: 0,
visibility: wgpu::ShaderStageFlags::VERTEX,
ty: wgpu::BindingType::UniformBuffer,
},
wgpu::BindGroupLayoutBinding {
binding: 1,
visibility: wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::SampledTexture,
},
wgpu::BindGroupLayoutBinding {
binding: 2,
visibility: wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::Sampler,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[&bind_group_layout],
});
// Create the texture
let size = 256u32;
let texels = create_texels(size as usize);
let texture_extent = wgpu::Extent3d {
width: size,
height: size,
depth: 1,
};
let texture = device.create_texture(&wgpu::TextureDescriptor {
size: texture_extent,
array_size: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsageFlags::SAMPLED | wgpu::TextureUsageFlags::TRANSFER_DST,
});
let texture_view = texture.create_default_view();
let temp_buf = device
.create_buffer_mapped(texels.len(), wgpu::BufferUsageFlags::TRANSFER_SRC)
.fill_from_slice(&texels);
init_encoder.copy_buffer_to_texture(
wgpu::BufferCopyView {
buffer: &temp_buf,
offset: 0,
row_pitch: 4 * size,
image_height: size,
},
wgpu::TextureCopyView {
texture: &texture,
level: 0,
slice: 0,
origin: wgpu::Origin3d {
x: 0.0,
y: 0.0,
z: 0.0,
},
},
texture_extent,
);
// Create other resources
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
r_address_mode: wgpu::AddressMode::ClampToEdge,
s_address_mode: wgpu::AddressMode::ClampToEdge,
t_address_mode: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::FilterMode::Nearest,
lod_min_clamp: -100.0,
lod_max_clamp: 100.0,
max_anisotropy: 0,
compare_function: wgpu::CompareFunction::Always,
border_color: wgpu::BorderColor::TransparentBlack,
});
let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
let mx_ref: &[f32; 16] = mx_total.as_ref();
let uniform_buf = device
.create_buffer_mapped(
16,
wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST,
)
.fill_from_slice(mx_ref);
// Create bind group
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &bind_group_layout,
bindings: &[
wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &uniform_buf,
range: 0..64,
},
},
wgpu::Binding {
binding: 1,
resource: wgpu::BindingResource::TextureView(&texture_view),
},
wgpu::Binding {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
});
// Create the render pipeline
let vs_bytes = framework::load_glsl("cube.vert", framework::ShaderStage::Vertex);
let fs_bytes = framework::load_glsl("cube.frag", framework::ShaderStage::Fragment);
let vs_module = device.create_shader_module(&vs_bytes);
let fs_module = device.create_shader_module(&fs_bytes);
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
layout: &pipeline_layout,
vertex_stage: wgpu::PipelineStageDescriptor {
module: &vs_module,
entry_point: "main",
},
fragment_stage: wgpu::PipelineStageDescriptor {
module: &fs_module,
entry_point: "main",
},
rasterization_state: wgpu::RasterizationStateDescriptor {
front_face: wgpu::FrontFace::Cw,
cull_mode: wgpu::CullMode::Back,
depth_bias: 0,
depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0,
},
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[wgpu::ColorStateDescriptor {
format: sc_desc.format,
color: wgpu::BlendDescriptor::REPLACE,
alpha: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWriteFlags::ALL,
}],
depth_stencil_state: None,
index_format: wgpu::IndexFormat::Uint16,
vertex_buffers: &[wgpu::VertexBufferDescriptor {
stride: vertex_size as u32,
step_mode: wgpu::InputStepMode::Vertex,
attributes: &[
wgpu::VertexAttributeDescriptor {
attribute_index: 0,
format: wgpu::VertexFormat::Float4,
offset: 0,
},
wgpu::VertexAttributeDescriptor {
attribute_index: 1,
format: wgpu::VertexFormat::Float2,
offset: 4 * 4,
},
],
}],
sample_count: 1,
});
// Done
let init_command_buf = init_encoder.finish();
device.get_queue().submit(&[init_command_buf]);
Example {
vertex_buf,
index_buf,
index_count: index_data.len(),
bind_group,
uniform_buf,
pipeline,
}
}
fn update(&mut self, _event: wgpu::winit::WindowEvent) {
//empty
}
fn resize(&mut self, sc_desc: &wgpu::SwapChainDescriptor, device: &mut wgpu::Device) {
let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
let mx_ref: &[f32; 16] = mx_total.as_ref();
let temp_buf = device
.create_buffer_mapped(16, wgpu::BufferUsageFlags::TRANSFER_SRC)
.fill_from_slice(mx_ref);
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
encoder.copy_buffer_to_buffer(&temp_buf, 0, &self.uniform_buf, 0, 64);
device.get_queue().submit(&[encoder.finish()]);
}
fn render(&mut self, frame: &wgpu::SwapChainOutput, device: &mut wgpu::Device) {
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
{
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
attachment: &frame.view,
load_op: wgpu::LoadOp::Clear,
store_op: wgpu::StoreOp::Store,
clear_color: wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.3,
a: 1.0,
},
}],
depth_stencil_attachment: None,
});
rpass.set_pipeline(&self.pipeline);
rpass.set_bind_group(0, &self.bind_group, &[]);
rpass.set_index_buffer(&self.index_buf, 0);
rpass.set_vertex_buffers(&[(&self.vertex_buf, 0)]);
rpass.draw_indexed(0..self.index_count as u32, 0, 0..1);
}
device.get_queue().submit(&[encoder.finish()]);
}
}
fn main() {
framework::run::<Example>("cube");
}

View File

@ -1,132 +0,0 @@
use log::info;
#[allow(dead_code)]
pub fn cast_slice<T>(data: &[T]) -> &[u8] {
use std::mem::size_of;
use std::slice::from_raw_parts;
unsafe { from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::<T>()) }
}
#[allow(dead_code)]
pub enum ShaderStage {
Vertex,
Fragment,
Compute,
}
pub fn load_glsl(name: &str, stage: ShaderStage) -> Vec<u8> {
use std::fs::read_to_string;
use std::io::Read;
use std::path::PathBuf;
let ty = match stage {
ShaderStage::Vertex => glsl_to_spirv::ShaderType::Vertex,
ShaderStage::Fragment => glsl_to_spirv::ShaderType::Fragment,
ShaderStage::Compute => glsl_to_spirv::ShaderType::Compute,
};
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("data")
.join(name);
let code = match read_to_string(&path) {
Ok(code) => code,
Err(e) => panic!("Unable to read {:?}: {:?}", path, e),
};
let mut output = glsl_to_spirv::compile(&code, ty).unwrap();
let mut spv = Vec::new();
output.read_to_end(&mut spv).unwrap();
spv
}
pub trait Example {
fn init(sc_desc: &wgpu::SwapChainDescriptor, device: &mut wgpu::Device) -> Self;
fn resize(&mut self, sc_desc: &wgpu::SwapChainDescriptor, device: &mut wgpu::Device);
fn update(&mut self, event: wgpu::winit::WindowEvent);
fn render(&mut self, frame: &wgpu::SwapChainOutput, device: &mut wgpu::Device);
}
pub fn run<E: Example>(title: &str) {
use wgpu::winit::{
ElementState,
Event,
EventsLoop,
KeyboardInput,
VirtualKeyCode,
Window,
WindowEvent,
};
info!("Initializing the device...");
env_logger::init();
let instance = wgpu::Instance::new();
let adapter = instance.get_adapter(&wgpu::AdapterDescriptor {
power_preference: wgpu::PowerPreference::LowPower,
});
let mut device = adapter.create_device(&wgpu::DeviceDescriptor {
extensions: wgpu::Extensions {
anisotropic_filtering: false,
},
});
info!("Initializing the window...");
let mut events_loop = EventsLoop::new();
let window = Window::new(&events_loop).unwrap();
window.set_title(title);
let size = window
.get_inner_size()
.unwrap()
.to_physical(window.get_hidpi_factor());
let surface = instance.create_surface(&window);
let mut sc_desc = wgpu::SwapChainDescriptor {
usage: wgpu::TextureUsageFlags::OUTPUT_ATTACHMENT,
format: wgpu::TextureFormat::Bgra8Unorm,
width: size.width.round() as u32,
height: size.height.round() as u32,
};
let mut swap_chain = device.create_swap_chain(&surface, &sc_desc);
info!("Initializing the example...");
let mut example = E::init(&sc_desc, &mut device);
info!("Entering render loop...");
let mut running = true;
while running {
events_loop.poll_events(|event| match event {
Event::WindowEvent {
event: WindowEvent::Resized(size),
..
} => {
let physical = size.to_physical(window.get_hidpi_factor());
info!("Resizing to {:?}", physical);
sc_desc.width = physical.width.round() as u32;
sc_desc.height = physical.height.round() as u32;
swap_chain = device.create_swap_chain(&surface, &sc_desc);
example.resize(&sc_desc, &mut device);
}
Event::WindowEvent { event, .. } => match event {
WindowEvent::KeyboardInput {
input:
KeyboardInput {
virtual_keycode: Some(VirtualKeyCode::Escape),
state: ElementState::Pressed,
..
},
..
}
| WindowEvent::CloseRequested => {
running = false;
}
_ => {
example.update(event);
}
},
_ => (),
});
let frame = swap_chain.get_next_texture();
example.render(&frame, &mut device);
running &= !cfg!(feature = "metal-auto-capture");
}
}

View File

@ -1,795 +0,0 @@
use std::mem;
use std::ops::Range;
use std::rc::Rc;
mod framework;
#[derive(Clone, Copy)]
struct Vertex {
_pos: [i8; 4],
_normal: [i8; 4],
}
fn vertex(pos: [i8; 3], nor: [i8; 3]) -> Vertex {
Vertex {
_pos: [pos[0], pos[1], pos[2], 1],
_normal: [nor[0], nor[1], nor[2], 0],
}
}
fn create_cube() -> (Vec<Vertex>, Vec<u16>) {
let vertex_data = [
// top (0, 0, 1)
vertex([-1, -1, 1], [0, 0, 1]),
vertex([1, -1, 1], [0, 0, 1]),
vertex([1, 1, 1], [0, 0, 1]),
vertex([-1, 1, 1], [0, 0, 1]),
// bottom (0, 0, -1)
vertex([-1, 1, -1], [0, 0, -1]),
vertex([1, 1, -1], [0, 0, -1]),
vertex([1, -1, -1], [0, 0, -1]),
vertex([-1, -1, -1], [0, 0, -1]),
// right (1, 0, 0)
vertex([1, -1, -1], [1, 0, 0]),
vertex([1, 1, -1], [1, 0, 0]),
vertex([1, 1, 1], [1, 0, 0]),
vertex([1, -1, 1], [1, 0, 0]),
// left (-1, 0, 0)
vertex([-1, -1, 1], [-1, 0, 0]),
vertex([-1, 1, 1], [-1, 0, 0]),
vertex([-1, 1, -1], [-1, 0, 0]),
vertex([-1, -1, -1], [-1, 0, 0]),
// front (0, 1, 0)
vertex([1, 1, -1], [0, 1, 0]),
vertex([-1, 1, -1], [0, 1, 0]),
vertex([-1, 1, 1], [0, 1, 0]),
vertex([1, 1, 1], [0, 1, 0]),
// back (0, -1, 0)
vertex([1, -1, 1], [0, -1, 0]),
vertex([-1, -1, 1], [0, -1, 0]),
vertex([-1, -1, -1], [0, -1, 0]),
vertex([1, -1, -1], [0, -1, 0]),
];
let index_data: &[u16] = &[
0, 1, 2, 2, 3, 0, // top
4, 5, 6, 6, 7, 4, // bottom
8, 9, 10, 10, 11, 8, // right
12, 13, 14, 14, 15, 12, // left
16, 17, 18, 18, 19, 16, // front
20, 21, 22, 22, 23, 20, // back
];
(vertex_data.to_vec(), index_data.to_vec())
}
fn create_plane(size: i8) -> (Vec<Vertex>, Vec<u16>) {
let vertex_data = [
vertex([size, -size, 0], [0, 0, 1]),
vertex([size, size, 0], [0, 0, 1]),
vertex([-size, -size, 0], [0, 0, 1]),
vertex([-size, size, 0], [0, 0, 1]),
];
let index_data: &[u16] = &[0, 1, 2, 2, 1, 3];
(vertex_data.to_vec(), index_data.to_vec())
}
struct Entity {
mx_world: cgmath::Matrix4<f32>,
rotation_speed: f32,
color: wgpu::Color,
vertex_buf: Rc<wgpu::Buffer>,
index_buf: Rc<wgpu::Buffer>,
index_count: usize,
bind_group: wgpu::BindGroup,
uniform_buf: wgpu::Buffer,
}
struct Light {
pos: cgmath::Point3<f32>,
color: wgpu::Color,
fov: f32,
depth: Range<f32>,
target_view: wgpu::TextureView,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct LightRaw {
proj: [[f32; 4]; 4],
pos: [f32; 4],
color: [f32; 4],
}
impl Light {
fn to_raw(&self) -> LightRaw {
use cgmath::{Deg, EuclideanSpace, Matrix4, PerspectiveFov, Point3, Vector3};
let mx_view = Matrix4::look_at(self.pos, Point3::origin(), -Vector3::unit_z());
let projection = PerspectiveFov {
fovy: Deg(self.fov).into(),
aspect: 1.0,
near: self.depth.start,
far: self.depth.end,
};
let mx_view_proj = cgmath::Matrix4::from(projection.to_perspective()) * mx_view;
LightRaw {
proj: *mx_view_proj.as_ref(),
pos: [self.pos.x, self.pos.y, self.pos.z, 1.0],
color: [self.color.r, self.color.g, self.color.b, 1.0],
}
}
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ForwardUniforms {
proj: [[f32; 4]; 4],
num_lights: [u32; 4],
}
#[repr(C)]
#[derive(Clone, Copy)]
struct EntityUniforms {
model: cgmath::Matrix4<f32>,
color: [f32; 4],
}
#[repr(C)]
struct ShadowUniforms {
proj: [[f32; 4]; 4],
}
struct Pass {
pipeline: wgpu::RenderPipeline,
bind_group: wgpu::BindGroup,
uniform_buf: wgpu::Buffer,
}
struct Example {
entities: Vec<Entity>,
lights: Vec<Light>,
lights_are_dirty: bool,
shadow_pass: Pass,
forward_pass: Pass,
forward_depth: wgpu::TextureView,
light_uniform_buf: wgpu::Buffer,
}
impl Example {
const MAX_LIGHTS: usize = 10;
const SHADOW_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::D32Float;
const SHADOW_SIZE: wgpu::Extent3d = wgpu::Extent3d {
width: 512,
height: 512,
depth: 1,
};
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::D32Float;
fn generate_matrix(aspect_ratio: f32) -> cgmath::Matrix4<f32> {
let mx_projection = cgmath::perspective(cgmath::Deg(45f32), aspect_ratio, 1.0, 20.0);
let mx_view = cgmath::Matrix4::look_at(
cgmath::Point3::new(3.0f32, -10.0, 6.0),
cgmath::Point3::new(0f32, 0.0, 0.0),
-cgmath::Vector3::unit_z(),
);
mx_projection * mx_view
}
}
impl framework::Example for Example {
fn init(sc_desc: &wgpu::SwapChainDescriptor, device: &mut wgpu::Device) -> Self {
// Create the vertex and index buffers
let vertex_size = mem::size_of::<Vertex>();
let (cube_vertex_data, cube_index_data) = create_cube();
let cube_vertex_buf = Rc::new(
device
.create_buffer_mapped(cube_vertex_data.len(), wgpu::BufferUsageFlags::VERTEX)
.fill_from_slice(&cube_vertex_data),
);
let cube_index_buf = Rc::new(
device
.create_buffer_mapped(cube_index_data.len(), wgpu::BufferUsageFlags::INDEX)
.fill_from_slice(&cube_index_data),
);
let (plane_vertex_data, plane_index_data) = create_plane(7);
let plane_vertex_buf = device
.create_buffer_mapped(plane_vertex_data.len(), wgpu::BufferUsageFlags::VERTEX)
.fill_from_slice(&plane_vertex_data);
let plane_index_buf = device
.create_buffer_mapped(plane_index_data.len(), wgpu::BufferUsageFlags::INDEX)
.fill_from_slice(&plane_index_data);
let entity_uniform_size = mem::size_of::<EntityUniforms>() as u32;
let plane_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
size: entity_uniform_size,
usage: wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST,
});
let local_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[wgpu::BindGroupLayoutBinding {
binding: 0,
visibility: wgpu::ShaderStageFlags::VERTEX | wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::UniformBuffer,
}],
});
let mut entities = vec![{
use cgmath::SquareMatrix;
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &local_bind_group_layout,
bindings: &[wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &plane_uniform_buf,
range: 0..entity_uniform_size,
},
}],
});
Entity {
mx_world: cgmath::Matrix4::identity(),
rotation_speed: 0.0,
color: wgpu::Color::WHITE,
vertex_buf: Rc::new(plane_vertex_buf),
index_buf: Rc::new(plane_index_buf),
index_count: plane_index_data.len(),
bind_group,
uniform_buf: plane_uniform_buf,
}
}];
struct CubeDesc {
offset: cgmath::Vector3<f32>,
angle: f32,
scale: f32,
rotation: f32,
}
let cube_descs = [
CubeDesc {
offset: cgmath::vec3(-2.0, -2.0, 2.0),
angle: 10.0,
scale: 0.7,
rotation: 1.0,
},
CubeDesc {
offset: cgmath::vec3(2.0, -2.0, 2.0),
angle: 50.0,
scale: 1.3,
rotation: 2.0,
},
CubeDesc {
offset: cgmath::vec3(-2.0, 2.0, 2.0),
angle: 140.0,
scale: 1.1,
rotation: 3.0,
},
CubeDesc {
offset: cgmath::vec3(2.0, 2.0, 2.0),
angle: 210.0,
scale: 0.9,
rotation: 4.0,
},
];
for cube in &cube_descs {
use cgmath::{Decomposed, Deg, InnerSpace, Quaternion, Rotation3};
let transform = Decomposed {
disp: cube.offset.clone(),
rot: Quaternion::from_axis_angle(cube.offset.normalize(), Deg(cube.angle)),
scale: cube.scale,
};
let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
size: entity_uniform_size,
usage: wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST,
});
entities.push(Entity {
mx_world: cgmath::Matrix4::from(transform),
rotation_speed: cube.rotation,
color: wgpu::Color::GREEN,
vertex_buf: Rc::clone(&cube_vertex_buf),
index_buf: Rc::clone(&cube_index_buf),
index_count: cube_index_data.len(),
bind_group: device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &local_bind_group_layout,
bindings: &[wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &uniform_buf,
range: 0..entity_uniform_size,
},
}],
}),
uniform_buf,
});
}
// Create other resources
let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
r_address_mode: wgpu::AddressMode::ClampToEdge,
s_address_mode: wgpu::AddressMode::ClampToEdge,
t_address_mode: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::FilterMode::Nearest,
lod_min_clamp: -100.0,
lod_max_clamp: 100.0,
max_anisotropy: 0,
compare_function: wgpu::CompareFunction::LessEqual,
border_color: wgpu::BorderColor::TransparentBlack,
});
let shadow_texture = device.create_texture(&wgpu::TextureDescriptor {
size: Self::SHADOW_SIZE,
array_size: Self::MAX_LIGHTS as u32,
dimension: wgpu::TextureDimension::D2,
format: Self::SHADOW_FORMAT,
usage: wgpu::TextureUsageFlags::OUTPUT_ATTACHMENT | wgpu::TextureUsageFlags::SAMPLED,
});
let shadow_view = shadow_texture.create_default_view();
let mut shadow_target_views = (0..2)
.map(|i| {
Some(shadow_texture.create_view(&wgpu::TextureViewDescriptor {
format: Self::SHADOW_FORMAT,
dimension: wgpu::TextureViewDimension::D2,
aspect: wgpu::TextureAspectFlags::DEPTH,
base_mip_level: 0,
level_count: 1,
base_array_layer: i as u32,
array_count: 1,
}))
})
.collect::<Vec<_>>();
let lights = vec![
Light {
pos: cgmath::Point3::new(7.0, -5.0, 10.0),
color: wgpu::Color {
r: 0.5,
g: 1.0,
b: 0.5,
a: 1.0,
},
fov: 60.0,
depth: 1.0..20.0,
target_view: shadow_target_views[0].take().unwrap(),
},
Light {
pos: cgmath::Point3::new(-5.0, 7.0, 10.0),
color: wgpu::Color {
r: 1.0,
g: 0.5,
b: 0.5,
a: 1.0,
},
fov: 45.0,
depth: 1.0..20.0,
target_view: shadow_target_views[1].take().unwrap(),
},
];
let light_uniform_size = (Self::MAX_LIGHTS * mem::size_of::<LightRaw>()) as u32;
let light_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
size: light_uniform_size,
usage: wgpu::BufferUsageFlags::UNIFORM
| wgpu::BufferUsageFlags::TRANSFER_SRC
| wgpu::BufferUsageFlags::TRANSFER_DST,
});
let vb_desc = wgpu::VertexBufferDescriptor {
stride: vertex_size as u32,
step_mode: wgpu::InputStepMode::Vertex,
attributes: &[
wgpu::VertexAttributeDescriptor {
attribute_index: 0,
format: wgpu::VertexFormat::Char4,
offset: 0,
},
wgpu::VertexAttributeDescriptor {
attribute_index: 1,
format: wgpu::VertexFormat::Char4,
offset: 4 * 1,
},
],
};
let shadow_pass = {
// Create pipeline layout
let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[wgpu::BindGroupLayoutBinding {
binding: 0, // global
visibility: wgpu::ShaderStageFlags::VERTEX,
ty: wgpu::BindingType::UniformBuffer,
}],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[&bind_group_layout, &local_bind_group_layout],
});
let uniform_size = mem::size_of::<ShadowUniforms>() as u32;
let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
size: uniform_size,
usage: wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST,
});
// Create bind group
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &bind_group_layout,
bindings: &[wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &uniform_buf,
range: 0..uniform_size,
},
}],
});
// Create the render pipeline
let vs_bytes = framework::load_glsl("shadow-bake.vert", framework::ShaderStage::Vertex);
let fs_bytes =
framework::load_glsl("shadow-bake.frag", framework::ShaderStage::Fragment);
let vs_module = device.create_shader_module(&vs_bytes);
let fs_module = device.create_shader_module(&fs_bytes);
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
layout: &pipeline_layout,
vertex_stage: wgpu::PipelineStageDescriptor {
module: &vs_module,
entry_point: "main",
},
fragment_stage: wgpu::PipelineStageDescriptor {
module: &fs_module,
entry_point: "main",
},
rasterization_state: wgpu::RasterizationStateDescriptor {
front_face: wgpu::FrontFace::Cw,
cull_mode: wgpu::CullMode::Back,
depth_bias: 2, // corresponds to bilinear filtering
depth_bias_slope_scale: 2.0,
depth_bias_clamp: 0.0,
},
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[],
depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor {
format: Self::SHADOW_FORMAT,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::LessEqual,
stencil_front: wgpu::StencilStateFaceDescriptor::IGNORE,
stencil_back: wgpu::StencilStateFaceDescriptor::IGNORE,
stencil_read_mask: 0,
stencil_write_mask: 0,
}),
index_format: wgpu::IndexFormat::Uint16,
vertex_buffers: &[vb_desc.clone()],
sample_count: 1,
});
Pass {
pipeline,
bind_group,
uniform_buf,
}
};
let forward_pass = {
// Create pipeline layout
let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[
wgpu::BindGroupLayoutBinding {
binding: 0, // global
visibility: wgpu::ShaderStageFlags::VERTEX
| wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::UniformBuffer,
},
wgpu::BindGroupLayoutBinding {
binding: 1, // lights
visibility: wgpu::ShaderStageFlags::VERTEX
| wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::UniformBuffer,
},
wgpu::BindGroupLayoutBinding {
binding: 2,
visibility: wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::SampledTexture,
},
wgpu::BindGroupLayoutBinding {
binding: 3,
visibility: wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::Sampler,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[&bind_group_layout, &local_bind_group_layout],
});
let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
let forward_uniforms = ForwardUniforms {
proj: *mx_total.as_ref(),
num_lights: [lights.len() as u32, 0, 0, 0],
};
let uniform_size = mem::size_of::<ForwardUniforms>() as u32;
let uniform_buf = device
.create_buffer_mapped(
1,
wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST,
)
.fill_from_slice(&[forward_uniforms]);
// Create bind group
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &bind_group_layout,
bindings: &[
wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &uniform_buf,
range: 0..uniform_size,
},
},
wgpu::Binding {
binding: 1,
resource: wgpu::BindingResource::Buffer {
buffer: &light_uniform_buf,
range: 0..light_uniform_size,
},
},
wgpu::Binding {
binding: 2,
resource: wgpu::BindingResource::TextureView(&shadow_view),
},
wgpu::Binding {
binding: 3,
resource: wgpu::BindingResource::Sampler(&shadow_sampler),
},
],
});
// Create the render pipeline
let vs_bytes =
framework::load_glsl("shadow-forward.vert", framework::ShaderStage::Vertex);
let fs_bytes =
framework::load_glsl("shadow-forward.frag", framework::ShaderStage::Fragment);
let vs_module = device.create_shader_module(&vs_bytes);
let fs_module = device.create_shader_module(&fs_bytes);
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
layout: &pipeline_layout,
vertex_stage: wgpu::PipelineStageDescriptor {
module: &vs_module,
entry_point: "main",
},
fragment_stage: wgpu::PipelineStageDescriptor {
module: &fs_module,
entry_point: "main",
},
rasterization_state: wgpu::RasterizationStateDescriptor {
front_face: wgpu::FrontFace::Cw,
cull_mode: wgpu::CullMode::Back,
depth_bias: 0,
depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0,
},
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[wgpu::ColorStateDescriptor {
format: sc_desc.format,
color: wgpu::BlendDescriptor::REPLACE,
alpha: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWriteFlags::ALL,
}],
depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor {
format: Self::DEPTH_FORMAT,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::Less,
stencil_front: wgpu::StencilStateFaceDescriptor::IGNORE,
stencil_back: wgpu::StencilStateFaceDescriptor::IGNORE,
stencil_read_mask: 0,
stencil_write_mask: 0,
}),
index_format: wgpu::IndexFormat::Uint16,
vertex_buffers: &[vb_desc],
sample_count: 1,
});
Pass {
pipeline,
bind_group,
uniform_buf,
}
};
let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
size: wgpu::Extent3d {
width: sc_desc.width,
height: sc_desc.height,
depth: 1,
},
array_size: 1,
dimension: wgpu::TextureDimension::D2,
format: Self::DEPTH_FORMAT,
usage: wgpu::TextureUsageFlags::OUTPUT_ATTACHMENT,
});
Example {
entities,
lights,
lights_are_dirty: true,
shadow_pass,
forward_pass,
forward_depth: depth_texture.create_default_view(),
light_uniform_buf,
}
}
fn update(&mut self, _event: wgpu::winit::WindowEvent) {
//empty
}
fn resize(&mut self, sc_desc: &wgpu::SwapChainDescriptor, device: &mut wgpu::Device) {
{
let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
let mx_ref: &[f32; 16] = mx_total.as_ref();
let temp_buf = device
.create_buffer_mapped(16, wgpu::BufferUsageFlags::TRANSFER_SRC)
.fill_from_slice(mx_ref);
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
encoder.copy_buffer_to_buffer(&temp_buf, 0, &self.forward_pass.uniform_buf, 0, 64);
device.get_queue().submit(&[encoder.finish()]);
}
let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
size: wgpu::Extent3d {
width: sc_desc.width,
height: sc_desc.height,
depth: 1,
},
array_size: 1,
dimension: wgpu::TextureDimension::D2,
format: Self::DEPTH_FORMAT,
usage: wgpu::TextureUsageFlags::OUTPUT_ATTACHMENT,
});
self.forward_depth = depth_texture.create_default_view();
}
fn render(&mut self, frame: &wgpu::SwapChainOutput, device: &mut wgpu::Device) {
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
{
let size = mem::size_of::<EntityUniforms>() as u32;
let temp_buf_data = device
.create_buffer_mapped(self.entities.len(), wgpu::BufferUsageFlags::TRANSFER_SRC);
for (i, entity) in self.entities.iter_mut().enumerate() {
if entity.rotation_speed != 0.0 {
let rotation =
cgmath::Matrix4::from_angle_x(cgmath::Deg(entity.rotation_speed));
entity.mx_world = entity.mx_world * rotation;
}
temp_buf_data.data[i] = EntityUniforms {
model: entity.mx_world.clone(),
color: [
entity.color.r,
entity.color.g,
entity.color.b,
entity.color.a,
],
};
}
let temp_buf = temp_buf_data.finish();
for (i, entity) in self.entities.iter().enumerate() {
encoder.copy_buffer_to_buffer(
&temp_buf,
i as u32 * size,
&entity.uniform_buf,
0,
size,
);
}
}
if self.lights_are_dirty {
self.lights_are_dirty = false;
let size = (self.lights.len() * mem::size_of::<LightRaw>()) as u32;
let temp_buf_data = device
.create_buffer_mapped(self.lights.len(), wgpu::BufferUsageFlags::TRANSFER_SRC);
for (i, light) in self.lights.iter().enumerate() {
temp_buf_data.data[i] = light.to_raw();
}
encoder.copy_buffer_to_buffer(
&temp_buf_data.finish(),
0,
&self.light_uniform_buf,
0,
size,
);
}
for (i, light) in self.lights.iter().enumerate() {
// The light uniform buffer already has the projection,
// let's just copy it over to the shadow uniform buffer.
encoder.copy_buffer_to_buffer(
&self.light_uniform_buf,
(i * mem::size_of::<LightRaw>()) as u32,
&self.shadow_pass.uniform_buf,
0,
64,
);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachmentDescriptor {
attachment: &light.target_view,
depth_load_op: wgpu::LoadOp::Clear,
depth_store_op: wgpu::StoreOp::Store,
stencil_load_op: wgpu::LoadOp::Clear,
stencil_store_op: wgpu::StoreOp::Store,
clear_depth: 1.0,
clear_stencil: 0,
}),
});
pass.set_pipeline(&self.shadow_pass.pipeline);
pass.set_bind_group(0, &self.shadow_pass.bind_group, &[]);
for entity in &self.entities {
pass.set_bind_group(1, &entity.bind_group, &[]);
pass.set_index_buffer(&entity.index_buf, 0);
pass.set_vertex_buffers(&[(&entity.vertex_buf, 0)]);
pass.draw_indexed(0..entity.index_count as u32, 0, 0..1);
}
}
// forward pass
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
attachment: &frame.view,
load_op: wgpu::LoadOp::Clear,
store_op: wgpu::StoreOp::Store,
clear_color: wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.3,
a: 1.0,
},
}],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachmentDescriptor {
attachment: &self.forward_depth,
depth_load_op: wgpu::LoadOp::Clear,
depth_store_op: wgpu::StoreOp::Store,
stencil_load_op: wgpu::LoadOp::Clear,
stencil_store_op: wgpu::StoreOp::Store,
clear_depth: 1.0,
clear_stencil: 0,
}),
});
pass.set_pipeline(&self.forward_pass.pipeline);
pass.set_bind_group(0, &self.forward_pass.bind_group, &[]);
for entity in &self.entities {
pass.set_bind_group(1, &entity.bind_group, &[]);
pass.set_index_buffer(&entity.index_buf, 0);
pass.set_vertex_buffers(&[(&entity.vertex_buf, 0)]);
pass.draw_indexed(0..entity.index_count as u32, 0, 0..1);
}
}
device.get_queue().submit(&[encoder.finish()]);
}
}
fn main() {
framework::run::<Example>("shadow");
}

View File

@ -1,4 +1,4 @@
header = ""
header = "#define WGPU_LOCAL"
include_version = true
braces = "SameLine"
line_length = 100
@ -7,11 +7,14 @@ language = "C"
[export]
prefix = "WGPU"
#TODO: figure out why cbindgen even tries to export a private type...
exclude = ["BufferMapResult"]
[parse]
parse_deps = false
[parse.expand]
crates = ["wgpu-native"]
features = ["local"]
[fn]
@ -28,4 +31,5 @@ bitflags = true
[defines]
"feature = window-winit" = "WGPU_WINDOW_WINIT"
"feature = local" = "WGPU_LOCAL"
"feature = remote" = "WGPU_REMOTE"

View File

@ -7,11 +7,15 @@ language = "C"
[export]
prefix = "WGPU"
exclude = ["BufferMapResult"]
[parse]
parse_deps = true
include = ["wgpu_native"]
[parse.expand]
crates = ["wgpu-native"]
[fn]
[struct]

View File

@ -1,27 +0,0 @@
[package]
name = "wgpu"
version = "0.2.2"
authors = [
"Dzmitry Malyshau <kvark@mozilla.com>",
"Joshua Groves <josh@joshgroves.com>",
]
edition = "2018"
description = "WebGPU native Rust wrapper"
homepage = "https://github.com/gfx-rs/wgpu"
repository = "https://github.com/gfx-rs/wgpu"
keywords = ["graphics"]
license = "MPL-2.0"
[lib]
[features]
default = []
metal-auto-capture = ["wgn/metal-auto-capture"]
metal = ["wgn/gfx-backend-metal"]
dx11 = ["wgn/gfx-backend-dx11"]
dx12 = ["wgn/gfx-backend-dx12"]
vulkan = ["wgn/gfx-backend-vulkan"]
[dependencies]
wgn = { package = "wgpu-native", version = "0.2.5", path = "../wgpu-native", features = ["local", "window-winit"] }
arrayvec = "0.4"

View File

@ -1,965 +0,0 @@
use arrayvec::ArrayVec;
use std::ffi::CString;
use std::ops::Range;
use std::ptr;
use std::slice;
pub use wgn::winit;
pub use wgn::{
AdapterDescriptor,
AddressMode,
BindGroupLayoutBinding,
BindingType,
BlendDescriptor,
BlendFactor,
BlendOperation,
BorderColor,
BufferDescriptor,
BufferMapAsyncStatus,
BufferUsageFlags,
Color,
ColorStateDescriptor,
ColorWriteFlags,
CommandEncoderDescriptor,
CompareFunction,
CullMode,
DepthStencilStateDescriptor,
DeviceDescriptor,
Extensions,
Extent3d,
FilterMode,
FrontFace,
IndexFormat,
InputStepMode,
LoadOp,
Origin3d,
PowerPreference,
PrimitiveTopology,
RasterizationStateDescriptor,
RenderPassColorAttachmentDescriptor,
RenderPassDepthStencilAttachmentDescriptor,
SamplerDescriptor,
ShaderAttributeIndex,
ShaderModuleDescriptor,
ShaderStageFlags,
StencilOperation,
StencilStateFaceDescriptor,
StoreOp,
SwapChainDescriptor,
TextureAspectFlags,
TextureDescriptor,
TextureDimension,
TextureFormat,
TextureUsageFlags,
TextureViewDescriptor,
TextureViewDimension,
VertexAttributeDescriptor,
VertexFormat,
};
//TODO: avoid heap allocating vectors during resource creation.
#[derive(Default)]
struct Temp {
//bind_group_descriptors: Vec<wgn::BindGroupDescriptor>,
//vertex_buffers: Vec<wgn::VertexBufferDescriptor>,
command_buffers: Vec<wgn::CommandBufferId>,
}
pub struct Instance {
id: wgn::InstanceId,
}
pub struct Adapter {
id: wgn::AdapterId,
}
pub struct Device {
id: wgn::DeviceId,
temp: Temp,
}
pub struct Buffer {
id: wgn::BufferId,
}
pub struct Texture {
id: wgn::TextureId,
owned: bool,
}
pub struct TextureView {
id: wgn::TextureViewId,
owned: bool,
}
pub struct Sampler {
id: wgn::SamplerId,
}
pub struct Surface {
id: wgn::SurfaceId,
}
pub struct SwapChain {
id: wgn::SwapChainId,
}
pub struct BindGroupLayout {
id: wgn::BindGroupLayoutId,
}
pub struct BindGroup {
id: wgn::BindGroupId,
}
impl Drop for BindGroup {
fn drop(&mut self) {
wgn::wgpu_bind_group_destroy(self.id);
}
}
pub struct ShaderModule {
id: wgn::ShaderModuleId,
}
pub struct PipelineLayout {
id: wgn::PipelineLayoutId,
}
pub struct RenderPipeline {
id: wgn::RenderPipelineId,
}
pub struct ComputePipeline {
id: wgn::ComputePipelineId,
}
pub struct CommandBuffer {
id: wgn::CommandBufferId,
}
pub struct CommandEncoder {
id: wgn::CommandEncoderId,
}
pub struct RenderPass<'a> {
id: wgn::RenderPassId,
_parent: &'a mut CommandEncoder,
}
pub struct ComputePass<'a> {
id: wgn::ComputePassId,
_parent: &'a mut CommandEncoder,
}
pub struct Queue<'a> {
id: wgn::QueueId,
temp: &'a mut Temp,
}
pub enum BindingResource<'a> {
Buffer {
buffer: &'a Buffer,
range: Range<u32>,
},
Sampler(&'a Sampler),
TextureView(&'a TextureView),
}
pub struct Binding<'a> {
pub binding: u32,
pub resource: BindingResource<'a>,
}
pub struct BindGroupLayoutDescriptor<'a> {
pub bindings: &'a [BindGroupLayoutBinding],
}
pub struct BindGroupDescriptor<'a> {
pub layout: &'a BindGroupLayout,
pub bindings: &'a [Binding<'a>],
}
pub struct PipelineLayoutDescriptor<'a> {
pub bind_group_layouts: &'a [&'a BindGroupLayout],
}
pub struct PipelineStageDescriptor<'a> {
pub module: &'a ShaderModule,
pub entry_point: &'a str,
}
#[derive(Clone, Debug)]
pub struct VertexBufferDescriptor<'a> {
pub stride: u32,
pub step_mode: InputStepMode,
pub attributes: &'a [VertexAttributeDescriptor],
}
pub struct RenderPipelineDescriptor<'a> {
pub layout: &'a PipelineLayout,
pub vertex_stage: PipelineStageDescriptor<'a>,
pub fragment_stage: PipelineStageDescriptor<'a>,
pub rasterization_state: RasterizationStateDescriptor,
pub primitive_topology: PrimitiveTopology,
pub color_states: &'a [ColorStateDescriptor],
pub depth_stencil_state: Option<DepthStencilStateDescriptor>,
pub index_format: IndexFormat,
pub vertex_buffers: &'a [VertexBufferDescriptor<'a>],
pub sample_count: u32,
}
pub struct ComputePipelineDescriptor<'a> {
pub layout: &'a PipelineLayout,
pub compute_stage: PipelineStageDescriptor<'a>,
}
pub struct RenderPassDescriptor<'a> {
pub color_attachments: &'a [RenderPassColorAttachmentDescriptor<&'a TextureView>],
pub depth_stencil_attachment:
Option<RenderPassDepthStencilAttachmentDescriptor<&'a TextureView>>,
}
pub struct SwapChainOutput<'a> {
pub texture: Texture,
pub view: TextureView,
swap_chain_id: &'a wgn::SwapChainId,
}
pub struct BufferCopyView<'a> {
pub buffer: &'a Buffer,
pub offset: u32,
pub row_pitch: u32,
pub image_height: u32,
}
impl<'a> BufferCopyView<'a> {
fn into_native(self) -> wgn::BufferCopyView {
wgn::BufferCopyView {
buffer: self.buffer.id,
offset: self.offset,
row_pitch: self.row_pitch,
image_height: self.image_height,
}
}
}
pub struct TextureCopyView<'a> {
pub texture: &'a Texture,
pub level: u32,
pub slice: u32,
pub origin: Origin3d,
}
impl<'a> TextureCopyView<'a> {
fn into_native(self) -> wgn::TextureCopyView {
wgn::TextureCopyView {
texture: self.texture.id,
level: self.level,
slice: self.slice,
origin: self.origin,
}
}
}
pub struct CreateBufferMapped<'a, T> {
id: wgn::BufferId,
pub data: &'a mut [T],
}
impl<'a, T> CreateBufferMapped<'a, T>
where
T: Copy,
{
pub fn fill_from_slice(self, slice: &[T]) -> Buffer {
self.data.copy_from_slice(slice);
self.finish()
}
pub fn finish(self) -> Buffer {
wgn::wgpu_buffer_unmap(self.id);
Buffer { id: self.id }
}
}
impl Instance {
pub fn new() -> Self {
Instance {
id: wgn::wgpu_create_instance(),
}
}
pub fn get_adapter(&self, desc: &AdapterDescriptor) -> Adapter {
Adapter {
id: wgn::wgpu_instance_get_adapter(self.id, desc),
}
}
pub fn create_surface(&self, window: &winit::Window) -> Surface {
Surface {
id: wgn::wgpu_instance_create_surface_from_winit(self.id, window),
}
}
#[cfg(feature = "metal")]
pub fn create_surface_with_metal_layer(&self, window: *mut std::ffi::c_void) -> Surface {
Surface {
id: wgn::wgpu_instance_create_surface_from_macos_layer(self.id, window),
}
}
}
impl Adapter {
pub fn create_device(&self, desc: &DeviceDescriptor) -> Device {
Device {
id: wgn::wgpu_adapter_create_device(self.id, desc),
temp: Temp::default(),
}
}
}
impl Device {
/// Check for resource cleanups and mapping callbacks.
pub fn poll(&self, force_wait: bool) {
wgn::wgpu_device_poll(self.id, force_wait);
}
pub fn create_shader_module(&self, spv: &[u8]) -> ShaderModule {
let desc = wgn::ShaderModuleDescriptor {
code: wgn::ByteArray {
bytes: spv.as_ptr(),
length: spv.len(),
},
};
ShaderModule {
id: wgn::wgpu_device_create_shader_module(self.id, &desc),
}
}
pub fn get_queue(&mut self) -> Queue {
Queue {
id: wgn::wgpu_device_get_queue(self.id),
temp: &mut self.temp,
}
}
pub fn create_command_encoder(&self, desc: &CommandEncoderDescriptor) -> CommandEncoder {
CommandEncoder {
id: wgn::wgpu_device_create_command_encoder(self.id, desc),
}
}
pub fn create_bind_group(&self, desc: &BindGroupDescriptor) -> BindGroup {
let bindings = desc
.bindings
.into_iter()
.map(|binding| wgn::Binding {
binding: binding.binding,
resource: match binding.resource {
BindingResource::Buffer {
ref buffer,
ref range,
} => wgn::BindingResource::Buffer(wgn::BufferBinding {
buffer: buffer.id,
offset: range.start,
size: range.end - range.start,
}),
BindingResource::Sampler(ref sampler) => {
wgn::BindingResource::Sampler(sampler.id)
}
BindingResource::TextureView(ref texture_view) => {
wgn::BindingResource::TextureView(texture_view.id)
}
},
})
.collect::<Vec<_>>();
BindGroup {
id: wgn::wgpu_device_create_bind_group(
self.id,
&wgn::BindGroupDescriptor {
layout: desc.layout.id,
bindings: bindings.as_ptr(),
bindings_length: bindings.len(),
},
),
}
}
pub fn create_bind_group_layout(&self, desc: &BindGroupLayoutDescriptor) -> BindGroupLayout {
BindGroupLayout {
id: wgn::wgpu_device_create_bind_group_layout(
self.id,
&wgn::BindGroupLayoutDescriptor {
bindings: desc.bindings.as_ptr(),
bindings_length: desc.bindings.len(),
},
),
}
}
pub fn create_pipeline_layout(&self, desc: &PipelineLayoutDescriptor) -> PipelineLayout {
//TODO: avoid allocation here
let temp_layouts = desc
.bind_group_layouts
.iter()
.map(|bgl| bgl.id)
.collect::<Vec<_>>();
PipelineLayout {
id: wgn::wgpu_device_create_pipeline_layout(
self.id,
&wgn::PipelineLayoutDescriptor {
bind_group_layouts: temp_layouts.as_ptr(),
bind_group_layouts_length: temp_layouts.len(),
},
),
}
}
pub fn create_render_pipeline(&self, desc: &RenderPipelineDescriptor) -> RenderPipeline {
let vertex_entry_point = CString::new(desc.vertex_stage.entry_point).unwrap();
let fragment_entry_point = CString::new(desc.fragment_stage.entry_point).unwrap();
let temp_color_states = desc.color_states.to_vec();
let temp_vertex_buffers = desc
.vertex_buffers
.iter()
.map(|vbuf| wgn::VertexBufferDescriptor {
stride: vbuf.stride,
step_mode: vbuf.step_mode,
attributes: vbuf.attributes.as_ptr(),
attributes_count: vbuf.attributes.len(),
})
.collect::<Vec<_>>();
RenderPipeline {
id: wgn::wgpu_device_create_render_pipeline(
self.id,
&wgn::RenderPipelineDescriptor {
layout: desc.layout.id,
vertex_stage: wgn::PipelineStageDescriptor {
module: desc.vertex_stage.module.id,
entry_point: vertex_entry_point.as_ptr(),
},
fragment_stage: wgn::PipelineStageDescriptor {
module: desc.fragment_stage.module.id,
entry_point: fragment_entry_point.as_ptr(),
},
rasterization_state: desc.rasterization_state.clone(),
primitive_topology: desc.primitive_topology,
color_states: temp_color_states.as_ptr(),
color_states_length: temp_color_states.len(),
depth_stencil_state: desc
.depth_stencil_state
.as_ref()
.map_or(ptr::null(), |p| p as *const _),
vertex_buffer_state: wgn::VertexBufferStateDescriptor {
index_format: desc.index_format,
vertex_buffers: temp_vertex_buffers.as_ptr(),
vertex_buffers_count: temp_vertex_buffers.len(),
},
sample_count: desc.sample_count,
},
),
}
}
pub fn create_compute_pipeline(&self, desc: &ComputePipelineDescriptor) -> ComputePipeline {
let entry_point = CString::new(desc.compute_stage.entry_point).unwrap();
ComputePipeline {
id: wgn::wgpu_device_create_compute_pipeline(
self.id,
&wgn::ComputePipelineDescriptor {
layout: desc.layout.id,
compute_stage: wgn::PipelineStageDescriptor {
module: desc.compute_stage.module.id,
entry_point: entry_point.as_ptr(),
},
},
),
}
}
pub fn create_buffer(&self, desc: &BufferDescriptor) -> Buffer {
Buffer {
id: wgn::wgpu_device_create_buffer(self.id, desc),
}
}
pub fn create_buffer_mapped<'a, T>(
&self,
count: usize,
usage: BufferUsageFlags,
) -> CreateBufferMapped<'a, T>
where
T: 'static + Copy,
{
let type_size = std::mem::size_of::<T>() as u32;
assert_ne!(type_size, 0);
let desc = BufferDescriptor {
size: (type_size * count as u32).max(1),
usage,
};
let mut ptr: *mut u8 = std::ptr::null_mut();
let id = wgn::wgpu_device_create_buffer_mapped(self.id, &desc, &mut ptr as *mut *mut u8);
let data = unsafe { std::slice::from_raw_parts_mut(ptr as *mut T, count) };
CreateBufferMapped { id, data }
}
pub fn create_texture(&self, desc: &TextureDescriptor) -> Texture {
Texture {
id: wgn::wgpu_device_create_texture(self.id, desc),
owned: true,
}
}
pub fn create_sampler(&self, desc: &SamplerDescriptor) -> Sampler {
Sampler {
id: wgn::wgpu_device_create_sampler(self.id, desc),
}
}
pub fn create_swap_chain(&self, surface: &Surface, desc: &SwapChainDescriptor) -> SwapChain {
SwapChain {
id: wgn::wgpu_device_create_swap_chain(self.id, surface.id, desc),
}
}
}
impl Drop for Device {
fn drop(&mut self) {
wgn::wgpu_device_poll(self.id, true);
//TODO: make this work in general
#[cfg(feature = "metal-auto-capture")]
wgn::wgpu_device_destroy(self.id);
}
}
pub struct BufferAsyncMapping<T> {
pub data: T,
buffer_id: wgn::BufferId,
}
//TODO: proper error type
pub type BufferMapAsyncResult<T> = Result<BufferAsyncMapping<T>, ()>;
impl<T> Drop for BufferAsyncMapping<T> {
fn drop(&mut self) {
wgn::wgpu_buffer_unmap(self.buffer_id);
}
}
struct BufferMapReadAsyncUserData<T, F>
where
F: FnOnce(BufferMapAsyncResult<&[T]>),
{
size: u32,
callback: F,
buffer_id: wgn::BufferId,
phantom: std::marker::PhantomData<T>,
}
struct BufferMapWriteAsyncUserData<T, F>
where
F: FnOnce(BufferMapAsyncResult<&mut [T]>),
{
size: u32,
callback: F,
buffer_id: wgn::BufferId,
phantom: std::marker::PhantomData<T>,
}
impl Buffer {
pub fn map_read_async<T, F>(&self, start: u32, size: u32, callback: F)
where
T: 'static + Copy,
F: FnOnce(BufferMapAsyncResult<&[T]>) + 'static,
{
let type_size = std::mem::size_of::<T>() as u32;
assert_ne!(type_size, 0);
assert_eq!(size % type_size, 0);
extern "C" fn buffer_map_read_callback_wrapper<T, F>(
status: wgn::BufferMapAsyncStatus,
data: *const u8,
user_data: *mut u8,
) where
F: FnOnce(BufferMapAsyncResult<&[T]>),
{
let user_data =
unsafe { Box::from_raw(user_data as *mut BufferMapReadAsyncUserData<T, F>) };
let data = unsafe {
slice::from_raw_parts(
data as *const T,
user_data.size as usize / std::mem::size_of::<T>(),
)
};
if let wgn::BufferMapAsyncStatus::Success = status {
(user_data.callback)(Ok(BufferAsyncMapping {
data,
buffer_id: user_data.buffer_id,
}));
} else {
(user_data.callback)(Err(()))
}
}
let user_data = Box::new(BufferMapReadAsyncUserData {
size,
callback,
buffer_id: self.id,
phantom: std::marker::PhantomData,
});
wgn::wgpu_buffer_map_read_async(
self.id,
start,
size,
buffer_map_read_callback_wrapper::<T, F>,
Box::into_raw(user_data) as *mut u8,
);
}
pub fn map_write_async<T, F>(&self, start: u32, size: u32, callback: F)
where
T: 'static + Copy,
F: FnOnce(BufferMapAsyncResult<&mut [T]>) + 'static,
{
let type_size = std::mem::size_of::<T>() as u32;
assert_ne!(type_size, 0);
assert_eq!(size % type_size, 0);
extern "C" fn buffer_map_write_callback_wrapper<T, F>(
status: wgn::BufferMapAsyncStatus,
data: *mut u8,
user_data: *mut u8,
) where
F: FnOnce(BufferMapAsyncResult<&mut [T]>),
{
let user_data =
unsafe { Box::from_raw(user_data as *mut BufferMapWriteAsyncUserData<T, F>) };
let data = unsafe {
slice::from_raw_parts_mut(
data as *mut T,
user_data.size as usize / std::mem::size_of::<T>(),
)
};
if let wgn::BufferMapAsyncStatus::Success = status {
(user_data.callback)(Ok(BufferAsyncMapping {
data,
buffer_id: user_data.buffer_id,
}));
} else {
(user_data.callback)(Err(()))
}
}
let user_data = Box::new(BufferMapWriteAsyncUserData {
size,
callback,
buffer_id: self.id,
phantom: std::marker::PhantomData,
});
wgn::wgpu_buffer_map_write_async(
self.id,
start,
size,
buffer_map_write_callback_wrapper::<T, F>,
Box::into_raw(user_data) as *mut u8,
);
}
pub fn unmap(&self) {
wgn::wgpu_buffer_unmap(self.id);
}
}
impl Drop for Buffer {
fn drop(&mut self) {
wgn::wgpu_buffer_destroy(self.id);
}
}
impl Texture {
pub fn create_view(&self, desc: &TextureViewDescriptor) -> TextureView {
TextureView {
id: wgn::wgpu_texture_create_view(self.id, desc),
owned: true,
}
}
pub fn create_default_view(&self) -> TextureView {
TextureView {
id: wgn::wgpu_texture_create_default_view(self.id),
owned: true,
}
}
}
impl Drop for Texture {
fn drop(&mut self) {
if self.owned {
wgn::wgpu_texture_destroy(self.id);
}
}
}
impl Drop for TextureView {
fn drop(&mut self) {
if self.owned {
wgn::wgpu_texture_view_destroy(self.id);
}
}
}
impl CommandEncoder {
pub fn finish(self) -> CommandBuffer {
CommandBuffer {
id: wgn::wgpu_command_encoder_finish(self.id),
}
}
pub fn begin_render_pass(&mut self, desc: &RenderPassDescriptor) -> RenderPass {
let colors = desc
.color_attachments
.iter()
.map(|ca| RenderPassColorAttachmentDescriptor {
attachment: ca.attachment.id,
load_op: ca.load_op,
store_op: ca.store_op,
clear_color: ca.clear_color,
})
.collect::<ArrayVec<[_; 4]>>();
let depth_stencil = desc.depth_stencil_attachment.as_ref().map(|dsa| {
RenderPassDepthStencilAttachmentDescriptor {
attachment: dsa.attachment.id,
depth_load_op: dsa.depth_load_op,
depth_store_op: dsa.depth_store_op,
clear_depth: dsa.clear_depth,
stencil_load_op: dsa.stencil_load_op,
stencil_store_op: dsa.stencil_store_op,
clear_stencil: dsa.clear_stencil,
}
});
RenderPass {
id: wgn::wgpu_command_encoder_begin_render_pass(
self.id,
wgn::RenderPassDescriptor {
color_attachments: colors.as_ptr(),
color_attachments_length: colors.len(),
depth_stencil_attachment: depth_stencil
.as_ref()
.map(|at| at as *const _)
.unwrap_or(ptr::null()),
},
),
_parent: self,
}
}
pub fn begin_compute_pass(&mut self) -> ComputePass {
ComputePass {
id: wgn::wgpu_command_encoder_begin_compute_pass(self.id),
_parent: self,
}
}
pub fn copy_buffer_to_buffer(
&mut self,
source: &Buffer,
source_offset: u32,
destination: &Buffer,
destination_offset: u32,
copy_size: u32,
) {
wgn::wgpu_command_buffer_copy_buffer_to_buffer(
self.id,
source.id,
source_offset,
destination.id,
destination_offset,
copy_size,
);
}
pub fn copy_buffer_to_texture(
&mut self,
source: BufferCopyView,
destination: TextureCopyView,
copy_size: Extent3d,
) {
wgn::wgpu_command_buffer_copy_buffer_to_texture(
self.id,
&source.into_native(),
&destination.into_native(),
copy_size,
);
}
pub fn copy_texture_to_buffer(
&mut self,
source: TextureCopyView,
destination: BufferCopyView,
copy_size: Extent3d,
) {
wgn::wgpu_command_buffer_copy_texture_to_buffer(
self.id,
&source.into_native(),
&destination.into_native(),
copy_size,
);
}
pub fn copy_texture_to_texture(
&mut self,
source: TextureCopyView,
destination: TextureCopyView,
copy_size: Extent3d,
) {
wgn::wgpu_command_buffer_copy_texture_to_texture(
self.id,
&source.into_native(),
&destination.into_native(),
copy_size,
);
}
}
impl<'a> RenderPass<'a> {
pub fn set_bind_group(&mut self, index: u32, bind_group: &BindGroup, offsets: &[u32]) {
wgn::wgpu_render_pass_set_bind_group(
self.id,
index,
bind_group.id,
offsets.as_ptr(),
offsets.len(),
);
}
pub fn set_pipeline(&mut self, pipeline: &RenderPipeline) {
wgn::wgpu_render_pass_set_pipeline(self.id, pipeline.id);
}
pub fn set_blend_color(&mut self, color: Color) {
wgn::wgpu_render_pass_set_blend_color(self.id, &color);
}
pub fn set_index_buffer(&mut self, buffer: &Buffer, offset: u32) {
wgn::wgpu_render_pass_set_index_buffer(self.id, buffer.id, offset);
}
pub fn set_vertex_buffers(&mut self, buffer_pairs: &[(&Buffer, u32)]) {
let mut buffers = Vec::new();
let mut offsets = Vec::new();
for &(buffer, offset) in buffer_pairs {
buffers.push(buffer.id);
offsets.push(offset);
}
wgn::wgpu_render_pass_set_vertex_buffers(
self.id,
buffers.as_ptr(),
offsets.as_ptr(),
buffer_pairs.len(),
);
}
pub fn set_scissor_rect(&mut self, x: u32, y: u32, w: u32, h: u32) {
wgn::wgpu_render_pass_set_scissor_rect(self.id, x, y, w, h)
}
pub fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
wgn::wgpu_render_pass_draw(
self.id,
vertices.end - vertices.start,
instances.end - instances.start,
vertices.start,
instances.start,
);
}
pub fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
wgn::wgpu_render_pass_draw_indexed(
self.id,
indices.end - indices.start,
instances.end - instances.start,
indices.start,
base_vertex,
instances.start,
);
}
}
impl<'a> Drop for RenderPass<'a> {
fn drop(&mut self) {
wgn::wgpu_render_pass_end_pass(self.id);
}
}
impl<'a> ComputePass<'a> {
pub fn set_bind_group(&mut self, index: u32, bind_group: &BindGroup, offsets: &[u32]) {
wgn::wgpu_compute_pass_set_bind_group(
self.id,
index,
bind_group.id,
offsets.as_ptr(),
offsets.len(),
);
}
pub fn set_pipeline(&mut self, pipeline: &ComputePipeline) {
wgn::wgpu_compute_pass_set_pipeline(self.id, pipeline.id);
}
pub fn dispatch(&mut self, x: u32, y: u32, z: u32) {
wgn::wgpu_compute_pass_dispatch(self.id, x, y, z);
}
}
impl<'a> Drop for ComputePass<'a> {
fn drop(&mut self) {
wgn::wgpu_compute_pass_end_pass(self.id);
}
}
impl<'a> Queue<'a> {
pub fn submit(&mut self, command_buffers: &[CommandBuffer]) {
self.temp.command_buffers.clear();
self.temp
.command_buffers
.extend(command_buffers.iter().map(|cb| cb.id));
wgn::wgpu_queue_submit(
self.id,
self.temp.command_buffers.as_ptr(),
command_buffers.len(),
);
}
}
impl<'a> Drop for SwapChainOutput<'a> {
fn drop(&mut self) {
wgn::wgpu_swap_chain_present(*self.swap_chain_id);
}
}
impl SwapChain {
pub fn get_next_texture(&mut self) -> SwapChainOutput {
let output = wgn::wgpu_swap_chain_get_next_texture(self.id);
SwapChainOutput {
texture: Texture {
id: output.texture_id,
owned: false,
},
view: TextureView {
id: output.view_id,
owned: false,
},
swap_chain_id: &self.id,
}
}
}

View File

@ -1,100 +0,0 @@
#[test]
#[cfg(any(feature = "vulkan", feature = "metal", feature = "dx12"))]
fn multithreaded_compute() {
use std::thread;
use std::time::Duration;
use std::sync::mpsc;
let thread_count = 8;
let (tx, rx) = mpsc::channel();
for _ in 0..thread_count {
let tx = tx.clone();
thread::spawn(move || {
let numbers = vec!(100, 100, 100);
let size = (numbers.len() * std::mem::size_of::<u32>()) as u32;
let instance = wgpu::Instance::new();
let adapter = instance.get_adapter(&wgpu::AdapterDescriptor {
power_preference: wgpu::PowerPreference::Default,
});
let mut device = adapter.create_device(&wgpu::DeviceDescriptor {
extensions: wgpu::Extensions {
anisotropic_filtering: false,
},
});
let cs_bytes = include_bytes!("./../../examples/data/collatz.comp.spv");
let cs_module = device.create_shader_module(cs_bytes);
let staging_buffer = device
.create_buffer_mapped(
numbers.len(),
wgpu::BufferUsageFlags::MAP_READ
| wgpu::BufferUsageFlags::TRANSFER_DST
| wgpu::BufferUsageFlags::TRANSFER_SRC,
)
.fill_from_slice(&numbers);
let storage_buffer = device.create_buffer(&wgpu::BufferDescriptor {
size,
usage: wgpu::BufferUsageFlags::STORAGE
| wgpu::BufferUsageFlags::TRANSFER_DST
| wgpu::BufferUsageFlags::TRANSFER_SRC,
});
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[wgpu::BindGroupLayoutBinding {
binding: 0,
visibility: wgpu::ShaderStageFlags::COMPUTE,
ty: wgpu::BindingType::StorageBuffer,
}],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &bind_group_layout,
bindings: &[wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &storage_buffer,
range: 0..size,
},
}],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[&bind_group_layout],
});
let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
layout: &pipeline_layout,
compute_stage: wgpu::PipelineStageDescriptor {
module: &cs_module,
entry_point: "main",
},
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
encoder.copy_buffer_to_buffer(&staging_buffer, 0, &storage_buffer, 0, size);
{
let mut cpass = encoder.begin_compute_pass();
cpass.set_pipeline(&compute_pipeline);
cpass.set_bind_group(0, &bind_group, &[]);
cpass.dispatch(numbers.len() as u32, 1, 1);
}
encoder.copy_buffer_to_buffer(&storage_buffer, 0, &staging_buffer, 0, size);
device.get_queue().submit(&[encoder.finish()]);
staging_buffer.map_read_async(0, size, |result: wgpu::BufferMapAsyncResult<&[u32]>| {
assert_eq!(result.unwrap().data, [25, 25, 25]);
});
tx.send(true).unwrap();
});
}
for _ in 0..thread_count {
rx.recv_timeout(Duration::from_secs(10)).expect("A thread never completed.");
}
}