~raph/dx11-toy

dx11-toy/src/d3d11.rs -rw-r--r-- 7.6 KiB
c3700a74Raph Levien Move shaders into file 2 years ago
                                                                                
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
use std::ops::Deref;
use std::ptr::{null, null_mut};

use winapi::um::{d3d11, d3dcommon, d3dcompiler};

use wio::com::ComPtr;

use crate::util::{wrap, Error};

pub struct D3D11Device(ComPtr<d3d11::ID3D11Device>);
pub struct D3D11DeviceContext(ComPtr<d3d11::ID3D11DeviceContext>);
pub struct D3D11Texture2D(pub ComPtr<d3d11::ID3D11Texture2D>);
pub struct D3D11RenderTargetView(pub ComPtr<d3d11::ID3D11RenderTargetView>);
pub struct D3D11Buffer(ComPtr<d3d11::ID3D11Buffer>);
pub struct D3DBlob(ComPtr<d3dcommon::ID3DBlob>);
pub struct D3D11VertexShader(ComPtr<d3d11::ID3D11VertexShader>);
pub struct D3D11PixelShader(ComPtr<d3d11::ID3D11PixelShader>);
pub struct D3D11InputLayout(ComPtr<d3d11::ID3D11InputLayout>);

impl D3D11Device {
    // This function only supports a fraction of available options.
    pub fn create() -> Result<(D3D11Device, D3D11DeviceContext), Error> {
        unsafe {
            let mut ptr = null_mut();
            let mut ctx_ptr = null_mut();
            let hr = d3d11::D3D11CreateDevice(
                null_mut(), /* adapter */
                d3dcommon::D3D_DRIVER_TYPE_HARDWARE,
                null_mut(), /* module */
                d3d11::D3D11_CREATE_DEVICE_BGRA_SUPPORT,
                null_mut(), /* feature levels */
                0,
                d3d11::D3D11_SDK_VERSION,
                &mut ptr,
                null_mut(), /* feature level */
                &mut ctx_ptr,
            );
            let device = wrap(hr, ptr, D3D11Device)?;
            let device_ctx = wrap(hr, ctx_ptr, D3D11DeviceContext)?;
            Ok((device, device_ctx))
        }
    }

    pub fn as_raw(&self) -> *mut d3d11::ID3D11Device {
        self.0.as_raw()
    }

    pub fn create_render_target_view(
        &self,
        resource: &D3D11Texture2D,
    ) -> Result<D3D11RenderTargetView, Error> {
        unsafe {
            let mut ptr = null_mut();
            let hr = self
                .0
                .CreateRenderTargetView(resource.0.as_raw() as *mut _, null(), &mut ptr);
            wrap(hr, ptr, D3D11RenderTargetView)
        }
    }

    /// Create a buffer from data.
    ///
    /// This method doesn't expose all possible options and is not
    /// suitable for creating an uninitialized buffer.
    pub fn create_buffer_from_data<T>(
        &self,
        data: &[T],
        usage: d3d11::D3D11_USAGE,
        bind_flags: u32,
        cpu_access_flags: u32,
        misc_flags: u32,
        is_srv: bool,
    ) -> Result<D3D11Buffer, Error> {
        unsafe {
            let mut ptr = null_mut();
            let size = std::mem::size_of_val(data);
            // TODO: this should probably be try_from
            assert!(size <= 0xffff_ffff);
            let byte_stride = if is_srv { std::mem::size_of::<T>() } else { 0 };
            assert!(byte_stride <= 0xffff_ffff);
            let desc = d3d11::D3D11_BUFFER_DESC {
                ByteWidth: size as u32,
                Usage: usage,
                BindFlags: bind_flags,
                CPUAccessFlags: cpu_access_flags,
                MiscFlags: misc_flags,
                StructureByteStride: byte_stride as u32,
            };
            let srd = d3d11::D3D11_SUBRESOURCE_DATA {
                pSysMem: data.as_ptr() as *const _,
                SysMemPitch: 0,
                SysMemSlicePitch: 0,
            };
            let hr = self.0.CreateBuffer(&desc, &srd, &mut ptr);
            wrap(hr, ptr, D3D11Buffer)
        }
    }

    pub fn create_vertex_shader(&self, shader: &[u8]) -> Result<D3D11VertexShader, Error> {
        unsafe {
            let mut ptr = null_mut();
            let hr = self.0.CreateVertexShader(
                shader.as_ptr() as *const _,
                shader.len(),
                null_mut(),
                &mut ptr,
            );
            wrap(hr, ptr, D3D11VertexShader)
        }
    }

