render_backend_d3d11.odin 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. #+build windows
  2. #+private file
  3. package karl2d
  4. @(private="package")
  5. RENDER_BACKEND_INTERFACE_D3D11 :: Render_Backend_Interface {
  6. state_size = d3d11_state_size,
  7. init = d3d11_init,
  8. shutdown = d3d11_shutdown,
  9. clear = d3d11_clear,
  10. present = d3d11_present,
  11. draw = d3d11_draw,
  12. resize_swapchain = d3d11_resize_swapchain,
  13. get_swapchain_width = d3d11_get_swapchain_width,
  14. get_swapchain_height = d3d11_get_swapchain_height,
  15. flip_z = d3d11_flip_z,
  16. set_internal_state = d3d11_set_internal_state,
  17. create_texture = d3d11_create_texture,
  18. load_texture = d3d11_load_texture,
  19. update_texture = d3d11_update_texture,
  20. destroy_texture = d3d11_destroy_texture,
  21. load_shader = d3d11_load_shader,
  22. destroy_shader = d3d11_destroy_shader,
  23. default_shader_vertex_source = d3d11_default_shader_vertex_source,
  24. default_shader_fragment_source = d3d11_default_shader_fragment_source,
  25. }
  26. import d3d11 "vendor:directx/d3d11"
  27. import dxgi "vendor:directx/dxgi"
  28. import "vendor:directx/d3d_compiler"
  29. import "core:strings"
  30. import "core:log"
  31. import "core:slice"
  32. import "core:mem"
  33. import hm "handle_map"
  34. import "base:runtime"
  35. d3d11_state_size :: proc() -> int {
  36. return size_of(D3D11_State)
  37. }
  38. d3d11_init :: proc(state: rawptr, window_handle: Window_Handle, swapchain_width, swapchain_height: int, allocator := context.allocator) {
  39. s = (^D3D11_State)(state)
  40. s.allocator = allocator
  41. s.window_handle = dxgi.HWND(window_handle)
  42. s.width = swapchain_width
  43. s.height = swapchain_height
  44. feature_levels := [?]d3d11.FEATURE_LEVEL{
  45. ._11_1,
  46. ._11_0,
  47. }
  48. base_device: ^d3d11.IDevice
  49. base_device_context: ^d3d11.IDeviceContext
  50. base_device_flags := d3d11.CREATE_DEVICE_FLAGS {
  51. .BGRA_SUPPORT,
  52. }
  53. when ODIN_DEBUG {
  54. device_flags := base_device_flags + { .DEBUG }
  55. device_err := ch(d3d11.CreateDevice(
  56. nil,
  57. .HARDWARE,
  58. nil,
  59. device_flags,
  60. &feature_levels[0], len(feature_levels),
  61. d3d11.SDK_VERSION, &base_device, nil, &base_device_context))
  62. if u32(device_err) == 0x887a002d {
  63. log.error("You're running in debug mode. So we are trying to create a debug D3D11 device. But you don't have DirectX SDK installed, so we can't enable debug layers. Creating a device without debug layers (you'll get no good D3D11 errors).")
  64. ch(d3d11.CreateDevice(
  65. nil,
  66. .HARDWARE,
  67. nil,
  68. base_device_flags,
  69. &feature_levels[0], len(feature_levels),
  70. d3d11.SDK_VERSION, &base_device, nil, &base_device_context))
  71. } else {
  72. ch(base_device->QueryInterface(d3d11.IInfoQueue_UUID, (^rawptr)(&s.info_queue)))
  73. }
  74. } else {
  75. ch(d3d11.CreateDevice(
  76. nil,
  77. .HARDWARE,
  78. nil,
  79. base_device_flags,
  80. &feature_levels[0], len(feature_levels),
  81. d3d11.SDK_VERSION, &base_device, nil, &base_device_context))
  82. }
  83. ch(base_device->QueryInterface(d3d11.IDevice_UUID, (^rawptr)(&s.device)))
  84. ch(base_device_context->QueryInterface(d3d11.IDeviceContext_UUID, (^rawptr)(&s.device_context)))
  85. dxgi_device: ^dxgi.IDevice
  86. ch(s.device->QueryInterface(dxgi.IDevice_UUID, (^rawptr)(&dxgi_device)))
  87. base_device->Release()
  88. base_device_context->Release()
  89. ch(dxgi_device->GetAdapter(&s.dxgi_adapter))
  90. create_swapchain(swapchain_width, swapchain_height)
  91. rasterizer_desc := d3d11.RASTERIZER_DESC{
  92. FillMode = .SOLID,
  93. CullMode = .BACK,
  94. ScissorEnable = true,
  95. }
  96. ch(s.device->CreateRasterizerState(&rasterizer_desc, &s.rasterizer_state))
  97. depth_stencil_desc := d3d11.DEPTH_STENCIL_DESC{
  98. DepthEnable = true,
  99. DepthWriteMask = .ALL,
  100. DepthFunc = .LESS,
  101. }
  102. ch(s.device->CreateDepthStencilState(&depth_stencil_desc, &s.depth_stencil_state))
  103. vertex_buffer_desc := d3d11.BUFFER_DESC{
  104. ByteWidth = VERTEX_BUFFER_MAX,
  105. Usage = .DYNAMIC,
  106. BindFlags = {.VERTEX_BUFFER},
  107. CPUAccessFlags = {.WRITE},
  108. }
  109. ch(s.device->CreateBuffer(&vertex_buffer_desc, nil, &s.vertex_buffer_gpu))
  110. blend_desc := d3d11.BLEND_DESC {
  111. RenderTarget = {
  112. 0 = {
  113. BlendEnable = true,
  114. SrcBlend = .SRC_ALPHA,
  115. DestBlend = .INV_SRC_ALPHA,
  116. BlendOp = .ADD,
  117. SrcBlendAlpha = .ONE,
  118. DestBlendAlpha = .ZERO,
  119. BlendOpAlpha = .ADD,
  120. RenderTargetWriteMask = u8(d3d11.COLOR_WRITE_ENABLE_ALL),
  121. },
  122. },
  123. }
  124. ch(s.device->CreateBlendState(&blend_desc, &s.blend_state))
  125. sampler_desc := d3d11.SAMPLER_DESC{
  126. Filter = .MIN_MAG_MIP_POINT,
  127. AddressU = .WRAP,
  128. AddressV = .WRAP,
  129. AddressW = .WRAP,
  130. ComparisonFunc = .NEVER,
  131. }
  132. s.device->CreateSamplerState(&sampler_desc, &s.sampler_state)
  133. }
  134. d3d11_shutdown :: proc() {
  135. s.sampler_state->Release()
  136. s.framebuffer_view->Release()
  137. s.depth_buffer_view->Release()
  138. s.depth_buffer->Release()
  139. s.framebuffer->Release()
  140. s.device_context->Release()
  141. s.vertex_buffer_gpu->Release()
  142. s.depth_stencil_state->Release()
  143. s.rasterizer_state->Release()
  144. s.swapchain->Release()
  145. s.blend_state->Release()
  146. s.dxgi_adapter->Release()
  147. when ODIN_DEBUG {
  148. debug: ^d3d11.IDebug
  149. if ch(s.device->QueryInterface(d3d11.IDebug_UUID, (^rawptr)(&debug))) >= 0 {
  150. ch(debug->ReportLiveDeviceObjects({.DETAIL, .IGNORE_INTERNAL}))
  151. log_messages()
  152. }
  153. debug->Release()
  154. }
  155. s.device->Release()
  156. s.info_queue->Release()
  157. }
  158. d3d11_clear :: proc(color: Color) {
  159. c := f32_color_from_color(color)
  160. s.device_context->ClearRenderTargetView(s.framebuffer_view, &c)
  161. s.device_context->ClearDepthStencilView(s.depth_buffer_view, {.DEPTH}, 1, 0)
  162. }
  163. d3d11_present :: proc() {
  164. ch(s.swapchain->Present(1, {}))
  165. }
  166. d3d11_draw :: proc(shd: Shader, texture: Texture_Handle, scissor: Maybe(Rect), vertex_buffer: []u8) {
  167. if len(vertex_buffer) == 0 {
  168. return
  169. }
  170. d3d_shd := hm.get(&s.shaders, shd.handle)
  171. if d3d_shd == nil {
  172. return
  173. }
  174. viewport := d3d11.VIEWPORT{
  175. 0, 0,
  176. f32(s.width), f32(s.height),
  177. 0, 1,
  178. }
  179. dc := s.device_context
  180. vb_data: d3d11.MAPPED_SUBRESOURCE
  181. ch(dc->Map(s.vertex_buffer_gpu, 0, .WRITE_DISCARD, {}, &vb_data))
  182. {
  183. gpu_map := slice.from_ptr((^u8)(vb_data.pData), VERTEX_BUFFER_MAX)
  184. copy(
  185. gpu_map,
  186. vertex_buffer,
  187. )
  188. }
  189. dc->Unmap(s.vertex_buffer_gpu, 0)
  190. dc->IASetPrimitiveTopology(.TRIANGLELIST)
  191. dc->IASetInputLayout(d3d_shd.input_layout)
  192. vertex_buffer_offset: u32
  193. vertex_buffer_stride := u32(shd.vertex_size)
  194. dc->IASetVertexBuffers(0, 1, &s.vertex_buffer_gpu, &vertex_buffer_stride, &vertex_buffer_offset)
  195. dc->VSSetShader(d3d_shd.vertex_shader, nil, 0)
  196. assert(len(shd.constants) == len(d3d_shd.constants))
  197. maps := make([]rawptr, len(d3d_shd.constant_buffers), frame_allocator)
  198. cpu_data := shd.constants_data
  199. for cidx in 0..<len(shd.constants) {
  200. cpu_loc := shd.constants[cidx]
  201. gpu_loc := d3d_shd.constants[cidx]//cpu_loc.gpu_constant_idx]
  202. gpu_buffer_info := d3d_shd.constant_buffers[gpu_loc.buffer_idx]
  203. gpu_data := gpu_buffer_info.gpu_data
  204. if gpu_data == nil {
  205. continue
  206. }
  207. if maps[gpu_loc.buffer_idx] == nil {
  208. // We do this little dance with the 'maps' array so we only have to map the memory once.
  209. // There can be multiple constants within a single constant buffer. So mapping and
  210. // unmapping for each one is slow.
  211. map_data: d3d11.MAPPED_SUBRESOURCE
  212. ch(dc->Map(gpu_data, 0, .WRITE_DISCARD, {}, &map_data))
  213. maps[gpu_loc.buffer_idx] = map_data.pData
  214. }
  215. data_slice := slice.bytes_from_ptr(maps[gpu_loc.buffer_idx], gpu_buffer_info.size)
  216. dst := data_slice[gpu_loc.offset:gpu_loc.offset+u32(cpu_loc.size)]
  217. src := cpu_data[cpu_loc.offset:cpu_loc.offset+cpu_loc.size]
  218. copy(dst, src)
  219. }
  220. vs_constant_buffers := make([dynamic]^d3d11.IBuffer, frame_allocator)
  221. ps_constant_buffers := make([dynamic]^d3d11.IBuffer, frame_allocator)
  222. for cb, cb_idx in d3d_shd.constant_buffers {
  223. switch cb.type {
  224. case .Vertex:
  225. append(&vs_constant_buffers, cb.gpu_data)
  226. case .Pixel:
  227. append(&ps_constant_buffers, cb.gpu_data)
  228. }
  229. if maps[cb_idx] != nil {
  230. dc->Unmap(cb.gpu_data, 0)
  231. maps[cb_idx] = nil
  232. }
  233. }
  234. dc->VSSetConstantBuffers(0, u32(len(vs_constant_buffers)), raw_data(vs_constant_buffers))
  235. dc->PSSetConstantBuffers(0, u32(len(ps_constant_buffers)), raw_data(ps_constant_buffers))
  236. dc->RSSetViewports(1, &viewport)
  237. dc->RSSetState(s.rasterizer_state)
  238. scissor_rect := d3d11.RECT {
  239. right = i32(s.width),
  240. bottom = i32(s.height),
  241. }
  242. if sciss, sciss_ok := scissor.?; sciss_ok {
  243. scissor_rect = d3d11.RECT {
  244. left = i32(sciss.x),
  245. top = i32(sciss.y),
  246. right = i32(sciss.x + sciss.w),
  247. bottom = i32(sciss.y + sciss.h),
  248. }
  249. }
  250. dc->RSSetScissorRects(1, &scissor_rect)
  251. dc->PSSetShader(d3d_shd.pixel_shader, nil, 0)
  252. if t := hm.get(&s.textures, texture); t != nil {
  253. dc->PSSetShaderResources(0, 1, &t.view)
  254. }
  255. dc->PSSetSamplers(0, 1, &s.sampler_state)
  256. dc->OMSetRenderTargets(1, &s.framebuffer_view, s.depth_buffer_view)
  257. dc->OMSetDepthStencilState(s.depth_stencil_state, 0)
  258. dc->OMSetBlendState(s.blend_state, nil, ~u32(0))
  259. dc->Draw(u32(len(vertex_buffer)/shd.vertex_size), 0)
  260. log_messages()
  261. }
  262. d3d11_resize_swapchain :: proc(w, h: int) {
  263. s.depth_buffer->Release()
  264. s.depth_buffer_view->Release()
  265. s.framebuffer->Release()
  266. s.framebuffer_view->Release()
  267. s.swapchain->Release()
  268. s.width = w
  269. s.height = h
  270. create_swapchain(w, h)
  271. }
  272. d3d11_get_swapchain_width :: proc() -> int {
  273. return s.width
  274. }
  275. d3d11_get_swapchain_height :: proc() -> int {
  276. return s.height
  277. }
  278. d3d11_flip_z :: proc() -> bool {
  279. return true
  280. }
  281. d3d11_set_internal_state :: proc(state: rawptr) {
  282. s = (^D3D11_State)(state)
  283. }
  284. d3d11_create_texture :: proc(width: int, height: int, format: Pixel_Format) -> Texture_Handle {
  285. texture_desc := d3d11.TEXTURE2D_DESC{
  286. Width = u32(width),
  287. Height = u32(height),
  288. MipLevels = 1,
  289. ArraySize = 1,
  290. // TODO: _SRGB or not?
  291. Format = dxgi_format_from_pixel_format(format),
  292. SampleDesc = {Count = 1},
  293. Usage = .DEFAULT,
  294. BindFlags = {.SHADER_RESOURCE},
  295. }
  296. texture: ^d3d11.ITexture2D
  297. s.device->CreateTexture2D(&texture_desc, nil, &texture)
  298. texture_view: ^d3d11.IShaderResourceView
  299. s.device->CreateShaderResourceView(texture, nil, &texture_view)
  300. tex := D3D11_Texture {
  301. tex = texture,
  302. format = format,
  303. view = texture_view,
  304. }
  305. return hm.add(&s.textures, tex)
  306. }
  307. d3d11_load_texture :: proc(data: []u8, width: int, height: int, format: Pixel_Format) -> Texture_Handle {
  308. texture_desc := d3d11.TEXTURE2D_DESC{
  309. Width = u32(width),
  310. Height = u32(height),
  311. MipLevels = 1,
  312. ArraySize = 1,
  313. // TODO: _SRGB or not?
  314. Format = dxgi_format_from_pixel_format(format),
  315. SampleDesc = {Count = 1},
  316. Usage = .DEFAULT,
  317. BindFlags = {.SHADER_RESOURCE},
  318. }
  319. texture_data := d3d11.SUBRESOURCE_DATA{
  320. pSysMem = raw_data(data),
  321. SysMemPitch = u32(width * pixel_format_size(format)),
  322. }
  323. texture: ^d3d11.ITexture2D
  324. s.device->CreateTexture2D(&texture_desc, &texture_data, &texture)
  325. texture_view: ^d3d11.IShaderResourceView
  326. s.device->CreateShaderResourceView(texture, nil, &texture_view)
  327. tex := D3D11_Texture {
  328. tex = texture,
  329. format = format,
  330. view = texture_view,
  331. }
  332. return hm.add(&s.textures, tex)
  333. }
  334. d3d11_update_texture :: proc(th: Texture_Handle, data: []u8, rect: Rect) -> bool {
  335. tex := hm.get(&s.textures, th)
  336. if tex == nil {
  337. return false
  338. }
  339. box := d3d11.BOX {
  340. left = u32(rect.x),
  341. top = u32(rect.y),
  342. bottom = u32(rect.y + rect.h),
  343. right = u32(rect.x + rect.w),
  344. back = 1,
  345. front = 0,
  346. }
  347. row_pitch := pixel_format_size(tex.format) * int(rect.w)
  348. s.device_context->UpdateSubresource(tex.tex, 0, &box, raw_data(data), u32(row_pitch), 0)
  349. return true
  350. }
  351. d3d11_destroy_texture :: proc(th: Texture_Handle) {
  352. if t := hm.get(&s.textures, th); t != nil {
  353. t.tex->Release()
  354. t.view->Release()
  355. }
  356. hm.remove(&s.textures, th)
  357. }
  358. d3d11_load_shader :: proc(
  359. vs_source: string,
  360. ps_source: string,
  361. desc_allocator := frame_allocator,
  362. layout_formats: []Pixel_Format = {},
  363. ) -> (
  364. handle: Shader_Handle,
  365. desc: Shader_Desc,
  366. ) {
  367. vs_blob: ^d3d11.IBlob
  368. vs_blob_errors: ^d3d11.IBlob
  369. ch(d3d_compiler.Compile(raw_data(vs_source), len(vs_source), nil, nil, nil, "vs_main", "vs_5_0", 0, 0, &vs_blob, &vs_blob_errors))
  370. if vs_blob_errors != nil {
  371. log.error("Failed compiling shader:")
  372. log.error(strings.string_from_ptr((^u8)(vs_blob_errors->GetBufferPointer()), int(vs_blob_errors->GetBufferSize())))
  373. return
  374. }
  375. // VERTEX SHADER
  376. vertex_shader: ^d3d11.IVertexShader
  377. ch(s.device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nil, &vertex_shader))
  378. vs_ref: ^d3d11.IShaderReflection
  379. ch(d3d_compiler.Reflect(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), d3d11.ID3D11ShaderReflection_UUID, (^rawptr)(&vs_ref)))
  380. vs_desc: d3d11.SHADER_DESC
  381. ch(vs_ref->GetDesc(&vs_desc))
  382. {
  383. desc.inputs = make([]Shader_Input, vs_desc.InputParameters, desc_allocator)
  384. assert(len(layout_formats) == 0 || len(layout_formats) == len(desc.inputs))
  385. for in_idx in 0..<vs_desc.InputParameters {
  386. in_desc: d3d11.SIGNATURE_PARAMETER_DESC
  387. if ch(vs_ref->GetInputParameterDesc(in_idx, &in_desc)) < 0 {
  388. log.errorf("Invalid shader input: %v", in_idx)
  389. continue
  390. }
  391. type: Shader_Input_Type
  392. if in_desc.SemanticIndex > 0 {
  393. log.errorf("Matrix shader input types not yet implemented")
  394. continue
  395. }
  396. switch in_desc.ComponentType {
  397. case .UNKNOWN: log.errorf("Unknown component type")
  398. case .UINT32: log.errorf("Not implemented")
  399. case .SINT32: log.errorf("Not implemented")
  400. case .FLOAT32:
  401. switch in_desc.Mask {
  402. case 0: log.errorf("Invalid input mask"); continue
  403. case 1: type = .F32
  404. case 3: type = .Vec2
  405. case 7: type = .Vec3
  406. case 15: type = .Vec4
  407. }
  408. }
  409. name := strings.clone_from_cstring(in_desc.SemanticName, desc_allocator)
  410. format := len(layout_formats) > 0 ? layout_formats[in_idx] : get_shader_input_format(name, type)
  411. desc.inputs[in_idx] = {
  412. name = name,
  413. register = int(in_idx),
  414. format = format,
  415. type = type,
  416. }
  417. }
  418. }
  419. constant_descs := make([dynamic]Shader_Constant_Desc, desc_allocator)
  420. d3d_constants := make([dynamic]D3D11_Shader_Constant, s.allocator)
  421. d3d_constant_buffers := make([dynamic]D3D11_Shader_Constant_Buffer, s.allocator)
  422. reflect_shader_constants(
  423. vs_desc,
  424. vs_ref,
  425. &constant_descs,
  426. &d3d_constants,
  427. &d3d_constant_buffers,
  428. desc_allocator,
  429. .Vertex,
  430. )
  431. input_layout_desc := make([]d3d11.INPUT_ELEMENT_DESC, len(desc.inputs), frame_allocator)
  432. for idx in 0..<len(desc.inputs) {
  433. input := desc.inputs[idx]
  434. input_layout_desc[idx] = {
  435. SemanticName = frame_cstring(input.name),
  436. Format = dxgi_format_from_pixel_format(input.format),
  437. AlignedByteOffset = idx == 0 ? 0 : d3d11.APPEND_ALIGNED_ELEMENT,
  438. InputSlotClass = .VERTEX_DATA,
  439. }
  440. }
  441. input_layout: ^d3d11.IInputLayout
  442. ch(s.device->CreateInputLayout(raw_data(input_layout_desc), u32(len(input_layout_desc)), vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &input_layout))
  443. // PIXEL SHADER
  444. ps_blob: ^d3d11.IBlob
  445. ps_blob_errors: ^d3d11.IBlob
  446. ch(d3d_compiler.Compile(raw_data(ps_source), len(ps_source), nil, nil, nil, "ps_main", "ps_5_0", 0, 0, &ps_blob, &ps_blob_errors))
  447. if ps_blob_errors != nil {
  448. log.error("Failed compiling shader:")
  449. log.error(strings.string_from_ptr((^u8)(ps_blob_errors->GetBufferPointer()), int(ps_blob_errors->GetBufferSize())))
  450. return
  451. }
  452. pixel_shader: ^d3d11.IPixelShader
  453. ch(s.device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nil, &pixel_shader))
  454. ps_ref: ^d3d11.IShaderReflection
  455. ch(d3d_compiler.Reflect(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), d3d11.ID3D11ShaderReflection_UUID, (^rawptr)(&ps_ref)))
  456. ps_desc: d3d11.SHADER_DESC
  457. ch(ps_ref->GetDesc(&ps_desc))
  458. reflect_shader_constants(
  459. ps_desc,
  460. ps_ref,
  461. &constant_descs,
  462. &d3d_constants,
  463. &d3d_constant_buffers,
  464. desc_allocator,
  465. .Pixel,
  466. )
  467. // ----
  468. desc.constants = constant_descs[:]
  469. d3d_shd := D3D11_Shader {
  470. constants = d3d_constants[:],
  471. constant_buffers = d3d_constant_buffers[:],
  472. vertex_shader = vertex_shader,
  473. pixel_shader = pixel_shader,
  474. input_layout = input_layout,
  475. }
  476. h := hm.add(&s.shaders, d3d_shd)
  477. return h, desc
  478. }
  479. D3D11_Shader_Type :: enum {
  480. Vertex,
  481. Pixel,
  482. }
  483. reflect_shader_constants :: proc(
  484. d3d_desc: d3d11.SHADER_DESC,
  485. ref: ^d3d11.IShaderReflection,
  486. constant_descs: ^[dynamic]Shader_Constant_Desc,
  487. d3d_constants: ^[dynamic]D3D11_Shader_Constant,
  488. d3d_constant_buffers: ^[dynamic]D3D11_Shader_Constant_Buffer,
  489. desc_allocator: runtime.Allocator,
  490. type: D3D11_Shader_Type,
  491. ) {
  492. for cb_idx in 0..<d3d_desc.ConstantBuffers {
  493. cb_info := ref->GetConstantBufferByIndex(cb_idx)
  494. if cb_info == nil {
  495. continue
  496. }
  497. cb_desc: d3d11.SHADER_BUFFER_DESC
  498. cb_info->GetDesc(&cb_desc)
  499. if cb_desc.Size == 0 {
  500. continue
  501. }
  502. constant_buffer_desc := d3d11.BUFFER_DESC{
  503. ByteWidth = cb_desc.Size,
  504. Usage = .DYNAMIC,
  505. BindFlags = {.CONSTANT_BUFFER},
  506. CPUAccessFlags = {.WRITE},
  507. }
  508. buf := D3D11_Shader_Constant_Buffer {
  509. type = type,
  510. }
  511. ch(s.device->CreateBuffer(&constant_buffer_desc, nil, &buf.gpu_data))
  512. buf.size = int(cb_desc.Size)
  513. append(d3d_constant_buffers, buf)
  514. for var_idx in 0..<cb_desc.Variables {
  515. var_info := cb_info->GetVariableByIndex(var_idx)
  516. if var_info == nil {
  517. continue
  518. }
  519. var_desc: d3d11.SHADER_VARIABLE_DESC
  520. var_info->GetDesc(&var_desc)
  521. if var_desc.Name != "" {
  522. append(constant_descs, Shader_Constant_Desc {
  523. name = strings.clone_from_cstring(var_desc.Name, desc_allocator),
  524. size = int(var_desc.Size),
  525. })
  526. append(d3d_constants, D3D11_Shader_Constant {
  527. buffer_idx = cb_idx,
  528. offset = var_desc.StartOffset,
  529. })
  530. }
  531. }
  532. }
  533. }
  534. d3d11_destroy_shader :: proc(h: Shader_Handle) {
  535. shd := hm.get(&s.shaders, h)
  536. if shd == nil {
  537. log.errorf("Invalid shader: %v", h)
  538. return
  539. }
  540. shd.input_layout->Release()
  541. shd.vertex_shader->Release()
  542. shd.pixel_shader->Release()
  543. for c in shd.constant_buffers {
  544. if c.gpu_data != nil {
  545. c.gpu_data->Release()
  546. }
  547. }
  548. delete(shd.constant_buffers, s.allocator)
  549. hm.remove(&s.shaders, h)
  550. }
  551. // API END
  552. s: ^D3D11_State
  553. D3D11_Shader_Constant_Buffer :: struct {
  554. gpu_data: ^d3d11.IBuffer,
  555. size: int,
  556. type: D3D11_Shader_Type,
  557. }
  558. D3D11_Shader_Constant :: struct {
  559. buffer_idx: u32,
  560. offset: u32,
  561. }
  562. D3D11_Shader :: struct {
  563. handle: Shader_Handle,
  564. vertex_shader: ^d3d11.IVertexShader,
  565. pixel_shader: ^d3d11.IPixelShader,
  566. input_layout: ^d3d11.IInputLayout,
  567. constant_buffers: []D3D11_Shader_Constant_Buffer,
  568. constants: []D3D11_Shader_Constant,
  569. }
  570. D3D11_State :: struct {
  571. allocator: runtime.Allocator,
  572. window_handle: dxgi.HWND,
  573. width: int,
  574. height: int,
  575. dxgi_adapter: ^dxgi.IAdapter,
  576. swapchain: ^dxgi.ISwapChain1,
  577. framebuffer_view: ^d3d11.IRenderTargetView,
  578. depth_buffer_view: ^d3d11.IDepthStencilView,
  579. device_context: ^d3d11.IDeviceContext,
  580. depth_stencil_state: ^d3d11.IDepthStencilState,
  581. rasterizer_state: ^d3d11.IRasterizerState,
  582. device: ^d3d11.IDevice,
  583. depth_buffer: ^d3d11.ITexture2D,
  584. framebuffer: ^d3d11.ITexture2D,
  585. blend_state: ^d3d11.IBlendState,
  586. sampler_state: ^d3d11.ISamplerState,
  587. textures: hm.Handle_Map(D3D11_Texture, Texture_Handle, 1024*10),
  588. shaders: hm.Handle_Map(D3D11_Shader, Shader_Handle, 1024*10),
  589. info_queue: ^d3d11.IInfoQueue,
  590. vertex_buffer_gpu: ^d3d11.IBuffer,
  591. }
  592. create_swapchain :: proc(w, h: int) {
  593. swapchain_desc := dxgi.SWAP_CHAIN_DESC1 {
  594. Width = u32(w),
  595. Height = u32(h),
  596. Format = .B8G8R8A8_UNORM,
  597. SampleDesc = {
  598. Count = 1,
  599. },
  600. BufferUsage = {.RENDER_TARGET_OUTPUT},
  601. BufferCount = 2,
  602. Scaling = .STRETCH,
  603. SwapEffect = .DISCARD,
  604. }
  605. dxgi_factory: ^dxgi.IFactory2
  606. ch(s.dxgi_adapter->GetParent(dxgi.IFactory2_UUID, (^rawptr)(&dxgi_factory)))
  607. ch(dxgi_factory->CreateSwapChainForHwnd(s.device, s.window_handle, &swapchain_desc, nil, nil, &s.swapchain))
  608. ch(s.swapchain->GetBuffer(0, d3d11.ITexture2D_UUID, (^rawptr)(&s.framebuffer)))
  609. ch(s.device->CreateRenderTargetView(s.framebuffer, nil, &s.framebuffer_view))
  610. depth_buffer_desc: d3d11.TEXTURE2D_DESC
  611. s.framebuffer->GetDesc(&depth_buffer_desc)
  612. depth_buffer_desc.Format = .D24_UNORM_S8_UINT
  613. depth_buffer_desc.BindFlags = {.DEPTH_STENCIL}
  614. ch(s.device->CreateTexture2D(&depth_buffer_desc, nil, &s.depth_buffer))
  615. ch(s.device->CreateDepthStencilView(s.depth_buffer, nil, &s.depth_buffer_view))
  616. s.device_context->ClearDepthStencilView(s.depth_buffer_view, {.DEPTH}, 1, 0)
  617. }
  618. D3D11_Texture :: struct {
  619. handle: Texture_Handle,
  620. tex: ^d3d11.ITexture2D,
  621. view: ^d3d11.IShaderResourceView,
  622. format: Pixel_Format,
  623. }
  624. dxgi_format_from_pixel_format :: proc(f: Pixel_Format) -> dxgi.FORMAT {
  625. switch f {
  626. case .Unknown: return .UNKNOWN
  627. case .RGBA_32_Float: return .R32G32B32A32_FLOAT
  628. case .RGB_32_Float: return .R32G32B32_FLOAT
  629. case .RG_32_Float: return .R32G32_FLOAT
  630. case .R_32_Float: return .R32_FLOAT
  631. case .RGBA_8_Norm: return .R8G8B8A8_UNORM
  632. case .RG_8_Norm: return .R8G8_UNORM
  633. case .R_8_Norm: return .R8_UNORM
  634. case .R_8_UInt: return .R8_UINT
  635. }
  636. log.error("Unknown format")
  637. return .UNKNOWN
  638. }
  639. // CHeck win errors and print message log if there is any error
  640. ch :: proc(hr: dxgi.HRESULT, loc := #caller_location) -> dxgi.HRESULT {
  641. if hr >= 0 {
  642. return hr
  643. }
  644. log.errorf("d3d11 error: %0x", u32(hr), location = loc)
  645. log_messages(loc)
  646. return hr
  647. }
  648. log_messages :: proc(loc := #caller_location) {
  649. iq := s.info_queue
  650. if iq == nil {
  651. return
  652. }
  653. n := iq->GetNumStoredMessages()
  654. longest_msg: d3d11.SIZE_T
  655. for i in 0..=n {
  656. msglen: d3d11.SIZE_T
  657. iq->GetMessage(i, nil, &msglen)
  658. if msglen > longest_msg {
  659. longest_msg = msglen
  660. }
  661. }
  662. if longest_msg > 0 {
  663. msg_raw_ptr, _ := (mem.alloc(int(longest_msg), allocator = frame_allocator))
  664. for i in 0..=n {
  665. msglen: d3d11.SIZE_T
  666. iq->GetMessage(i, nil, &msglen)
  667. if msglen > 0 {
  668. msg := (^d3d11.MESSAGE)(msg_raw_ptr)
  669. iq->GetMessage(i, msg, &msglen)
  670. log.error(msg.pDescription, location = loc)
  671. }
  672. }
  673. }
  674. iq->ClearStoredMessages()
  675. }
  676. DEFAULT_SHADER_SOURCE :: #load("shader.hlsl")
  677. d3d11_default_shader_vertex_source :: proc() -> string {
  678. return string(DEFAULT_SHADER_SOURCE)
  679. }
  680. d3d11_default_shader_fragment_source :: proc() -> string {
  681. return string(DEFAULT_SHADER_SOURCE)
  682. }