karl2d.odin 52 KB

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