Crate objc2_metal

Source
Expand description

§Bindings to the Metal framework

See Apple’s docs and the general docs on framework crates for more information.

Metal has tools for validating that you’re using it correctly, using these is highly recommended! See Apple’s documentation on it, or run man MetalValidation to get information on environment variables.

NOTE: To use MTLCreateSystemDefaultDevice you need to link to CoreGraphics, this can be done by using objc2-core-graphics, or by doing:

#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {}

§Example

Drawing a rotating triangle.

#![deny(unsafe_op_in_unsafe_fn)]
#![allow(clippy::incompatible_msrv)]
#![cfg_attr(not(target_os = "macos"), allow(dead_code, unused))]

use core::{cell::OnceCell, ptr::NonNull};

use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly};
#[cfg(target_os = "macos")]
use objc2_app_kit::{
    NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate, NSBackingStoreType,
    NSWindow, NSWindowStyleMask,
};
use objc2_foundation::{
    ns_string, NSDate, NSNotification, NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize,
};
use objc2_metal::{
    MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLCreateSystemDefaultDevice,
    MTLDevice as _, MTLLibrary, MTLPackedFloat3, MTLPrimitiveType, MTLRenderCommandEncoder,
    MTLRenderPipelineDescriptor, MTLRenderPipelineState,
};
#[cfg(target_os = "macos")]
use objc2_metal_kit::{MTKView, MTKViewDelegate};

#[derive(Copy, Clone)]
#[repr(C)]
struct SceneProperties {
    time: f32,
}

#[derive(Copy, Clone)]
#[repr(C)]
struct VertexInput {
    position: MTLPackedFloat3,
    color: MTLPackedFloat3,
}

macro_rules! idcell {
    ($name:ident => $this:expr) => {
        $this.ivars().$name.set($name).expect(&format!(
            "ivar should not already be initialized: `{}`",
            stringify!($name)
        ));
    };
    ($name:ident <= $this:expr) => {
        #[rustfmt::skip]
        let Some($name) = $this.ivars().$name.get() else {
            unreachable!(
                "ivar should be initialized: `{}`",
                stringify!($name)
            )
        };
    };
}

// The state of our application.
struct Ivars {
    start_date: Retained<NSDate>,
    command_queue: OnceCell<Retained<ProtocolObject<dyn MTLCommandQueue>>>,
    pipeline_state: OnceCell<Retained<ProtocolObject<dyn MTLRenderPipelineState>>>,
    #[cfg(target_os = "macos")]
    window: OnceCell<Retained<NSWindow>>,
}

define_class!(
    // SAFETY:
    // - The superclass NSObject does not have any subclassing requirements.
    // - `MainThreadOnly` is correct, since this is an application delegate.
    // - `Delegate` does not implement `Drop`.
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "Delegate"]
    #[ivars = Ivars]
    struct Delegate;

    unsafe impl NSObjectProtocol for Delegate {}

    // define the delegate methods for the `NSApplicationDelegate` protocol
    #[cfg(target_os = "macos")]
    unsafe impl NSApplicationDelegate for Delegate {
        #[unsafe(method(applicationDidFinishLaunching:))]
        #[allow(non_snake_case)]
        unsafe fn applicationDidFinishLaunching(&self, _notification: &NSNotification) {
            let mtm = self.mtm();
            // create the app window
            let window = {
                let content_rect = NSRect::new(NSPoint::new(0., 0.), NSSize::new(768., 768.));
                let style = NSWindowStyleMask::Closable
                    | NSWindowStyleMask::Resizable
                    | NSWindowStyleMask::Titled;
                let backing_store_type = NSBackingStoreType::Buffered;
                let flag = false;
                unsafe {
                    NSWindow::initWithContentRect_styleMask_backing_defer(
                        NSWindow::alloc(mtm),
                        content_rect,
                        style,
                        backing_store_type,
                        flag,
                    )
                }
            };

            // get the default device
            let device =
                MTLCreateSystemDefaultDevice().expect("failed to get default system device");

            // create the command queue
            let command_queue = device
                .newCommandQueue()
                .expect("Failed to create a command queue.");

            // create the metal view
            let mtk_view = {
                let frame_rect = window.frame();
                unsafe {
                    MTKView::initWithFrame_device(MTKView::alloc(mtm), frame_rect, Some(&device))
                }
            };

            // create the pipeline descriptor
            let pipeline_descriptor = MTLRenderPipelineDescriptor::new();

            unsafe {
                pipeline_descriptor
                    .colorAttachments()
                    .objectAtIndexedSubscript(0)
                    .setPixelFormat(mtk_view.colorPixelFormat());
            }

            // compile the shaders
            let library = device
                .newLibraryWithSource_options_error(
                    ns_string!(include_str!("triangle.metal")),
                    None,
                )
                .expect("Failed to create a library.");

            // configure the vertex shader
            let vertex_function = library.newFunctionWithName(ns_string!("vertex_main"));
            pipeline_descriptor.setVertexFunction(vertex_function.as_deref());

            // configure the fragment shader
            let fragment_function = library.newFunctionWithName(ns_string!("fragment_main"));
            pipeline_descriptor.setFragmentFunction(fragment_function.as_deref());

            // create the pipeline state
            let pipeline_state = device
                .newRenderPipelineStateWithDescriptor_error(&pipeline_descriptor)
                .expect("Failed to create a pipeline state.");

            // configure the metal view delegate
            unsafe {
                let object = ProtocolObject::from_ref(self);
                mtk_view.setDelegate(Some(object));
            }

            // configure the window
            window.setContentView(Some(&mtk_view));
            window.center();
            window.setTitle(ns_string!("metal example"));
            window.makeKeyAndOrderFront(None);

            // initialize the delegate state
            idcell!(command_queue => self);
            idcell!(pipeline_state => self);
            idcell!(window => self);
        }
    }

    // define the delegate methods for the `MTKViewDelegate` protocol
    #[cfg(target_os = "macos")] // TODO: Support iOS
    unsafe impl MTKViewDelegate for Delegate {
        #[unsafe(method(drawInMTKView:))]
        #[allow(non_snake_case)]
        unsafe fn drawInMTKView(&self, mtk_view: &MTKView) {
            idcell!(command_queue <= self);
            idcell!(pipeline_state <= self);

            // prepare for drawing
            let Some(current_drawable) = (unsafe { mtk_view.currentDrawable() }) else {
                return;
            };
            let Some(command_buffer) = command_queue.commandBuffer() else {
                return;
            };
            let Some(pass_descriptor) = (unsafe { mtk_view.currentRenderPassDescriptor() }) else {
                return;
            };
            let Some(encoder) = command_buffer.renderCommandEncoderWithDescriptor(&pass_descriptor)
            else {
                return;
            };

            // compute the scene properties
            let scene_properties_data = &SceneProperties {
                time: unsafe { self.ivars().start_date.timeIntervalSinceNow() } as f32,
            };
            // write the scene properties to the vertex shader argument buffer at index 0
            let scene_properties_bytes = NonNull::from(scene_properties_data);
            unsafe {
                encoder.setVertexBytes_length_atIndex(
                    scene_properties_bytes.cast::<core::ffi::c_void>(),
                    core::mem::size_of_val(scene_properties_data),
                    0,
                )
            };

            // compute the triangle geometry
            let vertex_input_data: &[VertexInput] = &[
                VertexInput {
                    position: MTLPackedFloat3 {
                        x: -f32::sqrt(3.0) / 4.0,
                        y: -0.25,
                        z: 0.,
                    },
                    color: MTLPackedFloat3 {
                        x: 1.,
                        y: 0.,
                        z: 0.,
                    },
                },
                VertexInput {
                    position: MTLPackedFloat3 {
                        x: f32::sqrt(3.0) / 4.0,
                        y: -0.25,
                        z: 0.,
                    },
                    color: MTLPackedFloat3 {
                        x: 0.,
                        y: 1.,
                        z: 0.,
                    },
                },
                VertexInput {
                    position: MTLPackedFloat3 {
                        x: 0.,
                        y: 0.5,
                        z: 0.,
                    },
                    color: MTLPackedFloat3 {
                        x: 0.,
                        y: 0.,
                        z: 1.,
                    },
                },
            ];
            // write the triangle geometry to the vertex shader argument buffer at index 1
            let vertex_input_bytes = NonNull::from(vertex_input_data);
            unsafe {
                encoder.setVertexBytes_length_atIndex(
                    vertex_input_bytes.cast::<core::ffi::c_void>(),
                    core::mem::size_of_val(vertex_input_data),
                    1,
                )
            };

            // configure the encoder with the pipeline and draw the triangle
            encoder.setRenderPipelineState(pipeline_state);
            unsafe {
                encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::Triangle, 0, 3)
            };
            encoder.endEncoding();

            // schedule the command buffer for display and commit
            command_buffer.presentDrawable(ProtocolObject::from_ref(&*current_drawable));
            command_buffer.commit();
        }

        #[unsafe(method(mtkView:drawableSizeWillChange:))]
        #[allow(non_snake_case)]
        unsafe fn mtkView_drawableSizeWillChange(&self, _view: &MTKView, _size: NSSize) {
            // println!("mtkView_drawableSizeWillChange");
        }
    }
);

