1#[cfg(not(windows))]
12fn main() {
13 println!("Direct3D is Windows' own: there is nothing for this example to show here.");
14}
15
16#[cfg(windows)]
17fn main() {
18 direct3d::run();
19}
20
21#[cfg(windows)]
22#[allow(non_camel_case_types, clippy::upper_case_acronyms)]
23pub mod direct3d {
24 use std::cell::RefCell;
25 use std::ffi::c_void;
26 use std::ptr::{null, null_mut};
27 use std::time::{Duration, Instant};
28 use taut::geom::Size;
29 use taut::layer_d3d12::Layer;
30 use taut::platform::{Messages, SystemClipboard};
31 use taut::{Color, Length, Ui};
32
33 pub type Com = *mut c_void;
35
36 pub unsafe fn function<F: Copy>(object: Com, at: usize) -> F {
41 unsafe { std::mem::transmute_copy(&*(*(object as *const *const usize)).add(at)) }
43 }
44
45 pub unsafe fn release(object: Com) {
50 if !object.is_null() {
51 unsafe { function::<unsafe extern "system" fn(Com) -> u32>(object, 2)(object) };
52 }
53 }
54
55 pub fn check(result: i32, what: &str) {
57 assert!(result >= 0, "{what} failed: {:#010x}", result as u32);
58 }
59
60 pub const fn named(a: u32, b: u16, c: u16, d: [u8; 8]) -> [u32; 4] {
62 [a, b as u32 | (c as u32) << 16, u32::from_le_bytes([d[0], d[1], d[2], d[3]]), u32::from_le_bytes([d[4], d[5], d[6], d[7]])]
63 }
64
65 pub const DEVICE: [u32; 4] = named(0x1898_19F1, 0x1DB6, 0x4B57, [0xBE, 0x54, 0x18, 0x21, 0x33, 0x9B, 0x85, 0xF7]);
66 pub const QUEUE: [u32; 4] = named(0x0EC8_70A6, 0x5D7E, 0x4C22, [0x8C, 0xFC, 0x5B, 0xAA, 0xE0, 0x76, 0x16, 0xED]);
67 pub const ALLOCATOR: [u32; 4] = named(0x6102_DEE4, 0xAF59, 0x4B09, [0xB9, 0x99, 0xB4, 0x4D, 0x73, 0xF0, 0x9B, 0x24]);
68 pub const LIST: [u32; 4] = named(0x5B16_0D0F, 0xAC1B, 0x4185, [0x8B, 0xA8, 0xB3, 0xAE, 0x42, 0xA5, 0xA4, 0x55]);
69 pub const FENCE: [u32; 4] = named(0x0A75_3DCF, 0xC4D8, 0x4B91, [0xAD, 0xF6, 0xBE, 0x5A, 0x60, 0xD9, 0x5A, 0x76]);
70 pub const HEAP: [u32; 4] = named(0x8EFB_471D, 0x616C, 0x4F49, [0x90, 0xF7, 0x12, 0x7B, 0xB7, 0x63, 0xFA, 0x51]);
71 pub const RESOURCE: [u32; 4] = named(0x6964_42BE, 0xA72E, 0x4059, [0xBC, 0x79, 0x5B, 0x5C, 0x98, 0x04, 0x0F, 0xAD]);
72 const FACTORY: [u32; 4] = named(0x1BC6_EA02, 0xEF36, 0x464F, [0xBF, 0x0C, 0x21, 0xCA, 0x39, 0xE5, 0x16, 0x8A]);
73 const ADAPTER: [u32; 4] = named(0x2411_E7E1, 0x12AC, 0x4CCF, [0xBD, 0x14, 0x97, 0x98, 0xE8, 0x53, 0x4D, 0xC0]);
74 const SWAP_CHAIN: [u32; 4] = named(0x94D9_9BDB, 0xF1F8, 0x4AB0, [0xB2, 0x36, 0x7D, 0xA0, 0x17, 0x0E, 0xDA, 0xB1]);
75
76 pub const PRESENT: u32 = 0;
78 pub const RENDER_TARGET: u32 = 0x4;
79
80 #[link(name = "d3d12")]
81 unsafe extern "system" {
82 fn D3D12CreateDevice(adapter: Com, level: u32, interface: *const [u32; 4], device: *mut Com) -> i32;
83 }
84 #[link(name = "dxgi")]
85 unsafe extern "system" {
86 fn CreateDXGIFactory2(flags: u32, interface: *const [u32; 4], factory: *mut Com) -> i32;
87 }
88
89 #[repr(C)]
91 pub struct Barrier {
92 pub kind: u32,
93 pub flags: u32,
94 pub resource: Com,
95 pub subresource: u32,
96 pub before: u32,
97 pub after: u32,
98 }
99
100 pub fn transition(resource: Com, before: u32, after: u32) -> Barrier {
102 Barrier { kind: 0, flags: 0, resource, subresource: u32::MAX, before, after }
103 }
104
105 #[repr(C)]
107 struct DXGI_SWAP_CHAIN_DESC1 {
108 width: u32,
109 height: u32,
110 format: u32,
111 stereo: i32,
112 sample_count: u32,
113 sample_quality: u32,
114 buffer_usage: u32,
115 buffer_count: u32,
116 scaling: u32,
117 swap_effect: u32,
118 alpha_mode: u32,
119 flags: u32,
120 }
121
122 pub struct Device {
126 pub device: Com,
128 pub queue: Com,
130 allocator: Com,
131 pub list: Com,
133 fence: Com,
134 fenced: u64,
135 pub swap: Com,
137 pub buffers: [Com; 2],
138 views: Com,
140 step: usize,
141 pub size: [u32; 2],
143 }
144
145 impl Device {
146 pub fn new(window: isize, software: bool) -> Device {
148 let mut made = Device {
149 device: null_mut(),
150 queue: null_mut(),
151 allocator: null_mut(),
152 list: null_mut(),
153 fence: null_mut(),
154 fenced: 0,
155 swap: null_mut(),
156 buffers: [null_mut(); 2],
157 views: null_mut(),
158 step: 0,
159 size: [0; 2],
160 };
161 let (mut factory, mut adapter, mut chain) = (null_mut(), null_mut(), null_mut());
162 let desc = DXGI_SWAP_CHAIN_DESC1 {
165 width: 0,
166 height: 0,
167 format: 87,
168 stereo: 0,
169 sample_count: 1,
170 sample_quality: 0,
171 buffer_usage: 0x20,
172 buffer_count: 2,
173 scaling: 0,
174 swap_effect: 4,
175 alpha_mode: 0,
176 flags: 0,
177 };
178 let (queue, views) = ([0u32; 4], [2u32, 2, 0, 0]);
180 unsafe {
184 check(CreateDXGIFactory2(0, &FACTORY, &mut factory), "making a DXGI factory");
185 if software {
186 check(function::<unsafe extern "system" fn(Com, *const [u32; 4], *mut Com) -> i32>(factory, 27)(factory, &ADAPTER, &mut adapter), "finding WARP");
187 }
188 if D3D12CreateDevice(adapter, 0xB000, &DEVICE, &mut made.device) < 0 {
189 check(function::<unsafe extern "system" fn(Com, *const [u32; 4], *mut Com) -> i32>(factory, 27)(factory, &ADAPTER, &mut adapter), "finding WARP");
190 check(D3D12CreateDevice(adapter, 0xB000, &DEVICE, &mut made.device), "making a Direct3D 12 device");
191 }
192 let device = made.device;
193 check(function::<unsafe extern "system" fn(Com, *const [u32; 4], *const [u32; 4], *mut Com) -> i32>(device, 8)(device, &queue, &QUEUE, &mut made.queue), "making the queue");
194 check(function::<unsafe extern "system" fn(Com, u32, *const [u32; 4], *mut Com) -> i32>(device, 9)(device, 0, &ALLOCATOR, &mut made.allocator), "making the command allocator");
195 check(
196 function::<unsafe extern "system" fn(Com, u32, u32, Com, Com, *const [u32; 4], *mut Com) -> i32>(device, 12)(device, 0, 0, made.allocator, null_mut(), &LIST, &mut made.list),
197 "making the command list",
198 );
199 check(function::<unsafe extern "system" fn(Com) -> i32>(made.list, 9)(made.list), "closing the command list");
200 check(function::<unsafe extern "system" fn(Com, u64, u32, *const [u32; 4], *mut Com) -> i32>(device, 36)(device, 0, 0, &FENCE, &mut made.fence), "making the fence");
201 check(function::<unsafe extern "system" fn(Com, *const [u32; 4], *const [u32; 4], *mut Com) -> i32>(device, 14)(device, &views, &HEAP, &mut made.views), "making the views' heap");
202 made.step = function::<unsafe extern "system" fn(Com, u32) -> u32>(device, 15)(device, 2) as usize;
203 type MakeChain = unsafe extern "system" fn(Com, Com, isize, *const DXGI_SWAP_CHAIN_DESC1, *const c_void, Com, *mut Com) -> i32;
204 check(function::<MakeChain>(factory, 15)(factory, made.queue, window, &desc, null(), null_mut(), &mut chain), "making the swap chain");
205 check(function::<unsafe extern "system" fn(Com, *const [u32; 4], *mut Com) -> i32>(chain, 0)(chain, &SWAP_CHAIN, &mut made.swap), "asking for IDXGISwapChain3");
206 [chain, adapter, factory].into_iter().for_each(|object| release(object));
207 }
208 made.resize(0, 0);
209 made
210 }
211
212 pub fn wait(&mut self) {
214 self.fenced += 1;
215 unsafe {
217 check(function::<unsafe extern "system" fn(Com, Com, u64) -> i32>(self.queue, 14)(self.queue, self.fence, self.fenced), "signalling");
218 check(function::<unsafe extern "system" fn(Com, u64, isize) -> i32>(self.fence, 9)(self.fence, self.fenced, 0), "waiting");
219 }
220 }
221
222 pub fn resize(&mut self, width: u32, height: u32) {
225 self.wait();
226 let mut desc = [0u32; 14];
227 unsafe {
231 self.buffers.into_iter().for_each(|object| release(object));
232 check(function::<unsafe extern "system" fn(Com, u32, u32, u32, u32, u32) -> i32>(self.swap, 13)(self.swap, 0, width, height, 0, 0), "resizing the swap chain");
233 for at in 0..2 {
234 check(function::<unsafe extern "system" fn(Com, u32, *const [u32; 4], *mut Com) -> i32>(self.swap, 9)(self.swap, at as u32, &RESOURCE, &mut self.buffers[at]), "finding a buffer");
235 function::<unsafe extern "system" fn(Com, Com, *const c_void, usize)>(self.device, 20)(self.device, self.buffers[at], null(), self.view(at));
236 }
237 function::<unsafe extern "system" fn(Com, *mut [u32; 14]) -> *mut [u32; 14]>(self.buffers[0], 10)(self.buffers[0], &mut desc);
238 }
239 self.size = [desc[4], desc[6]];
241 }
242
243 fn view(&self, at: usize) -> usize {
245 let mut start = 0;
246 unsafe { function::<unsafe extern "system" fn(Com, *mut usize) -> *mut usize>(self.views, 9)(self.views, &mut start) };
248 start + at * self.step
249 }
250
251 pub fn current(&self) -> usize {
253 unsafe { function::<unsafe extern "system" fn(Com) -> u32>(self.swap, 36)(self.swap) as usize }
255 }
256
257 pub fn begin(&mut self, colour: [f32; 4]) {
260 let (list, at) = (self.list, self.current());
261 let viewport = [0.0, 0.0, self.size[0] as f32, self.size[1] as f32, 0.0, 1.0];
262 unsafe {
266 check(function::<unsafe extern "system" fn(Com) -> i32>(self.allocator, 8)(self.allocator), "resetting the allocator");
267 check(function::<unsafe extern "system" fn(Com, Com, Com) -> i32>(list, 10)(list, self.allocator, null_mut()), "resetting the list");
268 function::<unsafe extern "system" fn(Com, u32, *const Barrier)>(list, 26)(list, 1, &transition(self.buffers[at], PRESENT, RENDER_TARGET));
269 function::<unsafe extern "system" fn(Com, u32, *const usize, i32, *const usize)>(list, 46)(list, 1, &self.view(at), 0, null());
270 function::<unsafe extern "system" fn(Com, usize, *const [f32; 4], u32, *const c_void)>(list, 48)(list, self.view(at), &colour, 0, null());
271 function::<unsafe extern "system" fn(Com, u32, *const [f32; 6])>(list, 21)(list, 1, &viewport);
272 }
273 }
274
275 pub fn finish(&mut self) {
278 let (list, at) = (self.list, self.current());
279 unsafe {
281 function::<unsafe extern "system" fn(Com, u32, *const Barrier)>(list, 26)(list, 1, &transition(self.buffers[at], RENDER_TARGET, PRESENT));
282 check(function::<unsafe extern "system" fn(Com) -> i32>(list, 9)(list), "closing the list");
283 function::<unsafe extern "system" fn(Com, u32, *const Com)>(self.queue, 10)(self.queue, 1, &list);
284 }
285 self.wait();
286 }
287
288 pub fn show(&self) {
290 unsafe { function::<unsafe extern "system" fn(Com, u32, u32) -> i32>(self.swap, 8)(self.swap, 1, 0) };
292 }
293 }
294
295 impl Drop for Device {
296 fn drop(&mut self) {
297 if !self.queue.is_null() && !self.fence.is_null() {
299 self.wait();
300 }
301 unsafe { [self.buffers[0], self.buffers[1], self.views, self.swap, self.fence, self.list, self.allocator, self.queue, self.device].into_iter().for_each(|object| release(object)) };
303 }
304 }
305
306 #[repr(C)]
309 struct WNDCLASSW {
310 style: u32,
311 proc: unsafe extern "system" fn(isize, u32, usize, isize) -> isize,
312 class_extra: i32,
313 window_extra: i32,
314 instance: isize,
315 icon: isize,
316 cursor: isize,
317 background: isize,
318 menu: *const u16,
319 name: *const u16,
320 }
321 #[repr(C)]
322 #[derive(Default)]
323 struct MSG {
324 hwnd: isize,
325 message: u32,
326 wparam: usize,
327 lparam: isize,
328 time: u32,
329 pt: [i32; 2],
330 }
331 #[repr(C)]
332 struct TRACKMOUSEEVENT {
333 size: u32,
334 flags: u32,
335 hwnd: isize,
336 hover_time: u32,
337 }
338 #[link(name = "user32")]
339 unsafe extern "system" {
340 fn RegisterClassW(class: *const WNDCLASSW) -> u16;
341 fn CreateWindowExW(ex: u32, class: *const u16, title: *const u16, style: u32, x: i32, y: i32, w: i32, h: i32, parent: isize, menu: isize, instance: isize, param: *const c_void) -> isize;
342 fn DefWindowProcW(hwnd: isize, msg: u32, w: usize, l: isize) -> isize;
343 fn PeekMessageW(msg: *mut MSG, hwnd: isize, first: u32, last: u32, remove: u32) -> i32;
344 fn TranslateMessage(msg: *const MSG) -> i32;
345 fn DispatchMessageW(msg: *const MSG) -> isize;
346 fn PostQuitMessage(code: i32);
347 fn LoadCursorW(instance: isize, name: *const u16) -> isize;
348 fn TrackMouseEvent(track: *mut TRACKMOUSEEVENT) -> i32;
349 fn SetProcessDpiAwarenessContext(context: isize) -> i32;
350 fn GetDpiForWindow(hwnd: isize) -> u32;
351 }
352 #[link(name = "kernel32")]
353 unsafe extern "system" {
354 fn GetModuleHandleW(name: *const u16) -> isize;
355 }
356 const WM_DESTROY: u32 = 0x0002;
357 const WM_SIZE: u32 = 0x0005;
358 const WM_QUIT: u32 = 0x0012;
359 const WM_MOUSEMOVE: u32 = 0x0200;
360
361 thread_local! {
362 static HEARD: RefCell<Vec<(u32, usize, isize)>> = const { RefCell::new(Vec::new()) };
364 }
365
366 unsafe extern "system" fn keep(hwnd: isize, msg: u32, w: usize, l: isize) -> isize {
368 HEARD.with_borrow_mut(|heard| heard.push((msg, w, l)));
369 let mut leave = TRACKMOUSEEVENT { size: size_of::<TRACKMOUSEEVENT>() as u32, flags: 2, hwnd, hover_time: 0 };
371 match msg {
373 WM_DESTROY => unsafe { PostQuitMessage(0) },
374 WM_MOUSEMOVE => _ = unsafe { TrackMouseEvent(&mut leave) },
375 _ => {}
376 }
377 unsafe { DefWindowProcW(hwnd, msg, w, l) }
378 }
379
380 fn pump() -> bool {
382 let mut message = MSG::default();
383 while unsafe { PeekMessageW(&mut message, 0, 0, 0, 1) } != 0 {
385 if message.message == WM_QUIT {
386 return false;
387 }
388 unsafe { (TranslateMessage(&message), DispatchMessageW(&message)) };
389 }
390 true
391 }
392
393 struct App {
395 still: bool,
396 speed: f32,
397 name: String,
398 }
399
400 fn describe(app: &mut App, ui: &mut Ui) {
401 let t = ui.theme;
402 ui.column().w(Length::Px(260.0)).offset(16.0, 16.0).pad(14.0).gap(10.0).fill(t.panel.with_alpha(0.9)).border(t.line_strong, 1.0).radius(10.0).shadow(12.0).open();
403 ui.text("Over Direct3D 12", t.font.bold(), t.text);
404 ui.switch(&mut app.still, "Hold the colour still");
405 ui.slider(&mut app.speed, 0.0..=4.0);
406 ui.text_box(&mut app.name, "Type here");
407 ui.note(&format!("{} letters typed", app.name.chars().count()));
408 ui.close();
409 }
410
411 pub fn run() {
412 let (class, title): (Vec<u16>, Vec<u16>) = ("taut-d3d12\0".encode_utf16().collect(), "taut over Direct3D 12\0".encode_utf16().collect());
413 let window = unsafe {
416 SetProcessDpiAwarenessContext(-4);
417 let instance = GetModuleHandleW(null());
418 let arrow = LoadCursorW(0, 32512 as *const u16);
419 RegisterClassW(&WNDCLASSW { style: 0, proc: keep, class_extra: 0, window_extra: 0, instance, icon: 0, cursor: arrow, background: 0, menu: null(), name: class.as_ptr() });
420 CreateWindowExW(0, class.as_ptr(), title.as_ptr(), 0x10CF_0000, i32::MIN, i32::MIN, 900, 600, 0, 0, instance, null())
421 };
422 let mut device = Device::new(window, false);
423 let mut layer = unsafe { Layer::new(device.device, device.queue, 87) }.unwrap_or_else(|failed| panic!("{failed}"));
425 let mut ui = Ui::new(taut::platform::system_text(), Box::new(SystemClipboard));
426 ui.theme.bg = Color::NONE;
427 let mut app = App { still: false, speed: 1.0, name: String::new() };
428 let (mut messages, scale) = (Messages::of(window), unsafe { GetDpiForWindow(window) } as f32 / 96.0);
429 let (mut waiting, started, mut hue) = (true, Instant::now(), 0.0f32);
430 while pump() {
431 for (msg, w, l) in HEARD.take() {
432 let (width, height) = (l as u32 & 0xffff, l as u32 >> 16 & 0xffff);
433 if msg == WM_SIZE && width > 0 && height > 0 {
434 device.resize(width, height);
435 ui.resize(Size { w: width as f32 / scale, h: height as f32 / scale }, scale);
436 waiting = true;
437 }
438 unsafe { messages.events(msg, w, l, scale, |event| waiting |= ui.event(event)) };
441 }
442 ui.set_time(started.elapsed());
444 if std::mem::take(&mut waiting) || ui.wake_in() == Some(Duration::ZERO) {
445 ui.run(&mut |ui| describe(&mut app, ui));
446 }
447 hue += if app.still { 0.0 } else { app.speed / 120.0 };
448 device.begin([0.3 + 0.25 * hue.sin(), 0.3 + 0.25 * (hue + 2.1).sin(), 0.3 + 0.25 * (hue + 4.2).sin(), 1.0]);
449 let area = [0, 0, device.size[0] as i32, device.size[1] as i32];
450 unsafe { layer.draw(&mut ui, device.list, area) }.unwrap_or_else(|failed| panic!("{failed}"));
452 device.finish();
453 device.show();
454 }
455 }
456}