Skip to main content

d3d9/
d3d9.rs

1//! taut under Direct3D 9. The program renders with Direct3D as usual, and the interface lies
2//! over it: `taut::layer_d3d9::Layer`, made once from the program's device, draws it with one
3//! call per frame, inside the program's scene. Around it is the plainest possible program: a
4//! window, a Direct3D 9Ex device, and the window's messages forwarded to the interface.
5//!   cargo run --example d3d9
6//!
7//! The Direct3D API used is declared here by hand, as the Windows SDK's d3d9.h declares it: COM
8//! methods are called by vtable index, noted beside each call. (A program using a Windows
9//! bindings crate calls them by name, and passes the layer its device's raw pointer.)
10#[cfg(not(windows))]
11fn main() {
12    println!("Direct3D is Windows' own: there is nothing for this example to show here.");
13}
14
15#[cfg(windows)]
16fn main() {
17    direct3d::run();
18}
19
20#[cfg(windows)]
21#[allow(non_camel_case_types, clippy::upper_case_acronyms)]
22pub mod direct3d {
23    use std::cell::RefCell;
24    use std::ffi::c_void;
25    use std::ptr::{null, null_mut};
26    use std::time::{Duration, Instant};
27    use taut::geom::Size;
28    use taut::layer_d3d9::Layer;
29    use taut::platform::{Messages, SystemClipboard};
30    use taut::{Color, Length, Ui};
31
32    /// An object of Direct3D's: a pointer to a pointer to its table of functions.
33    pub type Com = *mut c_void;
34
35    /// Function number `at` of a COM object's table, as a function of the kind `F`.
36    ///
37    /// # Safety
38    /// The object is alive, and its function of that number is of that kind.
39    pub unsafe fn function<F: Copy>(object: Com, at: usize) -> F {
40        // SAFETY: as the caller promises; a function is known by where it is, one number.
41        unsafe { std::mem::transmute_copy(&*(*(object as *const *const usize)).add(at)) }
42    }
43
44    /// Lets go of a COM object (function 2, of every one), if there is one.
45    ///
46    /// # Safety
47    /// The object is held once here, and not used after this.
48    pub unsafe fn release(object: Com) {
49        if !object.is_null() {
50            unsafe { function::<unsafe extern "system" fn(Com) -> u32>(object, 2)(object) };
51        }
52    }
53
54    /// Stops the program with what Direct3D said, where it said something went wrong.
55    pub fn check(result: i32, what: &str) {
56        assert!(result >= 0, "{what} failed: {:#010x}", result as u32);
57    }
58
59    #[link(name = "d3d9")]
60    unsafe extern "system" {
61        fn Direct3DCreate9(version: u32) -> Com;
62        fn Direct3DCreate9Ex(version: u32, made: *mut Com) -> i32;
63    }
64
65    /// `D3DPRESENT_PARAMETERS`.
66    #[repr(C)]
67    #[derive(Clone, Copy)]
68    pub struct D3DPRESENT_PARAMETERS {
69        pub width: u32,
70        pub height: u32,
71        pub format: u32,
72        pub count: u32,
73        pub multisample: u32,
74        pub quality: u32,
75        pub swap_effect: u32,
76        pub window: isize,
77        pub windowed: i32,
78        pub depth: i32,
79        pub depth_format: u32,
80        pub flags: u32,
81        pub refresh: u32,
82        pub interval: u32,
83    }
84
85    /// A Direct3D 9 device on the graphics card (9Ex, or the first kind where `ex` is false),
86    /// showing its frames in the window.
87    pub struct Device {
88        d3d: Com,
89        /// The device (`IDirect3DDevice9Ex`, or `IDirect3DDevice9`).
90        pub device: Com,
91        /// It is a 9Ex device.
92        pub ex: bool,
93        /// How it shows its frames: its back buffer's size among them.
94        pub shown: D3DPRESENT_PARAMETERS,
95    }
96
97    impl Device {
98        pub fn new(window: isize, ex: bool) -> Device {
99            // A back buffer of A8R8G8B8 (21) the window's size, its frames let go of once shown
100            // (1), in a window, shown at the screen's refresh (0).
101            let shown = D3DPRESENT_PARAMETERS {
102                width: 0,
103                height: 0,
104                format: 21,
105                count: 1,
106                multisample: 0,
107                quality: 0,
108                swap_effect: 1,
109                window,
110                windowed: 1,
111                depth: 0,
112                depth_format: 0,
113                flags: 0,
114                refresh: 0,
115                interval: 0,
116            };
117            let mut made = Device { d3d: null_mut(), device: null_mut(), ex, shown };
118            // Vertices made by the graphics card (0x40), the window left as it is (0x800), the
119            // processor's floating point left as it is (0x2).
120            let flags = 0x40 | 0x800 | 0x2;
121            // SAFETY: the version is the SDK's (32); the description is whole. (IDirect3D9Ex 20:
122            // CreateDeviceEx; IDirect3D9 16: CreateDevice; on the first adapter (0), the
123            // graphics card (1).)
124            unsafe {
125                if ex {
126                    check(Direct3DCreate9Ex(32, &mut made.d3d), "making Direct3D 9Ex");
127                    type Make = unsafe extern "system" fn(Com, u32, u32, isize, u32, *mut D3DPRESENT_PARAMETERS, *const c_void, *mut Com) -> i32;
128                    check(function::<Make>(made.d3d, 20)(made.d3d, 0, 1, window, flags, &mut made.shown, null(), &mut made.device), "making a Direct3D 9Ex device");
129                } else {
130                    made.d3d = Direct3DCreate9(32);
131                    assert!(!made.d3d.is_null(), "making Direct3D 9");
132                    type Make = unsafe extern "system" fn(Com, u32, u32, isize, u32, *mut D3DPRESENT_PARAMETERS, *mut Com) -> i32;
133                    check(function::<Make>(made.d3d, 16)(made.d3d, 0, 1, window, flags, &mut made.shown, &mut made.device), "making a Direct3D 9 device");
134                }
135            }
136            made
137        }
138
139        /// The back buffer at the window's new size (0 by 0: the size it has). A device of the
140        /// first kind lets go of everything in its own memory first: so the layer does, before.
141        pub fn resize(&mut self, width: u32, height: u32) -> i32 {
142            (self.shown.width, self.shown.height) = (width, height);
143            // SAFETY: the device is alive (IDirect3DDevice9Ex 132: ResetEx; IDirect3DDevice9 16:
144            // Reset).
145            unsafe {
146                match self.ex {
147                    true => function::<unsafe extern "system" fn(Com, *mut D3DPRESENT_PARAMETERS, *const c_void) -> i32>(self.device, 132)(self.device, &mut self.shown, null()),
148                    false => function::<unsafe extern "system" fn(Com, *mut D3DPRESENT_PARAMETERS) -> i32>(self.device, 16)(self.device, &mut self.shown),
149                }
150            }
151        }
152
153        /// Starts a frame: the back buffer filled with the program's own picture, which is
154        /// here a colour (`0xAARRGGBB`), and the scene begun (device 43 clears, 41 begins).
155        pub fn begin(&self, colour: u32) {
156            // SAFETY: the device is alive.
157            unsafe {
158                function::<unsafe extern "system" fn(Com, u32, *const c_void, u32, u32, f32, u32) -> i32>(self.device, 43)(self.device, 0, null(), 1, colour, 1.0, 0);
159                check(function::<unsafe extern "system" fn(Com) -> i32>(self.device, 41)(self.device), "beginning the scene");
160            }
161        }
162
163        /// Ends the scene (device 42), and shows the frame (17).
164        pub fn show(&self) {
165            // SAFETY: the device is alive.
166            unsafe {
167                function::<unsafe extern "system" fn(Com) -> i32>(self.device, 42)(self.device);
168                function::<unsafe extern "system" fn(Com, *const c_void, *const c_void, isize, *const c_void) -> i32>(self.device, 17)(self.device, null(), null(), 0, null());
169            }
170        }
171    }
172
173    impl Drop for Device {
174        fn drop(&mut self) {
175            // SAFETY: each is held once, by this.
176            unsafe { [self.device, self.d3d].into_iter().for_each(|object| release(object)) };
177        }
178    }
179
180    // Everything from here on is the program's own: its window, what it shows, its loop.
181
182    #[repr(C)]
183    struct WNDCLASSW {
184        style: u32,
185        proc: unsafe extern "system" fn(isize, u32, usize, isize) -> isize,
186        class_extra: i32,
187        window_extra: i32,
188        instance: isize,
189        icon: isize,
190        cursor: isize,
191        background: isize,
192        menu: *const u16,
193        name: *const u16,
194    }
195    #[repr(C)]
196    #[derive(Default)]
197    struct MSG {
198        hwnd: isize,
199        message: u32,
200        wparam: usize,
201        lparam: isize,
202        time: u32,
203        pt: [i32; 2],
204    }
205    #[repr(C)]
206    struct TRACKMOUSEEVENT {
207        size: u32,
208        flags: u32,
209        hwnd: isize,
210        hover_time: u32,
211    }
212    #[link(name = "user32")]
213    unsafe extern "system" {
214        fn RegisterClassW(class: *const WNDCLASSW) -> u16;
215        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;
216        fn DefWindowProcW(hwnd: isize, msg: u32, w: usize, l: isize) -> isize;
217        fn PeekMessageW(msg: *mut MSG, hwnd: isize, first: u32, last: u32, remove: u32) -> i32;
218        fn TranslateMessage(msg: *const MSG) -> i32;
219        fn DispatchMessageW(msg: *const MSG) -> isize;
220        fn PostQuitMessage(code: i32);
221        fn LoadCursorW(instance: isize, name: *const u16) -> isize;
222        fn TrackMouseEvent(track: *mut TRACKMOUSEEVENT) -> i32;
223        fn SetProcessDpiAwarenessContext(context: isize) -> i32;
224        fn GetDpiForWindow(hwnd: isize) -> u32;
225    }
226    #[link(name = "kernel32")]
227    unsafe extern "system" {
228        fn GetModuleHandleW(name: *const u16) -> isize;
229    }
230    const WM_DESTROY: u32 = 0x0002;
231    const WM_SIZE: u32 = 0x0005;
232    const WM_QUIT: u32 = 0x0012;
233    const WM_MOUSEMOVE: u32 = 0x0200;
234
235    thread_local! {
236        /// The messages the window got since they were last looked at.
237        static HEARD: RefCell<Vec<(u32, usize, isize)>> = const { RefCell::new(Vec::new()) };
238    }
239
240    /// What Windows calls with each message for the window: it is kept, for the loop below.
241    unsafe extern "system" fn keep(hwnd: isize, msg: u32, w: usize, l: isize) -> isize {
242        HEARD.with_borrow_mut(|heard| heard.push((msg, w, l)));
243        // (Windows says when the pointer leaves the window only to a window that asks.)
244        let mut leave = TRACKMOUSEEVENT { size: size_of::<TRACKMOUSEEVENT>() as u32, flags: 2, hwnd, hover_time: 0 };
245        // SAFETY: the window is this one; the record is filled in as Windows wants it.
246        match msg {
247            WM_DESTROY => unsafe { PostQuitMessage(0) },
248            WM_MOUSEMOVE => _ = unsafe { TrackMouseEvent(&mut leave) },
249            _ => {}
250        }
251        unsafe { DefWindowProcW(hwnd, msg, w, l) }
252    }
253
254    /// Hands the window every message that is waiting for it; false once the program is to end.
255    fn pump() -> bool {
256        let mut message = MSG::default();
257        // SAFETY: messages of this thread's window, handed back to Windows to be sent on.
258        while unsafe { PeekMessageW(&mut message, 0, 0, 0, 1) } != 0 {
259            if message.message == WM_QUIT {
260                return false;
261            }
262            unsafe { (TranslateMessage(&message), DispatchMessageW(&message)) };
263        }
264        true
265    }
266
267    /// What the program's own parts are set to.
268    struct App {
269        still: bool,
270        speed: f32,
271        name: String,
272    }
273
274    fn describe(app: &mut App, ui: &mut Ui) {
275        let t = ui.theme;
276        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();
277        ui.text("Over Direct3D 9", t.font.bold(), t.text);
278        ui.switch(&mut app.still, "Hold the colour still");
279        ui.slider(&mut app.speed, 0.0..=4.0);
280        ui.text_box(&mut app.name, "Type here");
281        ui.note(&format!("{} letters typed", app.name.chars().count()));
282        ui.close();
283    }
284
285    pub fn run() {
286        let (class, title): (Vec<u16>, Vec<u16>) = ("taut-d3d9\0".encode_utf16().collect(), "taut over Direct3D 9\0".encode_utf16().collect());
287        // SAFETY: the class and the window are made once, with names that end in a zero; the
288        // pixels of this program are the screen's own (-4: per monitor, the second way).
289        let window = unsafe {
290            SetProcessDpiAwarenessContext(-4);
291            let instance = GetModuleHandleW(null());
292            let arrow = LoadCursorW(0, 32512 as *const u16);
293            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() });
294            CreateWindowExW(0, class.as_ptr(), title.as_ptr(), 0x10CF_0000, i32::MIN, i32::MIN, 900, 600, 0, 0, instance, null())
295        };
296        let mut device = Device::new(window, true);
297        // SAFETY: the device is the program's own, and alive.
298        let mut layer = unsafe { Layer::new(device.device) }.unwrap_or_else(|failed| panic!("{failed}"));
299        let mut ui = Ui::new(taut::platform::system_text(), Box::new(SystemClipboard));
300        ui.theme.bg = Color::NONE;
301        let mut app = App { still: false, speed: 1.0, name: String::new() };
302        let (mut messages, scale) = (Messages::of(window), unsafe { GetDpiForWindow(window) } as f32 / 96.0);
303        let (mut waiting, started, mut hue) = (true, Instant::now(), 0.0f32);
304        while pump() {
305            for (msg, w, l) in HEARD.take() {
306                let (width, height) = (l as u32 & 0xffff, l as u32 >> 16 & 0xffff);
307                if msg == WM_SIZE && width > 0 && height > 0 {
308                    layer.before_reset();
309                    check(device.resize(width, height), "resizing the back buffer");
310                    ui.resize(Size { w: width as f32 / scale, h: height as f32 / scale }, scale);
311                    waiting = true;
312                }
313                // SAFETY: the message comes straight from the window procedure, with what
314                // Windows sent along with it.
315                unsafe { messages.events(msg, w, l, scale, |event| waiting |= ui.event(event)) };
316            }
317            // The interface runs when something happened, or something in it moves.
318            ui.set_time(started.elapsed());
319            if std::mem::take(&mut waiting) || ui.wake_in() == Some(Duration::ZERO) {
320                ui.run(&mut |ui| describe(&mut app, ui));
321            }
322            hue += if app.still { 0.0 } else { app.speed / 120.0 };
323            let channel = |at: f32| ((0.3 + 0.25 * (hue + at).sin()) * 255.0) as u32;
324            device.begin(0xff00_0000 | channel(0.0) << 16 | channel(2.1) << 8 | channel(4.2));
325            layer.draw(&mut ui).unwrap_or_else(|failed| panic!("{failed}"));
326            device.show();
327        }
328    }
329}