1#[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 pub type Com = *mut c_void;
34
35 pub unsafe fn function<F: Copy>(object: Com, at: usize) -> F {
40 unsafe { std::mem::transmute_copy(&*(*(object as *const *const usize)).add(at)) }
42 }
43
44 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 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 #[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 pub struct Device {
88 d3d: Com,
89 pub device: Com,
91 pub ex: bool,
93 pub shown: D3DPRESENT_PARAMETERS,
95 }
96
97 impl Device {
98 pub fn new(window: isize, ex: bool) -> Device {
99 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 let flags = 0x40 | 0x800 | 0x2;
121 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 pub fn resize(&mut self, width: u32, height: u32) -> i32 {
142 (self.shown.width, self.shown.height) = (width, height);
143 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 pub fn begin(&self, colour: u32) {
156 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 pub fn show(&self) {
165 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 unsafe { [self.device, self.d3d].into_iter().for_each(|object| release(object)) };
177 }
178 }
179
180 #[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 static HEARD: RefCell<Vec<(u32, usize, isize)>> = const { RefCell::new(Vec::new()) };
238 }
239
240 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 let mut leave = TRACKMOUSEEVENT { size: size_of::<TRACKMOUSEEVENT>() as u32, flags: 2, hwnd, hover_time: 0 };
245 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 fn pump() -> bool {
256 let mut message = MSG::default();
257 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 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 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 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 unsafe { messages.events(msg, w, l, scale, |event| waiting |= ui.event(event)) };
316 }
317 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}