dxgi 0.1.0

Provides a convenient, higher level wrapping of the DXGI APIs. Targetting dxgi 1.2 stuff that works on Windows 7.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use device::Device;
use error::Error;
use surface::Surface;

use std::ffi::OsString;
use std::fmt;
use std::mem;
use std::ptr;

use num::rational::Ratio;
use winapi::shared::dxgi::{IDXGIOutput, DXGI_FRAME_STATISTICS, DXGI_OUTPUT_DESC};
use winapi::shared::dxgiformat::{DXGI_FORMAT, DXGI_FORMAT_UNKNOWN};
use winapi::shared::dxgitype::{DXGI_GAMMA_CONTROL, DXGI_GAMMA_CONTROL_CAPABILITIES,
                               DXGI_MODE_DESC, DXGI_MODE_ROTATION, DXGI_MODE_SCALING,
                               DXGI_MODE_SCALING_UNSPECIFIED, DXGI_MODE_SCANLINE_ORDER,
                               DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED, DXGI_RATIONAL, DXGI_RGB};
use winapi::shared::minwindef::BOOL;
use winapi::shared::windef::{HMONITOR, RECT};
use winapi::shared::winerror::{DXGI_ERROR_MORE_DATA, DXGI_ERROR_NOT_CURRENTLY_AVAILABLE, S_OK};
use winapi::um::unknwnbase::IUnknown;
use wio::com::ComPtr;
use wio::wide::FromWide;

pub struct Output {
    ptr: ComPtr<IDXGIOutput>,
}

impl Output {
    #[inline]
    pub unsafe fn from_raw(ptr: *mut IDXGIOutput) -> Output {
        Output {
            ptr: ComPtr::from_raw(ptr),
        }
    }

    #[inline]
    pub unsafe fn get_raw(&self) -> *mut IDXGIOutput {
        self.ptr.as_raw()
    }

    #[inline]
    pub fn get_desc(&self) -> OutputDesc {
        unsafe {
            let mut desc = mem::uninitialized();

            let result = self.ptr.GetDesc(&mut desc);
            assert!(result >= 0);

            OutputDesc { desc }
        }
    }

    #[inline]
    pub fn get_modes(&self, format: DXGI_FORMAT) -> Result<Vec<Mode>, Error> {
        unsafe {
            let mut buf: Vec<Mode> = Vec::new();
            loop {
                let mut len = 0;
                let ptr = ptr::null_mut();
                let hr = self.ptr.GetDisplayModeList(format, 2, &mut len, ptr);
                Error::map(hr, ())?;

                buf.reserve_exact(len as usize);

                let ptr = buf.as_mut_ptr() as *mut DXGI_MODE_DESC;
                let hr = self.ptr.GetDisplayModeList(format, 2, &mut len, ptr);
                match hr {
                    S_OK => {
                        buf.set_len(len as usize);
                        return Ok(buf);
                    }
                    DXGI_ERROR_MORE_DATA => continue,
                    DXGI_ERROR_NOT_CURRENTLY_AVAILABLE => return Err(Error(hr)),
                    _ => unreachable!(),
                }
            }
        }
    }

    #[inline]
    pub fn find_closest_matching_mode(
        &self,
        mode: &Mode,
        device: Option<&Device>,
    ) -> Result<Mode, Error> {
        unsafe {
            let dev = device
                .map(|d| d.get_raw() as *mut IUnknown)
                .unwrap_or(ptr::null_mut());

            let mut matching: Mode = mem::uninitialized();
            let hr = self.ptr
                .FindClosestMatchingMode(&mode.desc, &mut matching.desc, dev);

            Error::map(hr, matching)
        }
    }

    #[inline]
    pub fn wait_for_vblank(&self) -> Result<(), Error> {
        unsafe {
            let hr = self.ptr.WaitForVBlank();
            Error::map(hr, ())
        }
    }

    #[inline]
    pub fn take_ownership(&self, device: &Device, exclusive: bool) -> Result<(), Error> {
        unsafe {
            let dev = device.get_raw();
            let hr = self.ptr.TakeOwnership(dev as *mut _, exclusive as BOOL);
            Error::map(hr, ())
        }
    }

    #[inline]
    pub fn release_ownership(&self) {
        unsafe {
            self.ptr.ReleaseOwnership();
        }
    }

    #[inline]
    pub fn get_gamma_control_capabilities(&self) -> Result<GammaControlCaps, Error> {
        unsafe {
            let mut caps: GammaControlCaps = mem::uninitialized();
            let hr = self.ptr.GetGammaControlCapabilities(&mut caps.desc);
            Error::map(hr, caps)
        }
    }

