karl2d.odin 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035
  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. YELLOW :: Color {240, 190, 0, 255 }
  1124. BLANK :: Color { 0, 0, 0, 0 }
  1125. BLUE :: Color { 30, 116, 240, 255 }
  1126. // These are from Raylib. They are here so you can easily port a Raylib program to Karl2D.
  1127. RL_LIGHTGRAY :: Color { 200, 200, 200, 255 }
  1128. RL_GRAY :: Color { 130, 130, 130, 255 }
  1129. RL_DARKGRAY :: Color { 80, 80, 80, 255 }
  1130. RL_YELLOW :: Color { 253, 249, 0, 255 }
  1131. RL_GOLD :: Color { 255, 203, 0, 255 }
  1132. RL_ORANGE :: Color { 255, 161, 0, 255 }
  1133. RL_PINK :: Color { 255, 109, 194, 255 }
  1134. RL_RED :: Color { 230, 41, 55, 255 }
  1135. RL_MAROON :: Color { 190, 33, 55, 255 }
  1136. RL_GREEN :: Color { 0, 228, 48, 255 }
  1137. RL_LIME :: Color { 0, 158, 47, 255 }
  1138. RL_DARKGREEN :: Color { 0, 117, 44, 255 }
  1139. RL_SKYBLUE :: Color { 102, 191, 255, 255 }
  1140. RL_BLUE :: Color { 0, 121, 241, 255 }
  1141. RL_DARKBLUE :: Color { 0, 82, 172, 255 }
  1142. RL_PURPLE :: Color { 200, 122, 255, 255 }
  1143. RL_VIOLET :: Color { 135, 60, 190, 255 }
  1144. RL_DARKPURPLE :: Color { 112, 31, 126, 255 }
  1145. RL_BEIGE :: Color { 211, 176, 131, 255 }
  1146. RL_BROWN :: Color { 127, 106, 79, 255 }
  1147. RL_DARKBROWN :: Color { 76, 63, 47, 255 }
  1148. RL_WHITE :: WHITE
  1149. RL_BLACK :: BLACK
  1150. RL_BLANK :: BLANK
  1151. RL_MAGENTA :: Color { 255, 0, 255, 255 }
  1152. RL_RAYWHITE :: Color { 245, 245, 245, 255 }
  1153. Texture :: struct {
  1154. handle: Texture_Handle,
  1155. width: int,
  1156. height: int,
  1157. }
  1158. Load_Texture_Option :: enum {
  1159. Premultiply_Alpha,
  1160. }
  1161. Load_Texture_Options :: bit_set[Load_Texture_Option]
  1162. Blend_Mode :: enum {
  1163. Alpha,
  1164. Premultiplied_Alpha, // Requires the alpha-channel to be multiplied into texture RGB channels.
  1165. }
  1166. Render_Texture :: struct {
  1167. texture: Texture,
  1168. render_target: Render_Target_Handle,
  1169. }
  1170. Texture_Filter :: enum {
  1171. Point, // Similar to "nearest neighbor". Pixly texture scaling.
  1172. Linear, // Smoothed texture scaling.
  1173. }
  1174. Camera :: struct {
  1175. target: Vec2,
  1176. offset: Vec2,
  1177. rotation: f32,
  1178. zoom: f32,
  1179. }
  1180. Window_Flag :: enum {
  1181. Resizable,
  1182. }
  1183. Window_Flags :: bit_set[Window_Flag]
  1184. Shader_Handle :: distinct Handle
  1185. SHADER_NONE :: Shader_Handle {}
  1186. Shader_Constant_Location :: struct {
  1187. offset: int,
  1188. size: int,
  1189. }
  1190. Shader :: struct {
  1191. handle: Shader_Handle,
  1192. // We store the CPU-side value of all constants in a single buffer to have less allocations.
  1193. // The 'constants' array says where in this buffer each constant is, and 'constant_lookup'
  1194. // maps a name to a constant location.
  1195. constants_data: []u8,
  1196. constants: []Shader_Constant_Location,
  1197. constant_lookup: map[string]Shader_Constant_Location,
  1198. // Maps built in constant types such as "model view projection matrix" to a location.
  1199. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location),
  1200. texture_bindpoints: []Texture_Handle,
  1201. texture_lookup: map[string]int,
  1202. default_texture_index: Maybe(int),
  1203. inputs: []Shader_Input,
  1204. input_overrides: []Shader_Input_Value_Override,
  1205. default_input_offsets: [Shader_Default_Inputs]int,
  1206. vertex_size: int,
  1207. }
  1208. SHADER_INPUT_VALUE_MAX_SIZE :: 256
  1209. Shader_Input_Value_Override :: struct {
  1210. val: [SHADER_INPUT_VALUE_MAX_SIZE]u8,
  1211. used: int,
  1212. }
  1213. Shader_Input_Type :: enum {
  1214. F32,
  1215. Vec2,
  1216. Vec3,
  1217. Vec4,
  1218. }
  1219. Shader_Builtin_Constant :: enum {
  1220. MVP,
  1221. }
  1222. Shader_Default_Inputs :: enum {
  1223. Unknown,
  1224. Position,
  1225. UV,
  1226. Color,
  1227. }
  1228. Shader_Input :: struct {
  1229. name: string,
  1230. register: int,
  1231. type: Shader_Input_Type,
  1232. format: Pixel_Format,
  1233. }
  1234. Pixel_Format :: enum {
  1235. Unknown,
  1236. RGBA_32_Float,
  1237. RGB_32_Float,
  1238. RG_32_Float,
  1239. R_32_Float,
  1240. RGBA_8_Norm,
  1241. RG_8_Norm,
  1242. R_8_Norm,
  1243. R_8_UInt,
  1244. }
  1245. Font :: struct {
  1246. atlas: Texture,
  1247. // internal
  1248. fontstash_handle: int,
  1249. }
  1250. Handle :: hm.Handle
  1251. Texture_Handle :: distinct Handle
  1252. Render_Target_Handle :: distinct Handle
  1253. Font_Handle :: distinct int
  1254. FONT_NONE :: Font_Handle {}
  1255. TEXTURE_NONE :: Texture_Handle {}
  1256. RENDER_TARGET_NONE :: Render_Target_Handle {}
  1257. // This keeps track of the internal state of the library. Usually, you do not need to poke at it.
  1258. // It is created and kept as a global variable when 'init' is called. However, 'init' also returns
  1259. // the pointer to it, so you can later use 'set_internal_state' to restore it (after for example hot
  1260. // reload).
  1261. State :: struct {
  1262. allocator: runtime.Allocator,
  1263. frame_arena: runtime.Arena,
  1264. frame_allocator: runtime.Allocator,
  1265. win: Window_Interface,
  1266. window_state: rawptr,
  1267. rb: Render_Backend_Interface,
  1268. rb_state: rawptr,
  1269. fs: fs.FontContext,
  1270. shutdown_wanted: bool,
  1271. mouse_position: Vec2,
  1272. mouse_delta: Vec2,
  1273. mouse_wheel_delta: f32,
  1274. key_went_down: #sparse [Keyboard_Key]bool,
  1275. key_went_up: #sparse [Keyboard_Key]bool,
  1276. key_is_held: #sparse [Keyboard_Key]bool,
  1277. mouse_button_went_down: #sparse [Mouse_Button]bool,
  1278. mouse_button_went_up: #sparse [Mouse_Button]bool,
  1279. mouse_button_is_held: #sparse [Mouse_Button]bool,
  1280. gamepad_button_went_down: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1281. gamepad_button_went_up: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1282. gamepad_button_is_held: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1283. window: Window_Handle,
  1284. default_font: Font_Handle,
  1285. fonts: [dynamic]Font,
  1286. shape_drawing_texture: Texture_Handle,
  1287. batch_font: Font_Handle,
  1288. batch_camera: Maybe(Camera),
  1289. batch_shader: Shader,
  1290. batch_scissor: Maybe(Rect),
  1291. batch_texture: Texture_Handle,
  1292. batch_render_target: Render_Target_Handle,
  1293. batch_blend_mode: Blend_Mode,
  1294. view_matrix: Mat4,
  1295. proj_matrix: Mat4,
  1296. depth: f32,
  1297. depth_start: f32,
  1298. depth_increment: f32,
  1299. vertex_buffer_cpu: []u8,
  1300. vertex_buffer_cpu_used: int,
  1301. default_shader: Shader,
  1302. // Time when the first call to `new_frame` happened
  1303. start_time: time.Time,
  1304. prev_frame_time: time.Time,
  1305. // "dt"
  1306. frame_time: f32,
  1307. time: f64,
  1308. }
  1309. // Support for up to 255 mouse buttons. Cast an int to type `Mouse_Button` to use things outside the
  1310. // options presented here.
  1311. Mouse_Button :: enum {
  1312. Left,
  1313. Right,
  1314. Middle,
  1315. Max = 255,
  1316. }
  1317. // Based on Raylib / GLFW
  1318. Keyboard_Key :: enum {
  1319. None = 0,
  1320. // Numeric keys (top row)
  1321. N0 = 48,
  1322. N1 = 49,
  1323. N2 = 50,
  1324. N3 = 51,
  1325. N4 = 52,
  1326. N5 = 53,
  1327. N6 = 54,
  1328. N7 = 55,
  1329. N8 = 56,
  1330. N9 = 57,
  1331. // Letter keys
  1332. A = 65,
  1333. B = 66,
  1334. C = 67,
  1335. D = 68,
  1336. E = 69,
  1337. F = 70,
  1338. G = 71,
  1339. H = 72,
  1340. I = 73,
  1341. J = 74,
  1342. K = 75,
  1343. L = 76,
  1344. M = 77,
  1345. N = 78,
  1346. O = 79,
  1347. P = 80,
  1348. Q = 81,
  1349. R = 82,
  1350. S = 83,
  1351. T = 84,
  1352. U = 85,
  1353. V = 86,
  1354. W = 87,
  1355. X = 88,
  1356. Y = 89,
  1357. Z = 90,
  1358. // Special characters
  1359. Apostrophe = 39,
  1360. Comma = 44,
  1361. Minus = 45,
  1362. Period = 46,
  1363. Slash = 47,
  1364. Semicolon = 59,
  1365. Equal = 61,
  1366. Left_Bracket = 91,
  1367. Backslash = 92,
  1368. Right_Bracket = 93,
  1369. Backtick = 96,
  1370. // Function keys, modifiers, caret control etc
  1371. Space = 32,
  1372. Escape = 256,
  1373. Enter = 257,
  1374. Tab = 258,
  1375. Backspace = 259,
  1376. Insert = 260,
  1377. Delete = 261,
  1378. Right = 262,
  1379. Left = 263,
  1380. Down = 264,
  1381. Up = 265,
  1382. Page_Up = 266,
  1383. Page_Down = 267,
  1384. Home = 268,
  1385. End = 269,
  1386. Caps_Lock = 280,
  1387. Scroll_Lock = 281,
  1388. Num_Lock = 282,
  1389. Print_Screen = 283,
  1390. Pause = 284,
  1391. F1 = 290,
  1392. F2 = 291,
  1393. F3 = 292,
  1394. F4 = 293,
  1395. F5 = 294,
  1396. F6 = 295,
  1397. F7 = 296,
  1398. F8 = 297,
  1399. F9 = 298,
  1400. F10 = 299,
  1401. F11 = 300,
  1402. F12 = 301,
  1403. Left_Shift = 340,
  1404. Left_Control = 341,
  1405. Left_Alt = 342,
  1406. Left_Super = 343,
  1407. Right_Shift = 344,
  1408. Right_Control = 345,
  1409. Right_Alt = 346,
  1410. Right_Super = 347,
  1411. Menu = 348,
  1412. // Numpad keys
  1413. NP_0 = 320,
  1414. NP_1 = 321,
  1415. NP_2 = 322,
  1416. NP_3 = 323,
  1417. NP_4 = 324,
  1418. NP_5 = 325,
  1419. NP_6 = 326,
  1420. NP_7 = 327,
  1421. NP_8 = 328,
  1422. NP_9 = 329,
  1423. NP_Decimal = 330,
  1424. NP_Divide = 331,
  1425. NP_Multiply = 332,
  1426. NP_Subtract = 333,
  1427. NP_Add = 334,
  1428. NP_Enter = 335,
  1429. NP_Equal = 336,
  1430. }
  1431. MAX_GAMEPADS :: 4
  1432. // A value between 0 and MAX_GAMEPADS - 1
  1433. Gamepad_Index :: int
  1434. Gamepad_Axis :: enum {
  1435. Left_Stick_X,
  1436. Left_Stick_Y,
  1437. Right_Stick_X,
  1438. Right_Stick_Y,
  1439. Left_Trigger,
  1440. Right_Trigger,
  1441. }
  1442. Gamepad_Button :: enum {
  1443. // DPAD buttons
  1444. Left_Face_Up,
  1445. Left_Face_Down,
  1446. Left_Face_Left,
  1447. Left_Face_Right,
  1448. Right_Face_Up, // XBOX: Y, PS: Triangle
  1449. Right_Face_Down, // XBOX: A, PS: X
  1450. Right_Face_Left, // XBOX: X, PS: Square
  1451. Right_Face_Right, // XBOX: B, PS: Circle
  1452. Left_Shoulder,
  1453. Left_Trigger,
  1454. Right_Shoulder,
  1455. Right_Trigger,
  1456. Left_Stick_Press, // Clicking the left analogue stick
  1457. Right_Stick_Press, // Clicking the right analogue stick
  1458. Middle_Face_Left, // Select / back / options button
  1459. Middle_Face_Middle, // PS button (not available on XBox)
  1460. Middle_Face_Right, // Start
  1461. }
  1462. // Used by API builder. Everything after this constant will not be in karl2d.doc.odin
  1463. API_END :: true
  1464. batch_vertex :: proc(v: Vec3, uv: Vec2, color: Color) {
  1465. v := v
  1466. if s.vertex_buffer_cpu_used == len(s.vertex_buffer_cpu) {
  1467. draw_current_batch()
  1468. }
  1469. shd := s.batch_shader
  1470. base_offset := s.vertex_buffer_cpu_used
  1471. pos_offset := shd.default_input_offsets[.Position]
  1472. uv_offset := shd.default_input_offsets[.UV]
  1473. color_offset := shd.default_input_offsets[.Color]
  1474. mem.set(&s.vertex_buffer_cpu[base_offset], 0, shd.vertex_size)
  1475. if pos_offset != -1 {
  1476. (^Vec3)(&s.vertex_buffer_cpu[base_offset + pos_offset])^ = v
  1477. }
  1478. if uv_offset != -1 {
  1479. (^Vec2)(&s.vertex_buffer_cpu[base_offset + uv_offset])^ = uv
  1480. }
  1481. if color_offset != -1 {
  1482. (^Color)(&s.vertex_buffer_cpu[base_offset + color_offset])^ = color
  1483. }
  1484. override_offset: int
  1485. for &o, idx in shd.input_overrides {
  1486. input := &shd.inputs[idx]
  1487. sz := pixel_format_size(input.format)
  1488. if o.used != 0 {
  1489. mem.copy(&s.vertex_buffer_cpu[base_offset + override_offset], raw_data(&o.val), o.used)
  1490. }
  1491. override_offset += sz
  1492. }
  1493. s.vertex_buffer_cpu_used += shd.vertex_size
  1494. }
  1495. VERTEX_BUFFER_MAX :: 1000000
  1496. @(private="file")
  1497. s: ^State
  1498. // These globals are here for access from other files. The state struct above is private to make
  1499. // sure global state sharing doesn't become too messy.
  1500. frame_allocator: runtime.Allocator
  1501. win: Window_Interface
  1502. rb: Render_Backend_Interface
  1503. get_shader_input_default_type :: proc(name: string, type: Shader_Input_Type) -> Shader_Default_Inputs {
  1504. if name == "position" && type == .Vec3 {
  1505. return .Position
  1506. } else if name == "texcoord" && type == .Vec2 {
  1507. return .UV
  1508. } else if name == "color" && type == .Vec4 {
  1509. return .Color
  1510. }
  1511. return .Unknown
  1512. }
  1513. get_shader_format_num_components :: proc(format: Pixel_Format) -> int {
  1514. switch format {
  1515. case .Unknown: return 0
  1516. case .RGBA_32_Float: return 4
  1517. case .RGB_32_Float: return 3
  1518. case .RG_32_Float: return 2
  1519. case .R_32_Float: return 1
  1520. case .RGBA_8_Norm: return 4
  1521. case .RG_8_Norm: return 2
  1522. case .R_8_Norm: return 1
  1523. case .R_8_UInt: return 1
  1524. }
  1525. return 0
  1526. }
  1527. get_shader_input_format :: proc(name: string, type: Shader_Input_Type) -> Pixel_Format {
  1528. default_type := get_shader_input_default_type(name, type)
  1529. if default_type != .Unknown {
  1530. switch default_type {
  1531. case .Position: return .RGB_32_Float
  1532. case .UV: return .RG_32_Float
  1533. case .Color: return .RGBA_8_Norm
  1534. case .Unknown: unreachable()
  1535. }
  1536. }
  1537. switch type {
  1538. case .F32: return .R_32_Float
  1539. case .Vec2: return .RG_32_Float
  1540. case .Vec3: return .RGB_32_Float
  1541. case .Vec4: return .RGBA_32_Float
  1542. }
  1543. return .Unknown
  1544. }
  1545. vec3_from_vec2 :: proc(v: Vec2) -> Vec3 {
  1546. return {
  1547. v.x, v.y, 0,
  1548. }
  1549. }
  1550. frame_cstring :: proc(str: string, loc := #caller_location) -> cstring {
  1551. return strings.clone_to_cstring(str, s.frame_allocator, loc)
  1552. }
  1553. @(require_results)
  1554. matrix_ortho3d_f32 :: proc "contextless" (left, right, bottom, top, near, far: f32) -> Mat4 #no_bounds_check {
  1555. m: Mat4
  1556. m[0, 0] = +2 / (right - left)
  1557. m[1, 1] = +2 / (top - bottom)
  1558. m[2, 2] = +1
  1559. m[0, 3] = -(right + left) / (right - left)
  1560. m[1, 3] = -(top + bottom) / (top - bottom)
  1561. m[2, 3] = 0
  1562. m[3, 3] = 1
  1563. return m
  1564. }
  1565. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  1566. return matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  1567. }
  1568. FONT_DEFAULT_ATLAS_SIZE :: 1024
  1569. _update_font :: proc(fh: Font_Handle) {
  1570. font := &s.fonts[fh]
  1571. font_dirty_rect: [4]f32
  1572. tw := FONT_DEFAULT_ATLAS_SIZE
  1573. if fs.ValidateTexture(&s.fs, &font_dirty_rect) {
  1574. fdr := font_dirty_rect
  1575. r := Rect {
  1576. fdr[0],
  1577. fdr[1],
  1578. fdr[2] - fdr[0],
  1579. fdr[3] - fdr[1],
  1580. }
  1581. x := int(r.x)
  1582. y := int(r.y)
  1583. w := int(fdr[2]) - int(fdr[0])
  1584. h := int(fdr[3]) - int(fdr[1])
  1585. expanded_pixels := make([]Color, w * h, frame_allocator)
  1586. start := x + tw * y
  1587. for i in 0..<w*h {
  1588. px := i%w
  1589. py := i/w
  1590. dst_pixel_idx := (px) + (py * w)
  1591. src_pixel_idx := start + (px) + (py * tw)
  1592. src := s.fs.textureData[src_pixel_idx]
  1593. expanded_pixels[dst_pixel_idx] = {255,255,255, src}
  1594. }
  1595. rb.update_texture(font.atlas.handle, slice.reinterpret([]u8, expanded_pixels), r)
  1596. }
  1597. }
  1598. // Not for direct use. Specify font to `draw_text_ex`
  1599. _set_font :: proc(fh: Font_Handle) {
  1600. fh := fh
  1601. if s.batch_font == fh {
  1602. return
  1603. }
  1604. draw_current_batch()
  1605. s.batch_font = fh
  1606. if s.batch_font != FONT_NONE {
  1607. _update_font(s.batch_font)
  1608. }
  1609. if fh == 0 {
  1610. fh = s.default_font
  1611. }
  1612. font := &s.fonts[fh]
  1613. fs.SetFont(&s.fs, font.fontstash_handle)
  1614. }
  1615. DEPTH_START :: -1 + DEPTH_INCREMENT
  1616. DEPTH_INCREMENT :: (1.0/10000000.0)
  1617. _ :: jpeg
  1618. _ :: bmp
  1619. _ :: png
  1620. _ :: tga
  1621. Color_F32 :: [4]f32
  1622. f32_color_from_color :: proc(color: Color) -> Color_F32 {
  1623. return {
  1624. f32(color.r) / 255,
  1625. f32(color.g) / 255,
  1626. f32(color.b) / 255,
  1627. f32(color.a) / 255,
  1628. }
  1629. }
  1630. vec3 :: proc(v2: Vec2, z: f32) -> Vec3 {
  1631. return {
  1632. v2.x, v2.y, z,
  1633. }
  1634. }
  1635. get_next_depth :: proc() -> f32 {
  1636. d := s.depth
  1637. s.depth += s.depth_increment
  1638. return d
  1639. }
  1640. FILESYSTEM_SUPPORTED :: ODIN_OS != .JS && ODIN_OS != .Freestanding