karl2d_windows.odin 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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 hm "handle_map"
  16. import "core:image/bmp"
  17. import "core:image/png"
  18. import "core:image/tga"
  19. _ :: bmp
  20. _ :: png
  21. _ :: tga
  22. MAX_CONSTANTS_SIZE :: 2048
  23. _init :: proc(width: int, height: int, title: string,
  24. allocator := context.allocator, loc := #caller_location) -> ^State {
  25. win32.SetProcessDPIAware()
  26. s = new(State, allocator, loc)
  27. s.allocator = allocator
  28. s.custom_context = context
  29. CLASS_NAME :: "karl2d"
  30. instance := win32.HINSTANCE(win32.GetModuleHandleW(nil))
  31. s.run = true
  32. s.width = width
  33. s.height = height
  34. cls := win32.WNDCLASSW {
  35. lpfnWndProc = window_proc,
  36. lpszClassName = CLASS_NAME,
  37. hInstance = instance,
  38. hCursor = win32.LoadCursorA(nil, win32.IDC_ARROW),
  39. }
  40. win32.RegisterClassW(&cls)
  41. r: win32.RECT
  42. r.right = i32(width)
  43. r.bottom = i32(height)
  44. style := win32.WS_OVERLAPPEDWINDOW | win32.WS_VISIBLE
  45. win32.AdjustWindowRect(&r, style, false)
  46. hwnd := win32.CreateWindowW(CLASS_NAME,
  47. win32.utf8_to_wstring(title),
  48. style,
  49. 100, 10, r.right - r.left, r.bottom - r.top,
  50. nil, nil, instance, nil)
  51. assert(hwnd != nil, "Failed creating window")
  52. feature_levels := [?]d3d11.FEATURE_LEVEL{
  53. ._11_1,
  54. ._11_0,
  55. }
  56. base_device: ^d3d11.IDevice
  57. base_device_context: ^d3d11.IDeviceContext
  58. device_flags := d3d11.CREATE_DEVICE_FLAGS {
  59. .BGRA_SUPPORT,
  60. }
  61. when ODIN_DEBUG {
  62. device_flags += { .DEBUG }
  63. }
  64. ch(d3d11.CreateDevice(
  65. nil,
  66. .HARDWARE,
  67. nil,
  68. device_flags,
  69. &feature_levels[0], len(feature_levels),
  70. d3d11.SDK_VERSION, &base_device, nil, &base_device_context))
  71. ch(base_device->QueryInterface(d3d11.IInfoQueue_UUID, (^rawptr)(&s.info_queue)))
  72. ch(base_device->QueryInterface(d3d11.IDevice_UUID, (^rawptr)(&s.device)))
  73. ch(base_device_context->QueryInterface(d3d11.IDeviceContext_UUID, (^rawptr)(&s.device_context)))
  74. dxgi_device: ^dxgi.IDevice
  75. ch(s.device->QueryInterface(dxgi.IDevice_UUID, (^rawptr)(&dxgi_device)))
  76. base_device->Release()
  77. base_device_context->Release()
  78. dxgi_adapter: ^dxgi.IAdapter
  79. ch(dxgi_device->GetAdapter(&dxgi_adapter))
  80. dxgi_device->Release()
  81. dxgi_factory: ^dxgi.IFactory2
  82. ch(dxgi_adapter->GetParent(dxgi.IFactory2_UUID, (^rawptr)(&dxgi_factory)))
  83. swapchain_desc := dxgi.SWAP_CHAIN_DESC1 {
  84. Format = .B8G8R8A8_UNORM,
  85. SampleDesc = {
  86. Count = 1,
  87. },
  88. BufferUsage = {.RENDER_TARGET_OUTPUT},
  89. BufferCount = 2,
  90. Scaling = .STRETCH,
  91. SwapEffect = .DISCARD,
  92. }
  93. ch(dxgi_factory->CreateSwapChainForHwnd(s.device, hwnd, &swapchain_desc, nil, nil, &s.swapchain))
  94. ch(s.swapchain->GetBuffer(0, d3d11.ITexture2D_UUID, (^rawptr)(&s.framebuffer)))
  95. ch(s.device->CreateRenderTargetView(s.framebuffer, nil, &s.framebuffer_view))
  96. depth_buffer_desc: d3d11.TEXTURE2D_DESC
  97. s.framebuffer->GetDesc(&depth_buffer_desc)
  98. depth_buffer_desc.Format = .D24_UNORM_S8_UINT
  99. depth_buffer_desc.BindFlags = {.DEPTH_STENCIL}
  100. ch(s.device->CreateTexture2D(&depth_buffer_desc, nil, &s.depth_buffer))
  101. ch(s.device->CreateDepthStencilView(s.depth_buffer, nil, &s.depth_buffer_view))
  102. rasterizer_desc := d3d11.RASTERIZER_DESC{
  103. FillMode = .SOLID,
  104. CullMode = .BACK,
  105. }
  106. ch(s.device->CreateRasterizerState(&rasterizer_desc, &s.rasterizer_state))
  107. depth_stencil_desc := d3d11.DEPTH_STENCIL_DESC{
  108. DepthEnable = false,
  109. DepthWriteMask = .ALL,
  110. DepthFunc = .LESS,
  111. }
  112. ch(s.device->CreateDepthStencilState(&depth_stencil_desc, &s.depth_stencil_state))
  113. vertex_buffer_desc := d3d11.BUFFER_DESC{
  114. ByteWidth = VERTEX_BUFFER_MAX * size_of(Vertex),
  115. Usage = .DYNAMIC,
  116. BindFlags = {.VERTEX_BUFFER},
  117. CPUAccessFlags = {.WRITE},
  118. }
  119. ch(s.device->CreateBuffer(&vertex_buffer_desc, nil, &s.vertex_buffer_gpu))
  120. s.vertex_buffer_cpu = make([]Vertex, VERTEX_BUFFER_MAX, allocator, loc)
  121. blend_desc := d3d11.BLEND_DESC {
  122. RenderTarget = {
  123. 0 = {
  124. BlendEnable = true,
  125. SrcBlend = .SRC_ALPHA,
  126. DestBlend = .INV_SRC_ALPHA,
  127. BlendOp = .ADD,
  128. SrcBlendAlpha = .ONE,
  129. DestBlendAlpha = .ZERO,
  130. BlendOpAlpha = .ADD,
  131. RenderTargetWriteMask = u8(d3d11.COLOR_WRITE_ENABLE_ALL),
  132. },
  133. },
  134. }
  135. ch(s.device->CreateBlendState(&blend_desc, &s.blend_state))
  136. s.proj_matrix = make_default_projection(s.width, s.height)
  137. s.view_matrix = 1
  138. sampler_desc := d3d11.SAMPLER_DESC{
  139. Filter = .MIN_MAG_MIP_POINT,
  140. AddressU = .WRAP,
  141. AddressV = .WRAP,
  142. AddressW = .WRAP,
  143. ComparisonFunc = .NEVER,
  144. }
  145. s.device->CreateSamplerState(&sampler_desc, &s.sampler_state)
  146. s.default_shader = _load_shader(string(shader_hlsl))
  147. white_rect: [16*16*4]u8
  148. slice.fill(white_rect[:], 255)
  149. s.shape_drawing_texture = _load_texture_from_memory(white_rect[:], 16, 16)
  150. return s
  151. }
  152. shader_hlsl :: #load("shader.hlsl")
  153. Vertex :: struct {
  154. pos: Vec2,
  155. uv: Vec2,
  156. color: Color,
  157. }
  158. s: ^State
  159. VERTEX_BUFFER_MAX :: 10000
  160. Handle :: hm.Handle
  161. Texture_Handle :: distinct hm.Handle
  162. TEXTURE_NONE :: Texture_Handle {}
  163. Shader_Constant_Buffer :: struct {
  164. gpu_data: ^d3d11.IBuffer,
  165. cpu_data: []u8,
  166. }
  167. Shader_Builtin_Constant :: enum {
  168. MVP,
  169. }
  170. Shader :: struct {
  171. handle: Shader_Handle,
  172. vertex_shader: ^d3d11.IVertexShader,
  173. pixel_shader: ^d3d11.IPixelShader,
  174. input_layout: ^d3d11.IInputLayout,
  175. constant_buffers: []Shader_Constant_Buffer,
  176. constant_lookup: map[string]Shader_Constant_Location,
  177. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location),
  178. }
  179. State :: struct {
  180. swapchain: ^dxgi.ISwapChain1,
  181. framebuffer_view: ^d3d11.IRenderTargetView,
  182. depth_buffer_view: ^d3d11.IDepthStencilView,
  183. device_context: ^d3d11.IDeviceContext,
  184. depth_stencil_state: ^d3d11.IDepthStencilState,
  185. rasterizer_state: ^d3d11.IRasterizerState,
  186. device: ^d3d11.IDevice,
  187. depth_buffer: ^d3d11.ITexture2D,
  188. framebuffer: ^d3d11.ITexture2D,
  189. blend_state: ^d3d11.IBlendState,
  190. shape_drawing_texture: Texture,
  191. sampler_state: ^d3d11.ISamplerState,
  192. default_shader: Shader_Handle,
  193. textures: hm.Handle_Map(_Texture, Texture_Handle, 1024*10),
  194. shaders: hm.Handle_Map(Shader, Shader_Handle, 1024*10),
  195. info_queue: ^d3d11.IInfoQueue,
  196. vertex_buffer_gpu: ^d3d11.IBuffer,
  197. vertex_buffer_cpu: []Vertex,
  198. vertex_buffer_cpu_count: int,
  199. vertex_buffer_offset: int,
  200. run: bool,
  201. custom_context: runtime.Context,
  202. allocator: runtime.Allocator,
  203. batch_texture: Texture_Handle,
  204. batch_camera: Maybe(Camera),
  205. batch_shader: Shader_Handle,
  206. batch_constants: [MAX_CONSTANTS_SIZE]u8,
  207. batch_constants_size: int,
  208. width: int,
  209. height: int,
  210. keys_went_down: #sparse [Keyboard_Key]bool,
  211. keys_went_up: #sparse [Keyboard_Key]bool,
  212. keys_is_held: #sparse [Keyboard_Key]bool,
  213. view_matrix: matrix[4,4]f32,
  214. proj_matrix: matrix[4,4]f32,
  215. }
  216. VK_MAP := [255]Keyboard_Key {
  217. win32.VK_A = .A,
  218. win32.VK_B = .B,
  219. win32.VK_C = .C,
  220. win32.VK_D = .D,
  221. win32.VK_E = .E,
  222. win32.VK_F = .F,
  223. win32.VK_G = .G,
  224. win32.VK_H = .H,
  225. win32.VK_I = .I,
  226. win32.VK_J = .J,
  227. win32.VK_K = .K,
  228. win32.VK_L = .L,
  229. win32.VK_M = .M,
  230. win32.VK_N = .N,
  231. win32.VK_O = .O,
  232. win32.VK_P = .P,
  233. win32.VK_Q = .Q,
  234. win32.VK_R = .R,
  235. win32.VK_S = .S,
  236. win32.VK_T = .T,
  237. win32.VK_U = .U,
  238. win32.VK_V = .V,
  239. win32.VK_W = .W,
  240. win32.VK_X = .X,
  241. win32.VK_Y = .Y,
  242. win32.VK_Z = .Z,
  243. win32.VK_LEFT = .Left,
  244. win32.VK_RIGHT = .Right,
  245. win32.VK_UP = .Up,
  246. win32.VK_DOWN = .Down,
  247. }
  248. window_proc :: proc "stdcall" (hwnd: win32.HWND, msg: win32.UINT, wparam: win32.WPARAM, lparam: win32.LPARAM) -> win32.LRESULT {
  249. context = s.custom_context
  250. switch msg {
  251. case win32.WM_DESTROY:
  252. win32.PostQuitMessage(0)
  253. s.run = false
  254. case win32.WM_CLOSE:
  255. s.run = false
  256. case win32.WM_KEYDOWN:
  257. key := VK_MAP[wparam]
  258. s.keys_went_down[key] = true
  259. s.keys_is_held[key] = true
  260. case win32.WM_KEYUP:
  261. key := VK_MAP[wparam]
  262. s.keys_is_held[key] = false
  263. s.keys_went_up[key] = true
  264. }
  265. return win32.DefWindowProcW(hwnd, msg, wparam, lparam)
  266. }
  267. _shutdown :: proc() {
  268. _destroy_texture(s.shape_drawing_texture)
  269. _destroy_shader(s.default_shader)
  270. s.sampler_state->Release()
  271. s.framebuffer_view->Release()
  272. s.depth_buffer_view->Release()
  273. s.depth_buffer->Release()
  274. s.framebuffer->Release()
  275. s.device_context->Release()
  276. s.vertex_buffer_gpu->Release()
  277. //s.constant_buffer->Release()
  278. s.depth_stencil_state->Release()
  279. s.rasterizer_state->Release()
  280. s.swapchain->Release()
  281. s.blend_state->Release()
  282. delete(s.vertex_buffer_cpu, s.allocator)
  283. when ODIN_DEBUG {
  284. debug: ^d3d11.IDebug
  285. if ch(s.device->QueryInterface(d3d11.IDebug_UUID, (^rawptr)(&debug))) >= 0 {
  286. ch(debug->ReportLiveDeviceObjects({.DETAIL, .IGNORE_INTERNAL}))
  287. log_messages()
  288. }
  289. debug->Release()
  290. }
  291. s.device->Release()
  292. s.info_queue->Release()
  293. a := s.allocator
  294. free(s, a)
  295. s = nil
  296. }
  297. _set_internal_state :: proc(new_state: ^State) {
  298. s = new_state
  299. }
  300. Color_F32 :: [4]f32
  301. f32_color_from_color :: proc(color: Color) -> Color_F32 {
  302. return {
  303. f32(color.r) / 255,
  304. f32(color.g) / 255,
  305. f32(color.b) / 255,
  306. f32(color.a) / 255,
  307. }
  308. }
  309. _clear :: proc(color: Color) {
  310. c := f32_color_from_color(color)
  311. s.device_context->ClearRenderTargetView(s.framebuffer_view, &c)
  312. s.device_context->ClearDepthStencilView(s.depth_buffer_view, {.DEPTH}, 1, 0)
  313. }
  314. _Texture :: struct {
  315. handle: Texture_Handle,
  316. tex: ^d3d11.ITexture2D,
  317. view: ^d3d11.IShaderResourceView,
  318. }
  319. _load_texture_from_file :: proc(filename: string) -> Texture {
  320. img, img_err := image.load_from_file(filename, options = {.alpha_add_if_missing}, allocator = context.temp_allocator)
  321. if img_err != nil {
  322. log.errorf("Error loading texture %v: %v", filename, img_err)
  323. return {}
  324. }
  325. return _load_texture_from_memory(img.pixels.buf[:], img.width, img.height)
  326. }
  327. _load_texture_from_memory :: proc(data: []u8, width: int, height: int) -> Texture {
  328. texture_desc := d3d11.TEXTURE2D_DESC{
  329. Width = u32(width),
  330. Height = u32(height),
  331. MipLevels = 1,
  332. ArraySize = 1,
  333. // TODO: _SRGB or not?
  334. Format = .R8G8B8A8_UNORM,
  335. SampleDesc = {Count = 1},
  336. Usage = .IMMUTABLE,
  337. BindFlags = {.SHADER_RESOURCE},
  338. }
  339. texture_data := d3d11.SUBRESOURCE_DATA{
  340. pSysMem = raw_data(data),
  341. SysMemPitch = u32(width * 4),
  342. }
  343. texture: ^d3d11.ITexture2D
  344. s.device->CreateTexture2D(&texture_desc, &texture_data, &texture)
  345. texture_view: ^d3d11.IShaderResourceView
  346. s.device->CreateShaderResourceView(texture, nil, &texture_view)
  347. tex := _Texture {
  348. tex = texture,
  349. view = texture_view,
  350. }
  351. handle := hm.add(&s.textures, tex)
  352. return {
  353. id = handle,
  354. width = width,
  355. height = height,
  356. }
  357. }
  358. _destroy_texture :: proc(tex: Texture) {
  359. if t := hm.get(&s.textures, tex.id); t != nil {
  360. t.tex->Release()
  361. t.view->Release()
  362. }
  363. hm.remove(&s.textures, tex.id)
  364. }
  365. _draw_texture :: proc(tex: Texture, pos: Vec2, tint := WHITE) {
  366. _draw_texture_ex(
  367. tex,
  368. {0, 0, f32(tex.width), f32(tex.height)},
  369. {pos.x, pos.y, f32(tex.width), f32(tex.height)},
  370. {},
  371. 0,
  372. tint,
  373. )
  374. }
  375. _draw_texture_rect :: proc(tex: Texture, rect: Rect, pos: Vec2, tint := WHITE) {
  376. _draw_texture_ex(
  377. tex,
  378. rect,
  379. {pos.x, pos.y, rect.w, rect.h},
  380. {},
  381. 0,
  382. tint,
  383. )
  384. }
  385. batch_vertex :: proc(v: Vec2, uv: Vec2, color: Color) {
  386. v := v
  387. if s.vertex_buffer_cpu_count == len(s.vertex_buffer_cpu) {
  388. panic("Must dispatch here")
  389. }
  390. s.vertex_buffer_cpu[s.vertex_buffer_cpu_count] = {
  391. pos = v,
  392. uv = uv,
  393. color = color,
  394. }
  395. s.vertex_buffer_cpu_count += 1
  396. }
  397. _draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rot: f32, tint := WHITE) {
  398. if tex.width == 0 || tex.height == 0 {
  399. return
  400. }
  401. if s.batch_texture != TEXTURE_NONE && s.batch_texture != tex.id {
  402. _draw_current_batch()
  403. }
  404. r := dst
  405. r.x -= origin.x
  406. r.y -= origin.y
  407. s.batch_texture = tex.id
  408. tl, tr, bl, br: Vec2
  409. // Rotation adapted from Raylib's "DrawTexturePro"
  410. if rot == 0 {
  411. x := dst.x - origin.x
  412. y := dst.y - origin.y
  413. tl = { x, y }
  414. tr = { x + dst.w, y }
  415. bl = { x, y + dst.h }
  416. br = { x + dst.w, y + dst.h }
  417. } else {
  418. sin_rot := math.sin(rot * math.RAD_PER_DEG)
  419. cos_rot := math.cos(rot * math.RAD_PER_DEG)
  420. x := dst.x
  421. y := dst.y
  422. dx := -origin.x
  423. dy := -origin.y
  424. tl = {
  425. x + dx * cos_rot - dy * sin_rot,
  426. y + dx * sin_rot + dy * cos_rot,
  427. }
  428. tr = {
  429. x + (dx + dst.w) * cos_rot - dy * sin_rot,
  430. y + (dx + dst.w) * sin_rot + dy * cos_rot,
  431. }
  432. bl = {
  433. x + dx * cos_rot - (dy + dst.h) * sin_rot,
  434. y + dx * sin_rot + (dy + dst.h) * cos_rot,
  435. }
  436. br = {
  437. x + (dx + dst.w) * cos_rot - (dy + dst.h) * sin_rot,
  438. y + (dx + dst.w) * sin_rot + (dy + dst.h) * cos_rot,
  439. }
  440. }
  441. ts := Vec2{f32(tex.width), f32(tex.height)}
  442. up := Vec2{src.x, src.y} / ts
  443. us := Vec2{src.w, src.h} / ts
  444. c := tint
  445. batch_vertex(tl, up, c)
  446. batch_vertex(tr, up + {us.x, 0}, c)
  447. batch_vertex(br, up + us, c)
  448. batch_vertex(tl, up, c)
  449. batch_vertex(br, up + us, c)
  450. batch_vertex(bl, up + {0, us.y}, c)
  451. }
  452. _draw_rectangle :: proc(r: Rect, c: Color) {
  453. if s.batch_texture != TEXTURE_NONE && s.batch_texture != s.shape_drawing_texture.id {
  454. _draw_current_batch()
  455. }
  456. s.batch_texture = s.shape_drawing_texture.id
  457. batch_vertex({r.x, r.y}, {0, 0}, c)
  458. batch_vertex({r.x + r.w, r.y}, {1, 0}, c)
  459. batch_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
  460. batch_vertex({r.x, r.y}, {0, 0}, c)
  461. batch_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
  462. batch_vertex({r.x, r.y + r.h}, {0, 1}, c)
  463. }
  464. _draw_rectangle_outline :: proc(r: Rect, thickness: f32, color: Color) {
  465. t := thickness
  466. // Based on DrawRectangleLinesEx from Raylib
  467. top := Rect {
  468. r.x,
  469. r.y,
  470. r.w,
  471. t,
  472. }
  473. bottom := Rect {
  474. r.x,
  475. r.y + r.h - t,
  476. r.w,
  477. t,
  478. }
  479. left := Rect {
  480. r.x,
  481. r.y + t,
  482. t,
  483. r.h - t * 2,
  484. }
  485. right := Rect {
  486. r.x + r.w - t,
  487. r.y + t,
  488. t,
  489. r.h - t * 2,
  490. }
  491. _draw_rectangle(top, color)
  492. _draw_rectangle(bottom, color)
  493. _draw_rectangle(left, color)
  494. _draw_rectangle(right, color)
  495. }
  496. _draw_circle :: proc(center: Vec2, radius: f32, color: Color) {
  497. }
  498. _draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  499. }
  500. _get_screen_width :: proc() -> int {
  501. return s.width
  502. }
  503. _get_screen_height :: proc() -> int {
  504. return s.height
  505. }
  506. _key_went_down :: proc(key: Keyboard_Key) -> bool {
  507. return s.keys_went_down[key]
  508. }
  509. _key_went_up :: proc(key: Keyboard_Key) -> bool {
  510. return s.keys_went_up[key]
  511. }
  512. _key_is_held :: proc(key: Keyboard_Key) -> bool {
  513. return s.keys_is_held[key]
  514. }
  515. _window_should_close :: proc() -> bool {
  516. return !s.run
  517. }
  518. _draw_text :: proc(text: string, pos: Vec2, font_size: f32, color: Color) {
  519. }
  520. _mouse_button_pressed :: proc(button: Mouse_Button) -> bool {
  521. return false
  522. }
  523. _mouse_button_released :: proc(button: Mouse_Button) -> bool {
  524. return false
  525. }
  526. _mouse_button_held :: proc(button: Mouse_Button) -> bool {
  527. return false
  528. }
  529. _mouse_wheel_delta :: proc() -> f32 {
  530. return 0
  531. }
  532. _mouse_position :: proc() -> Vec2 {
  533. return {}
  534. }
  535. _enable_scissor :: proc(x, y, w, h: int) {
  536. }
  537. _disable_scissor :: proc() {
  538. }
  539. _set_window_size :: proc(width: int, height: int) {
  540. }
  541. _set_window_position :: proc(x: int, y: int) {
  542. }
  543. _screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  544. return pos
  545. }
  546. Vec3 :: [3]f32
  547. vec3_from_vec2 :: proc(v: Vec2) -> Vec3 {
  548. return {
  549. v.x, v.y, 0,
  550. }
  551. }
  552. _set_camera :: proc(camera: Maybe(Camera)) {
  553. if camera == s.batch_camera {
  554. return
  555. }
  556. _draw_current_batch()
  557. s.batch_camera = camera
  558. if c, c_ok := camera.?; c_ok {
  559. origin_trans := linalg.matrix4_translate(vec3_from_vec2(-c.origin))
  560. translate := linalg.matrix4_translate(vec3_from_vec2(c.target))
  561. rot := linalg.matrix4_rotate_f32(c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  562. camera_matrix := translate * rot * origin_trans
  563. s.view_matrix = linalg.inverse(camera_matrix)
  564. s.proj_matrix = make_default_projection(s.width, s.height)
  565. s.proj_matrix[0, 0] *= c.zoom
  566. s.proj_matrix[1, 1] *= c.zoom
  567. } else {
  568. s.proj_matrix = make_default_projection(s.width, s.height)
  569. s.view_matrix = 1
  570. }
  571. }
  572. _set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  573. }
  574. _set_shader :: proc(shader: Shader_Handle) {
  575. if shader == s.batch_shader {
  576. return
  577. }
  578. _draw_current_batch()
  579. s.batch_shader = shader
  580. }
  581. _set_shader_constant :: proc(shader: Shader_Handle, loc: Shader_Constant_Location, val: $T) {
  582. _draw_current_batch()
  583. shd := hm.get(&s.shaders, shader)
  584. if shd == nil {
  585. return
  586. }
  587. if int(loc.buffer_idx) >= len(shd.constant_buffers) {
  588. log.warnf("Constant buffer idx %v is out of bounds", loc.buffer_idx)
  589. return
  590. }
  591. b := &shd.constant_buffers[loc.buffer_idx]
  592. if int(loc.offset) + size_of(val) > len(b.cpu_data) {
  593. log.warnf("Constant buffer idx %v is trying to be written out of bounds by at offset %v with %v bytes", loc.buffer_idx, loc.offset, size_of(val))
  594. return
  595. }
  596. dst := (^T)(&b.cpu_data[loc.offset])
  597. dst^ = val
  598. }
  599. _set_shader_constant_mat4 :: proc(shader: Shader_Handle, loc: Shader_Constant_Location, val: matrix[4,4]f32) {
  600. _set_shader_constant(shader, loc, val)
  601. }
  602. _set_shader_constant_f32 :: proc(shader: Shader_Handle, loc: Shader_Constant_Location, val: f32) {
  603. _set_shader_constant(shader, loc, val)
  604. }
  605. _set_shader_constant_vec2 :: proc(shader: Shader_Handle, loc: Shader_Constant_Location, val: Vec2) {
  606. _set_shader_constant(shader, loc, val)
  607. }
  608. _process_events :: proc() {
  609. s.keys_went_up = {}
  610. s.keys_went_down = {}
  611. msg: win32.MSG
  612. for win32.PeekMessageW(&msg, nil, 0, 0, win32.PM_REMOVE) {
  613. win32.TranslateMessage(&msg)
  614. win32.DispatchMessageW(&msg)
  615. }
  616. }
  617. _draw_current_batch :: proc() {
  618. if s.vertex_buffer_cpu_count == s.vertex_buffer_offset {
  619. return
  620. }
  621. viewport := d3d11.VIEWPORT{
  622. 0, 0,
  623. f32(s.width), f32(s.height),
  624. 0, 1,
  625. }
  626. dc := s.device_context
  627. vb_data: d3d11.MAPPED_SUBRESOURCE
  628. ch(dc->Map(s.vertex_buffer_gpu, 0, .WRITE_NO_OVERWRITE, {}, &vb_data))
  629. {
  630. gpu_map := slice.from_ptr((^Vertex)(vb_data.pData), VERTEX_BUFFER_MAX)
  631. copy(
  632. gpu_map[s.vertex_buffer_offset:s.vertex_buffer_cpu_count],
  633. s.vertex_buffer_cpu[s.vertex_buffer_offset:s.vertex_buffer_cpu_count],
  634. )
  635. }
  636. dc->Unmap(s.vertex_buffer_gpu, 0)
  637. dc->IASetPrimitiveTopology(.TRIANGLELIST)
  638. shd := hm.get(&s.shaders, s.batch_shader)
  639. if shd == nil {
  640. shd = hm.get(&s.shaders, s.default_shader)
  641. assert(shd != nil, "Failed fetching default shader")
  642. }
  643. dc->IASetInputLayout(shd.input_layout)
  644. vertex_buffer_offset := u32(0)
  645. vertex_buffer_stride := u32(size_of(Vertex))
  646. dc->IASetVertexBuffers(0, 1, &s.vertex_buffer_gpu, &vertex_buffer_stride, &vertex_buffer_offset)
  647. for mloc, builtin in shd.constant_builtin_locations {
  648. loc, loc_ok := mloc.?
  649. if !loc_ok {
  650. continue
  651. }
  652. switch builtin {
  653. case .MVP:
  654. dst := (^matrix[4,4]f32)(&shd.constant_buffers[loc.buffer_idx].cpu_data[loc.offset])
  655. dst^ = s.proj_matrix * s.view_matrix
  656. }
  657. }
  658. dc->VSSetShader(shd.vertex_shader, nil, 0)
  659. for &c, c_idx in shd.constant_buffers {
  660. if c.gpu_data == nil {
  661. continue
  662. }
  663. cb_data: d3d11.MAPPED_SUBRESOURCE
  664. ch(dc->Map(c.gpu_data, 0, .WRITE_DISCARD, {}, &cb_data))
  665. mem.copy(cb_data.pData, raw_data(c.cpu_data), len(c.cpu_data))
  666. dc->Unmap(c.gpu_data, 0)
  667. dc->VSSetConstantBuffers(u32(c_idx), 1, &c.gpu_data)
  668. dc->PSSetConstantBuffers(u32(c_idx), 1, &c.gpu_data)
  669. }
  670. dc->RSSetViewports(1, &viewport)
  671. dc->RSSetState(s.rasterizer_state)
  672. dc->PSSetShader(shd.pixel_shader, nil, 0)
  673. if t := hm.get(&s.textures, s.batch_texture); t != nil {
  674. dc->PSSetShaderResources(0, 1, &t.view)
  675. }
  676. dc->PSSetSamplers(0, 1, &s.sampler_state)
  677. dc->OMSetRenderTargets(1, &s.framebuffer_view, s.depth_buffer_view)
  678. dc->OMSetDepthStencilState(s.depth_stencil_state, 0)
  679. dc->OMSetBlendState(s.blend_state, nil, ~u32(0))
  680. dc->Draw(u32(s.vertex_buffer_cpu_count - s.vertex_buffer_offset), u32(s.vertex_buffer_offset))
  681. s.vertex_buffer_offset = s.vertex_buffer_cpu_count
  682. log_messages()
  683. }
  684. Constants :: struct #align (16) {
  685. mvp: matrix[4, 4]f32,
  686. }
  687. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  688. return linalg.matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  689. }
  690. _present :: proc() {
  691. _draw_current_batch()
  692. ch(s.swapchain->Present(1, {}))
  693. s.vertex_buffer_offset = 0
  694. s.vertex_buffer_cpu_count = 0
  695. }
  696. Shader_Constant_Location :: struct {
  697. buffer_idx: u32,
  698. offset: u32,
  699. }
  700. _load_shader :: proc(shader: string) -> Shader_Handle {
  701. vs_blob: ^d3d11.IBlob
  702. vs_blob_errors: ^d3d11.IBlob
  703. ch(d3d_compiler.Compile(raw_data(shader), len(shader), nil, nil, nil, "vs_main", "vs_5_0", 0, 0, &vs_blob, &vs_blob_errors))
  704. if vs_blob_errors != nil {
  705. log.error("Failed compiling shader:")
  706. log.error(strings.string_from_ptr((^u8)(vs_blob_errors->GetBufferPointer()), int(vs_blob_errors->GetBufferSize())))
  707. }
  708. vertex_shader: ^d3d11.IVertexShader
  709. ch(s.device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nil, &vertex_shader))
  710. ref: ^d3d11.IShaderReflection
  711. ch(d3d_compiler.Reflect(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), d3d11.ID3D11ShaderReflection_UUID, (^rawptr)(&ref)))
  712. constant_buffers: []Shader_Constant_Buffer
  713. constant_lookup: map[string]Shader_Constant_Location
  714. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location)
  715. {
  716. context.allocator = s.allocator
  717. d: d3d11.SHADER_DESC
  718. ch(ref->GetDesc(&d))
  719. constant_buffers = make([]Shader_Constant_Buffer, d.ConstantBuffers)
  720. for cb_idx in 0..<d.ConstantBuffers {
  721. cb_info := ref->GetConstantBufferByIndex(cb_idx)
  722. if cb_info == nil {
  723. continue
  724. }
  725. cb_desc: d3d11.SHADER_BUFFER_DESC
  726. cb_info->GetDesc(&cb_desc)
  727. if cb_desc.Size == 0 {
  728. continue
  729. }
  730. b := &constant_buffers[cb_idx]
  731. b.cpu_data = make([]u8, cb_desc.Size, s.allocator)
  732. constant_buffer_desc := d3d11.BUFFER_DESC{
  733. ByteWidth = cb_desc.Size,
  734. Usage = .DYNAMIC,
  735. BindFlags = {.CONSTANT_BUFFER},
  736. CPUAccessFlags = {.WRITE},
  737. }
  738. ch(s.device->CreateBuffer(&constant_buffer_desc, nil, &b.gpu_data))
  739. for var_idx in 0..<cb_desc.Variables {
  740. var_info := cb_info->GetVariableByIndex(var_idx)
  741. if var_info == nil {
  742. continue
  743. }
  744. var_desc: d3d11.SHADER_VARIABLE_DESC
  745. var_info->GetDesc(&var_desc)
  746. if var_desc.Name != "" {
  747. loc := Shader_Constant_Location {
  748. buffer_idx = cb_idx,
  749. offset = var_desc.StartOffset,
  750. }
  751. constant_lookup[strings.clone_from_cstring(var_desc.Name)] = loc
  752. switch var_desc.Name {
  753. case "mvp":
  754. constant_builtin_locations[.MVP] = loc
  755. }
  756. }
  757. // TODO add the size or type somewhere so we set it correctly
  758. /*log.info(var_desc)
  759. type_info := var_info->GetType()
  760. type_info_desc: d3d11.SHADER_TYPE_DESC
  761. type_info->GetDesc(&type_info_desc)
  762. log.info(type_info_desc)*/
  763. }
  764. }
  765. }
  766. input_element_desc := [?]d3d11.INPUT_ELEMENT_DESC{
  767. { "POS", 0, .R32G32_FLOAT, 0, 0, .VERTEX_DATA, 0 },
  768. { "UV", 0, .R32G32_FLOAT, 0, d3d11.APPEND_ALIGNED_ELEMENT, .VERTEX_DATA, 0 },
  769. { "COL", 0, .R8G8B8A8_UNORM, 0, d3d11.APPEND_ALIGNED_ELEMENT, .VERTEX_DATA, 0 },
  770. }
  771. input_layout: ^d3d11.IInputLayout
  772. ch(s.device->CreateInputLayout(&input_element_desc[0], len(input_element_desc), vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &input_layout))
  773. ps_blob: ^d3d11.IBlob
  774. ps_blob_errors: ^d3d11.IBlob
  775. ch(d3d_compiler.Compile(raw_data(shader), len(shader), nil, nil, nil, "ps_main", "ps_5_0", 0, 0, &ps_blob, &ps_blob_errors))
  776. if ps_blob_errors != nil {
  777. log.error("Failed compiling shader:")
  778. log.error(strings.string_from_ptr((^u8)(ps_blob_errors->GetBufferPointer()), int(ps_blob_errors->GetBufferSize())))
  779. }
  780. pixel_shader: ^d3d11.IPixelShader
  781. ch(s.device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nil, &pixel_shader))
  782. shd := Shader {
  783. vertex_shader = vertex_shader,
  784. pixel_shader = pixel_shader,
  785. input_layout = input_layout,
  786. constant_buffers = constant_buffers,
  787. constant_lookup = constant_lookup,
  788. constant_builtin_locations = constant_builtin_locations,
  789. }
  790. h := hm.add(&s.shaders, shd)
  791. return h
  792. }
  793. _destroy_shader :: proc(shader: Shader_Handle) {
  794. if shd := hm.get(&s.shaders, shader); shd != nil {
  795. shd.input_layout->Release()
  796. shd.vertex_shader->Release()
  797. shd.pixel_shader->Release()
  798. for c in shd.constant_buffers {
  799. if c.gpu_data != nil {
  800. c.gpu_data->Release()
  801. }
  802. delete(c.cpu_data)
  803. }
  804. delete(shd.constant_buffers)
  805. for k,_ in shd.constant_lookup {
  806. delete(k)
  807. }
  808. delete(shd.constant_lookup)
  809. }
  810. hm.remove(&s.shaders, shader)
  811. }
  812. _get_shader_constant_location :: proc(shader: Shader_Handle, name: string) -> Shader_Constant_Location {
  813. shd := hm.get(&s.shaders, shader)
  814. if shd == nil {
  815. return {}
  816. }
  817. return shd.constant_lookup[name]
  818. }
  819. temp_cstring :: proc(str: string, loc := #caller_location) -> cstring {
  820. return strings.clone_to_cstring(str, context.temp_allocator, loc)
  821. }
  822. // CHeck win errors and print message log if there is any error
  823. ch :: proc(hr: win32.HRESULT, loc := #caller_location) -> win32.HRESULT {
  824. if hr >= 0 {
  825. return hr
  826. }
  827. log.errorf("d3d11 error: %0x", u32(hr), location = loc)
  828. log_messages(loc)
  829. return hr
  830. }
  831. log_messages :: proc(loc := #caller_location) {
  832. iq := s.info_queue
  833. if iq == nil {
  834. return
  835. }
  836. n := iq->GetNumStoredMessages()
  837. longest_msg: d3d11.SIZE_T
  838. for i in 0..=n {
  839. msglen: d3d11.SIZE_T
  840. iq->GetMessage(i, nil, &msglen)
  841. if msglen > longest_msg {
  842. longest_msg = msglen
  843. }
  844. }
  845. if longest_msg > 0 {
  846. msg_raw_ptr, _ := (mem.alloc(int(longest_msg), allocator = context.temp_allocator))
  847. for i in 0..=n {
  848. msglen: d3d11.SIZE_T
  849. iq->GetMessage(i, nil, &msglen)
  850. if msglen > 0 {
  851. msg := (^d3d11.MESSAGE)(msg_raw_ptr)
  852. iq->GetMessage(i, msg, &msglen)
  853. log.error(msg.pDescription, location = loc)
  854. }
  855. }
  856. }
  857. iq->ClearStoredMessages()
  858. }