karl2d.odin 40 KB

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