impl Delegate {
    fn new(mtm: MainThreadMarker) -> Retained<Self> {
        let this = Self::alloc(mtm);
        let this = this.set_ivars(Ivars {
            start_date: unsafe { NSDate::now() },
            command_queue: OnceCell::default(),
            pipeline_state: OnceCell::default(),
            #[cfg(target_os = "macos")]
            window: OnceCell::default(),
        });
        unsafe { msg_send![super(this), init] }
    }
}

#[cfg(target_os = "macos")]
fn main() {
    let mtm = MainThreadMarker::new().unwrap();
    // configure the app
    let app = NSApplication::sharedApplication(mtm);
    app.setActivationPolicy(NSApplicationActivationPolicy::Regular);

    // configure the application delegate
    let delegate = Delegate::new(mtm);
    let object = ProtocolObject::from_ref(&*delegate);
    app.setDelegate(Some(object));

    // run the app
    app.run();
}

#[cfg(not(target_os = "macos"))]
fn main() {
    panic!("This example is currently only supported on macOS");
}

With the following shader.

#include <metal_stdlib>

struct SceneProperties {
    float time;
};

struct VertexInput {
    metal::packed_float3 position;
    metal::packed_float3 color;
};

struct VertexOutput {
    metal::float4 position [[position]];
    metal::float4 color;
};

vertex VertexOutput vertex_main(
    device const SceneProperties& properties [[buffer(0)]],
    device const VertexInput* vertices [[buffer(1)]],
    uint vertex_idx [[vertex_id]]
) {
    VertexOutput out;
    VertexInput in = vertices[vertex_idx];
    out.position =
        metal::float4(
            metal::float2x2(
                metal::cos(properties.time), -metal::sin(properties.time),
                metal::sin(properties.time),  metal::cos(properties.time)
            ) * in.position.xy,
            in.position.z,
            1);
    out.color = metal::float4(in.color, 1);
    return out;
}

fragment metal::float4 fragment_main(VertexOutput in [[stage_in]]) {
    return in.color;
}

Structs§

