render_backend_d3d11.odin 30 KB

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