Update to winit 0.30 (#9089)

This commit is contained in:
Connor Fitzgerald authored and GitHub committed 2026-03-18 20:34:12 +01:00
1 parent 9a3bba6962
commit 2810e95489
12 files changed
+1615 -1428

No files matched your search

+24 -2
View File
@@ -1,8 +1,6 @@
[bans]
multiple-versions = "deny"
skip-tree = [
{ name = "windows-sys", version = "0.45" },
{ name = "winit", version = "0.29" },
{ name = "rustc-hash", version = "1.1.0" },
# introduced by Deno, to be investigated
@@ -10,6 +8,12 @@ skip-tree = [
# Winit 0.30 uses an older objc2
{ name = "objc2-foundation", version = "0.2" },
# glutin and tracy-client-sys use windows-sys 0.52, pulling older windows-targets
{ name = "windows-targets", version = "0.52" },
# winit uses an old version via android-activity → jni
{ name = "windows-targets", version = "0.42" },
]
skip = [
# flume -> fastrand uses an old version only on wasm32
@@ -21,6 +25,24 @@ skip = [
{ name = "bincode", version = "1.3.3" },
{ name = "which", version = "6.0.3" },
# Winit uses an old version via android-activity → jni
{ name = "windows-sys", version = "0.45" },
# Winit uses an old version via calloop → rustix 0.38
{ name = "linux-raw-sys", version = "0.4" },
{ name = "rustix", version = "0.38" },
{ name = "windows-sys", version = "0.59" },
# Winit uses an old version via android-activity
{ name = "thiserror", version = "1" },
{ name = "thiserror-impl", version = "1" },
# glutin uses an old version
{ name = "windows-sys", version = "0.52" },
# getrandom 0.3 uses an old version
{ name = "r-efi", version = "5" },
# parking-lot uses an old version
{ name = "redox_syscall", version = "0.5.18" },
Generated
+78 -415
View File
@@ -61,27 +61,6 @@ version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "android-activity"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee91c0c2905bae44f84bfa4e044536541df26b7703fd0888deeb9060fcc44289"
dependencies = [
"android-properties",
"bitflags 2.11.0",
"cc",
"cesu8",
"jni",
"jni-sys",
"libc",
"log",
"ndk 0.8.0",
"ndk-context",
"ndk-sys 0.5.0+25.2.9519653",
"num_enum",
"thiserror 1.0.69",
]
[[package]]
name = "android-activity"
version = "0.6.0"
@@ -96,9 +75,9 @@ dependencies = [
"jni-sys",
"libc",
"log",
"ndk 0.9.0",
"ndk",
"ndk-context",
"ndk-sys 0.6.0+11769913",
"ndk-sys",
"num_enum",
"thiserror 1.0.69",
]
@@ -414,25 +393,6 @@ dependencies = [
"wyz",
]
[[package]]
name = "block-sys"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae85a0696e7ea3b835a453750bf002770776609115e6d25c6d2ff28a8200f7e7"
dependencies = [
"objc-sys",
]
[[package]]
name = "block2"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b55663a85f33501257357e6421bb33e769d5c9ffb5ba0921c975a123e35e68"
dependencies = [
"block-sys",
"objc2 0.4.1",
]
[[package]]
name = "block2"
version = "0.5.1"
@@ -499,20 +459,6 @@ version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "calloop"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fba7adb4dd5aa98e5553510223000e7148f621165ec5f9acd7113f6ca4995298"
dependencies = [
"bitflags 2.11.0",
"log",
"polling",
"rustix 0.38.44",
"slab",
"thiserror 1.0.69",
]
[[package]]
name = "calloop"
version = "0.13.0"
@@ -527,25 +473,13 @@ dependencies = [
"thiserror 1.0.69",
]
[[package]]
name = "calloop-wayland-source"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f0ea9b9476c7fad82841a8dbb380e2eae480c21910feba80725b46931ed8f02"
dependencies = [
"calloop 0.12.4",
"rustix 0.38.44",
"wayland-backend",
"wayland-client",
]
[[package]]
name = "calloop-wayland-source"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20"
dependencies = [
"calloop 0.13.0",
"calloop",
"rustix 0.38.44",
"wayland-backend",
"wayland-client",
@@ -643,12 +577,6 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "cfg_aliases"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"
[[package]]
name = "cfg_aliases"
version = "0.2.1"
@@ -1145,7 +1073,7 @@ dependencies = [
"deno_error",
"deno_unsync",
"indexmap",
"raw-window-handle 0.6.2",
"raw-window-handle",
"serde",
"serde_json",
"thiserror 2.0.18",
@@ -1697,56 +1625,48 @@ dependencies = [
[[package]]
name = "glutin"
version = "0.31.3"
version = "0.32.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18fcd4ae4e86d991ad1300b8f57166e5be0c95ef1f63f3f5b827f8a164548746"
checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325"
dependencies = [
"bitflags 2.11.0",
"cfg_aliases 0.1.1",
"cfg_aliases",
"cgl",
"core-foundation",
"dispatch",
"dispatch2",
"glutin_egl_sys",
"glutin_wgl_sys 0.5.0",
"icrate",
"glutin_wgl_sys",
"libloading",
"objc2 0.4.1",
"objc2 0.6.4",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"once_cell",
"raw-window-handle 0.5.2",
"raw-window-handle",
"wayland-sys",
"windows-sys 0.48.0",
"windows-sys 0.52.0",
"x11-dl",
]
[[package]]
name = "glutin-winit"
version = "0.4.2"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebcdfba24f73b8412c5181e56f092b5eff16671c514ce896b258a0a64bd7735"
checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f"
dependencies = [
"cfg_aliases 0.1.1",
"cfg_aliases",
"glutin",
"raw-window-handle 0.5.2",
"winit 0.29.15",
"raw-window-handle",
"winit",
]
[[package]]
name = "glutin_egl_sys"
version = "0.6.0"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77cc5623f5309ef433c3dd4ca1223195347fe62c413da8e2fdd0eb76db2d9bcd"
dependencies = [
"gl_generator",
"windows-sys 0.48.0",
]
[[package]]
name = "glutin_wgl_sys"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8098adac955faa2d31079b65dc48841251f69efd3ac25477903fc424362ead"
checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2"
dependencies = [
"gl_generator",
"windows-sys 0.52.0",
]
[[package]]
@@ -1873,17 +1793,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "icrate"
version = "0.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99d3aaff8a54577104bafdf686ff18565c3b6903ca5782a2026ef06e2c7aa319"
dependencies = [
"block2 0.3.0",
"dispatch",
"objc2 0.4.1",
]
[[package]]
name = "icu_collections"
version = "2.1.1"
@@ -2034,7 +1943,7 @@ dependencies = [
"portable-atomic",
"unicode-width",
"unit-prefix",
"web-time 1.1.0",
"web-time",
]
[[package]]
@@ -2399,7 +2308,7 @@ dependencies = [
"bit-set 0.9.1",
"bitflags 2.11.0",
"cfg-if",
"cfg_aliases 0.2.1",
"cfg_aliases",
"codespan-reporting",
"diff",
"env_logger",
@@ -2445,7 +2354,7 @@ name = "naga-fuzz"
version = "28.0.0"
dependencies = [
"arbitrary",
"cfg_aliases 0.2.1",
"cfg_aliases",
"libfuzzer-sys",
"naga",
]
@@ -2504,22 +2413,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a846cbc04412cf509efcd8f3694b114fc700a035fb5a37f21517f9fb019f1ebc"
[[package]]
name = "ndk"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2076a31b7010b17a38c01907c45b945e8f11495ee4dd588309718901b1f7a5b7"
dependencies = [
"bitflags 2.11.0",
"jni-sys",
"log",
"ndk-sys 0.5.0+25.2.9519653",
"num_enum",
"raw-window-handle 0.5.2",
"raw-window-handle 0.6.2",
"thiserror 1.0.69",
]
[[package]]
name = "ndk"
version = "0.9.0"
@@ -2529,9 +2422,9 @@ dependencies = [
"bitflags 2.11.0",
"jni-sys",
"log",
"ndk-sys 0.6.0+11769913",
"ndk-sys",
"num_enum",
"raw-window-handle 0.6.2",
"raw-window-handle",
"thiserror 1.0.69",
]
@@ -2541,15 +2434,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
[[package]]
name = "ndk-sys"
version = "0.5.0+25.2.9519653"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691"
dependencies = [
"jni-sys",
]
[[package]]
name = "ndk-sys"
version = "0.6.0+11769913"
@@ -2692,16 +2576,6 @@ version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
[[package]]
name = "objc2"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "559c5a40fdd30eb5e344fbceacf7595a81e242529fb4e21cf5f43fb4f11ff98d"
dependencies = [
"objc-sys",
"objc2-encode 3.0.0",
]
[[package]]
name = "objc2"
version = "0.5.2"
@@ -2709,7 +2583,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
dependencies = [
"objc-sys",
"objc2-encode 4.1.0",
"objc2-encode",
]
[[package]]
@@ -2718,7 +2592,7 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
dependencies = [
"objc2-encode 4.1.0",
"objc2-encode",
]
[[package]]
@@ -2737,6 +2611,18 @@ dependencies = [
"objc2-quartz-core 0.2.2",
]
[[package]]
name = "objc2-app-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
dependencies = [
"bitflags 2.11.0",
"objc2 0.6.4",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
]
[[package]]
name = "objc2-cloud-kit"
version = "0.2.2"
@@ -2808,12 +2694,6 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "objc2-encode"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d079845b37af429bfe5dfa76e6d087d788031045b25cfc6fd898486fd9847666"
[[package]]
name = "objc2-encode"
version = "4.1.0"
@@ -2852,7 +2732,7 @@ checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398"
dependencies = [
"block2 0.5.1",
"objc2 0.5.2",
"objc2-app-kit",
"objc2-app-kit 0.2.2",
"objc2-foundation 0.2.2",
]
@@ -3138,12 +3018,12 @@ dependencies = [
"env_logger",
"hashbrown 0.16.1",
"log",
"raw-window-handle 0.6.2",
"raw-window-handle",
"ron",
"serde",
"wgpu-core",
"wgpu-types",
"winit 0.29.15",
"winit",
]
[[package]]
@@ -3361,12 +3241,6 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"
[[package]]
name = "raw-window-handle"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2ff9a1f06a88b01621b7ae906ef0211290d1c8a168a15542486a8f61c0833b9"
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -3405,15 +3279,6 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "redox_syscall"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29"
dependencies = [
"bitflags 1.3.2",
]
[[package]]
name = "redox_syscall"
version = "0.4.1"
@@ -3577,19 +3442,6 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "sctk-adwaita"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70b31447ca297092c5a9916fc3b955203157b37c19ca8edde4f52e9843e602c7"
dependencies = [
"ab_glyph",
"log",
"memmap2",
"smithay-client-toolkit 0.18.1",
"tiny-skia",
]
[[package]]
name = "sctk-adwaita"
version = "0.10.1"
@@ -3599,7 +3451,7 @@ dependencies = [
"ab_glyph",
"log",
"memmap2",
"smithay-client-toolkit 0.19.2",
"smithay-client-toolkit",
"tiny-skia",
]
@@ -3741,31 +3593,6 @@ dependencies = [
"serde",
]
[[package]]
name = "smithay-client-toolkit"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "922fd3eeab3bd820d76537ce8f582b1cf951eceb5475c28500c7457d9d17f53a"
dependencies = [
"bitflags 2.11.0",
"calloop 0.12.4",
"calloop-wayland-source 0.2.0",
"cursor-icon",
"libc",
"log",
"memmap2",
"rustix 0.38.44",
"thiserror 1.0.69",
"wayland-backend",
"wayland-client",
"wayland-csd-frame",
"wayland-cursor",
"wayland-protocols 0.31.2",
"wayland-protocols-wlr 0.2.0",
"wayland-scanner",
"xkeysym",
]
[[package]]
name = "smithay-client-toolkit"
version = "0.19.2"
@@ -3773,8 +3600,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016"
dependencies = [
"bitflags 2.11.0",
"calloop 0.13.0",
"calloop-wayland-source 0.3.0",
"calloop",
"calloop-wayland-source",
"cursor-icon",
"libc",
"log",
@@ -3785,8 +3612,8 @@ dependencies = [
"wayland-client",
"wayland-csd-frame",
"wayland-cursor",
"wayland-protocols 0.32.11",
"wayland-protocols-wlr 0.3.11",
"wayland-protocols",
"wayland-protocols-wlr",
"wayland-scanner",
"xkeysym",
]
@@ -4636,18 +4463,6 @@ dependencies = [
"xcursor",
]
[[package]]
name = "wayland-protocols"
version = "0.31.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f81f365b8b4a97f422ac0e8737c438024b5951734506b0e1d775c73030561f4"
dependencies = [
"bitflags 2.11.0",
"wayland-backend",
"wayland-client",
"wayland-scanner",
]
[[package]]
name = "wayland-protocols"
version = "0.32.11"
@@ -4660,19 +4475,6 @@ dependencies = [
"wayland-scanner",
]
[[package]]
name = "wayland-protocols-plasma"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23803551115ff9ea9bce586860c5c5a971e360825a0309264102a9495a5ff479"
dependencies = [
"bitflags 2.11.0",
"wayland-backend",
"wayland-client",
"wayland-protocols 0.31.2",
"wayland-scanner",
]
[[package]]
name = "wayland-protocols-plasma"
version = "0.3.11"
@@ -4682,20 +4484,7 @@ dependencies = [
"bitflags 2.11.0",
"wayland-backend",
"wayland-client",
"wayland-protocols 0.32.11",
"wayland-scanner",
]
[[package]]
name = "wayland-protocols-wlr"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad1f61b76b6c2d8742e10f9ba5c3737f6530b4c243132c2a2ccc8aa96fe25cd6"
dependencies = [
"bitflags 2.11.0",
"wayland-backend",
"wayland-client",
"wayland-protocols 0.31.2",
"wayland-protocols",
"wayland-scanner",
]
@@ -4708,7 +4497,7 @@ dependencies = [
"bitflags 2.11.0",
"wayland-backend",
"wayland-client",
"wayland-protocols 0.32.11",
"wayland-protocols",
"wayland-scanner",
]
@@ -4745,16 +4534,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "web-time"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa30049b1c872b72c89866d458eae9f20380ab280ffd1b1e18df2d3e2d98cfe0"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "web-time"
version = "1.1.0"
@@ -4773,7 +4552,7 @@ dependencies = [
"bitflags 2.11.0",
"bytemuck",
"cfg-if",
"cfg_aliases 0.2.1",
"cfg_aliases",
"document-features",
"hashbrown 0.16.1",
"js-sys",
@@ -4782,7 +4561,7 @@ dependencies = [
"parking_lot",
"portable-atomic",
"profiling",
"raw-window-handle 0.6.2",
"raw-window-handle",
"smallvec",
"static_assertions",
"wasm-bindgen",
@@ -4821,7 +4600,7 @@ dependencies = [
"env_logger",
"pollster",
"wgpu",
"winit 0.30.13",
"winit",
]
[[package]]
@@ -4833,7 +4612,7 @@ dependencies = [
"bit-vec 0.9.1",
"bitflags 2.11.0",
"bytemuck",
"cfg_aliases 0.2.1",
"cfg_aliases",
"document-features",
"hashbrown 0.16.1",
"indexmap",
@@ -4844,7 +4623,7 @@ dependencies = [
"parking_lot",
"portable-atomic",
"profiling",
"raw-window-handle 0.6.2",
"raw-window-handle",
"ron",
"rustc-hash 1.1.0",
"serde",
@@ -4904,7 +4683,7 @@ dependencies = [
"env_logger",
"pollster",
"wgpu",
"winit 0.30.13",
"winit",
]
[[package]]
@@ -4940,10 +4719,10 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-bindgen-test",
"web-sys",
"web-time 1.1.0",
"web-time",
"wgpu",
"wgpu-test",
"winit 0.29.15",
"winit",
]
[[package]]
@@ -4958,13 +4737,13 @@ dependencies = [
"block2 0.6.2",
"bytemuck",
"cfg-if",
"cfg_aliases 0.2.1",
"cfg_aliases",
"env_logger",
"glam",
"glow",
"glutin",
"glutin-winit",
"glutin_wgl_sys 0.6.1",
"glutin_wgl_sys",
"gpu-allocator",
"gpu-descriptor",
"hashbrown 0.16.1",
@@ -4975,7 +4754,7 @@ dependencies = [
"log",
"mach-dxcompiler-rs",
"naga",
"ndk-sys 0.6.0+11769913",
"ndk-sys",
"objc2 0.6.4",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
@@ -4988,8 +4767,7 @@ dependencies = [
"portable-atomic-util",
"profiling",
"range-alloc",
"raw-window-handle 0.5.2",
"raw-window-handle 0.6.2",
"raw-window-handle",
"raw-window-metal",
"renderdoc-sys",
"smallvec",
@@ -5001,7 +4779,7 @@ dependencies = [
"wgpu-types",
"windows",
"windows-core",
"winit 0.29.15",
"winit",
]
[[package]]
@@ -5065,7 +4843,7 @@ dependencies = [
"png",
"pollster",
"profiling",
"raw-window-handle 0.6.2",
"raw-window-handle",
"serde",
"serde_json",
"strum",
@@ -5089,7 +4867,7 @@ dependencies = [
"bytemuck",
"js-sys",
"log",
"raw-window-handle 0.6.2",
"raw-window-handle",
"serde",
"serde_json",
"web-sys",
@@ -5270,15 +5048,6 @@ dependencies = [
"windows-targets 0.42.2",
]
[[package]]
name = "windows-sys"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets 0.48.5",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
@@ -5321,21 +5090,6 @@ dependencies = [
"windows_x86_64_msvc 0.42.2",
]
[[package]]
name = "windows-targets"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
"windows_aarch64_gnullvm 0.48.5",
"windows_aarch64_msvc 0.48.5",
"windows_i686_gnu 0.48.5",
"windows_i686_msvc 0.48.5",
"windows_x86_64_gnu 0.48.5",
"windows_x86_64_gnullvm 0.48.5",
"windows_x86_64_msvc 0.48.5",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
@@ -5367,12 +5121,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
@@ -5385,12 +5133,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
@@ -5403,12 +5145,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
@@ -5427,12 +5163,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
@@ -5445,12 +5175,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
@@ -5463,12 +5187,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
@@ -5481,67 +5199,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winit"
version = "0.29.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d59ad965a635657faf09c8f062badd885748428933dad8e8bdd64064d92e5ca"
dependencies = [
"ahash",
"android-activity 0.5.2",
"atomic-waker",
"bitflags 2.11.0",
"bytemuck",
"calloop 0.12.4",
"cfg_aliases 0.1.1",
"core-foundation",
"core-graphics",
"cursor-icon",
"icrate",
"js-sys",
"libc",
"log",
"memmap2",
"ndk 0.8.0",
"ndk-sys 0.5.0+25.2.9519653",
"objc2 0.4.1",
"once_cell",
"orbclient",
"percent-encoding",
"raw-window-handle 0.5.2",
"raw-window-handle 0.6.2",
"redox_syscall 0.3.5",
"rustix 0.38.44",
"sctk-adwaita 0.8.3",
"smithay-client-toolkit 0.18.1",
"smol_str",
"unicode-segmentation",
"wasm-bindgen",
"wasm-bindgen-futures",
"wayland-backend",
"wayland-client",
"wayland-protocols 0.31.2",
"wayland-protocols-plasma 0.2.0",
"web-sys",
"web-time 0.2.4",
"windows-sys 0.48.0",
"x11-dl",
"x11rb",
"xkbcommon-dl",
]
[[package]]
name = "winit"
version = "0.30.13"
@@ -5549,13 +5212,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d"
dependencies = [
"ahash",
"android-activity 0.6.0",
"android-activity",
"atomic-waker",
"bitflags 2.11.0",
"block2 0.5.1",
"bytemuck",
"calloop 0.13.0",
"cfg_aliases 0.2.1",
"calloop",
"cfg_aliases",
"concurrent-queue",
"core-foundation",
"core-graphics",
@@ -5564,19 +5227,19 @@ dependencies = [
"js-sys",
"libc",
"memmap2",
"ndk 0.9.0",
"ndk",
"objc2 0.5.2",
"objc2-app-kit",
"objc2-app-kit 0.2.2",
"objc2-foundation 0.2.2",
"objc2-ui-kit",
"orbclient",
"percent-encoding",
"pin-project",
"raw-window-handle 0.6.2",
"raw-window-handle",
"redox_syscall 0.4.1",
"rustix 0.38.44",
"sctk-adwaita 0.10.1",
"smithay-client-toolkit 0.19.2",
"sctk-adwaita",
"smithay-client-toolkit",
"smol_str",
"tracing",
"unicode-segmentation",
@@ -5584,10 +5247,10 @@ dependencies = [
"wasm-bindgen-futures",
"wayland-backend",
"wayland-client",
"wayland-protocols 0.32.11",
"wayland-protocols-plasma 0.3.11",
"wayland-protocols",
"wayland-protocols-plasma",
"web-sys",
"web-time 1.1.0",
"web-time",
"windows-sys 0.52.0",
"x11-dl",
"x11rb",
+3 -4
View File
@@ -177,7 +177,6 @@ pp-rs = "0.2.1"
profiling = { version = "1.0.1", default-features = false }
quote = "1.0.38"
raw-window-handle = { version = "0.6.2", default-features = false }
rwh_05 = { version = "0.5.2", package = "raw-window-handle" } # temporary compatibility for glutin-winit
rayon = "1.3"
regex-lite = "0.1"
renderdoc-sys = "1"
@@ -202,7 +201,7 @@ tracy-client = "0.18"
thiserror = { version = "2.0.12", default-features = false }
unicode-ident = "1.0.5"
walkdir = "2.3"
winit = { version = "0.29", features = ["android-native-activity"] }
winit = { version = "0.30.8", features = ["android-native-activity"] }
which = "8"
xshell = "0.2.2"
@@ -284,8 +283,8 @@ gpu-allocator = { version = "0.28", default-features = false, features = [
# Gles dependencies
khronos-egl = "6"
glow = "0.17"
glutin = { version = "0.31", default-features = false }
glutin-winit = { version = "0.4", default-features = false }
glutin = { version = "0.32", default-features = false }
glutin-winit = { version = "0.5", default-features = false }
glutin_wgl_sys = "0.6"
# DX12 and GLES dependencies
+267 -152
View File
@@ -1,10 +1,12 @@
use std::future::Future;
use std::sync::Arc;
use wgpu::{Instance, Surface};
use winit::{
application::ApplicationHandler,
dpi::PhysicalSize,
event::{Event, KeyEvent, StartCause, WindowEvent},
event_loop::{EventLoop, EventLoopWindowTarget},
event::{KeyEvent, WindowEvent},
event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},
keyboard::{Key, NamedKey},
window::Window,
};
@@ -80,34 +82,18 @@ fn init_logger() {
}
}
struct EventLoopWrapper {
event_loop: EventLoop<()>,
window: Arc<Window>,
/// Runs a future to completion. On native this blocks via pollster, on wasm this spawns
/// a local task. This allows the same async wgpu initialization code to work on both platforms.
#[cfg(not(target_arch = "wasm32"))]
fn spawn(f: impl Future<Output = ()> + 'static) {
pollster::block_on(f);
}
impl EventLoopWrapper {
pub fn new(title: &str) -> Self {
let event_loop = EventLoop::new().unwrap();
let mut builder = winit::window::WindowBuilder::new();
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowBuilderExtWebSys;
let canvas = web_sys::window()
.unwrap()
.document()
.unwrap()
.get_element_by_id("canvas")
.unwrap()
.dyn_into::<web_sys::HtmlCanvasElement>()
.unwrap();
builder = builder.with_canvas(Some(canvas));
}
builder = builder.with_title(title);
let window = Arc::new(builder.build(&event_loop).unwrap());
Self { event_loop, window }
}
/// Runs a future to completion. On native this blocks via pollster, on wasm this spawns
/// a local task. This allows the same async wgpu initialization code to work on both platforms.
#[cfg(target_arch = "wasm32")]
fn spawn(f: impl Future<Output = ()> + 'static) {
wasm_bindgen_futures::spawn_local(f);
}
/// Wrapper type which manages the surface and surface configuration.
@@ -140,20 +126,10 @@ impl SurfaceWrapper {
}
}
/// Check if the event is the start condition for the surface.
fn start_condition(e: &Event<()>) -> bool {
match e {
// On all other platforms, we can create the surface immediately.
Event::NewEvents(StartCause::Init) => !cfg!(target_os = "android"),
// On android we need to wait for a resumed event to create the surface.
Event::Resumed => cfg!(target_os = "android"),
_ => false,
}
}
/// Called when an event which matches [`Self::start_condition`] is received.
/// Called on resume to create (on native) and configure the surface.
///
/// On all native platforms, this is where we create the surface.
/// On wasm, the surface was already created in [`Self::pre_adapter`].
///
/// Additionally, we configure the surface based on the (now valid) window size.
fn resume(&mut self, context: &ExampleContext, window: Arc<Window>, srgb: bool) {
@@ -257,14 +233,15 @@ struct ExampleContext {
}
impl ExampleContext {
/// Initializes the example context.
async fn init_async<E: Example>(surface: &mut SurfaceWrapper, window: Arc<Window>) -> Self {
async fn init_async<E: Example>(
surface: &mut SurfaceWrapper,
window: Arc<Window>,
display_handle: winit::event_loop::OwnedDisplayHandle,
) -> Self {
log::info!("Initializing wgpu...");
let instance_descriptor =
wgpu::InstanceDescriptor::new_with_display_handle_from_env(Box::new(
// TODO: Use event_loop.owned_display_handle() with winit 0.30
window.clone(),
));
wgpu::InstanceDescriptor::new_with_display_handle_from_env(Box::new(display_handle));
let instance = wgpu::Instance::new(instance_descriptor);
surface.pre_adapter(&instance, window);
let adapter = get_adapter_with_capabilities_or_from_env(
@@ -336,7 +313,244 @@ impl FrameCounter {
}
}
async fn start<E: Example>(title: &str) {
/// User event sent via [`EventLoopProxy`] to deliver async initialization results
/// back to the main event loop.
enum AppAction {
/// The async wgpu initialization has completed.
WgpuInitialized {
context: ExampleContext,
surface: SurfaceWrapper,
},
}
#[expect(clippy::large_enum_variant)]
enum AppState<E> {
/// Waiting for the first `resumed()` call.
Uninitialized,
/// Window created, async wgpu initialization in progress.
Loading,
/// Fully initialized and rendering.
Running {
context: ExampleContext,
surface: SurfaceWrapper,
example: E,
},
}
/// The main application struct, implementing winit's [`ApplicationHandler`].
///
/// Winit 0.30 requires that windows are not created until the `resumed()` callback,
/// and that all wgpu resources (instance, adapter, device) are initialized after the
/// window exists. On native, this init happens synchronously via `pollster::block_on`.
/// On wasm, it happens asynchronously via `wasm_bindgen_futures::spawn_local`, with
/// the results delivered back through an [`EventLoopProxy`] user event.
struct App<E: Example> {
title: &'static str,
proxy: EventLoopProxy<AppAction>,
window: Option<Arc<Window>>,
frame_counter: FrameCounter,
occluded: bool,
state: AppState<E>,
}
impl<E: Example> App<E> {
fn new(title: &'static str, event_loop: &EventLoop<AppAction>) -> Self {
Self {
title,
proxy: event_loop.create_proxy(),
window: None,
frame_counter: FrameCounter::new(),
occluded: false,
state: AppState::Uninitialized,
}
}
}
impl<E: Example> ApplicationHandler<AppAction> for App<E> {
/// Called when the application is (re)started. On the first call, the window and wgpu
/// resources are created. On Android, this may be called again after each suspend —
/// in that case we only need to re-create the surface.
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
// On Android, re-create the surface after a suspend/resume cycle.
if let AppState::Running {
ref context,
ref mut surface,
..
} = self.state
{
if let Some(window) = &self.window {
surface.resume(context, window.clone(), E::SRGB);
window.request_redraw();
}
return;
}
if !matches!(self.state, AppState::Uninitialized) {
return;
}
self.state = AppState::Loading;
#[cfg_attr(
not(target_arch = "wasm32"),
expect(unused_mut, reason = "wasm32 re-assigns to specify canvas")
)]
let mut attributes = Window::default_attributes().with_title(self.title);
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowAttributesExtWebSys;
let canvas = web_sys::window()
.unwrap()
.document()
.unwrap()
.get_element_by_id("canvas")
.unwrap()
.dyn_into::<web_sys::HtmlCanvasElement>()
.unwrap();
attributes = attributes.with_canvas(Some(canvas));
}
let window = Arc::new(
event_loop
.create_window(attributes)
.expect("Failed to create window"),
);
self.window = Some(window.clone());
let display_handle = event_loop.owned_display_handle();
let proxy = self.proxy.clone();
// Spawn the async wgpu initialization. On native, `spawn` uses `pollster::block_on`
// so this completes synchronously before `resumed()` returns. On wasm, `spawn` uses
// `wasm_bindgen_futures::spawn_local` so the result arrives later via `user_event()`.
spawn(async move {
let mut surface = SurfaceWrapper::new();
let context =
ExampleContext::init_async::<E>(&mut surface, window.clone(), display_handle).await;
surface.resume(&context, window, E::SRGB);
let _ = proxy.send_event(AppAction::WgpuInitialized { context, surface });
});
}
/// Receives the result of the async wgpu initialization. Creates the [`Example`] and
/// transitions to the running state.
fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: AppAction) {
match event {
AppAction::WgpuInitialized { context, surface } => {
let example = E::init(
surface.config(),
&context.adapter,
&context.device,
&context.queue,
);
self.state = AppState::Running {
context,
surface,
example,
};
if let Some(window) = &self.window {
window.request_redraw();
}
}
}
}
fn suspended(&mut self, _event_loop: &ActiveEventLoop) {
if let AppState::Running { surface, .. } = &mut self.state {
surface.suspend();
}
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
let AppState::Running {
ref mut context,
ref mut surface,
ref mut example,
} = self.state
else {
return;
};
match event {
WindowEvent::Resized(size) => {
surface.resize(context, size);
example.resize(surface.config(), &context.device, &context.queue);
if let Some(window) = &self.window {
window.request_redraw();
}
}
WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: Key::Named(NamedKey::Escape),
..
},
..
}
| WindowEvent::CloseRequested => {
event_loop.exit();
}
#[cfg(not(target_arch = "wasm32"))]
WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: Key::Character(s),
..
},
..
} if s == "r" => {
println!("{:#?}", context.instance.generate_report());
}
WindowEvent::RedrawRequested => {
// Don't render while occluded, this may leak on apple platforms.
if self.occluded {
return;
}
self.frame_counter.update();
if let Some(frame) = surface.acquire(context) {
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor {
format: Some(surface.config().view_formats[0]),
..wgpu::TextureViewDescriptor::default()
});
example.render(&view, &context.device, &context.queue);
if let Some(window) = &self.window {
window.pre_present_notify();
}
frame.present();
}
if let Some(window) = &self.window {
window.request_redraw();
}
}
WindowEvent::Occluded(is_occluded) => {
self.occluded = is_occluded;
// Resume rendering when un-occluded.
if !is_occluded {
if let Some(window) = &self.window {
window.request_redraw();
}
}
}
_ => example.update(event),
}
}
}
fn start<E: Example>(title: &'static str) {
init_logger();
log::debug!(
@@ -344,123 +558,24 @@ async fn start<E: Example>(title: &str) {
wgpu::Instance::enabled_backend_features()
);
let window_loop = EventLoopWrapper::new(title);
let mut surface = SurfaceWrapper::new();
let context = ExampleContext::init_async::<E>(&mut surface, window_loop.window.clone()).await;
let mut frame_counter = FrameCounter::new();
let event_loop = EventLoop::with_user_event().build().unwrap();
// We wait to create the example until we have a valid surface.
let mut example = None;
#[cfg_attr(target_arch = "wasm32", expect(unused_mut))]
let mut app = App::<E>::new(title, &event_loop);
log::info!("Entering event loop...");
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
use winit::platform::web::EventLoopExtWebSys;
let event_loop_function = EventLoop::spawn;
event_loop.spawn_app(app);
} else {
let event_loop_function = EventLoop::run;
event_loop.run_app(&mut app).unwrap();
}
}
log::info!("Entering event loop...");
#[cfg_attr(target_arch = "wasm32", expect(clippy::let_unit_value))]
let _ = (event_loop_function)(
window_loop.event_loop,
move |event: Event<()>, target: &EventLoopWindowTarget<()>| {
match event {
ref e if SurfaceWrapper::start_condition(e) => {
surface.resume(&context, window_loop.window.clone(), E::SRGB);
// If we haven't created the example yet, do so now.
if example.is_none() {
example = Some(E::init(
surface.config(),
&context.adapter,
&context.device,
&context.queue,
));
}
}
Event::Suspended => {
surface.suspend();
}
Event::WindowEvent { event, .. } => match event {
WindowEvent::Resized(size) => {
surface.resize(&context, size);
example.as_mut().unwrap().resize(
surface.config(),
&context.device,
&context.queue,
);
window_loop.window.request_redraw();
}
WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: Key::Named(NamedKey::Escape),
..
},
..
}
| WindowEvent::CloseRequested => {
target.exit();
}
#[cfg(not(target_arch = "wasm32"))]
WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: Key::Character(s),
..
},
..
} if s == "r" => {
println!("{:#?}", context.instance.generate_report());
}
WindowEvent::RedrawRequested => {
// On MacOS, currently redraw requested comes in _before_ Init does.
// If this happens, just drop the requested redraw on the floor.
//
// See https://github.com/rust-windowing/winit/issues/3235 for some discussion
if example.is_none() {
return;
}
frame_counter.update();
if let Some(frame) = surface.acquire(&context) {
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor {
format: Some(surface.config().view_formats[0]),
..wgpu::TextureViewDescriptor::default()
});
example.as_mut().unwrap().render(
&view,
&context.device,
&context.queue,
);
window_loop.window.pre_present_notify();
frame.present();
}
window_loop.window.request_redraw();
}
_ => example.as_mut().unwrap().update(event),
},
_ => {}
}
},
);
}
pub fn run<E: Example>(title: &'static str) {
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
wasm_bindgen_futures::spawn_local(async move { start::<E>(title).await })
} else {
pollster::block_on(start::<E>(title));
}
}
start::<E>(title);
}
#[cfg(target_arch = "wasm32")]
+280 -172
View File
@@ -1,197 +1,305 @@
use std::{borrow::Cow, sync::Arc};
use std::{borrow::Cow, future::Future, sync::Arc};
use wgpu::SurfaceError;
use winit::{
event::{Event, WindowEvent},
event_loop::EventLoop,
application::ApplicationHandler,
event::WindowEvent,
event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},
window::Window,
};
async fn run(event_loop: EventLoop<()>, window: Window) {
let window = Arc::new(window);
let mut size = window.inner_size();
size.width = size.width.max(1);
size.height = size.height.max(1);
/// Runs a future to completion. On native this blocks synchronously via pollster.
/// On wasm this spawns a local task so control returns to the browser immediately.
#[cfg(not(target_arch = "wasm32"))]
fn spawn(f: impl Future<Output = ()> + 'static) {
pollster::block_on(f);
}
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_with_display_handle_from_env(
// TODO: Use event_loop.owned_display_handle() with winit 0.30
Box::new(window.clone()),
));
/// Runs a future to completion. On native this blocks synchronously via pollster.
/// On wasm this spawns a local task so control returns to the browser immediately.
#[cfg(target_arch = "wasm32")]
fn spawn(f: impl Future<Output = ()> + 'static) {
wasm_bindgen_futures::spawn_local(f);
}
let surface = instance.create_surface(&window).unwrap();
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
force_fallback_adapter: false,
// Request an adapter which can render to our surface
compatible_surface: Some(&surface),
})
.await
.expect("Failed to find an appropriate adapter");
struct WgpuState {
device: wgpu::Device,
queue: wgpu::Queue,
surface: wgpu::Surface<'static>,
config: wgpu::SurfaceConfiguration,
render_pipeline: wgpu::RenderPipeline,
}
// Create the logical device and command queue
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: None,
required_features: wgpu::Features::empty(),
// Make sure we use the texture resolution limits from the adapter, so we can support images the size of the swapchain.
required_limits: wgpu::Limits::downlevel_webgl2_defaults()
.using_resolution(adapter.limits()),
experimental_features: wgpu::ExperimentalFeatures::disabled(),
memory_hints: wgpu::MemoryHints::MemoryUsage,
trace: wgpu::Trace::Off,
})
.await
.expect("Failed to create device");
enum TriangleAction {
Initialized(WgpuState),
}
// Load the shaders from disk
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
});
#[expect(clippy::large_enum_variant)]
enum AppState {
Uninitialized,
Loading,
Running(WgpuState),
}
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[],
immediate_size: 0,
});
struct App {
proxy: EventLoopProxy<TriangleAction>,
window: Option<Arc<Window>>,
state: AppState,
}
let swapchain_capabilities = surface.get_capabilities(&adapter);
let swapchain_format = swapchain_capabilities.formats[0];
impl App {
fn new(event_loop: &EventLoop<TriangleAction>) -> Self {
Self {
proxy: event_loop.create_proxy(),
window: None,
state: AppState::Uninitialized,
}
}
}
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None,
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(swapchain_format.into())],
}),
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
impl ApplicationHandler<TriangleAction> for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if !matches!(self.state, AppState::Uninitialized) {
return;
}
self.state = AppState::Loading;
let mut config = surface
.get_default_config(&adapter, size.width, size.height)
.unwrap();
surface.configure(&device, &config);
#[cfg_attr(
not(target_arch = "wasm32"),
expect(unused_mut, reason = "wasm32 re-assigns to specify canvas")
)]
let mut attributes = Window::default_attributes();
let window = &window;
event_loop
.run(move |event, target| {
// Have the closure take ownership of the resources.
// `event_loop.run` never returns, therefore we must do this to ensure
// the resources are properly cleaned up.
let _ = (&instance, &adapter, &shader, &pipeline_layout);
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowAttributesExtWebSys;
let canvas = web_sys::window()
.unwrap()
.document()
.unwrap()
.get_element_by_id("canvas")
.unwrap()
.dyn_into::<web_sys::HtmlCanvasElement>()
.unwrap();
attributes = attributes.with_canvas(Some(canvas));
}
if let Event::WindowEvent {
window_id: _,
event,
} = event
{
match event {
WindowEvent::Resized(new_size) => {
// Reconfigure the surface with the new size
config.width = new_size.width.max(1);
config.height = new_size.height.max(1);
surface.configure(&device, &config);
// On macos the window needs to be redrawn manually after resizing
let window = Arc::new(
event_loop
.create_window(attributes)
.expect("Failed to create window"),
);
self.window = Some(window.clone());
let display_handle = event_loop.owned_display_handle();
let proxy = self.proxy.clone();
spawn(async move {
let mut size = window.inner_size();
size.width = size.width.max(1);
size.height = size.height.max(1);
let instance =
wgpu::Instance::new(wgpu::InstanceDescriptor::new_with_display_handle_from_env(
Box::new(display_handle),
));
let surface = instance.create_surface(window.clone()).unwrap();
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
force_fallback_adapter: false,
// Request an adapter which can render to our surface
compatible_surface: Some(&surface),
})
.await
.expect("Failed to find an appropriate adapter");
// Create the logical device and command queue
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: None,
required_features: wgpu::Features::empty(),
// Make sure we use the texture resolution limits from the adapter,
// so we can support images the size of the swapchain.
required_limits: wgpu::Limits::downlevel_webgl2_defaults()
.using_resolution(adapter.limits()),
experimental_features: wgpu::ExperimentalFeatures::disabled(),
memory_hints: wgpu::MemoryHints::MemoryUsage,
trace: wgpu::Trace::Off,
})
.await
.expect("Failed to create device");
// Load the shaders from disk
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[],
immediate_size: 0,
});
let swapchain_capabilities = surface.get_capabilities(&adapter);
let swapchain_format = swapchain_capabilities.formats[0];
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None,
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(swapchain_format.into())],
}),
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let config = surface
.get_default_config(&adapter, size.width, size.height)
.unwrap();
surface.configure(&device, &config);
let _ = proxy.send_event(TriangleAction::Initialized(WgpuState {
device,
queue,
surface,
config,
render_pipeline,
}));
});
}
fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: TriangleAction) {
match event {
TriangleAction::Initialized(wgpu_state) => {
self.state = AppState::Running(wgpu_state);
if let Some(window) = &self.window {
window.request_redraw();
}
}
}
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
let AppState::Running(wgpu_state) = &mut self.state else {
return;
};
match event {
WindowEvent::Resized(new_size) => {
// Reconfigure the surface with the new size
wgpu_state.config.width = new_size.width.max(1);
wgpu_state.config.height = new_size.height.max(1);
wgpu_state
.surface
.configure(&wgpu_state.device, &wgpu_state.config);
// On macos the window needs to be redrawn manually after resizing
if let Some(window) = &self.window {
window.request_redraw();
}
}
WindowEvent::RedrawRequested => {
match wgpu_state.surface.get_current_texture() {
Ok(frame) => {
let view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = wgpu_state.device.create_command_encoder(
&wgpu::CommandEncoderDescriptor { label: None },
);
{
let mut rpass =
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::GREEN),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
rpass.set_pipeline(&wgpu_state.render_pipeline);
rpass.draw(0..3, 0..1);
}
wgpu_state.queue.submit(Some(encoder.finish()));
if let Some(window) = &self.window {
window.pre_present_notify();
}
frame.present();
}
Err(SurfaceError::Timeout | SurfaceError::Occluded) => {
// Try again later
if let Some(window) = &self.window {
window.request_redraw();
}
}
Err(err) => {
// TODO: reconfigure the surface instead
panic!("get_current_texture: {err}");
}
}
}
WindowEvent::Occluded(is_occluded) => {
if !is_occluded {
if let Some(window) = &self.window {
window.request_redraw();
}
WindowEvent::RedrawRequested => match surface.get_current_texture() {
Ok(frame) => {
let view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: None,
});
{
let mut rpass =
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(
wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::GREEN),
store: wgpu::StoreOp::Store,
},
},
)],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
rpass.set_pipeline(&render_pipeline);
rpass.draw(0..3, 0..1);
}
queue.submit(Some(encoder.finish()));
window.pre_present_notify();
frame.present();
}
Err(SurfaceError::Timeout | SurfaceError::Occluded) => {
window.request_redraw(); // Try again later
}
Err(err) => {
// TODO: reconfigure the surface instead
panic!("get_current_texture: {err}");
}
},
WindowEvent::CloseRequested => target.exit(),
_ => {}
};
}
}
})
.unwrap();
WindowEvent::CloseRequested => event_loop.exit(),
_ => {}
}
}
}
pub fn main() {
let event_loop = EventLoop::new().unwrap();
#[cfg_attr(
not(target_arch = "wasm32"),
expect(unused_mut, reason = "`wasm32` re-assigns to specify canvas")
)]
let mut builder = winit::window::WindowBuilder::new();
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowBuilderExtWebSys;
let canvas = web_sys::window()
.unwrap()
.document()
.unwrap()
.get_element_by_id("canvas")
.unwrap()
.dyn_into::<web_sys::HtmlCanvasElement>()
.unwrap();
builder = builder.with_canvas(Some(canvas));
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
console_log::init().expect("could not initialize logger");
} else {
env_logger::init();
}
}
let window = builder.build(&event_loop).unwrap();
#[cfg(not(target_arch = "wasm32"))]
{
env_logger::init();
pollster::block_on(run(event_loop, window));
}
#[cfg(target_arch = "wasm32")]
{
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
console_log::init().expect("could not initialize logger");
wasm_bindgen_futures::spawn_local(run(event_loop, window));
let event_loop = EventLoop::with_user_event().build().unwrap();
#[cfg_attr(target_arch = "wasm32", expect(unused_mut))]
let mut app = App::new(&event_loop);
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
use winit::platform::web::EventLoopExtWebSys;
event_loop.spawn_app(app);
} else {
event_loop.run_app(&mut app).unwrap();
}
}
}
+193 -132
View File
@@ -1,10 +1,11 @@
#![cfg_attr(target_arch = "wasm32", allow(dead_code))]
#![cfg_attr(target_arch = "wasm32", allow(dead_code, unused_imports))]
use std::{collections::HashMap, sync::Arc};
use wgpu::SurfaceError;
use winit::{
event::{Event, WindowEvent},
event_loop::EventLoop,
application::ApplicationHandler,
event::WindowEvent,
event_loop::ActiveEventLoop,
window::{Window, WindowId},
};
@@ -52,138 +53,57 @@ impl Viewport {
}
}
async fn run(event_loop: EventLoop<()>, viewports: Vec<(Arc<Window>, wgpu::Color)>) {
let instance = wgpu::Instance::default();
let viewports: Vec<_> = viewports
.into_iter()
.map(|(window, color)| ViewportDesc::new(window, color, &instance))
.collect();
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
// Request an adapter which can render to our surface
compatible_surface: viewports.first().map(|desc| &desc.surface),
..Default::default()
})
.await
.expect("Failed to find an appropriate adapter");
const WINDOW_SIZE: u32 = 128;
const WINDOW_PADDING: u32 = 16;
const WINDOW_TITLEBAR: u32 = 32;
const WINDOW_OFFSET: u32 = WINDOW_SIZE + WINDOW_PADDING;
const ROWS: u32 = 4;
const COLUMNS: u32 = 4;
// Create the logical device and command queue
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: None,
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::downlevel_defaults(),
experimental_features: wgpu::ExperimentalFeatures::disabled(),
memory_hints: wgpu::MemoryHints::MemoryUsage,
trace: wgpu::Trace::Off,
})
.await
.expect("Failed to create device");
let mut viewports: HashMap<WindowId, Viewport> = viewports
.into_iter()
.map(|desc| (desc.window.id(), desc.build(&adapter, &device)))
.collect();
event_loop
.run(move |event, target| {
// Have the closure take ownership of the resources.
// `event_loop.run` never returns, therefore we must do this to ensure
// the resources are properly cleaned up.
let _ = (&instance, &adapter);
if let Event::WindowEvent { window_id, event } = event {
match event {
WindowEvent::Resized(new_size) => {
// Recreate the swap chain with the new size
if let Some(viewport) = viewports.get_mut(&window_id) {
viewport.resize(&device, new_size);
// On macos the window needs to be redrawn manually after resizing
viewport.desc.window.request_redraw();
}
}
WindowEvent::RedrawRequested => {
if let Some(viewport) = viewports.get_mut(&window_id) {
match viewport.get_current_texture() {
Ok(frame) => {
let view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = device.create_command_encoder(
&wgpu::CommandEncoderDescriptor { label: None },
);
{
let _rpass = encoder.begin_render_pass(
&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(
wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(
viewport.desc.background,
),
store: wgpu::StoreOp::Store,
},
},
)],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
},
);
}
queue.submit(Some(encoder.finish()));
viewport.desc.window.pre_present_notify();
frame.present();
}
Err(SurfaceError::Timeout | SurfaceError::Occluded) => {
viewport.desc.window.request_redraw(); // Try again later
}
Err(err) => {
// TODO: reconfigure the surface instead
panic!("get_current_texture: {err}");
}
}
}
}
WindowEvent::CloseRequested => {
viewports.remove(&window_id);
if viewports.is_empty() {
target.exit();
}
}
_ => {}
}
}
})
.unwrap();
enum AppState {
Uninitialized,
Running {
device: wgpu::Device,
queue: wgpu::Queue,
viewports: HashMap<WindowId, Viewport>,
},
}
pub fn main() {
#[cfg(not(target_arch = "wasm32"))]
{
const WINDOW_SIZE: u32 = 128;
const WINDOW_PADDING: u32 = 16;
const WINDOW_TITLEBAR: u32 = 32;
const WINDOW_OFFSET: u32 = WINDOW_SIZE + WINDOW_PADDING;
const ROWS: u32 = 4;
const COLUMNS: u32 = 4;
struct App {
state: AppState,
}
let event_loop = EventLoop::new().unwrap();
let mut viewports = Vec::with_capacity((ROWS * COLUMNS) as usize);
impl App {
fn new() -> Self {
Self {
state: AppState::Uninitialized,
}
}
}
impl ApplicationHandler for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if !matches!(self.state, AppState::Uninitialized) {
return;
}
// Create all 16 windows.
let mut windows: Vec<(Arc<Window>, wgpu::Color)> =
Vec::with_capacity((ROWS * COLUMNS) as usize);
for row in 0..ROWS {
for column in 0..COLUMNS {
let window = winit::window::WindowBuilder::new()
.with_title(format!("x{column}y{row}"))
.with_inner_size(winit::dpi::PhysicalSize::new(WINDOW_SIZE, WINDOW_SIZE))
.build(&event_loop)
.unwrap();
let window = Arc::new(window);
let window = Arc::new(
event_loop
.create_window(
Window::default_attributes()
.with_title(format!("x{column}y{row}"))
.with_inner_size(winit::dpi::PhysicalSize::new(
WINDOW_SIZE,
WINDOW_SIZE,
)),
)
.unwrap(),
);
window.set_outer_position(winit::dpi::PhysicalPosition::new(
WINDOW_PADDING + column * WINDOW_OFFSET,
WINDOW_PADDING + row * (WINDOW_OFFSET + WINDOW_TITLEBAR),
@@ -191,7 +111,7 @@ pub fn main() {
fn frac(index: u32, max: u32) -> f64 {
index as f64 / max as f64
}
viewports.push((
windows.push((
window,
wgpu::Color {
r: frac(row, ROWS),
@@ -199,12 +119,153 @@ pub fn main() {
b: frac(column, COLUMNS),
a: 1.0,
},
))
));
}
}
// Initialize wgpu synchronously (native-only).
let instance =
wgpu::Instance::new(wgpu::InstanceDescriptor::new_with_display_handle_from_env(
Box::new(event_loop.owned_display_handle()),
));
let viewport_descs: Vec<_> = windows
.into_iter()
.map(|(window, color)| ViewportDesc::new(window, color, &instance))
.collect();
let (adapter, device, queue) = pollster::block_on(async {
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
compatible_surface: viewport_descs.first().map(|desc| &desc.surface),
..Default::default()
})
.await
.expect("Failed to find an appropriate adapter");
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: None,
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::downlevel_defaults(),
experimental_features: wgpu::ExperimentalFeatures::disabled(),
memory_hints: wgpu::MemoryHints::MemoryUsage,
trace: wgpu::Trace::Off,
})
.await
.expect("Failed to create device");
(adapter, device, queue)
});
let viewports: HashMap<WindowId, Viewport> = viewport_descs
.into_iter()
.map(|desc| (desc.window.id(), desc.build(&adapter, &device)))
.collect();
self.state = AppState::Running {
device,
queue,
viewports,
};
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
window_id: WindowId,
event: WindowEvent,
) {
let AppState::Running {
device,
queue,
viewports,
} = &mut self.state
else {
return;
};
match event {
WindowEvent::Resized(new_size) => {
// Recreate the swap chain with the new size
if let Some(viewport) = viewports.get_mut(&window_id) {
viewport.resize(device, new_size);
// On macos the window needs to be redrawn manually after resizing
viewport.desc.window.request_redraw();
}
}
WindowEvent::RedrawRequested => {
if let Some(viewport) = viewports.get_mut(&window_id) {
match viewport.get_current_texture() {
Ok(frame) => {
let view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: None,
});
{
let _rpass =
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(
wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(
viewport.desc.background,
),
store: wgpu::StoreOp::Store,
},
},
)],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
}
queue.submit(Some(encoder.finish()));
viewport.desc.window.pre_present_notify();
frame.present();
}
Err(SurfaceError::Timeout | SurfaceError::Occluded) => {
viewport.desc.window.request_redraw();
}
Err(err) => {
// TODO: reconfigure the surface instead
panic!("get_current_texture: {err}");
}
}
}
}
WindowEvent::Occluded(is_occluded) => {
if !is_occluded {
if let Some(viewport) = viewports.get(&window_id) {
viewport.desc.window.request_redraw();
}
}
}
WindowEvent::CloseRequested => {
viewports.remove(&window_id);
if viewports.is_empty() {
event_loop.exit();
}
}
_ => {}
}
}
}
pub fn main() {
#[cfg(not(target_arch = "wasm32"))]
{
env_logger::init();
pollster::block_on(run(event_loop, viewports));
let event_loop = winit::event_loop::EventLoop::new().unwrap();
let mut app = App::new();
event_loop.run_app(&mut app).unwrap();
}
#[cfg(target_arch = "wasm32")]
{
+277 -190
View File
@@ -16,14 +16,15 @@
//! The usage of the uniform buffer within the shader itself is pretty self-explanatory given
//! some understanding of WGSL.
use std::sync::Arc;
use std::{future::Future, sync::Arc};
// We won't bring StorageBuffer into scope as that might be too easy to confuse
// with actual GPU-allocated wgpu storage buffers.
use encase::ShaderType;
use wgpu::SurfaceError;
use winit::{
event::{Event, KeyEvent, WindowEvent},
event_loop::EventLoop,
application::ApplicationHandler,
event::{KeyEvent, WindowEvent},
event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},
keyboard::{Key, NamedKey},
window::Window,
};
@@ -31,15 +32,25 @@ use winit::{
const ZOOM_INCREMENT_FACTOR: f32 = 1.1;
const CAMERA_POS_INCREMENT_FACTOR: f32 = 0.1;
#[cfg(not(target_arch = "wasm32"))]
fn spawn(f: impl Future<Output = ()> + 'static) {
pollster::block_on(f);
}
#[cfg(target_arch = "wasm32")]
fn spawn(f: impl Future<Output = ()> + 'static) {
wasm_bindgen_futures::spawn_local(f);
}
// (1)
#[derive(Debug, ShaderType)]
struct AppState {
struct ShaderState {
pub cursor_pos: glam::Vec2,
pub zoom: f32,
pub max_iterations: u32,
}
impl AppState {
impl ShaderState {
// Translating Rust structures to WGSL is always tricky and can prove
// incredibly difficult to remember all the rules by which WGSL
// lays out and formats structs in memory. It is also often extremely
@@ -75,9 +86,9 @@ impl AppState {
}
}
impl Default for AppState {
impl Default for ShaderState {
fn default() -> Self {
AppState {
ShaderState {
cursor_pos: glam::Vec2::ZERO,
zoom: 1.0,
max_iterations: 50,
@@ -86,7 +97,6 @@ impl Default for AppState {
}
struct WgpuContext {
pub window: Arc<Window>,
pub surface: wgpu::Surface<'static>,
pub surface_config: wgpu::SurfaceConfiguration,
pub device: wgpu::Device,
@@ -97,10 +107,15 @@ struct WgpuContext {
}
impl WgpuContext {
async fn new(window: Arc<Window>) -> WgpuContext {
async fn new(
window: Arc<Window>,
display_handle: winit::event_loop::OwnedDisplayHandle,
) -> WgpuContext {
let size = window.inner_size();
let instance = wgpu::Instance::default();
let instance = wgpu::Instance::new(
wgpu::InstanceDescriptor::new_with_display_handle_from_env(Box::new(display_handle)),
);
let surface = instance.create_surface(window.clone()).unwrap();
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
@@ -127,7 +142,7 @@ impl WgpuContext {
// (2)
let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: size_of::<AppState>() as u64,
size: size_of::<ShaderState>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -197,7 +212,6 @@ impl WgpuContext {
// (5)
WgpuContext {
window,
surface,
surface_config,
device,
@@ -212,204 +226,277 @@ impl WgpuContext {
self.surface_config.width = new_size.width;
self.surface_config.height = new_size.height;
self.surface.configure(&self.device, &self.surface_config);
self.window.request_redraw();
}
}
async fn run(event_loop: EventLoop<()>, window: Arc<Window>) {
let mut wgpu_context = Some(WgpuContext::new(window.clone()).await);
// (6)
let mut state = Some(AppState::default());
let main_window_id = wgpu_context.as_ref().unwrap().window.id();
event_loop
.run(move |event, target| {
match event {
Event::LoopExiting => {
wgpu_context = None;
state = None;
enum UniformAction {
Initialized(WgpuContext),
}
#[expect(clippy::large_enum_variant)]
enum RunState {
Uninitialized,
Loading,
Running {
wgpu_ctx: WgpuContext,
// (6)
shader_state: ShaderState,
},
}
struct App {
proxy: EventLoopProxy<UniformAction>,
window: Option<Arc<Window>>,
state: RunState,
}
impl App {
fn new(event_loop: &EventLoop<UniformAction>) -> Self {
Self {
proxy: event_loop.create_proxy(),
window: None,
state: RunState::Uninitialized,
}
}
}
impl ApplicationHandler<UniformAction> for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if !matches!(self.state, RunState::Uninitialized) {
return;
}
self.state = RunState::Loading;
#[cfg_attr(
not(target_arch = "wasm32"),
expect(unused_mut, reason = "wasm32 re-assigns to specify canvas")
)]
let mut attributes = Window::default_attributes()
.with_title("Remember: Use U/D to change sample count!")
.with_inner_size(winit::dpi::LogicalSize::new(900, 900));
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowAttributesExtWebSys;
let canvas = web_sys::window()
.unwrap()
.document()
.unwrap()
.get_element_by_id("canvas")
.unwrap()
.dyn_into::<web_sys::HtmlCanvasElement>()
.unwrap();
attributes = attributes.with_canvas(Some(canvas));
}
let window = Arc::new(
event_loop
.create_window(attributes)
.expect("Failed to create window"),
);
self.window = Some(window.clone());
let display_handle = event_loop.owned_display_handle();
let proxy = self.proxy.clone();
spawn(async move {
let wgpu_ctx = WgpuContext::new(window, display_handle).await;
let _ = proxy.send_event(UniformAction::Initialized(wgpu_ctx));
});
}
fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: UniformAction) {
match event {
UniformAction::Initialized(wgpu_ctx) => {
self.state = RunState::Running {
wgpu_ctx,
shader_state: ShaderState::default(),
};
if let Some(window) = &self.window {
window.request_redraw();
}
Event::WindowEvent { window_id, event } if window_id == main_window_id => {
match event {
WindowEvent::CloseRequested => {
target.exit();
}
WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key, text, ..
},
..
} => {
let state_mut = state.as_mut().unwrap();
let wgpu_context_ref = wgpu_context.as_ref().unwrap();
}
}
}
if let Key::Named(key) = logical_key {
match key {
NamedKey::Escape => target.exit(),
NamedKey::ArrowUp => state_mut.translate_view(1, 1),
NamedKey::ArrowDown => state_mut.translate_view(-1, 1),
NamedKey::ArrowLeft => state_mut.translate_view(-1, 0),
NamedKey::ArrowRight => state_mut.translate_view(1, 0),
_ => {}
}
}
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
self.state = RunState::Uninitialized;
}
if let Some(text) = text {
if text == "u" {
state_mut.max_iterations += 3;
} else if text == "d" {
state_mut.max_iterations -= 3;
}
};
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
let RunState::Running {
wgpu_ctx,
shader_state,
} = &mut self.state
else {
return;
};
wgpu_context_ref.window.request_redraw();
}
WindowEvent::MouseWheel { delta, .. } => {
let change = match delta {
winit::event::MouseScrollDelta::LineDelta(_, vertical) => vertical,
winit::event::MouseScrollDelta::PixelDelta(pos) => {
pos.y as f32 / 20.0
}
};
let state_mut = state.as_mut().unwrap();
let wgpu_context_ref = wgpu_context.as_ref().unwrap();
// (7b)
state_mut.zoom(change);
wgpu_context_ref.window.request_redraw();
}
WindowEvent::Resized(new_size) => {
let wgpu_context_mut = wgpu_context.as_mut().unwrap();
wgpu_context_mut.resize(new_size);
wgpu_context_mut.window.request_redraw();
}
WindowEvent::RedrawRequested => {
let wgpu_context_ref = wgpu_context.as_ref().unwrap();
let state_ref = state.as_ref().unwrap();
match wgpu_context_ref.surface.get_current_texture() {
Ok(frame) => {
let view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
// (8)
wgpu_context_ref.queue.write_buffer(
&wgpu_context_ref.uniform_buffer,
0,
&state_ref.as_wgsl_bytes().expect(
"Error in encase translating AppState struct to WGSL bytes."
),
);
let mut encoder =
wgpu_context_ref.device.create_command_encoder(
&wgpu::CommandEncoderDescriptor { label: None },
);
{
let mut render_pass = encoder.begin_render_pass(
&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(
wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(
wgpu::Color::GREEN,
),
store: wgpu::StoreOp::Store,
},
},
)],
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
multiview_mask: None,
},
);
render_pass.set_pipeline(&wgpu_context_ref.pipeline);
// (9)
render_pass.set_bind_group(
0,
Some(&wgpu_context_ref.bind_group),
&[],
);
render_pass.draw(0..3, 0..1);
}
wgpu_context_ref.queue.submit(Some(encoder.finish()));
window.pre_present_notify();
frame.present();
}
Err(SurfaceError::Timeout | SurfaceError::Occluded) => {
window.request_redraw(); // try again later
}
Err(err) => {
// TODO: reconfigure the surface instead
panic!("get_current_texture: {err}");
}
}
}
match event {
WindowEvent::CloseRequested => {
event_loop.exit();
}
WindowEvent::KeyboardInput {
event: KeyEvent {
logical_key, text, ..
},
..
} => {
if let Key::Named(key) = logical_key {
match key {
NamedKey::Escape => event_loop.exit(),
NamedKey::ArrowUp => shader_state.translate_view(1, 1),
NamedKey::ArrowDown => shader_state.translate_view(-1, 1),
NamedKey::ArrowLeft => shader_state.translate_view(-1, 0),
NamedKey::ArrowRight => shader_state.translate_view(1, 0),
_ => {}
}
}
_ => {}
if let Some(text) = text {
if text == "u" {
shader_state.max_iterations += 3;
} else if text == "d" {
shader_state.max_iterations = shader_state.max_iterations.saturating_sub(3);
}
};
if let Some(window) = &self.window {
window.request_redraw();
}
}
})
.unwrap();
WindowEvent::MouseWheel { delta, .. } => {
let change = match delta {
winit::event::MouseScrollDelta::LineDelta(_, vertical) => vertical,
winit::event::MouseScrollDelta::PixelDelta(pos) => pos.y as f32 / 20.0,
};
// (7b)
shader_state.zoom(change);
if let Some(window) = &self.window {
window.request_redraw();
}
}
WindowEvent::Resized(new_size) => {
wgpu_ctx.resize(new_size);
if let Some(window) = &self.window {
window.request_redraw();
}
}
WindowEvent::RedrawRequested => {
match wgpu_ctx.surface.get_current_texture() {
Ok(frame) => {
let view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
// (8)
wgpu_ctx.queue.write_buffer(
&wgpu_ctx.uniform_buffer,
0,
&shader_state.as_wgsl_bytes().expect(
"Error in encase translating ShaderState \
struct to WGSL bytes.",
),
);
let mut encoder = wgpu_ctx.device.create_command_encoder(
&wgpu::CommandEncoderDescriptor { label: None },
);
{
let mut render_pass =
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::GREEN),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
multiview_mask: None,
});
render_pass.set_pipeline(&wgpu_ctx.pipeline);
// (9)
render_pass.set_bind_group(0, Some(&wgpu_ctx.bind_group), &[]);
render_pass.draw(0..3, 0..1);
}
wgpu_ctx.queue.submit(Some(encoder.finish()));
if let Some(window) = &self.window {
window.pre_present_notify();
}
frame.present();
}
Err(SurfaceError::Timeout | SurfaceError::Occluded) => {
if let Some(window) = &self.window {
window.request_redraw();
}
}
Err(err) => {
// TODO: reconfigure the surface instead
panic!("get_current_texture: {err}");
}
}
}
WindowEvent::Occluded(is_occluded) => {
if !is_occluded {
if let Some(window) = &self.window {
window.request_redraw();
}
}
}
_ => {}
}
}
}
pub fn main() {
let event_loop = EventLoop::new().unwrap();
#[cfg_attr(
not(target_arch = "wasm32"),
expect(unused_mut, reason = "`wasm32` re-assigns to specify canvas")
)]
let mut builder = winit::window::WindowBuilder::new()
.with_title("Remember: Use U/D to change sample count!")
.with_inner_size(winit::dpi::LogicalSize::new(900, 900));
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowBuilderExtWebSys;
let canvas = web_sys::window()
.unwrap()
.document()
.unwrap()
.get_element_by_id("canvas")
.unwrap()
.dyn_into::<web_sys::HtmlCanvasElement>()
.unwrap();
builder = builder.with_canvas(Some(canvas));
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
console_log::init().expect("could not initialize logger");
} else {
env_logger::builder().format_timestamp_nanos().init();
}
}
let window = builder.build(&event_loop).unwrap();
let window = Arc::new(window);
#[cfg(not(target_arch = "wasm32"))]
{
env_logger::builder().format_timestamp_nanos().init();
pollster::block_on(run(event_loop, window));
}
#[cfg(target_arch = "wasm32")]
{
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
console_log::init().expect("could not initialize logger");
let event_loop = EventLoop::with_user_event().build().unwrap();
let document = web_sys::window()
.and_then(|win| win.document())
.expect("Failed to get document.");
let body = document.body().unwrap();
let controls_text = document
.create_element("p")
.expect("Failed to create controls text as element.");
controls_text.set_inner_html(
"Controls: <br/>
#[cfg_attr(target_arch = "wasm32", expect(unused_mut))]
let mut app = App::new(&event_loop);
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
use winit::platform::web::EventLoopExtWebSys;
let document = web_sys::window()
.and_then(|win| win.document())
.expect("Failed to get document.");
let body = document.body().unwrap();
let controls_text = document
.create_element("p")
.expect("Failed to create controls text as element.");
controls_text.set_inner_html(
"Controls: <br/>
Up, Down, Left, Right: Move view, <br/>
Scroll: Zoom, <br/>
U, D: Increase / decrease sample count.",
);
body.append_child(&controls_text)
.expect("Failed to append controls text to body.");
);
body.append_child(&controls_text)
.expect("Failed to append controls text to body.");
wasm_bindgen_futures::spawn_local(run(event_loop, window));
event_loop.spawn_app(app);
} else {
event_loop.run_app(&mut app).unwrap();
}
}
}
+144 -110
View File
@@ -20,10 +20,11 @@ fn main() {
use raw_window_handle::HasWindowHandle;
#[cfg(feature = "winit")]
use winit::{
event::KeyEvent,
event_loop::EventLoop,
application::ApplicationHandler,
event::{ElementState, KeyEvent, WindowEvent},
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
keyboard::{Key, NamedKey},
window::WindowBuilder,
window::Window,
};
env_logger::init();
@@ -62,28 +63,14 @@ fn main() {
log::info!("Creating a window");
EventLoop::new().unwrap()
};
#[cfg(feature = "winit")]
let window = Arc::new(
WindowBuilder::new()
.with_title("wgpu player")
.with_resizable(true)
.build(&event_loop)
.unwrap(),
);
let instance_desc = wgt::InstanceDescriptor::new_without_display_handle_from_env();
#[cfg(feature = "winit")]
// TODO: Use event_loop.owned_display_handle() with winit 0.30
let instance_desc = instance_desc.with_display_handle(Box::new(window.clone()));
let instance_desc =
instance_desc.with_display_handle(Box::new(event_loop.owned_display_handle()));
let instance_flags = instance_desc.flags;
let instance = wgc::instance::Instance::new("player", instance_desc, None);
#[cfg(feature = "winit")]
let surface =
unsafe { instance.create_surface(None, window.window_handle().unwrap().into()) }.unwrap();
#[cfg(feature = "winit")]
let mut configured_surface_id = None;
let (backends, device_desc) =
match actions.pop_if(|action| matches!(action, trace::Action::Init { .. })) {
Some(trace::Action::Init { desc, backend }) => {
@@ -98,9 +85,6 @@ fn main() {
instance
.request_adapter(
&wgt::RequestAdapterOptions {
#[cfg(feature = "winit")]
compatible_surface: Some(&surface),
#[cfg(not(feature = "winit"))]
compatible_surface: None,
..Default::default()
},
@@ -132,107 +116,157 @@ fn main() {
}
#[cfg(feature = "winit")]
{
use winit::{
event::{ElementState, Event, WindowEvent},
event_loop::ControlFlow,
};
struct App<'a> {
window: Option<Arc<Window>>,
surface: Option<wgc::instance::Surface>,
configured_surface_id: Option<wgc::id::PointerId<wgc::id::markers::Surface>>,
instance: &'a wgc::instance::Instance,
device: &'a Arc<wgc::device::Device>,
queue: &'a Arc<wgc::device::queue::Queue>,
player: &'a mut Player,
actions: &'a mut Vec<trace::Action<'a, PointerReferences>>,
dir: &'a Path,
resize_config: Option<wgt::SurfaceConfiguration<Vec<wgt::TextureFormat>>>,
frame_count: usize,
done: bool,
}
let mut resize_config = None;
let mut frame_count = 0;
let mut done = false;
event_loop
.run(move |event, target| {
target.set_control_flow(ControlFlow::Poll);
impl ApplicationHandler for App<'_> {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.window.is_some() {
return;
}
let window = Arc::new(
event_loop
.create_window(
Window::default_attributes()
.with_title("wgpu player")
.with_resizable(true),
)
.unwrap(),
);
let surface = unsafe {
self.instance
.create_surface(None, window.window_handle().unwrap().into())
}
.unwrap();
self.window = Some(window);
self.surface = Some(surface);
}
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
log::info!("Closing");
self.device
.poll(wgt::PollType::wait_indefinitely())
.unwrap();
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
event_loop.set_control_flow(ControlFlow::Poll);
let window = self.window.as_ref().unwrap();
let surface = self.surface.as_ref().unwrap();
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::RedrawRequested if resize_config.is_none() => loop {
match actions.pop() {
Some(trace::Action::ConfigureSurface(surface_id, config)) => {
log::info!("Configuring the surface");
let current_size: (u32, u32) = window.inner_size().into();
let size = (config.width, config.height);
if current_size != size {
let _ = window.request_inner_size(
winit::dpi::PhysicalSize::new(
config.width,
config.height,
),
);
resize_config = Some(config);
break;
} else {
let error = device.configure_surface(&surface, &config);
configured_surface_id = Some(surface_id);
if let Some(e) = error {
panic!("{e:?}");
}
WindowEvent::RedrawRequested if self.resize_config.is_none() => loop {
match self.actions.pop() {
Some(trace::Action::ConfigureSurface(surface_id, config)) => {
log::info!("Configuring the surface");
let current_size: (u32, u32) = window.inner_size().into();
let size = (config.width, config.height);
if current_size != size {
let _ = window.request_inner_size(
winit::dpi::PhysicalSize::new(config.width, config.height),
);
self.resize_config = Some(config);
break;
} else {
let error = self.device.configure_surface(surface, &config);
self.configured_surface_id = Some(surface_id);
if let Some(e) = error {
panic!("{e:?}");
}
}
Some(trace::Action::GetSurfaceTexture { id, parent }) => {
log::debug!("Get surface texture for frame {frame_count}");
assert!(
configured_surface_id == Some(parent),
"rendering to an unexpected surface"
);
player.get_surface_texture(id, &surface);
}
Some(trace::Action::Present(_id)) => {
frame_count += 1;
log::debug!("Presenting frame {frame_count}");
surface.present().unwrap();
break;
}
Some(trace::Action::DiscardSurfaceTexture(_id)) => {
log::debug!("Discarding frame {frame_count}");
surface.discard().unwrap();
break;
}
Some(action) => {
player.process(
&device,
&queue,
action,
trace::DiskTraceLoader::new(&dir),
);
}
None => {
if !done {
println!("Finished the end at frame {frame_count}");
done = true;
}
break;
}
}
},
WindowEvent::Resized(_) => {
if let Some(config) = resize_config.take() {
let error = device.configure_surface(&surface, &config);
if let Some(e) = error {
panic!("{e:?}");
Some(trace::Action::GetSurfaceTexture { id, parent }) => {
log::debug!("Get surface texture for frame {}", self.frame_count);
assert!(
self.configured_surface_id == Some(parent),
"rendering to an unexpected surface"
);
self.player.get_surface_texture(id, surface);
}
Some(trace::Action::Present(_id)) => {
self.frame_count += 1;
log::debug!("Presenting frame {}", self.frame_count);
surface.present().unwrap();
break;
}
Some(trace::Action::DiscardSurfaceTexture(_id)) => {
log::debug!("Discarding frame {}", self.frame_count);
surface.discard().unwrap();
break;
}
Some(action) => {
self.player.process(
self.device,
self.queue,
action,
trace::DiskTraceLoader::new(self.dir),
);
}
None => {
if !self.done {
println!("Finished the end at frame {}", self.frame_count);
self.done = true;
}
break;
}
}
WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: Key::Named(NamedKey::Escape),
state: ElementState::Pressed,
..
},
..
}
| WindowEvent::CloseRequested => target.exit(),
_ => {}
},
Event::LoopExiting => {
log::info!("Closing");
device.poll(wgt::PollType::wait_indefinitely()).unwrap();
WindowEvent::Resized(_) => {
if let Some(config) = self.resize_config.take() {
let error = self.device.configure_surface(surface, &config);
if let Some(e) = error {
panic!("{e:?}");
}
}
}
WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: Key::Named(NamedKey::Escape),
state: ElementState::Pressed,
..
},
..
}
| WindowEvent::CloseRequested => event_loop.exit(),
_ => {}
}
})
.unwrap();
}
}
let mut app = App {
window: None,
surface: None,
configured_surface_id: None,
instance: &instance,
device: &device,
queue: &queue,
player: &mut player,
actions: &mut actions,
dir: &dir,
resize_config: None,
frame_count: 0,
done: false,
};
event_loop.run_app(&mut app).unwrap();
}
}
+1 -4
View File
@@ -346,9 +346,6 @@ naga = { workspace = true, features = ["wgsl-in", "termcolor"] }
winit.workspace = true # for "halmark" example
### Platform: Windows + MacOS + Linux for "raw-gles" example ###
[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos")))'.dev-dependencies]
[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies]
glutin-winit = { workspace = true, features = ["egl", "wgl", "wayland", "x11"] }
glutin = { workspace = true, features = ["egl", "wgl", "wayland", "x11"] }
# temporary compatibility for glutin-winit
rwh_05.workspace = true
winit = { workspace = true, features = ["rwh_05"] }
+83 -61
View File
@@ -7,9 +7,11 @@ use hal::{
};
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use winit::{
event::{ElementState, Event, KeyEvent, WindowEvent},
event_loop::ControlFlow,
application::ApplicationHandler,
event::{ElementState, KeyEvent, WindowEvent},
event_loop::{ActiveEventLoop, ControlFlow},
keyboard::{Key, NamedKey},
window::Window,
};
use std::{
@@ -830,67 +832,87 @@ cfg_if::cfg_if! {
}
}
struct App {
example: Option<Example<Api>>,
window: Option<Window>,
last_frame_inst: Instant,
frame_count: u32,
accum_time: f32,
}
impl ApplicationHandler for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.window.is_some() {
return;
}
let window = event_loop
.create_window(Window::default_attributes().with_title("hal-bunnymark"))
.unwrap();
let example = Example::<Api>::init(&window).expect("Selected backend is not supported");
self.window = Some(window);
self.example = Some(example);
println!("Press space to spawn bunnies.");
self.window.as_ref().unwrap().request_redraw();
}
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
self.example.take().unwrap().exit();
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
event_loop.set_control_flow(ControlFlow::Poll);
match event {
WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: Key::Named(NamedKey::Escape),
state: ElementState::Pressed,
..
},
..
}
| WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::RedrawRequested => {
let ex = self.example.as_mut().unwrap();
{
self.accum_time += self.last_frame_inst.elapsed().as_secs_f32();
self.last_frame_inst = Instant::now();
self.frame_count += 1;
if self.frame_count == 100 && !ex.is_empty() {
println!(
"Avg frame time {}ms",
self.accum_time * 1000.0 / self.frame_count as f32
);
self.accum_time = 0.0;
self.frame_count = 0;
}
}
ex.render();
self.window.as_ref().unwrap().request_redraw();
}
_ => {
self.example.as_mut().unwrap().update(event);
}
}
}
}
fn main() {
env_logger::init();
let event_loop = winit::event_loop::EventLoop::new().unwrap();
let window = winit::window::WindowBuilder::new()
.with_title("hal-bunnymark")
.build(&event_loop)
.unwrap();
let example_result = Example::<Api>::init(&window);
let mut example = Some(example_result.expect("Selected backend is not supported"));
println!("Press space to spawn bunnies.");
let mut last_frame_inst = Instant::now();
let (mut frame_count, mut accum_time) = (0, 0.0);
event_loop
.run(move |event, target| {
let _ = &window; // force ownership by the closure
target.set_control_flow(ControlFlow::Poll);
match event {
Event::LoopExiting => {
example.take().unwrap().exit();
}
Event::WindowEvent { event, .. } => match event {
WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: Key::Named(NamedKey::Escape),
state: ElementState::Pressed,
..
},
..
}
| WindowEvent::CloseRequested => target.exit(),
WindowEvent::RedrawRequested => {
let ex = example.as_mut().unwrap();
{
accum_time += last_frame_inst.elapsed().as_secs_f32();
last_frame_inst = Instant::now();
frame_count += 1;
if frame_count == 100 && !ex.is_empty() {
println!(
"Avg frame time {}ms",
accum_time * 1000.0 / frame_count as f32
);
accum_time = 0.0;
frame_count = 0;
}
}
ex.render();
window.request_redraw();
}
_ => {
example.as_mut().unwrap().update(event);
}
},
_ => {}
}
})
.unwrap();
let mut app = App {
example: None,
window: None,
last_frame_inst: Instant::now(),
frame_count: 0,
accum_time: 0.0,
};
event_loop.run_app(&mut app).unwrap();
}
+189 -136
View File
@@ -10,9 +10,14 @@
extern crate wgpu_hal as hal;
#[cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos")))]
#[cfg(not(any(
target_arch = "wasm32",
target_os = "ios",
target_os = "visionos",
target_env = "ohos"
)))]
fn main() {
use std::{ffi::CString, num::NonZeroU32};
use std::ffi::CString;
use glutin::{
config::GlConfig as _,
@@ -21,28 +26,21 @@ fn main() {
surface::GlSurface as _,
};
use glutin_winit::GlWindow as _;
use rwh_05::HasRawWindowHandle as _;
use raw_window_handle::HasWindowHandle as _;
use winit::{
application::ApplicationHandler,
event::{KeyEvent, WindowEvent},
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
keyboard::{Key, NamedKey},
window::Window,
};
env_logger::init();
println!("Initializing external GL context");
let event_loop = winit::event_loop::EventLoop::new().unwrap();
// Only Windows requires the window to be present before creating the display.
// Other platforms don't really need one.
let window_builder = cfg!(windows).then(|| {
winit::window::WindowBuilder::new()
.with_title("wgpu raw GLES example (press Escape to exit)")
});
// The template will match only the configurations supporting rendering
// to Windows.
let template = glutin::config::ConfigTemplateBuilder::new();
let display_builder = glutin_winit::DisplayBuilder::new().with_window_builder(window_builder);
// Find the config with the maximum number of samples, so our triangle will be
// smooth.
pub fn gl_config_picker(
/// Find the config with the maximum number of samples, so our triangle will be
/// smooth.
fn gl_config_picker(
configs: Box<dyn Iterator<Item = glutin::config::Config> + '_>,
) -> glutin::config::Config {
configs
@@ -56,140 +54,141 @@ fn main() {
.expect("Failed to find a matching config")
}
let (mut window, gl_config) = display_builder
.build(&event_loop, template, gl_config_picker)
.expect("Failed to build window and config from display");
struct App {
gl_config: Option<glutin::config::Config>,
not_current_gl_context: Option<glutin::context::NotCurrentContext>,
state: Option<(
glutin::context::PossiblyCurrentContext,
glutin::surface::Surface<glutin::surface::WindowSurface>,
Window,
)>,
exposed: Option<hal::ExposedAdapter<hal::api::Gles>>,
}
println!("Picked a config with {} samples", gl_config.num_samples());
impl App {
fn new() -> Self {
Self {
gl_config: None,
not_current_gl_context: None,
state: None,
exposed: None,
}
}
}
let raw_window_handle = window.as_ref().map(|window| window.raw_window_handle());
impl ApplicationHandler for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
// First call: create display, pick config, create GL context.
if self.gl_config.is_none() {
// Only Windows requires the window to be present before creating the display.
// Other platforms don't really need one.
let window_attributes = cfg!(windows).then(|| {
Window::default_attributes()
.with_title("wgpu raw GLES example (press Escape to exit)")
});
// XXX The display could be obtained from any object created by it, so we can
// query it from the config.
let gl_display = gl_config.display();
let template = glutin::config::ConfigTemplateBuilder::new();
// Glutin tries to create an OpenGL context by default. Force it to use any version of GLES.
let context_attributes = glutin::context::ContextAttributesBuilder::new()
// wgpu expects GLES 3.0+.
.with_context_api(glutin::context::ContextApi::Gles(Some(Version::new(3, 0))))
.build(raw_window_handle);
let display_builder =
glutin_winit::DisplayBuilder::new().with_window_attributes(window_attributes);
let mut not_current_gl_context = Some(unsafe {
gl_display
.create_context(&gl_config, &context_attributes)
.expect("failed to create context")
});
let (window, gl_config) = display_builder
.build(event_loop, template, gl_config_picker)
.expect("Failed to build window and config from display");
let mut state = None;
println!("Picked a config with {} samples", gl_config.num_samples());
// Only needs to be loaded once
let mut exposed = None;
let raw_window_handle = window
.as_ref()
.and_then(|window| window.window_handle().ok())
.map(|handle| handle.as_raw());
event_loop
.run(move |event, window_target| {
use winit::{
event::{Event, KeyEvent, WindowEvent},
event_loop::ControlFlow,
keyboard::{Key, NamedKey},
};
window_target.set_control_flow(ControlFlow::Wait);
let gl_display = gl_config.display();
// Glutin tries to create an OpenGL context by default.
// Force it to use any version of GLES.
let context_attributes = glutin::context::ContextAttributesBuilder::new()
// wgpu expects GLES 3.0+.
.with_context_api(glutin::context::ContextApi::Gles(Some(Version::new(3, 0))))
.build(raw_window_handle);
let gl_context = unsafe {
gl_display
.create_context(&gl_config, &context_attributes)
.expect("failed to create context")
};
self.not_current_gl_context = Some(gl_context);
self.gl_config = Some(gl_config);
// On Windows, the window was already created by DisplayBuilder.
if let Some(window) = window {
self.create_surface(event_loop, window);
return;
}
}
// Create window + surface (non-Windows first call, or Android re-resume).
if self.state.is_none() {
let gl_config = self.gl_config.as_ref().unwrap();
let window = glutin_winit::finalize_window(
event_loop,
Window::default_attributes()
.with_title("wgpu raw GLES example (press Escape to exit)"),
gl_config,
)
.unwrap();
self.create_surface(event_loop, window);
}
}
fn suspended(&mut self, _event_loop: &ActiveEventLoop) {
// This event is only raised on Android, where the backing NativeWindow for a GL
// Surface can appear and disappear at any moment.
println!("Android window removed");
// Destroy the GL Surface and un-current the GL Context before ndk-glue releases
// the window back to the system.
if let Some((gl_context, ..)) = self.state.take() {
assert!(self
.not_current_gl_context
.replace(gl_context.make_not_current().unwrap())
.is_none());
}
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
event_loop.set_control_flow(ControlFlow::Wait);
match event {
// Event::LoopExiting => (),
Event::WindowEvent {
window_id: _,
WindowEvent::CloseRequested
| WindowEvent::KeyboardInput {
event:
WindowEvent::CloseRequested
| WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: Key::Named(NamedKey::Escape),
..
},
KeyEvent {
logical_key: Key::Named(NamedKey::Escape),
..
},
} => window_target.exit(),
Event::Resumed => {
let window = window.take().unwrap_or_else(|| {
let window_builder = winit::window::WindowBuilder::new()
.with_title("wgpu raw GLES example (press Escape to exit)");
glutin_winit::finalize_window(window_target, window_builder, &gl_config)
.unwrap()
});
let attrs = window.build_surface_attributes(Default::default());
let gl_surface = unsafe {
gl_config
.display()
.create_window_surface(&gl_config, &attrs)
.expect("Cannot create GL WindowSurface")
};
// Make it current.
let gl_context = not_current_gl_context
.take()
.unwrap()
.make_current(&gl_surface)
.expect("GL context cannot be made current with WindowSurface");
// The context needs to be current for the Renderer to set up shaders and
// buffers. It also performs function loading, which needs a current context on
// WGL.
println!("Hooking up to wgpu-hal");
exposed.get_or_insert_with(|| {
unsafe {
<hal::api::Gles as hal::Api>::Adapter::new_external(
|name| {
// XXX: On WGL this should only be called after the context was made current
gl_config
.display()
.get_proc_address(&CString::new(name).expect(name))
},
wgpu_types::GlBackendOptions::default(),
)
}
.expect("GL adapter can't be initialized")
});
assert!(state.replace((gl_context, gl_surface, window)).is_none());
}
Event::Suspended => {
// This event is only raised on Android, where the backing NativeWindow for a GL
// Surface can appear and disappear at any moment.
println!("Android window removed");
// Destroy the GL Surface and un-current the GL Context before ndk-glue releases
// the window back to the system.
let (gl_context, ..) = state.take().unwrap();
assert!(not_current_gl_context
.replace(gl_context.make_not_current().unwrap())
.is_none());
}
Event::WindowEvent {
window_id: _,
event: WindowEvent::Resized(size),
} => {
..
} => event_loop.exit(),
WindowEvent::Resized(size) => {
if size.width != 0 && size.height != 0 {
// Some platforms like EGL require resizing GL surface to update the size
// Some platforms like EGL require resizing GL surface to update the size.
// Notable platforms here are Wayland and macOS, other don't require it
// and the function is no-op, but it's wise to resize it for portability
// reasons.
if let Some((gl_context, gl_surface, _)) = &state {
gl_surface.resize(
gl_context,
NonZeroU32::new(size.width).unwrap(),
NonZeroU32::new(size.height).unwrap(),
);
// XXX: If there's a state for fill_screen(), this would need to be updated too.
if let Some((gl_context, gl_surface, window)) = &self.state {
window.resize_surface(gl_surface, gl_context);
}
}
}
Event::WindowEvent {
window_id: _,
event: WindowEvent::RedrawRequested,
} => {
WindowEvent::RedrawRequested => {
if let (Some(exposed), Some((gl_context, gl_surface, window))) =
(&exposed, &state)
(&self.exposed, &self.state)
{
let inner_size = window.inner_size();
@@ -203,7 +202,60 @@ fn main() {
}
_ => (),
}
})
}
}
impl App {
fn create_surface(&mut self, _event_loop: &ActiveEventLoop, window: Window) {
let gl_config = self.gl_config.as_ref().unwrap();
let attrs = window
.build_surface_attributes(Default::default())
.expect("Failed to build surface attributes");
let gl_surface = unsafe {
gl_config
.display()
.create_window_surface(gl_config, &attrs)
.expect("Cannot create GL WindowSurface")
};
// Make it current.
let gl_context = self
.not_current_gl_context
.take()
.unwrap()
.make_current(&gl_surface)
.expect("GL context cannot be made current with WindowSurface");
// The context needs to be current for the Renderer to set up shaders and
// buffers. It also performs function loading, which needs a current context on
// WGL.
println!("Hooking up to wgpu-hal");
self.exposed.get_or_insert_with(|| {
unsafe {
<hal::api::Gles as hal::Api>::Adapter::new_external(
|name| {
// XXX: On WGL this should only be called after the context was
// made current
gl_config
.display()
.get_proc_address(&CString::new(name).expect(name))
},
wgpu_types::GlBackendOptions::default(),
)
}
.expect("GL adapter can't be initialized")
});
window.request_redraw();
self.state = Some((gl_context, gl_surface, window));
}
}
let event_loop = EventLoop::new().unwrap();
let mut app = App::new();
event_loop
.run_app(&mut app)
.expect("Couldn't run event loop");
}
@@ -260,10 +312,11 @@ fn main() {
#[cfg(any(
all(target_arch = "wasm32", not(target_os = "emscripten")),
target_os = "ios",
target_os = "visionos"
target_os = "visionos",
target_env = "ohos"
))]
fn main() {
eprintln!("This example is not supported on Windows and non-emscripten wasm32")
eprintln!("This example is not supported on this platform")
}
#[cfg(not(any(
+76 -50
View File
@@ -12,7 +12,11 @@ use std::{
time::Instant,
};
use wgpu_types::Dx12BackendOptions;
use winit::window::WindowButtons;
use winit::{
application::ApplicationHandler,
event_loop::{ActiveEventLoop, ControlFlow},
window::{Window, WindowButtons},
};
const DESIRED_MAX_LATENCY: u32 = 2;
@@ -1141,57 +1145,79 @@ cfg_if::cfg_if! {
}
}
struct App {
example: Option<Example<Api>>,
window: Option<Window>,
}
impl ApplicationHandler for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.window.is_some() {
return;
}
let window = event_loop
.create_window(
Window::default_attributes()
.with_title("hal-ray-traced-triangle")
.with_inner_size(winit::dpi::PhysicalSize {
width: 512,
height: 512,
})
.with_resizable(false)
.with_enabled_buttons(WindowButtons::CLOSE),
)
.unwrap();
let example = Example::<Api>::init(&window).expect("Selected backend is not supported");
self.window = Some(window);
self.example = Some(example);
}
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
self.example.take().unwrap().exit();
}
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
if let Some(window) = &self.window {
window.request_redraw();
}
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: winit::window::WindowId,
event: winit::event::WindowEvent,
) {
event_loop.set_control_flow(ControlFlow::Poll);
match event {
winit::event::WindowEvent::CloseRequested => {
event_loop.exit();
}
winit::event::WindowEvent::KeyboardInput { event, .. }
if event.physical_key
== winit::keyboard::PhysicalKey::Code(winit::keyboard::KeyCode::Escape) =>
{
event_loop.exit();
}
winit::event::WindowEvent::RedrawRequested => {
let ex = self.example.as_mut().unwrap();
ex.render();
}
_ => {
self.example.as_mut().unwrap().update(event);
}
}
}
}
fn main() {
env_logger::init();
let event_loop = winit::event_loop::EventLoop::new().unwrap();
let window = winit::window::WindowBuilder::new()
.with_title("hal-ray-traced-triangle")
.with_inner_size(winit::dpi::PhysicalSize {
width: 512,
height: 512,
})
.with_resizable(false)
.with_enabled_buttons(WindowButtons::CLOSE)
.build(&event_loop)
.unwrap();
let example_result = Example::<Api>::init(&window);
let mut example = Some(example_result.expect("Selected backend is not supported"));
event_loop
.run(move |event, target| {
let _ = &window; // force ownership by the closure
target.set_control_flow(winit::event_loop::ControlFlow::Poll);
match event {
winit::event::Event::WindowEvent { event, .. } => match event {
winit::event::WindowEvent::CloseRequested => {
target.exit();
}
winit::event::WindowEvent::KeyboardInput { event, .. }
if event.physical_key
== winit::keyboard::PhysicalKey::Code(
winit::keyboard::KeyCode::Escape,
) =>
{
target.exit();
}
winit::event::WindowEvent::RedrawRequested => {
let ex = example.as_mut().unwrap();
ex.render();
}
_ => {
example.as_mut().unwrap().update(event);
}
},
winit::event::Event::LoopExiting => {
example.take().unwrap().exit();
}
winit::event::Event::AboutToWait => {
window.request_redraw();
}
_ => {}
}
})
.unwrap();
let mut app = App {
example: None,
window: None,
};
event_loop.run_app(&mut app).unwrap();
}