    #[inline]
    pub fn get_gamma_control(&self) -> Result<GammaControl, Error> {
        unsafe {
            let mut control: GammaControl = mem::uninitialized();
            let hr = self.ptr.GetGammaControl(&mut control.desc);
            Error::map(hr, control)
        }
    }

    #[inline]
    pub fn set_gamma_control(&self, control: &GammaControl) -> Result<(), Error> {
        unsafe {
            let hr = self.ptr.SetGammaControl(&control.desc);
            Error::map(hr, ())
        }
    }

    // NOTE: Windows docs say to *NEVER* use SetDisplaySurface as an application. I've omitted the
    // method for now. If someone has a use case for it, open an issue and I'll add it.

    #[inline]
    pub fn get_display_surface_data(&self, surface: &Surface) -> Result<(), Error> {
        unsafe {
            let hr = self.ptr.GetDisplaySurfaceData(surface.get_raw());
            Error::map(hr, ())
        }
    }

    #[inline]
    pub fn get_frame_statistics(&self) -> Result<FrameStatistics, Error> {
        unsafe {
            let mut stats: FrameStatistics = mem::uninitialized();
            let hr = self.ptr.GetFrameStatistics(&mut stats.desc);
            Error::map(hr, stats)
        }
    }
}

unsafe impl Send for Output {}
unsafe impl Sync for Output {}

#[derive(Copy, Clone)]
pub struct OutputDesc {
    desc: DXGI_OUTPUT_DESC,
}

impl OutputDesc {
    #[inline]
    pub fn device_name(&self) -> String {
        let len = self.desc
            .DeviceName
            .iter()
            .position(|&c| c == 0)
            .unwrap_or(128);
        let ostr = OsString::from_wide(&self.desc.DeviceName[..len]);
        ostr.to_string_lossy().into_owned()
    }

    #[inline]
    pub fn desktop_coordinates(&self) -> RECT {
        self.desc.DesktopCoordinates
    }

    #[inline]
    pub fn attached_to_desktop(&self) -> bool {
        self.desc.AttachedToDesktop != 0
    }

    #[inline]
    pub fn rotation(&self) -> DXGI_MODE_ROTATION {
        self.desc.Rotation
    }

    #[inline]
    pub fn monitor(&self) -> HMONITOR {
        self.desc.Monitor
    }
}

#[repr(C)]
#[derive(Copy, Clone)]
pub struct Mode {
    desc: DXGI_MODE_DESC,
}

impl Mode {
    #[inline]
    pub fn new() -> Mode {
        Mode {
            desc: DXGI_MODE_DESC {
                Width: 0,
                Height: 0,
                RefreshRate: DXGI_RATIONAL {
                    Numerator: 0,
                    Denominator: 1,
                },
                Format: DXGI_FORMAT_UNKNOWN,
                ScanlineOrdering: DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED,
                Scaling: DXGI_MODE_SCALING_UNSPECIFIED,
            },
        }
    }

    #[inline]
    pub fn width(&self) -> u32 {
        self.desc.Width
    }

    #[inline]
    pub fn set_width(&mut self, width: u32) {
        self.desc.Width = width;
    }

    #[inline]
    pub fn height(&self) -> u32 {
        self.desc.Height
    }

    #[inline]
    pub fn set_height(&mut self, height: u32) {
        self.desc.Height = height;
    }

    #[inline]
    pub fn refresh_rate(&self) -> Ratio<u32> {
        Ratio::new(
            self.desc.RefreshRate.Numerator,
            self.desc.RefreshRate.Denominator,
        )
    }

    #[inline]
    pub fn set_refresh_rate(&mut self, rate: Ratio<u32>) {
        self.desc.RefreshRate.Numerator = *rate.numer();
        self.desc.RefreshRate.Denominator = *rate.denom();
    }

    #[inline]
    pub fn format(&self) -> DXGI_FORMAT {
        self.desc.Format
    }

    #[inline]
    pub fn set_format(&mut self, format: DXGI_FORMAT) {
        self.desc.Format = format;
    }

    #[inline]
    pub fn scanline_ordering(&self) -> DXGI_MODE_SCANLINE_ORDER {
        self.desc.ScanlineOrdering
    }

    #[inline]
    pub fn set_scanline_ordering(&mut self, ordering: DXGI_MODE_SCANLINE_ORDER) {
        self.desc.ScanlineOrdering = ordering;
    }

    #[inline]
    pub fn scaling(&self) -> DXGI_MODE_SCALING {
        self.desc.Scaling
    }

    #[inline]
    pub fn set_scaling(&mut self, scaling: DXGI_MODE_SCALING) {
        self.desc.Scaling = scaling;
    }