MTLAccelerationStructureBoundingBoxGeometryDescriptorMTLAccelerationStructure
Descriptor for bounding box geometry
MTLAccelerationStructureCurveGeometryDescriptorMTLAccelerationStructure
Acceleration structure geometry descriptor describing geometry made of curve primitives
MTLAccelerationStructureDescriptorMTLAccelerationStructure
Base class for acceleration structure descriptors. Do not use this class directly. Use one of the derived classes instead.
MTLAccelerationStructureGeometryDescriptorMTLAccelerationStructure
Base class for all geometry descriptors. Do not use this class directly. Use one of the derived classes instead.
MTLAccelerationStructureInstanceDescriptorMTLAccelerationStructure and MTLAccelerationStructureTypes
Apple’s documentation
MTLAccelerationStructureInstanceDescriptorTypeMTLAccelerationStructure
Apple’s documentation
MTLAccelerationStructureInstanceOptionsMTLAccelerationStructure
Apple’s documentation
MTLAccelerationStructureMotionBoundingBoxGeometryDescriptorMTLAccelerationStructure
Descriptor for motion bounding box geometry
MTLAccelerationStructureMotionCurveGeometryDescriptorMTLAccelerationStructure
Acceleration structure motion geometry descriptor describing geometry made of curve primitives
MTLAccelerationStructureMotionInstanceDescriptorMTLAccelerationStructure
Apple’s documentation
MTLAccelerationStructureMotionTriangleGeometryDescriptorMTLAccelerationStructure
Descriptor for motion triangle geometry
MTLAccelerationStructurePassDescriptorMTLAccelerationStructureCommandEncoder
MTLAccelerationStructurePassDescriptor represents a collection of attachments to be used to create a concrete acceleration structure encoder.
MTLAccelerationStructurePassSampleBufferAttachmentDescriptorMTLAccelerationStructureCommandEncoder
Apple’s documentation
MTLAccelerationStructurePassSampleBufferAttachmentDescriptorArrayMTLAccelerationStructureCommandEncoder
Apple’s documentation
MTLAccelerationStructureRefitOptionsMTLAccelerationStructureCommandEncoder
Controls the acceleration structure refit operation
MTLAccelerationStructureSizesMTLDevice
Describes the memory requirements for an acceleration structure
MTLAccelerationStructureTriangleGeometryDescriptorMTLAccelerationStructure
Descriptor for triangle geometry
MTLAccelerationStructureUsageMTLAccelerationStructure
Apple’s documentation
MTLAccelerationStructureUserIDInstanceDescriptorMTLAccelerationStructure and MTLAccelerationStructureTypes
Apple’s documentation
MTLArchitectureMTLDevice
Contains information about the device’s architecture
MTLArgumentDeprecatedMTLArgument
MTLArgument
MTLArgumentBuffersTierMTLDevice
MTLArgumentBuffersTier determines support level for argument buffers.
MTLArgumentDescriptorMTLDevice
Represents a member of an argument buffer
MTLArgumentTypeDeprecatedMTLArgument
The type for an input to a MTLRenderPipelineState or a MTLComputePipelineState
MTLArrayTypeMTLArgument
Apple’s documentation
MTLAttributeMTLLibrary
Apple’s documentation
MTLAttributeDescriptorMTLStageInputOutputDescriptor
Apple’s documentation
MTLAttributeDescriptorArrayMTLStageInputOutputDescriptor
Apple’s documentation
MTLAttributeFormatMTLStageInputOutputDescriptor
Apple’s documentation
MTLAxisAlignedBoundingBoxMTLAccelerationStructureTypes
An axis aligned bounding box with a min and max point
MTLBarrierScopeMTLCommandEncoder
Describes the types of resources that the a barrier operates on
MTLBinaryArchiveDescriptorMTLBinaryArchive
A class used to indicate how an archive should be created
MTLBinaryArchiveErrorMTLBinaryArchive
Apple’s documentation
MTLBindingAccessMTLArgument
Apple’s documentation
MTLBindingTypeMTLArgument
The type of a resource binding.
MTLBlendFactorMTLRenderPipeline
Apple’s documentation
MTLBlendOperationMTLRenderPipeline
Apple’s documentation
MTLBlitOptionMTLBlitCommandEncoder
Controls the blit operation
MTLBlitPassDescriptorMTLBlitPass
MTLBlitPassDescriptor represents a collection of attachments to be used to create a concrete blit command encoder
MTLBlitPassSampleBufferAttachmentDescriptorMTLBlitPass
Apple’s documentation
MTLBlitPassSampleBufferAttachmentDescriptorArrayMTLBlitPass
Apple’s documentation
MTLBufferLayoutDescriptorMTLStageInputOutputDescriptor
Apple’s documentation
MTLBufferLayoutDescriptorArrayMTLStageInputOutputDescriptor
Apple’s documentation
MTLCPUCacheModeMTLResource
Describes what CPU cache mode is used for the CPU’s mapping of a texture resource.
MTLCaptureDescriptorMTLCaptureManager
Apple’s documentation
MTLCaptureDestinationMTLCaptureManager
The destination where you want the GPU trace to be captured to.
MTLCaptureErrorMTLCaptureManager
Apple’s documentation
MTLCaptureManagerMTLCaptureManager
Apple’s documentation
MTLClearColorMTLRenderPass
Apple’s documentation
MTLColorWriteMaskMTLRenderPipeline
Apple’s documentation
MTLCommandBufferDescriptorMTLCommandBuffer
An object that you use to configure new Metal command buffer objects.
MTLCommandBufferErrorMTLCommandBuffer
Error codes that can be found in MTLCommandBuffer.error
MTLCommandBufferErrorOptionMTLCommandBuffer
Options for controlling the error reporting for Metal command buffer objects.
MTLCommandBufferStatusMTLCommandBuffer
MTLCommandBufferStatus reports the current stage in the lifetime of MTLCommandBuffer, as it proceeds to enqueued, committed, scheduled, and completed.
MTLCommandEncoderErrorStateMTLCommandBuffer
The error states for a Metal command encoder after command buffer execution.
MTLCommandQueueDescriptorMTLCommandQueue
Apple’s documentation
MTLCompareFunctionMTLDepthStencil
Apple’s documentation
MTLCompileOptionsMTLLibrary
Apple’s documentation
MTLCompileSymbolVisibilityMTLLibrary
Apple’s documentation
MTLComponentTransformMTLAccelerationStructureTypes
A transformation represented by individual components such as translation and rotation. The rotation is represented by a quaternion, allowing for correct motion interpolation.
MTLComputePassDescriptorMTLComputePass
MTLComputePassDescriptor represents a collection of attachments to be used to create a concrete compute command encoder
MTLComputePassSampleBufferAttachmentDescriptorMTLComputePass
Apple’s documentation
MTLComputePassSampleBufferAttachmentDescriptorArrayMTLComputePass
Apple’s documentation
MTLComputePipelineDescriptorMTLComputePipeline
Apple’s documentation
MTLComputePipelineReflectionMTLComputePipeline
Apple’s documentation
MTLCounterResultStageUtilizationMTLCounters
Apple’s documentation
MTLCounterResultStatisticMTLCounters
Apple’s documentation
MTLCounterResultTimestampMTLCounters
Apple’s documentation
MTLCounterSampleBufferDescriptorMTLCounters
Object to represent the counter state.
MTLCounterSampleBufferErrorMTLCounters
There wasn’t enough memory available to allocate the counter sample buffer.
MTLCounterSamplingPointMTLDevice
MTLCounterSamplingPoint determines type of sampling points that are supported on given device.
MTLCullModeMTLRenderCommandEncoder
Apple’s documentation
MTLCurveBasisMTLAccelerationStructure
Basis function to use to interpolate curve control points
MTLCurveEndCapsMTLAccelerationStructure
Type of end cap to insert at the beginning and end of each connected sequence of curve segments.
MTLCurveTypeMTLAccelerationStructure
Curve types
MTLDataTypeMTLArgument
Apple’s documentation
MTLDepthClipModeMTLRenderCommandEncoder
Apple’s documentation
MTLDepthStencilDescriptorMTLDepthStencil
Apple’s documentation
MTLDeviceLocationMTLDevice
Specifies the location of the GPU on macOS
MTLDispatchThreadgroupsIndirectArgumentsMTLComputeCommandEncoder
Apple’s documentation
MTLDispatchTypeMTLCommandBuffer
MTLDispatchType Describes how a command encoder will execute dispatched work.
MTLDrawIndexedPrimitivesIndirectArgumentsMTLRenderCommandEncoder
Apple’s documentation
MTLDrawPatchIndirectArgumentsMTLRenderCommandEncoder
Apple’s documentation
MTLDrawPrimitivesIndirectArgumentsMTLRenderCommandEncoder
Apple’s documentation
MTLDynamicLibraryErrorMTLDynamicLibrary
Apple’s documentation
MTLFeatureSetDeprecatedMTLDevice
Apple’s documentation
MTLFunctionConstantMTLLibrary
describe an uberShader constant used by the function
MTLFunctionConstantValuesMTLFunctionConstantValues
Apple’s documentation
MTLFunctionDescriptorMTLFunctionDescriptor
Apple’s documentation
MTLFunctionLogTypeMTLFunctionLog
Apple’s documentation
MTLFunctionOptionsMTLFunctionDescriptor
Apple’s documentation
MTLFunctionStitchingAttributeAlwaysInlineMTLFunctionStitching
Applies the __attribute__((always_inline)) attribute to the produced stitched function.
MTLFunctionStitchingFunctionNodeMTLFunctionStitching
A function node that calls the specified function with arguments and ordering determined by data and control dependencies.
MTLFunctionStitchingGraphMTLFunctionStitching
A function graph that describes a directed acyclic graph.
MTLFunctionStitchingInputNodeMTLFunctionStitching
An indexed input node of the produced stitched function.
MTLFunctionTypeMTLLibrary
An identifier for a top-level Metal function.
MTLGPUFamilyMTLDevice
Apple’s documentation
MTLHazardTrackingModeMTLResource
Describes how hazard tracking is performed.
MTLHeapDescriptorMTLHeap
Apple’s documentation
MTLHeapTypeMTLHeap
Describes the mode of operation for an MTLHeap.
MTLIOCommandQueueDescriptorMTLIOCommandQueue
Represents a descriptor to create a MTLIOCommandQueue.
MTLIOCommandQueueTypeMTLIOCommandQueue
Apple’s documentation
MTLIOCompressionMethodMTLDevice
Apple’s documentation
MTLIOCompressionStatusMTLIOCompressor
Apple’s documentation
MTLIOErrorMTLIOCommandQueue
Apple’s documentation
MTLIOPriorityMTLIOCommandQueue
Apple’s documentation
MTLIOStatusMTLIOCommandBuffer
Apple’s documentation
MTLIndexTypeMTLStageInputOutputDescriptor
Apple’s documentation
MTLIndirectAccelerationStructureInstanceDescriptorMTLAccelerationStructure and MTLAccelerationStructureTypes and MTLTypes
Apple’s documentation
MTLIndirectAccelerationStructureMotionInstanceDescriptorMTLAccelerationStructure and MTLTypes
Apple’s documentation
MTLIndirectCommandBufferDescriptorMTLIndirectCommandBuffer
Describes the limits and features that can be used in an indirect command
MTLIndirectCommandBufferExecutionRangeMTLIndirectCommandBuffer
The data layout required for specifying an indirect command buffer execution range.
MTLIndirectCommandTypeMTLIndirectCommandBuffer
A bitfield of commands that may be performed indirectly.
MTLIndirectInstanceAccelerationStructureDescriptorMTLAccelerationStructure
Descriptor for an instance acceleration structure built with an indirected buffer of instances.
MTLInstanceAccelerationStructureDescriptorMTLAccelerationStructure
Descriptor for an instance acceleration structure
MTLIntersectionFunctionDescriptorMTLFunctionDescriptor
Apple’s documentation
MTLIntersectionFunctionSignatureMTLIntersectionFunctionTable
Signature defining what data is provided to an intersection function. The signature must match across the shading language declaration of the intersection function table, intersection functions in the table, and the intersector using the table.
MTLIntersectionFunctionTableDescriptorMTLIntersectionFunctionTable
Apple’s documentation
MTLLanguageVersionMTLLibrary
Apple’s documentation
MTLLibraryErrorMTLLibrary
NSErrors raised when creating a library.
MTLLibraryOptimizationLevelMTLLibrary
Optimization level for the Metal compiler.
MTLLibraryTypeMTLLibrary
Apple’s documentation
MTLLinkedFunctionsMTLLinkedFunctions
A class to set functions to be linked.
MTLLoadActionMTLRenderPass
Apple’s documentation
MTLLogLevelMTLLogState
The level of the log entry.
MTLLogStateDescriptorMTLLogState
Apple’s documentation
MTLLogStateErrorMTLLogState
NSErrors raised when creating a logstate.
MTLMapIndirectArgumentsMTLResourceStateCommandEncoder
Structure describing indirect mapping region. This structure is used to populate a buffer for the method ‘MTLResourceStateCommandEncoder updateTextureMapping:indirectBuffer:indirectBufferOffset:’
MTLMathFloatingPointFunctionsMTLLibrary
An enum to indicate the default math functions for single precision floating-point
MTLMathModeMTLLibrary
An enum to indicate if the compiler can perform optimizations for floating-point arithmetic that may violate the IEEE 754 standard
MTLMatrixLayoutMTLAccelerationStructure
Apple’s documentation
MTLMeshRenderPipelineDescriptorMTLRenderPipeline
As an alternative to a vertex + fragment shader render pipeline, this render pipeline uses a (object +) mesh + fragment shader for rendering geometry.
MTLMotionBorderModeMTLAccelerationStructure
Describes what happens to the object before the first motion key and after the last motion key.
MTLMotionKeyframeDataMTLAccelerationStructure
MTLbuffer and description how the data is stored in it.
MTLMultisampleDepthResolveFilterMTLRenderPass
Controls the MSAA depth resolve operation. Supported on iOS GPU Family 3 and later.
MTLMultisampleStencilResolveFilterMTLRenderPass
Controls the MSAA stencil resolve operation.
MTLMutabilityMTLPipeline
Specifies whether a buffer will be modified between the time it is bound and a compute or render pipeline is executed in a draw or dispatch.
MTLOriginMTLTypes
Identify a pixel in an image. MTLOrigin is ususally used as the upper-left corner of a region of a texture.
MTLPackedFloat3MTLAccelerationStructureTypes
MTLPackedFloat4x3MTLAccelerationStructureTypes
Apple’s documentation
MTLPackedFloatQuaternionMTLAccelerationStructureTypes
Apple’s documentation
MTLPatchTypeMTLLibrary
Apple’s documentation
MTLPipelineBufferDescriptorMTLPipeline
Apple’s documentation
MTLPipelineBufferDescriptorArrayMTLPipeline
Apple’s documentation
MTLPipelineOptionMTLDevice
Controls the creation of the pipeline
MTLPixelFormatMTLPixelFormat
Apple’s documentation
MTLPointerTypeMTLArgument
Apple’s documentation
MTLPrimitiveAccelerationStructureDescriptorMTLAccelerationStructure
Descriptor for a primitive acceleration structure
MTLPrimitiveTopologyClassMTLRenderPipeline
Apple’s documentation
MTLPrimitiveTypeMTLRenderCommandEncoder
Apple’s documentation
MTLPurgeableStateMTLResource
Options for setPurgeable call.
MTLQuadTessellationFactorsHalfMTLRenderCommandEncoder
Apple’s documentation
MTLRasterizationRateLayerArrayMTLRasterizationRate
Mutable array of MTLRasterizationRateLayerDescriptor
MTLRasterizationRateLayerDescriptorMTLRasterizationRate
Describes the minimum rasterization rate screen space using two piecewise linear functions.
MTLRasterizationRateMapDescriptorMTLRasterizationRate
Describes a MTLRasterizationRateMap containing an arbitrary number of MTLRasterizationRateLayerDescriptor instances.
MTLRasterizationRateSampleArrayMTLRasterizationRate
A helper object for convient access to samples stored in an array.
MTLReadWriteTextureTierMTLDevice
MTLReadWriteTextureTier determines support level for read-write texture formats.
MTLRegionMTLTypes
Identify a region in an image or texture.
MTLRenderPassAttachmentDescriptorMTLRenderPass
Apple’s documentation
MTLRenderPassColorAttachmentDescriptorMTLRenderPass
Apple’s documentation
MTLRenderPassColorAttachmentDescriptorArrayMTLRenderPass
Apple’s documentation
MTLRenderPassDepthAttachmentDescriptorMTLRenderPass
Apple’s documentation
MTLRenderPassDescriptorMTLRenderPass
MTLRenderPassDescriptor represents a collection of attachments to be used to create a concrete render command encoder
MTLRenderPassSampleBufferAttachmentDescriptorMTLRenderPass
Apple’s documentation
MTLRenderPassSampleBufferAttachmentDescriptorArrayMTLRenderPass
Apple’s documentation
MTLRenderPassStencilAttachmentDescriptorMTLRenderPass
Apple’s documentation
MTLRenderPipelineColorAttachmentDescriptorMTLRenderPipeline
Apple’s documentation
MTLRenderPipelineColorAttachmentDescriptorArrayMTLRenderPipeline
Apple’s documentation
MTLRenderPipelineDescriptorMTLRenderPipeline
Apple’s documentation
MTLRenderPipelineFunctionsDescriptorMTLRenderPipeline
Apple’s documentation
MTLRenderPipelineReflectionMTLRenderPipeline
Apple’s documentation
MTLRenderStagesMTLRenderCommandEncoder
Generic render stage enum
MTLResidencySetDescriptorMTLResidencySet
Specifies the parameters for MTLResidencySet creation.
MTLResourceIDMTLTypes
Handle of the GPU resource suitable for storing in an Argument Buffer
MTLResourceOptionsMTLResource
Apple’s documentation
MTLResourceStatePassDescriptorMTLResourceStatePass
MTLResourceStatePassDescriptor represents a collection of attachments to be used to create a concrete resourceState command encoder
MTLResourceStatePassSampleBufferAttachmentDescriptorMTLResourceStatePass
Apple’s documentation
MTLResourceStatePassSampleBufferAttachmentDescriptorArrayMTLResourceStatePass
Apple’s documentation
MTLResourceUsageMTLCommandEncoder
Describes how a resource will be used by a shader through an argument buffer
MTLSamplePositionMTLTypes
Identify a sample within a pixel. Origin is top-left with a range [0,1) for both x and y.
MTLSamplerAddressModeMTLSampler
Options for what value is returned when a fetch falls outside the bounds of a texture.
MTLSamplerBorderColorMTLSampler
Specify the color value that will be clamped to when the sampler address mode is MTLSamplerAddressModeClampToBorderColor.
MTLSamplerDescriptorMTLSampler
A mutable descriptor used to configure a sampler. When complete, this can be used to create an immutable MTLSamplerState.
MTLSamplerMinMagFilterMTLSampler
Options for filtering texels within a mip level.
MTLSamplerMipFilterMTLSampler
Options for selecting and filtering between mipmap levels
MTLScissorRectMTLRenderCommandEncoder
Apple’s documentation
MTLShaderValidationMTLPipeline
Apple’s documentation
MTLSharedEventHandleMTLEvent
Apple’s documentation
MTLSharedEventListenerMTLEvent
This class provides a simple interface for handling the dispatching of MTLSharedEvent notifications from Metal.
MTLSharedTextureHandleMTLTexture
Apple’s documentation
MTLSizeMTLTypes
A set of dimensions to declare the size of an object, such as an image, texture, threadgroup, or grid.
MTLSizeAndAlignMTLDevice
Represent a memory size and alignment in bytes.
MTLSparsePageSizeMTLDevice
Physical size of sparse resource page in KBs.
MTLSparseTextureMappingModeMTLResourceStateCommandEncoder
Type of mapping operation for sparse texture
MTLSparseTextureRegionAlignmentModeMTLDevice
MTLSparseTextureRegionAlignmentMode determines type of alignment used when converting from pixel region to tile region.
MTLStageInRegionIndirectArgumentsMTLComputeCommandEncoder
Apple’s documentation
MTLStageInputOutputDescriptorMTLStageInputOutputDescriptor
Apple’s documentation
MTLStencilDescriptorMTLDepthStencil
Apple’s documentation
MTLStencilOperationMTLDepthStencil
Apple’s documentation
MTLStepFunctionMTLStageInputOutputDescriptor
Apple’s documentation
MTLStitchedLibraryDescriptorMTLFunctionStitching
A container for the graphs and functions needed to create the stitched functions described by the graphs.
MTLStitchedLibraryOptionsMTLFunctionStitching
A bitfield of options to create a stitched library
MTLStorageModeMTLResource
Describes location and CPU mapping of MTLTexture.
MTLStoreActionMTLRenderPass
Apple’s documentation
MTLStoreActionOptionsMTLRenderPass
Apple’s documentation
MTLStructMemberMTLArgument
Apple’s documentation
MTLStructTypeMTLArgument
Apple’s documentation
MTLTessellationControlPointIndexTypeMTLRenderPipeline
Apple’s documentation
MTLTessellationFactorFormatMTLRenderPipeline
Apple’s documentation
MTLTessellationFactorStepFunctionMTLRenderPipeline
Apple’s documentation
MTLTessellationPartitionModeMTLRenderPipeline
Apple’s documentation
MTLTextureCompressionTypeMTLTexture
Apple’s documentation
MTLTextureDescriptorMTLTexture
Apple’s documentation
MTLTextureReferenceTypeMTLArgument
Apple’s documentation
MTLTextureSwizzleMTLTexture
Apple’s documentation
MTLTextureSwizzleChannelsMTLTexture
Apple’s documentation
MTLTextureTypeMTLTexture
MTLTextureType describes the dimensionality of each image, and if multiple images are arranged into an array or cube.
MTLTextureUsageMTLTexture
MTLTextureUsage declares how the texture will be used over its lifetime (bitwise OR for multiple uses).
MTLTileRenderPipelineColorAttachmentDescriptorMTLRenderPipeline
Apple’s documentation
MTLTileRenderPipelineColorAttachmentDescriptorArrayMTLRenderPipeline
Apple’s documentation
MTLTileRenderPipelineDescriptorMTLRenderPipeline
Apple’s documentation
MTLTransformTypeMTLAccelerationStructure
Apple’s documentation
MTLTriangleFillModeMTLRenderCommandEncoder
Apple’s documentation
MTLTriangleTessellationFactorsHalfMTLRenderCommandEncoder
Apple’s documentation
MTLTypeMTLArgument
Apple’s documentation
MTLVertexAmplificationViewMappingMTLRenderCommandEncoder
Apple’s documentation
MTLVertexAttributeMTLLibrary
Apple’s documentation
MTLVertexAttributeDescriptorMTLVertexDescriptor
Apple’s documentation
MTLVertexAttributeDescriptorArrayMTLVertexDescriptor
Apple’s documentation
MTLVertexBufferLayoutDescriptorMTLVertexDescriptor
Apple’s documentation
MTLVertexBufferLayoutDescriptorArrayMTLVertexDescriptor
Apple’s documentation
MTLVertexDescriptorMTLVertexDescriptor
Apple’s documentation
MTLVertexFormatMTLVertexDescriptor
specifies how the vertex attribute data is laid out in memory.
MTLVertexStepFunctionMTLVertexDescriptor
Apple’s documentation
MTLViewportMTLRenderCommandEncoder
Apple’s documentation
MTLVisibilityResultModeMTLRenderCommandEncoder
Apple’s documentation
MTLVisibleFunctionTableDescriptorMTLVisibleFunctionTable
Apple’s documentation
MTLWindingMTLRenderCommandEncoder
Apple’s documentation

