Protocol

MTLDevice

The Metal interface to a GPU that you use to draw graphics or do parallel computation.

Declaration

protocol MTLDevice

Overview

The MTLDevice protocol defines the interface to a GPU. You can query a MTLDevice for the unique capabilities it offers your Metal app, and use the MTLDevice to issue all of your Metal commands. Don't implement this protocol yourself; instead, request a GPU from the system at runtime using MTLCreateSystemDefaultDevice() in iOS or tvOS, and in macOS, get a list of available MTLDevice objects using MTLCopyAllDevicesWithObserver(handler:). See Getting the Default GPU for a full discussion on choosing the right GPU(s).

MTLDevice objects are your go-to object to do anything in Metal, so all of the Metal objects your app interacts with come from the MTLDevice instances you acquire at runtime. MTLDevice-created objects are expensive but persistent; many of them are designed to be initialized once and reused through the lifetime of your app. However, these objects are specific to the MTLDevice that issued them. If you use multiple MTLDevice instances or want to switch from one MTLDevice to another, you need to create a separate set of objects for each MTLDevice.

Topics

Acquiring Device Objects

func MTLCreateSystemDefaultDevice() -> MTLDevice?

Returns a reference to the preferred default Metal device object.

func MTLCopyAllDevices() -> [MTLDevice]

Returns an array of references to all Metal device objects in the system.

func MTLCopyAllDevicesWithObserver(handler: MTLDeviceNotificationHandler) -> (devices: [MTLDevice], observer: NSObject)

Fetches the available Metal devices and registers a notification observer for changes to the list.

func MTLRemoveDeviceObserver(NSObjectProtocol)

Removes a registered observer of device notifications.

Querying GPU Properties

var name: String

The name of the device.

Required.

var isHeadless: Bool

A Boolean value that indicates whether a device is configured as headless.

Required.

var isLowPower: Bool

A Boolean value that indicates whether a device is low-power.

Required.

var isRemovable: Bool

A Boolean value that determines whether or not a GPU is removable.

Required.

var registryID: UInt64

The registry ID value for the device.

Required.

var location: MTLDeviceLocation

The physical location of the GPU relative to the host computer.

Required.

var locationNumber: Int

A more detailed specifier for the GPU's location.

Required.

var maxTransferRate: UInt64

The highest theoretical rate of transfer between system RAM and dedicated GPU memory (VRAM), measured in bytes per second.

Required.

var hasUnifiedMemory: Bool

A Boolean that indicates whether the GPU shares all of its memory with the CPU.

Required.

enum MTLDeviceLocation

Options describing possible locations for the GPU.

Finding Groups of Connected GPUs

Transferring Data Between Connected GPUs

Use high-speed connections between GPUs to transfer data quickly.

var peerGroupID: UInt64

The peer group, if any, that the GPU belongs to.

Required.

var peerCount: UInt32

The number of GPUs in the peer group.

Required.

var peerIndex: UInt32

The unique identifier for a GPU in a peer group.

Required.

Querying Features

Detecting GPU Features and Metal Software Versions

Use the device object’s properties to determine how you perform tasks in Metal.

func supportsFamily(MTLGPUFamily) -> Bool

Determines whether the device object supports the feature set of a particular GPU family.

Required.

func supportsFeatureSet(MTLFeatureSet) -> Bool

Determines whether a device supports a particular feature set.

Required.

enum MTLGPUFamily

Options for families of GPUs.

enum MTLFeatureSet

The device feature sets that define specific platform, hardware, and software configurations.

Querying Memory Availability and Limits

var recommendedMaxWorkingSetSize: UInt64

An approximation of how much memory, in bytes, this device can use with good performance.

Required.

var currentAllocatedSize: Int

The current size, in bytes, of all resources allocated on this device for this process.

Required.

var maxThreadgroupMemoryLength: Int

The maximum threadgroup memory available to a compute kernel, in bytes.

Required.

Querying Threadgroup Limits

