Debian Codegraph @

third_party/rust/metal/examples/compute/compute-argument-buffer.rs

raw
1 // Copyright 2017 GFX developers
2 //
3 // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4 // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5 // http://opensource.org/licenses/MIT>, at your option. This file may not be
6 // copied, modified, or distributed except according to those terms.
7
8 use metal::*;
9 use objc::rc::autoreleasepool;
10 use std::mem::size_of_val;
11
12 static LIBRARY_SRC: &str = include_str!("compute-argument-buffer.metal");
13
14 fn main() {
15 autoreleasepool(|| {
16 let device = Device::system_default().expect("no device found");
17 let command_queue = device.new_command_queue();
18
19 let data = [
20 1u32, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
21 24, 25, 26, 27, 28, 29, 30,
22 ];
23
24 let buffer = device.new_buffer_with_data(
25 data.as_ptr().cast(),
26 size_of_val(&data) as u64,
27 MTLResourceOptions::CPUCacheModeDefaultCache,
28 );
29
30 let sum = {
31 let data = [0u32];
32 device.new_buffer_with_data(
33 data.as_ptr().cast(),
34 size_of_val(&data) as u64,
35 MTLResourceOptions::CPUCacheModeDefaultCache,
36 )
37 };
38
39 let command_buffer = command_queue.new_command_buffer();
40 let encoder = command_buffer.new_compute_command_encoder();
41
42 let library = device
43 .new_library_with_source(LIBRARY_SRC, &CompileOptions::new())
44 .unwrap();
45 let kernel = library.get_function("sum", None).unwrap();
46
47 let argument_encoder = kernel.new_argument_encoder(0);
48 let arg_buffer = device.new_buffer(
49 argument_encoder.encoded_length(),
50 MTLResourceOptions::empty(),
51 );
52 argument_encoder.set_argument_buffer(&arg_buffer, 0);
53 argument_encoder.set_buffer(0, &buffer, 0);
54 argument_encoder.set_buffer(1, &sum, 0);
55
56 let pipeline_state_descriptor = ComputePipelineDescriptor::new();
57 pipeline_state_descriptor.set_compute_function(Some(&kernel));
58
59 let pipeline_state = device
60 .new_compute_pipeline_state_with_function(
61 pipeline_state_descriptor.compute_function().unwrap(),
62 )
63 .unwrap();
64
65 encoder.set_compute_pipeline_state(&pipeline_state);
66 encoder.set_buffer(0, Some(&arg_buffer), 0);
67
68 encoder.use_resource(&buffer, MTLResourceUsage::Read);
69 encoder.use_resource(&sum, MTLResourceUsage::Write);
70
71 let width = 16;
72
73 let thread_group_count = MTLSize {
74 width,
75 height: 1,
76 depth: 1,
77 };
78
79 let thread_group_size = MTLSize {
80 width: (data.len() as u64 + width) / width,
81 height: 1,
82 depth: 1,
83 };
84
85 encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
86 encoder.end_encoding();
87 command_buffer.commit();
88 command_buffer.wait_until_completed();
89
90 let sum = unsafe { *sum.contents().cast::<u32>() };
91 assert_eq!(465, sum);
92 });
93 }