mirror of
https://github.com/storytold/wgpu.git
synced 2026-11-19 22:11:01 +01:00
Use objc2-metal with metal naming scheme
To keep the diff smaller and easier to review, this uses a temporary fork of `objc2-metal` and `objc2-quartz-core` whose methods use the naming scheme of the `metal` crate. One particular difficult part with this is that the `metal` crate has several methods where the order of the arguments are swapped relative to the corresponding Objective-C methods. This includes most perilously the following, since these have both an offset and an index argument, both of which are integers: - `set_bytes` - `set_vertex_bytes` - `set_fragment_bytes` - `set_buffer` - `set_vertex_buffer` - `set_fragment_buffer` - `set_threadgroup_memory_length` But also: - `set_vertex_texture` - `set_fragment_texture` - `set_sampler_state` - `set_vertex_sampler_state` - `set_fragment_sampler_state`
This commit is contained in:
1 parent
b042784fa2
commit
80871cfc01
11 files changed
+1188
-898
No files matched your search
@@ -53,6 +53,12 @@ Bottom level categories:
|
||||
|
||||
- Allow parsing shaders which make use of `SPV_KHR_non_semantic_info` for debug info. Also removes `naga::front::spv::SUPPORTED_EXT_SETS`. By @inner-daemons in #8827.
|
||||
|
||||
### Changes
|
||||
|
||||
#### Metal
|
||||
|
||||
- Use autogenerated `objc2` bindings internally, which should resolve a lot of leaks and unsoundness. By @madsmtm in [#5641](https://github.com/gfx-rs/wgpu/pull/5641).
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
#### General
|
||||
|
||||
Generated
+101
-87
@@ -400,12 +400,6 @@ dependencies = [
|
||||
"wyz",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
|
||||
|
||||
[[package]]
|
||||
name = "block-sys"
|
||||
version = "0.2.1"
|
||||
@@ -434,6 +428,14 @@ dependencies = [
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.6.2"
|
||||
source = "git+https://github.com/madsmtm/objc2?branch=metal-wgpu#363fb6f76a49db6f15c10c9f274ee7a2956483cf"
|
||||
dependencies = [
|
||||
"objc2 0.6.3 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "boxed_error"
|
||||
version = "0.2.3"
|
||||
@@ -792,16 +794,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
@@ -815,8 +807,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"core-foundation 0.9.4",
|
||||
"core-graphics-types 0.1.3",
|
||||
"core-foundation",
|
||||
"core-graphics-types",
|
||||
"foreign-types",
|
||||
"libc",
|
||||
]
|
||||
@@ -828,18 +820,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"core-foundation 0.9.4",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-graphics-types"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"core-foundation 0.10.1",
|
||||
"core-foundation",
|
||||
"libc",
|
||||
]
|
||||
|
||||
@@ -1196,7 +1177,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "89a09f22a6c6069a18470eb92d2298acf25463f14256d24778e1230d789a2aec"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"objc2 0.6.3",
|
||||
"objc2 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dispatch2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/madsmtm/objc2?branch=metal-wgpu#363fb6f76a49db6f15c10c9f274ee7a2956483cf"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"objc2 0.6.3 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1701,7 +1691,7 @@ dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"cfg_aliases 0.1.1",
|
||||
"cgl",
|
||||
"core-foundation 0.9.4",
|
||||
"core-foundation",
|
||||
"dispatch",
|
||||
"glutin_egl_sys",
|
||||
"glutin_wgl_sys 0.5.0",
|
||||
@@ -2304,15 +2294,6 @@ version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30"
|
||||
|
||||
[[package]]
|
||||
name = "malloc_buf"
|
||||
version = "0.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matchers"
|
||||
version = "0.2.0"
|
||||
@@ -2337,21 +2318,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "metal"
|
||||
version = "0.33.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7047791b5bc903b8cd963014b355f71dc9864a9a0b727057676c1dcae5cbc15"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"block",
|
||||
"core-graphics-types 0.2.0",
|
||||
"foreign-types",
|
||||
"log",
|
||||
"objc",
|
||||
"paste",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minicov"
|
||||
version = "0.3.8"
|
||||
@@ -2695,15 +2661,6 @@ version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "059c95245738cdc7b40078cdd51a23200252a4c0a0a6dd005136152b3f467a4a"
|
||||
|
||||
[[package]]
|
||||
name = "objc"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"
|
||||
dependencies = [
|
||||
"malloc_buf",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc-sys"
|
||||
version = "0.3.5"
|
||||
@@ -2727,7 +2684,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
|
||||
dependencies = [
|
||||
"objc-sys",
|
||||
"objc2-encode 4.1.0",
|
||||
"objc2-encode 4.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2736,7 +2693,15 @@ version = "0.6.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7c2599ce0ec54857b29ce62166b0ed9b4f6f1a70ccc9a71165b6154caca8c05"
|
||||
dependencies = [
|
||||
"objc2-encode 4.1.0",
|
||||
"objc2-encode 4.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.3"
|
||||
source = "git+https://github.com/madsmtm/objc2?branch=metal-wgpu#363fb6f76a49db6f15c10c9f274ee7a2956483cf"
|
||||
dependencies = [
|
||||
"objc2-encode 4.1.0 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2798,8 +2763,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"dispatch2",
|
||||
"objc2 0.6.3",
|
||||
"dispatch2 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"objc2 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-foundation"
|
||||
version = "0.3.2"
|
||||
source = "git+https://github.com/madsmtm/objc2?branch=metal-wgpu#363fb6f76a49db6f15c10c9f274ee7a2956483cf"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"dispatch2 0.3.0 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
"objc2 0.6.3 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2838,6 +2813,11 @@ version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
|
||||
|
||||
[[package]]
|
||||
name = "objc2-encode"
|
||||
version = "4.1.0"
|
||||
source = "git+https://github.com/madsmtm/objc2?branch=metal-wgpu#363fb6f76a49db6f15c10c9f274ee7a2956483cf"
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.2.2"
|
||||
@@ -2858,8 +2838,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"objc2 0.6.3",
|
||||
"objc2-core-foundation",
|
||||
"objc2 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"objc2-core-foundation 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.3.2"
|
||||
source = "git+https://github.com/madsmtm/objc2?branch=metal-wgpu#363fb6f76a49db6f15c10c9f274ee7a2956483cf"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"objc2 0.6.3 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2893,8 +2882,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"objc2 0.6.3",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"objc2-foundation 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-metal"
|
||||
version = "0.3.2"
|
||||
source = "git+https://github.com/madsmtm/objc2?branch=metal-wgpu#363fb6f76a49db6f15c10c9f274ee7a2956483cf"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.3 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
"objc2-foundation 0.3.2 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2917,10 +2917,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"objc2 0.6.3",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-metal 0.3.2",
|
||||
"objc2 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"objc2-core-foundation 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"objc2-foundation 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"objc2-metal 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-quartz-core"
|
||||
version = "0.3.2"
|
||||
source = "git+https://github.com/madsmtm/objc2?branch=metal-wgpu#363fb6f76a49db6f15c10c9f274ee7a2956483cf"
|
||||
dependencies = [
|
||||
"bitflags 2.10.0",
|
||||
"objc2 0.6.3 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
"objc2-core-foundation 0.3.2 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
"objc2-foundation 0.3.2 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
"objc2-metal 0.3.2 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3393,10 +3405,10 @@ version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135"
|
||||
dependencies = [
|
||||
"objc2 0.6.3",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-quartz-core 0.3.2",
|
||||
"objc2 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"objc2-core-foundation 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"objc2-foundation 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"objc2-quartz-core 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4921,11 +4933,10 @@ dependencies = [
|
||||
"ash",
|
||||
"bit-set",
|
||||
"bitflags 2.10.0",
|
||||
"block",
|
||||
"block2 0.6.2",
|
||||
"bytemuck",
|
||||
"cfg-if",
|
||||
"cfg_aliases 0.2.1",
|
||||
"core-graphics-types 0.2.0",
|
||||
"env_logger",
|
||||
"glam",
|
||||
"glow",
|
||||
@@ -4941,10 +4952,13 @@ dependencies = [
|
||||
"libloading",
|
||||
"log",
|
||||
"mach-dxcompiler-rs",
|
||||
"metal",
|
||||
"naga",
|
||||
"ndk-sys 0.6.0+11769913",
|
||||
"objc",
|
||||
"objc2 0.6.3 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
"objc2-core-foundation 0.3.2 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
"objc2-foundation 0.3.2 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
"objc2-metal 0.3.2 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
"objc2-quartz-core 0.3.2 (git+https://github.com/madsmtm/objc2?branch=metal-wgpu)",
|
||||
"once_cell",
|
||||
"ordered-float",
|
||||
"parking_lot",
|
||||
@@ -5534,7 +5548,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"calloop 0.12.4",
|
||||
"cfg_aliases 0.1.1",
|
||||
"core-foundation 0.9.4",
|
||||
"core-foundation",
|
||||
"core-graphics",
|
||||
"cursor-icon",
|
||||
"icrate",
|
||||
@@ -5585,7 +5599,7 @@ dependencies = [
|
||||
"calloop 0.13.0",
|
||||
"cfg_aliases 0.2.1",
|
||||
"concurrent-queue",
|
||||
"core-foundation 0.9.4",
|
||||
"core-foundation",
|
||||
"core-graphics",
|
||||
"cursor-icon",
|
||||
"dpi",
|
||||
|
||||
+53
-4
@@ -202,10 +202,59 @@ which = "8"
|
||||
xshell = "0.2.2"
|
||||
|
||||
# Metal dependencies
|
||||
metal = "0.33"
|
||||
block = "0.1.6"
|
||||
core-graphics-types = "0.2"
|
||||
objc = "0.2.5"
|
||||
block2 = { version = "0.6.2", git = "https://github.com/madsmtm/objc2", branch = "metal-wgpu" }
|
||||
objc2 = { version = "0.6.3", git = "https://github.com/madsmtm/objc2", branch = "metal-wgpu" }
|
||||
objc2-core-foundation = { version = "0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"CFCGTypes",
|
||||
], git = "https://github.com/madsmtm/objc2", branch = "metal-wgpu" }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"NSError",
|
||||
"NSProcessInfo",
|
||||
"NSRange",
|
||||
"NSString",
|
||||
], git = "https://github.com/madsmtm/objc2", branch = "metal-wgpu" }
|
||||
objc2-metal = { version = "0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"block2",
|
||||
"MTLAllocation",
|
||||
"MTLBlitCommandEncoder",
|
||||
"MTLBlitPass",
|
||||
"MTLBuffer",
|
||||
"MTLCaptureManager",
|
||||
"MTLCaptureScope",
|
||||
"MTLCommandBuffer",
|
||||
"MTLCommandEncoder",
|
||||
"MTLCommandQueue",
|
||||
"MTLComputeCommandEncoder",
|
||||
"MTLComputePass",
|
||||
"MTLComputePipeline",
|
||||
"MTLCounters",
|
||||
"MTLDepthStencil",
|
||||
"MTLDevice",
|
||||
"MTLDrawable",
|
||||
"MTLEvent",
|
||||
"MTLLibrary",
|
||||
"MTLPipeline",
|
||||
"MTLPixelFormat",
|
||||
"MTLRenderCommandEncoder",
|
||||
"MTLRenderPass",
|
||||
"MTLRenderPipeline",
|
||||
"MTLResource",
|
||||
"MTLSampler",
|
||||
"MTLStageInputOutputDescriptor",
|
||||
"MTLTexture",
|
||||
"MTLTypes",
|
||||
"MTLVertexDescriptor",
|
||||
], git = "https://github.com/madsmtm/objc2", branch = "metal-wgpu" }
|
||||
objc2-quartz-core = { version = "0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"objc2-core-foundation",
|
||||
"CALayer",
|
||||
"CAMetalLayer",
|
||||
"objc2-metal",
|
||||
], git = "https://github.com/madsmtm/objc2", branch = "metal-wgpu" }
|
||||
raw-window-metal = "1.0"
|
||||
|
||||
# Vulkan dependencies
|
||||
|
||||
+16
-13
@@ -18,10 +18,9 @@ rust-version = "1.82.0"
|
||||
[package.metadata.docs.rs]
|
||||
# Ideally we would enable all the features.
|
||||
#
|
||||
# However, the metal features fail to be documented because the docs.rs runner cross-compiling under
|
||||
# x86_64-unknown-linux-gnu and metal-rs cannot compile in that environment at the moment. The same applies
|
||||
# for the dx12 feature.
|
||||
features = ["vulkan", "gles", "renderdoc"]
|
||||
# However, the dx12 features fail to be documented because the docs.rs runner cross-compiling under
|
||||
# x86_64-unknown-linux-gnu cannot compile in that environment at the moment.
|
||||
features = ["metal", "vulkan", "gles", "renderdoc"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
targets = [
|
||||
"x86_64-unknown-linux-gnu",
|
||||
@@ -75,13 +74,15 @@ metal = [
|
||||
# Metal is only available on Apple platforms, therefore request MSL output also only if we target an Apple platform.
|
||||
"naga/msl-out",
|
||||
"dep:arrayvec",
|
||||
"dep:block",
|
||||
"dep:core-graphics-types",
|
||||
"dep:block2",
|
||||
"dep:hashbrown",
|
||||
"dep:libc",
|
||||
"dep:log",
|
||||
"dep:metal",
|
||||
"dep:objc",
|
||||
"dep:objc2",
|
||||
"dep:objc2-core-foundation",
|
||||
"dep:objc2-foundation",
|
||||
"dep:objc2-metal",
|
||||
"dep:objc2-quartz-core",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:smallvec",
|
||||
@@ -120,7 +121,7 @@ gles = [
|
||||
"dep:libloading",
|
||||
"dep:log",
|
||||
"dep:ndk-sys",
|
||||
"dep:objc",
|
||||
"dep:objc2",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:wasm-bindgen",
|
||||
@@ -281,10 +282,12 @@ mach-dxcompiler-rs = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||
# Backend: Metal
|
||||
block = { workspace = true, optional = true }
|
||||
core-graphics-types = { workspace = true, optional = true }
|
||||
metal = { workspace = true, optional = true }
|
||||
objc = { workspace = true, optional = true }
|
||||
block2 = { workspace = true, optional = true }
|
||||
objc2 = { workspace = true, optional = true }
|
||||
objc2-core-foundation = { workspace = true, optional = true }
|
||||
objc2-foundation = { workspace = true, optional = true }
|
||||
objc2-metal = { workspace = true, optional = true }
|
||||
objc2-quartz-core = { workspace = true, optional = true }
|
||||
|
||||
# backend: Metal + Vulkan
|
||||
raw-window-metal = { workspace = true, optional = true }
|
||||
|
||||
@@ -1253,10 +1253,11 @@ impl crate::Surface for Surface {
|
||||
let window_ptr = handle.ns_view.as_ptr();
|
||||
#[cfg(target_os = "macos")]
|
||||
let window_ptr = {
|
||||
use objc::{msg_send, runtime::Object, sel, sel_impl};
|
||||
use objc2::msg_send;
|
||||
use objc2::runtime::AnyObject;
|
||||
// ns_view always have a layer and don't need to verify that it exists.
|
||||
let layer: *mut Object =
|
||||
msg_send![handle.ns_view.as_ptr().cast::<Object>(), layer];
|
||||
let layer: *mut AnyObject =
|
||||
msg_send![handle.ns_view.as_ptr().cast::<AnyObject>(), layer];
|
||||
layer.cast::<ffi::c_void>()
|
||||
};
|
||||
window_ptr
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
use metal::{
|
||||
MTLArgumentBuffersTier, MTLCounterSamplingPoint, MTLFeatureSet, MTLGPUFamily,
|
||||
MTLLanguageVersion, MTLPixelFormat, MTLReadWriteTextureTier, NSInteger,
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2_foundation::{NSOperatingSystemVersion, NSProcessInfo};
|
||||
use objc2_metal::{
|
||||
MTLArgumentBuffersTier, MTLCounterSamplingPoint, MTLDevice, MTLFeatureSet, MTLGPUFamily,
|
||||
MTLLanguageVersion, MTLPixelFormat, MTLReadWriteTextureTier,
|
||||
};
|
||||
use objc::{class, msg_send, sel, sel_impl};
|
||||
use parking_lot::Mutex;
|
||||
use wgt::{AstcBlock, AstcChannel};
|
||||
|
||||
use alloc::{sync::Arc, vec::Vec};
|
||||
use alloc::{string::ToString as _, sync::Arc, vec::Vec};
|
||||
|
||||
use super::TimestampQuerySupport;
|
||||
|
||||
@@ -27,7 +28,7 @@ use super::TimestampQuerySupport;
|
||||
/// <https://bugzilla.mozilla.org/show_bug.cgi?id=1971452>.
|
||||
///
|
||||
/// [new command buffer]: https://developer.apple.com/documentation/metal/mtlcommandqueue/makecommandbuffer()?language=objc
|
||||
const MAX_COMMAND_BUFFERS: u64 = 4096;
|
||||
const MAX_COMMAND_BUFFERS: usize = 4096;
|
||||
|
||||
unsafe impl Send for super::Adapter {}
|
||||
unsafe impl Sync for super::Adapter {}
|
||||
@@ -50,7 +51,8 @@ impl crate::Adapter for super::Adapter {
|
||||
let queue = self
|
||||
.shared
|
||||
.device
|
||||
.new_command_queue_with_max_command_buffer_count(MAX_COMMAND_BUFFERS);
|
||||
.new_command_queue_with_max_command_buffer_count(MAX_COMMAND_BUFFERS)
|
||||
.unwrap();
|
||||
|
||||
// Acquiring the meaning of timestamp ticks is hard with Metal!
|
||||
// The only thing there is a method correlating cpu & gpu timestamps (`device.sample_timestamps`).
|
||||
@@ -71,7 +73,7 @@ impl crate::Adapter for super::Adapter {
|
||||
// Based on:
|
||||
// * https://github.com/gfx-rs/wgpu/pull/2528
|
||||
// * https://github.com/gpuweb/gpuweb/issues/1325#issuecomment-761041326
|
||||
let timestamp_period = if self.shared.device.name().starts_with("Intel") {
|
||||
let timestamp_period = if self.shared.device.name().to_string().starts_with("Intel") {
|
||||
83.333
|
||||
} else {
|
||||
// Known for Apple Silicon (at least M1 & M2, iPad Pro 2018) and AMD GPUs.
|
||||
@@ -106,6 +108,8 @@ impl crate::Adapter for super::Adapter {
|
||||
MTLReadWriteTextureTier::TierNone => (Tfc::empty(), Tfc::empty()),
|
||||
MTLReadWriteTextureTier::Tier1 => (Tfc::STORAGE_READ_WRITE, Tfc::empty()),
|
||||
MTLReadWriteTextureTier::Tier2 => (Tfc::STORAGE_READ_WRITE, Tfc::STORAGE_READ_WRITE),
|
||||
// Unknown levels of support are likely higher than Tier 2.
|
||||
_ => (Tfc::STORAGE_READ_WRITE, Tfc::STORAGE_READ_WRITE),
|
||||
};
|
||||
let msaa_count = pc.sample_count_mask;
|
||||
|
||||
@@ -128,7 +132,7 @@ impl crate::Adapter for super::Adapter {
|
||||
],
|
||||
);
|
||||
|
||||
let image_atomic_if = if pc.msl_version >= MTLLanguageVersion::V3_1 {
|
||||
let image_atomic_if = if pc.msl_version >= MTLLanguageVersion::Version3_1 {
|
||||
Tfc::STORAGE_ATOMIC
|
||||
} else {
|
||||
Tfc::empty()
|
||||
@@ -515,22 +519,18 @@ const DEPTH_CLIP_MODE: &[MTLFeatureSet] = &[
|
||||
MTLFeatureSet::macOS_GPUFamily1_v1,
|
||||
];
|
||||
|
||||
const OS_NOT_SUPPORT: (usize, usize) = (10000, 0);
|
||||
const OS_NOT_SUPPORT: (isize, isize) = (10000, 0);
|
||||
|
||||
impl super::PrivateCapabilities {
|
||||
fn supports_any(raw: &metal::DeviceRef, features_sets: &[MTLFeatureSet]) -> bool {
|
||||
fn supports_any(raw: &ProtocolObject<dyn MTLDevice>, features_sets: &[MTLFeatureSet]) -> bool {
|
||||
features_sets
|
||||
.iter()
|
||||
.cloned()
|
||||
.any(|x| raw.supports_feature_set(x))
|
||||
}
|
||||
|
||||
pub fn new(device: &metal::Device) -> Self {
|
||||
let version: NSOperatingSystemVersion = unsafe {
|
||||
let process_info: *mut objc::runtime::Object =
|
||||
msg_send![class!(NSProcessInfo), processInfo];
|
||||
msg_send![process_info, operatingSystemVersion]
|
||||
};
|
||||
pub fn new(device: &ProtocolObject<dyn MTLDevice>) -> Self {
|
||||
let version = NSProcessInfo::processInfo().operatingSystemVersion();
|
||||
|
||||
let os_type = super::OsType::new(version, device);
|
||||
let family_check = version.at_least((10, 15), (13, 0), (13, 0), (1, 0), os_type);
|
||||
@@ -588,7 +588,7 @@ impl super::PrivateCapabilities {
|
||||
.at_least((10, 13), (11, 0), (11, 0), (1, 0), os_type)
|
||||
.then(|| device.argument_buffers_support());
|
||||
|
||||
let is_virtual = device.name().to_lowercase().contains("virtual");
|
||||
let is_virtual = device.name().to_string().to_lowercase().contains("virtual");
|
||||
|
||||
let mesh_shaders = family_check
|
||||
&& (device.supports_family(MTLGPUFamily::Metal3)
|
||||
@@ -598,25 +598,25 @@ impl super::PrivateCapabilities {
|
||||
&& !is_virtual;
|
||||
|
||||
let msl_version = if version.at_least((14, 0), (17, 0), (17, 0), (1, 0), os_type) {
|
||||
MTLLanguageVersion::V3_1
|
||||
MTLLanguageVersion::Version3_1
|
||||
} else if version.at_least((13, 0), (16, 0), (16, 0), (1, 0), os_type) {
|
||||
MTLLanguageVersion::V3_0
|
||||
MTLLanguageVersion::Version3_0
|
||||
} else if version.at_least((12, 0), (15, 0), (15, 0), (1, 0), os_type) {
|
||||
MTLLanguageVersion::V2_4
|
||||
MTLLanguageVersion::Version2_4
|
||||
} else if version.at_least((11, 0), (14, 0), (14, 0), (1, 0), os_type) {
|
||||
MTLLanguageVersion::V2_3
|
||||
MTLLanguageVersion::Version2_3
|
||||
} else if version.at_least((10, 15), (13, 0), (13, 0), (1, 0), os_type) {
|
||||
MTLLanguageVersion::V2_2
|
||||
MTLLanguageVersion::Version2_2
|
||||
} else if version.at_least((10, 14), (12, 0), (12, 0), (1, 0), os_type) {
|
||||
MTLLanguageVersion::V2_1
|
||||
MTLLanguageVersion::Version2_1
|
||||
} else if version.at_least((10, 13), (11, 0), (11, 0), (1, 0), os_type) {
|
||||
MTLLanguageVersion::V2_0
|
||||
MTLLanguageVersion::Version2_0
|
||||
} else if version.at_least((10, 12), (10, 0), (10, 0), (1, 0), os_type) {
|
||||
MTLLanguageVersion::V1_2
|
||||
MTLLanguageVersion::Version1_2
|
||||
} else if version.at_least((10, 11), (9, 0), (9, 0), (1, 0), os_type) {
|
||||
MTLLanguageVersion::V1_1
|
||||
MTLLanguageVersion::Version1_1
|
||||
} else {
|
||||
MTLLanguageVersion::V1_0
|
||||
MTLLanguageVersion::Version1_0
|
||||
};
|
||||
|
||||
// The `PrivateCapabilities` we are constructing here duplicates many of the limits
|
||||
@@ -654,8 +654,9 @@ impl super::PrivateCapabilities {
|
||||
texture_cube_array: Self::supports_any(device, TEXTURE_CUBE_ARRAY_SUPPORT),
|
||||
supports_float_filtering: os_type == super::OsType::Macos
|
||||
|| (version.at_least((11, 0), (14, 0), (16, 0), (1, 0), os_type)
|
||||
&& device.supports_32bit_float_filtering()),
|
||||
format_depth24_stencil8: os_type == super::OsType::Macos && device.d24_s8_supported(),
|
||||
&& device.supports32_bit_float_filtering()),
|
||||
format_depth24_stencil8: os_type == super::OsType::Macos
|
||||
&& device.is_depth24_stencil8_pixel_format_supported(),
|
||||
format_depth32_stencil8_filter: os_type == super::OsType::Macos,
|
||||
format_depth32_stencil8_none: os_type != super::OsType::Macos,
|
||||
format_min_srgb_channels: if os_type == super::OsType::Macos {
|
||||
@@ -767,8 +768,7 @@ impl super::PrivateCapabilities {
|
||||
64
|
||||
},
|
||||
max_buffer_size: if version.at_least((10, 14), (12, 0), (12, 0), (1, 0), os_type) {
|
||||
let buffer_size: NSInteger = unsafe { msg_send![device.as_ref(), maxBufferLength] };
|
||||
buffer_size as _
|
||||
device.max_buffer_length() as u64
|
||||
} else if os_type == super::OsType::Macos {
|
||||
1 << 30 // 1GB on macOS 10.11 and up
|
||||
} else {
|
||||
@@ -1046,7 +1046,7 @@ impl super::PrivateCapabilities {
|
||||
);
|
||||
features.set(
|
||||
F::DUAL_SOURCE_BLENDING,
|
||||
self.msl_version >= MTLLanguageVersion::V1_2 && self.dual_source_blending,
|
||||
self.msl_version >= MTLLanguageVersion::Version1_2 && self.dual_source_blending,
|
||||
);
|
||||
features.set(F::TEXTURE_COMPRESSION_ASTC, self.format_astc);
|
||||
features.set(F::TEXTURE_COMPRESSION_ASTC_HDR, self.format_astc_hdr);
|
||||
@@ -1066,42 +1066,42 @@ impl super::PrivateCapabilities {
|
||||
| F::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
|
||||
| F::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING
|
||||
| F::PARTIALLY_BOUND_BINDING_ARRAY,
|
||||
self.msl_version >= MTLLanguageVersion::V3_0
|
||||
self.msl_version >= MTLLanguageVersion::Version3_0
|
||||
&& self.supports_arrays_of_textures
|
||||
&& self
|
||||
.argument_buffers
|
||||
.unwrap_or(MTLArgumentBuffersTier::Tier1) as u64
|
||||
>= MTLArgumentBuffersTier::Tier2 as u64,
|
||||
.unwrap_or(MTLArgumentBuffersTier::Tier1)
|
||||
>= MTLArgumentBuffersTier::Tier2,
|
||||
);
|
||||
features.set(
|
||||
F::STORAGE_RESOURCE_BINDING_ARRAY,
|
||||
self.msl_version >= MTLLanguageVersion::V3_0
|
||||
self.msl_version >= MTLLanguageVersion::Version3_0
|
||||
&& self.supports_arrays_of_textures
|
||||
&& self.supports_arrays_of_textures_write
|
||||
&& self
|
||||
.argument_buffers
|
||||
.unwrap_or(MTLArgumentBuffersTier::Tier1) as u64
|
||||
>= MTLArgumentBuffersTier::Tier2 as u64,
|
||||
.unwrap_or(MTLArgumentBuffersTier::Tier1)
|
||||
>= MTLArgumentBuffersTier::Tier2,
|
||||
);
|
||||
features.set(
|
||||
F::SHADER_INT64,
|
||||
self.int64 && self.msl_version >= MTLLanguageVersion::V2_3,
|
||||
self.int64 && self.msl_version >= MTLLanguageVersion::Version2_3,
|
||||
);
|
||||
features.set(
|
||||
F::SHADER_INT64_ATOMIC_MIN_MAX,
|
||||
self.int64_atomics_min_max && self.msl_version >= MTLLanguageVersion::V2_4,
|
||||
self.int64_atomics_min_max && self.msl_version >= MTLLanguageVersion::Version2_4,
|
||||
);
|
||||
features.set(
|
||||
F::TEXTURE_INT64_ATOMIC,
|
||||
self.int64_atomics && self.msl_version >= MTLLanguageVersion::V3_1,
|
||||
self.int64_atomics && self.msl_version >= MTLLanguageVersion::Version3_1,
|
||||
);
|
||||
features.set(
|
||||
F::TEXTURE_ATOMIC,
|
||||
self.msl_version >= MTLLanguageVersion::V3_1,
|
||||
self.msl_version >= MTLLanguageVersion::Version3_1,
|
||||
);
|
||||
features.set(
|
||||
F::SHADER_FLOAT32_ATOMIC,
|
||||
self.float_atomics && self.msl_version >= MTLLanguageVersion::V3_0,
|
||||
self.float_atomics && self.msl_version >= MTLLanguageVersion::Version3_0,
|
||||
);
|
||||
|
||||
features.set(
|
||||
@@ -1114,7 +1114,7 @@ impl super::PrivateCapabilities {
|
||||
|
||||
features.set(
|
||||
F::SHADER_BARYCENTRICS,
|
||||
self.shader_barycentrics && self.msl_version >= MTLLanguageVersion::V2_2,
|
||||
self.shader_barycentrics && self.msl_version >= MTLLanguageVersion::Version2_2,
|
||||
);
|
||||
|
||||
if self.supports_simd_scoped_operations {
|
||||
@@ -1126,7 +1126,7 @@ impl super::PrivateCapabilities {
|
||||
// Cooperative matrix (simdgroup matrix) requires MSL 2.3+
|
||||
features.set(
|
||||
F::EXPERIMENTAL_COOPERATIVE_MATRIX,
|
||||
self.supports_cooperative_matrix && self.msl_version >= MTLLanguageVersion::V2_3,
|
||||
self.supports_cooperative_matrix && self.msl_version >= MTLLanguageVersion::Version2_3,
|
||||
);
|
||||
|
||||
if self.supported_vertex_amplification_factor > 1 {
|
||||
@@ -1275,7 +1275,7 @@ impl super::PrivateCapabilities {
|
||||
///
|
||||
/// Metal's simdgroup_matrix supports 8x8 tiles with f16 and f32 element types.
|
||||
fn cooperative_matrix_properties(&self) -> Vec<wgt::CooperativeMatrixProperties> {
|
||||
if !self.supports_cooperative_matrix || self.msl_version < MTLLanguageVersion::V2_3 {
|
||||
if !self.supports_cooperative_matrix || self.msl_version < MTLLanguageVersion::Version2_3 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
@@ -1482,8 +1482,8 @@ impl super::PrivateCapabilities {
|
||||
}
|
||||
|
||||
impl super::PrivateDisabilities {
|
||||
pub fn new(device: &metal::Device) -> Self {
|
||||
let is_intel = device.name().starts_with("Intel");
|
||||
pub fn new(device: &ProtocolObject<dyn MTLDevice>) -> Self {
|
||||
let is_intel = device.name().to_string().starts_with("Intel");
|
||||
Self {
|
||||
broken_viewport_near_depth: is_intel
|
||||
&& !device.supports_feature_set(MTLFeatureSet::macOS_GPUFamily1_v4),
|
||||
@@ -1493,12 +1493,12 @@ impl super::PrivateDisabilities {
|
||||
}
|
||||
|
||||
impl super::OsType {
|
||||
fn new(version: NSOperatingSystemVersion, device: &metal::Device) -> Self {
|
||||
fn new(version: NSOperatingSystemVersion, device: &ProtocolObject<dyn MTLDevice>) -> Self {
|
||||
// Metal was first introduced in OS X 10.11 and iOS 8. The current version number of visionOS is 1.0.0. Additionally,
|
||||
// on the Simulator, Apple only provides the Apple2 GPU capability, and the Apple2+ GPU capability covers the capabilities of Apple2.
|
||||
// Therefore, the following conditions can be used to determine if it is visionOS.
|
||||
// https://developer.apple.com/documentation/metal/developing_metal_apps_that_run_in_simulator
|
||||
let os_is_vision = version.major < 8 && device.supports_family(MTLGPUFamily::Apple2);
|
||||
let os_is_vision = version.majorVersion < 8 && device.supports_family(MTLGPUFamily::Apple2);
|
||||
let os_is_mac = device.supports_feature_set(MTLFeatureSet::macOS_GPUFamily1_v1);
|
||||
let os_is_tvos = device.supports_feature_set(MTLFeatureSet::tvOS_GPUFamily1_v1);
|
||||
if os_is_vision {
|
||||
@@ -1513,22 +1513,24 @@ impl super::OsType {
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[allow(clippy::upper_case_acronyms)]
|
||||
struct NSOperatingSystemVersion {
|
||||
major: usize,
|
||||
minor: usize,
|
||||
patch: usize,
|
||||
}
|
||||
|
||||
impl NSOperatingSystemVersion {
|
||||
trait AtLeast {
|
||||
fn at_least(
|
||||
&self,
|
||||
mac_version: (usize, usize),
|
||||
ios_version: (usize, usize),
|
||||
tvos_version: (usize, usize),
|
||||
visionos_version: (usize, usize),
|
||||
mac_version: (isize, isize),
|
||||
ios_version: (isize, isize),
|
||||
tvos_version: (isize, isize),
|
||||
visionos_version: (isize, isize),
|
||||
os_type: super::OsType,
|
||||
) -> bool;
|
||||
}
|
||||
|
||||
impl AtLeast for NSOperatingSystemVersion {
|
||||
fn at_least(
|
||||
&self,
|
||||
mac_version: (isize, isize),
|
||||
ios_version: (isize, isize),
|
||||
tvos_version: (isize, isize),
|
||||
visionos_version: (isize, isize),
|
||||
os_type: super::OsType,
|
||||
) -> bool {
|
||||
let required = match os_type {
|
||||
@@ -1537,6 +1539,6 @@ impl NSOperatingSystemVersion {
|
||||
super::OsType::Tvos => tvos_version,
|
||||
super::OsType::VisionOs => visionos_version,
|
||||
};
|
||||
(self.major, self.minor) >= required
|
||||
(self.majorVersion, self.minorVersion) >= required
|
||||
}
|
||||
}
|
||||
+501
-352
File diff suppressed because it is too large.
Load diff
+18
-16
@@ -1,9 +1,10 @@
|
||||
use metal::{
|
||||
use objc2_foundation::NSRange;
|
||||
use objc2_metal::{
|
||||
MTLBlendFactor, MTLBlendOperation, MTLBlitOption, MTLClearColor, MTLColorWriteMask,
|
||||
MTLCompareFunction, MTLCullMode, MTLOrigin, MTLPrimitiveTopologyClass, MTLPrimitiveType,
|
||||
MTLRenderStages, MTLResourceUsage, MTLSamplerAddressMode, MTLSamplerBorderColor,
|
||||
MTLSamplerMinMagFilter, MTLSize, MTLStencilOperation, MTLStoreAction, MTLTextureType,
|
||||
MTLTextureUsage, MTLVertexFormat, MTLVertexStepFunction, MTLWinding, NSRange,
|
||||
MTLTextureUsage, MTLVertexFormat, MTLVertexStepFunction, MTLWinding,
|
||||
};
|
||||
|
||||
pub fn map_texture_usage(format: wgt::TextureFormat, usage: wgt::TextureUses) -> MTLTextureUsage {
|
||||
@@ -44,12 +45,12 @@ pub fn map_texture_view_dimension(dim: wgt::TextureViewDimension) -> MTLTextureT
|
||||
use wgt::TextureViewDimension as Tvd;
|
||||
use MTLTextureType as MTL;
|
||||
match dim {
|
||||
Tvd::D1 => MTL::D1,
|
||||
Tvd::D2 => MTL::D2,
|
||||
Tvd::D2Array => MTL::D2Array,
|
||||
Tvd::D3 => MTL::D3,
|
||||
Tvd::Cube => MTL::Cube,
|
||||
Tvd::CubeArray => MTL::CubeArray,
|
||||
Tvd::D1 => MTL::Type1D,
|
||||
Tvd::D2 => MTL::Type2D,
|
||||
Tvd::D2Array => MTL::Type2DArray,
|
||||
Tvd::D3 => MTL::Type3D,
|
||||
Tvd::Cube => MTL::TypeCube,
|
||||
Tvd::CubeArray => MTL::TypeCubeArray,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,24 +275,24 @@ pub fn map_cull_mode(face: Option<wgt::Face>) -> MTLCullMode {
|
||||
|
||||
pub fn map_range(range: &crate::MemoryRange) -> NSRange {
|
||||
NSRange {
|
||||
location: range.start,
|
||||
length: range.end - range.start,
|
||||
location: range.start as usize,
|
||||
length: (range.end - range.start) as usize,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_copy_extent(extent: &crate::CopyExtent) -> MTLSize {
|
||||
MTLSize {
|
||||
width: extent.width as u64,
|
||||
height: extent.height as u64,
|
||||
depth: extent.depth as u64,
|
||||
width: extent.width as usize,
|
||||
height: extent.height as usize,
|
||||
depth: extent.depth as usize,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_origin(origin: &wgt::Origin3d) -> MTLOrigin {
|
||||
MTLOrigin {
|
||||
x: origin.x as u64,
|
||||
y: origin.y as u64,
|
||||
z: origin.z as u64,
|
||||
x: origin.x as usize,
|
||||
y: origin.y as usize,
|
||||
z: origin.z as usize,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -341,6 +342,7 @@ pub fn map_render_stages(stage: wgt::ShaderStages) -> MTLRenderStages {
|
||||
|
||||
pub fn map_resource_usage(ty: &wgt::BindingType) -> MTLResourceUsage {
|
||||
match ty {
|
||||
#[allow(deprecated)]
|
||||
wgt::BindingType::Texture { .. } => MTLResourceUsage::Sample,
|
||||
wgt::BindingType::StorageTexture { access, .. } => match access {
|
||||
wgt::StorageTextureAccess::WriteOnly => MTLResourceUsage::Write,
|
||||
|
||||
+277
-191
@@ -2,23 +2,33 @@ use alloc::{borrow::ToOwned as _, sync::Arc, vec::Vec};
|
||||
use core::{ptr::NonNull, sync::atomic};
|
||||
use std::{thread, time};
|
||||
|
||||
use super::{conv, PassthroughShader};
|
||||
use crate::auxil::map_naga_stage;
|
||||
use crate::metal::ShaderModuleSource;
|
||||
use crate::TlasInstance;
|
||||
|
||||
use metal::{
|
||||
foreign_types::ForeignType, MTLCommandBufferStatus, MTLDepthClipMode, MTLLanguageVersion,
|
||||
MTLMutability, MTLPixelFormat, MTLPrimitiveTopologyClass, MTLResourceID, MTLResourceOptions,
|
||||
MTLSamplerAddressMode, MTLSamplerMipFilter, MTLSize, MTLStorageMode, MTLTextureType,
|
||||
MTLTriangleFillMode, MTLVertexStepFunction, NSRange,
|
||||
use objc2::{
|
||||
msg_send,
|
||||
rc::{autoreleasepool, Retained},
|
||||
runtime::ProtocolObject,
|
||||
};
|
||||
use objc2_foundation::{ns_string, NSError, NSRange, NSString, NSUInteger};
|
||||
use objc2_metal::{
|
||||
MTLBuffer, MTLCaptureManager, MTLCaptureScope, MTLCommandBuffer, MTLCommandBufferStatus,
|
||||
MTLCompileOptions, MTLComputePipelineDescriptor, MTLComputePipelineState,
|
||||
MTLCounterSampleBufferDescriptor, MTLCounterSet, MTLDepthClipMode, MTLDepthStencilDescriptor,
|
||||
MTLDevice, MTLFunction, MTLLanguageVersion, MTLLibrary, MTLMeshRenderPipelineDescriptor,
|
||||
MTLMutability, MTLPipelineBufferDescriptorArray, MTLPixelFormat, MTLPrimitiveTopologyClass,
|
||||
MTLRenderPipelineColorAttachmentDescriptorArray, MTLRenderPipelineDescriptor, MTLResource,
|
||||
MTLResourceID, MTLResourceOptions, MTLSamplerAddressMode, MTLSamplerDescriptor,
|
||||
MTLSamplerMipFilter, MTLSamplerState, MTLSize, MTLStencilDescriptor, MTLStorageMode,
|
||||
MTLTexture, MTLTextureDescriptor, MTLTextureType, MTLTriangleFillMode, MTLVertexDescriptor,
|
||||
MTLVertexStepFunction,
|
||||
};
|
||||
|
||||
use super::{conv, PassthroughShader, ShaderModuleSource};
|
||||
use crate::{auxil::map_naga_stage, TlasInstance};
|
||||
|
||||
type DeviceResult<T> = Result<T, crate::DeviceError>;
|
||||
|
||||
struct CompiledShader {
|
||||
library: metal::Library,
|
||||
function: metal::Function,
|
||||
library: Retained<ProtocolObject<dyn MTLLibrary>>,
|
||||
function: Retained<ProtocolObject<dyn MTLFunction>>,
|
||||
wg_size: MTLSize,
|
||||
wg_memory_sizes: Vec<u32>,
|
||||
|
||||
@@ -39,8 +49,8 @@ fn create_stencil_desc(
|
||||
face: &wgt::StencilFaceState,
|
||||
read_mask: u32,
|
||||
write_mask: u32,
|
||||
) -> metal::StencilDescriptor {
|
||||
let desc = metal::StencilDescriptor::new();
|
||||
) -> Retained<MTLStencilDescriptor> {
|
||||
let desc = MTLStencilDescriptor::new();
|
||||
desc.set_stencil_compare_function(conv::map_compare_function(face.compare));
|
||||
desc.set_read_mask(read_mask);
|
||||
desc.set_write_mask(write_mask);
|
||||
@@ -50,8 +60,10 @@ fn create_stencil_desc(
|
||||
desc
|
||||
}
|
||||
|
||||
fn create_depth_stencil_desc(state: &wgt::DepthStencilState) -> metal::DepthStencilDescriptor {
|
||||
let desc = metal::DepthStencilDescriptor::new();
|
||||
fn create_depth_stencil_desc(
|
||||
state: &wgt::DepthStencilState,
|
||||
) -> Retained<MTLDepthStencilDescriptor> {
|
||||
let desc = MTLDepthStencilDescriptor::new();
|
||||
desc.set_depth_compare_function(conv::map_compare_function(state.depth_compare));
|
||||
desc.set_depth_write_enabled(state.depth_write_enabled);
|
||||
let s = &state.stencil;
|
||||
@@ -149,16 +161,19 @@ impl super::Device {
|
||||
|
||||
let options = naga::back::msl::Options {
|
||||
lang_version: match self.shared.private_caps.msl_version {
|
||||
MTLLanguageVersion::V1_0 => (1, 0),
|
||||
MTLLanguageVersion::V1_1 => (1, 1),
|
||||
MTLLanguageVersion::V1_2 => (1, 2),
|
||||
MTLLanguageVersion::V2_0 => (2, 0),
|
||||
MTLLanguageVersion::V2_1 => (2, 1),
|
||||
MTLLanguageVersion::V2_2 => (2, 2),
|
||||
MTLLanguageVersion::V2_3 => (2, 3),
|
||||
MTLLanguageVersion::V2_4 => (2, 4),
|
||||
MTLLanguageVersion::V3_0 => (3, 0),
|
||||
MTLLanguageVersion::V3_1 => (3, 1),
|
||||
#[allow(deprecated)]
|
||||
MTLLanguageVersion::Version1_0 => (1, 0),
|
||||
MTLLanguageVersion::Version1_1 => (1, 1),
|
||||
MTLLanguageVersion::Version1_2 => (1, 2),
|
||||
MTLLanguageVersion::Version2_0 => (2, 0),
|
||||
MTLLanguageVersion::Version2_1 => (2, 1),
|
||||
MTLLanguageVersion::Version2_2 => (2, 2),
|
||||
MTLLanguageVersion::Version2_3 => (2, 3),
|
||||
MTLLanguageVersion::Version2_4 => (2, 4),
|
||||
MTLLanguageVersion::Version3_0 => (3, 0),
|
||||
MTLLanguageVersion::Version3_1 => (3, 1),
|
||||
// Newer version, fall back to 3.1
|
||||
_ => (3, 1),
|
||||
},
|
||||
inline_samplers: Default::default(),
|
||||
spirv_cross_compatibility: false,
|
||||
@@ -203,7 +218,7 @@ impl super::Device {
|
||||
&source
|
||||
);
|
||||
|
||||
let options = metal::CompileOptions::new();
|
||||
let options = MTLCompileOptions::new();
|
||||
options.set_language_version(self.shared.private_caps.msl_version);
|
||||
|
||||
if self.shared.private_caps.supports_preserve_invariance {
|
||||
@@ -213,7 +228,10 @@ impl super::Device {
|
||||
let library = self
|
||||
.shared
|
||||
.device
|
||||
.new_library_with_source(source.as_ref(), &options)
|
||||
.new_library_with_source_options_error(
|
||||
&NSString::from_str(&source),
|
||||
Some(&options),
|
||||
)
|
||||
.map_err(|err| {
|
||||
log::debug!("Naga generated shader:\n{source}");
|
||||
crate::PipelineError::Linkage(stage_bit, format!("Metal: {err}"))
|
||||
@@ -236,9 +254,9 @@ impl super::Device {
|
||||
};
|
||||
|
||||
let function = library
|
||||
.get_function(translated_ep_name, None)
|
||||
.map_err(|e| {
|
||||
log::error!("get_function: {e:?}");
|
||||
.new_function_with_name(&NSString::from_str(translated_ep_name))
|
||||
.ok_or_else(|| {
|
||||
log::error!("Function '{translated_ep_name}' does not exist");
|
||||
crate::PipelineError::EntryPoint(naga_stage)
|
||||
})?;
|
||||
|
||||
@@ -304,9 +322,9 @@ impl super::Device {
|
||||
library: shader.library.clone(),
|
||||
function: shader.function.clone(),
|
||||
wg_size: MTLSize {
|
||||
width: shader.num_workgroups.0 as u64,
|
||||
height: shader.num_workgroups.1 as u64,
|
||||
depth: shader.num_workgroups.2 as u64,
|
||||
width: shader.num_workgroups.0 as usize,
|
||||
height: shader.num_workgroups.1 as usize,
|
||||
depth: shader.num_workgroups.2 as usize,
|
||||
},
|
||||
wg_memory_sizes: vec![],
|
||||
sized_bindings: vec![],
|
||||
@@ -316,21 +334,19 @@ impl super::Device {
|
||||
}
|
||||
|
||||
fn set_buffers_mutability(
|
||||
buffers: &metal::PipelineBufferDescriptorArrayRef,
|
||||
buffers: &MTLPipelineBufferDescriptorArray,
|
||||
mut immutable_mask: usize,
|
||||
) {
|
||||
while immutable_mask != 0 {
|
||||
let slot = immutable_mask.trailing_zeros();
|
||||
immutable_mask ^= 1 << slot;
|
||||
buffers
|
||||
.object_at(slot as u64)
|
||||
.unwrap()
|
||||
unsafe { buffers.object_at_indexed_subscript(slot as usize) }
|
||||
.set_mutability(MTLMutability::Immutable);
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn texture_from_raw(
|
||||
raw: metal::Texture,
|
||||
raw: Retained<ProtocolObject<dyn MTLTexture>>,
|
||||
format: wgt::TextureFormat,
|
||||
raw_type: MTLTextureType,
|
||||
array_layers: u32,
|
||||
@@ -347,7 +363,10 @@ impl super::Device {
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn device_from_raw(raw: metal::Device, features: wgt::Features) -> super::Device {
|
||||
pub unsafe fn device_from_raw(
|
||||
raw: Retained<ProtocolObject<dyn MTLDevice>>,
|
||||
features: wgt::Features,
|
||||
) -> super::Device {
|
||||
super::Device {
|
||||
shared: Arc::new(super::AdapterShared::new(raw)),
|
||||
features,
|
||||
@@ -355,11 +374,14 @@ impl super::Device {
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn buffer_from_raw(raw: metal::Buffer, size: wgt::BufferAddress) -> super::Buffer {
|
||||
pub unsafe fn buffer_from_raw(
|
||||
raw: Retained<ProtocolObject<dyn MTLBuffer>>,
|
||||
size: wgt::BufferAddress,
|
||||
) -> super::Buffer {
|
||||
super::Buffer { raw, size }
|
||||
}
|
||||
|
||||
pub fn raw_device(&self) -> &metal::Device {
|
||||
pub fn raw_device(&self) -> &Retained<ProtocolObject<dyn MTLDevice>> {
|
||||
&self.shared.device
|
||||
}
|
||||
}
|
||||
@@ -382,10 +404,14 @@ impl crate::Device for super::Device {
|
||||
|
||||
//TODO: HazardTrackingModeUntracked
|
||||
|
||||
objc::rc::autoreleasepool(|| {
|
||||
let raw = self.shared.device.new_buffer(desc.size, options);
|
||||
autoreleasepool(|_| {
|
||||
let raw = self
|
||||
.shared
|
||||
.device
|
||||
.new_buffer_with_length_options(desc.size as usize, options)
|
||||
.unwrap();
|
||||
if let Some(label) = desc.label {
|
||||
raw.set_label(label);
|
||||
raw.set_label(Some(&NSString::from_str(label)));
|
||||
}
|
||||
self.counters.buffers.add(1);
|
||||
Ok(super::Buffer {
|
||||
@@ -408,9 +434,8 @@ impl crate::Device for super::Device {
|
||||
range: crate::MemoryRange,
|
||||
) -> DeviceResult<crate::BufferMapping> {
|
||||
let ptr = buffer.raw.contents().cast::<u8>();
|
||||
assert!(!ptr.is_null());
|
||||
Ok(crate::BufferMapping {
|
||||
ptr: NonNull::new(unsafe { ptr.offset(range.start as isize) }).unwrap(),
|
||||
ptr: NonNull::new(unsafe { ptr.as_ptr().offset(range.start as isize) }).unwrap(),
|
||||
is_coherent: true,
|
||||
})
|
||||
}
|
||||
@@ -423,29 +448,29 @@ impl crate::Device for super::Device {
|
||||
&self,
|
||||
desc: &crate::TextureDescriptor,
|
||||
) -> DeviceResult<super::Texture> {
|
||||
use metal::foreign_types::ForeignType as _;
|
||||
|
||||
let mtl_format = self.shared.private_caps.map_format(desc.format);
|
||||
|
||||
objc::rc::autoreleasepool(|| {
|
||||
let descriptor = metal::TextureDescriptor::new();
|
||||
autoreleasepool(|_| {
|
||||
let descriptor = MTLTextureDescriptor::new();
|
||||
|
||||
let mtl_type = match desc.dimension {
|
||||
wgt::TextureDimension::D1 => MTLTextureType::D1,
|
||||
wgt::TextureDimension::D1 => MTLTextureType::Type1D,
|
||||
wgt::TextureDimension::D2 => {
|
||||
if desc.sample_count > 1 {
|
||||
descriptor.set_sample_count(desc.sample_count as u64);
|
||||
MTLTextureType::D2Multisample
|
||||
unsafe { descriptor.set_sample_count(desc.sample_count as usize) };
|
||||
MTLTextureType::Type2DMultisample
|
||||
} else if desc.size.depth_or_array_layers > 1 {
|
||||
descriptor.set_array_length(desc.size.depth_or_array_layers as u64);
|
||||
MTLTextureType::D2Array
|
||||
unsafe {
|
||||
descriptor.set_array_length(desc.size.depth_or_array_layers as usize)
|
||||
};
|
||||
MTLTextureType::Type2DArray
|
||||
} else {
|
||||
MTLTextureType::D2
|
||||
MTLTextureType::Type2D
|
||||
}
|
||||
}
|
||||
wgt::TextureDimension::D3 => {
|
||||
descriptor.set_depth(desc.size.depth_or_array_layers as u64);
|
||||
MTLTextureType::D3
|
||||
unsafe { descriptor.set_depth(desc.size.depth_or_array_layers as usize) };
|
||||
MTLTextureType::Type3D
|
||||
}
|
||||
};
|
||||
|
||||
@@ -458,19 +483,20 @@ impl crate::Device for super::Device {
|
||||
};
|
||||
|
||||
descriptor.set_texture_type(mtl_type);
|
||||
descriptor.set_width(desc.size.width as u64);
|
||||
descriptor.set_height(desc.size.height as u64);
|
||||
descriptor.set_mipmap_level_count(desc.mip_level_count as u64);
|
||||
unsafe { descriptor.set_width(desc.size.width as usize) };
|
||||
unsafe { descriptor.set_height(desc.size.height as usize) };
|
||||
unsafe { descriptor.set_mipmap_level_count(desc.mip_level_count as usize) };
|
||||
descriptor.set_pixel_format(mtl_format);
|
||||
descriptor.set_usage(conv::map_texture_usage(desc.format, desc.usage));
|
||||
descriptor.set_storage_mode(mtl_storage_mode);
|
||||
|
||||
let raw = self.shared.device.new_texture(&descriptor);
|
||||
if raw.as_ptr().is_null() {
|
||||
return Err(crate::DeviceError::OutOfMemory);
|
||||
}
|
||||
let raw = self
|
||||
.shared
|
||||
.device
|
||||
.new_texture_with_descriptor(&descriptor)
|
||||
.ok_or(crate::DeviceError::OutOfMemory)?;
|
||||
if let Some(label) = desc.label {
|
||||
raw.set_label(label);
|
||||
raw.set_label(Some(&NSString::from_str(label)));
|
||||
}
|
||||
|
||||
self.counters.textures.add(1);
|
||||
@@ -499,7 +525,7 @@ impl crate::Device for super::Device {
|
||||
texture: &super::Texture,
|
||||
desc: &crate::TextureViewDescriptor,
|
||||
) -> DeviceResult<super::TextureView> {
|
||||
let raw_type = if texture.raw_type == MTLTextureType::D2Multisample {
|
||||
let raw_type = if texture.raw_type == MTLTextureType::Type2DMultisample {
|
||||
texture.raw_type
|
||||
} else {
|
||||
conv::map_texture_view_dimension(desc.dimension)
|
||||
@@ -532,21 +558,28 @@ impl crate::Device for super::Device {
|
||||
.array_layer_count
|
||||
.unwrap_or(texture.array_layers - desc.range.base_array_layer);
|
||||
|
||||
objc::rc::autoreleasepool(|| {
|
||||
let raw = texture.raw.new_texture_view_from_slice(
|
||||
raw_format,
|
||||
raw_type,
|
||||
NSRange {
|
||||
location: desc.range.base_mip_level as _,
|
||||
length: mip_level_count as _,
|
||||
},
|
||||
NSRange {
|
||||
location: desc.range.base_array_layer as _,
|
||||
length: array_layer_count as _,
|
||||
},
|
||||
);
|
||||
autoreleasepool(|_| {
|
||||
let level_range = NSRange {
|
||||
location: desc.range.base_mip_level as _,
|
||||
length: mip_level_count as _,
|
||||
};
|
||||
let slice_range = NSRange {
|
||||
location: desc.range.base_array_layer as _,
|
||||
length: array_layer_count as _,
|
||||
};
|
||||
let raw = unsafe {
|
||||
texture
|
||||
.raw
|
||||
.new_texture_view_with_pixel_format_texture_type_levels_slices(
|
||||
raw_format,
|
||||
raw_type,
|
||||
level_range,
|
||||
slice_range,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
if let Some(label) = desc.label {
|
||||
raw.set_label(label);
|
||||
raw.set_label(Some(&NSString::from_str(label)));
|
||||
}
|
||||
raw
|
||||
})
|
||||
@@ -565,8 +598,8 @@ impl crate::Device for super::Device {
|
||||
&self,
|
||||
desc: &crate::SamplerDescriptor,
|
||||
) -> DeviceResult<super::Sampler> {
|
||||
objc::rc::autoreleasepool(|| {
|
||||
let descriptor = metal::SamplerDescriptor::new();
|
||||
autoreleasepool(|_| {
|
||||
let descriptor = MTLSamplerDescriptor::new();
|
||||
|
||||
descriptor.set_min_filter(conv::map_filter_mode(desc.min_filter));
|
||||
descriptor.set_mag_filter(conv::map_filter_mode(desc.mag_filter));
|
||||
@@ -579,9 +612,9 @@ impl crate::Device for super::Device {
|
||||
});
|
||||
|
||||
let [s, t, r] = desc.address_modes;
|
||||
descriptor.set_address_mode_s(conv::map_address_mode(s));
|
||||
descriptor.set_address_mode_t(conv::map_address_mode(t));
|
||||
descriptor.set_address_mode_r(conv::map_address_mode(r));
|
||||
descriptor.set_s_address_mode(conv::map_address_mode(s));
|
||||
descriptor.set_t_address_mode(conv::map_address_mode(t));
|
||||
descriptor.set_r_address_mode(conv::map_address_mode(r));
|
||||
|
||||
// Anisotropy is always supported on mac up to 16x
|
||||
descriptor.set_max_anisotropy(desc.anisotropy_clamp as _);
|
||||
@@ -596,15 +629,15 @@ impl crate::Device for super::Device {
|
||||
if let Some(border_color) = desc.border_color {
|
||||
if let wgt::SamplerBorderColor::Zero = border_color {
|
||||
if s == wgt::AddressMode::ClampToBorder {
|
||||
descriptor.set_address_mode_s(MTLSamplerAddressMode::ClampToZero);
|
||||
descriptor.set_s_address_mode(MTLSamplerAddressMode::ClampToZero);
|
||||
}
|
||||
|
||||
if t == wgt::AddressMode::ClampToBorder {
|
||||
descriptor.set_address_mode_t(MTLSamplerAddressMode::ClampToZero);
|
||||
descriptor.set_t_address_mode(MTLSamplerAddressMode::ClampToZero);
|
||||
}
|
||||
|
||||
if r == wgt::AddressMode::ClampToBorder {
|
||||
descriptor.set_address_mode_r(MTLSamplerAddressMode::ClampToZero);
|
||||
descriptor.set_r_address_mode(MTLSamplerAddressMode::ClampToZero);
|
||||
}
|
||||
} else {
|
||||
descriptor.set_border_color(conv::map_border_color(border_color));
|
||||
@@ -612,12 +645,16 @@ impl crate::Device for super::Device {
|
||||
}
|
||||
|
||||
if let Some(label) = desc.label {
|
||||
descriptor.set_label(label);
|
||||
descriptor.set_label(Some(&NSString::from_str(label)));
|
||||
}
|
||||
if self.features.contains(wgt::Features::TEXTURE_BINDING_ARRAY) {
|
||||
descriptor.set_support_argument_buffers(true);
|
||||
}
|
||||
let raw = self.shared.device.new_sampler(&descriptor);
|
||||
let raw = self
|
||||
.shared
|
||||
.device
|
||||
.new_sampler_state_with_descriptor(&descriptor)
|
||||
.unwrap();
|
||||
|
||||
self.counters.samplers.add(1);
|
||||
|
||||
@@ -845,7 +882,7 @@ impl crate::Device for super::Device {
|
||||
super::AccelerationStructure,
|
||||
>,
|
||||
) -> DeviceResult<super::BindGroup> {
|
||||
objc::rc::autoreleasepool(|| {
|
||||
autoreleasepool(|_| {
|
||||
let mut bg = super::BindGroup::default();
|
||||
for (&stage, counter) in super::NAGA_STAGES.iter().zip(bg.counters.iter_mut()) {
|
||||
let stage_bit = map_naga_stage(stage);
|
||||
@@ -872,15 +909,19 @@ impl crate::Device for super::Device {
|
||||
let uses = conv::map_resource_usage(&layout.ty);
|
||||
|
||||
// Create argument buffer for this array
|
||||
let buffer = self.shared.device.new_buffer(
|
||||
8 * count as u64,
|
||||
MTLResourceOptions::HazardTrackingModeUntracked
|
||||
| MTLResourceOptions::StorageModeShared,
|
||||
);
|
||||
let buffer = self
|
||||
.shared
|
||||
.device
|
||||
.new_buffer_with_length_options(
|
||||
8 * count as usize,
|
||||
MTLResourceOptions::HazardTrackingModeUntracked
|
||||
| MTLResourceOptions::StorageModeShared,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let contents: &mut [MTLResourceID] = unsafe {
|
||||
core::slice::from_raw_parts_mut(
|
||||
buffer.contents().cast(),
|
||||
buffer.contents().cast().as_ptr(),
|
||||
count as usize,
|
||||
)
|
||||
};
|
||||
@@ -922,7 +963,7 @@ impl crate::Device for super::Device {
|
||||
}
|
||||
|
||||
bg.buffers.push(super::BufferResource {
|
||||
ptr: unsafe { NonNull::new_unchecked(buffer.as_ptr()) },
|
||||
ptr: NonNull::from(&*buffer),
|
||||
offset: 0,
|
||||
dynamic_index: None,
|
||||
binding_size: None,
|
||||
@@ -1053,17 +1094,22 @@ impl crate::Device for super::Device {
|
||||
entry_point,
|
||||
num_workgroups,
|
||||
} => {
|
||||
let options = metal::CompileOptions::new();
|
||||
let options = MTLCompileOptions::new();
|
||||
// Obtain the device from shared
|
||||
let device = &self.shared.device;
|
||||
let library = device
|
||||
.new_library_with_source(source, &options)
|
||||
.new_library_with_source_options_error(
|
||||
&NSString::from_str(source),
|
||||
Some(&options),
|
||||
)
|
||||
.map_err(|e| crate::ShaderError::Compilation(format!("MSL: {e:?}")))?;
|
||||
let function = library.get_function(&entry_point, None).map_err(|_| {
|
||||
crate::ShaderError::Compilation(format!(
|
||||
"Entry point '{entry_point}' not found"
|
||||
))
|
||||
})?;
|
||||
let function = library
|
||||
.new_function_with_name(&NSString::from_str(&entry_point))
|
||||
.ok_or_else(|| {
|
||||
crate::ShaderError::Compilation(format!(
|
||||
"Entry point '{entry_point}' not found"
|
||||
))
|
||||
})?;
|
||||
|
||||
Ok(super::ShaderModule {
|
||||
source: ShaderModuleSource::Passthrough(PassthroughShader {
|
||||
@@ -1094,10 +1140,10 @@ impl crate::Device for super::Device {
|
||||
super::PipelineCache,
|
||||
>,
|
||||
) -> Result<super::RenderPipeline, crate::PipelineError> {
|
||||
objc::rc::autoreleasepool(|| {
|
||||
autoreleasepool(|_| {
|
||||
enum MetalGenericRenderPipelineDescriptor {
|
||||
Standard(metal::RenderPipelineDescriptor),
|
||||
Mesh(metal::MeshRenderPipelineDescriptor),
|
||||
Standard(Retained<MTLRenderPipelineDescriptor>),
|
||||
Mesh(Retained<MTLMeshRenderPipelineDescriptor>),
|
||||
}
|
||||
macro_rules! descriptor_fn {
|
||||
($descriptor:ident . $method:ident $( ( $($args:expr),* ) )? ) => {
|
||||
@@ -1108,10 +1154,13 @@ impl crate::Device for super::Device {
|
||||
};
|
||||
}
|
||||
impl MetalGenericRenderPipelineDescriptor {
|
||||
fn set_fragment_function(&self, function: Option<&metal::FunctionRef>) {
|
||||
descriptor_fn!(self.set_fragment_function(function));
|
||||
unsafe fn set_fragment_function(
|
||||
&self,
|
||||
function: Option<&ProtocolObject<dyn MTLFunction>>,
|
||||
) {
|
||||
unsafe { descriptor_fn!(self.set_fragment_function(function)) };
|
||||
}
|
||||
fn fragment_buffers(&self) -> Option<&metal::PipelineBufferDescriptorArrayRef> {
|
||||
fn fragment_buffers(&self) -> Retained<MTLPipelineBufferDescriptorArray> {
|
||||
descriptor_fn!(self.fragment_buffers())
|
||||
}
|
||||
fn set_depth_attachment_pixel_format(&self, pixel_format: MTLPixelFormat) {
|
||||
@@ -1119,7 +1168,7 @@ impl crate::Device for super::Device {
|
||||
}
|
||||
fn color_attachments(
|
||||
&self,
|
||||
) -> &metal::RenderPipelineColorAttachmentDescriptorArrayRef {
|
||||
) -> Retained<MTLRenderPipelineColorAttachmentDescriptorArray> {
|
||||
descriptor_fn!(self.color_attachments())
|
||||
}
|
||||
fn set_stencil_attachment_pixel_format(&self, pixel_format: MTLPixelFormat) {
|
||||
@@ -1128,11 +1177,11 @@ impl crate::Device for super::Device {
|
||||
fn set_alpha_to_coverage_enabled(&self, enabled: bool) {
|
||||
descriptor_fn!(self.set_alpha_to_coverage_enabled(enabled));
|
||||
}
|
||||
fn set_label(&self, label: &str) {
|
||||
fn set_label(&self, label: Option<&NSString>) {
|
||||
descriptor_fn!(self.set_label(label));
|
||||
}
|
||||
fn set_max_vertex_amplification_count(&self, count: metal::NSUInteger) {
|
||||
descriptor_fn!(self.set_max_vertex_amplification_count(count))
|
||||
unsafe fn set_max_vertex_amplification_count(&self, count: NSUInteger) {
|
||||
unsafe { descriptor_fn!(self.set_max_vertex_amplification_count(count)) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1151,7 +1200,7 @@ impl crate::Device for super::Device {
|
||||
} => {
|
||||
// Vertex pipeline specific setup
|
||||
|
||||
let descriptor = metal::RenderPipelineDescriptor::new();
|
||||
let descriptor = MTLRenderPipelineDescriptor::new();
|
||||
ts_info = None;
|
||||
ms_info = None;
|
||||
|
||||
@@ -1208,7 +1257,7 @@ impl crate::Device for super::Device {
|
||||
descriptor.set_vertex_function(Some(&vs.function));
|
||||
if self.shared.private_caps.supports_mutability {
|
||||
Self::set_buffers_mutability(
|
||||
descriptor.vertex_buffers().unwrap(),
|
||||
&descriptor.vertex_buffers(),
|
||||
vs.immutable_buffer_mask,
|
||||
);
|
||||
}
|
||||
@@ -1219,7 +1268,11 @@ impl crate::Device for super::Device {
|
||||
sized_bindings: vs.sized_bindings,
|
||||
vertex_buffer_mappings,
|
||||
library: Some(vs.library),
|
||||
raw_wg_size: Default::default(),
|
||||
raw_wg_size: MTLSize {
|
||||
width: 0,
|
||||
height: 0,
|
||||
depth: 0,
|
||||
},
|
||||
work_group_memory_sizes: vec![],
|
||||
});
|
||||
}
|
||||
@@ -1241,12 +1294,15 @@ impl crate::Device for super::Device {
|
||||
|
||||
// Set the pipeline vertex buffer info
|
||||
if !vertex_buffers.is_empty() {
|
||||
let vertex_descriptor = metal::VertexDescriptor::new();
|
||||
let vertex_descriptor = MTLVertexDescriptor::new();
|
||||
for (i, vb) in vertex_buffers.iter().enumerate() {
|
||||
let buffer_index =
|
||||
self.shared.private_caps.max_vertex_buffers as u64 - 1 - i as u64;
|
||||
let buffer_desc =
|
||||
vertex_descriptor.layouts().object_at(buffer_index).unwrap();
|
||||
self.shared.private_caps.max_vertex_buffers as usize - 1 - i;
|
||||
let buffer_desc = unsafe {
|
||||
vertex_descriptor
|
||||
.layouts()
|
||||
.object_at_indexed_subscript(buffer_index)
|
||||
};
|
||||
|
||||
// Metal expects the stride to be the actual size of the attributes.
|
||||
// The semantics of array_stride == 0 can be achieved by setting
|
||||
@@ -1258,25 +1314,28 @@ impl crate::Device for super::Device {
|
||||
.map(|attribute| attribute.offset + attribute.format.size())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
buffer_desc.set_stride(wgt::math::align_to(stride, 4));
|
||||
unsafe {
|
||||
buffer_desc.set_stride(wgt::math::align_to(stride as _, 4))
|
||||
};
|
||||
buffer_desc.set_step_function(MTLVertexStepFunction::Constant);
|
||||
buffer_desc.set_step_rate(0);
|
||||
unsafe { buffer_desc.set_step_rate(0) };
|
||||
} else {
|
||||
buffer_desc.set_stride(vb.array_stride);
|
||||
unsafe { buffer_desc.set_stride(vb.array_stride as _) };
|
||||
buffer_desc.set_step_function(conv::map_step_mode(vb.step_mode));
|
||||
}
|
||||
|
||||
for at in vb.attributes {
|
||||
let attribute_desc = vertex_descriptor
|
||||
.attributes()
|
||||
.object_at(at.shader_location as u64)
|
||||
.unwrap();
|
||||
let attribute_desc = unsafe {
|
||||
vertex_descriptor
|
||||
.attributes()
|
||||
.object_at_indexed_subscript(at.shader_location as _)
|
||||
};
|
||||
attribute_desc.set_format(conv::map_vertex_format(at.format));
|
||||
attribute_desc.set_buffer_index(buffer_index);
|
||||
attribute_desc.set_offset(at.offset);
|
||||
unsafe { attribute_desc.set_buffer_index(buffer_index) };
|
||||
unsafe { attribute_desc.set_offset(at.offset as _) };
|
||||
}
|
||||
}
|
||||
descriptor.set_vertex_descriptor(Some(vertex_descriptor));
|
||||
descriptor.set_vertex_descriptor(Some(&vertex_descriptor));
|
||||
}
|
||||
|
||||
MetalGenericRenderPipelineDescriptor::Standard(descriptor)
|
||||
@@ -1288,7 +1347,7 @@ impl crate::Device for super::Device {
|
||||
// Mesh pipeline specific setup
|
||||
|
||||
vs_info = None;
|
||||
let descriptor = metal::MeshRenderPipelineDescriptor::new();
|
||||
let descriptor = MTLMeshRenderPipelineDescriptor::new();
|
||||
|
||||
// Setup task stage
|
||||
if let Some(ref task_stage) = task_stage {
|
||||
@@ -1299,10 +1358,10 @@ impl crate::Device for super::Device {
|
||||
primitive_class,
|
||||
naga::ShaderStage::Task,
|
||||
)?;
|
||||
descriptor.set_object_function(Some(&ts.function));
|
||||
unsafe { descriptor.set_object_function(Some(&ts.function)) };
|
||||
if self.shared.private_caps.supports_mutability {
|
||||
Self::set_buffers_mutability(
|
||||
descriptor.mesh_buffers().unwrap(),
|
||||
&descriptor.mesh_buffers(),
|
||||
ts.immutable_buffer_mask,
|
||||
);
|
||||
}
|
||||
@@ -1328,10 +1387,10 @@ impl crate::Device for super::Device {
|
||||
primitive_class,
|
||||
naga::ShaderStage::Mesh,
|
||||
)?;
|
||||
descriptor.set_mesh_function(Some(&ms.function));
|
||||
unsafe { descriptor.set_mesh_function(Some(&ms.function)) };
|
||||
if self.shared.private_caps.supports_mutability {
|
||||
Self::set_buffers_mutability(
|
||||
descriptor.mesh_buffers().unwrap(),
|
||||
&descriptor.mesh_buffers(),
|
||||
ms.immutable_buffer_mask,
|
||||
);
|
||||
}
|
||||
@@ -1370,10 +1429,10 @@ impl crate::Device for super::Device {
|
||||
naga::ShaderStage::Fragment,
|
||||
)?;
|
||||
|
||||
descriptor.set_fragment_function(Some(&fs.function));
|
||||
unsafe { descriptor.set_fragment_function(Some(&fs.function)) };
|
||||
if self.shared.private_caps.supports_mutability {
|
||||
Self::set_buffers_mutability(
|
||||
descriptor.fragment_buffers().unwrap(),
|
||||
&descriptor.fragment_buffers(),
|
||||
fs.immutable_buffer_mask,
|
||||
);
|
||||
}
|
||||
@@ -1384,7 +1443,11 @@ impl crate::Device for super::Device {
|
||||
sized_bindings: fs.sized_bindings,
|
||||
vertex_buffer_mappings: vec![],
|
||||
library: Some(fs.library),
|
||||
raw_wg_size: Default::default(),
|
||||
raw_wg_size: MTLSize {
|
||||
width: 0,
|
||||
height: 0,
|
||||
depth: 0,
|
||||
},
|
||||
work_group_memory_sizes: vec![],
|
||||
})
|
||||
}
|
||||
@@ -1400,7 +1463,11 @@ impl crate::Device for super::Device {
|
||||
|
||||
// Setup pipeline color attachments
|
||||
for (i, ct) in desc.color_targets.iter().enumerate() {
|
||||
let at_descriptor = descriptor.color_attachments().object_at(i as u64).unwrap();
|
||||
let at_descriptor = unsafe {
|
||||
descriptor
|
||||
.color_attachments()
|
||||
.object_at_indexed_subscript(i)
|
||||
};
|
||||
let ct = if let Some(color_target) = ct.as_ref() {
|
||||
color_target
|
||||
} else {
|
||||
@@ -1440,7 +1507,7 @@ impl crate::Device for super::Device {
|
||||
}
|
||||
|
||||
let ds_descriptor = create_depth_stencil_desc(ds);
|
||||
let raw = self.shared.device.new_depth_stencil_state(&ds_descriptor);
|
||||
let raw = self.shared.device.new_depth_stencil_state_with_descriptor(&ds_descriptor).unwrap();
|
||||
Some((raw, ds.bias))
|
||||
}
|
||||
None => None,
|
||||
@@ -1451,10 +1518,11 @@ impl crate::Device for super::Device {
|
||||
//TODO: handle sample mask
|
||||
match descriptor {
|
||||
MetalGenericRenderPipelineDescriptor::Standard(ref inner) => {
|
||||
inner.set_sample_count(desc.multisample.count as u64);
|
||||
#[allow(deprecated)]
|
||||
inner.set_sample_count(desc.multisample.count as _);
|
||||
}
|
||||
MetalGenericRenderPipelineDescriptor::Mesh(ref inner) => {
|
||||
inner.set_raster_sample_count(desc.multisample.count as u64);
|
||||
unsafe { inner.set_raster_sample_count(desc.multisample.count as _) };
|
||||
}
|
||||
}
|
||||
descriptor
|
||||
@@ -1464,19 +1532,27 @@ impl crate::Device for super::Device {
|
||||
|
||||
// Set debug label
|
||||
if let Some(name) = desc.label {
|
||||
descriptor.set_label(name);
|
||||
descriptor.set_label(Some(&NSString::from_str(name)));
|
||||
}
|
||||
if let Some(mv) = desc.multiview_mask {
|
||||
descriptor.set_max_vertex_amplification_count(mv.get().count_ones() as u64);
|
||||
unsafe {
|
||||
descriptor.set_max_vertex_amplification_count(mv.get().count_ones() as usize)
|
||||
};
|
||||
}
|
||||
|
||||
// Create the pipeline from descriptor
|
||||
let raw = match descriptor {
|
||||
MetalGenericRenderPipelineDescriptor::Standard(d) => {
|
||||
self.shared.device.new_render_pipeline_state(&d)
|
||||
}
|
||||
MetalGenericRenderPipelineDescriptor::Standard(d) => self
|
||||
.shared
|
||||
.device
|
||||
.new_render_pipeline_state_with_descriptor_error(&d),
|
||||
MetalGenericRenderPipelineDescriptor::Mesh(d) => {
|
||||
self.shared.device.new_mesh_render_pipeline_state(&d)
|
||||
// TODO: `newRenderPipelineStateWithMeshDescriptor:error:` is not exposed on
|
||||
// `MTLDevice`, is this always correct?
|
||||
let device = &self.shared.device;
|
||||
unsafe {
|
||||
msg_send![device, newRenderPipelineStateWithMeshDescriptor: &*d, error: _]
|
||||
}
|
||||
}
|
||||
}
|
||||
.map_err(|e| {
|
||||
@@ -1524,19 +1600,19 @@ impl crate::Device for super::Device {
|
||||
super::PipelineCache,
|
||||
>,
|
||||
) -> Result<super::ComputePipeline, crate::PipelineError> {
|
||||
objc::rc::autoreleasepool(|| {
|
||||
let descriptor = metal::ComputePipelineDescriptor::new();
|
||||
autoreleasepool(|_| {
|
||||
let descriptor = MTLComputePipelineDescriptor::new();
|
||||
|
||||
let module = desc.stage.module;
|
||||
let cs = if let ShaderModuleSource::Passthrough(desc) = &module.source {
|
||||
CompiledShader {
|
||||
library: desc.library.clone(),
|
||||
function: desc.function.clone(),
|
||||
wg_size: MTLSize::new(
|
||||
desc.num_workgroups.0 as u64,
|
||||
desc.num_workgroups.1 as u64,
|
||||
desc.num_workgroups.2 as u64,
|
||||
),
|
||||
wg_size: MTLSize {
|
||||
width: desc.num_workgroups.0 as usize,
|
||||
height: desc.num_workgroups.1 as usize,
|
||||
depth: desc.num_workgroups.2 as usize,
|
||||
},
|
||||
wg_memory_sizes: vec![],
|
||||
sized_bindings: vec![],
|
||||
immutable_buffer_mask: 0,
|
||||
@@ -1554,10 +1630,7 @@ impl crate::Device for super::Device {
|
||||
descriptor.set_compute_function(Some(&cs.function));
|
||||
|
||||
if self.shared.private_caps.supports_mutability {
|
||||
Self::set_buffers_mutability(
|
||||
descriptor.buffers().unwrap(),
|
||||
cs.immutable_buffer_mask,
|
||||
);
|
||||
Self::set_buffers_mutability(&descriptor.buffers(), cs.immutable_buffer_mask);
|
||||
}
|
||||
|
||||
let cs_info = super::PipelineStageInfo {
|
||||
@@ -1571,14 +1644,18 @@ impl crate::Device for super::Device {
|
||||
};
|
||||
|
||||
if let Some(name) = desc.label {
|
||||
descriptor.set_label(name);
|
||||
descriptor.set_label(Some(&NSString::from_str(name)));
|
||||
}
|
||||
|
||||
let raw = self
|
||||
.shared
|
||||
.device
|
||||
.new_compute_pipeline_state(&descriptor)
|
||||
.map_err(|e| {
|
||||
// TODO: `newComputePipelineStateWithDescriptor:error:` is not exposed on
|
||||
// `MTLDevice`, is this always correct?
|
||||
let device = &self.shared.device;
|
||||
let raw = unsafe {
|
||||
msg_send![device, newComputePipelineStateWithDescriptor: &*descriptor, error: _]
|
||||
};
|
||||
|
||||
let raw: Retained<ProtocolObject<dyn MTLComputePipelineState>> =
|
||||
raw.map_err(|e: Retained<NSError>| {
|
||||
crate::PipelineError::Linkage(
|
||||
wgt::ShaderStages::COMPUTE,
|
||||
format!("new_compute_pipeline_state: {e:?}"),
|
||||
@@ -1607,15 +1684,19 @@ impl crate::Device for super::Device {
|
||||
&self,
|
||||
desc: &wgt::QuerySetDescriptor<crate::Label>,
|
||||
) -> DeviceResult<super::QuerySet> {
|
||||
objc::rc::autoreleasepool(|| {
|
||||
autoreleasepool(|_| {
|
||||
match desc.ty {
|
||||
wgt::QueryType::Occlusion => {
|
||||
let size = desc.count as u64 * crate::QUERY_SIZE;
|
||||
let options = MTLResourceOptions::empty();
|
||||
//TODO: HazardTrackingModeUntracked
|
||||
let raw_buffer = self.shared.device.new_buffer(size, options);
|
||||
let raw_buffer = self
|
||||
.shared
|
||||
.device
|
||||
.new_buffer_with_length_options(size as usize, options)
|
||||
.unwrap();
|
||||
if let Some(label) = desc.label {
|
||||
raw_buffer.set_label(label);
|
||||
raw_buffer.set_label(Some(&NSString::from_str(label)));
|
||||
}
|
||||
Ok(super::QuerySet {
|
||||
raw_buffer,
|
||||
@@ -1626,28 +1707,32 @@ impl crate::Device for super::Device {
|
||||
wgt::QueryType::Timestamp => {
|
||||
let size = desc.count as u64 * crate::QUERY_SIZE;
|
||||
let device = &self.shared.device;
|
||||
let destination_buffer = device.new_buffer(size, MTLResourceOptions::empty());
|
||||
let destination_buffer = device
|
||||
.new_buffer_with_length_options(size as usize, MTLResourceOptions::empty())
|
||||
.unwrap();
|
||||
|
||||
let csb_desc = metal::CounterSampleBufferDescriptor::new();
|
||||
let csb_desc = MTLCounterSampleBufferDescriptor::new();
|
||||
csb_desc.set_storage_mode(MTLStorageMode::Shared);
|
||||
csb_desc.set_sample_count(desc.count as _);
|
||||
unsafe { csb_desc.set_sample_count(desc.count as _) };
|
||||
if let Some(label) = desc.label {
|
||||
csb_desc.set_label(label);
|
||||
csb_desc.set_label(&NSString::from_str(label));
|
||||
}
|
||||
|
||||
let counter_sets = device.counter_sets();
|
||||
let timestamp_counter =
|
||||
match counter_sets.iter().find(|cs| cs.name() == "timestamp") {
|
||||
Some(counter) => counter,
|
||||
None => {
|
||||
log::error!("Failed to obtain timestamp counter set.");
|
||||
return Err(crate::DeviceError::Unexpected);
|
||||
}
|
||||
};
|
||||
csb_desc.set_counter_set(timestamp_counter);
|
||||
let counter_sets = device.counter_sets().unwrap();
|
||||
let timestamp_counter = match counter_sets
|
||||
.iter()
|
||||
.find(|cs| &*cs.name() == ns_string!("timestamp"))
|
||||
{
|
||||
Some(counter) => counter,
|
||||
None => {
|
||||
log::error!("Failed to obtain timestamp counter set.");
|
||||
return Err(crate::DeviceError::Unexpected);
|
||||
}
|
||||
};
|
||||
csb_desc.set_counter_set(Some(×tamp_counter));
|
||||
|
||||
let counter_sample_buffer =
|
||||
match device.new_counter_sample_buffer_with_descriptor(&csb_desc) {
|
||||
match device.new_counter_sample_buffer_with_descriptor_error(&csb_desc) {
|
||||
Ok(buffer) => buffer,
|
||||
Err(err) => {
|
||||
log::error!("Failed to create counter sample buffer: {err:?}");
|
||||
@@ -1677,7 +1762,7 @@ impl crate::Device for super::Device {
|
||||
unsafe fn create_fence(&self) -> DeviceResult<super::Fence> {
|
||||
self.counters.fences.add(1);
|
||||
let shared_event = if self.shared.private_caps.supports_shared_event {
|
||||
Some(self.shared.device.new_shared_event())
|
||||
Some(self.shared.device.new_shared_event().unwrap())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -1742,16 +1827,17 @@ impl crate::Device for super::Device {
|
||||
return false;
|
||||
}
|
||||
let device = &self.shared.device;
|
||||
let shared_capture_manager = metal::CaptureManager::shared();
|
||||
let shared_capture_manager = unsafe { MTLCaptureManager::shared_capture_manager() };
|
||||
let default_capture_scope = shared_capture_manager.new_capture_scope_with_device(device);
|
||||
shared_capture_manager.set_default_capture_scope(&default_capture_scope);
|
||||
shared_capture_manager.set_default_capture_scope(Some(&default_capture_scope));
|
||||
#[allow(deprecated)]
|
||||
shared_capture_manager.start_capture_with_scope(&default_capture_scope);
|
||||
default_capture_scope.begin_scope();
|
||||
true
|
||||
}
|
||||
|
||||
unsafe fn stop_graphics_debugger_capture(&self) {
|
||||
let shared_capture_manager = metal::CaptureManager::shared();
|
||||
let shared_capture_manager = unsafe { MTLCaptureManager::shared_capture_manager() };
|
||||
if let Some(default_capture_scope) = shared_capture_manager.default_capture_scope() {
|
||||
default_capture_scope.end_scope();
|
||||
}
|
||||
|
||||
+120
-135
@@ -25,20 +25,32 @@ mod device;
|
||||
mod surface;
|
||||
mod time;
|
||||
|
||||
use alloc::{borrow::ToOwned as _, string::String, sync::Arc, vec::Vec};
|
||||
use alloc::{
|
||||
string::{String, ToString as _},
|
||||
sync::Arc,
|
||||
vec::Vec,
|
||||
};
|
||||
use core::{fmt, iter, ops, ptr::NonNull, sync::atomic};
|
||||
|
||||
use arrayvec::ArrayVec;
|
||||
use bitflags::bitflags;
|
||||
use hashbrown::HashMap;
|
||||
use metal::{
|
||||
foreign_types::{ForeignType as _, ForeignTypeRef as _},
|
||||
MTLArgumentBuffersTier, MTLBuffer, MTLCommandBufferStatus, MTLCullMode, MTLDepthClipMode,
|
||||
MTLIndexType, MTLLanguageVersion, MTLPrimitiveType, MTLReadWriteTextureTier, MTLRenderStages,
|
||||
MTLResource, MTLResourceUsage, MTLSamplerState, MTLSize, MTLTexture, MTLTextureType,
|
||||
MTLTriangleFillMode, MTLWinding,
|
||||
};
|
||||
use naga::FastHashMap;
|
||||
use objc2::{
|
||||
rc::{autoreleasepool, Retained},
|
||||
runtime::ProtocolObject,
|
||||
};
|
||||
use objc2_foundation::ns_string;
|
||||
use objc2_metal::{
|
||||
MTLArgumentBuffersTier, MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer,
|
||||
MTLCommandBufferStatus, MTLCommandQueue, MTLComputeCommandEncoder, MTLComputePipelineState,
|
||||
MTLCounterSampleBuffer, MTLCullMode, MTLDepthClipMode, MTLDepthStencilState, MTLDevice,
|
||||
MTLDrawable, MTLFunction, MTLIndexType, MTLLanguageVersion, MTLLibrary, MTLPrimitiveType,
|
||||
MTLReadWriteTextureTier, MTLRenderCommandEncoder, MTLRenderPipelineState, MTLRenderStages,
|
||||
MTLResource, MTLResourceUsage, MTLSamplerState, MTLSharedEvent, MTLSize, MTLTexture,
|
||||
MTLTextureType, MTLTriangleFillMode, MTLWinding,
|
||||
};
|
||||
use objc2_quartz_core::CAMetalLayer;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -105,7 +117,7 @@ crate::impl_dyn_resource!(
|
||||
pub struct Instance {}
|
||||
|
||||
impl Instance {
|
||||
pub fn create_surface_from_layer(&self, layer: &metal::MetalLayerRef) -> Surface {
|
||||
pub fn create_surface_from_layer(&self, layer: &CAMetalLayer) -> Surface {
|
||||
Surface::from_layer(layer)
|
||||
}
|
||||
}
|
||||
@@ -140,8 +152,10 @@ impl crate::Instance for Instance {
|
||||
};
|
||||
|
||||
// SAFETY: The layer is an initialized instance of `CAMetalLayer`, and
|
||||
// we transfer the retain count to `MetalLayer` using `into_raw`.
|
||||
let layer = unsafe { metal::MetalLayer::from_ptr(layer.into_raw().cast().as_ptr()) };
|
||||
// we transfer the retain count to `Retained` using `into_raw`.
|
||||
let layer = unsafe {
|
||||
Retained::from_raw(layer.into_raw().cast::<CAMetalLayer>().as_ptr()).unwrap()
|
||||
};
|
||||
|
||||
Ok(Surface::new(layer))
|
||||
}
|
||||
@@ -150,11 +164,11 @@ impl crate::Instance for Instance {
|
||||
&self,
|
||||
_surface_hint: Option<&Surface>,
|
||||
) -> Vec<crate::ExposedAdapter<Api>> {
|
||||
let devices = metal::Device::all();
|
||||
let devices = objc2_metal::MTLCopyAllDevices();
|
||||
let mut adapters: Vec<crate::ExposedAdapter<Api>> = devices
|
||||
.into_iter()
|
||||
.map(|dev| {
|
||||
let name = dev.name().into();
|
||||
let name = dev.name().to_string();
|
||||
let shared = AdapterShared::new(dev);
|
||||
crate::ExposedAdapter {
|
||||
info: wgt::AdapterInfo {
|
||||
@@ -353,7 +367,7 @@ impl Default for Settings {
|
||||
}
|
||||
|
||||
struct AdapterShared {
|
||||
device: metal::Device,
|
||||
device: Retained<ProtocolObject<dyn MTLDevice>>,
|
||||
disabilities: PrivateDisabilities,
|
||||
private_caps: PrivateCapabilities,
|
||||
settings: Settings,
|
||||
@@ -364,7 +378,7 @@ unsafe impl Send for AdapterShared {}
|
||||
unsafe impl Sync for AdapterShared {}
|
||||
|
||||
impl AdapterShared {
|
||||
fn new(device: metal::Device) -> Self {
|
||||
fn new(device: Retained<ProtocolObject<dyn MTLDevice>>) -> Self {
|
||||
let private_caps = PrivateCapabilities::new(&device);
|
||||
log::debug!("{private_caps:#?}");
|
||||
|
||||
@@ -383,7 +397,7 @@ pub struct Adapter {
|
||||
}
|
||||
|
||||
pub struct Queue {
|
||||
raw: Arc<Mutex<metal::CommandQueue>>,
|
||||
raw: Arc<Mutex<Retained<ProtocolObject<dyn MTLCommandQueue>>>>,
|
||||
timestamp_period: f32,
|
||||
}
|
||||
|
||||
@@ -391,14 +405,17 @@ unsafe impl Send for Queue {}
|
||||
unsafe impl Sync for Queue {}
|
||||
|
||||
impl Queue {
|
||||
pub unsafe fn queue_from_raw(raw: metal::CommandQueue, timestamp_period: f32) -> Self {
|
||||
pub unsafe fn queue_from_raw(
|
||||
raw: Retained<ProtocolObject<dyn MTLCommandQueue>>,
|
||||
timestamp_period: f32,
|
||||
) -> Self {
|
||||
Self {
|
||||
raw: Arc::new(Mutex::new(raw)),
|
||||
timestamp_period,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_raw(&self) -> &Arc<Mutex<metal::CommandQueue>> {
|
||||
pub fn as_raw(&self) -> &Arc<Mutex<Retained<ProtocolObject<dyn MTLCommandQueue>>>> {
|
||||
&self.raw
|
||||
}
|
||||
}
|
||||
@@ -410,7 +427,7 @@ pub struct Device {
|
||||
}
|
||||
|
||||
pub struct Surface {
|
||||
render_layer: Mutex<metal::MetalLayer>,
|
||||
render_layer: Mutex<Retained<CAMetalLayer>>,
|
||||
swapchain_format: RwLock<Option<wgt::TextureFormat>>,
|
||||
extent: RwLock<wgt::Extent3d>,
|
||||
}
|
||||
@@ -421,9 +438,9 @@ unsafe impl Sync for Surface {}
|
||||
#[derive(Debug)]
|
||||
pub struct SurfaceTexture {
|
||||
texture: Texture,
|
||||
drawable: metal::MetalDrawable,
|
||||
// Useful for UI-intensive applications that are sensitive to
|
||||
// window resizing.
|
||||
drawable: Retained<ProtocolObject<dyn MTLDrawable>>,
|
||||
present_with_transaction: bool,
|
||||
}
|
||||
|
||||
@@ -453,33 +470,30 @@ impl crate::Queue for Queue {
|
||||
_surface_textures: &[&SurfaceTexture],
|
||||
(signal_fence, signal_value): (&mut Fence, crate::FenceValue),
|
||||
) -> Result<(), crate::DeviceError> {
|
||||
objc::rc::autoreleasepool(|| {
|
||||
autoreleasepool(|_| {
|
||||
let extra_command_buffer = {
|
||||
let completed_value = Arc::clone(&signal_fence.completed_value);
|
||||
let block = block::ConcreteBlock::new(move |_cmd_buf| {
|
||||
let block = block2::RcBlock::new(move |_cmd_buf| {
|
||||
completed_value.store(signal_value, atomic::Ordering::Release);
|
||||
})
|
||||
.copy();
|
||||
});
|
||||
|
||||
let raw = match command_buffers.last() {
|
||||
Some(&cmd_buf) => cmd_buf.raw.to_owned(),
|
||||
Some(&cmd_buf) => cmd_buf.raw.clone(),
|
||||
None => {
|
||||
let queue = self.raw.lock();
|
||||
queue
|
||||
.new_command_buffer_with_unretained_references()
|
||||
.to_owned()
|
||||
queue.command_buffer_with_unretained_references().unwrap()
|
||||
}
|
||||
};
|
||||
raw.set_label("(wgpu internal) Signal");
|
||||
raw.add_completed_handler(&block);
|
||||
raw.set_label(Some(ns_string!("(wgpu internal) Signal")));
|
||||
unsafe { raw.add_completed_handler(block2::RcBlock::as_ptr(&block)) };
|
||||
|
||||
signal_fence.maintain();
|
||||
signal_fence
|
||||
.pending_command_buffers
|
||||
.push((signal_value, raw.to_owned()));
|
||||
.push((signal_value, raw.clone()));
|
||||
|
||||
if let Some(shared_event) = signal_fence.shared_event.as_ref() {
|
||||
raw.encode_signal_event(shared_event, signal_value);
|
||||
if let Some(shared_event) = &signal_fence.shared_event {
|
||||
raw.encode_signal_event_value(shared_event.as_ref(), signal_value);
|
||||
}
|
||||
// only return an extra one if it's extra
|
||||
match command_buffers.last() {
|
||||
@@ -504,9 +518,9 @@ impl crate::Queue for Queue {
|
||||
texture: SurfaceTexture,
|
||||
) -> Result<(), crate::SurfaceError> {
|
||||
let queue = &self.raw.lock();
|
||||
objc::rc::autoreleasepool(|| {
|
||||
let command_buffer = queue.new_command_buffer();
|
||||
command_buffer.set_label("(wgpu internal) Present");
|
||||
autoreleasepool(|_| {
|
||||
let command_buffer = queue.command_buffer().unwrap();
|
||||
command_buffer.set_label(Some(ns_string!("(wgpu internal) Present")));
|
||||
|
||||
// https://developer.apple.com/documentation/quartzcore/cametallayer/1478157-presentswithtransaction?language=objc
|
||||
if !texture.present_with_transaction {
|
||||
@@ -530,7 +544,7 @@ impl crate::Queue for Queue {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Buffer {
|
||||
raw: metal::Buffer,
|
||||
raw: Retained<ProtocolObject<dyn MTLBuffer>>,
|
||||
size: wgt::BufferAddress,
|
||||
}
|
||||
|
||||
@@ -540,8 +554,8 @@ unsafe impl Sync for Buffer {}
|
||||
impl crate::DynBuffer for Buffer {}
|
||||
|
||||
impl Buffer {
|
||||
fn as_raw(&self) -> BufferPtr {
|
||||
unsafe { NonNull::new_unchecked(self.raw.as_ptr()) }
|
||||
fn as_raw(&self) -> NonNull<ProtocolObject<dyn MTLBuffer>> {
|
||||
unsafe { NonNull::new_unchecked(Retained::as_ptr(&self.raw) as *mut _) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -556,7 +570,7 @@ impl crate::BufferBinding<'_, Buffer> {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Texture {
|
||||
raw: metal::Texture,
|
||||
raw: Retained<ProtocolObject<dyn MTLTexture>>,
|
||||
format: wgt::TextureFormat,
|
||||
raw_type: MTLTextureType,
|
||||
array_layers: u32,
|
||||
@@ -565,10 +579,7 @@ pub struct Texture {
|
||||
}
|
||||
|
||||
impl Texture {
|
||||
/// # Safety
|
||||
///
|
||||
/// - The texture handle must not be manually destroyed
|
||||
pub unsafe fn raw_handle(&self) -> &metal::Texture {
|
||||
pub fn raw_handle(&self) -> &ProtocolObject<dyn MTLTexture> {
|
||||
&self.raw
|
||||
}
|
||||
}
|
||||
@@ -580,7 +591,7 @@ unsafe impl Sync for Texture {}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TextureView {
|
||||
raw: metal::Texture,
|
||||
raw: Retained<ProtocolObject<dyn MTLTexture>>,
|
||||
aspects: crate::FormatAspects,
|
||||
}
|
||||
|
||||
@@ -590,14 +601,14 @@ unsafe impl Send for TextureView {}
|
||||
unsafe impl Sync for TextureView {}
|
||||
|
||||
impl TextureView {
|
||||
fn as_raw(&self) -> TexturePtr {
|
||||
unsafe { NonNull::new_unchecked(self.raw.as_ptr()) }
|
||||
fn as_raw(&self) -> NonNull<ProtocolObject<dyn MTLTexture>> {
|
||||
unsafe { NonNull::new_unchecked(Retained::as_ptr(&self.raw) as *mut _) }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Sampler {
|
||||
raw: metal::SamplerState,
|
||||
raw: Retained<ProtocolObject<dyn MTLSamplerState>>,
|
||||
}
|
||||
|
||||
impl crate::DynSampler for Sampler {}
|
||||
@@ -606,8 +617,8 @@ unsafe impl Send for Sampler {}
|
||||
unsafe impl Sync for Sampler {}
|
||||
|
||||
impl Sampler {
|
||||
fn as_raw(&self) -> SamplerPtr {
|
||||
unsafe { NonNull::new_unchecked(self.raw.as_ptr()) }
|
||||
fn as_raw(&self) -> NonNull<ProtocolObject<dyn MTLSamplerState>> {
|
||||
unsafe { NonNull::new_unchecked(Retained::as_ptr(&self.raw) as *mut _) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -716,68 +727,9 @@ pub struct PipelineLayout {
|
||||
|
||||
impl crate::DynPipelineLayout for PipelineLayout {}
|
||||
|
||||
trait AsNative {
|
||||
type Native;
|
||||
fn from(native: &Self::Native) -> Self;
|
||||
fn as_native(&self) -> &Self::Native;
|
||||
}
|
||||
|
||||
type ResourcePtr = NonNull<MTLResource>;
|
||||
type BufferPtr = NonNull<MTLBuffer>;
|
||||
type TexturePtr = NonNull<MTLTexture>;
|
||||
type SamplerPtr = NonNull<MTLSamplerState>;
|
||||
|
||||
impl AsNative for ResourcePtr {
|
||||
type Native = metal::ResourceRef;
|
||||
#[inline]
|
||||
fn from(native: &Self::Native) -> Self {
|
||||
unsafe { NonNull::new_unchecked(native.as_ptr()) }
|
||||
}
|
||||
#[inline]
|
||||
fn as_native(&self) -> &Self::Native {
|
||||
unsafe { Self::Native::from_ptr(self.as_ptr()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl AsNative for BufferPtr {
|
||||
type Native = metal::BufferRef;
|
||||
#[inline]
|
||||
fn from(native: &Self::Native) -> Self {
|
||||
unsafe { NonNull::new_unchecked(native.as_ptr()) }
|
||||
}
|
||||
#[inline]
|
||||
fn as_native(&self) -> &Self::Native {
|
||||
unsafe { Self::Native::from_ptr(self.as_ptr()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl AsNative for TexturePtr {
|
||||
type Native = metal::TextureRef;
|
||||
#[inline]
|
||||
fn from(native: &Self::Native) -> Self {
|
||||
unsafe { NonNull::new_unchecked(native.as_ptr()) }
|
||||
}
|
||||
#[inline]
|
||||
fn as_native(&self) -> &Self::Native {
|
||||
unsafe { Self::Native::from_ptr(self.as_ptr()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl AsNative for SamplerPtr {
|
||||
type Native = metal::SamplerStateRef;
|
||||
#[inline]
|
||||
fn from(native: &Self::Native) -> Self {
|
||||
unsafe { NonNull::new_unchecked(native.as_ptr()) }
|
||||
}
|
||||
#[inline]
|
||||
fn as_native(&self) -> &Self::Native {
|
||||
unsafe { Self::Native::from_ptr(self.as_ptr()) }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct BufferResource {
|
||||
ptr: BufferPtr,
|
||||
ptr: NonNull<ProtocolObject<dyn MTLBuffer>>,
|
||||
offset: wgt::BufferAddress,
|
||||
dynamic_index: Option<u32>,
|
||||
|
||||
@@ -815,11 +767,11 @@ impl Default for UseResourceInfo {
|
||||
pub struct BindGroup {
|
||||
counters: MultiStageResourceCounters,
|
||||
buffers: Vec<BufferResource>,
|
||||
samplers: Vec<SamplerPtr>,
|
||||
textures: Vec<TexturePtr>,
|
||||
samplers: Vec<NonNull<ProtocolObject<dyn MTLSamplerState>>>,
|
||||
textures: Vec<NonNull<ProtocolObject<dyn MTLTexture>>>,
|
||||
|
||||
argument_buffers: Vec<metal::Buffer>,
|
||||
resources_to_use: HashMap<ResourcePtr, UseResourceInfo>,
|
||||
argument_buffers: Vec<Retained<ProtocolObject<dyn MTLBuffer>>>,
|
||||
resources_to_use: HashMap<NonNull<ProtocolObject<dyn MTLResource>>, UseResourceInfo>,
|
||||
}
|
||||
|
||||
impl crate::DynBindGroup for BindGroup {}
|
||||
@@ -835,12 +787,15 @@ pub enum ShaderModuleSource {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PassthroughShader {
|
||||
pub library: metal::Library,
|
||||
pub function: metal::Function,
|
||||
pub library: Retained<ProtocolObject<dyn MTLLibrary>>,
|
||||
pub function: Retained<ProtocolObject<dyn MTLFunction>>,
|
||||
pub entry_point: String,
|
||||
pub num_workgroups: (u32, u32, u32),
|
||||
}
|
||||
|
||||
unsafe impl Send for PassthroughShader {}
|
||||
unsafe impl Sync for PassthroughShader {}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ShaderModule {
|
||||
source: ShaderModuleSource,
|
||||
@@ -849,10 +804,10 @@ pub struct ShaderModule {
|
||||
|
||||
impl crate::DynShaderModule for ShaderModule {}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
#[derive(Debug)]
|
||||
struct PipelineStageInfo {
|
||||
#[allow(dead_code)]
|
||||
library: Option<metal::Library>,
|
||||
library: Option<Retained<ProtocolObject<dyn MTLLibrary>>>,
|
||||
immediates: Option<ImmediateDataInfo>,
|
||||
|
||||
/// The buffer argument table index at which we pass runtime-sized arrays' buffer sizes.
|
||||
@@ -875,6 +830,26 @@ struct PipelineStageInfo {
|
||||
work_group_memory_sizes: Vec<u32>,
|
||||
}
|
||||
|
||||
// TODO(madsmtm): Derive this when a release with
|
||||
// https://github.com/madsmtm/objc2/issues/804 is available (likely 0.4).
|
||||
impl Default for PipelineStageInfo {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
library: Default::default(),
|
||||
immediates: Default::default(),
|
||||
sizes_slot: Default::default(),
|
||||
sized_bindings: Default::default(),
|
||||
vertex_buffer_mappings: Default::default(),
|
||||
raw_wg_size: MTLSize {
|
||||
width: 0,
|
||||
height: 0,
|
||||
depth: 0,
|
||||
},
|
||||
work_group_memory_sizes: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PipelineStageInfo {
|
||||
fn clear(&mut self) {
|
||||
self.immediates = None;
|
||||
@@ -883,7 +858,11 @@ impl PipelineStageInfo {
|
||||
self.vertex_buffer_mappings.clear();
|
||||
self.library = None;
|
||||
self.work_group_memory_sizes.clear();
|
||||
self.raw_wg_size = Default::default();
|
||||
self.raw_wg_size = MTLSize {
|
||||
width: 0,
|
||||
height: 0,
|
||||
depth: 0,
|
||||
};
|
||||
}
|
||||
|
||||
fn assign_from(&mut self, other: &Self) {
|
||||
@@ -904,7 +883,7 @@ impl PipelineStageInfo {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RenderPipeline {
|
||||
raw: metal::RenderPipelineState,
|
||||
raw: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
|
||||
vs_info: Option<PipelineStageInfo>,
|
||||
fs_info: Option<PipelineStageInfo>,
|
||||
ts_info: Option<PipelineStageInfo>,
|
||||
@@ -914,7 +893,10 @@ pub struct RenderPipeline {
|
||||
raw_front_winding: MTLWinding,
|
||||
raw_cull_mode: MTLCullMode,
|
||||
raw_depth_clip_mode: Option<MTLDepthClipMode>,
|
||||
depth_stencil: Option<(metal::DepthStencilState, wgt::DepthBiasState)>,
|
||||
depth_stencil: Option<(
|
||||
Retained<ProtocolObject<dyn MTLDepthStencilState>>,
|
||||
wgt::DepthBiasState,
|
||||
)>,
|
||||
}
|
||||
|
||||
unsafe impl Send for RenderPipeline {}
|
||||
@@ -924,7 +906,7 @@ impl crate::DynRenderPipeline for RenderPipeline {}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ComputePipeline {
|
||||
raw: metal::ComputePipelineState,
|
||||
raw: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
|
||||
cs_info: PipelineStageInfo,
|
||||
}
|
||||
|
||||
@@ -935,9 +917,9 @@ impl crate::DynComputePipeline for ComputePipeline {}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct QuerySet {
|
||||
raw_buffer: metal::Buffer,
|
||||
raw_buffer: Retained<ProtocolObject<dyn MTLBuffer>>,
|
||||
//Metal has a custom buffer for counters.
|
||||
counter_sample_buffer: Option<metal::CounterSampleBuffer>,
|
||||
counter_sample_buffer: Option<Retained<ProtocolObject<dyn MTLCounterSampleBuffer>>>,
|
||||
ty: wgt::QueryType,
|
||||
}
|
||||
|
||||
@@ -950,8 +932,11 @@ unsafe impl Sync for QuerySet {}
|
||||
pub struct Fence {
|
||||
completed_value: Arc<atomic::AtomicU64>,
|
||||
/// The pending fence values have to be ascending.
|
||||
pending_command_buffers: Vec<(crate::FenceValue, metal::CommandBuffer)>,
|
||||
shared_event: Option<metal::SharedEvent>,
|
||||
pending_command_buffers: Vec<(
|
||||
crate::FenceValue,
|
||||
Retained<ProtocolObject<dyn MTLCommandBuffer>>,
|
||||
)>,
|
||||
shared_event: Option<Retained<ProtocolObject<dyn MTLSharedEvent>>>,
|
||||
}
|
||||
|
||||
impl crate::DynFence for Fence {}
|
||||
@@ -976,13 +961,13 @@ impl Fence {
|
||||
.retain(|&(value, _)| value > latest);
|
||||
}
|
||||
|
||||
pub fn raw_shared_event(&self) -> Option<&metal::SharedEvent> {
|
||||
self.shared_event.as_ref()
|
||||
pub fn raw_shared_event(&self) -> Option<&ProtocolObject<dyn MTLSharedEvent>> {
|
||||
self.shared_event.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
struct IndexState {
|
||||
buffer_ptr: BufferPtr,
|
||||
buffer_ptr: NonNull<ProtocolObject<dyn MTLBuffer>>,
|
||||
offset: wgt::BufferAddress,
|
||||
stride: wgt::BufferAddress,
|
||||
raw_type: MTLIndexType,
|
||||
@@ -994,9 +979,9 @@ struct Temp {
|
||||
}
|
||||
|
||||
struct CommandState {
|
||||
blit: Option<metal::BlitCommandEncoder>,
|
||||
render: Option<metal::RenderCommandEncoder>,
|
||||
compute: Option<metal::ComputeCommandEncoder>,
|
||||
blit: Option<Retained<ProtocolObject<dyn MTLBlitCommandEncoder>>>,
|
||||
render: Option<Retained<ProtocolObject<dyn MTLRenderCommandEncoder>>>,
|
||||
compute: Option<Retained<ProtocolObject<dyn MTLComputeCommandEncoder>>>,
|
||||
raw_primitive_type: MTLPrimitiveType,
|
||||
index: Option<IndexState>,
|
||||
stage_infos: MultiStageData<PipelineStageInfo>,
|
||||
@@ -1032,8 +1017,8 @@ struct CommandState {
|
||||
|
||||
pub struct CommandEncoder {
|
||||
shared: Arc<AdapterShared>,
|
||||
raw_queue: Arc<Mutex<metal::CommandQueue>>,
|
||||
raw_cmd_buf: Option<metal::CommandBuffer>,
|
||||
raw_queue: Arc<Mutex<Retained<ProtocolObject<dyn MTLCommandQueue>>>>,
|
||||
raw_cmd_buf: Option<Retained<ProtocolObject<dyn MTLCommandBuffer>>>,
|
||||
state: CommandState,
|
||||
temp: Temp,
|
||||
counters: Arc<wgt::HalCounters>,
|
||||
@@ -1053,7 +1038,7 @@ unsafe impl Sync for CommandEncoder {}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CommandBuffer {
|
||||
raw: metal::CommandBuffer,
|
||||
raw: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
|
||||
}
|
||||
|
||||
impl crate::DynCommandBuffer for CommandBuffer {}
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
#![allow(clippy::let_unit_value)] // `let () =` being used to constrain result type
|
||||
|
||||
use alloc::borrow::ToOwned as _;
|
||||
|
||||
use core_graphics_types::{
|
||||
base::CGFloat,
|
||||
geometry::{CGRect, CGSize},
|
||||
};
|
||||
use metal::MTLTextureType;
|
||||
use objc::{
|
||||
class, msg_send,
|
||||
rc::autoreleasepool,
|
||||
runtime::{BOOL, YES},
|
||||
sel, sel_impl,
|
||||
use objc2::{
|
||||
rc::{autoreleasepool, Retained},
|
||||
runtime::ProtocolObject,
|
||||
ClassType, Message,
|
||||
};
|
||||
use objc2_core_foundation::CGSize;
|
||||
use objc2_foundation::NSObjectProtocol;
|
||||
use objc2_metal::MTLTextureType;
|
||||
use objc2_quartz_core::{CAMetalDrawable, CAMetalLayer};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
|
||||
impl super::Surface {
|
||||
pub fn new(layer: metal::MetalLayer) -> Self {
|
||||
pub fn new(layer: Retained<CAMetalLayer>) -> Self {
|
||||
Self {
|
||||
render_layer: Mutex::new(layer),
|
||||
swapchain_format: RwLock::new(None),
|
||||
@@ -24,14 +20,12 @@ impl super::Surface {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_layer(layer: &metal::MetalLayerRef) -> Self {
|
||||
let class = class!(CAMetalLayer);
|
||||
let proper_kind: BOOL = unsafe { msg_send![layer, isKindOfClass: class] };
|
||||
assert_eq!(proper_kind, YES);
|
||||
Self::new(layer.to_owned())
|
||||
pub fn from_layer(layer: &CAMetalLayer) -> Self {
|
||||
assert!(layer.isKindOfClass(CAMetalLayer::class()));
|
||||
Self::new(layer.retain())
|
||||
}
|
||||
|
||||
pub fn render_layer(&self) -> &Mutex<metal::MetalLayer> {
|
||||
pub fn render_layer(&self) -> &Mutex<Retained<CAMetalLayer>> {
|
||||
&self.render_layer
|
||||
}
|
||||
|
||||
@@ -43,11 +37,10 @@ impl super::Surface {
|
||||
/// of sync. This is sound, as these properties are accessed atomically.
|
||||
/// See: <https://github.com/gfx-rs/wgpu/pull/7692>
|
||||
pub(super) fn dimensions(&self) -> wgt::Extent3d {
|
||||
let (size, scale): (CGSize, CGFloat) = unsafe {
|
||||
let render_layer_borrow = self.render_layer.lock();
|
||||
let render_layer = render_layer_borrow.as_ref();
|
||||
let bounds: CGRect = msg_send![render_layer, bounds];
|
||||
let contents_scale: CGFloat = msg_send![render_layer, contentsScale];
|
||||
let (size, scale) = {
|
||||
let render_layer = self.render_layer.lock();
|
||||
let bounds = render_layer.bounds();
|
||||
let contents_scale = render_layer.contents_scale();
|
||||
(bounds.size, contents_scale)
|
||||
};
|
||||
|
||||
@@ -89,7 +82,7 @@ impl crate::Surface for super::Surface {
|
||||
}
|
||||
|
||||
let device_raw = &device.shared.device;
|
||||
render_layer.set_device(device_raw);
|
||||
render_layer.set_device(Some(device_raw));
|
||||
render_layer.set_pixel_format(caps.map_format(config.format));
|
||||
render_layer.set_framebuffer_only(framebuffer_only);
|
||||
// opt-in to Metal EDR
|
||||
@@ -100,13 +93,13 @@ impl crate::Surface for super::Surface {
|
||||
}
|
||||
|
||||
// this gets ignored on iOS for certain OS/device combinations (iphone5s iOS 10.3)
|
||||
render_layer.set_maximum_drawable_count(config.maximum_frame_latency as u64 + 1);
|
||||
render_layer.set_maximum_drawable_count(config.maximum_frame_latency as usize + 1);
|
||||
render_layer.set_drawable_size(drawable_size);
|
||||
if caps.can_set_next_drawable_timeout {
|
||||
let () = msg_send![*render_layer, setAllowsNextDrawableTimeout:false];
|
||||
render_layer.set_allows_next_drawable_timeout(false);
|
||||
}
|
||||
if caps.can_set_display_sync {
|
||||
let () = msg_send![*render_layer, setDisplaySyncEnabled: display_sync];
|
||||
render_layer.set_display_sync_enabled(display_sync);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -122,7 +115,7 @@ impl crate::Surface for super::Surface {
|
||||
_fence: &super::Fence,
|
||||
) -> Result<Option<crate::AcquiredSurfaceTexture<super::Api>>, crate::SurfaceError> {
|
||||
let render_layer = self.render_layer.lock();
|
||||
let (drawable, texture) = match autoreleasepool(|| {
|
||||
let (drawable, texture) = match autoreleasepool(|_| {
|
||||
render_layer
|
||||
.next_drawable()
|
||||
.map(|drawable| (drawable.to_owned(), drawable.texture().to_owned()))
|
||||
@@ -137,7 +130,7 @@ impl crate::Surface for super::Surface {
|
||||
texture: super::Texture {
|
||||
raw: texture,
|
||||
format: swapchain_format,
|
||||
raw_type: MTLTextureType::D2,
|
||||
raw_type: MTLTextureType::Type2D,
|
||||
array_layers: 1,
|
||||
mip_levels: 1,
|
||||
copy_size: crate::CopyExtent {
|
||||
@@ -146,7 +139,7 @@ impl crate::Surface for super::Surface {
|
||||
depth: 1,
|
||||
},
|
||||
},
|
||||
drawable,
|
||||
drawable: ProtocolObject::from_retained(drawable),
|
||||
present_with_transaction: render_layer.presents_with_transaction(),
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user