karl2d.odin 39 KB

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