render_backend_d3d11.odin 26 KB

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