Constants§

MTLCounterDontSampleMTLCounters
MTLCounterErrorValueMTLCounters
MTLResourceCPUCacheModeMaskMTLResource
MTLResourceCPUCacheModeShiftMTLResource
MTLResourceHazardTrackingModeMaskMTLResource
MTLResourceHazardTrackingModeShiftMTLResource
MTLResourceStorageModeMaskMTLResource
MTLResourceStorageModeShiftMTLResource
MTLTextureSwizzleChannelsDefaultMTLTexture

Statics§

MTLAttributeStrideStaticMTLArgumentEncoder
Apple’s documentation
MTLBinaryArchiveDomainMTLBinaryArchive
Apple’s documentation
MTLBufferLayoutStrideDynamicMTLVertexDescriptor
when a MTLVertexBufferLayoutDescriptor has its stride set to this value, the stride will be dynamic and must be set explicitly when binding a buffer to a render command encoder.
MTLCaptureErrorDomainMTLCaptureManager
Apple’s documentation
MTLCommandBufferEncoderInfoErrorKeyMTLCommandBuffer
Key in the userInfo for MTLCommandBufferError NSErrors. Value is an NSArray of MTLCommandBufferEncoderInfo objects in recorded order if an appropriate MTLCommandBufferErrorOption was set, otherwise the key will not exist in the userInfo dictionary.
MTLCommandBufferErrorDomainMTLCommandBuffer
An error domain for NSError objects produced by MTLCommandBuffer
MTLCommonCounterClipperInvocationsMTLCounters
Apple’s documentation
MTLCommonCounterClipperPrimitivesOutMTLCounters
Apple’s documentation
MTLCommonCounterComputeKernelInvocationsMTLCounters
Apple’s documentation
MTLCommonCounterFragmentCyclesMTLCounters
Apple’s documentation
MTLCommonCounterFragmentInvocationsMTLCounters
Apple’s documentation
MTLCommonCounterFragmentsPassedMTLCounters
Apple’s documentation
MTLCommonCounterPostTessellationVertexCyclesMTLCounters
Apple’s documentation
MTLCommonCounterPostTessellationVertexInvocationsMTLCounters
Apple’s documentation
MTLCommonCounterRenderTargetWriteCyclesMTLCounters
Apple’s documentation
MTLCommonCounterSetStageUtilizationMTLCounters
Apple’s documentation
MTLCommonCounterSetStatisticMTLCounters
Apple’s documentation
MTLCommonCounterSetTimestampMTLCounters
Apple’s documentation
MTLCommonCounterTessellationCyclesMTLCounters
Apple’s documentation
MTLCommonCounterTessellationInputPatchesMTLCounters
Apple’s documentation
MTLCommonCounterTimestampMTLCounters
Apple’s documentation
MTLCommonCounterTotalCyclesMTLCounters
Apple’s documentation
MTLCommonCounterVertexCyclesMTLCounters
Apple’s documentation
MTLCommonCounterVertexInvocationsMTLCounters
Apple’s documentation
MTLCounterErrorDomainMTLCounters
NSErrors raised when creating a counter sample buffer.
MTLDeviceRemovalRequestedNotificationMTLDevice
This notification is posted when the user has requested that applications cease using a particular device. Applications should assume that the device will be removed (terminated) imminently. Additionally, the device will be removed from the internal device array prior to this notification being posted. Applications should immediately begin the process of releasing all resources created on the given device, as well as any references to the device itself.
MTLDeviceWasAddedNotificationMTLDevice
This notification is posted when a new Metal device is added to the system
MTLDeviceWasRemovedNotificationMTLDevice
This notification is posted if the device is removed while there are still outstanding references to it, due to either a surprise or forced disconnect by the user. Applications must expect that any attempt to use the device after this point will fail.
MTLDynamicLibraryDomainMTLDynamicLibrary
Apple’s documentation
MTLIOErrorDomainMTLIOCommandQueue
Apple’s documentation
MTLLibraryErrorDomainMTLLibrary
NSErrors raised when creating a library.
MTLLogStateErrorDomainMTLLogState
Apple’s documentation
NSDeviceCertificationiPhonePerformanceGamingMTLDeviceCertification
Apple’s documentation
NSProcessInfoPerformanceProfileDidChangeNotificationMTLDeviceCertification
Apple’s documentation
NSProcessPerformanceProfileDefaultMTLDeviceCertification
Apple’s documentation
NSProcessPerformanceProfileSustainedMTLDeviceCertification
Apple’s documentation