    #[inline]
    pub fn raw(&self) -> &DXGI_MODE_DESC {
        &self.desc
    }
}

impl fmt::Debug for Mode {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Mode")
            .field("width", &self.width())
            .field("height", &self.height())
            .field("refresh_rate", &self.refresh_rate())
            .field("format", &self.format())
            .field("scanline_ordering", &self.scanline_ordering())
            .field("scaling", &self.scaling())
            .finish()
    }
}

#[derive(Copy, Clone)]
pub struct GammaControlCaps {
    desc: DXGI_GAMMA_CONTROL_CAPABILITIES,
}

impl GammaControlCaps {
    #[inline]
    pub fn scale_and_offset_supported(&self) -> bool {
        self.desc.ScaleAndOffsetSupported != 0
    }

    #[inline]
    pub fn max_converted_value(&self) -> f32 {
        self.desc.MaxConvertedValue
    }

    #[inline]
    pub fn min_converted_value(&self) -> f32 {
        self.desc.MinConvertedValue
    }

    #[inline]
    pub fn control_point_positions(&self) -> &[f32] {
        assert!(self.desc.NumGammaControlPoints <= 1025);
        &self.desc.ControlPointPositions[..self.desc.NumGammaControlPoints as usize]
    }
}

impl fmt::Debug for GammaControlCaps {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("GammaControlCaps")
            .field(
                "scale_and_offset_supported",
                &self.scale_and_offset_supported(),
            )
            .field("max_converted_value", &self.max_converted_value())
            .field("min_converted_value", &self.min_converted_value())
            .field("control_point_positions", &self.control_point_positions())
            .finish()
    }
}

#[derive(Copy, Clone)]
pub struct GammaControl {
    desc: DXGI_GAMMA_CONTROL,
}

impl GammaControl {
    #[inline]
    pub fn new() -> GammaControl {
        unsafe { mem::zeroed() }
    }

    #[inline]
    pub fn scale(&self) -> Rgb {
        unsafe { mem::transmute(self.desc.Scale) }
    }

    #[inline]
    pub fn set_scale(&mut self, scale: Rgb) {
        self.desc.Scale = scale.rgb;
    }

    #[inline]
    pub fn offset(&self) -> Rgb {
        unsafe { mem::transmute(self.desc.Offset) }
    }

    #[inline]
    pub fn set_offset(&mut self, offset: Rgb) {
        self.desc.Offset = offset.rgb;
    }

    #[inline]
    pub fn gamma_curve(&self) -> &[Rgb; 1025] {
        unsafe { mem::transmute(&self.desc.GammaCurve) }
    }

    #[inline]
    pub fn gamma_curve_mut(&mut self) -> &mut [Rgb; 1025] {
        unsafe { mem::transmute(&mut self.desc.GammaCurve) }
    }
}

#[repr(C)]
#[derive(Copy, Clone)]
pub struct Rgb {
    rgb: DXGI_RGB,
}

impl Rgb {
    #[inline]
    pub fn new(r: f32, g: f32, b: f32) -> Rgb {
        Rgb {
            rgb: DXGI_RGB {
                Red: r,
                Green: g,
                Blue: b,
            },
        }
    }

    #[inline]
    pub fn r(&self) -> f32 {
        self.rgb.Red
    }

    #[inline]
    pub fn g(&self) -> f32 {
        self.rgb.Green
    }

    #[inline]
    pub fn b(&self) -> f32 {
        self.rgb.Blue
    }

    #[inline]
    pub fn set_r(&mut self, r: f32) {
        self.rgb.Red = r;
    }

    #[inline]
    pub fn set_g(&mut self, g: f32) {
        self.rgb.Green = g;
    }

    #[inline]
    pub fn set_b(&mut self, b: f32) {
        self.rgb.Blue = b;
    }
}

#[derive(Copy, Clone)]
pub struct FrameStatistics {
    desc: DXGI_FRAME_STATISTICS,
}

impl FrameStatistics {
    #[inline]
    pub fn present_count(&self) -> u32 {
        self.desc.PresentCount
    }

    #[inline]
    pub fn present_refresh_count(&self) -> u32 {
        self.desc.PresentRefreshCount
    }

    #[inline]
    pub fn sync_refresh_count(&self) -> u32 {
        self.desc.SyncRefreshCount
    }

    #[inline]
    pub fn sync_qpc_time(&self) -> i64 {
        unsafe { *self.desc.SyncQPCTime.QuadPart() }
    }

    #[inline]
    pub fn sync_gpu_time(&self) -> i64 {
        unsafe { *self.desc.SyncGPUTime.QuadPart() }
    }
}