var maxThreadsPerThreadgroup: MTLSize

The maximum number of threads along each dimension of a threadgroup.

Required.

Querying Programmable Sample Positions

var areProgrammableSamplePositionsSupported: Bool

A Boolean that indicates whether a device supports programmable sample positions.

Required.

func getDefaultSamplePositions(sampleCount: Int) -> [MTLSamplePosition]

Retrieves the default sample positions for a specific sample count.

Querying Raster Order Groups Support

var areRasterOrderGroupsSupported: Bool

A Boolean value that indicates whether a device supports raster order groups.

Required.

Querying Depth and Stencil Support

var isDepth24Stencil8PixelFormatSupported: Bool

A Boolean value that indicates whether a device supports a packed depth-and-stencil pixel format.

Required.

Querying Barycentric Coordinate Support

var areBarycentricCoordsSupported: Bool

A Boolean value indicating whether the GPU supports barycentric coordinates.

Required.

Querying Vertex Amplification Support

func supportsVertexAmplificationCount(Int) -> Bool

Determines whether a given amplification count is supported by the device object.

Required.

Creating a Command Queue

func makeCommandQueue() -> MTLCommandQueue?

Creates a command submission queue.

Required.

func makeCommandQueue(maxCommandBufferCount: Int) -> MTLCommandQueue?

Creates a command submission queue with a fixed maximum number of uncompleted command buffers.

Required.

Creating Events and Fences

func makeEvent() -> MTLEvent?

Creates a new event whose use is limited to the device object.

Required.

func makeSharedEvent() -> MTLSharedEvent?

Creates a shareable event.

Required.

func makeSharedEvent(handle: MTLSharedEventHandle) -> MTLSharedEvent?

Re-creates a shareable event from a shareable event handle.

Required.

func makeFence() -> MTLFence?

Creates a new fence.

Required.

Creating Shader Libraries

func makeDefaultLibrary() -> MTLLibrary?

Creates a library object containing the functions in the app’s default Metal library.

Required.

func makeDefaultLibrary(bundle: Bundle) -> MTLLibrary

Creates a library object containing the functions stored in the default Metal library in the specified bundle.

Required.

func makeLibrary(filepath: String) -> MTLLibrary

Creates a library object containing the functions in a Metal library file at a specified path.

Required.

func makeLibrary(URL: URL) -> MTLLibrary

Creates a library object containing the functions in a Metal library file at a specified URL.

Required.

func makeLibrary(data: __DispatchData) -> MTLLibrary

Creates a library object containing the functions stored in a binary data object created from a precompiled Metal library.

Required.

func makeLibrary(source: String, options: MTLCompileOptions?, completionHandler: MTLNewLibraryCompletionHandler)

Creates a library object asynchronously by compiling the functions stored in the specified source string.

Required.

func makeLibrary(source: String, options: MTLCompileOptions?) -> MTLLibrary

Creates a library object synchronously by compiling the functions stored in the specified source string.

Required.

Creating a Render Pipeline

Creating a Compute Pipeline

func makeComputePipelineState(descriptor: MTLComputePipelineDescriptor, options: MTLPipelineOption, completionHandler: MTLNewComputePipelineStateWithReflectionCompletionHandler)

Asynchronously creates a compute pipeline state object, and associated reflection information, using a compute pipeline descriptor.

Required.

func makeComputePipelineState(function: MTLFunction, completionHandler: MTLNewComputePipelineStateCompletionHandler)

Asynchronously creates a new compute pipeline state object using a function object.

Required.

func makeComputePipelineState(function: MTLFunction, options: MTLPipelineOption, completionHandler: MTLNewComputePipelineStateWithReflectionCompletionHandler)

Asynchronously creates a new compute pipeline state object, and associated reflection information, using a function object.

Required.

func makeComputePipelineState(function: MTLFunction) -> MTLComputePipelineState

Synchronously creates a new compute pipeline state object using a function object.

Required.

Creating Buffers