Traits§

MTLAccelerationStructureMTLAccelerationStructure and MTLAllocation and MTLResource
Apple’s documentation
MTLAccelerationStructureCommandEncoderMTLAccelerationStructureCommandEncoder and MTLCommandEncoder
Apple’s documentation
MTLAllocationMTLAllocation
Apple’s documentation
MTLArgumentEncoderMTLArgumentEncoder
MTLArgumentEncoder encodes buffer, texture, sampler, and constant data into a buffer.
MTLBinaryArchiveMTLBinaryArchive
A container of pipeline state descriptors and their associated compiled code.
MTLBindingMTLArgument
Apple’s documentation
MTLBlitCommandEncoderMTLBlitCommandEncoder and MTLCommandEncoder
A command encoder that performs basic copies and blits between buffers and textures.
MTLBufferMTLAllocation and MTLBuffer and MTLResource
A typeless allocation accessible by both the CPU and the GPU (MTLDevice) or by only the GPU when the storage mode is MTLResourceStorageModePrivate.
MTLBufferBindingMTLArgument
Apple’s documentation
MTLCaptureScopeMTLCaptureScope
Apple’s documentation
MTLCommandBufferMTLCommandBuffer
A serial list of commands for the device to execute.
MTLCommandBufferEncoderInfoMTLCommandBuffer
Provides execution status information for a Metal command encoder.
MTLCommandEncoderMTLCommandEncoder
MTLCommandEncoder is the common interface for objects that write commands into MTLCommandBuffers.
MTLCommandQueueMTLCommandQueue
A serial queue of command buffers to be executed by the device.
MTLComputeCommandEncoderMTLCommandEncoder and MTLComputeCommandEncoder
A command encoder that writes data parallel compute commands.
MTLComputePipelineStateMTLComputePipeline
A handle to compiled code for a compute function.
MTLCounterMTLCounters
A descriptor for a single counter.
MTLCounterSampleBufferMTLCounters
The Counter Sample Buffer contains opaque counter samples as well as state needed to request a sample from the API.
MTLCounterSetMTLCounters
A collection of MTLCounters that the device can capture in a single pass.
MTLDepthStencilStateMTLDepthStencil
Apple’s documentation
MTLDeviceMTLDevice
MTLDevice represents a processor capable of data parallel computations
MTLDrawableMTLDrawable
All “drawable” objects (such as those coming from CAMetalLayer) are expected to conform to this protocol
MTLDynamicLibraryMTLDynamicLibrary
A container for the binary representation of code compiled for a MTLDevice.
MTLEventMTLEvent
Apple’s documentation
MTLFenceMTLFence
Apple’s documentation
MTLFunctionMTLLibrary
A handle to intermediate code used as inputs for either a MTLComputePipelineState or a MTLRenderPipelineState.
MTLFunctionHandleMTLFunctionHandle
Apple’s documentation
MTLFunctionLogMTLFunctionLog
Apple’s documentation
MTLFunctionLogDebugLocationMTLFunctionLog
Apple’s documentation
MTLFunctionStitchingAttributeMTLFunctionStitching
An attribute to be applied to the produced stitched function.
MTLFunctionStitchingNodeMTLFunctionStitching
A node used in a graph for stitching.
MTLHeapMTLAllocation and MTLHeap
Apple’s documentation
MTLIOCommandBufferMTLIOCommandBuffer
represents a list of IO commands for a queue to execute
MTLIOCommandQueueMTLIOCommandQueue
Represents a queue that schedules command buffers containing command that read from handle objects and write to MTLResource objects.
MTLIOFileHandleMTLIOCommandQueue
Represents a file (raw or compressed) that can be used as a source for load commands encoded in a MTLIOCommandBuffer.
MTLIOScratchBufferMTLIOCommandQueue
An extendible protocol that can be used to wrap the buffers vended by a custom allocator. The underlying buffer is used as scratch space for IO commands that need it.
MTLIOScratchBufferAllocatorMTLIOCommandQueue
An extendible protocol that can implement a custom allocator passed to the queue descriptor.
MTLIndirectCommandBufferMTLAllocation and MTLIndirectCommandBuffer and MTLResource
Apple’s documentation
MTLIndirectComputeCommandMTLIndirectCommandEncoder
Apple’s documentation
MTLIndirectRenderCommandMTLIndirectCommandEncoder
Apple’s documentation
MTLIntersectionFunctionTableMTLAllocation and MTLIntersectionFunctionTable and MTLResource
Apple’s documentation
MTLLibraryMTLLibrary
Apple’s documentation
MTLLogContainerMTLFunctionLog
Apple’s documentation
MTLLogStateMTLLogState
Apple’s documentation
MTLObjectPayloadBindingMTLArgument
Apple’s documentation
MTLParallelRenderCommandEncoderMTLCommandEncoder and MTLParallelRenderCommandEncoder
The MTLParallelRenderCommandEncoder protocol is designed to allow a single render to texture operation to be efficiently (and safely) broken up across multiple threads.
MTLRasterizationRateMapMTLRasterizationRate
Compiled read-only object that determines how variable rasterization rate is applied when rendering.
MTLRenderCommandEncoderMTLCommandEncoder and MTLRenderCommandEncoder
MTLRenderCommandEncoder is a container for graphics rendering state and the code to translate the state into a command format that the device can execute.
MTLRenderCommandEncoderSliceExtMTLRenderCommandEncoder and MTLCommandEncoder
MTLRenderPipelineStateMTLRenderPipeline
MTLRenderPipelineState represents a compiled render pipeline
MTLResidencySetMTLResidencySet
A residency set is responsible for managing resource and heap residency and is referenced by a command buffer or command queue in order to ensure that resources and heaps are resident. Resources and heaps are added and removed uncommitted and a subsequent commit call applies all of the changes in bulk.
MTLResourceMTLAllocation and MTLResource
Common APIs available for MTLBuffer and MTLTexture instances
MTLResourceStateCommandEncoderMTLCommandEncoder and MTLResourceStateCommandEncoder
Apple’s documentation
MTLSamplerStateMTLSampler
An immutable collection of sampler state compiled for a single device.
MTLSharedEventMTLEvent
Apple’s documentation
MTLTextureMTLAllocation and MTLResource and MTLTexture
MTLTexture represents a collection of 1D, 2D, or 3D images.
MTLTextureBindingMTLArgument
Apple’s documentation
MTLThreadgroupBindingMTLArgument
Apple’s documentation
MTLVisibleFunctionTableMTLAllocation and MTLResource and MTLVisibleFunctionTable
Apple’s documentation
NSProcessInfoNSDeviceCertificationMTLDeviceCertification
Category “NSDeviceCertification” on NSProcessInfo.

