karl2d.odin 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. package karl2d
  2. import "base:runtime"
  3. import "core:mem"
  4. import "core:log"
  5. import "core:math"
  6. import "core:math/linalg"
  7. import "core:slice"
  8. import "core:strings"
  9. import "core:reflect"
  10. import "core:image"
  11. import "core:image/bmp"
  12. import "core:image/png"
  13. import "core:image/tga"
  14. import hm "handle_map"
  15. //-----------------------------------------------//
  16. // SETUP, WINDOW MANAGEMENT AND FRAME MANAGEMENT //
  17. //-----------------------------------------------//
  18. // Opens a window and initializes some internal state. The internal state will use `allocator` for
  19. // all dynamically allocated memory. The return value can be ignored unless you need to later call
  20. // `set_internal_state`.
  21. init :: proc(window_width: int, window_height: int, window_title: string,
  22. window_creation_flags := Window_Flags {},
  23. allocator := context.allocator, loc := #caller_location) -> ^State {
  24. assert(s == nil, "Don't call 'init' twice.")
  25. s = new(State, allocator, loc)
  26. s.allocator = allocator
  27. s.custom_context = context
  28. s.width = window_width
  29. s.height = window_height
  30. s.win = WINDOW_INTERFACE_WIN32
  31. win = s.win
  32. window_state_alloc_error: runtime.Allocator_Error
  33. s.window_state, window_state_alloc_error = mem.alloc(win.state_size())
  34. log.assertf(window_state_alloc_error == nil, "Failed allocating memory for window state: %v", window_state_alloc_error)
  35. win.init(s.window_state, window_width, window_height, window_title, window_creation_flags, allocator)
  36. s.window = win.window_handle()
  37. s.rb = RENDER_BACKEND_INTERFACE_D3D11
  38. rb = s.rb
  39. rb_alloc_error: runtime.Allocator_Error
  40. s.rb_state, rb_alloc_error = mem.alloc(rb.state_size())
  41. log.assertf(rb_alloc_error == nil, "Failed allocating memory for rendering backend: %v", rb_alloc_error)
  42. s.proj_matrix = make_default_projection(window_width, window_height)
  43. s.view_matrix = 1
  44. rb.init(s.rb_state, s.window, window_width, window_height, allocator)
  45. s.vertex_buffer_cpu = make([]u8, VERTEX_BUFFER_MAX, allocator, loc)
  46. white_rect: [16*16*4]u8
  47. slice.fill(white_rect[:], 255)
  48. s.shape_drawing_texture = rb.load_texture(white_rect[:], 16, 16)
  49. s.default_shader = load_shader(string(DEFAULT_SHADER_SOURCE))
  50. return s
  51. }
  52. // Returns true if the program wants to shut down. This happens when for example pressing the close
  53. // button on the window. The application can decide if it wants to shut down or if it wants to show
  54. // some kind of confirmation dialogue and shut down later.
  55. //
  56. // Commonly used for creating the "main loop" of a game.
  57. shutdown_wanted :: proc() -> bool {
  58. return s.shutdown_wanted
  59. }
  60. // Closes the window and cleans up the internal state.
  61. shutdown :: proc() {
  62. assert(s != nil, "You've called 'shutdown' without calling 'init' first")
  63. rb.destroy_texture(s.shape_drawing_texture)
  64. destroy_shader(s.default_shader)
  65. rb.shutdown()
  66. delete(s.vertex_buffer_cpu, s.allocator)
  67. win.shutdown()
  68. a := s.allocator
  69. free(s.window_state, a)
  70. free(s.rb_state, a)
  71. free(s, a)
  72. s = nil
  73. }
  74. // Clear the backbuffer with supplied color.
  75. clear :: proc(color: Color) {
  76. rb.clear(color)
  77. }
  78. // Present the backbuffer. Call at end of frame to make everything you've drawn appear on the screen.
  79. present :: proc() {
  80. draw_current_batch()
  81. rb.present()
  82. }
  83. // Call at start or end of frame to process all events that have arrived to the window.
  84. //
  85. // WARNING: Not calling this will make your program impossible to interact with.
  86. process_events :: proc() {
  87. s.key_went_up = {}
  88. s.key_went_down = {}
  89. s.mouse_button_went_up = {}
  90. s.mouse_button_went_down = {}
  91. s.mouse_delta = {}
  92. s.mouse_wheel_delta = 0
  93. win.process_events()
  94. events := win.get_events()
  95. for &event in events {
  96. switch &e in event {
  97. case Window_Event_Close_Wanted:
  98. s.shutdown_wanted = true
  99. case Window_Event_Key_Went_Down:
  100. s.key_went_down[e.key] = true
  101. s.key_is_held[e.key] = true
  102. case Window_Event_Key_Went_Up:
  103. s.key_went_up[e.key] = true
  104. s.key_is_held[e.key] = false
  105. case Window_Event_Mouse_Button_Went_Down:
  106. s.mouse_button_went_down[e.button] = true
  107. s.mouse_button_is_held[e.button] = true
  108. case Window_Event_Mouse_Button_Went_Up:
  109. s.mouse_button_went_up[e.button] = true
  110. s.mouse_button_is_held[e.button] = false
  111. case Window_Event_Mouse_Move:
  112. prev_pos := s.mouse_position
  113. s.mouse_position = e.position
  114. s.mouse_delta = prev_pos - s.mouse_position
  115. case Window_Event_Mouse_Wheel:
  116. s.mouse_wheel_delta = e.delta
  117. case Window_Event_Gamepad_Button_Went_Down:
  118. if e.gamepad < MAX_GAMEPADS {
  119. s.gamepad_button_went_down[e.gamepad][e.button] = true
  120. s.gamepad_button_is_held[e.gamepad][e.button] = true
  121. }
  122. case Window_Event_Gamepad_Button_Went_Up:
  123. if e.gamepad < MAX_GAMEPADS {
  124. s.gamepad_button_went_up[e.gamepad][e.button] = true
  125. s.gamepad_button_is_held[e.gamepad][e.button] = false
  126. }
  127. case Window_Event_Resize:
  128. s.width = e.width
  129. s.height = e.height
  130. rb.resize_swapchain(s.width, s.height)
  131. s.proj_matrix = make_default_projection(s.width, s.height)
  132. }
  133. }
  134. win.clear_events()
  135. }
  136. get_screen_width :: proc() -> int {
  137. return s.width
  138. }
  139. get_screen_height :: proc() -> int {
  140. return s.height
  141. }
  142. set_window_position :: proc(x: int, y: int) {
  143. win.set_position(x, y)
  144. }
  145. set_window_size :: proc(width: int, height: int) {
  146. // TODO not sure if we should resize swapchain here. On windows the WM_SIZE event fires and
  147. // it all works out. But perhaps not on all platforms?
  148. win.set_size(width, height)
  149. }
  150. set_window_flags :: proc(flags: Window_Flags) {
  151. win.set_flags(flags)
  152. }
  153. // Flushes the current batch. This sends off everything to the GPU that has been queued in the
  154. // current batch. Normally, you do not need to do this manually. It is done automatically when these
  155. // procedures run:
  156. //
  157. // - present
  158. // - set_camera
  159. // - set_shader
  160. // - set_shader_constant
  161. // - draw_texture_* IF previous draw did not use the same texture (1)
  162. // - draw_rect_*, draw_circle_* IF previous draw did not use the shapes drawing texture (2)
  163. //
  164. // (1) When drawing textures, the current texture is fed into the active shader. Everything within
  165. // the same batch must use the same texture. So drawing with a new texture will draw the current
  166. // batch. You can combine several textures into an atlas to get bigger batches.
  167. //
  168. // (2) In order to use the same shader for shapes drawing and textured drawing, the shapes drawing
  169. // uses a blank, white texture. For the same reasons as (1), drawing something else than shapes
  170. // before drawing a shape will break up the batches. TODO: Add possibility to customize shape
  171. // drawing texture so that you can put it into an atlas.
  172. //
  173. // TODO: Name of this proc? submit_current_batch, flush_current_batch, draw_current_batch
  174. draw_current_batch :: proc() {
  175. shader := s.batch_shader.? or_else s.default_shader
  176. rb.draw(shader, s.batch_texture, s.proj_matrix * s.view_matrix, s.batch_scissor, s.vertex_buffer_cpu[:s.vertex_buffer_cpu_used])
  177. s.vertex_buffer_cpu_used = 0
  178. }
  179. //-------//
  180. // INPUT //
  181. //-------//
  182. // Returns true if a keyboard key went down between the current and the previous frame. Set when
  183. // 'process_events' runs (probably once per frame).
  184. key_went_down :: proc(key: Keyboard_Key) -> bool {
  185. return s.key_went_down[key]
  186. }
  187. // Returns true if a keyboard key went up (was released) between the current and the previous frame.
  188. // Set when 'process_events' runs (probably once per frame).
  189. key_went_up :: proc(key: Keyboard_Key) -> bool {
  190. return s.key_went_up[key]
  191. }
  192. // Returns true if a keyboard is currently being held down. Set when 'process_events' runs (probably
  193. // once per frame).
  194. key_is_held :: proc(key: Keyboard_Key) -> bool {
  195. return s.key_is_held[key]
  196. }
  197. mouse_button_went_down :: proc(button: Mouse_Button) -> bool {
  198. return s.mouse_button_went_down[button]
  199. }
  200. mouse_button_went_up :: proc(button: Mouse_Button) -> bool {
  201. return s.mouse_button_went_up[button]
  202. }
  203. mouse_button_is_held :: proc(button: Mouse_Button) -> bool {
  204. return s.mouse_button_is_held[button]
  205. }
  206. get_mouse_wheel_delta :: proc() -> f32 {
  207. return s.mouse_wheel_delta
  208. }
  209. get_mouse_position :: proc() -> Vec2 {
  210. return s.mouse_position
  211. }
  212. gamepad_button_went_down :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  213. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  214. return false
  215. }
  216. return s.gamepad_button_went_down[gamepad][button]
  217. }
  218. gamepad_button_went_up :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  219. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  220. return false
  221. }
  222. return s.gamepad_button_went_up[gamepad][button]
  223. }
  224. gamepad_button_is_held :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  225. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  226. return false
  227. }
  228. return s.gamepad_button_is_held[gamepad][button]
  229. }
  230. get_gamepad_axis :: proc(gamepad: Gamepad_Index, axis: Gamepad_Axis) -> f32 {
  231. return win.get_gamepad_axis(gamepad, axis)
  232. }
  233. //---------//
  234. // DRAWING //
  235. //---------//
  236. draw_rect :: proc(r: Rect, c: Color) {
  237. if s.batch_texture != TEXTURE_NONE && s.batch_texture != s.shape_drawing_texture {
  238. draw_current_batch()
  239. }
  240. s.batch_texture = s.shape_drawing_texture
  241. batch_vertex({r.x, r.y}, {0, 0}, c)
  242. batch_vertex({r.x + r.w, r.y}, {1, 0}, c)
  243. batch_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
  244. batch_vertex({r.x, r.y}, {0, 0}, c)
  245. batch_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
  246. batch_vertex({r.x, r.y + r.h}, {0, 1}, c)
  247. }
  248. draw_rect_vec :: proc(pos: Vec2, size: Vec2, c: Color) {
  249. draw_rect({pos.x, pos.y, size.x, size.y}, c)
  250. }
  251. draw_rect_ex :: proc(r: Rect, origin: Vec2, rot: f32, c: Color) {
  252. if s.batch_texture != TEXTURE_NONE && s.batch_texture != s.shape_drawing_texture {
  253. draw_current_batch()
  254. }
  255. s.batch_texture = s.shape_drawing_texture
  256. tl, tr, bl, br: Vec2
  257. // Rotation adapted from Raylib's "DrawTexturePro"
  258. if rot == 0 {
  259. x := r.x - origin.x
  260. y := r.y - origin.y
  261. tl = { x, y }
  262. tr = { x + r.w, y }
  263. bl = { x, y + r.h }
  264. br = { x + r.w, y + r.h }
  265. } else {
  266. sin_rot := math.sin(rot * math.RAD_PER_DEG)
  267. cos_rot := math.cos(rot * math.RAD_PER_DEG)
  268. x := r.x
  269. y := r.y
  270. dx := -origin.x
  271. dy := -origin.y
  272. tl = {
  273. x + dx * cos_rot - dy * sin_rot,
  274. y + dx * sin_rot + dy * cos_rot,
  275. }
  276. tr = {
  277. x + (dx + r.w) * cos_rot - dy * sin_rot,
  278. y + (dx + r.w) * sin_rot + dy * cos_rot,
  279. }
  280. bl = {
  281. x + dx * cos_rot - (dy + r.h) * sin_rot,
  282. y + dx * sin_rot + (dy + r.h) * cos_rot,
  283. }
  284. br = {
  285. x + (dx + r.w) * cos_rot - (dy + r.h) * sin_rot,
  286. y + (dx + r.w) * sin_rot + (dy + r.h) * cos_rot,
  287. }
  288. }
  289. batch_vertex(tl, {0, 0}, c)
  290. batch_vertex(tr, {1, 0}, c)
  291. batch_vertex(br, {1, 1}, c)
  292. batch_vertex(tl, {0, 0}, c)
  293. batch_vertex(br, {1, 1}, c)
  294. batch_vertex(bl, {0, 1}, c)
  295. }
  296. draw_rect_outline :: proc(r: Rect, thickness: f32, color: Color) {
  297. t := thickness
  298. // Based on DrawRectangleLinesEx from Raylib
  299. top := Rect {
  300. r.x,
  301. r.y,
  302. r.w,
  303. t,
  304. }
  305. bottom := Rect {
  306. r.x,
  307. r.y + r.h - t,
  308. r.w,
  309. t,
  310. }
  311. left := Rect {
  312. r.x,
  313. r.y + t,
  314. t,
  315. r.h - t * 2,
  316. }
  317. right := Rect {
  318. r.x + r.w - t,
  319. r.y + t,
  320. t,
  321. r.h - t * 2,
  322. }
  323. draw_rect(top, color)
  324. draw_rect(bottom, color)
  325. draw_rect(left, color)
  326. draw_rect(right, color)
  327. }
  328. draw_circle :: proc(center: Vec2, radius: f32, color: Color, segments := 16) {
  329. if s.batch_texture != TEXTURE_NONE && s.batch_texture != s.shape_drawing_texture {
  330. draw_current_batch()
  331. }
  332. s.batch_texture = s.shape_drawing_texture
  333. prev := center + {radius, 0}
  334. for s in 1..=segments {
  335. sr := (f32(s)/f32(segments)) * 2*math.PI
  336. rot := linalg.matrix2_rotate(sr)
  337. p := center + rot * Vec2{radius, 0}
  338. batch_vertex(prev, {0, 0}, color)
  339. batch_vertex(p, {1, 0}, color)
  340. batch_vertex(center, {1, 1}, color)
  341. prev = p
  342. }
  343. }
  344. draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  345. p := Vec2{start.x, start.y + thickness*0.5}
  346. s := Vec2{linalg.length(end - start), thickness}
  347. origin := Vec2 {0, thickness*0.5}
  348. r := Rect {p.x, p.y, s.x, s.y}
  349. rot := math.atan2(end.y - start.y, end.x - start.x)
  350. draw_rect_ex(r, origin, rot * math.DEG_PER_RAD, color)
  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. draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rotation: f32, tint := WHITE) {
  373. if tex.width == 0 || tex.height == 0 {
  374. return
  375. }
  376. if s.batch_texture != TEXTURE_NONE && s.batch_texture != tex.handle {
  377. draw_current_batch()
  378. }
  379. flip_x, flip_y: bool
  380. src := src
  381. dst := dst
  382. if src.w < 0 {
  383. flip_x = true
  384. src.w = -src.w
  385. }
  386. if src.h < 0 {
  387. flip_y = true
  388. src.h = -src.h
  389. }
  390. if dst.w < 0 {
  391. dst.w *= -1
  392. }
  393. if dst.h < 0 {
  394. dst.h *= -1
  395. }
  396. s.batch_texture = tex.handle
  397. tl, tr, bl, br: Vec2
  398. // Rotation adapted from Raylib's "DrawTexturePro"
  399. if rotation == 0 {
  400. x := dst.x - origin.x
  401. y := dst.y - origin.y
  402. tl = { x, y }
  403. tr = { x + dst.w, y }
  404. bl = { x, y + dst.h }
  405. br = { x + dst.w, y + dst.h }
  406. } else {
  407. sin_rot := math.sin(rotation * math.RAD_PER_DEG)
  408. cos_rot := math.cos(rotation * math.RAD_PER_DEG)
  409. x := dst.x
  410. y := dst.y
  411. dx := -origin.x
  412. dy := -origin.y
  413. tl = {
  414. x + dx * cos_rot - dy * sin_rot,
  415. y + dx * sin_rot + dy * cos_rot,
  416. }
  417. tr = {
  418. x + (dx + dst.w) * cos_rot - dy * sin_rot,
  419. y + (dx + dst.w) * sin_rot + dy * cos_rot,
  420. }
  421. bl = {
  422. x + dx * cos_rot - (dy + dst.h) * sin_rot,
  423. y + dx * sin_rot + (dy + dst.h) * cos_rot,
  424. }
  425. br = {
  426. x + (dx + dst.w) * cos_rot - (dy + dst.h) * sin_rot,
  427. y + (dx + dst.w) * sin_rot + (dy + dst.h) * cos_rot,
  428. }
  429. }
  430. ts := Vec2{f32(tex.width), f32(tex.height)}
  431. up := Vec2{src.x, src.y} / ts
  432. us := Vec2{src.w, src.h} / ts
  433. c := tint
  434. uv0 := up
  435. uv1 := up + {us.x, 0}
  436. uv2 := up + us
  437. uv3 := up
  438. uv4 := up + us
  439. uv5 := up + {0, us.y}
  440. if flip_x {
  441. uv0.x += us.x
  442. uv1.x -= us.x
  443. uv2.x -= us.x
  444. uv3.x += us.x
  445. uv4.x -= us.x
  446. uv5.x += us.x
  447. }
  448. if flip_y {
  449. uv0.y += us.y
  450. uv1.y += us.y
  451. uv2.y -= us.y
  452. uv3.y += us.y
  453. uv4.y -= us.y
  454. uv5.y -= us.y
  455. }
  456. batch_vertex(tl, uv0, c)
  457. batch_vertex(tr, uv1, c)
  458. batch_vertex(br, uv2, c)
  459. batch_vertex(tl, uv3, c)
  460. batch_vertex(br, uv4, c)
  461. batch_vertex(bl, uv5, c)
  462. }
  463. draw_text :: proc(text: string, pos: Vec2, font_size: f32, color: Color) {
  464. }
  465. //--------------------//
  466. // TEXTURE MANAGEMENT //
  467. //--------------------//
  468. load_texture_from_file :: proc(filename: string) -> Texture {
  469. img, img_err := image.load_from_file(filename, options = {.alpha_add_if_missing}, allocator = context.temp_allocator)
  470. if img_err != nil {
  471. log.errorf("Error loading texture %v: %v", filename, img_err)
  472. return {}
  473. }
  474. backend_tex := rb.load_texture(img.pixels.buf[:], img.width, img.height)
  475. return {
  476. handle = backend_tex,
  477. width = img.width,
  478. height = img.height,
  479. }
  480. }
  481. destroy_texture :: proc(tex: Texture) {
  482. rb.destroy_texture(tex.handle)
  483. }
  484. //---------//
  485. // SHADERS //
  486. //---------//
  487. load_shader :: proc(shader_source: string, layout_formats: []Pixel_Format = {}) -> Shader {
  488. handle, desc := rb.load_shader(shader_source, context.temp_allocator, layout_formats)
  489. if handle == SHADER_NONE {
  490. log.error("Failed loading shader")
  491. return {}
  492. }
  493. shd := Shader {
  494. handle = handle,
  495. constant_buffers = make([]Shader_Constant_Buffer, len(desc.constant_buffers), s.allocator),
  496. constant_lookup = make(map[string]Shader_Constant_Location, s.allocator),
  497. inputs = slice.clone(desc.inputs, s.allocator),
  498. input_overrides = make([]Shader_Input_Value_Override, len(desc.inputs), s.allocator),
  499. }
  500. for &input in shd.inputs {
  501. input.name = strings.clone(input.name, s.allocator)
  502. }
  503. for cb_idx in 0..<len(desc.constant_buffers) {
  504. cb_desc := &desc.constant_buffers[cb_idx]
  505. shd.constant_buffers[cb_idx] = {
  506. cpu_data = make([]u8, desc.constant_buffers[cb_idx].size, s.allocator),
  507. }
  508. for &v in cb_desc.variables {
  509. if v.name == "" {
  510. continue
  511. }
  512. shd.constant_lookup[strings.clone(v.name, s.allocator)] = v.loc
  513. switch v.name {
  514. case "mvp":
  515. shd.constant_builtin_locations[.MVP] = v.loc
  516. }
  517. }
  518. }
  519. for &d in shd.default_input_offsets {
  520. d = -1
  521. }
  522. input_offset: int
  523. for &input in shd.inputs {
  524. default_format := get_shader_input_default_type(input.name, input.type)
  525. if default_format != .Unknown {
  526. shd.default_input_offsets[default_format] = input_offset
  527. }
  528. input_offset += pixel_format_size(input.format)
  529. }
  530. shd.vertex_size = input_offset
  531. return shd
  532. }
  533. destroy_shader :: proc(shader: Shader) {
  534. rb.destroy_shader(shader.handle)
  535. for c in shader.constant_buffers {
  536. delete(c.cpu_data)
  537. }
  538. delete(shader.constant_buffers)
  539. for k, _ in shader.constant_lookup {
  540. delete(k)
  541. }
  542. delete(shader.constant_lookup)
  543. for i in shader.inputs {
  544. delete(i.name)
  545. }
  546. delete(shader.inputs)
  547. delete(shader.input_overrides)
  548. }
  549. get_default_shader :: proc() -> Shader {
  550. return s.default_shader
  551. }
  552. set_shader :: proc(shader: Maybe(Shader)) {
  553. if maybe_handle_equal(shader, s.batch_shader) {
  554. return
  555. }
  556. draw_current_batch()
  557. s.batch_shader = shader
  558. }
  559. set_shader_constant :: proc(shd: Shader, loc: Shader_Constant_Location, val: any) {
  560. draw_current_batch()
  561. if int(loc.buffer_idx) >= len(shd.constant_buffers) {
  562. log.warnf("Constant buffer idx %v is out of bounds", loc.buffer_idx)
  563. return
  564. }
  565. sz := reflect.size_of_typeid(val.id)
  566. b := &shd.constant_buffers[loc.buffer_idx]
  567. if int(loc.offset) + sz > len(b.cpu_data) {
  568. 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))
  569. return
  570. }
  571. mem.copy(&b.cpu_data[loc.offset], val.data, sz)
  572. }
  573. override_shader_input :: proc(shader: Shader, input: int, val: any) {
  574. sz := reflect.size_of_typeid(val.id)
  575. assert(sz < SHADER_INPUT_VALUE_MAX_SIZE)
  576. if input >= len(shader.input_overrides) {
  577. log.errorf("Input override out of range. Wanted to override input %v, but shader only has %v inputs", input, len(shader.input_overrides))
  578. return
  579. }
  580. o := &shader.input_overrides[input]
  581. o.val = {}
  582. if sz > 0 {
  583. mem.copy(raw_data(&o.val), val.data, sz)
  584. }
  585. o.used = sz
  586. }
  587. pixel_format_size :: proc(f: Pixel_Format) -> int {
  588. switch f {
  589. case .Unknown: return 0
  590. case .RGBA_32_Float: return 32
  591. case .RGB_32_Float: return 12
  592. case .RG_32_Float: return 8
  593. case .R_32_Float: return 4
  594. case .RGBA_8_Norm: return 4
  595. case .RG_8_Norm: return 2
  596. case .R_8_Norm: return 1
  597. }
  598. return 0
  599. }
  600. //-------------------------------//
  601. // CAMERA AND COORDINATE SYSTEMS //
  602. //-------------------------------//
  603. set_camera :: proc(camera: Maybe(Camera)) {
  604. if camera == s.batch_camera {
  605. return
  606. }
  607. draw_current_batch()
  608. s.batch_camera = camera
  609. s.proj_matrix = make_default_projection(s.width, s.height)
  610. if c, c_ok := camera.?; c_ok {
  611. s.view_matrix = get_camera_view_matrix(c)
  612. } else {
  613. s.view_matrix = 1
  614. }
  615. }
  616. screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  617. return (get_camera_world_matrix(camera) * Vec4 { pos.x, pos.y, 0, 1 }).xy
  618. }
  619. world_to_screen :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  620. return (get_camera_view_matrix(camera) * Vec4 { pos.x, pos.y, 0, 1 }).xy
  621. }
  622. get_camera_view_matrix :: proc(c: Camera) -> Mat4 {
  623. inv_target_translate := linalg.matrix4_translate(vec3_from_vec2(-c.target))
  624. inv_rot := linalg.matrix4_rotate_f32(c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  625. inv_scale := linalg.matrix4_scale(Vec3{c.zoom, c.zoom, 1})
  626. inv_offset_translate := linalg.matrix4_translate(vec3_from_vec2(c.offset))
  627. // A view matrix is essentially the world transform matrix of the camera, but inverted. We
  628. // bring everything in the world "in front of the camera".
  629. //
  630. // Instead of constructing the camera matrix and doing a matrix inverse, here we just do the
  631. // maths in "backwards order". I.e. a camera transform matrix would be:
  632. //
  633. // target_translate * rot * scale * offset_translate
  634. return inv_offset_translate * inv_scale * inv_rot * inv_target_translate
  635. }
  636. get_camera_world_matrix :: proc(c: Camera) -> Mat4 {
  637. offset_translate := linalg.matrix4_translate(vec3_from_vec2(-c.offset))
  638. rot := linalg.matrix4_rotate_f32(-c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  639. scale := linalg.matrix4_scale(Vec3{1/c.zoom, 1/c.zoom, 1})
  640. target_translate := linalg.matrix4_translate(vec3_from_vec2(c.target))
  641. return target_translate * rot * scale * offset_translate
  642. }
  643. //------//
  644. // MISC //
  645. //------//
  646. set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  647. draw_current_batch()
  648. s.batch_scissor = scissor_rect
  649. }
  650. // Restore the internal state using the pointer returned by `init`. Useful after reloading the
  651. // library (for example, when doing code hot reload).
  652. set_internal_state :: proc(state: ^State) {
  653. s = state
  654. rb = s.rb
  655. win = s.win
  656. rb.set_internal_state(s.rb_state)
  657. win.set_internal_state(s.window_state)
  658. }
  659. //---------------------//
  660. // TYPES AND CONSTANTS //
  661. //---------------------//
  662. Vec2 :: [2]f32
  663. Vec3 :: [3]f32
  664. Vec4 :: [4]f32
  665. Mat4 :: matrix[4,4]f32
  666. // A two dimensional vector of integer numeric type.
  667. Vec2i :: [2]int
  668. // A rectangle that sits at position (x, y) and has size (w, h).
  669. Rect :: struct {
  670. x, y: f32,
  671. w, h: f32,
  672. }
  673. // An RGBA (Red, Green, Blue, Alpha) color. Each channel can have a value between 0 and 255.
  674. Color :: [4]u8
  675. WHITE :: Color { 255, 255, 255, 255 }
  676. BLACK :: Color { 0, 0, 0, 255 }
  677. GRAY :: Color { 127, 127, 127, 255 }
  678. RED :: Color { 198, 80, 90, 255 }
  679. BLANK :: Color { 0, 0, 0, 0 }
  680. BLUE :: Color { 30, 116, 240, 255 }
  681. // These are from Raylib. They are here so you can easily port a Raylib program to Karl2D.
  682. RL_LIGHTGRAY :: Color { 200, 200, 200, 255 }
  683. RL_GRAY :: Color { 130, 130, 130, 255 }
  684. RL_DARKGRAY :: Color { 80, 80, 80, 255 }
  685. RL_YELLOW :: Color { 253, 249, 0, 255 }
  686. RL_GOLD :: Color { 255, 203, 0, 255 }
  687. RL_ORANGE :: Color { 255, 161, 0, 255 }
  688. RL_PINK :: Color { 255, 109, 194, 255 }
  689. RL_RED :: Color { 230, 41, 55, 255 }
  690. RL_MAROON :: Color { 190, 33, 55, 255 }
  691. RL_GREEN :: Color { 0, 228, 48, 255 }
  692. RL_LIME :: Color { 0, 158, 47, 255 }
  693. RL_DARKGREEN :: Color { 0, 117, 44, 255 }
  694. RL_SKYBLUE :: Color { 102, 191, 255, 255 }
  695. RL_BLUE :: Color { 0, 121, 241, 255 }
  696. RL_DARKBLUE :: Color { 0, 82, 172, 255 }
  697. RL_PURPLE :: Color { 200, 122, 255, 255 }
  698. RL_VIOLET :: Color { 135, 60, 190, 255 }
  699. RL_DARKPURPLE :: Color { 112, 31, 126, 255 }
  700. RL_BEIGE :: Color { 211, 176, 131, 255 }
  701. RL_BROWN :: Color { 127, 106, 79, 255 }
  702. RL_DARKBROWN :: Color { 76, 63, 47, 255 }
  703. RL_WHITE :: WHITE
  704. RL_BLACK :: BLACK
  705. RL_BLANK :: BLANK
  706. RL_MAGENTA :: Color { 255, 0, 255, 255 }
  707. RL_RAYWHITE :: Color { 245, 245, 245, 255 }
  708. Texture :: struct {
  709. handle: Texture_Handle,
  710. width: int,
  711. height: int,
  712. }
  713. Camera :: struct {
  714. target: Vec2,
  715. offset: Vec2,
  716. rotation: f32,
  717. zoom: f32,
  718. }
  719. Window_Flag :: enum {
  720. Resizable,
  721. }
  722. Window_Flags :: bit_set[Window_Flag]
  723. Shader_Handle :: distinct Handle
  724. SHADER_NONE :: Shader_Handle {}
  725. Shader :: struct {
  726. handle: Shader_Handle,
  727. constant_buffers: []Shader_Constant_Buffer,
  728. constant_lookup: map[string]Shader_Constant_Location,
  729. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location),
  730. inputs: []Shader_Input,
  731. input_overrides: []Shader_Input_Value_Override,
  732. default_input_offsets: [Shader_Default_Inputs]int,
  733. vertex_size: int,
  734. }
  735. Shader_Constant_Buffer :: struct {
  736. cpu_data: []u8,
  737. }
  738. SHADER_INPUT_VALUE_MAX_SIZE :: 256
  739. Shader_Input_Value_Override :: struct {
  740. val: [SHADER_INPUT_VALUE_MAX_SIZE]u8,
  741. used: int,
  742. }
  743. Shader_Input_Type :: enum {
  744. F32,
  745. Vec2,
  746. Vec3,
  747. Vec4,
  748. }
  749. Shader_Builtin_Constant :: enum {
  750. MVP,
  751. }
  752. Shader_Default_Inputs :: enum {
  753. Unknown,
  754. Position,
  755. UV,
  756. Color,
  757. }
  758. Shader_Input :: struct {
  759. name: string,
  760. register: int,
  761. type: Shader_Input_Type,
  762. format: Pixel_Format,
  763. }
  764. Shader_Constant_Location :: struct {
  765. buffer_idx: u32,
  766. offset: u32,
  767. }
  768. Pixel_Format :: enum {
  769. Unknown,
  770. RGBA_32_Float,
  771. RGB_32_Float,
  772. RG_32_Float,
  773. R_32_Float,
  774. RGBA_8_Norm,
  775. RG_8_Norm,
  776. R_8_Norm,
  777. }
  778. Handle :: hm.Handle
  779. Texture_Handle :: distinct Handle
  780. TEXTURE_NONE :: Texture_Handle {}
  781. // This keeps track of the internal state of the library. Usually, you do not need to poke at it.
  782. // It is created and kept as a global variable when 'init' is called. However, 'init' also returns
  783. // the pointer to it, so you can later use 'set_internal_state' to restore it (after for example hot
  784. // reload).
  785. State :: struct {
  786. allocator: runtime.Allocator,
  787. custom_context: runtime.Context,
  788. win: Window_Interface,
  789. window_state: rawptr,
  790. rb: Render_Backend_Interface,
  791. rb_state: rawptr,
  792. shutdown_wanted: bool,
  793. mouse_position: Vec2,
  794. mouse_delta: Vec2,
  795. mouse_wheel_delta: f32,
  796. key_went_down: #sparse [Keyboard_Key]bool,
  797. key_went_up: #sparse [Keyboard_Key]bool,
  798. key_is_held: #sparse [Keyboard_Key]bool,
  799. mouse_button_went_down: #sparse [Mouse_Button]bool,
  800. mouse_button_went_up: #sparse [Mouse_Button]bool,
  801. mouse_button_is_held: #sparse [Mouse_Button]bool,
  802. gamepad_button_went_down: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  803. gamepad_button_went_up: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  804. gamepad_button_is_held: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  805. window: Window_Handle,
  806. width: int,
  807. height: int,
  808. shape_drawing_texture: Texture_Handle,
  809. batch_camera: Maybe(Camera),
  810. batch_shader: Maybe(Shader),
  811. batch_scissor: Maybe(Rect),
  812. batch_texture: Texture_Handle,
  813. view_matrix: Mat4,
  814. proj_matrix: Mat4,
  815. vertex_buffer_cpu: []u8,
  816. vertex_buffer_cpu_used: int,
  817. default_shader: Shader,
  818. }
  819. // Support for up to 255 mouse buttons. Cast an int to type `Mouse_Button` to use things outside the
  820. // options presented here.
  821. Mouse_Button :: enum {
  822. Left,
  823. Right,
  824. Middle,
  825. Max = 255,
  826. }
  827. // Based on Raylib / GLFW
  828. Keyboard_Key :: enum {
  829. None = 0,
  830. // Numeric keys (top row)
  831. N0 = 48,
  832. N1 = 49,
  833. N2 = 50,
  834. N3 = 51,
  835. N4 = 52,
  836. N5 = 53,
  837. N6 = 54,
  838. N7 = 55,
  839. N8 = 56,
  840. N9 = 57,
  841. // Letter keys
  842. A = 65,
  843. B = 66,
  844. C = 67,
  845. D = 68,
  846. E = 69,
  847. F = 70,
  848. G = 71,
  849. H = 72,
  850. I = 73,
  851. J = 74,
  852. K = 75,
  853. L = 76,
  854. M = 77,
  855. N = 78,
  856. O = 79,
  857. P = 80,
  858. Q = 81,
  859. R = 82,
  860. S = 83,
  861. T = 84,
  862. U = 85,
  863. V = 86,
  864. W = 87,
  865. X = 88,
  866. Y = 89,
  867. Z = 90,
  868. // Special characters
  869. Apostrophe = 39,
  870. Comma = 44,
  871. Minus = 45,
  872. Period = 46,
  873. Slash = 47,
  874. Semicolon = 59,
  875. Equal = 61,
  876. Left_Bracket = 91,
  877. Backslash = 92,
  878. Right_Bracket = 93,
  879. Grave_Accent = 96,
  880. // Function keys, modifiers, caret control etc
  881. Space = 32,
  882. Escape = 256,
  883. Enter = 257,
  884. Tab = 258,
  885. Backspace = 259,
  886. Insert = 260,
  887. Delete = 261,
  888. Right = 262,
  889. Left = 263,
  890. Down = 264,
  891. Up = 265,
  892. Page_Up = 266,
  893. Page_Down = 267,
  894. Home = 268,
  895. End = 269,
  896. Caps_Lock = 280,
  897. Scroll_Lock = 281,
  898. Num_Lock = 282,
  899. Print_Screen = 283,
  900. Pause = 284,
  901. F1 = 290,
  902. F2 = 291,
  903. F3 = 292,
  904. F4 = 293,
  905. F5 = 294,
  906. F6 = 295,
  907. F7 = 296,
  908. F8 = 297,
  909. F9 = 298,
  910. F10 = 299,
  911. F11 = 300,
  912. F12 = 301,
  913. Left_Shift = 340,
  914. Left_Control = 341,
  915. Left_Alt = 342,
  916. Left_Super = 343,
  917. Right_Shift = 344,
  918. Right_Control = 345,
  919. Right_Alt = 346,
  920. Right_Super = 347,
  921. Menu = 348,
  922. // Numpad keys
  923. NP_0 = 320,
  924. NP_1 = 321,
  925. NP_2 = 322,
  926. NP_3 = 323,
  927. NP_4 = 324,
  928. NP_5 = 325,
  929. NP_6 = 326,
  930. NP_7 = 327,
  931. NP_8 = 328,
  932. NP_9 = 329,
  933. NP_Decimal = 330,
  934. NP_Divide = 331,
  935. NP_Multiply = 332,
  936. NP_Subtract = 333,
  937. NP_Add = 334,
  938. NP_Enter = 335,
  939. NP_Equal = 336,
  940. }
  941. MAX_GAMEPADS :: 4
  942. // A value between 0 and MAX_GAMEPADS - 1
  943. Gamepad_Index :: int
  944. Gamepad_Axis :: enum {
  945. Left_Stick_X,
  946. Left_Stick_Y,
  947. Right_Stick_X,
  948. Right_Stick_Y,
  949. Left_Trigger,
  950. Right_Trigger,
  951. }
  952. Gamepad_Button :: enum {
  953. // DPAD buttons
  954. Left_Face_Up,
  955. Left_Face_Down,
  956. Left_Face_Left,
  957. Left_Face_Right,
  958. Right_Face_Up, // XBOX: Y, PS: Triangle
  959. Right_Face_Down, // XBOX: A, PS: X
  960. Right_Face_Left, // XBOX: X, PS: Square
  961. Right_Face_Right, // XBOX: B, PS: Circle
  962. Left_Shoulder,
  963. Left_Trigger,
  964. Right_Shoulder,
  965. Right_Trigger,
  966. Left_Stick_Press, // Clicking the left analogue stick
  967. Right_Stick_Press, // Clicking the right analogue stick
  968. Middle_Face_Left, // Select / back / options button
  969. Middle_Face_Middle, // PS button (not available on XBox)
  970. Middle_Face_Right, // Start
  971. }
  972. // Used by API builder. Everything after this constant will not be in karl2d.doc.odin
  973. API_END :: true
  974. batch_vertex :: proc(v: Vec2, uv: Vec2, color: Color) {
  975. v := v
  976. if s.vertex_buffer_cpu_used == len(s.vertex_buffer_cpu) {
  977. panic("Must dispatch here")
  978. }
  979. shd := s.batch_shader.? or_else s.default_shader
  980. base_offset := s.vertex_buffer_cpu_used
  981. pos_offset := shd.default_input_offsets[.Position]
  982. uv_offset := shd.default_input_offsets[.UV]
  983. color_offset := shd.default_input_offsets[.Color]
  984. mem.set(&s.vertex_buffer_cpu[base_offset], 0, shd.vertex_size)
  985. if pos_offset != -1 {
  986. (^Vec2)(&s.vertex_buffer_cpu[base_offset + pos_offset])^ = {v.x, v.y}
  987. }
  988. if uv_offset != -1 {
  989. (^Vec2)(&s.vertex_buffer_cpu[base_offset + uv_offset])^ = uv
  990. }
  991. if color_offset != -1 {
  992. (^Color)(&s.vertex_buffer_cpu[base_offset + color_offset])^ = color
  993. }
  994. override_offset: int
  995. for &o, idx in shd.input_overrides {
  996. input := &shd.inputs[idx]
  997. sz := pixel_format_size(input.format)
  998. if o.used != 0 {
  999. mem.copy(&s.vertex_buffer_cpu[base_offset + override_offset], raw_data(&o.val), o.used)
  1000. }
  1001. override_offset += sz
  1002. }
  1003. s.vertex_buffer_cpu_used += shd.vertex_size
  1004. }
  1005. VERTEX_BUFFER_MAX :: 1000000
  1006. DEFAULT_SHADER_SOURCE :: #load("shader.hlsl")
  1007. @(private="file")
  1008. s: ^State
  1009. win: Window_Interface
  1010. rb: Render_Backend_Interface
  1011. maybe_handle_equal :: proc(m1: Maybe($T), m2: Maybe(T)) -> bool {
  1012. if m1 == nil && m2 == nil {
  1013. return true
  1014. }
  1015. m1v, m1v_ok := m1.?
  1016. m2v, m2v_ok := m2.?
  1017. if !m1v_ok || !m2v_ok {
  1018. return false
  1019. }
  1020. return m1v.handle == m2v.handle
  1021. }
  1022. get_shader_input_default_type :: proc(name: string, type: Shader_Input_Type) -> Shader_Default_Inputs {
  1023. if name == "POS" && type == .Vec2 {
  1024. return .Position
  1025. } else if name == "UV" && type == .Vec2 {
  1026. return .UV
  1027. } else if name == "COL" && type == .Vec4 {
  1028. return .Color
  1029. }
  1030. return .Unknown
  1031. }
  1032. get_shader_input_format :: proc(name: string, type: Shader_Input_Type) -> Pixel_Format {
  1033. default_type := get_shader_input_default_type(name, type)
  1034. if default_type != .Unknown {
  1035. switch default_type {
  1036. case .Position: return .RG_32_Float
  1037. case .UV: return .RG_32_Float
  1038. case .Color: return .RGBA_8_Norm
  1039. case .Unknown: unreachable()
  1040. }
  1041. }
  1042. switch type {
  1043. case .F32: return .R_32_Float
  1044. case .Vec2: return .RG_32_Float
  1045. case .Vec3: return .RGB_32_Float
  1046. case .Vec4: return .RGBA_32_Float
  1047. }
  1048. return .Unknown
  1049. }
  1050. vec3_from_vec2 :: proc(v: Vec2) -> Vec3 {
  1051. return {
  1052. v.x, v.y, 0,
  1053. }
  1054. }
  1055. temp_cstring :: proc(str: string, loc := #caller_location) -> cstring {
  1056. return strings.clone_to_cstring(str, context.temp_allocator, loc)
  1057. }
  1058. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  1059. return linalg.matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  1060. }
  1061. _ :: bmp
  1062. _ :: png
  1063. _ :: tga