Fill buffers with arbitrary data structures that you design and send as arguments to your shader functions on the GPU.

var maxBufferLength: Int

The maximum size of a buffer, in bytes.

Required.

func makeBuffer(length: Int, options: MTLResourceOptions) -> MTLBuffer?

Allocates a new zero-filled buffer of a given length.

Required.

func makeBuffer(bytes: UnsafeRawPointer, length: Int, options: MTLResourceOptions) -> MTLBuffer?

Allocates a new buffer of a given length and initializes its contents by copying existing data into it.

Required.

Querying Texture Support

func supportsTextureSampleCount(Int) -> Bool

Determines whether a device supports a given texture sample count.

Required.

func minimumLinearTextureAlignment(for: MTLPixelFormat) -> Int

Calculates the minimum alignment required for creating a linear texture with a given pixel format.

Required.

func minimumTextureBufferAlignment(for: MTLPixelFormat) -> Int

Calculates the minimum alignment required when creating a texture buffer from a buffer.

Required.

var readWriteTextureSupport: MTLReadWriteTextureTier

The device objects's read-write texture support tier.

Required.

Creating Textures and Samplers

func makeTexture(descriptor: MTLTextureDescriptor, iosurface: IOSurfaceRef, plane: Int) -> MTLTexture?

Creates a texture using an IOSurface to store the texture data.

Required.

func makeSharedTexture(descriptor: MTLTextureDescriptor) -> MTLTexture?

Create a texture that can be shared across process boundaries.

Required.

func makeSharedTexture(handle: MTLSharedTextureHandle) -> MTLTexture?

Creates a texture referencing an existing shared texture.

Required.

Querying Argument Buffer Support

var argumentBuffersSupport: MTLArgumentBuffersTier

Determines the argument buffers tier supported by the device.

Required.

var maxArgumentBufferSamplerCount: Int

The maximum number of unique argument buffer samplers per app.

Required.

Creating Argument Buffer Encoders

func makeArgumentEncoder(arguments: [MTLArgumentDescriptor]) -> MTLArgumentEncoder?

Creates an argument encoder for a specific array of arguments.

Required.

Creating Resource Heaps

func heapBufferSizeAndAlign(length: Int, options: MTLResourceOptions) -> MTLSizeAndAlign

Returns the size and alignment, in bytes, of a buffer sub-allocated from a heap.

Required.

func heapTextureSizeAndAlign(descriptor: MTLTextureDescriptor) -> MTLSizeAndAlign

Returns the size and alignment, in bytes, of a texture sub-allocated from a heap.

Required.

Creating Depth and Stencil State

func makeDepthStencilState(descriptor: MTLDepthStencilDescriptor) -> MTLDepthStencilState?

Creates a new object that contains depth and stencil test state.

Required.

Creating Counter Sample Buffers

var counterSets: [MTLCounterSet]?

The counter sets supported by the device object.

Required.

Creating Rasterization Rate Maps

func supportsRasterizationRateMap(layerCount: Int) -> Bool

Returns a Boolean value that indicates whether the device object supports the desired number of layers in a rasterization rate map.

Required.

Querying Sparse Tile Properties

var sparseTileSizeInBytes: Int

The size of sparse tiles created by this device object, measured in bytes.

Required.

func sparseTileSize(with: MTLTextureType, pixelFormat: MTLPixelFormat, sampleCount: Int) -> MTLSize

Returns the dimensions of a sparse tile for a specific texture.

Required.

Converting Between Pixel Regions and Sparse Tile Regions

struct MTLSparseTextureRegionAlignmentMode

Options used when converting between a pixel-based region within a texture to a tile-based region.

Relationships

Inherits From

See Also

GPUs

Getting the Default GPU

Select the system's default GPU device on which to run your Metal code.

GPU Selection in macOS

Select one or more GPUs on which to run your Metal code by considering GPU capabilities, power, or performance characteristics.

GPU Features

Find feature information for specific GPU families.