diff options
Diffstat (limited to 'third_party/rust/metal/examples')
33 files changed, 1922 insertions, 0 deletions
diff --git a/third_party/rust/metal/examples/argument-buffer/main.rs b/third_party/rust/metal/examples/argument-buffer/main.rs new file mode 100644 index 0000000000..23e88990d9 --- /dev/null +++ b/third_party/rust/metal/examples/argument-buffer/main.rs @@ -0,0 +1,88 @@ +// Copyright 2017 GFX developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use metal::*; +use objc::rc::autoreleasepool; + +fn main() { + autoreleasepool(|| { + let device = Device::system_default().expect("no device found"); + + /* + + // Build encoder for the following MSL argument buffer: + struct ArgumentBuffer { + texture2d<float> texture [[id(0)]]; + sampler sampler [[id(1)]]; + array<device float *, 2> buffers [[id(2)]]; + } + + */ + + let desc1 = ArgumentDescriptor::new(); + desc1.set_index(0); + desc1.set_data_type(MTLDataType::Texture); + desc1.set_texture_type(MTLTextureType::D2); + + let desc2 = ArgumentDescriptor::new(); + desc2.set_index(1); + desc2.set_data_type(MTLDataType::Sampler); + + let desc3 = ArgumentDescriptor::new(); + desc3.set_index(2); + desc3.set_data_type(MTLDataType::Pointer); + desc3.set_array_length(2); + + let encoder = device.new_argument_encoder(Array::from_slice(&[desc1, desc2, desc3])); + println!("Encoder: {:?}", encoder); + + let argument_buffer = + device.new_buffer(encoder.encoded_length(), MTLResourceOptions::empty()); + encoder.set_argument_buffer(&argument_buffer, 0); + + let sampler = { + let descriptor = SamplerDescriptor::new(); + descriptor.set_support_argument_buffers(true); + device.new_sampler(&descriptor) + }; + println!("{:?}", sampler); + + let buffer1 = device.new_buffer(1024, MTLResourceOptions::empty()); + println!("Buffer1: {:?}", buffer1); + let buffer2 = device.new_buffer(1024, MTLResourceOptions::empty()); + println!("Buffer2: {:?}", buffer2); + + encoder.set_sampler_state(1, &sampler); + encoder.set_buffer(2, &buffer1, 0); + encoder.set_buffer(3, &buffer2, 0); + + // How to use argument buffer with render encoder. + + let queue = device.new_command_queue(); + let command_buffer = queue.new_command_buffer(); + + let render_pass_descriptor = RenderPassDescriptor::new(); + let encoder = command_buffer.new_render_command_encoder(render_pass_descriptor); + + // This method makes the array of resources resident for the selected stages of the render pass. + // Call this method before issuing any draw calls that may access the array of resources. + encoder.use_resources( + &[&buffer1, &buffer2], + MTLResourceUsage::Read, + MTLRenderStages::Vertex, + ); + // Bind argument buffer to vertex stage. + encoder.set_vertex_buffer(0, Some(&argument_buffer), 0); + + // Render pass here... + + encoder.end_encoding(); + println!("Encoder: {:?}", encoder); + + command_buffer.commit(); + }); +} diff --git a/third_party/rust/metal/examples/bind/main.rs b/third_party/rust/metal/examples/bind/main.rs new file mode 100644 index 0000000000..811b1c5a17 --- /dev/null +++ b/third_party/rust/metal/examples/bind/main.rs @@ -0,0 +1,34 @@ +// Copyright 2018 GFX developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use metal::*; +use objc::rc::autoreleasepool; + +fn main() { + autoreleasepool(|| { + let device = Device::system_default().expect("no device found"); + + let buffer = device.new_buffer(4, MTLResourceOptions::empty()); + let sampler = { + let descriptor = SamplerDescriptor::new(); + device.new_sampler(&descriptor) + }; + + let queue = device.new_command_queue(); + let cmd_buf = queue.new_command_buffer(); + + let encoder = cmd_buf.new_compute_command_encoder(); + + encoder.set_buffers(2, &[Some(&buffer), None], &[4, 0]); + encoder.set_sampler_states(1, &[Some(&sampler), None]); + + encoder.end_encoding(); + cmd_buf.commit(); + + println!("Everything is bound"); + }); +} diff --git a/third_party/rust/metal/examples/bindless/main.rs b/third_party/rust/metal/examples/bindless/main.rs new file mode 100644 index 0000000000..09c3a59ab9 --- /dev/null +++ b/third_party/rust/metal/examples/bindless/main.rs @@ -0,0 +1,149 @@ +// Copyright 2017 GFX developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use metal::*; +use objc::rc::autoreleasepool; + +const BINDLESS_TEXTURE_COUNT: NSUInteger = 100_000; // ~25Mb + +/// This example demonstrates: +/// - How to create a heap +/// - How to allocate textures from heap. +/// - How to create bindless resources via Metal's argument buffers. +/// - How to bind argument buffer to render encoder +fn main() { + autoreleasepool(|| { + let device = Device::system_default().expect("no device found"); + + /* + + MSL + + struct Textures { + texture2d<float> texture; + }; + struct BindlessTextures { + device Textures *textures; + }; + + */ + + // Tier 2 argument buffers are supported by macOS devices with a discrete GPU and by the A13 GPU. + // The maximum per-app resources available at any given time are: + // - 500,000 buffers or textures + // - 2048 unique samplers + let tier = device.argument_buffers_support(); + println!("Argument buffer support: {:?}", tier); + assert_eq!(MTLArgumentBuffersTier::Tier2, tier); + + let texture_descriptor = TextureDescriptor::new(); + texture_descriptor.set_width(1); + texture_descriptor.set_height(1); + texture_descriptor.set_depth(1); + texture_descriptor.set_texture_type(MTLTextureType::D2); + texture_descriptor.set_pixel_format(MTLPixelFormat::R8Uint); + texture_descriptor.set_storage_mode(MTLStorageMode::Private); // GPU only. + println!("Texture descriptor: {:?}", texture_descriptor); + + // Determine the size required for the heap for the given descriptor + let size_and_align = device.heap_texture_size_and_align(&texture_descriptor); + + // Align the size so that more resources will fit in the heap after this texture + // See https://developer.apple.com/documentation/metal/buffers/using_argument_buffers_with_resource_heaps + let texture_size = + (size_and_align.size & (size_and_align.align - 1)) + size_and_align.align; + let heap_size = texture_size * BINDLESS_TEXTURE_COUNT; + + let heap_descriptor = HeapDescriptor::new(); + heap_descriptor.set_storage_mode(texture_descriptor.storage_mode()); // Must be compatible + heap_descriptor.set_size(heap_size); + println!("Heap descriptor: {:?}", heap_descriptor); + + let heap = device.new_heap(&heap_descriptor); + println!("Heap: {:?}", heap); + + // Allocate textures from heap + let textures = (0..BINDLESS_TEXTURE_COUNT) + .map(|i| { + heap.new_texture(&texture_descriptor) + .expect(&format!("Failed to allocate texture {}", i)) + }) + .collect::<Vec<_>>(); + + // Crate argument encoder that knows how to encode single texture + let descriptor = ArgumentDescriptor::new(); + descriptor.set_index(0); + descriptor.set_data_type(MTLDataType::Texture); + descriptor.set_texture_type(MTLTextureType::D2); + descriptor.set_access(MTLArgumentAccess::ReadOnly); + println!("Argument descriptor: {:?}", descriptor); + + let encoder = device.new_argument_encoder(Array::from_slice(&[descriptor])); + println!("Encoder: {:?}", encoder); + + // Determinate argument buffer size to allocate. + // Size needed to encode one texture * total number of bindless textures. + let argument_buffer_size = encoder.encoded_length() * BINDLESS_TEXTURE_COUNT; + let argument_buffer = device.new_buffer(argument_buffer_size, MTLResourceOptions::empty()); + + // Encode textures to the argument buffer. + textures.iter().enumerate().for_each(|(index, texture)| { + // Offset encoder to a proper texture slot + let offset = index as NSUInteger * encoder.encoded_length(); + encoder.set_argument_buffer(&argument_buffer, offset); + encoder.set_texture(0, texture); + }); + + // How to use bindless argument buffer when drawing + + let queue = device.new_command_queue(); + let command_buffer = queue.new_command_buffer(); + + let render_pass_descriptor = RenderPassDescriptor::new(); + let encoder = command_buffer.new_render_command_encoder(render_pass_descriptor); + + // Bind argument buffer. + encoder.set_fragment_buffer(0, Some(&argument_buffer), 0); + // Make sure all textures are available to the pass. + encoder.use_heap_at(&heap, MTLRenderStages::Fragment); + + // Bind material buffer at index 1 + // Draw + + /* + + // Now instead of binding individual textures each draw call, + // you can just bind material information instead: + + MSL + + struct Material { + int diffuse_texture_index; + int normal_texture_index; + // ... + } + + fragment float4 pixel( + VertexOut v [[stage_in]], + constant const BindlessTextures * textures [[buffer(0)]], + constant Material * material [[buffer(1)]] + ) { + if (material->base_color_texture_index != -1) { + textures[material->diffuse_texture_index].texture.sampler(...) + } + if (material->normal_texture_index != -1) { + ... + } + ... + } + + */ + + encoder.end_encoding(); + command_buffer.commit(); + }); +} diff --git a/third_party/rust/metal/examples/caps/main.rs b/third_party/rust/metal/examples/caps/main.rs new file mode 100644 index 0000000000..ae8fca4f0a --- /dev/null +++ b/third_party/rust/metal/examples/caps/main.rs @@ -0,0 +1,33 @@ +// Copyright 2017 GFX developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use metal::*; + +fn main() { + let device = Device::system_default().expect("no device found"); + + #[cfg(feature = "private")] + { + println!("Vendor: {:?}", unsafe { device.vendor() }); + println!("Family: {:?}", unsafe { device.family_name() }); + } + println!( + "Max threads per threadgroup: {:?}", + device.max_threads_per_threadgroup() + ); + #[cfg(target_os = "macos")] + { + println!("Integrated GPU: {:?}", device.is_low_power()); + println!("Headless: {:?}", device.is_headless()); + println!("D24S8: {:?}", device.d24_s8_supported()); + } + println!("maxBufferLength: {} Mb", device.max_buffer_length() >> 20); + println!( + "Indirect argument buffer: {:?}", + device.argument_buffers_support() + ); +} diff --git a/third_party/rust/metal/examples/circle/README.md b/third_party/rust/metal/examples/circle/README.md new file mode 100644 index 0000000000..f51853ac38 --- /dev/null +++ b/third_party/rust/metal/examples/circle/README.md @@ -0,0 +1,11 @@ +## circle + +Renders a circle in a window. As metal primitive types are only limited to point, line and triangle shape, this example shows how we can form complex structures out of primitive types. + +![Screenshot of the final render](./screenshot.png) + +## To Run + +``` +cargo run --example circle +``` diff --git a/third_party/rust/metal/examples/circle/main.rs b/third_party/rust/metal/examples/circle/main.rs new file mode 100644 index 0000000000..18da704421 --- /dev/null +++ b/third_party/rust/metal/examples/circle/main.rs @@ -0,0 +1,251 @@ +use metal::*; + +use winit::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + platform::macos::WindowExtMacOS, +}; + +use cocoa::{appkit::NSView, base::id as cocoa_id}; +use core_graphics_types::geometry::CGSize; + +use objc::{rc::autoreleasepool, runtime::YES}; + +use std::mem; + +// Declare the data structures needed to carry vertex layout to +// metal shading language(MSL) program. Use #[repr(C)], to make +// the data structure compatible with C++ type data structure +// for vertex defined in MSL program as MSL program is broadly +// based on C++ +#[repr(C)] +#[derive(Debug)] +pub struct position(cty::c_float, cty::c_float); +#[repr(C)] +#[derive(Debug)] +pub struct color(cty::c_float, cty::c_float, cty::c_float); +#[repr(C)] +#[derive(Debug)] +pub struct AAPLVertex { + p: position, + c: color, +} + +fn main() { + // Create a window for viewing the content + let event_loop = EventLoop::new(); + let events_loop = winit::event_loop::EventLoop::new(); + let size = winit::dpi::LogicalSize::new(800, 600); + + let window = winit::window::WindowBuilder::new() + .with_inner_size(size) + .with_title("Metal".to_string()) + .build(&events_loop) + .unwrap(); + + // Set up the GPU device found in the system + let device = Device::system_default().expect("no device found"); + println!("Your device is: {}", device.name(),); + + let binary_archive_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("examples/circle/binary_archive.metallib"); + + let binary_archive_url = + URL::new_with_string(&format!("file://{}", binary_archive_path.display())); + + let binary_archive_descriptor = BinaryArchiveDescriptor::new(); + if binary_archive_path.exists() { + binary_archive_descriptor.set_url(&binary_archive_url); + } + + // Set up a binary archive to cache compiled shaders. + let binary_archive = device + .new_binary_archive_with_descriptor(&binary_archive_descriptor) + .unwrap(); + + let library_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("examples/circle/shaders.metallib"); + + // Use the metallib file generated out of .metal shader file + let library = device.new_library_with_file(library_path).unwrap(); + + // The render pipeline generated from the vertex and fragment shaders in the .metal shader file. + let pipeline_state = prepare_pipeline_state(&device, &library, &binary_archive); + + // Serialize the binary archive to disk. + binary_archive + .serialize_to_url(&binary_archive_url) + .unwrap(); + + // Set the command queue used to pass commands to the device. + let command_queue = device.new_command_queue(); + + // Currently, MetalLayer is the only interface that provide + // layers to carry drawable texture from GPU rendaring through metal + // library to viewable windows. + let layer = MetalLayer::new(); + layer.set_device(&device); + layer.set_pixel_format(MTLPixelFormat::BGRA8Unorm); + layer.set_presents_with_transaction(false); + + unsafe { + let view = window.ns_view() as cocoa_id; + view.setWantsLayer(YES); + view.setLayer(mem::transmute(layer.as_ref())); + } + + let draw_size = window.inner_size(); + layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64)); + + let vbuf = { + let vertex_data = create_vertex_points_for_circle(); + let vertex_data = vertex_data.as_slice(); + + device.new_buffer_with_data( + vertex_data.as_ptr() as *const _, + (vertex_data.len() * mem::size_of::<AAPLVertex>()) as u64, + MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged, + ) + }; + + event_loop.run(move |event, _, control_flow| { + autoreleasepool(|| { + // ControlFlow::Wait pauses the event loop if no events are available to process. + // This is ideal for non-game applications that only update in response to user + // input, and uses significantly less power/CPU time than ControlFlow::Poll. + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } => { + println!("The close button was pressed; stopping"); + *control_flow = ControlFlow::Exit + } + Event::MainEventsCleared => { + // Queue a RedrawRequested event. + window.request_redraw(); + } + Event::RedrawRequested(_) => { + // It's preferrable to render in this event rather than in MainEventsCleared, since + // rendering in here allows the program to gracefully handle redraws requested + // by the OS. + let drawable = match layer.next_drawable() { + Some(drawable) => drawable, + None => return, + }; + + // Create a new command buffer for each render pass to the current drawable + let command_buffer = command_queue.new_command_buffer(); + + // Obtain a renderPassDescriptor generated from the view's drawable textures. + let render_pass_descriptor = RenderPassDescriptor::new(); + prepare_render_pass_descriptor(&render_pass_descriptor, drawable.texture()); + + // Create a render command encoder. + let encoder = + command_buffer.new_render_command_encoder(&render_pass_descriptor); + encoder.set_render_pipeline_state(&pipeline_state); + // Pass in the parameter data. + encoder.set_vertex_buffer(0, Some(&vbuf), 0); + // Draw the triangles which will eventually form the circle. + encoder.draw_primitives(MTLPrimitiveType::TriangleStrip, 0, 1080); + encoder.end_encoding(); + + // Schedule a present once the framebuffer is complete using the current drawable. + command_buffer.present_drawable(&drawable); + + // Finalize rendering here & push the command buffer to the GPU. + command_buffer.commit(); + } + _ => (), + } + }); + }); +} + +// If we want to draw a circle, we need to draw it out of the three primitive +// types available with metal framework. Triangle is used in this case to form +// the circle. If we consider a circle to be total of 360 degree at center, we +// can form small triangle with one point at origin and two points at the +// perimeter of the circle for each degree. Eventually, if we can take enough +// triangle virtices for total of 360 degree, the triangles together will +// form a circle. This function captures the triangle vertices for each degree +// and push the co-ordinates of the vertices to a rust vector +fn create_vertex_points_for_circle() -> Vec<AAPLVertex> { + let mut v: Vec<AAPLVertex> = Vec::new(); + let origin_x: f32 = 0.0; + let origin_y: f32 = 0.0; + + // Size of the circle + let circle_size = 0.8f32; + + for i in 0..720 { + let y = i as f32; + // Get the X co-ordinate of each point on the perimeter of circle + let position_x: f32 = y.to_radians().cos() * 100.0; + let position_x: f32 = position_x.trunc() / 100.0; + // Set the size of the circle + let position_x: f32 = position_x * circle_size; + // Get the Y co-ordinate of each point on the perimeter of circle + let position_y: f32 = y.to_radians().sin() * 100.0; + let position_y: f32 = position_y.trunc() / 100.0; + // Set the size of the circle + let position_y: f32 = position_y * circle_size; + + v.push(AAPLVertex { + p: position(position_x, position_y), + c: color(0.7, 0.3, 0.5), + }); + + if (i + 1) % 2 == 0 { + // For each two points on perimeter, push one point of origin + v.push(AAPLVertex { + p: position(origin_x, origin_y), + c: color(0.2, 0.7, 0.4), + }); + } + } + + v +} + +fn prepare_render_pass_descriptor(descriptor: &RenderPassDescriptorRef, texture: &TextureRef) { + let color_attachment = descriptor.color_attachments().object_at(0).unwrap(); + + color_attachment.set_texture(Some(texture)); + color_attachment.set_load_action(MTLLoadAction::Clear); + // Setting a background color + color_attachment.set_clear_color(MTLClearColor::new(0.5, 0.5, 0.8, 1.0)); + color_attachment.set_store_action(MTLStoreAction::Store); +} + +fn prepare_pipeline_state( + device: &Device, + library: &Library, + binary_archive: &BinaryArchive, +) -> RenderPipelineState { + let vert = library.get_function("vs", None).unwrap(); + let frag = library.get_function("ps", None).unwrap(); + + let pipeline_state_descriptor = RenderPipelineDescriptor::new(); + pipeline_state_descriptor.set_vertex_function(Some(&vert)); + pipeline_state_descriptor.set_fragment_function(Some(&frag)); + pipeline_state_descriptor + .color_attachments() + .object_at(0) + .unwrap() + .set_pixel_format(MTLPixelFormat::BGRA8Unorm); + // Set the binary archives to search for a cached pipeline in. + pipeline_state_descriptor.set_binary_archives(&[binary_archive]); + + // Add the pipeline descriptor to the binary archive cache. + binary_archive + .add_render_pipeline_functions_with_descriptor(&pipeline_state_descriptor) + .unwrap(); + + device + .new_render_pipeline_state(&pipeline_state_descriptor) + .unwrap() +} diff --git a/third_party/rust/metal/examples/circle/screenshot.png b/third_party/rust/metal/examples/circle/screenshot.png Binary files differnew file mode 100644 index 0000000000..38f86e733d --- /dev/null +++ b/third_party/rust/metal/examples/circle/screenshot.png diff --git a/third_party/rust/metal/examples/circle/shaders.metal b/third_party/rust/metal/examples/circle/shaders.metal new file mode 100644 index 0000000000..037af8a233 --- /dev/null +++ b/third_party/rust/metal/examples/circle/shaders.metal @@ -0,0 +1,39 @@ +#include <metal_stdlib> + +#include <simd/simd.h> + +using namespace metal; + +typedef struct { + float x; + float y; +}position; + +typedef struct { + float r; + float g; + float b; +}color; + +typedef struct { + position p; + color c; +}AAPLVertex; + +struct ColorInOut { + float4 position[[position]]; + float4 color; +}; + +vertex ColorInOut vs(constant AAPLVertex * vertex_array[[buffer(0)]], unsigned int vid[[vertex_id]]) { + ColorInOut out; + + out.position = float4(float2(vertex_array[vid].p.x, vertex_array[vid].p.y), 0.0, 1.0); + out.color = float4(float3(vertex_array[vid].c.r, vertex_array[vid].c.g, vertex_array[vid].c.b), 1.0); + + return out; +} + +fragment float4 ps(ColorInOut in [[stage_in]]) { + return in.color; +} diff --git a/third_party/rust/metal/examples/circle/shaders.metallib b/third_party/rust/metal/examples/circle/shaders.metallib Binary files differnew file mode 100644 index 0000000000..cbb9bc5e5a --- /dev/null +++ b/third_party/rust/metal/examples/circle/shaders.metallib diff --git a/third_party/rust/metal/examples/compute/compute-argument-buffer.metal b/third_party/rust/metal/examples/compute/compute-argument-buffer.metal new file mode 100644 index 0000000000..1dcc79daf5 --- /dev/null +++ b/third_party/rust/metal/examples/compute/compute-argument-buffer.metal @@ -0,0 +1,14 @@ +#include <metal_stdlib> + +using namespace metal; + +struct SumInput { + device uint *data; + volatile device atomic_uint *sum; +}; + +kernel void sum(device SumInput& input [[ buffer(0) ]], + uint gid [[ thread_position_in_grid ]]) +{ + atomic_fetch_add_explicit(input.sum, input.data[gid], memory_order_relaxed); +} diff --git a/third_party/rust/metal/examples/compute/compute-argument-buffer.rs b/third_party/rust/metal/examples/compute/compute-argument-buffer.rs new file mode 100644 index 0000000000..97527091a3 --- /dev/null +++ b/third_party/rust/metal/examples/compute/compute-argument-buffer.rs @@ -0,0 +1,95 @@ +// Copyright 2017 GFX developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use metal::*; +use objc::rc::autoreleasepool; +use std::mem; + +static LIBRARY_SRC: &str = include_str!("compute-argument-buffer.metal"); + +fn main() { + autoreleasepool(|| { + let device = Device::system_default().expect("no device found"); + let command_queue = device.new_command_queue(); + + let data = [ + 1u32, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, + ]; + + let buffer = device.new_buffer_with_data( + unsafe { mem::transmute(data.as_ptr()) }, + (data.len() * mem::size_of::<u32>()) as u64, + MTLResourceOptions::CPUCacheModeDefaultCache, + ); + + let sum = { + let data = [0u32]; + device.new_buffer_with_data( + unsafe { mem::transmute(data.as_ptr()) }, + (data.len() * mem::size_of::<u32>()) as u64, + MTLResourceOptions::CPUCacheModeDefaultCache, + ) + }; + + let command_buffer = command_queue.new_command_buffer(); + let encoder = command_buffer.new_compute_command_encoder(); + + let library = device + .new_library_with_source(LIBRARY_SRC, &CompileOptions::new()) + .unwrap(); + let kernel = library.get_function("sum", None).unwrap(); + + let argument_encoder = kernel.new_argument_encoder(0); + let arg_buffer = device.new_buffer( + argument_encoder.encoded_length(), + MTLResourceOptions::empty(), + ); + argument_encoder.set_argument_buffer(&arg_buffer, 0); + argument_encoder.set_buffer(0, &buffer, 0); + argument_encoder.set_buffer(1, &sum, 0); + + let pipeline_state_descriptor = ComputePipelineDescriptor::new(); + pipeline_state_descriptor.set_compute_function(Some(&kernel)); + + let pipeline_state = device + .new_compute_pipeline_state_with_function( + pipeline_state_descriptor.compute_function().unwrap(), + ) + .unwrap(); + + encoder.set_compute_pipeline_state(&pipeline_state); + encoder.set_buffer(0, Some(&arg_buffer), 0); + + encoder.use_resource(&buffer, MTLResourceUsage::Read); + encoder.use_resource(&sum, MTLResourceUsage::Write); + + let width = 16; + + let thread_group_count = MTLSize { + width, + height: 1, + depth: 1, + }; + + let thread_group_size = MTLSize { + width: (data.len() as u64 + width) / width, + height: 1, + depth: 1, + }; + + encoder.dispatch_thread_groups(thread_group_count, thread_group_size); + encoder.end_encoding(); + command_buffer.commit(); + command_buffer.wait_until_completed(); + + let ptr = sum.contents() as *mut u32; + unsafe { + assert_eq!(465, *ptr); + } + }); +} diff --git a/third_party/rust/metal/examples/compute/embedded-lib.rs b/third_party/rust/metal/examples/compute/embedded-lib.rs new file mode 100644 index 0000000000..0fd193abe3 --- /dev/null +++ b/third_party/rust/metal/examples/compute/embedded-lib.rs @@ -0,0 +1,24 @@ +// Copyright 2017 GFX developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use metal::*; +use objc::rc::autoreleasepool; + +fn main() { + let library_data = include_bytes!("shaders.metallib"); + + autoreleasepool(|| { + let device = Device::system_default().expect("no device found"); + + let library = device.new_library_with_data(&library_data[..]).unwrap(); + let kernel = library.get_function("sum", None).unwrap(); + + println!("Function name: {}", kernel.name()); + println!("Function type: {:?}", kernel.function_type()); + println!("OK"); + }); +} diff --git a/third_party/rust/metal/examples/compute/main.rs b/third_party/rust/metal/examples/compute/main.rs new file mode 100644 index 0000000000..6497c790ae --- /dev/null +++ b/third_party/rust/metal/examples/compute/main.rs @@ -0,0 +1,91 @@ +// Copyright 2017 GFX developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use metal::*; +use objc::rc::autoreleasepool; +use std::mem; + +fn main() { + autoreleasepool(|| { + let device = Device::system_default().expect("no device found"); + let command_queue = device.new_command_queue(); + + let data = [ + 1u32, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, + ]; + + let buffer = device.new_buffer_with_data( + unsafe { mem::transmute(data.as_ptr()) }, + (data.len() * mem::size_of::<u32>()) as u64, + MTLResourceOptions::CPUCacheModeDefaultCache, + ); + + let sum = { + let data = [0u32]; + device.new_buffer_with_data( + unsafe { mem::transmute(data.as_ptr()) }, + (data.len() * mem::size_of::<u32>()) as u64, + MTLResourceOptions::CPUCacheModeDefaultCache, + ) + }; + + let command_buffer = command_queue.new_command_buffer(); + + command_buffer.set_label("label"); + let block = block::ConcreteBlock::new(move |buffer: &metal::CommandBufferRef| { + println!("{}", buffer.label()); + }) + .copy(); + + command_buffer.add_completed_handler(&block); + + let encoder = command_buffer.new_compute_command_encoder(); + let library_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("examples/compute/shaders.metallib"); + + let library = device.new_library_with_file(library_path).unwrap(); + let kernel = library.get_function("sum", None).unwrap(); + + let pipeline_state_descriptor = ComputePipelineDescriptor::new(); + pipeline_state_descriptor.set_compute_function(Some(&kernel)); + + let pipeline_state = device + .new_compute_pipeline_state_with_function( + pipeline_state_descriptor.compute_function().unwrap(), + ) + .unwrap(); + + encoder.set_compute_pipeline_state(&pipeline_state); + encoder.set_buffer(0, Some(&buffer), 0); + encoder.set_buffer(1, Some(&sum), 0); + + let width = 16; + + let thread_group_count = MTLSize { + width, + height: 1, + depth: 1, + }; + + let thread_group_size = MTLSize { + width: (data.len() as u64 + width) / width, + height: 1, + depth: 1, + }; + + encoder.dispatch_thread_groups(thread_group_count, thread_group_size); + encoder.end_encoding(); + command_buffer.commit(); + command_buffer.wait_until_completed(); + + let ptr = sum.contents() as *mut u32; + unsafe { + assert_eq!(465, *ptr); + } + }); +} diff --git a/third_party/rust/metal/examples/compute/shaders.metal b/third_party/rust/metal/examples/compute/shaders.metal new file mode 100644 index 0000000000..51363a1d36 --- /dev/null +++ b/third_party/rust/metal/examples/compute/shaders.metal @@ -0,0 +1,10 @@ +#include <metal_stdlib> + +using namespace metal; + +kernel void sum(device uint *data [[ buffer(0) ]], + volatile device atomic_uint *sum [[ buffer(1) ]], + uint gid [[ thread_position_in_grid ]]) +{ + atomic_fetch_add_explicit(sum, data[gid], memory_order_relaxed); +} diff --git a/third_party/rust/metal/examples/compute/shaders.metallib b/third_party/rust/metal/examples/compute/shaders.metallib Binary files differnew file mode 100644 index 0000000000..af7cb17240 --- /dev/null +++ b/third_party/rust/metal/examples/compute/shaders.metallib diff --git a/third_party/rust/metal/examples/events/main.rs b/third_party/rust/metal/examples/events/main.rs new file mode 100644 index 0000000000..9e4fe0e820 --- /dev/null +++ b/third_party/rust/metal/examples/events/main.rs @@ -0,0 +1,50 @@ +// Copyright 2020 GFX developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use dispatch::{Queue, QueueAttribute}; +use metal::*; + +/// This example replicates `Synchronizing Events Between a GPU and the CPU` article. +/// See https://developer.apple.com/documentation/metal/synchronization/synchronizing_events_between_a_gpu_and_the_cpu +fn main() { + let device = Device::system_default().expect("No device found"); + + let command_queue = device.new_command_queue(); + let command_buffer = command_queue.new_command_buffer(); + + // Shareable event + let shared_event = device.new_shared_event(); + + // Shareable event listener + let my_queue = Queue::create( + "com.example.apple-samplecode.MyQueue", + QueueAttribute::Serial, + ); + + // Enable `dispatch` feature to use dispatch queues, + // otherwise unsafe `from_queue_handle` is available for use with native APIs. + let shared_event_listener = SharedEventListener::from_queue(&my_queue); + + // Register CPU work + let notify_block = block::ConcreteBlock::new(move |evt: &SharedEventRef, val: u64| { + println!("Got notification from GPU: {}", val); + evt.set_signaled_value(3); + }); + + shared_event.notify(&shared_event_listener, 2, notify_block.copy()); + + // Encode GPU work + command_buffer.encode_signal_event(&shared_event, 1); + command_buffer.encode_signal_event(&shared_event, 2); + command_buffer.encode_wait_for_event(&shared_event, 3); + + command_buffer.commit(); + + command_buffer.wait_until_completed(); + + println!("Done"); +} diff --git a/third_party/rust/metal/examples/fence/main.rs b/third_party/rust/metal/examples/fence/main.rs new file mode 100644 index 0000000000..53515d39f5 --- /dev/null +++ b/third_party/rust/metal/examples/fence/main.rs @@ -0,0 +1,30 @@ +// Copyright 2020 GFX developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use metal::*; + +fn main() { + let device = Device::system_default().expect("No device found"); + + let command_queue = device.new_command_queue(); + let command_buffer = command_queue.new_command_buffer(); + + let fence = device.new_fence(); + + let blit_encoder = command_buffer.new_blit_command_encoder(); + blit_encoder.update_fence(&fence); + blit_encoder.end_encoding(); + + let compute_encoder = command_buffer.new_compute_command_encoder(); + compute_encoder.wait_for_fence(&fence); + compute_encoder.end_encoding(); + + command_buffer.commit(); + command_buffer.wait_until_completed(); + + println!("Done"); +} diff --git a/third_party/rust/metal/examples/headless-render/README.md b/third_party/rust/metal/examples/headless-render/README.md new file mode 100644 index 0000000000..6bc434b44a --- /dev/null +++ b/third_party/rust/metal/examples/headless-render/README.md @@ -0,0 +1,11 @@ +## headless-render + +Renders the triangle from the [window example](../window) headlessly and then writes it to a PNG file. + +![Screenshot of the final render](./screenshot.png) + +## To Run + +``` +cargo run --example headless-render +``` diff --git a/third_party/rust/metal/examples/headless-render/main.rs b/third_party/rust/metal/examples/headless-render/main.rs new file mode 100644 index 0000000000..ed68da1a53 --- /dev/null +++ b/third_party/rust/metal/examples/headless-render/main.rs @@ -0,0 +1,159 @@ +use std::mem; +use std::path::PathBuf; + +use std::fs::File; +use std::io::BufWriter; + +use metal::{ + Buffer, Device, DeviceRef, LibraryRef, MTLClearColor, MTLLoadAction, MTLOrigin, MTLPixelFormat, + MTLPrimitiveType, MTLRegion, MTLResourceOptions, MTLSize, MTLStoreAction, RenderPassDescriptor, + RenderPassDescriptorRef, RenderPipelineDescriptor, RenderPipelineState, Texture, + TextureDescriptor, TextureRef, +}; +use png::ColorType; + +const VIEW_WIDTH: u64 = 512; +const VIEW_HEIGHT: u64 = 512; +const TOTAL_BYTES: usize = (VIEW_WIDTH * VIEW_HEIGHT * 4) as usize; + +const VERTEX_SHADER: &'static str = "triangle_vertex"; +const FRAGMENT_SHADER: &'static str = "triangle_fragment"; + +// [2 bytes position, 3 bytes color] * 3 +#[rustfmt::skip] +const VERTEX_ATTRIBS: [f32; 15] = [ + 0.0, 0.5, 1.0, 0.0, 0.0, + -0.5, -0.5, 0.0, 1.0, 0.0, + 0.5, -0.5, 0.0, 0.0, 1.0, +]; + +/// This example shows how to render headlessly by: +/// +/// 1. Rendering a triangle to an MtlDrawable +/// +/// 2. Waiting for the render to complete and the color texture to be synchronized with the CPU +/// by using a blit command encoder +/// +/// 3. Reading the texture bytes from the MtlTexture +/// +/// 4. Saving the texture to a PNG file +fn main() { + let device = Device::system_default().expect("No device found"); + + let texture = create_texture(&device); + + let library_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("examples/window/shaders.metallib"); + + let library = device.new_library_with_file(library_path).unwrap(); + + let pipeline_state = prepare_pipeline_state(&device, &library); + + let command_queue = device.new_command_queue(); + + let vertex_buffer = create_vertex_buffer(&device); + + let render_pass_descriptor = RenderPassDescriptor::new(); + initialize_color_attachment(&render_pass_descriptor, &texture); + + let command_buffer = command_queue.new_command_buffer(); + let rc_encoder = command_buffer.new_render_command_encoder(&render_pass_descriptor); + rc_encoder.set_render_pipeline_state(&pipeline_state); + rc_encoder.set_vertex_buffer(0, Some(&vertex_buffer), 0); + rc_encoder.draw_primitives(MTLPrimitiveType::Triangle, 0, 3); + rc_encoder.end_encoding(); + + render_pass_descriptor + .color_attachments() + .object_at(0) + .unwrap() + .set_load_action(MTLLoadAction::DontCare); + + let blit_encoder = command_buffer.new_blit_command_encoder(); + blit_encoder.synchronize_resource(&texture); + blit_encoder.end_encoding(); + + command_buffer.commit(); + + command_buffer.wait_until_completed(); + + save_image(&texture); +} + +fn save_image(texture: &TextureRef) { + let mut image = vec![0; TOTAL_BYTES]; + + texture.get_bytes( + image.as_mut_ptr() as *mut std::ffi::c_void, + VIEW_WIDTH * 4, + MTLRegion { + origin: MTLOrigin { x: 0, y: 0, z: 0 }, + size: MTLSize { + width: VIEW_WIDTH, + height: VIEW_HEIGHT, + depth: 1, + }, + }, + 0, + ); + + let out_file = + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/headless-render/out.png"); + let file = File::create(&out_file).unwrap(); + let ref mut w = BufWriter::new(file); + + let mut encoder = png::Encoder::new(w, VIEW_WIDTH as u32, VIEW_HEIGHT as u32); + encoder.set_color(ColorType::RGBA); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().unwrap(); + + writer.write_image_data(&image).unwrap(); + + println!("Image saved to {:?}", out_file); +} + +fn create_texture(device: &Device) -> Texture { + let texture = TextureDescriptor::new(); + texture.set_width(VIEW_WIDTH); + texture.set_height(VIEW_HEIGHT); + texture.set_pixel_format(MTLPixelFormat::RGBA8Unorm); + + device.new_texture(&texture) +} + +fn prepare_pipeline_state(device: &DeviceRef, library: &LibraryRef) -> RenderPipelineState { + let vert = library.get_function(VERTEX_SHADER, None).unwrap(); + let frag = library.get_function(FRAGMENT_SHADER, None).unwrap(); + + let pipeline_state_descriptor = RenderPipelineDescriptor::new(); + + pipeline_state_descriptor.set_vertex_function(Some(&vert)); + pipeline_state_descriptor.set_fragment_function(Some(&frag)); + + pipeline_state_descriptor + .color_attachments() + .object_at(0) + .unwrap() + .set_pixel_format(MTLPixelFormat::RGBA8Unorm); + + device + .new_render_pipeline_state(&pipeline_state_descriptor) + .unwrap() +} + +fn create_vertex_buffer(device: &DeviceRef) -> Buffer { + device.new_buffer_with_data( + VERTEX_ATTRIBS.as_ptr() as *const _, + (VERTEX_ATTRIBS.len() * mem::size_of::<f32>()) as u64, + MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged, + ) +} + +fn initialize_color_attachment(descriptor: &RenderPassDescriptorRef, texture: &TextureRef) { + let color_attachment = descriptor.color_attachments().object_at(0).unwrap(); + + color_attachment.set_texture(Some(texture)); + color_attachment.set_load_action(MTLLoadAction::Clear); + color_attachment.set_clear_color(MTLClearColor::new(0.5, 0.2, 0.2, 1.0)); + color_attachment.set_store_action(MTLStoreAction::Store); +} diff --git a/third_party/rust/metal/examples/headless-render/screenshot.png b/third_party/rust/metal/examples/headless-render/screenshot.png Binary files differnew file mode 100644 index 0000000000..2af9c5895f --- /dev/null +++ b/third_party/rust/metal/examples/headless-render/screenshot.png diff --git a/third_party/rust/metal/examples/library/main.rs b/third_party/rust/metal/examples/library/main.rs new file mode 100644 index 0000000000..7223db89c1 --- /dev/null +++ b/third_party/rust/metal/examples/library/main.rs @@ -0,0 +1,17 @@ +// Copyright 2016 GFX developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use metal::*; + +const PROGRAM: &'static str = ""; + +fn main() { + let device = Device::system_default().expect("no device found"); + + let options = CompileOptions::new(); + let _library = device.new_library_with_source(PROGRAM, &options); +} diff --git a/third_party/rust/metal/examples/mps/main.rs b/third_party/rust/metal/examples/mps/main.rs new file mode 100644 index 0000000000..efff9f4eba --- /dev/null +++ b/third_party/rust/metal/examples/mps/main.rs @@ -0,0 +1,147 @@ +use metal::*; +use std::ffi::c_void; +use std::mem; + +#[repr(C)] +struct Vertex { + xyz: [f32; 3], +} + +type Ray = MPSRayOriginMinDistanceDirectionMaxDistance; +type Intersection = MPSIntersectionDistancePrimitiveIndexCoordinates; + +// Original example taken from https://sergeyreznik.github.io/metal-ray-tracer/part-1/index.html +fn main() { + let device = Device::system_default().expect("No device found"); + + let library_path = + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/mps/shaders.metallib"); + let library = device + .new_library_with_file(library_path) + .expect("Failed to load shader library"); + + let generate_rays_pipeline = create_pipeline("generateRays", &library, &device); + + let queue = device.new_command_queue(); + let command_buffer = queue.new_command_buffer(); + + // Simple vertex/index buffer data + + let vertices: [Vertex; 3] = [ + Vertex { + xyz: [0.25, 0.25, 0.0], + }, + Vertex { + xyz: [0.75, 0.25, 0.0], + }, + Vertex { + xyz: [0.50, 0.75, 0.0], + }, + ]; + + let vertex_stride = mem::size_of::<Vertex>(); + + let indices: [u32; 3] = [0, 1, 2]; + + // Vertex data should be stored in private or managed buffers on discrete GPU systems (AMD, NVIDIA). + // Private buffers are stored entirely in GPU memory and cannot be accessed by the CPU. Managed + // buffers maintain a copy in CPU memory and a copy in GPU memory. + let buffer_opts = MTLResourceOptions::StorageModeManaged; + + let vertex_buffer = device.new_buffer_with_data( + vertices.as_ptr() as *const c_void, + (vertex_stride * vertices.len()) as u64, + buffer_opts, + ); + + let index_buffer = device.new_buffer_with_data( + indices.as_ptr() as *const c_void, + (mem::size_of::<u32>() * indices.len()) as u64, + buffer_opts, + ); + + // Build an acceleration structure using our vertex and index buffers containing the single triangle. + let acceleration_structure = TriangleAccelerationStructure::from_device(&device) + .expect("Failed to create acceleration structure"); + + acceleration_structure.set_vertex_buffer(Some(&vertex_buffer)); + acceleration_structure.set_vertex_stride(vertex_stride as u64); + acceleration_structure.set_index_buffer(Some(&index_buffer)); + acceleration_structure.set_index_type(MPSDataType::UInt32); + acceleration_structure.set_triangle_count(1); + acceleration_structure.set_usage(MPSAccelerationStructureUsage::None); + acceleration_structure.rebuild(); + + let ray_intersector = + RayIntersector::from_device(&device).expect("Failed to create ray intersector"); + + ray_intersector.set_ray_stride(mem::size_of::<Ray>() as u64); + ray_intersector.set_ray_data_type(MPSRayDataType::OriginMinDistanceDirectionMaxDistance); + ray_intersector.set_intersection_stride(mem::size_of::<Intersection>() as u64); + ray_intersector + .set_intersection_data_type(MPSIntersectionDataType::DistancePrimitiveIndexCoordinates); + + // Create a buffer to hold generated rays and intersection results + let ray_count = 1024; + let ray_buffer = device.new_buffer( + (mem::size_of::<Ray>() * ray_count) as u64, + MTLResourceOptions::StorageModePrivate, + ); + + let intersection_buffer = device.new_buffer( + (mem::size_of::<Intersection>() * ray_count) as u64, + MTLResourceOptions::StorageModePrivate, + ); + + // Run the compute shader to generate rays + let encoder = command_buffer.new_compute_command_encoder(); + encoder.set_buffer(0, Some(&ray_buffer), 0); + encoder.set_compute_pipeline_state(&generate_rays_pipeline); + encoder.dispatch_thread_groups( + MTLSize { + width: 4, + height: 4, + depth: 1, + }, + MTLSize { + width: 8, + height: 8, + depth: 1, + }, + ); + encoder.end_encoding(); + + // Intersect rays with triangles inside acceleration structure + ray_intersector.encode_intersection_to_command_buffer( + &command_buffer, + MPSIntersectionType::Nearest, + &ray_buffer, + 0, + &intersection_buffer, + 0, + ray_count as u64, + &acceleration_structure, + ); + + command_buffer.commit(); + command_buffer.wait_until_completed(); + + println!("Done"); +} + +fn create_pipeline(func: &str, library: &LibraryRef, device: &DeviceRef) -> ComputePipelineState { + // Create compute pipelines will will execute code on the GPU + let compute_descriptor = ComputePipelineDescriptor::new(); + + // Set to YES to allow compiler to make certain optimizations + compute_descriptor.set_thread_group_size_is_multiple_of_thread_execution_width(true); + + let function = library.get_function(func, None).unwrap(); + compute_descriptor.set_compute_function(Some(&function)); + + let pipeline = device + .new_compute_pipeline_state(&compute_descriptor) + .unwrap(); + + pipeline +} diff --git a/third_party/rust/metal/examples/mps/shaders.metal b/third_party/rust/metal/examples/mps/shaders.metal new file mode 100644 index 0000000000..d824d70d1b --- /dev/null +++ b/third_party/rust/metal/examples/mps/shaders.metal @@ -0,0 +1,26 @@ +// +// Created by Sergey Reznik on 9/15/18. +// Copyright © 2018 Serhii Rieznik. All rights reserved. +// + +// Taken from https://github.com/sergeyreznik/metal-ray-tracer/tree/part-1/source/Shaders +// MIT License https://github.com/sergeyreznik/metal-ray-tracer/blob/part-1/LICENSE + +#include <MetalPerformanceShaders/MetalPerformanceShaders.h> + +using Ray = MPSRayOriginMinDistanceDirectionMaxDistance; +using Intersection = MPSIntersectionDistancePrimitiveIndexCoordinates; + +kernel void generateRays( + device Ray* rays [[buffer(0)]], + uint2 coordinates [[thread_position_in_grid]], + uint2 size [[threads_per_grid]]) +{ + float2 uv = float2(coordinates) / float2(size - 1); + + uint rayIndex = coordinates.x + coordinates.y * size.x; + rays[rayIndex].origin = MPSPackedFloat3(uv.x, uv.y, -1.0); + rays[rayIndex].direction = MPSPackedFloat3(0.0, 0.0, 1.0); + rays[rayIndex].minDistance = 0.0f; + rays[rayIndex].maxDistance = 2.0f; +} diff --git a/third_party/rust/metal/examples/mps/shaders.metallib b/third_party/rust/metal/examples/mps/shaders.metallib Binary files differnew file mode 100644 index 0000000000..2cecf7b837 --- /dev/null +++ b/third_party/rust/metal/examples/mps/shaders.metallib diff --git a/third_party/rust/metal/examples/reflection/main.rs b/third_party/rust/metal/examples/reflection/main.rs new file mode 100644 index 0000000000..efe9fc2994 --- /dev/null +++ b/third_party/rust/metal/examples/reflection/main.rs @@ -0,0 +1,75 @@ +// Copyright 2016 GFX developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use metal::*; +use objc::rc::autoreleasepool; + +const PROGRAM: &'static str = " + #include <metal_stdlib>\n\ + + using namespace metal;\n\ + + typedef struct {\n\ + float2 position;\n\ + float3 color;\n\ + } vertex_t;\n\ + + struct ColorInOut {\n\ + float4 position [[position]];\n\ + float4 color;\n\ + };\n\ + + vertex ColorInOut vs(device vertex_t* vertex_array [[ buffer(0) ]],\n\ + unsigned int vid [[ vertex_id ]])\n\ + {\n\ + ColorInOut out;\n\ + + out.position = float4(float2(vertex_array[vid].position), 0.0, 1.0);\n\ + out.color = float4(float3(vertex_array[vid].color), 1.0);\n\ + + return out;\n\ + }\n\ + + fragment float4 ps(ColorInOut in [[stage_in]])\n\ + {\n\ + return in.color;\n\ + };\n\ +"; + +fn main() { + autoreleasepool(|| { + let device = Device::system_default().expect("no device found"); + + let options = CompileOptions::new(); + let library = device.new_library_with_source(PROGRAM, &options).unwrap(); + let (vs, ps) = ( + library.get_function("vs", None).unwrap(), + library.get_function("ps", None).unwrap(), + ); + + let vertex_desc = VertexDescriptor::new(); + + let desc = RenderPipelineDescriptor::new(); + desc.set_vertex_function(Some(&vs)); + desc.set_fragment_function(Some(&ps)); + desc.set_vertex_descriptor(Some(vertex_desc)); + + println!("{:?}", desc); + + let reflect_options = MTLPipelineOption::ArgumentInfo | MTLPipelineOption::BufferTypeInfo; + let (_, reflection) = device + .new_render_pipeline_state_with_reflection(&desc, reflect_options) + .unwrap(); + + println!("Vertex arguments: "); + let vertex_arguments = reflection.vertex_arguments(); + for index in 0..vertex_arguments.count() { + let argument = vertex_arguments.object_at(index).unwrap(); + println!("{:?}", argument); + } + }); +} diff --git a/third_party/rust/metal/examples/shader-dylib/main.rs b/third_party/rust/metal/examples/shader-dylib/main.rs new file mode 100644 index 0000000000..b713e20e06 --- /dev/null +++ b/third_party/rust/metal/examples/shader-dylib/main.rs @@ -0,0 +1,177 @@ +use cocoa::{appkit::NSView, base::id as cocoa_id}; +use core_graphics_types::geometry::CGSize; + +use metal::*; +use objc::{rc::autoreleasepool, runtime::YES}; + +use winit::{ + event::{Event, WindowEvent}, + event_loop::ControlFlow, + platform::macos::WindowExtMacOS, +}; + +use std::mem; + +struct App { + pub device: Device, + pub command_queue: CommandQueue, + pub layer: MetalLayer, + pub image_fill_cps: ComputePipelineState, + pub width: u32, + pub height: u32, +} + +fn select_device() -> Option<Device> { + let devices = Device::all(); + for device in devices { + if device.supports_dynamic_libraries() { + return Some(device); + } + } + + None +} + +impl App { + fn new(window: &winit::window::Window) -> Self { + let device = select_device().expect("no device found that supports dynamic libraries"); + let command_queue = device.new_command_queue(); + + let layer = MetalLayer::new(); + layer.set_device(&device); + layer.set_pixel_format(MTLPixelFormat::BGRA8Unorm); + layer.set_presents_with_transaction(false); + layer.set_framebuffer_only(false); + unsafe { + let view = window.ns_view() as cocoa_id; + view.setWantsLayer(YES); + view.setLayer(mem::transmute(layer.as_ref())); + } + let draw_size = window.inner_size(); + layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64)); + + // compile dynamic lib shader + let dylib_src_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("examples/shader-dylib/test_dylib.metal"); + let install_path = + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target/test_dylib.metallib"); + + let dylib_src = std::fs::read_to_string(dylib_src_path).expect("bad shit"); + let opts = metal::CompileOptions::new(); + opts.set_library_type(MTLLibraryType::Dynamic); + opts.set_install_name(install_path.to_str().unwrap()); + + let lib = device + .new_library_with_source(dylib_src.as_str(), &opts) + .unwrap(); + + // create dylib + let dylib = device.new_dynamic_library(&lib).unwrap(); + dylib.set_label("test_dylib"); + + // optional: serialize binary blob that can be loaded later + let blob_url = String::from("file://") + install_path.to_str().unwrap(); + let url = URL::new_with_string(&blob_url); + dylib.serialize_to_url(&url).unwrap(); + + // create shader that links with dylib + let shader_src_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("examples/shader-dylib/test_shader.metal"); + + let shader_src = std::fs::read_to_string(shader_src_path).expect("bad shit"); + let opts = metal::CompileOptions::new(); + // add dynamic library to link with + let libraries = [dylib.as_ref()]; + opts.set_libraries(&libraries); + + // compile + let shader_lib = device + .new_library_with_source(shader_src.as_str(), &opts) + .unwrap(); + + let func = shader_lib.get_function("test_kernel", None).unwrap(); + + // create pipeline state + // linking occurs here + let image_fill_cps = device + .new_compute_pipeline_state_with_function(&func) + .unwrap(); + + Self { + device, + command_queue, + layer, + image_fill_cps, + width: draw_size.width, + height: draw_size.height, + } + } + + fn resize(&mut self, width: u32, height: u32) { + self.layer + .set_drawable_size(CGSize::new(width as f64, height as f64)); + self.width = width; + self.height = height; + } + + fn draw(&self) { + let drawable = match self.layer.next_drawable() { + Some(drawable) => drawable, + None => return, + }; + + let w = self.image_fill_cps.thread_execution_width(); + let h = self.image_fill_cps.max_total_threads_per_threadgroup() / w; + let threads_per_threadgroup = MTLSize::new(w, h, 1); + let threads_per_grid = MTLSize::new(self.width as _, self.height as _, 1); + + let command_buffer = self.command_queue.new_command_buffer(); + + { + let encoder = command_buffer.new_compute_command_encoder(); + encoder.set_compute_pipeline_state(&self.image_fill_cps); + encoder.set_texture(0, Some(&drawable.texture())); + encoder.dispatch_threads(threads_per_grid, threads_per_threadgroup); + encoder.end_encoding(); + } + + command_buffer.present_drawable(&drawable); + command_buffer.commit(); + } +} + +fn main() { + let events_loop = winit::event_loop::EventLoop::new(); + let size = winit::dpi::LogicalSize::new(800, 600); + + let window = winit::window::WindowBuilder::new() + .with_inner_size(size) + .with_title("Metal Shader Dylib Example".to_string()) + .build(&events_loop) + .unwrap(); + + let mut app = App::new(&window); + + events_loop.run(move |event, _, control_flow| { + autoreleasepool(|| { + *control_flow = ControlFlow::Poll; + + match event { + Event::WindowEvent { event, .. } => match event { + WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, + WindowEvent::Resized(size) => { + app.resize(size.width, size.height); + } + _ => (), + }, + Event::MainEventsCleared => { + window.request_redraw(); + } + Event::RedrawRequested(_) => { + app.draw(); + } + _ => {} + } + }); + }); +} diff --git a/third_party/rust/metal/examples/shader-dylib/test_dylib.metal b/third_party/rust/metal/examples/shader-dylib/test_dylib.metal new file mode 100644 index 0000000000..5faa4a803a --- /dev/null +++ b/third_party/rust/metal/examples/shader-dylib/test_dylib.metal @@ -0,0 +1,8 @@ +#include <metal_stdlib> + +using namespace metal; + +float4 get_color_test(float4 inColor) +{ + return float4(inColor.r, inColor.g, inColor.b, 0); +} diff --git a/third_party/rust/metal/examples/shader-dylib/test_shader.metal b/third_party/rust/metal/examples/shader-dylib/test_shader.metal new file mode 100644 index 0000000000..38203a64a5 --- /dev/null +++ b/third_party/rust/metal/examples/shader-dylib/test_shader.metal @@ -0,0 +1,14 @@ +#include <metal_stdlib> + +using namespace metal; + +extern float4 get_color_test(float4 inColor); + +kernel void test_kernel( + texture2d<float, access::write> image [[texture(0)]], + uint2 coordinates [[thread_position_in_grid]], + uint2 size [[threads_per_grid]]) +{ + float2 uv = float2(coordinates) / float2(size - 1); + image.write(get_color_test(float4(uv, 0.0, 1.0)), coordinates); +} diff --git a/third_party/rust/metal/examples/window/README.md b/third_party/rust/metal/examples/window/README.md new file mode 100644 index 0000000000..62233be356 --- /dev/null +++ b/third_party/rust/metal/examples/window/README.md @@ -0,0 +1,11 @@ +## window + +Renders a spinning triangle to a [winit](https://github.com/rust-windowing/winit) window. + +![Screenshot of the final render](./screenshot.png) + +## To Run + +``` +cargo run --example window +``` diff --git a/third_party/rust/metal/examples/window/main.rs b/third_party/rust/metal/examples/window/main.rs new file mode 100644 index 0000000000..08936e82fc --- /dev/null +++ b/third_party/rust/metal/examples/window/main.rs @@ -0,0 +1,261 @@ +// Copyright 2016 metal-rs developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +extern crate objc; + +use cocoa::{appkit::NSView, base::id as cocoa_id}; +use core_graphics_types::geometry::CGSize; + +use metal::*; +use objc::{rc::autoreleasepool, runtime::YES}; +use std::mem; +use winit::platform::macos::WindowExtMacOS; + +use winit::{ + event::{Event, WindowEvent}, + event_loop::ControlFlow, +}; + +#[repr(C)] +struct Rect { + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, +} + +#[repr(C)] +struct Color { + pub r: f32, + pub g: f32, + pub b: f32, + pub a: f32, +} + +#[repr(C)] +struct ClearRect { + pub rect: Rect, + pub color: Color, +} + +fn prepare_pipeline_state<'a>( + device: &DeviceRef, + library: &LibraryRef, + vertex_shader: &str, + fragment_shader: &str, +) -> RenderPipelineState { + let vert = library.get_function(vertex_shader, None).unwrap(); + let frag = library.get_function(fragment_shader, None).unwrap(); + + let pipeline_state_descriptor = RenderPipelineDescriptor::new(); + pipeline_state_descriptor.set_vertex_function(Some(&vert)); + pipeline_state_descriptor.set_fragment_function(Some(&frag)); + let attachment = pipeline_state_descriptor + .color_attachments() + .object_at(0) + .unwrap(); + attachment.set_pixel_format(MTLPixelFormat::BGRA8Unorm); + + attachment.set_blending_enabled(true); + attachment.set_rgb_blend_operation(metal::MTLBlendOperation::Add); + attachment.set_alpha_blend_operation(metal::MTLBlendOperation::Add); + attachment.set_source_rgb_blend_factor(metal::MTLBlendFactor::SourceAlpha); + attachment.set_source_alpha_blend_factor(metal::MTLBlendFactor::SourceAlpha); + attachment.set_destination_rgb_blend_factor(metal::MTLBlendFactor::OneMinusSourceAlpha); + attachment.set_destination_alpha_blend_factor(metal::MTLBlendFactor::OneMinusSourceAlpha); + + device + .new_render_pipeline_state(&pipeline_state_descriptor) + .unwrap() +} + +fn prepare_render_pass_descriptor(descriptor: &RenderPassDescriptorRef, texture: &TextureRef) { + //descriptor.color_attachments().set_object_at(0, MTLRenderPassColorAttachmentDescriptor::alloc()); + //let color_attachment: MTLRenderPassColorAttachmentDescriptor = unsafe { msg_send![descriptor.color_attachments().0, _descriptorAtIndex:0] };//descriptor.color_attachments().object_at(0); + let color_attachment = descriptor.color_attachments().object_at(0).unwrap(); + + color_attachment.set_texture(Some(texture)); + color_attachment.set_load_action(MTLLoadAction::Clear); + color_attachment.set_clear_color(MTLClearColor::new(0.2, 0.2, 0.25, 1.0)); + color_attachment.set_store_action(MTLStoreAction::Store); +} + +fn main() { + let events_loop = winit::event_loop::EventLoop::new(); + let size = winit::dpi::LogicalSize::new(800, 600); + + let window = winit::window::WindowBuilder::new() + .with_inner_size(size) + .with_title("Metal Window Example".to_string()) + .build(&events_loop) + .unwrap(); + + let device = Device::system_default().expect("no device found"); + + let layer = MetalLayer::new(); + layer.set_device(&device); + layer.set_pixel_format(MTLPixelFormat::BGRA8Unorm); + layer.set_presents_with_transaction(false); + + unsafe { + let view = window.ns_view() as cocoa_id; + view.setWantsLayer(YES); + view.setLayer(mem::transmute(layer.as_ref())); + } + + let draw_size = window.inner_size(); + layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64)); + + let library_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("examples/window/shaders.metallib"); + + let library = device.new_library_with_file(library_path).unwrap(); + let triangle_pipeline_state = + prepare_pipeline_state(&device, &library, "triangle_vertex", "triangle_fragment"); + let clear_rect_pipeline_state = prepare_pipeline_state( + &device, + &library, + "clear_rect_vertex", + "clear_rect_fragment", + ); + + let command_queue = device.new_command_queue(); + //let nc: () = msg_send![command_queue.0, setExecutionEnabled:true]; + + let vbuf = { + let vertex_data = [ + 0.0f32, 0.5, 1.0, 0.0, 0.0, -0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 0.0, 1.0, + ]; + + device.new_buffer_with_data( + vertex_data.as_ptr() as *const _, + (vertex_data.len() * mem::size_of::<f32>()) as u64, + MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged, + ) + }; + + let mut r = 0.0f32; + + let clear_rect = vec![ClearRect { + rect: Rect { + x: -1.0, + y: -1.0, + w: 2.0, + h: 2.0, + }, + color: Color { + r: 0.5, + g: 0.8, + b: 0.5, + a: 1.0, + }, + }]; + + let clear_rect_buffer = device.new_buffer_with_data( + clear_rect.as_ptr() as *const _, + mem::size_of::<ClearRect>() as u64, + MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged, + ); + + events_loop.run(move |event, _, control_flow| { + autoreleasepool(|| { + *control_flow = ControlFlow::Poll; + + match event { + Event::WindowEvent { event, .. } => match event { + WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, + WindowEvent::Resized(size) => { + layer.set_drawable_size(CGSize::new(size.width as f64, size.height as f64)); + } + _ => (), + }, + Event::MainEventsCleared => { + window.request_redraw(); + } + Event::RedrawRequested(_) => { + let p = vbuf.contents(); + let vertex_data = [ + 0.0f32, + 0.5, + 1.0, + 0.0, + 0.0, + -0.5 + (r.cos() / 2. + 0.5), + -0.5, + 0.0, + 1.0, + 0.0, + 0.5 - (r.cos() / 2. + 0.5), + -0.5, + 0.0, + 0.0, + 1.0, + ]; + + unsafe { + std::ptr::copy( + vertex_data.as_ptr(), + p as *mut f32, + (vertex_data.len() * mem::size_of::<f32>()) as usize, + ); + } + + vbuf.did_modify_range(crate::NSRange::new( + 0 as u64, + (vertex_data.len() * mem::size_of::<f32>()) as u64, + )); + + let drawable = match layer.next_drawable() { + Some(drawable) => drawable, + None => return, + }; + + let render_pass_descriptor = RenderPassDescriptor::new(); + + prepare_render_pass_descriptor(&render_pass_descriptor, drawable.texture()); + + let command_buffer = command_queue.new_command_buffer(); + let encoder = + command_buffer.new_render_command_encoder(&render_pass_descriptor); + + encoder.set_scissor_rect(MTLScissorRect { + x: 20, + y: 20, + width: 100, + height: 100, + }); + encoder.set_render_pipeline_state(&clear_rect_pipeline_state); + encoder.set_vertex_buffer(0, Some(&clear_rect_buffer), 0); + encoder.draw_primitives_instanced( + metal::MTLPrimitiveType::TriangleStrip, + 0, + 4, + 1, + ); + let physical_size = window.inner_size(); + encoder.set_scissor_rect(MTLScissorRect { + x: 0, + y: 0, + width: physical_size.width as _, + height: physical_size.height as _, + }); + + encoder.set_render_pipeline_state(&triangle_pipeline_state); + encoder.set_vertex_buffer(0, Some(&vbuf), 0); + encoder.draw_primitives(MTLPrimitiveType::Triangle, 0, 3); + encoder.end_encoding(); + + command_buffer.present_drawable(&drawable); + command_buffer.commit(); + + r += 0.01f32; + } + _ => {} + } + }); + }); +} diff --git a/third_party/rust/metal/examples/window/screenshot.png b/third_party/rust/metal/examples/window/screenshot.png Binary files differnew file mode 100644 index 0000000000..9f5eba8ccf --- /dev/null +++ b/third_party/rust/metal/examples/window/screenshot.png diff --git a/third_party/rust/metal/examples/window/shaders.metal b/third_party/rust/metal/examples/window/shaders.metal new file mode 100644 index 0000000000..cc05f5d57e --- /dev/null +++ b/third_party/rust/metal/examples/window/shaders.metal @@ -0,0 +1,97 @@ +#include <metal_stdlib> + +using namespace metal; + +typedef struct { + packed_float2 position; + packed_float3 color; +} vertex_t; + +struct ColorInOut { + float4 position [[position]]; + float4 color; +}; +// vertex shader function +vertex ColorInOut triangle_vertex(const device vertex_t* vertex_array [[ buffer(0) ]], + unsigned int vid [[ vertex_id ]]) +{ + ColorInOut out; + + auto device const &v = vertex_array[vid]; + out.position = float4(v.position.x, v.position.y, 0.0, 1.0); + out.color = float4(v.color.x, v.color.y, v.color.z, 0.2); + + return out; +} + +// fragment shader function +fragment float4 triangle_fragment(ColorInOut in [[stage_in]]) +{ + return in.color; +}; + + +struct Rect { + float x; + float y; + float w; + float h; +}; + +struct Color { + float r; + float g; + float b; + float a; +}; + +struct ClearRect { + Rect rect; + Color color; +}; + +float2 rect_vert( + Rect rect, + uint vid +) { + float2 pos; + + float left = rect.x; + float right = rect.x + rect.w; + float bottom = rect.y; + float top = rect.y + rect.h; + + switch (vid) { + case 0: + pos = float2(right, top); + break; + case 1: + pos = float2(left, top); + break; + case 2: + pos = float2(right, bottom); + break; + case 3: + pos = float2(left, bottom); + break; + } + return pos; +} + +vertex ColorInOut clear_rect_vertex( + const device ClearRect *clear_rect [[ buffer(0) ]], + unsigned int vid [[ vertex_id ]] +) { + ColorInOut out; + float4 pos = float4(rect_vert(clear_rect->rect, vid), 0, 1); + auto col = clear_rect->color; + + out.position = pos; + out.color = float4(col.r, col.g, col.b, col.a); + return out; +} + +fragment float4 clear_rect_fragment(ColorInOut in [[stage_in]]) +{ + return in.color; +}; diff --git a/third_party/rust/metal/examples/window/shaders.metallib b/third_party/rust/metal/examples/window/shaders.metallib Binary files differnew file mode 100644 index 0000000000..a6388fc9bc --- /dev/null +++ b/third_party/rust/metal/examples/window/shaders.metallib |