Functions§

MTLCopyAllDevicesMTLDevice
Returns all Metal devices in the system.
MTLCopyAllDevicesWithObserverMTLDevice and block2
Returns an NSArray of the current set of available Metal devices and installs a notification handler to be notified of any further changes (additions, removals, etc.). The observer return value is retained by Metal and may be passed to MTLRemoveDeviceObserver() if the application no longer wishes to receive notifications.
MTLCreateSystemDefaultDeviceMTLDevice
Returns a reference to the preferred system default Metal device.
MTLIOCompressionContextAppendDataMTLIOCompressor
MTLIOCompressionContextDefaultChunkSizeMTLIOCompressor
MTLIOCreateCompressionContextMTLIOCompressor and MTLDevice
MTLIOFlushAndDestroyCompressionContextMTLIOCompressor
MTLRemoveDeviceObserverMTLDevice
Removes a previously installed observer for device change notifications.

Type Aliases§

MTLArgumentAccessMTLArgument
Apple’s documentation
MTLAutoreleasedArgumentMTLArgument and MTLLibrary
Apple’s documentation
MTLAutoreleasedComputePipelineReflectionMTLComputePipeline and MTLDevice
Apple’s documentation
MTLAutoreleasedRenderPipelineReflectionMTLDevice and MTLRenderPipeline
Apple’s documentation
MTLCommandBufferHandlerMTLCommandBuffer and block2
Apple’s documentation
MTLCommonCounterMTLCounters
Common counters that, when present, are expected to have similar meanings across different implementations.
MTLCommonCounterSetMTLCounters
Common counter set names.
MTLCoordinate2DMTLTypes
A floating point coordinate in an abstract 2D space. Refer to location of use for concrete information on the space in which the coordinate exists.
MTLDeviceNotificationHandlerMTLDevice and block2
Block signature for device notifications
MTLDeviceNotificationNameMTLDevice
Type for device notifications
MTLDrawablePresentedHandlerMTLDrawable and block2
The presented callback function protocol
MTLIOCommandBufferHandlerMTLIOCommandBuffer and block2
Apple’s documentation
MTLIOCompressionContextMTLIOCompressor
Apple’s documentation
MTLNewComputePipelineStateCompletionHandlerMTLComputePipeline and MTLDevice and block2
Apple’s documentation
MTLNewComputePipelineStateWithReflectionCompletionHandlerMTLComputePipeline and MTLDevice and block2
Apple’s documentation
MTLNewLibraryCompletionHandlerMTLDevice and MTLLibrary and block2
Apple’s documentation
MTLNewRenderPipelineStateCompletionHandlerMTLDevice and MTLRenderPipeline and block2
Apple’s documentation
MTLNewRenderPipelineStateWithReflectionCompletionHandlerMTLDevice and MTLRenderPipeline and block2
Apple’s documentation
MTLSharedEventNotificationBlockMTLEvent and block2
Apple’s documentation
MTLTimestampMTLDevice
Apple’s documentation
NSDeviceCertificationMTLDeviceCertification
Apple’s documentation
NSProcessPerformanceProfileMTLDeviceCertification
Apple’s documentation