render_backend_d3d11.odin 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  1. #+build windows
  2. #+vet explicit-allocators
  3. #+private file
  4. package karl2d
  5. @(private="package")
  6. RENDER_BACKEND_INTERFACE_D3D11 :: Render_Backend_Interface {
  7. state_size = d3d11_state_size,
  8. init = d3d11_init,
  9. shutdown = d3d11_shutdown,
  10. clear = d3d11_clear,
  11. present = d3d11_present,
  12. draw = d3d11_draw,
  13. resize_swapchain = d3d11_resize_swapchain,
  14. get_swapchain_width = d3d11_get_swapchain_width,
  15. get_swapchain_height = d3d11_get_swapchain_height,
  16. flip_z = d3d11_flip_z,
  17. set_internal_state = d3d11_set_internal_state,
  18. create_texture = d3d11_create_texture,
  19. load_texture = d3d11_load_texture,
  20. update_texture = d3d11_update_texture,
  21. destroy_texture = d3d11_destroy_texture,
  22. create_render_texture = d3d11_create_render_texture,
  23. destroy_render_target = d3d11_destroy_render_target,
  24. set_texture_filter = d3d11_set_texture_filter,
  25. load_shader = d3d11_load_shader,
  26. destroy_shader = d3d11_destroy_shader,
  27. default_shader_vertex_source = d3d11_default_shader_vertex_source,
  28. default_shader_fragment_source = d3d11_default_shader_fragment_source,
  29. }
  30. import d3d11 "vendor:directx/d3d11"
  31. import dxgi "vendor:directx/dxgi"
  32. import "vendor:directx/d3d_compiler"
  33. import "core:strings"
  34. import "core:log"
  35. import "core:slice"
  36. import "core:mem"
  37. import hm "handle_map"
  38. import "base:runtime"
  39. d3d11_state_size :: proc() -> int {
  40. return size_of(D3D11_State)
  41. }
  42. d3d11_init :: proc(state: rawptr, window_handle: Window_Handle, swapchain_width, swapchain_height: int, allocator := context.allocator) {
  43. s = (^D3D11_State)(state)
  44. s.allocator = allocator
  45. s.window_handle = dxgi.HWND(window_handle)
  46. s.width = swapchain_width
  47. s.height = swapchain_height
  48. feature_levels := [?]d3d11.FEATURE_LEVEL{
  49. ._11_1,
  50. ._11_0,
  51. }
  52. base_device: ^d3d11.IDevice
  53. base_device_context: ^d3d11.IDeviceContext
  54. base_device_flags := d3d11.CREATE_DEVICE_FLAGS {
  55. .BGRA_SUPPORT,
  56. }
  57. when ODIN_DEBUG {
  58. device_flags := base_device_flags + { .DEBUG }
  59. device_err := ch(d3d11.CreateDevice(
  60. nil,
  61. .HARDWARE,
  62. nil,
  63. device_flags,
  64. &feature_levels[0], len(feature_levels),
  65. d3d11.SDK_VERSION, &base_device, nil, &base_device_context))
  66. if u32(device_err) == 0x887a002d {
  67. 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).")
  68. ch(d3d11.CreateDevice(
  69. nil,
  70. .HARDWARE,
  71. nil,
  72. base_device_flags,
  73. &feature_levels[0], len(feature_levels),
  74. d3d11.SDK_VERSION, &base_device, nil, &base_device_context))
  75. } else {
  76. ch(base_device->QueryInterface(d3d11.IInfoQueue_UUID, (^rawptr)(&s.info_queue)))
  77. }
  78. } else {
  79. ch(d3d11.CreateDevice(
  80. nil,
  81. .HARDWARE,
  82. nil,
  83. base_device_flags,
  84. &feature_levels[0], len(feature_levels),
  85. d3d11.SDK_VERSION, &base_device, nil, &base_device_context))
  86. }
  87. ch(base_device->QueryInterface(d3d11.IDevice_UUID, (^rawptr)(&s.device)))
  88. ch(base_device_context->QueryInterface(d3d11.IDeviceContext_UUID, (^rawptr)(&s.device_context)))
  89. dxgi_device: ^dxgi.IDevice
  90. ch(s.device->QueryInterface(dxgi.IDevice_UUID, (^rawptr)(&dxgi_device)))
  91. base_device->Release()
  92. base_device_context->Release()
  93. ch(dxgi_device->GetAdapter(&s.dxgi_adapter))
  94. create_swapchain(swapchain_width, swapchain_height)
  95. rasterizer_desc := d3d11.RASTERIZER_DESC{
  96. FillMode = .SOLID,
  97. CullMode = .BACK,
  98. ScissorEnable = true,
  99. }
  100. ch(s.device->CreateRasterizerState(&rasterizer_desc, &s.rasterizer_state))
  101. depth_stencil_desc := d3d11.DEPTH_STENCIL_DESC{
  102. DepthEnable = true,
  103. DepthWriteMask = .ALL,
  104. DepthFunc = .LESS,
  105. }
  106. ch(s.device->CreateDepthStencilState(&depth_stencil_desc, &s.depth_stencil_state))
  107. vertex_buffer_desc := d3d11.BUFFER_DESC{
  108. ByteWidth = VERTEX_BUFFER_MAX,
  109. Usage = .DYNAMIC,
  110. BindFlags = {.VERTEX_BUFFER},
  111. CPUAccessFlags = {.WRITE},
  112. }
  113. ch(s.device->CreateBuffer(&vertex_buffer_desc, nil, &s.vertex_buffer_gpu))
  114. blend_alpha_desc := d3d11.BLEND_DESC {
  115. RenderTarget = {
  116. 0 = {
  117. BlendEnable = true,
  118. SrcBlend = .SRC_ALPHA,
  119. DestBlend = .INV_SRC_ALPHA,
  120. BlendOp = .ADD,
  121. SrcBlendAlpha = .SRC_ALPHA,
  122. DestBlendAlpha = .INV_SRC_ALPHA,
  123. BlendOpAlpha = .ADD,
  124. RenderTargetWriteMask = u8(d3d11.COLOR_WRITE_ENABLE_ALL),
  125. },
  126. },
  127. }
  128. ch(s.device->CreateBlendState(&blend_alpha_desc, &s.blend_state_alpha))
  129. blend_premultiplied_alpha_desc := d3d11.BLEND_DESC {
  130. RenderTarget = {
  131. 0 = {
  132. BlendEnable = true,
  133. SrcBlend = .ONE,
  134. DestBlend = .INV_SRC_ALPHA,
  135. BlendOp = .ADD,
  136. SrcBlendAlpha = .ONE,
  137. DestBlendAlpha = .INV_SRC_ALPHA,
  138. BlendOpAlpha = .ADD,
  139. RenderTargetWriteMask = u8(d3d11.COLOR_WRITE_ENABLE_ALL),
  140. },
  141. },
  142. }
  143. ch(s.device->CreateBlendState(&blend_premultiplied_alpha_desc, &s.blend_state_premultiplied_alpha))
  144. }
  145. d3d11_shutdown :: proc() {
  146. s.framebuffer_view->Release()
  147. s.depth_buffer_view->Release()
  148. s.depth_buffer->Release()
  149. s.framebuffer->Release()
  150. s.device_context->Release()
  151. s.vertex_buffer_gpu->Release()
  152. s.depth_stencil_state->Release()
  153. s.rasterizer_state->Release()
  154. s.swapchain->Release()
  155. s.blend_state_alpha->Release()
  156. s.blend_state_premultiplied_alpha->Release()
  157. s.dxgi_adapter->Release()
  158. when ODIN_DEBUG {
  159. debug: ^d3d11.IDebug
  160. if ch(s.device->QueryInterface(d3d11.IDebug_UUID, (^rawptr)(&debug))) >= 0 {
  161. ch(debug->ReportLiveDeviceObjects({.DETAIL, .IGNORE_INTERNAL}))
  162. log_messages()
  163. }
  164. debug->Release()
  165. }
  166. s.device->Release()
  167. s.info_queue->Release()
  168. }
  169. d3d11_clear :: proc(render_target: Render_Target_Handle, color: Color) {
  170. c := f32_color_from_color(color)
  171. if rt := hm.get(&s.render_targets, render_target); rt != nil {
  172. s.device_context->ClearRenderTargetView(rt.render_target_view, &c)
  173. s.device_context->ClearDepthStencilView(rt.depth_stencil_texture_view, {.DEPTH}, 1, 0)
  174. } else {
  175. s.device_context->ClearRenderTargetView(s.framebuffer_view, &c)
  176. s.device_context->ClearDepthStencilView(s.depth_buffer_view, {.DEPTH}, 1, 0)
  177. }
  178. }
  179. d3d11_present :: proc() {
  180. ch(s.swapchain->Present(1, {}))
  181. }
  182. d3d11_draw :: proc(
  183. shd: Shader,
  184. render_target: Render_Target_Handle,
  185. bound_textures: []Texture_Handle,
  186. scissor: Maybe(Rect),
  187. blend_mode: Blend_Mode,
  188. vertex_buffer: []u8,
  189. ) {
  190. if len(vertex_buffer) == 0 {
  191. return
  192. }
  193. d3d_shd := hm.get(&s.shaders, shd.handle)
  194. if d3d_shd == nil {
  195. log.error("Trying to draw with invalid shader %v", shd.handle)
  196. return
  197. }
  198. dc := s.device_context
  199. vb_data: d3d11.MAPPED_SUBRESOURCE
  200. ch(dc->Map(s.vertex_buffer_gpu, 0, .WRITE_DISCARD, {}, &vb_data))
  201. {
  202. gpu_map := slice.from_ptr((^u8)(vb_data.pData), VERTEX_BUFFER_MAX)
  203. copy(
  204. gpu_map,
  205. vertex_buffer,
  206. )
  207. }
  208. dc->Unmap(s.vertex_buffer_gpu, 0)
  209. dc->IASetPrimitiveTopology(.TRIANGLELIST)
  210. dc->IASetInputLayout(d3d_shd.input_layout)
  211. vertex_buffer_offset: u32
  212. vertex_buffer_stride := u32(shd.vertex_size)
  213. dc->IASetVertexBuffers(0, 1, &s.vertex_buffer_gpu, &vertex_buffer_stride, &vertex_buffer_offset)
  214. dc->VSSetShader(d3d_shd.vertex_shader, nil, 0)
  215. assert(len(shd.constants) == len(d3d_shd.constants))
  216. maps := make([]rawptr, len(d3d_shd.constant_buffers), frame_allocator)
  217. cpu_data := shd.constants_data
  218. for cidx in 0..<len(shd.constants) {
  219. cpu_loc := shd.constants[cidx]
  220. gpu_loc := d3d_shd.constants[cidx]//cpu_loc.gpu_constant_idx]
  221. gpu_buffer_info := d3d_shd.constant_buffers[gpu_loc.buffer_idx]
  222. gpu_data := gpu_buffer_info.gpu_data
  223. if gpu_data == nil {
  224. continue
  225. }
  226. if maps[gpu_loc.buffer_idx] == nil {
  227. // We do this little dance with the 'maps' array so we only have to map the memory once.
  228. // There can be multiple constants within a single constant buffer. So mapping and
  229. // unmapping for each one is slow.
  230. map_data: d3d11.MAPPED_SUBRESOURCE
  231. ch(dc->Map(gpu_data, 0, .WRITE_DISCARD, {}, &map_data))
  232. maps[gpu_loc.buffer_idx] = map_data.pData
  233. }
  234. data_slice := slice.bytes_from_ptr(maps[gpu_loc.buffer_idx], gpu_buffer_info.size)
  235. dst := data_slice[gpu_loc.offset:gpu_loc.offset+u32(cpu_loc.size)]
  236. src := cpu_data[cpu_loc.offset:cpu_loc.offset+cpu_loc.size]
  237. copy(dst, src)
  238. }
  239. for &cb, cb_idx in d3d_shd.constant_buffers {
  240. if .Vertex in cb.bound_shaders {
  241. dc->VSSetConstantBuffers(cb.bind_point, 1, &cb.gpu_data)
  242. }
  243. if .Pixel in cb.bound_shaders {
  244. dc->PSSetConstantBuffers(cb.bind_point, 1, &cb.gpu_data)
  245. }
  246. if maps[cb_idx] != nil {
  247. dc->Unmap(cb.gpu_data, 0)
  248. maps[cb_idx] = nil
  249. }
  250. }
  251. viewport := d3d11.VIEWPORT{
  252. 0, 0,
  253. f32(s.width), f32(s.height),
  254. 0, 1,
  255. }
  256. dc->RSSetViewports(1, &viewport)
  257. dc->RSSetState(s.rasterizer_state)
  258. scissor_rect := d3d11.RECT {
  259. right = i32(s.width),
  260. bottom = i32(s.height),
  261. }
  262. if sciss, sciss_ok := scissor.?; sciss_ok {
  263. scissor_rect = d3d11.RECT {
  264. left = i32(sciss.x),
  265. top = i32(sciss.y),
  266. right = i32(sciss.x + sciss.w),
  267. bottom = i32(sciss.y + sciss.h),
  268. }
  269. }
  270. dc->RSSetScissorRects(1, &scissor_rect)
  271. dc->PSSetShader(d3d_shd.pixel_shader, nil, 0)
  272. if len(bound_textures) == len(d3d_shd.texture_bindings) {
  273. for t, t_idx in bound_textures {
  274. d3d_t := d3d_shd.texture_bindings[t_idx]
  275. if t := hm.get(&s.textures, t); t != nil {
  276. dc->PSSetShaderResources(d3d_t.bind_point, 1, &t.view)
  277. dc->PSSetSamplers(d3d_t.sampler_bind_point, 1, &t.sampler)
  278. }
  279. }
  280. }
  281. if rt := hm.get(&s.render_targets, render_target); rt != nil {
  282. dc->OMSetRenderTargets(1, &rt.render_target_view, rt.depth_stencil_texture_view)
  283. } else {
  284. dc->OMSetRenderTargets(1, &s.framebuffer_view, s.depth_buffer_view)
  285. }
  286. dc->OMSetDepthStencilState(s.depth_stencil_state, 0)
  287. switch blend_mode {
  288. case .Alpha:
  289. dc->OMSetBlendState(s.blend_state_alpha, nil, ~u32(0))
  290. case .Premultiplied_Alpha:
  291. dc->OMSetBlendState(s.blend_state_premultiplied_alpha, nil, ~u32(0))
  292. }
  293. dc->Draw(u32(len(vertex_buffer)/shd.vertex_size), 0)
  294. dc->OMSetRenderTargets(0, nil, nil)
  295. log_messages()
  296. }
  297. d3d11_resize_swapchain :: proc(w, h: int) {
  298. s.depth_buffer->Release()
  299. s.depth_buffer_view->Release()
  300. s.framebuffer->Release()
  301. s.framebuffer_view->Release()
  302. s.swapchain->Release()
  303. s.width = w
  304. s.height = h
  305. create_swapchain(w, h)
  306. }
  307. d3d11_get_swapchain_width :: proc() -> int {
  308. return s.width
  309. }
  310. d3d11_get_swapchain_height :: proc() -> int {
  311. return s.height
  312. }
  313. d3d11_flip_z :: proc() -> bool {
  314. return true
  315. }
  316. d3d11_set_internal_state :: proc(state: rawptr) {
  317. s = (^D3D11_State)(state)
  318. }
  319. create_texture :: proc(
  320. width: int,
  321. height: int,
  322. format: Pixel_Format,
  323. data: rawptr,
  324. ) -> (
  325. Texture_Handle,
  326. ) {
  327. texture_desc := d3d11.TEXTURE2D_DESC{
  328. Width = u32(width),
  329. Height = u32(height),
  330. MipLevels = 1,
  331. ArraySize = 1,
  332. Format = dxgi_format_from_pixel_format(format),
  333. SampleDesc = {Count = 1},
  334. Usage = .DEFAULT,
  335. BindFlags = {.SHADER_RESOURCE},
  336. }
  337. texture: ^d3d11.ITexture2D
  338. if data != nil {
  339. texture_data := d3d11.SUBRESOURCE_DATA{
  340. pSysMem = data,
  341. SysMemPitch = u32(width * pixel_format_size(format)),
  342. }
  343. s.device->CreateTexture2D(&texture_desc, &texture_data, &texture)
  344. } else {
  345. s.device->CreateTexture2D(&texture_desc, nil, &texture)
  346. }
  347. texture_view: ^d3d11.IShaderResourceView
  348. s.device->CreateShaderResourceView(texture, nil, &texture_view)
  349. tex := D3D11_Texture {
  350. tex = texture,
  351. format = format,
  352. view = texture_view,
  353. sampler = create_sampler(.MIN_MAG_MIP_POINT),
  354. }
  355. return hm.add(&s.textures, tex)
  356. }
  357. d3d11_create_texture :: proc(width: int, height: int, format: Pixel_Format) -> Texture_Handle {
  358. return create_texture(width, height, format, nil)
  359. }
  360. d3d11_create_render_texture :: proc(width: int, height: int) -> (Texture_Handle, Render_Target_Handle) {
  361. texture_desc := d3d11.TEXTURE2D_DESC{
  362. Width = u32(width),
  363. Height = u32(height),
  364. MipLevels = 1,
  365. ArraySize = 1,
  366. Format = dxgi_format_from_pixel_format(.RGBA_32_Float),
  367. SampleDesc = {Count = 1},
  368. Usage = .DEFAULT,
  369. BindFlags = {.SHADER_RESOURCE, .RENDER_TARGET},
  370. }
  371. texture: ^d3d11.ITexture2D
  372. ch(s.device->CreateTexture2D(&texture_desc, nil, &texture))
  373. texture_view: ^d3d11.IShaderResourceView
  374. ch(s.device->CreateShaderResourceView(texture, nil, &texture_view))
  375. depth_stencil_desc := d3d11.TEXTURE2D_DESC{
  376. Width = u32(width),
  377. Height = u32(height),
  378. MipLevels = 1,
  379. ArraySize = 1,
  380. Format = .D24_UNORM_S8_UINT,
  381. SampleDesc = {Count = 1},
  382. Usage = .DEFAULT,
  383. BindFlags = {.DEPTH_STENCIL},
  384. }
  385. depth_stencil_texture: ^d3d11.ITexture2D
  386. ch(ch(s.device->CreateTexture2D(&depth_stencil_desc, nil, &depth_stencil_texture)))
  387. depth_stencil_texture_view: ^d3d11.IDepthStencilView
  388. ch(s.device->CreateDepthStencilView(depth_stencil_texture, nil, &depth_stencil_texture_view))
  389. render_target_view_desc := d3d11.RENDER_TARGET_VIEW_DESC {
  390. Format = texture_desc.Format,
  391. ViewDimension = .TEXTURE2D,
  392. }
  393. render_target_view: ^d3d11.IRenderTargetView
  394. ch(s.device->CreateRenderTargetView(texture, &render_target_view_desc, &render_target_view))
  395. d3d11_texture := D3D11_Texture {
  396. tex = texture,
  397. view = texture_view,
  398. format = .RGBA_32_Float,
  399. sampler = create_sampler(.MIN_MAG_MIP_POINT),
  400. }
  401. d3d11_render_target := D3D11_Render_Target {
  402. depth_stencil_texture = depth_stencil_texture,
  403. depth_stencil_texture_view = depth_stencil_texture_view,
  404. render_target_view = render_target_view,
  405. }
  406. return hm.add(&s.textures, d3d11_texture), hm.add(&s.render_targets, d3d11_render_target)
  407. }
  408. d3d11_destroy_render_target :: proc(render_target: Render_Target_Handle) {
  409. if rt := hm.get(&s.render_targets, render_target); rt != nil {
  410. rt.depth_stencil_texture->Release()
  411. rt.depth_stencil_texture_view->Release()
  412. rt.render_target_view->Release()
  413. }
  414. hm.remove(&s.render_targets, render_target)
  415. }
  416. d3d11_load_texture :: proc(data: []u8, width: int, height: int, format: Pixel_Format) -> Texture_Handle {
  417. return create_texture(width, height, format, raw_data(data))
  418. }
  419. d3d11_update_texture :: proc(th: Texture_Handle, data: []u8, rect: Rect) -> bool {
  420. tex := hm.get(&s.textures, th)
  421. if tex == nil || tex.tex == nil {
  422. log.errorf("Trying to update texture %v with new data, but it is invalid.", th)
  423. return false
  424. }
  425. box := d3d11.BOX {
  426. left = u32(rect.x),
  427. top = u32(rect.y),
  428. bottom = u32(rect.y + rect.h),
  429. right = u32(rect.x + rect.w),
  430. back = 1,
  431. front = 0,
  432. }
  433. row_pitch := pixel_format_size(tex.format) * int(rect.w)
  434. s.device_context->UpdateSubresource(tex.tex, 0, &box, raw_data(data), u32(row_pitch), 0)
  435. return true
  436. }
  437. d3d11_destroy_texture :: proc(th: Texture_Handle) {
  438. if t := hm.get(&s.textures, th); t != nil {
  439. t.tex->Release()
  440. t.view->Release()
  441. if t.sampler != nil {
  442. t.sampler->Release()
  443. }
  444. }
  445. hm.remove(&s.textures, th)
  446. }
  447. d3d11_set_texture_filter :: proc(
  448. th: Texture_Handle,
  449. scale_down_filter: Texture_Filter,
  450. scale_up_filter: Texture_Filter,
  451. mip_filter: Texture_Filter,
  452. ) {
  453. t := hm.get(&s.textures, th)
  454. if t == nil {
  455. log.error("Trying to set texture filter for invalid texture %v", th)
  456. return
  457. }
  458. d := scale_down_filter
  459. u := scale_up_filter
  460. m := mip_filter
  461. f: d3d11.FILTER
  462. if d == .Point && u == .Point && m == .Point {
  463. f = .MIN_MAG_MIP_POINT
  464. } else if d == .Linear && u == .Linear && m == .Linear {
  465. f = .MIN_MAG_MIP_LINEAR
  466. } else if d == .Point && u == .Point && m == .Linear {
  467. f = .MIN_MAG_POINT_MIP_LINEAR
  468. } else if d == .Point && u == .Linear && m == .Linear {
  469. f = .MIN_POINT_MAG_MIP_LINEAR
  470. } else if d == .Linear && u == .Linear && m == .Linear {
  471. f = .MIN_MAG_MIP_LINEAR
  472. } else if d == .Linear && u == .Linear && m == .Point {
  473. f = .MIN_MAG_LINEAR_MIP_POINT
  474. } else if d == .Linear && u == .Point && m == .Point {
  475. f = .MIN_LINEAR_MAG_MIP_POINT
  476. } else if d == .Linear && u == .Point && m == .Linear {
  477. f = .MIN_LINEAR_MAG_POINT_MIP_LINEAR
  478. } else if d == .Point && u == .Linear && m == .Point {
  479. f = .MIN_POINT_MAG_LINEAR_MIP_POINT
  480. }
  481. if t.sampler != nil {
  482. t.sampler->Release()
  483. }
  484. t.sampler = create_sampler(f)
  485. }
  486. create_sampler :: proc(filter: d3d11.FILTER) -> ^d3d11.ISamplerState {
  487. sampler_desc := d3d11.SAMPLER_DESC{
  488. Filter = filter,
  489. AddressU = .WRAP,
  490. AddressV = .WRAP,
  491. AddressW = .WRAP,
  492. ComparisonFunc = .NEVER,
  493. }
  494. smp: ^d3d11.ISamplerState
  495. ch(s.device->CreateSamplerState(&sampler_desc, &smp))
  496. return smp
  497. }
  498. d3d11_load_shader :: proc(
  499. vs_source: string,
  500. ps_source: string,
  501. desc_allocator := frame_allocator,
  502. layout_formats: []Pixel_Format = {},
  503. ) -> (
  504. handle: Shader_Handle,
  505. desc: Shader_Desc,
  506. ) {
  507. vs_blob: ^d3d11.IBlob
  508. vs_blob_errors: ^d3d11.IBlob
  509. 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))
  510. if vs_blob_errors != nil {
  511. log.error("Failed compiling shader:")
  512. log.error(strings.string_from_ptr((^u8)(vs_blob_errors->GetBufferPointer()), int(vs_blob_errors->GetBufferSize())))
  513. return
  514. }
  515. // VERTEX SHADER
  516. vertex_shader: ^d3d11.IVertexShader
  517. ch(s.device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nil, &vertex_shader))
  518. vs_ref: ^d3d11.IShaderReflection
  519. ch(d3d_compiler.Reflect(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), d3d11.ID3D11ShaderReflection_UUID, (^rawptr)(&vs_ref)))
  520. vs_desc: d3d11.SHADER_DESC
  521. ch(vs_ref->GetDesc(&vs_desc))
  522. {
  523. desc.inputs = make([]Shader_Input, vs_desc.InputParameters, desc_allocator)
  524. assert(len(layout_formats) == 0 || len(layout_formats) == len(desc.inputs))
  525. for in_idx in 0..<vs_desc.InputParameters {
  526. in_desc: d3d11.SIGNATURE_PARAMETER_DESC
  527. if ch(vs_ref->GetInputParameterDesc(in_idx, &in_desc)) < 0 {
  528. log.errorf("Invalid shader input: %v", in_idx)
  529. continue
  530. }
  531. type: Shader_Input_Type
  532. if in_desc.SemanticIndex > 0 {
  533. log.errorf("Matrix shader input types not yet implemented")
  534. continue
  535. }
  536. switch in_desc.ComponentType {
  537. case .UNKNOWN: log.errorf("Unknown component type")
  538. case .UINT32: log.errorf("Not implemented")
  539. case .SINT32: log.errorf("Not implemented")
  540. case .FLOAT32:
  541. switch in_desc.Mask {
  542. case 0: log.errorf("Invalid input mask"); continue
  543. case 1: type = .F32
  544. case 3: type = .Vec2
  545. case 7: type = .Vec3
  546. case 15: type = .Vec4
  547. }
  548. }
  549. name := strings.clone_from_cstring(in_desc.SemanticName, desc_allocator)
  550. format := len(layout_formats) > 0 ? layout_formats[in_idx] : get_shader_input_format(name, type)
  551. desc.inputs[in_idx] = {
  552. name = name,
  553. register = int(in_idx),
  554. format = format,
  555. type = type,
  556. }
  557. }
  558. }
  559. constant_descs := make([dynamic]Shader_Constant_Desc, desc_allocator)
  560. d3d_constants := make([dynamic]D3D11_Shader_Constant, s.allocator)
  561. d3d_constant_buffers := make([dynamic]D3D11_Shader_Constant_Buffer, s.allocator)
  562. d3d_texture_bindings := make([dynamic]D3D11_Texture_Binding, s.allocator)
  563. texture_bindpoint_descs := make([dynamic]Shader_Texture_Bindpoint_Desc, desc_allocator)
  564. reflect_shader_constants(
  565. vs_desc,
  566. vs_ref,
  567. &constant_descs,
  568. &d3d_constants,
  569. &d3d_constant_buffers,
  570. &d3d_texture_bindings,
  571. &texture_bindpoint_descs,
  572. desc_allocator,
  573. .Vertex,
  574. )
  575. input_layout_desc := make([]d3d11.INPUT_ELEMENT_DESC, len(desc.inputs), frame_allocator)
  576. for idx in 0..<len(desc.inputs) {
  577. input := desc.inputs[idx]
  578. input_layout_desc[idx] = {
  579. SemanticName = frame_cstring(input.name),
  580. Format = dxgi_format_from_pixel_format(input.format),
  581. AlignedByteOffset = idx == 0 ? 0 : d3d11.APPEND_ALIGNED_ELEMENT,
  582. InputSlotClass = .VERTEX_DATA,
  583. }
  584. }
  585. input_layout: ^d3d11.IInputLayout
  586. ch(s.device->CreateInputLayout(raw_data(input_layout_desc), u32(len(input_layout_desc)), vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &input_layout))
  587. // PIXEL SHADER
  588. ps_blob: ^d3d11.IBlob
  589. ps_blob_errors: ^d3d11.IBlob
  590. 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))
  591. if ps_blob_errors != nil {
  592. log.error("Failed compiling shader:")
  593. log.error(strings.string_from_ptr((^u8)(ps_blob_errors->GetBufferPointer()), int(ps_blob_errors->GetBufferSize())))
  594. return
  595. }
  596. pixel_shader: ^d3d11.IPixelShader
  597. ch(s.device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nil, &pixel_shader))
  598. ps_ref: ^d3d11.IShaderReflection
  599. ch(d3d_compiler.Reflect(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), d3d11.ID3D11ShaderReflection_UUID, (^rawptr)(&ps_ref)))
  600. ps_desc: d3d11.SHADER_DESC
  601. ch(ps_ref->GetDesc(&ps_desc))
  602. reflect_shader_constants(
  603. ps_desc,
  604. ps_ref,
  605. &constant_descs,
  606. &d3d_constants,
  607. &d3d_constant_buffers,
  608. &d3d_texture_bindings,
  609. &texture_bindpoint_descs,
  610. desc_allocator,
  611. .Pixel,
  612. )
  613. // Done with vertex and pixel shader. Just combine all the state.
  614. desc.constants = constant_descs[:]
  615. desc.texture_bindpoints = texture_bindpoint_descs[:]
  616. d3d_shd := D3D11_Shader {
  617. constants = d3d_constants[:],
  618. constant_buffers = d3d_constant_buffers[:],
  619. vertex_shader = vertex_shader,
  620. pixel_shader = pixel_shader,
  621. input_layout = input_layout,
  622. texture_bindings = d3d_texture_bindings[:],
  623. }
  624. h := hm.add(&s.shaders, d3d_shd)
  625. return h, desc
  626. }
  627. D3D11_Shader_Type :: enum {
  628. Vertex,
  629. Pixel,
  630. }
  631. reflect_shader_constants :: proc(
  632. d3d_desc: d3d11.SHADER_DESC,
  633. ref: ^d3d11.IShaderReflection,
  634. constant_descs: ^[dynamic]Shader_Constant_Desc,
  635. d3d_constants: ^[dynamic]D3D11_Shader_Constant,
  636. d3d_constant_buffers: ^[dynamic]D3D11_Shader_Constant_Buffer,
  637. d3d_texture_bindings: ^[dynamic]D3D11_Texture_Binding,
  638. texture_bindpoint_descs: ^[dynamic]Shader_Texture_Bindpoint_Desc,
  639. desc_allocator: runtime.Allocator,
  640. shader_type: D3D11_Shader_Type,
  641. ) {
  642. found_sampler_bindpoints := make([dynamic]u32, frame_allocator)
  643. for br_idx in 0..<d3d_desc.BoundResources {
  644. bind_desc: d3d11.SHADER_INPUT_BIND_DESC
  645. ref->GetResourceBindingDesc(br_idx, &bind_desc)
  646. #partial switch bind_desc.Type {
  647. case .SAMPLER:
  648. append(&found_sampler_bindpoints, bind_desc.BindPoint)
  649. case .TEXTURE:
  650. append(d3d_texture_bindings, D3D11_Texture_Binding {
  651. bind_point = bind_desc.BindPoint,
  652. })
  653. append(texture_bindpoint_descs, Shader_Texture_Bindpoint_Desc {
  654. name = strings.clone_from_cstring(bind_desc.Name, desc_allocator),
  655. })
  656. case .CBUFFER:
  657. cb_info := ref->GetConstantBufferByName(bind_desc.Name)
  658. if cb_info == nil {
  659. continue
  660. }
  661. cb_desc: d3d11.SHADER_BUFFER_DESC
  662. cb_info->GetDesc(&cb_desc)
  663. if cb_desc.Size == 0 {
  664. continue
  665. }
  666. constant_buffer_desc := d3d11.BUFFER_DESC{
  667. ByteWidth = cb_desc.Size,
  668. Usage = .DYNAMIC,
  669. BindFlags = {.CONSTANT_BUFFER},
  670. CPUAccessFlags = {.WRITE},
  671. }
  672. buffer_idx := -1
  673. for &existing, existing_idx in d3d_constant_buffers {
  674. if existing.bind_point == bind_desc.BindPoint {
  675. existing.bound_shaders += {shader_type}
  676. buffer_idx = existing_idx
  677. break
  678. }
  679. }
  680. if buffer_idx == -1 {
  681. buffer_idx = len(d3d_constant_buffers)
  682. buf := D3D11_Shader_Constant_Buffer {
  683. bound_shaders = {shader_type},
  684. }
  685. ch(s.device->CreateBuffer(&constant_buffer_desc, nil, &buf.gpu_data))
  686. buf.size = int(cb_desc.Size)
  687. buf.bind_point = bind_desc.BindPoint
  688. append(d3d_constant_buffers, buf)
  689. }
  690. for var_idx in 0..<cb_desc.Variables {
  691. var_info := cb_info->GetVariableByIndex(var_idx)
  692. if var_info == nil {
  693. continue
  694. }
  695. var_desc: d3d11.SHADER_VARIABLE_DESC
  696. var_info->GetDesc(&var_desc)
  697. if var_desc.Name != "" {
  698. append(constant_descs, Shader_Constant_Desc {
  699. name = strings.clone_from_cstring(var_desc.Name, desc_allocator),
  700. size = int(var_desc.Size),
  701. })
  702. append(d3d_constants, D3D11_Shader_Constant {
  703. buffer_idx = u32(buffer_idx),
  704. offset = var_desc.StartOffset,
  705. })
  706. }
  707. }
  708. case:
  709. log.errorf("Type is %v", bind_desc.Type)
  710. }
  711. }
  712. // Make sure each texture has a sampler. In GL samplers are associated with textures. In D3D11
  713. // several textures can use a single sampler. We don't want this as we want to be able to
  714. // configure filters etc on a per-texture level. Since two textures can arrive at a draw call
  715. // with different filters set, if they use the same sampler, then it will be impossible to set
  716. // that filtering up.
  717. for t, t_idx in d3d_texture_bindings {
  718. found := false
  719. for sampler_bindpoint in found_sampler_bindpoints {
  720. if t.bind_point == sampler_bindpoint {
  721. found = true
  722. break
  723. }
  724. }
  725. if !found {
  726. log.errorf(
  727. "Texture %v at bindpoint %v does not have a dedicated sampler at " +
  728. "the sampler register with the same bindpoint number. This is required to " +
  729. "in order to make D3D11 behave the same way as OpenGL etc",
  730. texture_bindpoint_descs[t_idx].name,
  731. t.bind_point,
  732. )
  733. }
  734. }
  735. }
  736. d3d11_destroy_shader :: proc(h: Shader_Handle) {
  737. shd := hm.get(&s.shaders, h)
  738. if shd == nil {
  739. log.errorf("Invalid shader: %v", h)
  740. return
  741. }
  742. shd.input_layout->Release()
  743. shd.vertex_shader->Release()
  744. shd.pixel_shader->Release()
  745. for c in shd.constant_buffers {
  746. if c.gpu_data != nil {
  747. c.gpu_data->Release()
  748. }
  749. }
  750. delete(shd.texture_bindings, s.allocator)
  751. delete(shd.constants, s.allocator)
  752. delete(shd.constant_buffers, s.allocator)
  753. hm.remove(&s.shaders, h)
  754. }
  755. // API END
  756. s: ^D3D11_State
  757. D3D11_Shader_Constant_Buffer :: struct {
  758. gpu_data: ^d3d11.IBuffer,
  759. size: int,
  760. bound_shaders: bit_set[D3D11_Shader_Type],
  761. bind_point: u32,
  762. }
  763. D3D11_Texture_Binding :: struct {
  764. bind_point: u32,
  765. sampler_bind_point: u32,
  766. }
  767. D3D11_Shader_Constant :: struct {
  768. buffer_idx: u32,
  769. offset: u32,
  770. }
  771. D3D11_Shader :: struct {
  772. handle: Shader_Handle,
  773. vertex_shader: ^d3d11.IVertexShader,
  774. pixel_shader: ^d3d11.IPixelShader,
  775. input_layout: ^d3d11.IInputLayout,
  776. constant_buffers: []D3D11_Shader_Constant_Buffer,
  777. constants: []D3D11_Shader_Constant,
  778. texture_bindings: []D3D11_Texture_Binding,
  779. }
  780. D3D11_State :: struct {
  781. allocator: runtime.Allocator,
  782. window_handle: dxgi.HWND,
  783. width: int,
  784. height: int,
  785. dxgi_adapter: ^dxgi.IAdapter,
  786. swapchain: ^dxgi.ISwapChain1,
  787. framebuffer_view: ^d3d11.IRenderTargetView,
  788. depth_buffer_view: ^d3d11.IDepthStencilView,
  789. device_context: ^d3d11.IDeviceContext,
  790. depth_stencil_state: ^d3d11.IDepthStencilState,
  791. rasterizer_state: ^d3d11.IRasterizerState,
  792. device: ^d3d11.IDevice,
  793. depth_buffer: ^d3d11.ITexture2D,
  794. framebuffer: ^d3d11.ITexture2D,
  795. blend_state_alpha: ^d3d11.IBlendState,
  796. blend_state_premultiplied_alpha: ^d3d11.IBlendState,
  797. textures: hm.Handle_Map(D3D11_Texture, Texture_Handle, 1024*10),
  798. render_targets: hm.Handle_Map(D3D11_Render_Target, Render_Target_Handle, 1024*10),
  799. shaders: hm.Handle_Map(D3D11_Shader, Shader_Handle, 1024*10),
  800. info_queue: ^d3d11.IInfoQueue,
  801. vertex_buffer_gpu: ^d3d11.IBuffer,
  802. all_samplers: map[^d3d11.ISamplerState]struct{},
  803. }
  804. create_swapchain :: proc(w, h: int) {
  805. swapchain_desc := dxgi.SWAP_CHAIN_DESC1 {
  806. Width = u32(w),
  807. Height = u32(h),
  808. Format = .B8G8R8A8_UNORM,
  809. SampleDesc = {
  810. Count = 1,
  811. },
  812. BufferUsage = {.RENDER_TARGET_OUTPUT},
  813. BufferCount = 2,
  814. Scaling = .STRETCH,
  815. SwapEffect = .DISCARD,
  816. }
  817. dxgi_factory: ^dxgi.IFactory2
  818. ch(s.dxgi_adapter->GetParent(dxgi.IFactory2_UUID, (^rawptr)(&dxgi_factory)))
  819. ch(dxgi_factory->CreateSwapChainForHwnd(s.device, s.window_handle, &swapchain_desc, nil, nil, &s.swapchain))
  820. ch(s.swapchain->GetBuffer(0, d3d11.ITexture2D_UUID, (^rawptr)(&s.framebuffer)))
  821. ch(s.device->CreateRenderTargetView(s.framebuffer, nil, &s.framebuffer_view))
  822. depth_buffer_desc: d3d11.TEXTURE2D_DESC
  823. s.framebuffer->GetDesc(&depth_buffer_desc)
  824. depth_buffer_desc.Format = .D24_UNORM_S8_UINT
  825. depth_buffer_desc.BindFlags = {.DEPTH_STENCIL}
  826. ch(s.device->CreateTexture2D(&depth_buffer_desc, nil, &s.depth_buffer))
  827. ch(s.device->CreateDepthStencilView(s.depth_buffer, nil, &s.depth_buffer_view))
  828. s.device_context->ClearDepthStencilView(s.depth_buffer_view, {.DEPTH}, 1, 0)
  829. }
  830. D3D11_Texture :: struct {
  831. handle: Texture_Handle,
  832. tex: ^d3d11.ITexture2D,
  833. view: ^d3d11.IShaderResourceView,
  834. format: Pixel_Format,
  835. // It may seem strange that we have a sampler here. But samplers are reused if you recreate them
  836. // with the same options. D3D11 will return the same object. So each time we set the filter
  837. // mode or the UV wrapping settings, then we just ask D3D11 for the sampler state for those
  838. // settings.
  839. //
  840. // Moreover, in order to make D3D11 behave a bit like GL (or rather, to make them behave more
  841. // similarly), we require that each texture in the HLSL shaders have a dedicated sampler.
  842. sampler: ^d3d11.ISamplerState,
  843. }
  844. D3D11_Render_Target :: struct {
  845. handle: Render_Target_Handle,
  846. depth_stencil_texture: ^d3d11.ITexture2D,
  847. depth_stencil_texture_view: ^d3d11.IDepthStencilView,
  848. render_target_view: ^d3d11.IRenderTargetView,
  849. }
  850. dxgi_format_from_pixel_format :: proc(f: Pixel_Format) -> dxgi.FORMAT {
  851. switch f {
  852. case .Unknown: return .UNKNOWN
  853. case .RGBA_32_Float: return .R32G32B32A32_FLOAT
  854. case .RGB_32_Float: return .R32G32B32_FLOAT
  855. case .RG_32_Float: return .R32G32_FLOAT
  856. case .R_32_Float: return .R32_FLOAT
  857. case .RGBA_8_Norm: return .R8G8B8A8_UNORM
  858. case .RG_8_Norm: return .R8G8_UNORM
  859. case .R_8_Norm: return .R8_UNORM
  860. case .R_8_UInt: return .R8_UINT
  861. }
  862. log.error("Unknown format")
  863. return .UNKNOWN
  864. }
  865. // CHeck win errors and print message log if there is any error
  866. ch :: proc(hr: dxgi.HRESULT, loc := #caller_location) -> dxgi.HRESULT {
  867. if hr >= 0 {
  868. return hr
  869. }
  870. log.errorf("d3d11 error: %0x", u32(hr), location = loc)
  871. log_messages(loc)
  872. return hr
  873. }
  874. log_messages :: proc(loc := #caller_location) {
  875. iq := s.info_queue
  876. if iq == nil {
  877. return
  878. }
  879. n := iq->GetNumStoredMessages()
  880. longest_msg: d3d11.SIZE_T
  881. for i in 0..=n {
  882. msglen: d3d11.SIZE_T
  883. iq->GetMessage(i, nil, &msglen)
  884. if msglen > longest_msg {
  885. longest_msg = msglen
  886. }
  887. }
  888. if longest_msg > 0 {
  889. msg_raw_ptr, _ := (mem.alloc(int(longest_msg), allocator = frame_allocator))
  890. for i in 0..=n {
  891. msglen: d3d11.SIZE_T
  892. iq->GetMessage(i, nil, &msglen)
  893. if msglen > 0 {
  894. msg := (^d3d11.MESSAGE)(msg_raw_ptr)
  895. iq->GetMessage(i, msg, &msglen)
  896. log.error(msg.pDescription, location = loc)
  897. }
  898. }
  899. }
  900. iq->ClearStoredMessages()
  901. }
  902. DEFAULT_SHADER_SOURCE :: #load("render_backend_d3d11_default_shader.hlsl")
  903. d3d11_default_shader_vertex_source :: proc() -> string {
  904. return string(DEFAULT_SHADER_SOURCE)
  905. }
  906. d3d11_default_shader_fragment_source :: proc() -> string {
  907. return string(DEFAULT_SHADER_SOURCE)
  908. }