karl2d.odin 53 KB

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