karl2d_windows.odin 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. _ = cls
  59. class := win.RegisterClassW(&cls)
  60. _ = class
  61. r: win.RECT
  62. r.right = i32(width)
  63. r.bottom = i32(height)
  64. style := win.WS_OVERLAPPEDWINDOW | win.WS_VISIBLE
  65. win.AdjustWindowRect(&r, style, false)
  66. hwnd := win.CreateWindowW(CLASS_NAME,
  67. win.utf8_to_wstring(title),
  68. style,
  69. 100, 10, r.right - r.left, r.bottom - r.top,
  70. nil, nil, instance, nil)
  71. feature_levels := [?]D3D11.FEATURE_LEVEL{
  72. ._11_1,
  73. ._11_0,
  74. }
  75. base_device: ^D3D11.IDevice
  76. base_device_context: ^D3D11.IDeviceContext
  77. device_flags := D3D11.CREATE_DEVICE_FLAGS {
  78. .BGRA_SUPPORT,
  79. }
  80. when ODIN_DEBUG {
  81. device_flags += { .DEBUG }
  82. }
  83. D3D11.CreateDevice(
  84. nil,
  85. .HARDWARE,
  86. nil,
  87. device_flags,
  88. &feature_levels[0], len(feature_levels),
  89. D3D11.SDK_VERSION, &base_device, nil, &base_device_context)
  90. base_device->QueryInterface(D3D11.IInfoQueue_UUID, (^rawptr)(&s.info_queue))
  91. base_device->QueryInterface(D3D11.IDevice_UUID, (^rawptr)(&device))
  92. base_device_context->QueryInterface(D3D11.IDeviceContext_UUID, (^rawptr)(&s.device_context))
  93. dxgi_device: ^DXGI.IDevice
  94. device->QueryInterface(DXGI.IDevice_UUID, (^rawptr)(&dxgi_device))
  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(device, hwnd, &swapchain_desc, nil, nil, &s.swapchain)
  110. framebuffer: ^D3D11.ITexture2D
  111. s.swapchain->GetBuffer(0, D3D11.ITexture2D_UUID, (^rawptr)(&framebuffer))
  112. device->CreateRenderTargetView(framebuffer, nil, &s.framebuffer_view)
  113. depth_buffer_desc: D3D11.TEXTURE2D_DESC
  114. framebuffer->GetDesc(&depth_buffer_desc)
  115. depth_buffer_desc.Format = .D24_UNORM_S8_UINT
  116. depth_buffer_desc.BindFlags = {.DEPTH_STENCIL}
  117. depth_buffer: ^D3D11.ITexture2D
  118. device->CreateTexture2D(&depth_buffer_desc, nil, &depth_buffer)
  119. device->CreateDepthStencilView(depth_buffer, nil, &s.depth_buffer_view)
  120. //////////
  121. vs_blob: ^D3D11.IBlob
  122. D3D.Compile(raw_data(shader_hlsl), len(shader_hlsl), "shader.hlsl", nil, nil, "vs_main", "vs_5_0", 0, 0, &vs_blob, nil)
  123. assert(vs_blob != nil)
  124. device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nil, &vertex_shader)
  125. input_element_desc := [?]D3D11.INPUT_ELEMENT_DESC{
  126. { "POS", 0, .R32G32_FLOAT, 0, 0, .VERTEX_DATA, 0 },
  127. { "COL", 0, .R8G8B8A8_UNORM , 0, D3D11.APPEND_ALIGNED_ELEMENT, .VERTEX_DATA, 0 },
  128. }
  129. device->CreateInputLayout(&input_element_desc[0], len(input_element_desc), vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &input_layout)
  130. ps_blob: ^D3D11.IBlob
  131. D3D.Compile(raw_data(shader_hlsl), len(shader_hlsl), "shader.hlsl", nil, nil, "ps_main", "ps_5_0", 0, 0, &ps_blob, nil)
  132. device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nil, &pixel_shader)
  133. //////////
  134. rasterizer_desc := D3D11.RASTERIZER_DESC{
  135. FillMode = .SOLID,
  136. CullMode = .BACK,
  137. }
  138. device->CreateRasterizerState(&rasterizer_desc, &rasterizer_state)
  139. depth_stencil_desc := D3D11.DEPTH_STENCIL_DESC{
  140. DepthEnable = false,
  141. DepthWriteMask = .ALL,
  142. DepthFunc = .LESS,
  143. }
  144. device->CreateDepthStencilState(&depth_stencil_desc, &depth_stencil_state)
  145. constant_buffer_desc := D3D11.BUFFER_DESC{
  146. ByteWidth = size_of(Constants),
  147. Usage = .DYNAMIC,
  148. BindFlags = {.CONSTANT_BUFFER},
  149. CPUAccessFlags = {.WRITE},
  150. }
  151. device->CreateBuffer(&constant_buffer_desc, nil, &constant_buffer)
  152. vertex_buffer_desc := D3D11.BUFFER_DESC{
  153. ByteWidth = VERTEX_BUFFER_MAX * size_of(Vertex),
  154. Usage = .DYNAMIC,
  155. BindFlags = {.VERTEX_BUFFER},
  156. CPUAccessFlags = {.WRITE},
  157. }
  158. device->CreateBuffer(&vertex_buffer_desc, nil, &s.vertex_buffer_gpu)
  159. s.vertex_buffer_cpu = make([]Vertex, VERTEX_BUFFER_MAX)
  160. s.proj_matrix = make_default_projection(s.width, s.height)
  161. return s
  162. }
  163. shader_hlsl :: #load("shader.hlsl")
  164. Vertex :: struct {
  165. pos: Vec2,
  166. color: Color,
  167. }
  168. s: ^State
  169. constant_buffer: ^D3D11.IBuffer
  170. vertex_shader: ^D3D11.IVertexShader
  171. pixel_shader: ^D3D11.IPixelShader
  172. depth_stencil_state: ^D3D11.IDepthStencilState
  173. rasterizer_state: ^D3D11.IRasterizerState
  174. input_layout: ^D3D11.IInputLayout
  175. device: ^D3D11.IDevice
  176. VERTEX_BUFFER_MAX :: 10000
  177. State :: struct {
  178. swapchain: ^DXGI.ISwapChain1,
  179. framebuffer_view: ^D3D11.IRenderTargetView,
  180. depth_buffer_view: ^D3D11.IDepthStencilView,
  181. device_context: ^D3D11.IDeviceContext,
  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. when ODIN_DEBUG {
  248. debug: ^D3D11.IDebug
  249. hr := device->QueryInterface(D3D11.IDebug_UUID, (^rawptr)(&debug))
  250. if hr >= 0 {
  251. debug->ReportLiveDeviceObjects({.DETAIL, .IGNORE_INTERNAL})
  252. check_messages()
  253. }
  254. debug->Release()
  255. }
  256. }
  257. _set_internal_state :: proc(new_state: ^State) {
  258. s = new_state
  259. }
  260. Color_F32 :: [4]f32
  261. f32_color_from_color :: proc(color: Color) -> Color_F32 {
  262. return {
  263. f32(color.r) / 255,
  264. f32(color.g) / 255,
  265. f32(color.b) / 255,
  266. f32(color.a) / 255,
  267. }
  268. }
  269. _clear :: proc(color: Color) {
  270. c := f32_color_from_color(color)
  271. s.device_context->ClearRenderTargetView(s.framebuffer_view, &c)
  272. s.device_context->ClearDepthStencilView(s.depth_buffer_view, {.DEPTH}, 1, 0)
  273. }
  274. _load_texture :: proc(filename: string) -> Texture {
  275. return {}
  276. }
  277. _destroy_texture :: proc(tex: Texture) {
  278. }
  279. _draw_texture :: proc(tex: Texture, pos: Vec2, tint := WHITE) {
  280. _draw_texture_ex(
  281. tex,
  282. {0, 0, f32(tex.width), f32(tex.height)},
  283. {pos.x, pos.y, f32(tex.width), f32(tex.height)},
  284. {},
  285. 0,
  286. tint,
  287. )
  288. }
  289. _draw_texture_rect :: proc(tex: Texture, rect: Rect, pos: Vec2, tint := WHITE) {
  290. _draw_texture_ex(
  291. tex,
  292. rect,
  293. {pos.x, pos.y, rect.w, rect.h},
  294. {},
  295. 0,
  296. tint,
  297. )
  298. }
  299. add_vertex :: proc(v: Vec2, color: Color) {
  300. if s.vertex_buffer_cpu_count == len(s.vertex_buffer_cpu) {
  301. panic("Must dispatch here")
  302. }
  303. s.vertex_buffer_cpu[s.vertex_buffer_cpu_count] = {
  304. pos = v,
  305. color = color,
  306. }
  307. s.vertex_buffer_cpu_count += 1
  308. }
  309. _draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rot: f32, tint := WHITE) {
  310. p := Vec2 {
  311. dst.x, dst.y,
  312. }
  313. p -= origin
  314. add_vertex({p.x, p.y}, tint)
  315. add_vertex({p.x + dst.w, p.y}, tint)
  316. add_vertex({p.x + dst.w, p.y + dst.h}, tint)
  317. add_vertex({p.x, p.y}, tint)
  318. add_vertex({p.x + dst.w, p.y + dst.h}, tint)
  319. add_vertex({p.x, p.y + dst.h}, tint)
  320. }
  321. _draw_rectangle :: proc(r: Rect, color: Color) {
  322. add_vertex({r.x, r.y}, color)
  323. add_vertex({r.x + r.w, r.y}, color)
  324. add_vertex({r.x + r.w, r.y + r.h}, color)
  325. add_vertex({r.x, r.y}, color)
  326. add_vertex({r.x + r.w, r.y + r.h}, color)
  327. add_vertex({r.x, r.y + r.h}, color)
  328. }
  329. _draw_rectangle_outline :: proc(rect: Rect, thickness: f32, color: Color) {
  330. }
  331. _draw_circle :: proc(center: Vec2, radius: f32, color: Color) {
  332. }
  333. _draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  334. }
  335. _get_screen_width :: proc() -> int {
  336. return 0
  337. }
  338. _get_screen_height :: proc() -> int {
  339. return 0
  340. }
  341. _key_went_down :: proc(key: Keyboard_Key) -> bool {
  342. return s.keys_went_down[key]
  343. }
  344. _key_went_up :: proc(key: Keyboard_Key) -> bool {
  345. return s.keys_went_up[key]
  346. }
  347. _key_is_held :: proc(key: Keyboard_Key) -> bool {
  348. return s.keys_is_held[key]
  349. }
  350. _window_should_close :: proc() -> bool {
  351. return !s.run
  352. }
  353. _draw_text :: proc(text: string, pos: Vec2, font_size: f32, color: Color) {
  354. }
  355. _mouse_button_pressed :: proc(button: Mouse_Button) -> bool {
  356. return false
  357. }
  358. _mouse_button_released :: proc(button: Mouse_Button) -> bool {
  359. return false
  360. }
  361. _mouse_button_held :: proc(button: Mouse_Button) -> bool {
  362. return false
  363. }
  364. _mouse_wheel_delta :: proc() -> f32 {
  365. return 0
  366. }
  367. _mouse_position :: proc() -> Vec2 {
  368. return {}
  369. }
  370. _enable_scissor :: proc(x, y, w, h: int) {
  371. }
  372. _disable_scissor :: proc() {
  373. }
  374. _set_window_size :: proc(width: int, height: int) {
  375. }
  376. _set_window_position :: proc(x: int, y: int) {
  377. }
  378. _screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  379. return pos
  380. }
  381. _set_camera :: proc(camera: Maybe(Camera)) {
  382. if c, c_ok := camera.?; c_ok {
  383. s.proj_matrix = make_default_projection(s.width, s.height)
  384. s.proj_matrix[0, 0] *= c.zoom
  385. s.proj_matrix[1, 1] *= c.zoom
  386. } else {
  387. s.proj_matrix = make_default_projection(s.width, s.height)
  388. }
  389. }
  390. _set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  391. }
  392. _set_shader :: proc(shader: Maybe(Shader)) {
  393. }
  394. _process_events :: proc() {
  395. s.keys_went_up = {}
  396. s.keys_went_down = {}
  397. msg: win.MSG
  398. for win.PeekMessageW(&msg, nil, 0, 0, win.PM_REMOVE) {
  399. win.TranslateMessage(&msg)
  400. win.DispatchMessageW(&msg)
  401. }
  402. }
  403. _flush :: proc() {
  404. }
  405. Constants :: struct #align (16) {
  406. projection: matrix[4, 4]f32,
  407. }
  408. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  409. return linalg.matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  410. }
  411. _present :: proc(do_flush := true) {
  412. viewport := D3D11.VIEWPORT{
  413. 0, 0,
  414. f32(s.width), f32(s.height),
  415. 0, 1,
  416. }
  417. dc := s.device_context
  418. vb_data: D3D11.MAPPED_SUBRESOURCE
  419. dc->Map(s.vertex_buffer_gpu, 0, .WRITE_NO_OVERWRITE, {}, &vb_data)
  420. {
  421. gpu_map := slice.from_ptr((^Vertex)(vb_data.pData), VERTEX_BUFFER_MAX)
  422. copy(gpu_map, s.vertex_buffer_cpu[:s.vertex_buffer_cpu_count])
  423. }
  424. dc->Unmap(s.vertex_buffer_gpu, 0)
  425. cb_data: D3D11.MAPPED_SUBRESOURCE
  426. dc->Map(constant_buffer, 0, .WRITE_DISCARD, {}, &cb_data)
  427. {
  428. constants := (^Constants)(cb_data.pData)
  429. constants.projection = s.proj_matrix
  430. }
  431. dc->Unmap(constant_buffer, 0)
  432. dc->IASetPrimitiveTopology(.TRIANGLELIST)
  433. dc->IASetInputLayout(input_layout)
  434. vertex_buffer_offset := u32(0)
  435. vertex_buffer_stride := u32(size_of(Vertex))
  436. dc->IASetVertexBuffers(0, 1, &s.vertex_buffer_gpu, &vertex_buffer_stride, &vertex_buffer_offset)
  437. dc->VSSetShader(vertex_shader, nil, 0)
  438. dc->VSSetConstantBuffers(0, 1, &constant_buffer)
  439. dc->RSSetViewports(1, &viewport)
  440. dc->RSSetState(rasterizer_state)
  441. dc->PSSetShader(pixel_shader, nil, 0)
  442. dc->OMSetRenderTargets(1, &s.framebuffer_view, s.depth_buffer_view)
  443. dc->OMSetDepthStencilState(depth_stencil_state, 0)
  444. dc->OMSetBlendState(nil, nil, ~u32(0)) // use default blend mode (i.e. disable)
  445. dc->Draw(u32(s.vertex_buffer_cpu_count), 0)
  446. s.swapchain->Present(1, {})
  447. s.vertex_buffer_cpu_count = 0
  448. }
  449. _load_shader :: proc(vs: string, fs: string) -> Shader {
  450. return {}
  451. }
  452. _destroy_shader :: proc(shader: Shader) {
  453. }
  454. _get_shader_location :: proc(shader: Shader, uniform_name: string) -> int {
  455. return 0
  456. }
  457. _set_shader_value_f32 :: proc(shader: Shader, loc: int, val: f32) {
  458. }
  459. _set_shader_value_vec2 :: proc(shader: Shader, loc: int, val: Vec2) {
  460. }
  461. temp_cstring :: proc(str: string) -> cstring {
  462. return strings.clone_to_cstring(str, context.temp_allocator)
  463. }