karl2d_windows.odin 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. #+build windows
  2. package karl2d
  3. import "base:runtime"
  4. import win32 "core:sys/windows"
  5. import d3d11 "vendor:directx/d3d11"
  6. import dxgi "vendor:directx/dxgi"
  7. import "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. import "core:math"
  14. import "core:image"
  15. import "core:image/bmp"
  16. import "core:image/png"
  17. import "core:image/tga"
  18. _ :: bmp
  19. _ :: png
  20. _ :: tga
  21. _init :: proc(width: int, height: int, title: string,
  22. allocator := context.allocator, loc := #caller_location) -> ^State {
  23. s = new(State, allocator, loc)
  24. s.custom_context = context
  25. CLASS_NAME :: "karl2d"
  26. instance := win32.HINSTANCE(win32.GetModuleHandleW(nil))
  27. s.run = true
  28. s.width = width
  29. s.height = height
  30. cls := win32.WNDCLASSW {
  31. lpfnWndProc = window_proc,
  32. lpszClassName = CLASS_NAME,
  33. hInstance = instance,
  34. hCursor = win32.LoadCursorA(nil, win32.IDC_ARROW),
  35. }
  36. win32.RegisterClassW(&cls)
  37. r: win32.RECT
  38. r.right = i32(width)
  39. r.bottom = i32(height)
  40. style := win32.WS_OVERLAPPEDWINDOW | win32.WS_VISIBLE
  41. win32.AdjustWindowRect(&r, style, false)
  42. hwnd := win32.CreateWindowW(CLASS_NAME,
  43. win32.utf8_to_wstring(title),
  44. style,
  45. 100, 10, r.right - r.left, r.bottom - r.top,
  46. nil, nil, instance, nil)
  47. assert(hwnd != nil, "Failed creating window")
  48. feature_levels := [?]d3d11.FEATURE_LEVEL{
  49. ._11_1,
  50. ._11_0,
  51. }
  52. base_device: ^d3d11.IDevice
  53. base_device_context: ^d3d11.IDeviceContext
  54. device_flags := d3d11.CREATE_DEVICE_FLAGS {
  55. .BGRA_SUPPORT,
  56. }
  57. when ODIN_DEBUG {
  58. device_flags += { .DEBUG }
  59. }
  60. 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. ch(base_device->QueryInterface(d3d11.IInfoQueue_UUID, (^rawptr)(&s.info_queue)))
  68. ch(base_device->QueryInterface(d3d11.IDevice_UUID, (^rawptr)(&s.device)))
  69. ch(base_device_context->QueryInterface(d3d11.IDeviceContext_UUID, (^rawptr)(&s.device_context)))
  70. dxgi_device: ^dxgi.IDevice
  71. ch(s.device->QueryInterface(dxgi.IDevice_UUID, (^rawptr)(&dxgi_device)))
  72. base_device->Release()
  73. base_device_context->Release()
  74. dxgi_adapter: ^dxgi.IAdapter
  75. ch(dxgi_device->GetAdapter(&dxgi_adapter))
  76. dxgi_device->Release()
  77. dxgi_factory: ^dxgi.IFactory2
  78. ch(dxgi_adapter->GetParent(dxgi.IFactory2_UUID, (^rawptr)(&dxgi_factory)))
  79. swapchain_desc := dxgi.SWAP_CHAIN_DESC1 {
  80. Format = .B8G8R8A8_UNORM,
  81. SampleDesc = {
  82. Count = 1,
  83. },
  84. BufferUsage = {.RENDER_TARGET_OUTPUT},
  85. BufferCount = 2,
  86. Scaling = .STRETCH,
  87. SwapEffect = .DISCARD,
  88. }
  89. ch(dxgi_factory->CreateSwapChainForHwnd(s.device, hwnd, &swapchain_desc, nil, nil, &s.swapchain))
  90. ch(s.swapchain->GetBuffer(0, d3d11.ITexture2D_UUID, (^rawptr)(&s.framebuffer)))
  91. ch(s.device->CreateRenderTargetView(s.framebuffer, nil, &s.framebuffer_view))
  92. depth_buffer_desc: d3d11.TEXTURE2D_DESC
  93. s.framebuffer->GetDesc(&depth_buffer_desc)
  94. depth_buffer_desc.Format = .D24_UNORM_S8_UINT
  95. depth_buffer_desc.BindFlags = {.DEPTH_STENCIL}
  96. ch(s.device->CreateTexture2D(&depth_buffer_desc, nil, &s.depth_buffer))
  97. ch(s.device->CreateDepthStencilView(s.depth_buffer, nil, &s.depth_buffer_view))
  98. vs_blob: ^d3d11.IBlob
  99. vs_blob_errors: ^d3d11.IBlob
  100. ch(d3d_compiler.Compile(raw_data(shader_hlsl), len(shader_hlsl), "shader.hlsl", nil, nil, "vs_main", "vs_5_0", 0, 0, &vs_blob, &vs_blob_errors))
  101. if vs_blob_errors != nil {
  102. log.error("Failed compiling shader:")
  103. log.error(strings.string_from_ptr((^u8)(vs_blob_errors->GetBufferPointer()), int(vs_blob_errors->GetBufferSize())))
  104. }
  105. ch(s.device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nil, &s.vertex_shader))
  106. input_element_desc := [?]d3d11.INPUT_ELEMENT_DESC{
  107. { "POS", 0, .R32G32_FLOAT, 0, 0, .VERTEX_DATA, 0 },
  108. { "UV", 0, .R32G32_FLOAT, 0, d3d11.APPEND_ALIGNED_ELEMENT, .VERTEX_DATA, 0 },
  109. { "COL", 0, .R8G8B8A8_UNORM, 0, d3d11.APPEND_ALIGNED_ELEMENT, .VERTEX_DATA, 0 },
  110. }
  111. ch(s.device->CreateInputLayout(&input_element_desc[0], len(input_element_desc), vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &s.input_layout))
  112. ps_blob: ^d3d11.IBlob
  113. ps_blob_errors: ^d3d11.IBlob
  114. ch(d3d_compiler.Compile(raw_data(shader_hlsl), len(shader_hlsl), "shader.hlsl", nil, nil, "ps_main", "ps_5_0", 0, 0, &ps_blob, &ps_blob_errors))
  115. if ps_blob_errors != nil {
  116. log.error("Failed compiling shader:")
  117. log.error(strings.string_from_ptr((^u8)(ps_blob_errors->GetBufferPointer()), int(ps_blob_errors->GetBufferSize())))
  118. }
  119. ch(s.device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nil, &s.pixel_shader))
  120. rasterizer_desc := d3d11.RASTERIZER_DESC{
  121. FillMode = .SOLID,
  122. CullMode = .BACK,
  123. }
  124. ch(s.device->CreateRasterizerState(&rasterizer_desc, &s.rasterizer_state))
  125. depth_stencil_desc := d3d11.DEPTH_STENCIL_DESC{
  126. DepthEnable = false,
  127. DepthWriteMask = .ALL,
  128. DepthFunc = .LESS,
  129. }
  130. ch(s.device->CreateDepthStencilState(&depth_stencil_desc, &s.depth_stencil_state))
  131. constant_buffer_desc := d3d11.BUFFER_DESC{
  132. ByteWidth = size_of(Constants),
  133. Usage = .DYNAMIC,
  134. BindFlags = {.CONSTANT_BUFFER},
  135. CPUAccessFlags = {.WRITE},
  136. }
  137. ch(s.device->CreateBuffer(&constant_buffer_desc, nil, &s.constant_buffer))
  138. vertex_buffer_desc := d3d11.BUFFER_DESC{
  139. ByteWidth = VERTEX_BUFFER_MAX * size_of(Vertex),
  140. Usage = .DYNAMIC,
  141. BindFlags = {.VERTEX_BUFFER},
  142. CPUAccessFlags = {.WRITE},
  143. }
  144. ch(s.device->CreateBuffer(&vertex_buffer_desc, nil, &s.vertex_buffer_gpu))
  145. s.vertex_buffer_cpu = make([]Vertex, VERTEX_BUFFER_MAX)
  146. blend_desc := d3d11.BLEND_DESC {
  147. RenderTarget = {
  148. 0 = {
  149. BlendEnable = true,
  150. SrcBlend = .SRC_ALPHA,
  151. DestBlend = .INV_SRC_ALPHA,
  152. BlendOp = .ADD,
  153. SrcBlendAlpha = .ONE,
  154. DestBlendAlpha = .ZERO,
  155. BlendOpAlpha = .ADD,
  156. RenderTargetWriteMask = u8(d3d11.COLOR_WRITE_ENABLE_ALL),
  157. },
  158. },
  159. }
  160. ch(s.device->CreateBlendState(&blend_desc, &s.blend_state))
  161. s.proj_matrix = make_default_projection(s.width, s.height)
  162. s.view_matrix = 1
  163. sampler_desc := d3d11.SAMPLER_DESC{
  164. Filter = .MIN_MAG_MIP_POINT,
  165. AddressU = .WRAP,
  166. AddressV = .WRAP,
  167. AddressW = .WRAP,
  168. ComparisonFunc = .NEVER,
  169. }
  170. s.device->CreateSamplerState(&sampler_desc, &s.sampler_state)
  171. return s
  172. }
  173. shader_hlsl :: #load("shader.hlsl")
  174. Vertex :: struct {
  175. pos: Vec2,
  176. uv: Vec2,
  177. color: Color,
  178. }
  179. s: ^State
  180. VERTEX_BUFFER_MAX :: 10000
  181. State :: struct {
  182. swapchain: ^dxgi.ISwapChain1,
  183. framebuffer_view: ^d3d11.IRenderTargetView,
  184. depth_buffer_view: ^d3d11.IDepthStencilView,
  185. device_context: ^d3d11.IDeviceContext,
  186. constant_buffer: ^d3d11.IBuffer,
  187. vertex_shader: ^d3d11.IVertexShader,
  188. pixel_shader: ^d3d11.IPixelShader,
  189. depth_stencil_state: ^d3d11.IDepthStencilState,
  190. rasterizer_state: ^d3d11.IRasterizerState,
  191. input_layout: ^d3d11.IInputLayout,
  192. device: ^d3d11.IDevice,
  193. depth_buffer: ^d3d11.ITexture2D,
  194. framebuffer: ^d3d11.ITexture2D,
  195. blend_state: ^d3d11.IBlendState,
  196. // these need to be generalized
  197. sampler_state: ^d3d11.ISamplerState,
  198. set_tex: Texture,
  199. info_queue: ^d3d11.IInfoQueue,
  200. vertex_buffer_gpu: ^d3d11.IBuffer,
  201. vertex_buffer_cpu: []Vertex,
  202. vertex_buffer_cpu_count: int,
  203. vertex_buffer_offset: int,
  204. run: bool,
  205. custom_context: runtime.Context,
  206. camera: Maybe(Camera),
  207. width: int,
  208. height: int,
  209. keys_went_down: #sparse [Keyboard_Key]bool,
  210. keys_went_up: #sparse [Keyboard_Key]bool,
  211. keys_is_held: #sparse [Keyboard_Key]bool,
  212. view_matrix: matrix[4,4]f32,
  213. proj_matrix: matrix[4,4]f32,
  214. }
  215. VK_MAP := [255]Keyboard_Key {
  216. win32.VK_A = .A,
  217. win32.VK_B = .B,
  218. win32.VK_C = .C,
  219. win32.VK_D = .D,
  220. win32.VK_E = .E,
  221. win32.VK_F = .F,
  222. win32.VK_G = .G,
  223. win32.VK_H = .H,
  224. win32.VK_I = .I,
  225. win32.VK_J = .J,
  226. win32.VK_K = .K,
  227. win32.VK_L = .L,
  228. win32.VK_M = .M,
  229. win32.VK_N = .N,
  230. win32.VK_O = .O,
  231. win32.VK_P = .P,
  232. win32.VK_Q = .Q,
  233. win32.VK_R = .R,
  234. win32.VK_S = .S,
  235. win32.VK_T = .T,
  236. win32.VK_U = .U,
  237. win32.VK_V = .V,
  238. win32.VK_W = .W,
  239. win32.VK_X = .X,
  240. win32.VK_Y = .Y,
  241. win32.VK_Z = .Z,
  242. win32.VK_LEFT = .Left,
  243. win32.VK_RIGHT = .Right,
  244. win32.VK_UP = .Up,
  245. win32.VK_DOWN = .Down,
  246. }
  247. window_proc :: proc "stdcall" (hwnd: win32.HWND, msg: win32.UINT, wparam: win32.WPARAM, lparam: win32.LPARAM) -> win32.LRESULT {
  248. context = s.custom_context
  249. switch msg {
  250. case win32.WM_DESTROY:
  251. win32.PostQuitMessage(0)
  252. s.run = false
  253. case win32.WM_CLOSE:
  254. s.run = false
  255. case win32.WM_KEYDOWN:
  256. key := VK_MAP[wparam]
  257. s.keys_went_down[key] = true
  258. s.keys_is_held[key] = true
  259. case win32.WM_KEYUP:
  260. key := VK_MAP[wparam]
  261. s.keys_is_held[key] = false
  262. s.keys_went_up[key] = true
  263. }
  264. return win32.DefWindowProcW(hwnd, msg, wparam, lparam)
  265. }
  266. _shutdown :: proc() {
  267. s.framebuffer_view->Release()
  268. s.depth_buffer_view->Release()
  269. s.depth_buffer->Release()
  270. s.framebuffer->Release()
  271. s.device_context->Release()
  272. s.vertex_buffer_gpu->Release()
  273. s.constant_buffer->Release()
  274. s.vertex_shader->Release()
  275. s.pixel_shader->Release()
  276. s.depth_stencil_state->Release()
  277. s.rasterizer_state->Release()
  278. s.input_layout->Release()
  279. s.swapchain->Release()
  280. s.blend_state->Release()
  281. when ODIN_DEBUG {
  282. debug: ^d3d11.IDebug
  283. if ch(s.device->QueryInterface(d3d11.IDebug_UUID, (^rawptr)(&debug))) >= 0 {
  284. ch(debug->ReportLiveDeviceObjects({.DETAIL, .IGNORE_INTERNAL}))
  285. log_messages()
  286. }
  287. debug->Release()
  288. }
  289. s.device->Release()
  290. s.info_queue->Release()
  291. }
  292. _set_internal_state :: proc(new_state: ^State) {
  293. s = new_state
  294. }
  295. Color_F32 :: [4]f32
  296. f32_color_from_color :: proc(color: Color) -> Color_F32 {
  297. return {
  298. f32(color.r) / 255,
  299. f32(color.g) / 255,
  300. f32(color.b) / 255,
  301. f32(color.a) / 255,
  302. }
  303. }
  304. _clear :: proc(color: Color) {
  305. c := f32_color_from_color(color)
  306. s.device_context->ClearRenderTargetView(s.framebuffer_view, &c)
  307. s.device_context->ClearDepthStencilView(s.depth_buffer_view, {.DEPTH}, 1, 0)
  308. }
  309. _Texture_Type :: struct {
  310. tex: ^d3d11.ITexture2D,
  311. view: ^d3d11.IShaderResourceView,
  312. }
  313. _load_texture_from_file :: proc(filename: string) -> Texture {
  314. img, img_err := image.load_from_file(filename, allocator = context.temp_allocator)
  315. if img_err != nil {
  316. log.errorf("Error loading texture %v: %v", filename, img_err)
  317. return {}
  318. }
  319. return _load_texture_from_memory(img.pixels.buf[:], img.width, img.height)
  320. }
  321. _load_texture_from_memory :: proc(data: []u8, width: int, height: int) -> Texture {
  322. texture_desc := d3d11.TEXTURE2D_DESC{
  323. Width = u32(width),
  324. Height = u32(height),
  325. MipLevels = 1,
  326. ArraySize = 1,
  327. // TODO: _SRGB or not?
  328. Format = .R8G8B8A8_UNORM_SRGB,
  329. SampleDesc = {Count = 1},
  330. Usage = .IMMUTABLE,
  331. BindFlags = {.SHADER_RESOURCE},
  332. }
  333. texture_data := d3d11.SUBRESOURCE_DATA{
  334. pSysMem = raw_data(data),
  335. SysMemPitch = u32(width * 4),
  336. }
  337. texture: ^d3d11.ITexture2D
  338. s.device->CreateTexture2D(&texture_desc, &texture_data, &texture)
  339. texture_view: ^d3d11.IShaderResourceView
  340. s.device->CreateShaderResourceView(texture, nil, &texture_view)
  341. return {
  342. id = {
  343. tex = texture,
  344. view = texture_view,
  345. },
  346. width = width,
  347. height = height,
  348. }
  349. }
  350. _destroy_texture :: proc(tex: Texture) {
  351. }
  352. _draw_texture :: proc(tex: Texture, pos: Vec2, tint := WHITE) {
  353. _draw_texture_ex(
  354. tex,
  355. {0, 0, f32(tex.width), f32(tex.height)},
  356. {pos.x, pos.y, f32(tex.width), f32(tex.height)},
  357. {},
  358. 0,
  359. tint,
  360. )
  361. }
  362. _draw_texture_rect :: proc(tex: Texture, rect: Rect, pos: Vec2, tint := WHITE) {
  363. _draw_texture_ex(
  364. tex,
  365. rect,
  366. {pos.x, pos.y, rect.w, rect.h},
  367. {},
  368. 0,
  369. tint,
  370. )
  371. }
  372. add_vertex :: proc(v: Vec2, uv: Vec2, color: Color) {
  373. v := v
  374. if s.vertex_buffer_cpu_count == len(s.vertex_buffer_cpu) {
  375. panic("Must dispatch here")
  376. }
  377. s.vertex_buffer_cpu[s.vertex_buffer_cpu_count] = {
  378. pos = v,
  379. uv = uv,
  380. color = color,
  381. }
  382. s.vertex_buffer_cpu_count += 1
  383. }
  384. _draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rot: f32, tint := WHITE) {
  385. if s.set_tex.id.tex != nil && s.set_tex.id.tex != tex.id.tex {
  386. maybe_draw_current_batch()
  387. }
  388. r := dst
  389. r.x -= origin.x
  390. r.y -= origin.y
  391. s.set_tex = tex
  392. tl, tr, bl, br: Vec2
  393. // Rotation adapted from Raylib's "DrawTexturePro"
  394. if rot == 0 {
  395. x := dst.x - origin.x
  396. y := dst.y - origin.y
  397. tl = { x, y }
  398. tr = { x + dst.w, y }
  399. bl = { x, y + dst.h}
  400. br = { x + dst.w, y + dst.h}
  401. } else {
  402. sin_rot := math.sin(rot * math.RAD_PER_DEG)
  403. cos_rot := math.cos(rot * math.RAD_PER_DEG)
  404. x := dst.x
  405. y := dst.y
  406. dx := -origin.x
  407. dy := -origin.y
  408. tl = {
  409. x + dx * cos_rot - dy * sin_rot,
  410. y + dx * sin_rot + dy * cos_rot,
  411. }
  412. tr = {
  413. x + (dx + dst.w) * cos_rot - dy * sin_rot,
  414. y + (dx + dst.w) * sin_rot + dy * cos_rot,
  415. }
  416. bl = {
  417. x + dx * cos_rot - (dy + dst.h) * sin_rot,
  418. y + dx * sin_rot + (dy + dst.h) * cos_rot,
  419. }
  420. br = {
  421. x + (dx + dst.w) * cos_rot - (dy + dst.h) * sin_rot,
  422. y + (dx + dst.w) * sin_rot + (dy + dst.h) * cos_rot,
  423. }
  424. }
  425. c := tint
  426. add_vertex(tl, {0, 0}, c)
  427. add_vertex(tr, {1, 0}, c)
  428. add_vertex(br, {1, 1}, c)
  429. add_vertex(tl, {0, 0}, c)
  430. add_vertex(br, {1, 1}, c)
  431. add_vertex(bl, {0, 1}, c)
  432. }
  433. _draw_rectangle :: proc(r: Rect, c: Color) {
  434. add_vertex({r.x, r.y}, {0, 0}, c)
  435. add_vertex({r.x + r.w, r.y}, {1, 0}, c)
  436. add_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
  437. add_vertex({r.x, r.y}, {0, 0}, c)
  438. add_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
  439. add_vertex({r.x, r.y + r.h}, {0, 1}, c)
  440. }
  441. _draw_rectangle_outline :: proc(r: Rect, thickness: f32, color: Color) {
  442. t := thickness
  443. // Based on DrawRectangleLinesEx from Raylib
  444. top := Rect {
  445. r.x,
  446. r.y,
  447. r.w,
  448. t,
  449. }
  450. bottom := Rect {
  451. r.x,
  452. r.y + r.h - t,
  453. r.w,
  454. t,
  455. }
  456. left := Rect {
  457. r.x,
  458. r.y + t,
  459. t,
  460. r.h - t * 2,
  461. }
  462. right := Rect {
  463. r.x + r.w - t,
  464. r.y + t,
  465. t,
  466. r.h - t * 2,
  467. }
  468. _draw_rectangle(top, color)
  469. _draw_rectangle(bottom, color)
  470. _draw_rectangle(left, color)
  471. _draw_rectangle(right, color)
  472. }
  473. _draw_circle :: proc(center: Vec2, radius: f32, color: Color) {
  474. }
  475. _draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  476. }
  477. _get_screen_width :: proc() -> int {
  478. return 0
  479. }
  480. _get_screen_height :: proc() -> int {
  481. return 0
  482. }
  483. _key_went_down :: proc(key: Keyboard_Key) -> bool {
  484. return s.keys_went_down[key]
  485. }
  486. _key_went_up :: proc(key: Keyboard_Key) -> bool {
  487. return s.keys_went_up[key]
  488. }
  489. _key_is_held :: proc(key: Keyboard_Key) -> bool {
  490. return s.keys_is_held[key]
  491. }
  492. _window_should_close :: proc() -> bool {
  493. return !s.run
  494. }
  495. _draw_text :: proc(text: string, pos: Vec2, font_size: f32, color: Color) {
  496. }
  497. _mouse_button_pressed :: proc(button: Mouse_Button) -> bool {
  498. return false
  499. }
  500. _mouse_button_released :: proc(button: Mouse_Button) -> bool {
  501. return false
  502. }
  503. _mouse_button_held :: proc(button: Mouse_Button) -> bool {
  504. return false
  505. }
  506. _mouse_wheel_delta :: proc() -> f32 {
  507. return 0
  508. }
  509. _mouse_position :: proc() -> Vec2 {
  510. return {}
  511. }
  512. _enable_scissor :: proc(x, y, w, h: int) {
  513. }
  514. _disable_scissor :: proc() {
  515. }
  516. _set_window_size :: proc(width: int, height: int) {
  517. }
  518. _set_window_position :: proc(x: int, y: int) {
  519. }
  520. _screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  521. return pos
  522. }
  523. Vec3 :: [3]f32
  524. vec3_from_vec2 :: proc(v: Vec2) -> Vec3 {
  525. return {
  526. v.x, v.y, 0,
  527. }
  528. }
  529. _set_camera :: proc(camera: Maybe(Camera)) {
  530. if camera == s.camera {
  531. return
  532. }
  533. s.camera = camera
  534. maybe_draw_current_batch()
  535. if c, c_ok := camera.?; c_ok {
  536. origin_trans :=linalg.matrix4_translate(vec3_from_vec2(-c.origin))
  537. translate := linalg.matrix4_translate(vec3_from_vec2(c.target))
  538. rot := linalg.matrix4_rotate_f32(c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  539. camera_matrix := translate * rot * origin_trans
  540. s.view_matrix = linalg.inverse(camera_matrix)
  541. s.proj_matrix = make_default_projection(s.width, s.height)
  542. s.proj_matrix[0, 0] *= c.zoom
  543. s.proj_matrix[1, 1] *= c.zoom
  544. } else {
  545. s.proj_matrix = make_default_projection(s.width, s.height)
  546. s.view_matrix = 1
  547. }
  548. }
  549. _set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  550. }
  551. _set_shader :: proc(shader: Maybe(Shader)) {
  552. }
  553. _process_events :: proc() {
  554. s.keys_went_up = {}
  555. s.keys_went_down = {}
  556. msg: win32.MSG
  557. for win32.PeekMessageW(&msg, nil, 0, 0, win32.PM_REMOVE) {
  558. win32.TranslateMessage(&msg)
  559. win32.DispatchMessageW(&msg)
  560. }
  561. }
  562. maybe_draw_current_batch :: proc() {
  563. if s.vertex_buffer_cpu_count == 0 {
  564. return
  565. }
  566. _draw_current_batch()
  567. }
  568. _draw_current_batch :: proc() {
  569. viewport := d3d11.VIEWPORT{
  570. 0, 0,
  571. f32(s.width), f32(s.height),
  572. 0, 1,
  573. }
  574. dc := s.device_context
  575. vb_data: d3d11.MAPPED_SUBRESOURCE
  576. ch(dc->Map(s.vertex_buffer_gpu, 0, .WRITE_NO_OVERWRITE, {}, &vb_data))
  577. {
  578. gpu_map := slice.from_ptr((^Vertex)(vb_data.pData), VERTEX_BUFFER_MAX)
  579. copy(
  580. gpu_map[s.vertex_buffer_offset:s.vertex_buffer_cpu_count],
  581. s.vertex_buffer_cpu[s.vertex_buffer_offset:s.vertex_buffer_cpu_count],
  582. )
  583. }
  584. dc->Unmap(s.vertex_buffer_gpu, 0)
  585. cb_data: d3d11.MAPPED_SUBRESOURCE
  586. ch(dc->Map(s.constant_buffer, 0, .WRITE_DISCARD, {}, &cb_data))
  587. {
  588. constants := (^Constants)(cb_data.pData)
  589. constants.mvp = s.proj_matrix * s.view_matrix
  590. }
  591. dc->Unmap(s.constant_buffer, 0)
  592. dc->IASetPrimitiveTopology(.TRIANGLELIST)
  593. dc->IASetInputLayout(s.input_layout)
  594. vertex_buffer_offset := u32(0)
  595. vertex_buffer_stride := u32(size_of(Vertex))
  596. dc->IASetVertexBuffers(0, 1, &s.vertex_buffer_gpu, &vertex_buffer_stride, &vertex_buffer_offset)
  597. dc->VSSetShader(s.vertex_shader, nil, 0)
  598. dc->VSSetConstantBuffers(0, 1, &s.constant_buffer)
  599. dc->RSSetViewports(1, &viewport)
  600. dc->RSSetState(s.rasterizer_state)
  601. dc->PSSetShader(s.pixel_shader, nil, 0)
  602. dc->PSSetShaderResources(0, 1, &s.set_tex.id.view)
  603. dc->PSSetSamplers(0, 1, &s.sampler_state)
  604. dc->OMSetRenderTargets(1, &s.framebuffer_view, s.depth_buffer_view)
  605. dc->OMSetDepthStencilState(s.depth_stencil_state, 0)
  606. dc->OMSetBlendState(s.blend_state, nil, ~u32(0))
  607. dc->Draw(u32(s.vertex_buffer_cpu_count - s.vertex_buffer_offset), u32(s.vertex_buffer_offset))
  608. s.vertex_buffer_offset = s.vertex_buffer_cpu_count
  609. log_messages()
  610. }
  611. Constants :: struct #align (16) {
  612. mvp: matrix[4, 4]f32,
  613. }
  614. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  615. return linalg.matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  616. }
  617. _present :: proc() {
  618. maybe_draw_current_batch()
  619. ch(s.swapchain->Present(1, {}))
  620. s.vertex_buffer_offset = 0
  621. s.vertex_buffer_cpu_count = 0
  622. }
  623. _load_shader :: proc(vs: string, fs: string) -> Shader {
  624. return {}
  625. }
  626. _destroy_shader :: proc(shader: Shader) {
  627. }
  628. _get_shader_location :: proc(shader: Shader, uniform_name: string) -> int {
  629. return 0
  630. }
  631. _set_shader_value_f32 :: proc(shader: Shader, loc: int, val: f32) {
  632. }
  633. _set_shader_value_vec2 :: proc(shader: Shader, loc: int, val: Vec2) {
  634. }
  635. temp_cstring :: proc(str: string, loc := #caller_location) -> cstring {
  636. return strings.clone_to_cstring(str, context.temp_allocator, loc)
  637. }
  638. // CHeck win errors and print message log if there is any error
  639. ch :: proc(hr: win32.HRESULT, loc := #caller_location) -> win32.HRESULT {
  640. if hr >= 0 {
  641. return hr
  642. }
  643. log.errorf("d3d11 error: %0x", u32(hr), location = loc)
  644. log_messages(loc)
  645. return hr
  646. }
  647. log_messages :: proc(loc := #caller_location) {
  648. iq := s.info_queue
  649. if iq == nil {
  650. return
  651. }
  652. n := iq->GetNumStoredMessages()
  653. longest_msg: d3d11.SIZE_T
  654. for i in 0..=n {
  655. msglen: d3d11.SIZE_T
  656. iq->GetMessage(i, nil, &msglen)
  657. if msglen > longest_msg {
  658. longest_msg = msglen
  659. }
  660. }
  661. if longest_msg > 0 {
  662. msg_raw_ptr, _ := (mem.alloc(int(longest_msg), allocator = context.temp_allocator))
  663. for i in 0..=n {
  664. msglen: d3d11.SIZE_T
  665. iq->GetMessage(i, nil, &msglen)
  666. if msglen > 0 {
  667. msg := (^d3d11.MESSAGE)(msg_raw_ptr)
  668. iq->GetMessage(i, msg, &msglen)
  669. log.error(msg.pDescription, location = loc)
  670. }
  671. }
  672. }
  673. iq->ClearStoredMessages()
  674. }