karl2d.odin 57 KB

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