karl2d.odin 43 KB

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