karl2d.odin 54 KB

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