    pub fn create_pixel_shader(&self, shader: &[u8]) -> Result<D3D11PixelShader, Error> {
        unsafe {
            let mut ptr = null_mut();
            let hr = self.0.CreatePixelShader(
                shader.as_ptr() as *const _,
                shader.len(),
                null_mut(),
                &mut ptr,
            );
            wrap(hr, ptr, D3D11PixelShader)
        }
    }

    pub fn create_input_layout(
        &self,
        descs: &[d3d11::D3D11_INPUT_ELEMENT_DESC],
        bytecode: &[u8],
    ) -> Result<D3D11InputLayout, Error> {
        unsafe {
            assert!(descs.len() <= 0xffff_ffff);
            let mut ptr = null_mut();
            let hr = self.0.CreateInputLayout(
                descs.as_ptr(),
                descs.len() as u32,
                bytecode.as_ptr() as *const _,
                bytecode.len(),
                &mut ptr,
            );
            wrap(hr, ptr, D3D11InputLayout)
        }
    }
}

impl D3D11DeviceContext {
    /// Sets a single render target, no stencil.
    pub fn set_render_target(&mut self, rtv: &D3D11RenderTargetView) {
        unsafe {
            let rtvs = [rtv.0.as_raw()];
            self.0.OMSetRenderTargets(1, rtvs.as_ptr(), null_mut());
        }
    }

    /// Sets a single viewport.
    pub fn set_viewport(&mut self, viewport: &d3d11::D3D11_VIEWPORT) {
        unsafe {
            self.0.RSSetViewports(1, viewport);
        }
    }

    pub fn clear_render_target_view(&mut self, rtv: &mut D3D11RenderTargetView, color: &[f32; 4]) {
        unsafe {
            self.0.ClearRenderTargetView(rtv.0.as_raw(), color);
        }
    }

    pub fn vs_set_shader(&mut self, shader: &D3D11VertexShader) {
        unsafe {
            self.0.VSSetShader(shader.0.as_raw(), null(), 0);
        }
    }

    pub fn ps_set_shader(&mut self, shader: &D3D11PixelShader) {
        unsafe {
            self.0.PSSetShader(shader.0.as_raw(), null(), 0);
        }
    }

    pub fn ia_set_vertex_buffer(&mut self, buf: &D3D11Buffer) {
        let stride = std::mem::size_of::<[f32; 3]>();
        let bufs = [buf.0.as_raw()];
        let strides = [stride as u32];
        let offsets = [0];
        unsafe {
            self.0
                .IASetVertexBuffers(0, 1, bufs.as_ptr(), strides.as_ptr(), offsets.as_ptr());
        }
    }

    pub fn ia_set_primitive_topology(&mut self, topology: d3d11::D3D11_PRIMITIVE_TOPOLOGY) {
        unsafe {
            self.0.IASetPrimitiveTopology(topology);
        }
    }

    pub fn ia_set_input_layout(&mut self, layout: &D3D11InputLayout) {
        unsafe {
            self.0.IASetInputLayout(layout.0.as_raw());
        }
    }

    pub fn draw(&mut self, count: u32, start: u32) {
        unsafe {
            self.0.Draw(count, start);
        }
    }
}

impl D3DBlob {
    pub fn compile_shader(
        hlsl: &str,
        target: &str,
        entry: &str,
        flags: u32,
    ) -> Result<D3DBlob, Error> {
        let target = [target, "\0"].concat();
        let entry = [entry, "\0"].concat();
        unsafe {
            let mut ptr = null_mut();
            let hr = d3dcompiler::D3DCompile(
                hlsl.as_ptr() as *const _,
                hlsl.len(),
                null(),
                null(),
                d3dcompiler::D3D_COMPILE_STANDARD_FILE_INCLUDE,
                entry.as_ptr() as *const _,
                target.as_ptr() as *const _,
                flags,
                0,
                &mut ptr,
                null_mut(),
            );
            //println!("blob: {} bytes", (*ptr).GetBufferSize());
            wrap(hr, ptr, D3DBlob)
        }
    }
}

impl Deref for D3DBlob {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        unsafe {
            let ptr = self.0.GetBufferPointer();
            let size = self.0.GetBufferSize();
            std::slice::from_raw_parts(ptr as *const _, size as usize)
        }
    }
}