Debian Codegraph @

third_party/rust/metal/examples/window/main.rs

raw
1 // Copyright 2016 metal-rs 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 extern crate objc;
9
10 use cocoa::{appkit::NSView, base::id as cocoa_id};
11 use core_graphics_types::geometry::CGSize;
12 use metal::*;
13 use objc::{rc::autoreleasepool, runtime::YES};
14
15 use winit::{
16 event::{Event, WindowEvent},
17 event_loop::ControlFlow,
18 raw_window_handle::{HasWindowHandle, RawWindowHandle},
19 };
20
21 #[repr(C)]
22 struct Rect {
23 pub x: f32,
24 pub y: f32,
25 pub w: f32,
26 pub h: f32,
27 }
28
29 #[repr(C)]
30 struct Color {
31 pub r: f32,
32 pub g: f32,
33 pub b: f32,
34 pub a: f32,
35 }
36
37 #[repr(C)]
38 struct ClearRect {
39 pub rect: Rect,
40 pub color: Color,
41 }
42
43 fn prepare_pipeline_state(
44 device: &DeviceRef,
45 library: &LibraryRef,
46 vertex_shader: &str,
47 fragment_shader: &str,
48 ) -> RenderPipelineState {
49 let vert = library.get_function(vertex_shader, None).unwrap();
50 let frag = library.get_function(fragment_shader, None).unwrap();
51
52 let pipeline_state_descriptor = RenderPipelineDescriptor::new();
53 pipeline_state_descriptor.set_vertex_function(Some(&vert));
54 pipeline_state_descriptor.set_fragment_function(Some(&frag));
55 let attachment = pipeline_state_descriptor
56 .color_attachments()
57 .object_at(0)
58 .unwrap();
59 attachment.set_pixel_format(MTLPixelFormat::BGRA8Unorm);
60
61 attachment.set_blending_enabled(true);
62 attachment.set_rgb_blend_operation(metal::MTLBlendOperation::Add);
63 attachment.set_alpha_blend_operation(metal::MTLBlendOperation::Add);
64 attachment.set_source_rgb_blend_factor(metal::MTLBlendFactor::SourceAlpha);
65 attachment.set_source_alpha_blend_factor(metal::MTLBlendFactor::SourceAlpha);
66 attachment.set_destination_rgb_blend_factor(metal::MTLBlendFactor::OneMinusSourceAlpha);
67 attachment.set_destination_alpha_blend_factor(metal::MTLBlendFactor::OneMinusSourceAlpha);
68
69 device
70 .new_render_pipeline_state(&pipeline_state_descriptor)
71 .unwrap()
72 }
73
74 fn prepare_render_pass_descriptor(descriptor: &RenderPassDescriptorRef, texture: &TextureRef) {
75 //descriptor.color_attachments().set_object_at(0, MTLRenderPassColorAttachmentDescriptor::alloc());
76 //let color_attachment: MTLRenderPassColorAttachmentDescriptor = unsafe { msg_send![descriptor.color_attachments().0, _descriptorAtIndex:0] };//descriptor.color_attachments().object_at(0);
77 let color_attachment = descriptor.color_attachments().object_at(0).unwrap();
78
79 color_attachment.set_texture(Some(texture));
80 color_attachment.set_load_action(MTLLoadAction::Clear);
81 color_attachment.set_clear_color(MTLClearColor::new(0.2, 0.2, 0.25, 1.0));
82 color_attachment.set_store_action(MTLStoreAction::Store);
83 }
84
85 fn main() {
86 let event_loop = winit::event_loop::EventLoop::new().unwrap();
87 let size = winit::dpi::LogicalSize::new(800, 600);
88
89 let window = winit::window::WindowBuilder::new()
90 .with_inner_size(size)
91 .with_title("Metal Window Example".to_string())
92 .build(&event_loop)
93 .unwrap();
94
95 let device = Device::system_default().expect("no device found");
96
97 let mut layer = MetalLayer::new();
98 layer.set_device(&device);
99 layer.set_pixel_format(MTLPixelFormat::BGRA8Unorm);
100 layer.set_presents_with_transaction(false);
101
102 unsafe {
103 if let Ok(RawWindowHandle::AppKit(rw)) = window.window_handle().map(|wh| wh.as_raw()) {
104 let view = rw.ns_view.as_ptr() as cocoa_id;
105 view.setWantsLayer(YES);
106 view.setLayer(<*mut _>::cast(layer.as_mut()));
107 }
108 }
109
110 let draw_size = window.inner_size();
111 layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64));
112
113 let library_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
114 .join("examples/window/shaders.metallib");
115
116 let library = device.new_library_with_file(library_path).unwrap();
117 let triangle_pipeline_state =
118 prepare_pipeline_state(&device, &library, "triangle_vertex", "triangle_fragment");
119 let clear_rect_pipeline_state = prepare_pipeline_state(
120 &device,
121 &library,
122 "clear_rect_vertex",
123 "clear_rect_fragment",
124 );
125
126 let command_queue = device.new_command_queue();
127 //let nc: () = msg_send![command_queue.0, setExecutionEnabled:true];
128
129 let vbuf = {
130 let vertex_data = [
131 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,
132 ];
133
134 device.new_buffer_with_data(
135 vertex_data.as_ptr().cast(),
136 size_of_val(&vertex_data) as u64,
137 MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged,
138 )
139 };
140
141 let mut r = 0.0f32;
142
143 let clear_rect = ClearRect {
144 rect: Rect {
145 x: -1.0,
146 y: -1.0,
147 w: 2.0,
148 h: 2.0,
149 },
150 color: Color {
151 r: 0.5,
152 g: 0.8,
153 b: 0.5,
154 a: 1.0,
155 },
156 };
157
158 let clear_rect_buffer = device.new_buffer_with_data(
159 (&raw const clear_rect).cast(),
160 size_of::<ClearRect>() as u64,
161 MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged,
162 );
163
164 event_loop
165 .run(move |event, event_loop| {
166 autoreleasepool(|| {
167 event_loop.set_control_flow(ControlFlow::Poll);
168
169 match event {
170 Event::AboutToWait => window.request_redraw(),
171 Event::WindowEvent { event, .. } => match event {
172 WindowEvent::CloseRequested => event_loop.exit(),
173 WindowEvent::Resized(size) => {
174 layer.set_drawable_size(CGSize::new(
175 size.width as f64,
176 size.height as f64,
177 ));
178 }
179 WindowEvent::RedrawRequested => {
180 let p = vbuf.contents();
181 let vertex_data = [
182 0.0f32,
183 0.5,
184 1.0,
185 0.0,
186 0.0,
187 -0.5 + (r.cos() / 2. + 0.5),
188 -0.5,
189 0.0,
190 1.0,
191 0.0,
192 0.5 - (r.cos() / 2. + 0.5),
193 -0.5,
194 0.0,
195 0.0,
196 1.0,
197 ];
198
199 unsafe {
200 std::ptr::copy(
201 vertex_data.as_ptr(),
202 p.cast(),
203 size_of_val(&vertex_data),
204 );
205 }
206
207 vbuf.did_modify_range(crate::NSRange::new(
208 0u64,
209 size_of_val(&vertex_data) as u64,
210 ));
211
212 let drawable = match layer.next_drawable() {
213 Some(drawable) => drawable,
214 None => return,
215 };
216
217 let render_pass_descriptor = RenderPassDescriptor::new();
218
219 prepare_render_pass_descriptor(
220 render_pass_descriptor,
221 drawable.texture(),
222 );
223
224 let command_buffer = command_queue.new_command_buffer();
225 let encoder =
226 command_buffer.new_render_command_encoder(render_pass_descriptor);
227
228 encoder.set_scissor_rect(MTLScissorRect {
229 x: 20,
230 y: 20,
231 width: 100,
232 height: 100,
233 });
234 encoder.set_render_pipeline_state(&clear_rect_pipeline_state);
235 encoder.set_vertex_buffer(0, Some(&clear_rect_buffer), 0);
236 encoder.draw_primitives_instanced(
237 metal::MTLPrimitiveType::TriangleStrip,
238 0,
239 4,
240 1,
241 );
242 let physical_size = window.inner_size();
243 encoder.set_scissor_rect(MTLScissorRect {
244 x: 0,
245 y: 0,
246 width: physical_size.width as _,
247 height: physical_size.height as _,
248 });
249
250 encoder.set_render_pipeline_state(&triangle_pipeline_state);
251 encoder.set_vertex_buffer(0, Some(&vbuf), 0);
252 encoder.draw_primitives(MTLPrimitiveType::Triangle, 0, 3);
253 encoder.end_encoding();
254
255 command_buffer.present_drawable(drawable);
256 command_buffer.commit();
257
258 r += 0.01f32;
259 }
260 _ => (),
261 },
262 _ => {}
263 }
264 });
265 })
266 .unwrap();
267 }