karl2d.odin 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095
  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 a colored rectangle. The rectangles have their (x, y) position in the top-left corner of the
  399. // rectangle.
  400. draw_rect :: proc(r: Rect, c: Color) {
  401. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  402. draw_current_batch()
  403. }
  404. if s.batch_texture != s.shape_drawing_texture {
  405. draw_current_batch()
  406. }
  407. s.batch_texture = s.shape_drawing_texture
  408. z := get_next_depth()
  409. batch_vertex({r.x, r.y, z}, {0, 0}, c)
  410. batch_vertex({r.x + r.w, r.y, z}, {1, 0}, c)
  411. batch_vertex({r.x + r.w, r.y + r.h, z}, {1, 1}, c)
  412. batch_vertex({r.x, r.y, z}, {0, 0}, c)
  413. batch_vertex({r.x + r.w, r.y + r.h, z}, {1, 1}, c)
  414. batch_vertex({r.x, r.y + r.h, z}, {0, 1}, c)
  415. }
  416. // Creates a rectangle from a position and a size and draws it.
  417. draw_rect_vec :: proc(pos: Vec2, size: Vec2, c: Color) {
  418. draw_rect({pos.x, pos.y, size.x, size.y}, c)
  419. }
  420. // Draw a rectangle with a custom origin and rotation.
  421. // The origin says which point the rotation rotates around. If the origin is `(0, 0)`, then the
  422. // rectangle rotates around the top-left corner of the rectangle. If it is `(rect.w/2, rect.h/2)`
  423. // then the rectangle rotates around its center.
  424. draw_rect_ex :: proc(r: Rect, origin: Vec2, rot: f32, c: Color) {
  425. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  426. draw_current_batch()
  427. }
  428. if s.batch_texture != s.shape_drawing_texture {
  429. draw_current_batch()
  430. }
  431. s.batch_texture = s.shape_drawing_texture
  432. tl, tr, bl, br: Vec2
  433. // Rotation adapted from Raylib's "DrawTexturePro"
  434. if rot == 0 {
  435. x := r.x - origin.x
  436. y := r.y - origin.y
  437. tl = { x, y }
  438. tr = { x + r.w, y }
  439. bl = { x, y + r.h }
  440. br = { x + r.w, y + r.h }
  441. } else {
  442. sin_rot := math.sin(rot * math.RAD_PER_DEG)
  443. cos_rot := math.cos(rot * math.RAD_PER_DEG)
  444. x := r.x
  445. y := r.y
  446. dx := -origin.x
  447. dy := -origin.y
  448. tl = {
  449. x + dx * cos_rot - dy * sin_rot,
  450. y + dx * sin_rot + dy * cos_rot,
  451. }
  452. tr = {
  453. x + (dx + r.w) * cos_rot - dy * sin_rot,
  454. y + (dx + r.w) * sin_rot + dy * cos_rot,
  455. }
  456. bl = {
  457. x + dx * cos_rot - (dy + r.h) * sin_rot,
  458. y + dx * sin_rot + (dy + r.h) * cos_rot,
  459. }
  460. br = {
  461. x + (dx + r.w) * cos_rot - (dy + r.h) * sin_rot,
  462. y + (dx + r.w) * sin_rot + (dy + r.h) * cos_rot,
  463. }
  464. }
  465. z := get_next_depth()
  466. batch_vertex(vec3(tl, z), {0, 0}, c)
  467. batch_vertex(vec3(tr, z), {1, 0}, c)
  468. batch_vertex(vec3(br, z), {1, 1}, c)
  469. batch_vertex(vec3(tl, z), {0, 0}, c)
  470. batch_vertex(vec3(br, z), {1, 1}, c)
  471. batch_vertex(vec3(bl, z), {0, 1}, c)
  472. }
  473. // Draw the outline of a rectangle with a specific thickness. The outline is drawn using four
  474. // rectangles.
  475. draw_rect_outline :: proc(r: Rect, thickness: f32, color: Color) {
  476. t := thickness
  477. // Based on DrawRectangleLinesEx from Raylib
  478. top := Rect {
  479. r.x,
  480. r.y,
  481. r.w,
  482. t,
  483. }
  484. bottom := Rect {
  485. r.x,
  486. r.y + r.h - t,
  487. r.w,
  488. t,
  489. }
  490. left := Rect {
  491. r.x,
  492. r.y + t,
  493. t,
  494. r.h - t * 2,
  495. }
  496. right := Rect {
  497. r.x + r.w - t,
  498. r.y + t,
  499. t,
  500. r.h - t * 2,
  501. }
  502. draw_rect(top, color)
  503. draw_rect(bottom, color)
  504. draw_rect(left, color)
  505. draw_rect(right, color)
  506. }
  507. // Draw a circle with a certain center and radius. Note the `segments` parameter: This circle is not
  508. // perfect! It is drawn using a number of "cake segments".
  509. draw_circle :: proc(center: Vec2, radius: f32, color: Color, segments := 16) {
  510. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 3 * segments > len(s.vertex_buffer_cpu) {
  511. draw_current_batch()
  512. }
  513. if s.batch_texture != s.shape_drawing_texture {
  514. draw_current_batch()
  515. }
  516. s.batch_texture = s.shape_drawing_texture
  517. z := get_next_depth()
  518. prev := center + {radius, 0}
  519. for s in 1..=segments {
  520. sr := (f32(s)/f32(segments)) * 2*math.PI
  521. rot := linalg.matrix2_rotate(sr)
  522. p := center + rot * Vec2{radius, 0}
  523. batch_vertex(vec3(prev, z), {0, 0}, color)
  524. batch_vertex(vec3(p, z), {1, 0}, color)
  525. batch_vertex(vec3(center, z), {1, 1}, color)
  526. prev = p
  527. }
  528. }
  529. // Like `draw_circle` but only draws the outer edge of the circle.
  530. draw_circle_outline :: proc(center: Vec2, radius: f32, thickness: f32, color: Color, segments := 16) {
  531. prev := center + {radius, 0}
  532. for s in 1..=segments {
  533. sr := (f32(s)/f32(segments)) * 2*math.PI
  534. rot := linalg.matrix2_rotate(sr)
  535. p := center + rot * Vec2{radius, 0}
  536. draw_line(prev, p, thickness, color)
  537. prev = p
  538. }
  539. }
  540. // Draws a line from `start` to `end` of a certain thickness.
  541. draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  542. p := Vec2{start.x, start.y + thickness*0.5}
  543. s := Vec2{linalg.length(end - start), thickness}
  544. origin := Vec2 {0, thickness*0.5}
  545. r := Rect {p.x, p.y, s.x, s.y}
  546. rot := math.atan2(end.y - start.y, end.x - start.x)
  547. draw_rect_ex(r, origin, rot * math.DEG_PER_RAD, color)
  548. }
  549. // Draw a texture at a specific position. The texture will be drawn with its top-left corner at
  550. // position `pos`.
  551. //
  552. // Load textures using `load_texture_from_file` or `load_texture_from_bytes`.
  553. draw_texture :: proc(tex: Texture, pos: Vec2, tint := WHITE) {
  554. draw_texture_ex(
  555. tex,
  556. {0, 0, f32(tex.width), f32(tex.height)},
  557. {pos.x, pos.y, f32(tex.width), f32(tex.height)},
  558. {},
  559. 0,
  560. tint,
  561. )
  562. }
  563. // Draw a section of a texture at a specific position. `rect` is a rectangle measured in pixels. It
  564. // tells the procedure which part of the texture to display. The texture will be drawn with its
  565. // top-left corner at position `pos`.
  566. draw_texture_rect :: proc(tex: Texture, rect: Rect, pos: Vec2, tint := WHITE) {
  567. draw_texture_ex(
  568. tex,
  569. rect,
  570. {pos.x, pos.y, rect.w, rect.h},
  571. {},
  572. 0,
  573. tint,
  574. )
  575. }
  576. // Draw a texture by taking a section of the texture specified by `src` and draw it into the area of
  577. // the screen specified by `dst`. You can also rotate the texture around an origin point of your
  578. // choice.
  579. //
  580. // Tip: Use `k2.get_texture_rect(tex)` for `src` if you want to draw the whole texture.
  581. draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rotation: f32, tint := WHITE) {
  582. if tex.width == 0 || tex.height == 0 {
  583. return
  584. }
  585. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  586. draw_current_batch()
  587. }
  588. if s.batch_texture != tex.handle {
  589. draw_current_batch()
  590. }
  591. s.batch_texture = tex.handle
  592. flip_x, flip_y: bool
  593. src := src
  594. dst := dst
  595. if src.w < 0 {
  596. flip_x = true
  597. src.w = -src.w
  598. }
  599. if src.h < 0 {
  600. flip_y = true
  601. src.h = -src.h
  602. }
  603. if dst.w < 0 {
  604. dst.w *= -1
  605. }
  606. if dst.h < 0 {
  607. dst.h *= -1
  608. }
  609. tl, tr, bl, br: Vec2
  610. // Rotation adapted from Raylib's "DrawTexturePro"
  611. if rotation == 0 {
  612. x := dst.x - origin.x
  613. y := dst.y - origin.y
  614. tl = { x, y }
  615. tr = { x + dst.w, y }
  616. bl = { x, y + dst.h }
  617. br = { x + dst.w, y + dst.h }
  618. } else {
  619. sin_rot := math.sin(rotation * math.RAD_PER_DEG)
  620. cos_rot := math.cos(rotation * math.RAD_PER_DEG)
  621. x := dst.x
  622. y := dst.y
  623. dx := -origin.x
  624. dy := -origin.y
  625. tl = {
  626. x + dx * cos_rot - dy * sin_rot,
  627. y + dx * sin_rot + dy * cos_rot,
  628. }
  629. tr = {
  630. x + (dx + dst.w) * cos_rot - dy * sin_rot,
  631. y + (dx + dst.w) * sin_rot + dy * cos_rot,
  632. }
  633. bl = {
  634. x + dx * cos_rot - (dy + dst.h) * sin_rot,
  635. y + dx * sin_rot + (dy + dst.h) * cos_rot,
  636. }
  637. br = {
  638. x + (dx + dst.w) * cos_rot - (dy + dst.h) * sin_rot,
  639. y + (dx + dst.w) * sin_rot + (dy + dst.h) * cos_rot,
  640. }
  641. }
  642. ts := Vec2{f32(tex.width), f32(tex.height)}
  643. up := Vec2{src.x, src.y} / ts
  644. us := Vec2{src.w, src.h} / ts
  645. c := tint
  646. uv0 := up
  647. uv1 := up + {us.x, 0}
  648. uv2 := up + us
  649. uv3 := up
  650. uv4 := up + us
  651. uv5 := up + {0, us.y}
  652. if flip_x {
  653. uv0.x += us.x
  654. uv1.x -= us.x
  655. uv2.x -= us.x
  656. uv3.x += us.x
  657. uv4.x -= us.x
  658. uv5.x += us.x
  659. }
  660. // HACK: We ask the render backend if this texture needs flipping. The idea is that GL will
  661. // flip render textures, so we need to automatically unflip them.
  662. //
  663. // Could we do something with the projection matrix while drawing into those render textures
  664. // instead? I tried that, but couldn't get it to work.
  665. if rb.texture_needs_vertical_flip(tex.handle) {
  666. flip_y = !flip_y
  667. }
  668. if flip_y {
  669. uv0.y += us.y
  670. uv1.y += us.y
  671. uv2.y -= us.y
  672. uv3.y += us.y
  673. uv4.y -= us.y
  674. uv5.y -= us.y
  675. }
  676. z := get_next_depth()
  677. batch_vertex(vec3(tl, z), uv0, c)
  678. batch_vertex(vec3(tr, z), uv1, c)
  679. batch_vertex(vec3(br, z), uv2, c)
  680. batch_vertex(vec3(tl, z), uv3, c)
  681. batch_vertex(vec3(br, z), uv4, c)
  682. batch_vertex(vec3(bl, z), uv5, c)
  683. }
  684. // Tells you how much space some text of a certain size will use on the screen. The font used is the
  685. // default font. The return value contains the width and height of the text.
  686. measure_text :: proc(text: string, font_size: f32) -> Vec2 {
  687. fs.SetSize(&s.fs, font_size)
  688. b: [4]f32
  689. fs.TextBounds(&s.fs, text, bounds = &b)
  690. return {b[2] - b[0], b[3] - b[1]}
  691. }
  692. // Tells you how much space some text of a certain size will use on the screen, using a custom font.
  693. // The return value contains the width and height of the text.
  694. measure_text_ex :: proc(font_handle: Font_Handle, text: string, font_size: f32) -> Vec2 {
  695. _set_font(font_handle)
  696. fs.SetSize(&s.fs, font_size)
  697. b: [4]f32
  698. fs.TextBounds(&s.fs, text, bounds = &b)
  699. return {b[2] - b[0], b[3] - b[1]}
  700. }
  701. // Draw text at a position with a size. This uses the default font. `pos` will be equal to the
  702. // top-left position of the text.
  703. draw_text :: proc(text: string, pos: Vec2, font_size: f32, color := BLACK) {
  704. draw_text_ex(s.default_font, text, pos, font_size, color)
  705. }
  706. // Draw text at a position with a size, using a custom font. `pos` will be equal to the top-left
  707. // position of the text.
  708. draw_text_ex :: proc(font_handle: Font_Handle, text: string, pos: Vec2, font_size: f32, color := BLACK) {
  709. if int(font_handle) >= len(s.fonts) {
  710. return
  711. }
  712. _set_font(font_handle)
  713. font := &s.fonts[font_handle]
  714. fs.SetSize(&s.fs, font_size)
  715. iter := fs.TextIterInit(&s.fs, pos.x, pos.y, text)
  716. q: fs.Quad
  717. for fs.TextIterNext(&s.fs, &iter, &q) {
  718. src := Rect {
  719. q.s0, q.t0,
  720. q.s1 - q.s0, q.t1 - q.t0,
  721. }
  722. w := f32(FONT_DEFAULT_ATLAS_SIZE)
  723. h := f32(FONT_DEFAULT_ATLAS_SIZE)
  724. src.x *= w
  725. src.y *= h
  726. src.w *= w
  727. src.h *= h
  728. dst := Rect {
  729. q.x0, q.y0,
  730. q.x1 - q.x0, q.y1 - q.y0,
  731. }
  732. draw_texture_ex(font.atlas, src, dst, {}, 0, color)
  733. }
  734. }
  735. //--------------------//
  736. // TEXTURE MANAGEMENT //
  737. //--------------------//
  738. // Create an empty texture.
  739. create_texture :: proc(width: int, height: int, format: Pixel_Format) -> Texture {
  740. h := rb.create_texture(width, height, format)
  741. return {
  742. handle = h,
  743. width = width,
  744. height = height,
  745. }
  746. }
  747. // Load a texture from disk and upload it to the GPU so you can draw it to the screen.
  748. // Supports PNG, BMP, TGA and baseline PNG. Note that progressive PNG files are not supported!
  749. //
  750. // The `options` parameter can be used to specify things things such as premultiplication of alpha.
  751. load_texture_from_file :: proc(filename: string, options: Load_Texture_Options = {}) -> Texture {
  752. when FILESYSTEM_SUPPORTED {
  753. load_options := image.Options {
  754. .alpha_add_if_missing,
  755. }
  756. if .Premultiply_Alpha in options {
  757. load_options += { .alpha_premultiply }
  758. }
  759. img, img_err := image.load_from_file(filename, options = load_options, allocator = s.frame_allocator)
  760. if img_err != nil {
  761. log.errorf("Error loading texture %v: %v", filename, img_err)
  762. return {}
  763. }
  764. return load_texture_from_bytes_raw(img.pixels.buf[:], img.width, img.height, .RGBA_8_Norm)
  765. } else {
  766. 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)
  767. return {}
  768. }
  769. }
  770. // Load a texture from a byte slice and upload it to the GPU so you can draw it to the screen.
  771. // Supports PNG, BMP, TGA and baseline PNG. Note that progressive PNG files are not supported!
  772. //
  773. // The `options` parameter can be used to specify things things such as premultiplication of alpha.
  774. load_texture_from_bytes :: proc(bytes: []u8, options: Load_Texture_Options = {}) -> Texture {
  775. load_options := image.Options {
  776. .alpha_add_if_missing,
  777. }
  778. if .Premultiply_Alpha in options {
  779. load_options += { .alpha_premultiply }
  780. }
  781. img, img_err := image.load_from_bytes(bytes, options = load_options, allocator = s.frame_allocator)
  782. if img_err != nil {
  783. log.errorf("Error loading texture: %v", img_err)
  784. return {}
  785. }
  786. return load_texture_from_bytes_raw(img.pixels.buf[:], img.width, img.height, .RGBA_8_Norm)
  787. }
  788. // Load raw texture data. You need to specify the data, size and format of the texture yourself.
  789. // This assumes that there is no header in the data. If your data has a header (you read the data
  790. // from a file on disk), then please use `load_texture_from_bytes` instead.
  791. load_texture_from_bytes_raw :: proc(bytes: []u8, width: int, height: int, format: Pixel_Format) -> Texture {
  792. backend_tex := rb.load_texture(bytes[:], width, height, format)
  793. if backend_tex == TEXTURE_NONE {
  794. return {}
  795. }
  796. return {
  797. handle = backend_tex,
  798. width = width,
  799. height = height,
  800. }
  801. }
  802. // Get a rectangle that spans the whole texture. Coordinates will be (x, y) = (0, 0) and size
  803. // (w, h) = (texture_width, texture_height)
  804. get_texture_rect :: proc(t: Texture) -> Rect {
  805. return {
  806. 0, 0,
  807. f32(t.width), f32(t.height),
  808. }
  809. }
  810. // Update a texture with new pixels. `bytes` is the new pixel data. `rect` is the rectangle in
  811. // `tex` where the new pixels should end up.
  812. update_texture :: proc(tex: Texture, bytes: []u8, rect: Rect) -> bool {
  813. return rb.update_texture(tex.handle, bytes, rect)
  814. }
  815. // Destroy a texture, freeing up any memory it has used on the GPU.
  816. destroy_texture :: proc(tex: Texture) {
  817. rb.destroy_texture(tex.handle)
  818. }
  819. // Controls how a texture should be filtered. You can choose "point" or "linear" filtering. Which
  820. // means "pixly" or "smooth". This filter will be used for up and down-scaling as well as for
  821. // mipmap sampling. Use `set_texture_filter_ex` if you need to control these settings separately.
  822. set_texture_filter :: proc(t: Texture, filter: Texture_Filter) {
  823. set_texture_filter_ex(t, filter, filter, filter)
  824. }
  825. // Controls how a texture should be filtered. `scale_down_filter` and `scale_up_filter` controls how
  826. // the texture is filtered when we render the texture at a smaller or larger size.
  827. // `mip_filter` controls how the texture is filtered when it is sampled using _mipmapping_.
  828. //
  829. // TODO: Add mipmapping generation controls for texture and refer to it from here.
  830. set_texture_filter_ex :: proc(
  831. t: Texture,
  832. scale_down_filter: Texture_Filter,
  833. scale_up_filter: Texture_Filter,
  834. mip_filter: Texture_Filter,
  835. ) {
  836. rb.set_texture_filter(t.handle, scale_down_filter, scale_up_filter, mip_filter)
  837. }
  838. //-----------------//
  839. // RENDER TEXTURES //
  840. //-----------------//
  841. // Create a texture that you can render into. Meaning that you can draw into it instead of drawing
  842. // onto the screen. Use `set_render_texture` to enable this Render Texture for drawing.
  843. create_render_texture :: proc(width: int, height: int) -> Render_Texture {
  844. texture, render_target := rb.create_render_texture(width, height)
  845. return {
  846. texture = {
  847. handle = texture,
  848. width = width,
  849. height = height,
  850. },
  851. render_target = render_target,
  852. }
  853. }
  854. // Destroy a Render_Texture previously created using `create_render_texture`.
  855. destroy_render_texture :: proc(render_texture: Render_Texture) {
  856. rb.destroy_texture(render_texture.texture.handle)
  857. rb.destroy_render_target(render_texture.render_target)
  858. }
  859. // Make all rendering go into a texture instead of onto the screen. Create the render texture using
  860. // `create_render_texture`. Pass `nil` to resume drawing onto the screen.
  861. set_render_texture :: proc(render_texture: Maybe(Render_Texture)) {
  862. if rt, rt_ok := render_texture.?; rt_ok {
  863. if s.batch_render_target == rt.render_target {
  864. return
  865. }
  866. draw_current_batch()
  867. s.batch_render_target = rt.render_target
  868. s.proj_matrix = make_default_projection(rt.texture.width, rt.texture.height)
  869. } else {
  870. if s.batch_render_target == RENDER_TARGET_NONE {
  871. return
  872. }
  873. draw_current_batch()
  874. s.batch_render_target = RENDER_TARGET_NONE
  875. s.proj_matrix = make_default_projection(win.get_width(), win.get_height())
  876. }
  877. }
  878. //-------//
  879. // FONTS //
  880. //-------//
  881. load_font_from_file :: proc(filename: string) -> Font_Handle {
  882. when !FILESYSTEM_SUPPORTED {
  883. 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)
  884. return {}
  885. }
  886. if data, data_ok := os.read_entire_file(filename, frame_allocator); data_ok {
  887. return load_font_from_bytes(data)
  888. }
  889. return FONT_NONE
  890. }
  891. load_font_from_bytes :: proc(data: []u8) -> Font_Handle {
  892. font := fs.AddFontMem(&s.fs, "", data, false)
  893. h := Font_Handle(len(s.fonts))
  894. append(&s.fonts, Font {
  895. fontstash_handle = font,
  896. atlas = {
  897. handle = rb.create_texture(FONT_DEFAULT_ATLAS_SIZE, FONT_DEFAULT_ATLAS_SIZE, .RGBA_8_Norm),
  898. width = FONT_DEFAULT_ATLAS_SIZE,
  899. height = FONT_DEFAULT_ATLAS_SIZE,
  900. },
  901. })
  902. return h
  903. }
  904. destroy_font :: proc(font: Font_Handle) {
  905. if int(font) >= len(s.fonts) {
  906. return
  907. }
  908. f := &s.fonts[font]
  909. rb.destroy_texture(f.atlas.handle)
  910. // TODO fontstash has no "destroy font" proc... I should make my own version of fontstash
  911. delete(s.fs.fonts[f.fontstash_handle].glyphs)
  912. s.fs.fonts[f.fontstash_handle].glyphs = {}
  913. }
  914. get_default_font :: proc() -> Font_Handle {
  915. return s.default_font
  916. }
  917. //---------//
  918. // SHADERS //
  919. //---------//
  920. load_shader_from_file :: proc(
  921. vertex_filename: string,
  922. fragment_filename: string,
  923. layout_formats: []Pixel_Format = {}
  924. ) -> Shader {
  925. vertex_source, vertex_source_ok := os.read_entire_file(vertex_filename, frame_allocator)
  926. if !vertex_source_ok {
  927. log.errorf("Failed loading shader %s", vertex_filename)
  928. return {}
  929. }
  930. fragment_source: []byte
  931. if fragment_filename == vertex_filename {
  932. fragment_source = vertex_source
  933. } else {
  934. fragment_source_ok: bool
  935. fragment_source, fragment_source_ok = os.read_entire_file(fragment_filename, frame_allocator)
  936. if !fragment_source_ok {
  937. log.errorf("Failed loading shader %s", fragment_filename)
  938. return {}
  939. }
  940. }
  941. return load_shader_from_bytes(vertex_source, fragment_source, layout_formats)
  942. }
  943. load_shader_from_bytes :: proc(
  944. vertex_shader_bytes: []byte,
  945. fragment_shader_bytes: []byte,
  946. layout_formats: []Pixel_Format = {},
  947. ) -> Shader {
  948. handle, desc := rb.load_shader(
  949. vertex_shader_bytes,
  950. fragment_shader_bytes,
  951. s.frame_allocator,
  952. layout_formats,
  953. )
  954. if handle == SHADER_NONE {
  955. log.error("Failed loading shader")
  956. return {}
  957. }
  958. constants_size: int
  959. for c in desc.constants {
  960. constants_size += c.size
  961. }
  962. shd := Shader {
  963. handle = handle,
  964. constants_data = make([]u8, constants_size, s.allocator),
  965. constants = make([]Shader_Constant_Location, len(desc.constants), s.allocator),
  966. constant_lookup = make(map[string]Shader_Constant_Location, s.allocator),
  967. inputs = slice.clone(desc.inputs, s.allocator),
  968. input_overrides = make([]Shader_Input_Value_Override, len(desc.inputs), s.allocator),
  969. texture_bindpoints = make([]Texture_Handle, len(desc.texture_bindpoints), s.allocator),
  970. texture_lookup = make(map[string]int, s.allocator),
  971. }
  972. for &input in shd.inputs {
  973. input.name = strings.clone(input.name, s.allocator)
  974. }
  975. constant_offset: int
  976. for cidx in 0..<len(desc.constants) {
  977. constant_desc := &desc.constants[cidx]
  978. loc := Shader_Constant_Location {
  979. offset = constant_offset,
  980. size = constant_desc.size,
  981. }
  982. shd.constants[cidx] = loc
  983. constant_offset += constant_desc.size
  984. if constant_desc.name != "" {
  985. shd.constant_lookup[strings.clone(constant_desc.name, s.allocator)] = loc
  986. switch constant_desc.name {
  987. case "mvp":
  988. shd.constant_builtin_locations[.MVP] = loc
  989. }
  990. }
  991. }
  992. for tbp, tbp_idx in desc.texture_bindpoints {
  993. shd.texture_lookup[tbp.name] = tbp_idx
  994. if tbp.name == "tex" {
  995. shd.default_texture_index = tbp_idx
  996. }
  997. }
  998. for &d in shd.default_input_offsets {
  999. d = -1
  1000. }
  1001. input_offset: int
  1002. for &input in shd.inputs {
  1003. default_format := get_shader_input_default_type(input.name, input.type)
  1004. if default_format != .Unknown {
  1005. shd.default_input_offsets[default_format] = input_offset
  1006. }
  1007. input_offset += pixel_format_size(input.format)
  1008. }
  1009. shd.vertex_size = input_offset
  1010. return shd
  1011. }
  1012. destroy_shader :: proc(shader: Shader) {
  1013. rb.destroy_shader(shader.handle)
  1014. a := s.allocator
  1015. delete(shader.constants_data, a)
  1016. delete(shader.constants, a)
  1017. delete(shader.texture_lookup)
  1018. delete(shader.texture_bindpoints, a)
  1019. for k, _ in shader.constant_lookup {
  1020. delete(k, a)
  1021. }
  1022. delete(shader.constant_lookup)
  1023. for i in shader.inputs {
  1024. delete(i.name, a)
  1025. }
  1026. delete(shader.inputs, a)
  1027. delete(shader.input_overrides, a)
  1028. }
  1029. get_default_shader :: proc() -> Shader {
  1030. return s.default_shader
  1031. }
  1032. set_shader :: proc(shader: Maybe(Shader)) {
  1033. if shd, shd_ok := shader.?; shd_ok {
  1034. if shd.handle == s.batch_shader.handle {
  1035. return
  1036. }
  1037. } else {
  1038. if s.batch_shader.handle == s.default_shader.handle {
  1039. return
  1040. }
  1041. }
  1042. draw_current_batch()
  1043. s.batch_shader = shader.? or_else s.default_shader
  1044. }
  1045. set_shader_constant :: proc(shd: Shader, loc: Shader_Constant_Location, val: any) {
  1046. if shd.handle == SHADER_NONE {
  1047. log.error("Invalid shader")
  1048. return
  1049. }
  1050. if loc.size == 0 {
  1051. log.error("Could not find shader constant")
  1052. return
  1053. }
  1054. draw_current_batch()
  1055. if loc.offset + loc.size > len(shd.constants_data) {
  1056. 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))
  1057. return
  1058. }
  1059. sz := reflect.size_of_typeid(val.id)
  1060. if sz != loc.size {
  1061. log.errorf("Trying to set constant of type %v, but it is not of correct size %v", val.id, loc.size)
  1062. return
  1063. }
  1064. mem.copy(&shd.constants_data[loc.offset], val.data, sz)
  1065. }
  1066. override_shader_input :: proc(shader: Shader, input: int, val: any) {
  1067. sz := reflect.size_of_typeid(val.id)
  1068. assert(sz < SHADER_INPUT_VALUE_MAX_SIZE)
  1069. if input >= len(shader.input_overrides) {
  1070. log.errorf("Input override out of range. Wanted to override input %v, but shader only has %v inputs", input, len(shader.input_overrides))
  1071. return
  1072. }
  1073. o := &shader.input_overrides[input]
  1074. o.val = {}
  1075. if sz > 0 {
  1076. mem.copy(raw_data(&o.val), val.data, sz)
  1077. }
  1078. o.used = sz
  1079. }
  1080. pixel_format_size :: proc(f: Pixel_Format) -> int {
  1081. switch f {
  1082. case .Unknown: return 0
  1083. case .RGBA_32_Float: return 32
  1084. case .RGB_32_Float: return 12
  1085. case .RG_32_Float: return 8
  1086. case .R_32_Float: return 4
  1087. case .RGBA_8_Norm: return 4
  1088. case .RG_8_Norm: return 2
  1089. case .R_8_Norm: return 1
  1090. case .R_8_UInt: return 1
  1091. }
  1092. return 0
  1093. }
  1094. //-------------------------------//
  1095. // CAMERA AND COORDINATE SYSTEMS //
  1096. //-------------------------------//
  1097. set_camera :: proc(camera: Maybe(Camera)) {
  1098. if camera == s.batch_camera {
  1099. return
  1100. }
  1101. draw_current_batch()
  1102. s.batch_camera = camera
  1103. s.proj_matrix = make_default_projection(win.get_width(), win.get_height())
  1104. if c, c_ok := camera.?; c_ok {
  1105. s.view_matrix = get_camera_view_matrix(c)
  1106. } else {
  1107. s.view_matrix = 1
  1108. }
  1109. }
  1110. screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  1111. return (get_camera_world_matrix(camera) * Vec4 { pos.x, pos.y, 0, 1 }).xy
  1112. }
  1113. world_to_screen :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  1114. return (get_camera_view_matrix(camera) * Vec4 { pos.x, pos.y, 0, 1 }).xy
  1115. }
  1116. get_camera_view_matrix :: proc(c: Camera) -> Mat4 {
  1117. inv_target_translate := linalg.matrix4_translate(vec3_from_vec2(-c.target))
  1118. inv_rot := linalg.matrix4_rotate_f32(c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  1119. inv_scale := linalg.matrix4_scale(Vec3{c.zoom, c.zoom, 1})
  1120. inv_offset_translate := linalg.matrix4_translate(vec3_from_vec2(c.offset))
  1121. // A view matrix is essentially the world transform matrix of the camera, but inverted. We
  1122. // bring everything in the world "in front of the camera".
  1123. //
  1124. // Instead of constructing the camera matrix and doing a matrix inverse, here we just do the
  1125. // maths in "backwards order". I.e. a camera transform matrix would be:
  1126. //
  1127. // target_translate * rot * scale * offset_translate
  1128. return inv_offset_translate * inv_scale * inv_rot * inv_target_translate
  1129. }
  1130. get_camera_world_matrix :: proc(c: Camera) -> Mat4 {
  1131. offset_translate := linalg.matrix4_translate(vec3_from_vec2(-c.offset))
  1132. rot := linalg.matrix4_rotate_f32(-c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  1133. scale := linalg.matrix4_scale(Vec3{1/c.zoom, 1/c.zoom, 1})
  1134. target_translate := linalg.matrix4_translate(vec3_from_vec2(c.target))
  1135. return target_translate * rot * scale * offset_translate
  1136. }
  1137. //------//
  1138. // MISC //
  1139. //------//
  1140. // Choose how the alpha channel is used when mixing half-transparent color with what is already
  1141. // drawn. The default is the .Alpha mode, but you also have the option of using .Premultiply_Alpha.
  1142. set_blend_mode :: proc(mode: Blend_Mode) {
  1143. if s.batch_blend_mode == mode {
  1144. return
  1145. }
  1146. draw_current_batch()
  1147. s.batch_blend_mode = mode
  1148. }
  1149. set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  1150. draw_current_batch()
  1151. s.batch_scissor = scissor_rect
  1152. }
  1153. // Restore the internal state using the pointer returned by `init`. Useful after reloading the
  1154. // library (for example, when doing code hot reload).
  1155. set_internal_state :: proc(state: ^State) {
  1156. s = state
  1157. rb = s.rb
  1158. win = s.win
  1159. rb.set_internal_state(s.rb_state)
  1160. win.set_internal_state(s.window_state)
  1161. }
  1162. //---------------------//
  1163. // TYPES AND CONSTANTS //
  1164. //---------------------//
  1165. Vec2 :: [2]f32
  1166. Vec3 :: [3]f32
  1167. Vec4 :: [4]f32
  1168. Mat4 :: matrix[4,4]f32
  1169. // A rectangle that sits at position (x, y) and has size (w, h).
  1170. Rect :: struct {
  1171. x, y: f32,
  1172. w, h: f32,
  1173. }
  1174. // An RGBA (Red, Green, Blue, Alpha) color. Each channel can have a value between 0 and 255.
  1175. Color :: [4]u8
  1176. WHITE :: Color { 255, 255, 255, 255 }
  1177. BLACK :: Color { 0, 0, 0, 255 }
  1178. GRAY :: Color { 127, 127, 127, 255 }
  1179. RED :: Color { 198, 40, 90, 255 }
  1180. GREEN :: Color { 30, 240, 30, 255 }
  1181. YELLOW :: Color {240, 190, 0, 255 }
  1182. BLANK :: Color { 0, 0, 0, 0 }
  1183. BLUE :: Color { 30, 116, 240, 255 }
  1184. // These are from Raylib. They are here so you can easily port a Raylib program to Karl2D.
  1185. RL_LIGHTGRAY :: Color { 200, 200, 200, 255 }
  1186. RL_GRAY :: Color { 130, 130, 130, 255 }
  1187. RL_DARKGRAY :: Color { 80, 80, 80, 255 }
  1188. RL_YELLOW :: Color { 253, 249, 0, 255 }
  1189. RL_GOLD :: Color { 255, 203, 0, 255 }
  1190. RL_ORANGE :: Color { 255, 161, 0, 255 }
  1191. RL_PINK :: Color { 255, 109, 194, 255 }
  1192. RL_RED :: Color { 230, 41, 55, 255 }
  1193. RL_MAROON :: Color { 190, 33, 55, 255 }
  1194. RL_GREEN :: Color { 0, 228, 48, 255 }
  1195. RL_LIME :: Color { 0, 158, 47, 255 }
  1196. RL_DARKGREEN :: Color { 0, 117, 44, 255 }
  1197. RL_SKYBLUE :: Color { 102, 191, 255, 255 }
  1198. RL_BLUE :: Color { 0, 121, 241, 255 }
  1199. RL_DARKBLUE :: Color { 0, 82, 172, 255 }
  1200. RL_PURPLE :: Color { 200, 122, 255, 255 }
  1201. RL_VIOLET :: Color { 135, 60, 190, 255 }
  1202. RL_DARKPURPLE :: Color { 112, 31, 126, 255 }
  1203. RL_BEIGE :: Color { 211, 176, 131, 255 }
  1204. RL_BROWN :: Color { 127, 106, 79, 255 }
  1205. RL_DARKBROWN :: Color { 76, 63, 47, 255 }
  1206. RL_WHITE :: WHITE
  1207. RL_BLACK :: BLACK
  1208. RL_BLANK :: BLANK
  1209. RL_MAGENTA :: Color { 255, 0, 255, 255 }
  1210. RL_RAYWHITE :: Color { 245, 245, 245, 255 }
  1211. Texture :: struct {
  1212. handle: Texture_Handle,
  1213. width: int,
  1214. height: int,
  1215. }
  1216. Load_Texture_Option :: enum {
  1217. Premultiply_Alpha,
  1218. }
  1219. Load_Texture_Options :: bit_set[Load_Texture_Option]
  1220. Blend_Mode :: enum {
  1221. Alpha,
  1222. Premultiplied_Alpha, // Requires the alpha-channel to be multiplied into texture RGB channels.
  1223. }
  1224. Render_Texture :: struct {
  1225. texture: Texture,
  1226. render_target: Render_Target_Handle,
  1227. }
  1228. Texture_Filter :: enum {
  1229. Point, // Similar to "nearest neighbor". Pixly texture scaling.
  1230. Linear, // Smoothed texture scaling.
  1231. }
  1232. Camera :: struct {
  1233. target: Vec2,
  1234. offset: Vec2,
  1235. rotation: f32,
  1236. zoom: f32,
  1237. }
  1238. Window_Flag :: enum {
  1239. Resizable,
  1240. }
  1241. Window_Flags :: bit_set[Window_Flag]
  1242. Shader_Handle :: distinct Handle
  1243. SHADER_NONE :: Shader_Handle {}
  1244. Shader_Constant_Location :: struct {
  1245. offset: int,
  1246. size: int,
  1247. }
  1248. Shader :: struct {
  1249. handle: Shader_Handle,
  1250. // We store the CPU-side value of all constants in a single buffer to have less allocations.
  1251. // The 'constants' array says where in this buffer each constant is, and 'constant_lookup'
  1252. // maps a name to a constant location.
  1253. constants_data: []u8,
  1254. constants: []Shader_Constant_Location,
  1255. constant_lookup: map[string]Shader_Constant_Location,
  1256. // Maps built in constant types such as "model view projection matrix" to a location.
  1257. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location),
  1258. texture_bindpoints: []Texture_Handle,
  1259. texture_lookup: map[string]int,
  1260. default_texture_index: Maybe(int),
  1261. inputs: []Shader_Input,
  1262. input_overrides: []Shader_Input_Value_Override,
  1263. default_input_offsets: [Shader_Default_Inputs]int,
  1264. vertex_size: int,
  1265. }
  1266. SHADER_INPUT_VALUE_MAX_SIZE :: 256
  1267. Shader_Input_Value_Override :: struct {
  1268. val: [SHADER_INPUT_VALUE_MAX_SIZE]u8,
  1269. used: int,
  1270. }
  1271. Shader_Input_Type :: enum {
  1272. F32,
  1273. Vec2,
  1274. Vec3,
  1275. Vec4,
  1276. }
  1277. Shader_Builtin_Constant :: enum {
  1278. MVP,
  1279. }
  1280. Shader_Default_Inputs :: enum {
  1281. Unknown,
  1282. Position,
  1283. UV,
  1284. Color,
  1285. }
  1286. Shader_Input :: struct {
  1287. name: string,
  1288. register: int,
  1289. type: Shader_Input_Type,
  1290. format: Pixel_Format,
  1291. }
  1292. Pixel_Format :: enum {
  1293. Unknown,
  1294. RGBA_32_Float,
  1295. RGB_32_Float,
  1296. RG_32_Float,
  1297. R_32_Float,
  1298. RGBA_8_Norm,
  1299. RG_8_Norm,
  1300. R_8_Norm,
  1301. R_8_UInt,
  1302. }
  1303. Font :: struct {
  1304. atlas: Texture,
  1305. // internal
  1306. fontstash_handle: int,
  1307. }
  1308. Handle :: hm.Handle
  1309. Texture_Handle :: distinct Handle
  1310. Render_Target_Handle :: distinct Handle
  1311. Font_Handle :: distinct int
  1312. FONT_NONE :: Font_Handle {}
  1313. TEXTURE_NONE :: Texture_Handle {}
  1314. RENDER_TARGET_NONE :: Render_Target_Handle {}
  1315. // This keeps track of the internal state of the library. Usually, you do not need to poke at it.
  1316. // It is created and kept as a global variable when 'init' is called. However, 'init' also returns
  1317. // the pointer to it, so you can later use 'set_internal_state' to restore it (after for example hot
  1318. // reload).
  1319. State :: struct {
  1320. allocator: runtime.Allocator,
  1321. frame_arena: runtime.Arena,
  1322. frame_allocator: runtime.Allocator,
  1323. win: Window_Interface,
  1324. window_state: rawptr,
  1325. rb: Render_Backend_Interface,
  1326. rb_state: rawptr,
  1327. fs: fs.FontContext,
  1328. shutdown_wanted: bool,
  1329. mouse_position: Vec2,
  1330. mouse_delta: Vec2,
  1331. mouse_wheel_delta: f32,
  1332. key_went_down: #sparse [Keyboard_Key]bool,
  1333. key_went_up: #sparse [Keyboard_Key]bool,
  1334. key_is_held: #sparse [Keyboard_Key]bool,
  1335. mouse_button_went_down: #sparse [Mouse_Button]bool,
  1336. mouse_button_went_up: #sparse [Mouse_Button]bool,
  1337. mouse_button_is_held: #sparse [Mouse_Button]bool,
  1338. gamepad_button_went_down: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1339. gamepad_button_went_up: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1340. gamepad_button_is_held: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1341. window: Window_Handle,
  1342. default_font: Font_Handle,
  1343. fonts: [dynamic]Font,
  1344. shape_drawing_texture: Texture_Handle,
  1345. batch_font: Font_Handle,
  1346. batch_camera: Maybe(Camera),
  1347. batch_shader: Shader,
  1348. batch_scissor: Maybe(Rect),
  1349. batch_texture: Texture_Handle,
  1350. batch_render_target: Render_Target_Handle,
  1351. batch_blend_mode: Blend_Mode,
  1352. view_matrix: Mat4,
  1353. proj_matrix: Mat4,
  1354. depth: f32,
  1355. depth_start: f32,
  1356. depth_increment: f32,
  1357. vertex_buffer_cpu: []u8,
  1358. vertex_buffer_cpu_used: int,
  1359. default_shader: Shader,
  1360. // Time when the first call to `new_frame` happened
  1361. start_time: time.Time,
  1362. prev_frame_time: time.Time,
  1363. // "dt"
  1364. frame_time: f32,
  1365. time: f64,
  1366. }
  1367. // Support for up to 255 mouse buttons. Cast an int to type `Mouse_Button` to use things outside the
  1368. // options presented here.
  1369. Mouse_Button :: enum {
  1370. Left,
  1371. Right,
  1372. Middle,
  1373. Max = 255,
  1374. }
  1375. // Based on Raylib / GLFW
  1376. Keyboard_Key :: enum {
  1377. None = 0,
  1378. // Numeric keys (top row)
  1379. N0 = 48,
  1380. N1 = 49,
  1381. N2 = 50,
  1382. N3 = 51,
  1383. N4 = 52,
  1384. N5 = 53,
  1385. N6 = 54,
  1386. N7 = 55,
  1387. N8 = 56,
  1388. N9 = 57,
  1389. // Letter keys
  1390. A = 65,
  1391. B = 66,
  1392. C = 67,
  1393. D = 68,
  1394. E = 69,
  1395. F = 70,
  1396. G = 71,
  1397. H = 72,
  1398. I = 73,
  1399. J = 74,
  1400. K = 75,
  1401. L = 76,
  1402. M = 77,
  1403. N = 78,
  1404. O = 79,
  1405. P = 80,
  1406. Q = 81,
  1407. R = 82,
  1408. S = 83,
  1409. T = 84,
  1410. U = 85,
  1411. V = 86,
  1412. W = 87,
  1413. X = 88,
  1414. Y = 89,
  1415. Z = 90,
  1416. // Special characters
  1417. Apostrophe = 39,
  1418. Comma = 44,
  1419. Minus = 45,
  1420. Period = 46,
  1421. Slash = 47,
  1422. Semicolon = 59,
  1423. Equal = 61,
  1424. Left_Bracket = 91,
  1425. Backslash = 92,
  1426. Right_Bracket = 93,
  1427. Backtick = 96,
  1428. // Function keys, modifiers, caret control etc
  1429. Space = 32,
  1430. Escape = 256,
  1431. Enter = 257,
  1432. Tab = 258,
  1433. Backspace = 259,
  1434. Insert = 260,
  1435. Delete = 261,
  1436. Right = 262,
  1437. Left = 263,
  1438. Down = 264,
  1439. Up = 265,
  1440. Page_Up = 266,
  1441. Page_Down = 267,
  1442. Home = 268,
  1443. End = 269,
  1444. Caps_Lock = 280,
  1445. Scroll_Lock = 281,
  1446. Num_Lock = 282,
  1447. Print_Screen = 283,
  1448. Pause = 284,
  1449. F1 = 290,
  1450. F2 = 291,
  1451. F3 = 292,
  1452. F4 = 293,
  1453. F5 = 294,
  1454. F6 = 295,
  1455. F7 = 296,
  1456. F8 = 297,
  1457. F9 = 298,
  1458. F10 = 299,
  1459. F11 = 300,
  1460. F12 = 301,
  1461. Left_Shift = 340,
  1462. Left_Control = 341,
  1463. Left_Alt = 342,
  1464. Left_Super = 343,
  1465. Right_Shift = 344,
  1466. Right_Control = 345,
  1467. Right_Alt = 346,
  1468. Right_Super = 347,
  1469. Menu = 348,
  1470. // Numpad keys
  1471. NP_0 = 320,
  1472. NP_1 = 321,
  1473. NP_2 = 322,
  1474. NP_3 = 323,
  1475. NP_4 = 324,
  1476. NP_5 = 325,
  1477. NP_6 = 326,
  1478. NP_7 = 327,
  1479. NP_8 = 328,
  1480. NP_9 = 329,
  1481. NP_Decimal = 330,
  1482. NP_Divide = 331,
  1483. NP_Multiply = 332,
  1484. NP_Subtract = 333,
  1485. NP_Add = 334,
  1486. NP_Enter = 335,
  1487. NP_Equal = 336,
  1488. }
  1489. MAX_GAMEPADS :: 4
  1490. // A value between 0 and MAX_GAMEPADS - 1
  1491. Gamepad_Index :: int
  1492. Gamepad_Axis :: enum {
  1493. Left_Stick_X,
  1494. Left_Stick_Y,
  1495. Right_Stick_X,
  1496. Right_Stick_Y,
  1497. Left_Trigger,
  1498. Right_Trigger,
  1499. }
  1500. Gamepad_Button :: enum {
  1501. // DPAD buttons
  1502. Left_Face_Up,
  1503. Left_Face_Down,
  1504. Left_Face_Left,
  1505. Left_Face_Right,
  1506. Right_Face_Up, // XBOX: Y, PS: Triangle
  1507. Right_Face_Down, // XBOX: A, PS: X
  1508. Right_Face_Left, // XBOX: X, PS: Square
  1509. Right_Face_Right, // XBOX: B, PS: Circle
  1510. Left_Shoulder,
  1511. Left_Trigger,
  1512. Right_Shoulder,
  1513. Right_Trigger,
  1514. Left_Stick_Press, // Clicking the left analogue stick
  1515. Right_Stick_Press, // Clicking the right analogue stick
  1516. Middle_Face_Left, // Select / back / options button
  1517. Middle_Face_Middle, // PS button (not available on XBox)
  1518. Middle_Face_Right, // Start
  1519. }
  1520. // Used by API builder. Everything after this constant will not be in karl2d.doc.odin
  1521. API_END :: true
  1522. batch_vertex :: proc(v: Vec3, uv: Vec2, color: Color) {
  1523. v := v
  1524. if s.vertex_buffer_cpu_used == len(s.vertex_buffer_cpu) {
  1525. draw_current_batch()
  1526. }
  1527. shd := s.batch_shader
  1528. base_offset := s.vertex_buffer_cpu_used
  1529. pos_offset := shd.default_input_offsets[.Position]
  1530. uv_offset := shd.default_input_offsets[.UV]
  1531. color_offset := shd.default_input_offsets[.Color]
  1532. mem.set(&s.vertex_buffer_cpu[base_offset], 0, shd.vertex_size)
  1533. if pos_offset != -1 {
  1534. (^Vec3)(&s.vertex_buffer_cpu[base_offset + pos_offset])^ = v
  1535. }
  1536. if uv_offset != -1 {
  1537. (^Vec2)(&s.vertex_buffer_cpu[base_offset + uv_offset])^ = uv
  1538. }
  1539. if color_offset != -1 {
  1540. (^Color)(&s.vertex_buffer_cpu[base_offset + color_offset])^ = color
  1541. }
  1542. override_offset: int
  1543. for &o, idx in shd.input_overrides {
  1544. input := &shd.inputs[idx]
  1545. sz := pixel_format_size(input.format)
  1546. if o.used != 0 {
  1547. mem.copy(&s.vertex_buffer_cpu[base_offset + override_offset], raw_data(&o.val), o.used)
  1548. }
  1549. override_offset += sz
  1550. }
  1551. s.vertex_buffer_cpu_used += shd.vertex_size
  1552. }
  1553. VERTEX_BUFFER_MAX :: 1000000
  1554. @(private="file")
  1555. s: ^State
  1556. // These globals are here for access from other files. The state struct above is private to make
  1557. // sure global state sharing doesn't become too messy.
  1558. frame_allocator: runtime.Allocator
  1559. win: Window_Interface
  1560. rb: Render_Backend_Interface
  1561. get_shader_input_default_type :: proc(name: string, type: Shader_Input_Type) -> Shader_Default_Inputs {
  1562. if name == "position" && type == .Vec3 {
  1563. return .Position
  1564. } else if name == "texcoord" && type == .Vec2 {
  1565. return .UV
  1566. } else if name == "color" && type == .Vec4 {
  1567. return .Color
  1568. }
  1569. return .Unknown
  1570. }
  1571. get_shader_format_num_components :: proc(format: Pixel_Format) -> int {
  1572. switch format {
  1573. case .Unknown: return 0
  1574. case .RGBA_32_Float: return 4
  1575. case .RGB_32_Float: return 3
  1576. case .RG_32_Float: return 2
  1577. case .R_32_Float: return 1
  1578. case .RGBA_8_Norm: return 4
  1579. case .RG_8_Norm: return 2
  1580. case .R_8_Norm: return 1
  1581. case .R_8_UInt: return 1
  1582. }
  1583. return 0
  1584. }
  1585. get_shader_input_format :: proc(name: string, type: Shader_Input_Type) -> Pixel_Format {
  1586. default_type := get_shader_input_default_type(name, type)
  1587. if default_type != .Unknown {
  1588. switch default_type {
  1589. case .Position: return .RGB_32_Float
  1590. case .UV: return .RG_32_Float
  1591. case .Color: return .RGBA_8_Norm
  1592. case .Unknown: unreachable()
  1593. }
  1594. }
  1595. switch type {
  1596. case .F32: return .R_32_Float
  1597. case .Vec2: return .RG_32_Float
  1598. case .Vec3: return .RGB_32_Float
  1599. case .Vec4: return .RGBA_32_Float
  1600. }
  1601. return .Unknown
  1602. }
  1603. vec3_from_vec2 :: proc(v: Vec2) -> Vec3 {
  1604. return {
  1605. v.x, v.y, 0,
  1606. }
  1607. }
  1608. frame_cstring :: proc(str: string, loc := #caller_location) -> cstring {
  1609. return strings.clone_to_cstring(str, s.frame_allocator, loc)
  1610. }
  1611. @(require_results)
  1612. matrix_ortho3d_f32 :: proc "contextless" (left, right, bottom, top, near, far: f32) -> Mat4 #no_bounds_check {
  1613. m: Mat4
  1614. m[0, 0] = +2 / (right - left)
  1615. m[1, 1] = +2 / (top - bottom)
  1616. m[2, 2] = +1
  1617. m[0, 3] = -(right + left) / (right - left)
  1618. m[1, 3] = -(top + bottom) / (top - bottom)
  1619. m[2, 3] = 0
  1620. m[3, 3] = 1
  1621. return m
  1622. }
  1623. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  1624. return matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  1625. }
  1626. FONT_DEFAULT_ATLAS_SIZE :: 1024
  1627. _update_font :: proc(fh: Font_Handle) {
  1628. font := &s.fonts[fh]
  1629. font_dirty_rect: [4]f32
  1630. tw := FONT_DEFAULT_ATLAS_SIZE
  1631. if fs.ValidateTexture(&s.fs, &font_dirty_rect) {
  1632. fdr := font_dirty_rect
  1633. r := Rect {
  1634. fdr[0],
  1635. fdr[1],
  1636. fdr[2] - fdr[0],
  1637. fdr[3] - fdr[1],
  1638. }
  1639. x := int(r.x)
  1640. y := int(r.y)
  1641. w := int(fdr[2]) - int(fdr[0])
  1642. h := int(fdr[3]) - int(fdr[1])
  1643. expanded_pixels := make([]Color, w * h, frame_allocator)
  1644. start := x + tw * y
  1645. for i in 0..<w*h {
  1646. px := i%w
  1647. py := i/w
  1648. dst_pixel_idx := (px) + (py * w)
  1649. src_pixel_idx := start + (px) + (py * tw)
  1650. src := s.fs.textureData[src_pixel_idx]
  1651. expanded_pixels[dst_pixel_idx] = {255,255,255, src}
  1652. }
  1653. rb.update_texture(font.atlas.handle, slice.reinterpret([]u8, expanded_pixels), r)
  1654. }
  1655. }
  1656. // Not for direct use. Specify font to `draw_text_ex`
  1657. _set_font :: proc(fh: Font_Handle) {
  1658. fh := fh
  1659. if s.batch_font == fh {
  1660. return
  1661. }
  1662. draw_current_batch()
  1663. s.batch_font = fh
  1664. if s.batch_font != FONT_NONE {
  1665. _update_font(s.batch_font)
  1666. }
  1667. if fh == 0 {
  1668. fh = s.default_font
  1669. }
  1670. font := &s.fonts[fh]
  1671. fs.SetFont(&s.fs, font.fontstash_handle)
  1672. }
  1673. DEPTH_START :: -1 + DEPTH_INCREMENT
  1674. DEPTH_INCREMENT :: (1.0/10000000.0)
  1675. _ :: jpeg
  1676. _ :: bmp
  1677. _ :: png
  1678. _ :: tga
  1679. Color_F32 :: [4]f32
  1680. f32_color_from_color :: proc(color: Color) -> Color_F32 {
  1681. return {
  1682. f32(color.r) / 255,
  1683. f32(color.g) / 255,
  1684. f32(color.b) / 255,
  1685. f32(color.a) / 255,
  1686. }
  1687. }
  1688. vec3 :: proc(v2: Vec2, z: f32) -> Vec3 {
  1689. return {
  1690. v2.x, v2.y, z,
  1691. }
  1692. }
  1693. get_next_depth :: proc() -> f32 {
  1694. d := s.depth
  1695. s.depth += s.depth_increment
  1696. return d
  1697. }
  1698. FILESYSTEM_SUPPORTED :: ODIN_OS != .JS && ODIN_OS != .Freestanding