karl2d_windows.odin 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. #+build windows
  2. package karl2d
  3. import "base:runtime"
  4. import win "core:sys/windows"
  5. import D3D11 "vendor:directx/d3d11"
  6. import DXGI "vendor:directx/dxgi"
  7. import D3D "vendor:directx/d3d_compiler"
  8. import "core:strings"
  9. import "core:log"
  10. import "core:math/linalg"
  11. import "core:slice"
  12. import "core:mem"
  13. _ :: slice
  14. _ :: log
  15. //import "core:math"
  16. check_messages :: proc(loc := #caller_location) {
  17. iq := s.info_queue
  18. if iq != nil {
  19. n := iq->GetNumStoredMessages()
  20. longest_msg: D3D11.SIZE_T
  21. for i in 0..=n {
  22. msglen: D3D11.SIZE_T
  23. iq->GetMessage(i, nil, &msglen)
  24. if msglen > longest_msg {
  25. longest_msg = msglen
  26. }
  27. }
  28. if longest_msg > 0 {
  29. msg_raw_ptr, _ := (mem.alloc(int(longest_msg), allocator = context.temp_allocator))
  30. for i in 0..=n {
  31. msglen: D3D11.SIZE_T
  32. iq->GetMessage(i, nil, &msglen)
  33. if msglen > 0 {
  34. msg := (^D3D11.MESSAGE)(msg_raw_ptr)
  35. iq->GetMessage(i, msg, &msglen)
  36. log.error(msg.pDescription, location = loc)
  37. }
  38. }
  39. }
  40. iq->ClearStoredMessages()
  41. }
  42. }
  43. _init :: proc(width: int, height: int, title: string,
  44. allocator := context.allocator, loc := #caller_location) -> ^State {
  45. s = new(State, allocator, loc)
  46. s.custom_context = context
  47. CLASS_NAME :: "karl2d"
  48. instance := win.HINSTANCE(win.GetModuleHandleW(nil))
  49. s.run = true
  50. s.width = width
  51. s.height = height
  52. cls := win.WNDCLASSW {
  53. lpfnWndProc = window_proc,
  54. lpszClassName = CLASS_NAME,
  55. hInstance = instance,
  56. hCursor = win.LoadCursorA(nil, win.IDC_ARROW),
  57. }
  58. win.RegisterClassW(&cls)
  59. r: win.RECT
  60. r.right = i32(width)
  61. r.bottom = i32(height)
  62. style := win.WS_OVERLAPPEDWINDOW | win.WS_VISIBLE
  63. win.AdjustWindowRect(&r, style, false)
  64. hwnd := win.CreateWindowW(CLASS_NAME,
  65. win.utf8_to_wstring(title),
  66. style,
  67. 100, 10, r.right - r.left, r.bottom - r.top,
  68. nil, nil, instance, nil)
  69. feature_levels := [?]D3D11.FEATURE_LEVEL{
  70. ._11_1,
  71. ._11_0,
  72. }
  73. base_device: ^D3D11.IDevice
  74. base_device_context: ^D3D11.IDeviceContext
  75. device_flags := D3D11.CREATE_DEVICE_FLAGS {
  76. .BGRA_SUPPORT,
  77. }
  78. when ODIN_DEBUG {
  79. device_flags += { .DEBUG }
  80. }
  81. D3D11.CreateDevice(
  82. nil,
  83. .HARDWARE,
  84. nil,
  85. device_flags,
  86. &feature_levels[0], len(feature_levels),
  87. D3D11.SDK_VERSION, &base_device, nil, &base_device_context)
  88. base_device->QueryInterface(D3D11.IInfoQueue_UUID, (^rawptr)(&s.info_queue))
  89. base_device->QueryInterface(D3D11.IDevice_UUID, (^rawptr)(&s.device))
  90. base_device_context->QueryInterface(D3D11.IDeviceContext_UUID, (^rawptr)(&s.device_context))
  91. dxgi_device: ^DXGI.IDevice
  92. s.device->QueryInterface(DXGI.IDevice_UUID, (^rawptr)(&dxgi_device))
  93. base_device->Release()
  94. base_device_context->Release()
  95. dxgi_adapter: ^DXGI.IAdapter
  96. dxgi_device->GetAdapter(&dxgi_adapter)
  97. dxgi_factory: ^DXGI.IFactory2
  98. dxgi_adapter->GetParent(DXGI.IFactory2_UUID, (^rawptr)(&dxgi_factory))
  99. swapchain_desc := DXGI.SWAP_CHAIN_DESC1 {
  100. Format = .B8G8R8A8_UNORM,
  101. SampleDesc = {
  102. Count = 1,
  103. },
  104. BufferUsage = {.RENDER_TARGET_OUTPUT},
  105. BufferCount = 2,
  106. Scaling = .STRETCH,
  107. SwapEffect = .DISCARD,
  108. }
  109. dxgi_factory->CreateSwapChainForHwnd(s.device, hwnd, &swapchain_desc, nil, nil, &s.swapchain)
  110. s.swapchain->GetBuffer(0, D3D11.ITexture2D_UUID, (^rawptr)(&s.framebuffer))
  111. s.device->CreateRenderTargetView(s.framebuffer, nil, &s.framebuffer_view)
  112. depth_buffer_desc: D3D11.TEXTURE2D_DESC
  113. s.framebuffer->GetDesc(&depth_buffer_desc)
  114. depth_buffer_desc.Format = .D24_UNORM_S8_UINT
  115. depth_buffer_desc.BindFlags = {.DEPTH_STENCIL}
  116. s.device->CreateTexture2D(&depth_buffer_desc, nil, &s.depth_buffer)
  117. s.device->CreateDepthStencilView(s.depth_buffer, nil, &s.depth_buffer_view)
  118. //////////
  119. vs_blob: ^D3D11.IBlob
  120. D3D.Compile(raw_data(shader_hlsl), len(shader_hlsl), "shader.hlsl", nil, nil, "vs_main", "vs_5_0", 0, 0, &vs_blob, nil)
  121. assert(vs_blob != nil)
  122. s.device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nil, &s.vertex_shader)
  123. input_element_desc := [?]D3D11.INPUT_ELEMENT_DESC{
  124. { "POS", 0, .R32G32_FLOAT, 0, 0, .VERTEX_DATA, 0 },
  125. { "COL", 0, .R8G8B8A8_UNORM , 0, D3D11.APPEND_ALIGNED_ELEMENT, .VERTEX_DATA, 0 },
  126. }
  127. s.device->CreateInputLayout(&input_element_desc[0], len(input_element_desc), vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &s.input_layout)
  128. ps_blob: ^D3D11.IBlob
  129. D3D.Compile(raw_data(shader_hlsl), len(shader_hlsl), "shader.hlsl", nil, nil, "ps_main", "ps_5_0", 0, 0, &ps_blob, nil)
  130. s.device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nil, &s.pixel_shader)
  131. //////////
  132. rasterizer_desc := D3D11.RASTERIZER_DESC{
  133. FillMode = .SOLID,
  134. CullMode = .BACK,
  135. }
  136. s.device->CreateRasterizerState(&rasterizer_desc, &s.rasterizer_state)
  137. depth_stencil_desc := D3D11.DEPTH_STENCIL_DESC{
  138. DepthEnable = false,
  139. DepthWriteMask = .ALL,
  140. DepthFunc = .LESS,
  141. }
  142. s.device->CreateDepthStencilState(&depth_stencil_desc, &s.depth_stencil_state)
  143. constant_buffer_desc := D3D11.BUFFER_DESC{
  144. ByteWidth = size_of(Constants),
  145. Usage = .DYNAMIC,
  146. BindFlags = {.CONSTANT_BUFFER},
  147. CPUAccessFlags = {.WRITE},
  148. }
  149. s.device->CreateBuffer(&constant_buffer_desc, nil, &s.constant_buffer)
  150. vertex_buffer_desc := D3D11.BUFFER_DESC{
  151. ByteWidth = VERTEX_BUFFER_MAX * size_of(Vertex),
  152. Usage = .DYNAMIC,
  153. BindFlags = {.VERTEX_BUFFER},
  154. CPUAccessFlags = {.WRITE},
  155. }
  156. s.device->CreateBuffer(&vertex_buffer_desc, nil, &s.vertex_buffer_gpu)
  157. s.vertex_buffer_cpu = make([]Vertex, VERTEX_BUFFER_MAX)
  158. s.proj_matrix = make_default_projection(s.width, s.height)
  159. return s
  160. }
  161. shader_hlsl :: #load("shader.hlsl")
  162. Vertex :: struct {
  163. pos: Vec2,
  164. color: Color,
  165. }
  166. s: ^State
  167. VERTEX_BUFFER_MAX :: 10000
  168. State :: struct {
  169. swapchain: ^DXGI.ISwapChain1,
  170. framebuffer_view: ^D3D11.IRenderTargetView,
  171. depth_buffer_view: ^D3D11.IDepthStencilView,
  172. device_context: ^D3D11.IDeviceContext,
  173. constant_buffer: ^D3D11.IBuffer,
  174. vertex_shader: ^D3D11.IVertexShader,
  175. pixel_shader: ^D3D11.IPixelShader,
  176. depth_stencil_state: ^D3D11.IDepthStencilState,
  177. rasterizer_state: ^D3D11.IRasterizerState,
  178. input_layout: ^D3D11.IInputLayout,
  179. device: ^D3D11.IDevice,
  180. depth_buffer: ^D3D11.ITexture2D,
  181. framebuffer: ^D3D11.ITexture2D,
  182. info_queue: ^D3D11.IInfoQueue,
  183. vertex_buffer_gpu: ^D3D11.IBuffer,
  184. vertex_buffer_cpu: []Vertex,
  185. vertex_buffer_cpu_count: int,
  186. run: bool,
  187. custom_context: runtime.Context,
  188. width: int,
  189. height: int,
  190. keys_went_down: #sparse [Keyboard_Key]bool,
  191. keys_went_up: #sparse [Keyboard_Key]bool,
  192. keys_is_held: #sparse [Keyboard_Key]bool,
  193. proj_matrix: matrix[4,4]f32,
  194. }
  195. VK_MAP := [255]Keyboard_Key {
  196. win.VK_A = .A,
  197. win.VK_B = .B,
  198. win.VK_C = .C,
  199. win.VK_D = .D,
  200. win.VK_E = .E,
  201. win.VK_F = .F,
  202. win.VK_G = .G,
  203. win.VK_H = .H,
  204. win.VK_I = .I,
  205. win.VK_J = .J,
  206. win.VK_K = .K,
  207. win.VK_L = .L,
  208. win.VK_M = .M,
  209. win.VK_N = .N,
  210. win.VK_O = .O,
  211. win.VK_P = .P,
  212. win.VK_Q = .Q,
  213. win.VK_R = .R,
  214. win.VK_S = .S,
  215. win.VK_T = .T,
  216. win.VK_U = .U,
  217. win.VK_V = .V,
  218. win.VK_W = .W,
  219. win.VK_X = .X,
  220. win.VK_Y = .Y,
  221. win.VK_Z = .Z,
  222. win.VK_LEFT = .Left,
  223. win.VK_RIGHT = .Right,
  224. win.VK_UP = .Up,
  225. win.VK_DOWN = .Down,
  226. }
  227. window_proc :: proc "stdcall" (hwnd: win.HWND, msg: win.UINT, wparam: win.WPARAM, lparam: win.LPARAM) -> win.LRESULT {
  228. context = s.custom_context
  229. switch msg {
  230. case win.WM_DESTROY:
  231. win.PostQuitMessage(0)
  232. s.run = false
  233. case win.WM_CLOSE:
  234. s.run = false
  235. case win.WM_KEYDOWN:
  236. key := VK_MAP[wparam]
  237. s.keys_went_down[key] = true
  238. s.keys_is_held[key] = true
  239. case win.WM_KEYUP:
  240. key := VK_MAP[wparam]
  241. s.keys_is_held[key] = false
  242. s.keys_went_up[key] = true
  243. }
  244. return win.DefWindowProcW(hwnd, msg, wparam, lparam)
  245. }
  246. _shutdown :: proc() {
  247. s.framebuffer_view->Release()
  248. s.depth_buffer_view->Release()
  249. s.depth_buffer->Release()
  250. s.framebuffer->Release()
  251. s.device_context->Release()
  252. s.vertex_buffer_gpu->Release()
  253. s.constant_buffer->Release()
  254. s.vertex_shader->Release()
  255. s.pixel_shader->Release()
  256. s.depth_stencil_state->Release()
  257. s.rasterizer_state->Release()
  258. s.input_layout->Release()
  259. s.swapchain->Release()
  260. when ODIN_DEBUG {
  261. debug: ^D3D11.IDebug
  262. hr := s.device->QueryInterface(D3D11.IDebug_UUID, (^rawptr)(&debug))
  263. if hr >= 0 {
  264. debug->ReportLiveDeviceObjects({.DETAIL, .IGNORE_INTERNAL})
  265. check_messages()
  266. }
  267. debug->Release()
  268. }
  269. s.device->Release()
  270. s.info_queue->Release()
  271. }
  272. _set_internal_state :: proc(new_state: ^State) {
  273. s = new_state
  274. }
  275. Color_F32 :: [4]f32
  276. f32_color_from_color :: proc(color: Color) -> Color_F32 {
  277. return {
  278. f32(color.r) / 255,
  279. f32(color.g) / 255,
  280. f32(color.b) / 255,
  281. f32(color.a) / 255,
  282. }
  283. }
  284. _clear :: proc(color: Color) {
  285. c := f32_color_from_color(color)
  286. s.device_context->ClearRenderTargetView(s.framebuffer_view, &c)
  287. s.device_context->ClearDepthStencilView(s.depth_buffer_view, {.DEPTH}, 1, 0)
  288. }
  289. _load_texture :: proc(filename: string) -> Texture {
  290. return {}
  291. }
  292. _destroy_texture :: proc(tex: Texture) {
  293. }
  294. _draw_texture :: proc(tex: Texture, pos: Vec2, tint := WHITE) {
  295. _draw_texture_ex(
  296. tex,
  297. {0, 0, f32(tex.width), f32(tex.height)},
  298. {pos.x, pos.y, f32(tex.width), f32(tex.height)},
  299. {},
  300. 0,
  301. tint,
  302. )
  303. }
  304. _draw_texture_rect :: proc(tex: Texture, rect: Rect, pos: Vec2, tint := WHITE) {
  305. _draw_texture_ex(
  306. tex,
  307. rect,
  308. {pos.x, pos.y, rect.w, rect.h},
  309. {},
  310. 0,
  311. tint,
  312. )
  313. }
  314. add_vertex :: proc(v: Vec2, color: Color) {
  315. if s.vertex_buffer_cpu_count == len(s.vertex_buffer_cpu) {
  316. panic("Must dispatch here")
  317. }
  318. s.vertex_buffer_cpu[s.vertex_buffer_cpu_count] = {
  319. pos = v,
  320. color = color,
  321. }
  322. s.vertex_buffer_cpu_count += 1
  323. }
  324. _draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rot: f32, tint := WHITE) {
  325. p := Vec2 {
  326. dst.x, dst.y,
  327. }
  328. p -= origin
  329. add_vertex({p.x, p.y}, tint)
  330. add_vertex({p.x + dst.w, p.y}, tint)
  331. add_vertex({p.x + dst.w, p.y + dst.h}, tint)
  332. add_vertex({p.x, p.y}, tint)
  333. add_vertex({p.x + dst.w, p.y + dst.h}, tint)
  334. add_vertex({p.x, p.y + dst.h}, tint)
  335. }
  336. _draw_rectangle :: proc(r: Rect, color: Color) {
  337. add_vertex({r.x, r.y}, color)
  338. add_vertex({r.x + r.w, r.y}, color)
  339. add_vertex({r.x + r.w, r.y + r.h}, color)
  340. add_vertex({r.x, r.y}, color)
  341. add_vertex({r.x + r.w, r.y + r.h}, color)
  342. add_vertex({r.x, r.y + r.h}, color)
  343. }
  344. _draw_rectangle_outline :: proc(rect: Rect, thickness: f32, color: Color) {
  345. }
  346. _draw_circle :: proc(center: Vec2, radius: f32, color: Color) {
  347. }
  348. _draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  349. }
  350. _get_screen_width :: proc() -> int {
  351. return 0
  352. }
  353. _get_screen_height :: proc() -> int {
  354. return 0
  355. }
  356. _key_went_down :: proc(key: Keyboard_Key) -> bool {
  357. return s.keys_went_down[key]
  358. }
  359. _key_went_up :: proc(key: Keyboard_Key) -> bool {
  360. return s.keys_went_up[key]
  361. }
  362. _key_is_held :: proc(key: Keyboard_Key) -> bool {
  363. return s.keys_is_held[key]
  364. }
  365. _window_should_close :: proc() -> bool {
  366. return !s.run
  367. }
  368. _draw_text :: proc(text: string, pos: Vec2, font_size: f32, color: Color) {
  369. }
  370. _mouse_button_pressed :: proc(button: Mouse_Button) -> bool {
  371. return false
  372. }
  373. _mouse_button_released :: proc(button: Mouse_Button) -> bool {
  374. return false
  375. }
  376. _mouse_button_held :: proc(button: Mouse_Button) -> bool {
  377. return false
  378. }
  379. _mouse_wheel_delta :: proc() -> f32 {
  380. return 0
  381. }
  382. _mouse_position :: proc() -> Vec2 {
  383. return {}
  384. }
  385. _enable_scissor :: proc(x, y, w, h: int) {
  386. }
  387. _disable_scissor :: proc() {
  388. }
  389. _set_window_size :: proc(width: int, height: int) {
  390. }
  391. _set_window_position :: proc(x: int, y: int) {
  392. }
  393. _screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  394. return pos
  395. }
  396. _set_camera :: proc(camera: Maybe(Camera)) {
  397. if c, c_ok := camera.?; c_ok {
  398. s.proj_matrix = make_default_projection(s.width, s.height)
  399. s.proj_matrix[0, 0] *= c.zoom
  400. s.proj_matrix[1, 1] *= c.zoom
  401. } else {
  402. s.proj_matrix = make_default_projection(s.width, s.height)
  403. }
  404. }
  405. _set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  406. }
  407. _set_shader :: proc(shader: Maybe(Shader)) {
  408. }
  409. _process_events :: proc() {
  410. s.keys_went_up = {}
  411. s.keys_went_down = {}
  412. msg: win.MSG
  413. for win.PeekMessageW(&msg, nil, 0, 0, win.PM_REMOVE) {
  414. win.TranslateMessage(&msg)
  415. win.DispatchMessageW(&msg)
  416. }
  417. }
  418. _flush :: proc() {
  419. }
  420. Constants :: struct #align (16) {
  421. projection: matrix[4, 4]f32,
  422. }
  423. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  424. return linalg.matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  425. }
  426. _present :: proc(do_flush := true) {
  427. viewport := D3D11.VIEWPORT{
  428. 0, 0,
  429. f32(s.width), f32(s.height),
  430. 0, 1,
  431. }
  432. dc := s.device_context
  433. vb_data: D3D11.MAPPED_SUBRESOURCE
  434. dc->Map(s.vertex_buffer_gpu, 0, .WRITE_NO_OVERWRITE, {}, &vb_data)
  435. {
  436. gpu_map := slice.from_ptr((^Vertex)(vb_data.pData), VERTEX_BUFFER_MAX)
  437. copy(gpu_map, s.vertex_buffer_cpu[:s.vertex_buffer_cpu_count])
  438. }
  439. dc->Unmap(s.vertex_buffer_gpu, 0)
  440. cb_data: D3D11.MAPPED_SUBRESOURCE
  441. dc->Map(s.constant_buffer, 0, .WRITE_DISCARD, {}, &cb_data)
  442. {
  443. constants := (^Constants)(cb_data.pData)
  444. constants.projection = s.proj_matrix
  445. }
  446. dc->Unmap(s.constant_buffer, 0)
  447. dc->IASetPrimitiveTopology(.TRIANGLELIST)
  448. dc->IASetInputLayout(s.input_layout)
  449. vertex_buffer_offset := u32(0)
  450. vertex_buffer_stride := u32(size_of(Vertex))
  451. dc->IASetVertexBuffers(0, 1, &s.vertex_buffer_gpu, &vertex_buffer_stride, &vertex_buffer_offset)
  452. dc->VSSetShader(s.vertex_shader, nil, 0)
  453. dc->VSSetConstantBuffers(0, 1, &s.constant_buffer)
  454. dc->RSSetViewports(1, &viewport)
  455. dc->RSSetState(s.rasterizer_state)
  456. dc->PSSetShader(s.pixel_shader, nil, 0)
  457. dc->OMSetRenderTargets(1, &s.framebuffer_view, s.depth_buffer_view)
  458. dc->OMSetDepthStencilState(s.depth_stencil_state, 0)
  459. dc->OMSetBlendState(nil, nil, ~u32(0)) // use default blend mode (i.e. disable)
  460. dc->Draw(u32(s.vertex_buffer_cpu_count), 0)
  461. s.swapchain->Present(1, {})
  462. s.vertex_buffer_cpu_count = 0
  463. }
  464. _load_shader :: proc(vs: string, fs: string) -> Shader {
  465. return {}
  466. }
  467. _destroy_shader :: proc(shader: Shader) {
  468. }
  469. _get_shader_location :: proc(shader: Shader, uniform_name: string) -> int {
  470. return 0
  471. }
  472. _set_shader_value_f32 :: proc(shader: Shader, loc: int, val: f32) {
  473. }
  474. _set_shader_value_vec2 :: proc(shader: Shader, loc: int, val: Vec2) {
  475. }
  476. temp_cstring :: proc(str: string) -> cstring {
  477. return strings.clone_to_cstring(str, context.temp_allocator)
  478. }