karl2d.odin 40 KB

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