karl2d.odin 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721
  1. package karl2d
  2. import "base:runtime"
  3. import "core:mem"
  4. import "core:log"
  5. import "core:math"
  6. import "core:math/linalg"
  7. import "core:slice"
  8. import "core:strings"
  9. import "core:reflect"
  10. import "core:os"
  11. import fs "vendor:fontstash"
  12. import "core:image"
  13. import "core:image/jpeg"
  14. import "core:image/bmp"
  15. import "core:image/png"
  16. import "core:image/tga"
  17. import hm "handle_map"
  18. //-----------------------------------------------//
  19. // SETUP, WINDOW MANAGEMENT AND FRAME MANAGEMENT //
  20. //-----------------------------------------------//
  21. // Opens a window and initializes some internal state. The internal state will use `allocator` for
  22. // all dynamically allocated memory. The return value can be ignored unless you need to later call
  23. // `set_internal_state`.
  24. init :: proc(window_width: int, window_height: int, window_title: string,
  25. window_creation_flags := Window_Flags {},
  26. allocator := context.allocator, loc := #caller_location) -> ^State {
  27. assert(s == nil, "Don't call 'init' twice.")
  28. context.allocator = allocator
  29. s = new(State, allocator, loc)
  30. s.frame_allocator = runtime.arena_allocator(&s.frame_arena)
  31. frame_allocator = s.frame_allocator
  32. s.allocator = allocator
  33. s.custom_context = context
  34. s.width = window_width
  35. s.height = window_height
  36. s.win = WINDOW_INTERFACE_WIN32
  37. win = s.win
  38. window_state_alloc_error: runtime.Allocator_Error
  39. s.window_state, window_state_alloc_error = mem.alloc(win.state_size())
  40. log.assertf(window_state_alloc_error == nil, "Failed allocating memory for window state: %v", window_state_alloc_error)
  41. win.init(s.window_state, window_width, window_height, window_title, window_creation_flags, allocator)
  42. s.window = win.window_handle()
  43. s.rb = BACKEND
  44. s.depth_start = DEPTH_START
  45. s.depth_increment = DEPTH_INCREMENT
  46. if s.rb.flip_z() {
  47. s.depth_start = -DEPTH_START
  48. s.depth_increment = -DEPTH_INCREMENT
  49. }
  50. s.depth = s.depth_start
  51. rb = s.rb
  52. rb_alloc_error: runtime.Allocator_Error
  53. s.rb_state, rb_alloc_error = mem.alloc(rb.state_size())
  54. log.assertf(rb_alloc_error == nil, "Failed allocating memory for rendering backend: %v", rb_alloc_error)
  55. s.proj_matrix = make_default_projection(window_width, window_height)
  56. s.view_matrix = 1
  57. rb.init(s.rb_state, s.window, window_width, window_height, allocator)
  58. s.vertex_buffer_cpu = make([]u8, VERTEX_BUFFER_MAX, allocator, loc)
  59. white_rect: [16*16*4]u8
  60. slice.fill(white_rect[:], 255)
  61. s.shape_drawing_texture = rb.load_texture(white_rect[:], 16, 16, .RGBA_8_Norm)
  62. s.default_shader = load_shader(rb.default_shader_vertex_source(), rb.default_shader_fragment_source())
  63. s.batch_shader = s.default_shader
  64. fs.Init(&s.fs, FONT_DEFAULT_ATLAS_SIZE, FONT_DEFAULT_ATLAS_SIZE, .TOPLEFT)
  65. DEFAULT_FONT_DATA :: #load("roboto.ttf")
  66. append_nothing(&s.fonts)
  67. s.default_font = load_font_from_bytes(DEFAULT_FONT_DATA)
  68. return s
  69. }
  70. // Returns true if the program wants to shut down. This happens when for example pressing the close
  71. // button on the window. The application can decide if it wants to shut down or if it wants to show
  72. // some kind of confirmation dialogue and shut down later.
  73. //
  74. // Commonly used for creating the "main loop" of a game.
  75. shutdown_wanted :: proc() -> bool {
  76. return s.shutdown_wanted
  77. }
  78. // Closes the window and cleans up the internal state.
  79. shutdown :: proc() {
  80. assert(s != nil, "You've called 'shutdown' without calling 'init' first")
  81. context.allocator = s.allocator
  82. destroy_font(s.default_font)
  83. rb.destroy_texture(s.shape_drawing_texture)
  84. destroy_shader(s.default_shader)
  85. rb.shutdown()
  86. delete(s.vertex_buffer_cpu, s.allocator)
  87. win.shutdown()
  88. fs.Destroy(&s.fs)
  89. a := s.allocator
  90. free(s.window_state, a)
  91. free(s.rb_state, a)
  92. free(s, a)
  93. s = nil
  94. }
  95. // Clear the backbuffer with supplied color.
  96. clear :: proc(color: Color) {
  97. rb.clear(color)
  98. s.depth = s.depth_start
  99. }
  100. // Present the backbuffer. Call at end of frame to make everything you've drawn appear on the screen.
  101. present :: proc() {
  102. draw_current_batch()
  103. rb.present()
  104. free_all(s.frame_allocator)
  105. }
  106. // Call at start or end of frame to process all events that have arrived to the window.
  107. //
  108. // WARNING: Not calling this will make your program impossible to interact with.
  109. process_events :: proc() {
  110. s.key_went_up = {}
  111. s.key_went_down = {}
  112. s.mouse_button_went_up = {}
  113. s.mouse_button_went_down = {}
  114. s.gamepad_button_went_up = {}
  115. s.gamepad_button_went_down = {}
  116. s.mouse_delta = {}
  117. s.mouse_wheel_delta = 0
  118. win.process_events()
  119. events := win.get_events()
  120. for &event in events {
  121. switch &e in event {
  122. case Window_Event_Close_Wanted:
  123. s.shutdown_wanted = true
  124. case Window_Event_Key_Went_Down:
  125. s.key_went_down[e.key] = true
  126. s.key_is_held[e.key] = true
  127. case Window_Event_Key_Went_Up:
  128. s.key_went_up[e.key] = true
  129. s.key_is_held[e.key] = false
  130. case Window_Event_Mouse_Button_Went_Down:
  131. s.mouse_button_went_down[e.button] = true
  132. s.mouse_button_is_held[e.button] = true
  133. case Window_Event_Mouse_Button_Went_Up:
  134. s.mouse_button_went_up[e.button] = true
  135. s.mouse_button_is_held[e.button] = false
  136. case Window_Event_Mouse_Move:
  137. prev_pos := s.mouse_position
  138. s.mouse_position = e.position
  139. s.mouse_delta = prev_pos - s.mouse_position
  140. case Window_Event_Mouse_Wheel:
  141. s.mouse_wheel_delta = e.delta
  142. case Window_Event_Gamepad_Button_Went_Down:
  143. if e.gamepad < MAX_GAMEPADS {
  144. s.gamepad_button_went_down[e.gamepad][e.button] = true
  145. s.gamepad_button_is_held[e.gamepad][e.button] = true
  146. }
  147. case Window_Event_Gamepad_Button_Went_Up:
  148. if e.gamepad < MAX_GAMEPADS {
  149. s.gamepad_button_went_up[e.gamepad][e.button] = true
  150. s.gamepad_button_is_held[e.gamepad][e.button] = false
  151. }
  152. case Window_Event_Resize:
  153. s.width = e.width
  154. s.height = e.height
  155. rb.resize_swapchain(s.width, s.height)
  156. s.proj_matrix = make_default_projection(s.width, s.height)
  157. }
  158. }
  159. win.clear_events()
  160. }
  161. get_screen_width :: proc() -> int {
  162. return s.width
  163. }
  164. get_screen_height :: proc() -> int {
  165. return s.height
  166. }
  167. set_window_position :: proc(x: int, y: int) {
  168. win.set_position(x, y)
  169. }
  170. set_window_size :: proc(width: int, height: int) {
  171. // TODO not sure if we should resize swapchain here. On windows the WM_SIZE event fires and
  172. // it all works out. But perhaps not on all platforms?
  173. win.set_size(width, height)
  174. }
  175. // Fetch the scale of the window. This usually comes from some DPI scaling setting in the OS.
  176. // 1 means 100% scale, 1.5 means 150% etc.
  177. get_window_scale :: proc() -> f32 {
  178. return win.get_window_scale()
  179. }
  180. set_window_flags :: proc(flags: Window_Flags) {
  181. win.set_flags(flags)
  182. }
  183. // Flushes the current batch. This sends off everything to the GPU that has been queued in the
  184. // current batch. Normally, you do not need to do this manually. It is done automatically when these
  185. // procedures run:
  186. //
  187. // - present
  188. // - set_camera
  189. // - set_shader
  190. // - set_shader_constant
  191. // - set_scissor_rect
  192. // - draw_texture_* IF previous draw did not use the same texture (1)
  193. // - draw_rect_*, draw_circle_*, draw_line IF previous draw did not use the shapes drawing texture (2)
  194. //
  195. // (1) When drawing textures, the current texture is fed into the active shader. Everything within
  196. // the same batch must use the same texture. So drawing with a new texture will draw the current
  197. // batch. You can combine several textures into an atlas to get bigger batches.
  198. //
  199. // (2) In order to use the same shader for shapes drawing and textured drawing, the shapes drawing
  200. // uses a blank, white texture. For the same reasons as (1), drawing something else than shapes
  201. // before drawing a shape will break up the batches. TODO: Add possibility to customize shape
  202. // drawing texture so that you can put it into an atlas.
  203. //
  204. // The batch has maximum size of VERTEX_BUFFER_MAX bytes. The shader dictates how big a vertex is
  205. // so the maximum number of vertices that can be drawn in each batch is
  206. // VERTEX_BUFFER_MAX / shader.vertex_size
  207. draw_current_batch :: proc() {
  208. update_font(s.batch_font)
  209. if s.vertex_buffer_cpu_used == 0 {
  210. return
  211. }
  212. shader := s.batch_shader
  213. mvp := s.proj_matrix * s.view_matrix
  214. for mloc, builtin in shader.constant_builtin_locations {
  215. constant, constant_ok := mloc.?
  216. if !constant_ok {
  217. continue
  218. }
  219. switch builtin {
  220. case .MVP:
  221. if constant.size == size_of(mvp) {
  222. dst := (^matrix[4,4]f32)(&shader.constants_data[constant.offset])
  223. dst^ = mvp
  224. }
  225. }
  226. }
  227. if def_tex_idx, has_def_tex_idx := shader.default_texture_index.?; has_def_tex_idx {
  228. shader.texture_bindpoints[def_tex_idx] = s.batch_texture
  229. }
  230. rb.draw(shader, shader.texture_bindpoints, s.batch_scissor, s.vertex_buffer_cpu[:s.vertex_buffer_cpu_used])
  231. s.vertex_buffer_cpu_used = 0
  232. }
  233. //-------//
  234. // INPUT //
  235. //-------//
  236. // Returns true if a keyboard key went down between the current and the previous frame. Set when
  237. // 'process_events' runs (probably once per frame).
  238. key_went_down :: proc(key: Keyboard_Key) -> bool {
  239. return s.key_went_down[key]
  240. }
  241. // Returns true if a keyboard key went up (was released) between the current and the previous frame.
  242. // Set when 'process_events' runs (probably once per frame).
  243. key_went_up :: proc(key: Keyboard_Key) -> bool {
  244. return s.key_went_up[key]
  245. }
  246. // Returns true if a keyboard is currently being held down. Set when 'process_events' runs (probably
  247. // once per frame).
  248. key_is_held :: proc(key: Keyboard_Key) -> bool {
  249. return s.key_is_held[key]
  250. }
  251. mouse_button_went_down :: proc(button: Mouse_Button) -> bool {
  252. return s.mouse_button_went_down[button]
  253. }
  254. mouse_button_went_up :: proc(button: Mouse_Button) -> bool {
  255. return s.mouse_button_went_up[button]
  256. }
  257. mouse_button_is_held :: proc(button: Mouse_Button) -> bool {
  258. return s.mouse_button_is_held[button]
  259. }
  260. get_mouse_wheel_delta :: proc() -> f32 {
  261. return s.mouse_wheel_delta
  262. }
  263. get_mouse_position :: proc() -> Vec2 {
  264. return s.mouse_position
  265. }
  266. gamepad_button_went_down :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  267. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  268. return false
  269. }
  270. return s.gamepad_button_went_down[gamepad][button]
  271. }
  272. gamepad_button_went_up :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  273. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  274. return false
  275. }
  276. return s.gamepad_button_went_up[gamepad][button]
  277. }
  278. gamepad_button_is_held :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  279. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  280. return false
  281. }
  282. return s.gamepad_button_is_held[gamepad][button]
  283. }
  284. get_gamepad_axis :: proc(gamepad: Gamepad_Index, axis: Gamepad_Axis) -> f32 {
  285. return win.get_gamepad_axis(gamepad, axis)
  286. }
  287. // Set the left and right vibration motor speed. The range of left and right is 0 to 1. Note that on
  288. // most gamepads, the left motor is "low frequency" and the right motor is "high frequency". They do
  289. // not vibrate with the same speed.
  290. set_gamepad_vibration :: proc(gamepad: Gamepad_Index, left: f32, right: f32) {
  291. win.set_gamepad_vibration(gamepad, left, right)
  292. }
  293. //---------//
  294. // DRAWING //
  295. //---------//
  296. draw_rect :: proc(r: Rect, c: Color) {
  297. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  298. draw_current_batch()
  299. }
  300. if s.batch_texture != s.shape_drawing_texture {
  301. draw_current_batch()
  302. }
  303. s.batch_texture = s.shape_drawing_texture
  304. z := get_next_depth()
  305. batch_vertex({r.x, r.y, z}, {0, 0}, c)
  306. batch_vertex({r.x + r.w, r.y, z}, {1, 0}, c)
  307. batch_vertex({r.x + r.w, r.y + r.h, z}, {1, 1}, c)
  308. batch_vertex({r.x, r.y, z}, {0, 0}, c)
  309. batch_vertex({r.x + r.w, r.y + r.h, z}, {1, 1}, c)
  310. batch_vertex({r.x, r.y + r.h, z}, {0, 1}, c)
  311. }
  312. draw_rect_vec :: proc(pos: Vec2, size: Vec2, c: Color) {
  313. draw_rect({pos.x, pos.y, size.x, size.y}, c)
  314. }
  315. draw_rect_ex :: proc(r: Rect, origin: Vec2, rot: f32, c: Color) {
  316. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  317. draw_current_batch()
  318. }
  319. if s.batch_texture != s.shape_drawing_texture {
  320. draw_current_batch()
  321. }
  322. s.batch_texture = s.shape_drawing_texture
  323. tl, tr, bl, br: Vec2
  324. // Rotation adapted from Raylib's "DrawTexturePro"
  325. if rot == 0 {
  326. x := r.x - origin.x
  327. y := r.y - origin.y
  328. tl = { x, y }
  329. tr = { x + r.w, y }
  330. bl = { x, y + r.h }
  331. br = { x + r.w, y + r.h }
  332. } else {
  333. sin_rot := math.sin(rot * math.RAD_PER_DEG)
  334. cos_rot := math.cos(rot * math.RAD_PER_DEG)
  335. x := r.x
  336. y := r.y
  337. dx := -origin.x
  338. dy := -origin.y
  339. tl = {
  340. x + dx * cos_rot - dy * sin_rot,
  341. y + dx * sin_rot + dy * cos_rot,
  342. }
  343. tr = {
  344. x + (dx + r.w) * cos_rot - dy * sin_rot,
  345. y + (dx + r.w) * sin_rot + dy * cos_rot,
  346. }
  347. bl = {
  348. x + dx * cos_rot - (dy + r.h) * sin_rot,
  349. y + dx * sin_rot + (dy + r.h) * cos_rot,
  350. }
  351. br = {
  352. x + (dx + r.w) * cos_rot - (dy + r.h) * sin_rot,
  353. y + (dx + r.w) * sin_rot + (dy + r.h) * cos_rot,
  354. }
  355. }
  356. z := get_next_depth()
  357. batch_vertex(vec3(tl, z), {0, 0}, c)
  358. batch_vertex(vec3(tr, z), {1, 0}, c)
  359. batch_vertex(vec3(br, z), {1, 1}, c)
  360. batch_vertex(vec3(tl, z), {0, 0}, c)
  361. batch_vertex(vec3(br, z), {1, 1}, c)
  362. batch_vertex(vec3(bl, z), {0, 1}, c)
  363. }
  364. draw_rect_outline :: proc(r: Rect, thickness: f32, color: Color) {
  365. t := thickness
  366. // Based on DrawRectangleLinesEx from Raylib
  367. top := Rect {
  368. r.x,
  369. r.y,
  370. r.w,
  371. t,
  372. }
  373. bottom := Rect {
  374. r.x,
  375. r.y + r.h - t,
  376. r.w,
  377. t,
  378. }
  379. left := Rect {
  380. r.x,
  381. r.y + t,
  382. t,
  383. r.h - t * 2,
  384. }
  385. right := Rect {
  386. r.x + r.w - t,
  387. r.y + t,
  388. t,
  389. r.h - t * 2,
  390. }
  391. draw_rect(top, color)
  392. draw_rect(bottom, color)
  393. draw_rect(left, color)
  394. draw_rect(right, color)
  395. }
  396. draw_circle :: proc(center: Vec2, radius: f32, color: Color, segments := 16) {
  397. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 3 * segments > len(s.vertex_buffer_cpu) {
  398. draw_current_batch()
  399. }
  400. if s.batch_texture != s.shape_drawing_texture {
  401. draw_current_batch()
  402. }
  403. s.batch_texture = s.shape_drawing_texture
  404. z := get_next_depth()
  405. prev := center + {radius, 0}
  406. for s in 1..=segments {
  407. sr := (f32(s)/f32(segments)) * 2*math.PI
  408. rot := linalg.matrix2_rotate(sr)
  409. p := center + rot * Vec2{radius, 0}
  410. batch_vertex(vec3(prev, z), {0, 0}, color)
  411. batch_vertex(vec3(p, z), {1, 0}, color)
  412. batch_vertex(vec3(center, z), {1, 1}, color)
  413. prev = p
  414. }
  415. }
  416. draw_circle_outline :: proc(center: Vec2, radius: f32, thickness: f32, color: Color, segments := 16) {
  417. prev := center + {radius, 0}
  418. for s in 1..=segments {
  419. sr := (f32(s)/f32(segments)) * 2*math.PI
  420. rot := linalg.matrix2_rotate(sr)
  421. p := center + rot * Vec2{radius, 0}
  422. draw_line(prev, p, thickness, color)
  423. prev = p
  424. }
  425. }
  426. draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  427. p := Vec2{start.x, start.y + thickness*0.5}
  428. s := Vec2{linalg.length(end - start), thickness}
  429. origin := Vec2 {0, thickness*0.5}
  430. r := Rect {p.x, p.y, s.x, s.y}
  431. rot := math.atan2(end.y - start.y, end.x - start.x)
  432. draw_rect_ex(r, origin, rot * math.DEG_PER_RAD, color)
  433. }
  434. draw_texture :: proc(tex: Texture, pos: Vec2, tint := WHITE) {
  435. draw_texture_ex(
  436. tex,
  437. {0, 0, f32(tex.width), f32(tex.height)},
  438. {pos.x, pos.y, f32(tex.width), f32(tex.height)},
  439. {},
  440. 0,
  441. tint,
  442. )
  443. }
  444. draw_texture_rect :: proc(tex: Texture, rect: Rect, pos: Vec2, tint := WHITE) {
  445. draw_texture_ex(
  446. tex,
  447. rect,
  448. {pos.x, pos.y, rect.w, rect.h},
  449. {},
  450. 0,
  451. tint,
  452. )
  453. }
  454. draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rotation: f32, tint := WHITE) {
  455. if tex.width == 0 || tex.height == 0 {
  456. return
  457. }
  458. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  459. draw_current_batch()
  460. }
  461. if s.batch_texture != tex.handle {
  462. draw_current_batch()
  463. }
  464. s.batch_texture = tex.handle
  465. flip_x, flip_y: bool
  466. src := src
  467. dst := dst
  468. if src.w < 0 {
  469. flip_x = true
  470. src.w = -src.w
  471. }
  472. if src.h < 0 {
  473. flip_y = true
  474. src.h = -src.h
  475. }
  476. if dst.w < 0 {
  477. dst.w *= -1
  478. }
  479. if dst.h < 0 {
  480. dst.h *= -1
  481. }
  482. tl, tr, bl, br: Vec2
  483. // Rotation adapted from Raylib's "DrawTexturePro"
  484. if rotation == 0 {
  485. x := dst.x - origin.x
  486. y := dst.y - origin.y
  487. tl = { x, y }
  488. tr = { x + dst.w, y }
  489. bl = { x, y + dst.h }
  490. br = { x + dst.w, y + dst.h }
  491. } else {
  492. sin_rot := math.sin(rotation * math.RAD_PER_DEG)
  493. cos_rot := math.cos(rotation * math.RAD_PER_DEG)
  494. x := dst.x
  495. y := dst.y
  496. dx := -origin.x
  497. dy := -origin.y
  498. tl = {
  499. x + dx * cos_rot - dy * sin_rot,
  500. y + dx * sin_rot + dy * cos_rot,
  501. }
  502. tr = {
  503. x + (dx + dst.w) * cos_rot - dy * sin_rot,
  504. y + (dx + dst.w) * sin_rot + dy * cos_rot,
  505. }
  506. bl = {
  507. x + dx * cos_rot - (dy + dst.h) * sin_rot,
  508. y + dx * sin_rot + (dy + dst.h) * cos_rot,
  509. }
  510. br = {
  511. x + (dx + dst.w) * cos_rot - (dy + dst.h) * sin_rot,
  512. y + (dx + dst.w) * sin_rot + (dy + dst.h) * cos_rot,
  513. }
  514. }
  515. ts := Vec2{f32(tex.width), f32(tex.height)}
  516. up := Vec2{src.x, src.y} / ts
  517. us := Vec2{src.w, src.h} / ts
  518. c := tint
  519. uv0 := up
  520. uv1 := up + {us.x, 0}
  521. uv2 := up + us
  522. uv3 := up
  523. uv4 := up + us
  524. uv5 := up + {0, us.y}
  525. if flip_x {
  526. uv0.x += us.x
  527. uv1.x -= us.x
  528. uv2.x -= us.x
  529. uv3.x += us.x
  530. uv4.x -= us.x
  531. uv5.x += us.x
  532. }
  533. if flip_y {
  534. uv0.y += us.y
  535. uv1.y += us.y
  536. uv2.y -= us.y
  537. uv3.y += us.y
  538. uv4.y -= us.y
  539. uv5.y -= us.y
  540. }
  541. z := get_next_depth()
  542. batch_vertex(vec3(tl, z), uv0, c)
  543. batch_vertex(vec3(tr, z), uv1, c)
  544. batch_vertex(vec3(br, z), uv2, c)
  545. batch_vertex(vec3(tl, z), uv3, c)
  546. batch_vertex(vec3(br, z), uv4, c)
  547. batch_vertex(vec3(bl, z), uv5, c)
  548. }
  549. vec3 :: proc(v2: Vec2, z: f32) -> Vec3 {
  550. return {
  551. v2.x, v2.y, z,
  552. }
  553. }
  554. get_next_depth :: proc() -> f32 {
  555. d := s.depth
  556. s.depth += s.depth_increment
  557. return d
  558. }
  559. measure_text :: proc(text: string, font_size: f32) -> Vec2 {
  560. fs.SetSize(&s.fs, font_size)
  561. b: [4]f32
  562. fs.TextBounds(&s.fs, text, bounds = &b)
  563. return {b[2] - b[0], b[3] - b[1]}
  564. }
  565. draw_text :: proc(text: string, pos: Vec2, font_size: f32, color: Color) {
  566. draw_text_ex(s.default_font, text, pos, font_size, color)
  567. }
  568. draw_text_ex :: proc(font: Font_Handle, text: string, pos: Vec2, font_size: f32, color: Color) {
  569. if int(font) >= len(s.fonts) {
  570. return
  571. }
  572. set_font(font)
  573. font := &s.fonts[font]
  574. fs.SetSize(&s.fs, font_size)
  575. iter := fs.TextIterInit(&s.fs, pos.x, pos.y+font_size/2, text)
  576. q: fs.Quad
  577. for fs.TextIterNext(&s.fs, &iter, &q) {
  578. src := Rect {
  579. q.s0, q.t0,
  580. q.s1 - q.s0, q.t1 - q.t0,
  581. }
  582. w := f32(FONT_DEFAULT_ATLAS_SIZE)
  583. h := f32(FONT_DEFAULT_ATLAS_SIZE)
  584. src.x *= w
  585. src.y *= h
  586. src.w *= w
  587. src.h *= h
  588. dst := Rect {
  589. q.x0, q.y0,
  590. q.x1 - q.x0, q.y1 - q.y0,
  591. }
  592. draw_texture_ex(font.atlas, src, dst, {}, 0, color)
  593. }
  594. }
  595. //--------------------//
  596. // TEXTURE MANAGEMENT //
  597. //--------------------//
  598. load_texture_from_file :: proc(filename: string) -> Texture {
  599. img, img_err := image.load_from_file(filename, options = {.alpha_add_if_missing}, allocator = s.frame_allocator)
  600. if img_err != nil {
  601. log.errorf("Error loading texture %v: %v", filename, img_err)
  602. return {}
  603. }
  604. return load_texture_from_bytes(img.pixels.buf[:], img.width, img.height, .RGBA_8_Norm)
  605. }
  606. // TODO should we have an error here or rely on check the handle of the texture?
  607. load_texture_from_bytes :: proc(bytes: []u8, width: int, height: int, format: Pixel_Format) -> Texture {
  608. backend_tex := rb.load_texture(bytes[:], width, height, format)
  609. if backend_tex == TEXTURE_NONE {
  610. return {}
  611. }
  612. return {
  613. handle = backend_tex,
  614. width = width,
  615. height = height,
  616. }
  617. }
  618. // Get a rectangle that spans the whole texture. Coordinates will be (x, y) = (0, 0) and size
  619. // (w, h) = (texture_width, texture_height)
  620. get_texture_rect :: proc(t: Texture) -> Rect {
  621. return {
  622. 0, 0,
  623. f32(t.width), f32(t.height),
  624. }
  625. }
  626. // Update a texture with new pixels. `bytes` is the new pixel data. `rect` is the rectangle in
  627. // `tex` where the new pixels should end up.
  628. update_texture :: proc(tex: Texture, bytes: []u8, rect: Rect) -> bool {
  629. return rb.update_texture(tex.handle, bytes, rect)
  630. }
  631. destroy_texture :: proc(tex: Texture) {
  632. rb.destroy_texture(tex.handle)
  633. }
  634. //-------//
  635. // FONTS //
  636. //-------//
  637. load_font_from_file :: proc(filename: string) -> Font_Handle {
  638. if data, data_ok := os.read_entire_file(filename); data_ok {
  639. return load_font_from_bytes(data)
  640. }
  641. return FONT_NONE
  642. }
  643. load_font_from_bytes :: proc(data: []u8) -> Font_Handle {
  644. font := fs.AddFontMem(&s.fs, "", data, false)
  645. h := Font_Handle(len(s.fonts))
  646. append(&s.fonts, Font {
  647. fontstash_handle = font,
  648. atlas = {
  649. handle = rb.create_texture(FONT_DEFAULT_ATLAS_SIZE, FONT_DEFAULT_ATLAS_SIZE, .RGBA_8_Norm),
  650. width = FONT_DEFAULT_ATLAS_SIZE,
  651. height = FONT_DEFAULT_ATLAS_SIZE,
  652. },
  653. })
  654. return h
  655. }
  656. destroy_font :: proc(font: Font_Handle) {
  657. if int(font) >= len(s.fonts) {
  658. return
  659. }
  660. f := &s.fonts[font]
  661. rb.destroy_texture(f.atlas.handle)
  662. // TODO fontstash has no "destroy font" proc... I should make my own version of fontstash
  663. delete(s.fs.fonts[f.fontstash_handle].glyphs)
  664. s.fs.fonts[f.fontstash_handle].glyphs = {}
  665. }
  666. get_default_font :: proc() -> Font_Handle {
  667. return s.default_font
  668. }
  669. //---------//
  670. // SHADERS //
  671. //---------//
  672. load_shader :: proc(
  673. vertex_shader_source: string,
  674. fragment_shader_source: string,
  675. layout_formats: []Pixel_Format = {},
  676. ) -> Shader {
  677. handle, desc := rb.load_shader(
  678. vertex_shader_source,
  679. fragment_shader_source,
  680. s.frame_allocator,
  681. layout_formats,
  682. )
  683. if handle == SHADER_NONE {
  684. log.error("Failed loading shader")
  685. return {}
  686. }
  687. constants_size: int
  688. for c in desc.constants {
  689. constants_size += c.size
  690. }
  691. shd := Shader {
  692. handle = handle,
  693. constants_data = make([]u8, constants_size, s.allocator),
  694. constants = make([]Shader_Constant_Location, len(desc.constants), s.allocator),
  695. constant_lookup = make(map[string]Shader_Constant_Location, s.allocator),
  696. inputs = slice.clone(desc.inputs, s.allocator),
  697. input_overrides = make([]Shader_Input_Value_Override, len(desc.inputs), s.allocator),
  698. texture_bindpoints = make([]Texture_Handle, len(desc.texture_bindpoints), s.allocator),
  699. texture_lookup = make(map[string]int, s.allocator),
  700. }
  701. for &input in shd.inputs {
  702. input.name = strings.clone(input.name, s.allocator)
  703. }
  704. constant_offset: int
  705. for cidx in 0..<len(desc.constants) {
  706. constant_desc := &desc.constants[cidx]
  707. loc := Shader_Constant_Location {
  708. offset = constant_offset,
  709. size = constant_desc.size,
  710. }
  711. shd.constants[cidx] = loc
  712. constant_offset += constant_desc.size
  713. if constant_desc.name != "" {
  714. shd.constant_lookup[strings.clone(constant_desc.name, s.allocator)] = loc
  715. switch constant_desc.name {
  716. case "mvp":
  717. shd.constant_builtin_locations[.MVP] = loc
  718. }
  719. }
  720. }
  721. for tbp, tbp_idx in desc.texture_bindpoints {
  722. shd.texture_lookup[tbp.name] = tbp_idx
  723. if tbp.name == "tex" {
  724. shd.default_texture_index = tbp_idx
  725. }
  726. }
  727. for &d in shd.default_input_offsets {
  728. d = -1
  729. }
  730. input_offset: int
  731. for &input in shd.inputs {
  732. default_format := get_shader_input_default_type(input.name, input.type)
  733. if default_format != .Unknown {
  734. shd.default_input_offsets[default_format] = input_offset
  735. }
  736. input_offset += pixel_format_size(input.format)
  737. }
  738. shd.vertex_size = input_offset
  739. return shd
  740. }
  741. destroy_shader :: proc(shader: Shader) {
  742. rb.destroy_shader(shader.handle)
  743. delete(shader.constants_data)
  744. delete(shader.constants)
  745. for k, _ in shader.constant_lookup {
  746. delete(k)
  747. }
  748. delete(shader.constant_lookup)
  749. for i in shader.inputs {
  750. delete(i.name)
  751. }
  752. delete(shader.inputs)
  753. delete(shader.input_overrides)
  754. }
  755. get_default_shader :: proc() -> Shader {
  756. return s.default_shader
  757. }
  758. set_shader :: proc(shader: Maybe(Shader)) {
  759. if shd, shd_ok := shader.?; shd_ok {
  760. if shd.handle == s.batch_shader.handle {
  761. return
  762. }
  763. } else {
  764. if s.batch_shader.handle == s.default_shader.handle {
  765. return
  766. }
  767. }
  768. draw_current_batch()
  769. s.batch_shader = shader.? or_else s.default_shader
  770. }
  771. set_shader_constant :: proc(shd: Shader, loc: Shader_Constant_Location, val: any) {
  772. if shd.handle == SHADER_NONE {
  773. log.error("Invalid shader")
  774. return
  775. }
  776. if loc.size == 0 {
  777. log.error("Could not find shader constant")
  778. return
  779. }
  780. draw_current_batch()
  781. if loc.offset + loc.size > len(shd.constants_data) {
  782. 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))
  783. return
  784. }
  785. sz := reflect.size_of_typeid(val.id)
  786. if sz != loc.size {
  787. log.errorf("Trying to set constant of type %v, but it is not of correct size %v", val.id, loc.size)
  788. return
  789. }
  790. mem.copy(&shd.constants_data[loc.offset], val.data, sz)
  791. }
  792. override_shader_input :: proc(shader: Shader, input: int, val: any) {
  793. sz := reflect.size_of_typeid(val.id)
  794. assert(sz < SHADER_INPUT_VALUE_MAX_SIZE)
  795. if input >= len(shader.input_overrides) {
  796. log.errorf("Input override out of range. Wanted to override input %v, but shader only has %v inputs", input, len(shader.input_overrides))
  797. return
  798. }
  799. o := &shader.input_overrides[input]
  800. o.val = {}
  801. if sz > 0 {
  802. mem.copy(raw_data(&o.val), val.data, sz)
  803. }
  804. o.used = sz
  805. }
  806. pixel_format_size :: proc(f: Pixel_Format) -> int {
  807. switch f {
  808. case .Unknown: return 0
  809. case .RGBA_32_Float: return 32
  810. case .RGB_32_Float: return 12
  811. case .RG_32_Float: return 8
  812. case .R_32_Float: return 4
  813. case .RGBA_8_Norm: return 4
  814. case .RG_8_Norm: return 2
  815. case .R_8_Norm: return 1
  816. case .R_8_UInt: return 1
  817. }
  818. return 0
  819. }
  820. //-------------------------------//
  821. // CAMERA AND COORDINATE SYSTEMS //
  822. //-------------------------------//
  823. set_camera :: proc(camera: Maybe(Camera)) {
  824. if camera == s.batch_camera {
  825. return
  826. }
  827. draw_current_batch()
  828. s.batch_camera = camera
  829. s.proj_matrix = make_default_projection(s.width, s.height)
  830. if c, c_ok := camera.?; c_ok {
  831. s.view_matrix = get_camera_view_matrix(c)
  832. } else {
  833. s.view_matrix = 1
  834. }
  835. }
  836. screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  837. return (get_camera_world_matrix(camera) * Vec4 { pos.x, pos.y, 0, 1 }).xy
  838. }
  839. world_to_screen :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  840. return (get_camera_view_matrix(camera) * Vec4 { pos.x, pos.y, 0, 1 }).xy
  841. }
  842. get_camera_view_matrix :: proc(c: Camera) -> Mat4 {
  843. inv_target_translate := linalg.matrix4_translate(vec3_from_vec2(-c.target))
  844. inv_rot := linalg.matrix4_rotate_f32(c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  845. inv_scale := linalg.matrix4_scale(Vec3{c.zoom, c.zoom, 1})
  846. inv_offset_translate := linalg.matrix4_translate(vec3_from_vec2(c.offset))
  847. // A view matrix is essentially the world transform matrix of the camera, but inverted. We
  848. // bring everything in the world "in front of the camera".
  849. //
  850. // Instead of constructing the camera matrix and doing a matrix inverse, here we just do the
  851. // maths in "backwards order". I.e. a camera transform matrix would be:
  852. //
  853. // target_translate * rot * scale * offset_translate
  854. return inv_offset_translate * inv_scale * inv_rot * inv_target_translate
  855. }
  856. get_camera_world_matrix :: proc(c: Camera) -> Mat4 {
  857. offset_translate := linalg.matrix4_translate(vec3_from_vec2(-c.offset))
  858. rot := linalg.matrix4_rotate_f32(-c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  859. scale := linalg.matrix4_scale(Vec3{1/c.zoom, 1/c.zoom, 1})
  860. target_translate := linalg.matrix4_translate(vec3_from_vec2(c.target))
  861. return target_translate * rot * scale * offset_translate
  862. }
  863. //------//
  864. // MISC //
  865. //------//
  866. set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  867. draw_current_batch()
  868. s.batch_scissor = scissor_rect
  869. }
  870. // Restore the internal state using the pointer returned by `init`. Useful after reloading the
  871. // library (for example, when doing code hot reload).
  872. set_internal_state :: proc(state: ^State) {
  873. s = state
  874. rb = s.rb
  875. win = s.win
  876. rb.set_internal_state(s.rb_state)
  877. win.set_internal_state(s.window_state)
  878. }
  879. //---------------------//
  880. // TYPES AND CONSTANTS //
  881. //---------------------//
  882. Vec2 :: [2]f32
  883. Vec3 :: [3]f32
  884. Vec4 :: [4]f32
  885. Mat4 :: matrix[4,4]f32
  886. // A two dimensional vector of integer numeric type.
  887. Vec2i :: [2]int
  888. // A rectangle that sits at position (x, y) and has size (w, h).
  889. Rect :: struct {
  890. x, y: f32,
  891. w, h: f32,
  892. }
  893. // An RGBA (Red, Green, Blue, Alpha) color. Each channel can have a value between 0 and 255.
  894. Color :: [4]u8
  895. WHITE :: Color { 255, 255, 255, 255 }
  896. BLACK :: Color { 0, 0, 0, 255 }
  897. GRAY :: Color { 127, 127, 127, 255 }
  898. RED :: Color { 198, 40, 90, 255 }
  899. GREEN :: Color { 30, 240, 30, 255 }
  900. BLANK :: Color { 0, 0, 0, 0 }
  901. BLUE :: Color { 30, 116, 240, 255 }
  902. // These are from Raylib. They are here so you can easily port a Raylib program to Karl2D.
  903. RL_LIGHTGRAY :: Color { 200, 200, 200, 255 }
  904. RL_GRAY :: Color { 130, 130, 130, 255 }
  905. RL_DARKGRAY :: Color { 80, 80, 80, 255 }
  906. RL_YELLOW :: Color { 253, 249, 0, 255 }
  907. RL_GOLD :: Color { 255, 203, 0, 255 }
  908. RL_ORANGE :: Color { 255, 161, 0, 255 }
  909. RL_PINK :: Color { 255, 109, 194, 255 }
  910. RL_RED :: Color { 230, 41, 55, 255 }
  911. RL_MAROON :: Color { 190, 33, 55, 255 }
  912. RL_GREEN :: Color { 0, 228, 48, 255 }
  913. RL_LIME :: Color { 0, 158, 47, 255 }
  914. RL_DARKGREEN :: Color { 0, 117, 44, 255 }
  915. RL_SKYBLUE :: Color { 102, 191, 255, 255 }
  916. RL_BLUE :: Color { 0, 121, 241, 255 }
  917. RL_DARKBLUE :: Color { 0, 82, 172, 255 }
  918. RL_PURPLE :: Color { 200, 122, 255, 255 }
  919. RL_VIOLET :: Color { 135, 60, 190, 255 }
  920. RL_DARKPURPLE :: Color { 112, 31, 126, 255 }
  921. RL_BEIGE :: Color { 211, 176, 131, 255 }
  922. RL_BROWN :: Color { 127, 106, 79, 255 }
  923. RL_DARKBROWN :: Color { 76, 63, 47, 255 }
  924. RL_WHITE :: WHITE
  925. RL_BLACK :: BLACK
  926. RL_BLANK :: BLANK
  927. RL_MAGENTA :: Color { 255, 0, 255, 255 }
  928. RL_RAYWHITE :: Color { 245, 245, 245, 255 }
  929. Texture :: struct {
  930. handle: Texture_Handle,
  931. width: int,
  932. height: int,
  933. }
  934. Camera :: struct {
  935. target: Vec2,
  936. offset: Vec2,
  937. rotation: f32,
  938. zoom: f32,
  939. }
  940. Window_Flag :: enum {
  941. Resizable,
  942. }
  943. Window_Flags :: bit_set[Window_Flag]
  944. Shader_Handle :: distinct Handle
  945. SHADER_NONE :: Shader_Handle {}
  946. Shader_Constant_Location :: struct {
  947. offset: int,
  948. size: int,
  949. }
  950. Shader :: struct {
  951. handle: Shader_Handle,
  952. // We store the CPU-side value of all constants in a single buffer to have less allocations.
  953. // The 'constants' array says where in this buffer each constant is, and 'constant_lookup'
  954. // maps a name to a constant location.
  955. constants_data: []u8,
  956. constants: []Shader_Constant_Location,
  957. constant_lookup: map[string]Shader_Constant_Location,
  958. // Maps built in constant types such as "model view projection matrix" to a location.
  959. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location),
  960. texture_bindpoints: []Texture_Handle,
  961. texture_lookup: map[string]int,
  962. default_texture_index: Maybe(int),
  963. inputs: []Shader_Input,
  964. input_overrides: []Shader_Input_Value_Override,
  965. default_input_offsets: [Shader_Default_Inputs]int,
  966. vertex_size: int,
  967. }
  968. SHADER_INPUT_VALUE_MAX_SIZE :: 256
  969. Shader_Input_Value_Override :: struct {
  970. val: [SHADER_INPUT_VALUE_MAX_SIZE]u8,
  971. used: int,
  972. }
  973. Shader_Input_Type :: enum {
  974. F32,
  975. Vec2,
  976. Vec3,
  977. Vec4,
  978. }
  979. Shader_Builtin_Constant :: enum {
  980. MVP,
  981. }
  982. Shader_Default_Inputs :: enum {
  983. Unknown,
  984. Position,
  985. UV,
  986. Color,
  987. }
  988. Shader_Input :: struct {
  989. name: string,
  990. register: int,
  991. type: Shader_Input_Type,
  992. format: Pixel_Format,
  993. }
  994. Pixel_Format :: enum {
  995. Unknown,
  996. RGBA_32_Float,
  997. RGB_32_Float,
  998. RG_32_Float,
  999. R_32_Float,
  1000. RGBA_8_Norm,
  1001. RG_8_Norm,
  1002. R_8_Norm,
  1003. R_8_UInt,
  1004. }
  1005. Font :: struct {
  1006. atlas: Texture,
  1007. // internal
  1008. fontstash_handle: int,
  1009. }
  1010. Handle :: hm.Handle
  1011. Texture_Handle :: distinct Handle
  1012. Font_Handle :: distinct int
  1013. FONT_NONE :: Font_Handle(0)
  1014. TEXTURE_NONE :: Texture_Handle {}
  1015. // This keeps track of the internal state of the library. Usually, you do not need to poke at it.
  1016. // It is created and kept as a global variable when 'init' is called. However, 'init' also returns
  1017. // the pointer to it, so you can later use 'set_internal_state' to restore it (after for example hot
  1018. // reload).
  1019. State :: struct {
  1020. allocator: runtime.Allocator,
  1021. frame_arena: runtime.Arena,
  1022. frame_allocator: runtime.Allocator,
  1023. custom_context: runtime.Context,
  1024. win: Window_Interface,
  1025. window_state: rawptr,
  1026. rb: Render_Backend_Interface,
  1027. rb_state: rawptr,
  1028. fs: fs.FontContext,
  1029. shutdown_wanted: bool,
  1030. mouse_position: Vec2,
  1031. mouse_delta: Vec2,
  1032. mouse_wheel_delta: f32,
  1033. key_went_down: #sparse [Keyboard_Key]bool,
  1034. key_went_up: #sparse [Keyboard_Key]bool,
  1035. key_is_held: #sparse [Keyboard_Key]bool,
  1036. mouse_button_went_down: #sparse [Mouse_Button]bool,
  1037. mouse_button_went_up: #sparse [Mouse_Button]bool,
  1038. mouse_button_is_held: #sparse [Mouse_Button]bool,
  1039. gamepad_button_went_down: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1040. gamepad_button_went_up: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1041. gamepad_button_is_held: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1042. window: Window_Handle,
  1043. width: int,
  1044. height: int,
  1045. default_font: Font_Handle,
  1046. fonts: [dynamic]Font,
  1047. shape_drawing_texture: Texture_Handle,
  1048. batch_font: Font_Handle,
  1049. batch_camera: Maybe(Camera),
  1050. batch_shader: Shader,
  1051. batch_scissor: Maybe(Rect),
  1052. batch_texture: Texture_Handle,
  1053. view_matrix: Mat4,
  1054. proj_matrix: Mat4,
  1055. depth: f32,
  1056. depth_start: f32,
  1057. depth_increment: f32,
  1058. vertex_buffer_cpu: []u8,
  1059. vertex_buffer_cpu_used: int,
  1060. default_shader: Shader,
  1061. }
  1062. // Support for up to 255 mouse buttons. Cast an int to type `Mouse_Button` to use things outside the
  1063. // options presented here.
  1064. Mouse_Button :: enum {
  1065. Left,
  1066. Right,
  1067. Middle,
  1068. Max = 255,
  1069. }
  1070. // Based on Raylib / GLFW
  1071. Keyboard_Key :: enum {
  1072. None = 0,
  1073. // Numeric keys (top row)
  1074. N0 = 48,
  1075. N1 = 49,
  1076. N2 = 50,
  1077. N3 = 51,
  1078. N4 = 52,
  1079. N5 = 53,
  1080. N6 = 54,
  1081. N7 = 55,
  1082. N8 = 56,
  1083. N9 = 57,
  1084. // Letter keys
  1085. A = 65,
  1086. B = 66,
  1087. C = 67,
  1088. D = 68,
  1089. E = 69,
  1090. F = 70,
  1091. G = 71,
  1092. H = 72,
  1093. I = 73,
  1094. J = 74,
  1095. K = 75,
  1096. L = 76,
  1097. M = 77,
  1098. N = 78,
  1099. O = 79,
  1100. P = 80,
  1101. Q = 81,
  1102. R = 82,
  1103. S = 83,
  1104. T = 84,
  1105. U = 85,
  1106. V = 86,
  1107. W = 87,
  1108. X = 88,
  1109. Y = 89,
  1110. Z = 90,
  1111. // Special characters
  1112. Apostrophe = 39,
  1113. Comma = 44,
  1114. Minus = 45,
  1115. Period = 46,
  1116. Slash = 47,
  1117. Semicolon = 59,
  1118. Equal = 61,
  1119. Left_Bracket = 91,
  1120. Backslash = 92,
  1121. Right_Bracket = 93,
  1122. Grave_Accent = 96,
  1123. // Function keys, modifiers, caret control etc
  1124. Space = 32,
  1125. Escape = 256,
  1126. Enter = 257,
  1127. Tab = 258,
  1128. Backspace = 259,
  1129. Insert = 260,
  1130. Delete = 261,
  1131. Right = 262,
  1132. Left = 263,
  1133. Down = 264,
  1134. Up = 265,
  1135. Page_Up = 266,
  1136. Page_Down = 267,
  1137. Home = 268,
  1138. End = 269,
  1139. Caps_Lock = 280,
  1140. Scroll_Lock = 281,
  1141. Num_Lock = 282,
  1142. Print_Screen = 283,
  1143. Pause = 284,
  1144. F1 = 290,
  1145. F2 = 291,
  1146. F3 = 292,
  1147. F4 = 293,
  1148. F5 = 294,
  1149. F6 = 295,
  1150. F7 = 296,
  1151. F8 = 297,
  1152. F9 = 298,
  1153. F10 = 299,
  1154. F11 = 300,
  1155. F12 = 301,
  1156. Left_Shift = 340,
  1157. Left_Control = 341,
  1158. Left_Alt = 342,
  1159. Left_Super = 343,
  1160. Right_Shift = 344,
  1161. Right_Control = 345,
  1162. Right_Alt = 346,
  1163. Right_Super = 347,
  1164. Menu = 348,
  1165. // Numpad keys
  1166. NP_0 = 320,
  1167. NP_1 = 321,
  1168. NP_2 = 322,
  1169. NP_3 = 323,
  1170. NP_4 = 324,
  1171. NP_5 = 325,
  1172. NP_6 = 326,
  1173. NP_7 = 327,
  1174. NP_8 = 328,
  1175. NP_9 = 329,
  1176. NP_Decimal = 330,
  1177. NP_Divide = 331,
  1178. NP_Multiply = 332,
  1179. NP_Subtract = 333,
  1180. NP_Add = 334,
  1181. NP_Enter = 335,
  1182. NP_Equal = 336,
  1183. }
  1184. MAX_GAMEPADS :: 4
  1185. // A value between 0 and MAX_GAMEPADS - 1
  1186. Gamepad_Index :: int
  1187. Gamepad_Axis :: enum {
  1188. Left_Stick_X,
  1189. Left_Stick_Y,
  1190. Right_Stick_X,
  1191. Right_Stick_Y,
  1192. Left_Trigger,
  1193. Right_Trigger,
  1194. }
  1195. Gamepad_Button :: enum {
  1196. // DPAD buttons
  1197. Left_Face_Up,
  1198. Left_Face_Down,
  1199. Left_Face_Left,
  1200. Left_Face_Right,
  1201. Right_Face_Up, // XBOX: Y, PS: Triangle
  1202. Right_Face_Down, // XBOX: A, PS: X
  1203. Right_Face_Left, // XBOX: X, PS: Square
  1204. Right_Face_Right, // XBOX: B, PS: Circle
  1205. Left_Shoulder,
  1206. Left_Trigger,
  1207. Right_Shoulder,
  1208. Right_Trigger,
  1209. Left_Stick_Press, // Clicking the left analogue stick
  1210. Right_Stick_Press, // Clicking the right analogue stick
  1211. Middle_Face_Left, // Select / back / options button
  1212. Middle_Face_Middle, // PS button (not available on XBox)
  1213. Middle_Face_Right, // Start
  1214. }
  1215. // Used by API builder. Everything after this constant will not be in karl2d.doc.odin
  1216. API_END :: true
  1217. batch_vertex :: proc(v: Vec3, uv: Vec2, color: Color) {
  1218. v := v
  1219. if s.vertex_buffer_cpu_used == len(s.vertex_buffer_cpu) {
  1220. draw_current_batch()
  1221. }
  1222. shd := s.batch_shader
  1223. base_offset := s.vertex_buffer_cpu_used
  1224. pos_offset := shd.default_input_offsets[.Position]
  1225. uv_offset := shd.default_input_offsets[.UV]
  1226. color_offset := shd.default_input_offsets[.Color]
  1227. mem.set(&s.vertex_buffer_cpu[base_offset], 0, shd.vertex_size)
  1228. if pos_offset != -1 {
  1229. (^Vec3)(&s.vertex_buffer_cpu[base_offset + pos_offset])^ = v
  1230. }
  1231. if uv_offset != -1 {
  1232. (^Vec2)(&s.vertex_buffer_cpu[base_offset + uv_offset])^ = uv
  1233. }
  1234. if color_offset != -1 {
  1235. (^Color)(&s.vertex_buffer_cpu[base_offset + color_offset])^ = color
  1236. }
  1237. override_offset: int
  1238. for &o, idx in shd.input_overrides {
  1239. input := &shd.inputs[idx]
  1240. sz := pixel_format_size(input.format)
  1241. if o.used != 0 {
  1242. mem.copy(&s.vertex_buffer_cpu[base_offset + override_offset], raw_data(&o.val), o.used)
  1243. }
  1244. override_offset += sz
  1245. }
  1246. s.vertex_buffer_cpu_used += shd.vertex_size
  1247. }
  1248. VERTEX_BUFFER_MAX :: 1000000
  1249. @(private="file")
  1250. s: ^State
  1251. frame_allocator: runtime.Allocator
  1252. win: Window_Interface
  1253. rb: Render_Backend_Interface
  1254. get_shader_input_default_type :: proc(name: string, type: Shader_Input_Type) -> Shader_Default_Inputs {
  1255. if name == "position" && type == .Vec3 {
  1256. return .Position
  1257. } else if name == "texcoord" && type == .Vec2 {
  1258. return .UV
  1259. } else if name == "color" && type == .Vec4 {
  1260. return .Color
  1261. }
  1262. return .Unknown
  1263. }
  1264. get_shader_format_num_components :: proc(format: Pixel_Format) -> int {
  1265. switch format {
  1266. case .Unknown: return 0
  1267. case .RGBA_32_Float: return 4
  1268. case .RGB_32_Float: return 3
  1269. case .RG_32_Float: return 2
  1270. case .R_32_Float: return 1
  1271. case .RGBA_8_Norm: return 4
  1272. case .RG_8_Norm: return 2
  1273. case .R_8_Norm: return 1
  1274. case .R_8_UInt: return 1
  1275. }
  1276. return 0
  1277. }
  1278. get_shader_input_format :: proc(name: string, type: Shader_Input_Type) -> Pixel_Format {
  1279. default_type := get_shader_input_default_type(name, type)
  1280. if default_type != .Unknown {
  1281. switch default_type {
  1282. case .Position: return .RGB_32_Float
  1283. case .UV: return .RG_32_Float
  1284. case .Color: return .RGBA_8_Norm
  1285. case .Unknown: unreachable()
  1286. }
  1287. }
  1288. switch type {
  1289. case .F32: return .R_32_Float
  1290. case .Vec2: return .RG_32_Float
  1291. case .Vec3: return .RGB_32_Float
  1292. case .Vec4: return .RGBA_32_Float
  1293. }
  1294. return .Unknown
  1295. }
  1296. vec3_from_vec2 :: proc(v: Vec2) -> Vec3 {
  1297. return {
  1298. v.x, v.y, 0,
  1299. }
  1300. }
  1301. frame_cstring :: proc(str: string, loc := #caller_location) -> cstring {
  1302. return strings.clone_to_cstring(str, s.frame_allocator, loc)
  1303. }
  1304. @(require_results)
  1305. matrix_ortho3d_f32 :: proc "contextless" (left, right, bottom, top, near, far: f32) -> Mat4 #no_bounds_check {
  1306. m: Mat4
  1307. m[0, 0] = +2 / (right - left)
  1308. m[1, 1] = +2 / (top - bottom)
  1309. m[2, 2] = +1
  1310. m[0, 3] = -(right + left) / (right - left)
  1311. m[1, 3] = -(top + bottom) / (top - bottom)
  1312. m[2, 3] = 0
  1313. m[3, 3] = 1
  1314. return m
  1315. }
  1316. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  1317. return matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  1318. }
  1319. FONT_DEFAULT_ATLAS_SIZE :: 1024
  1320. update_font :: proc(fh: Font_Handle) {
  1321. font := &s.fonts[fh]
  1322. font_dirty_rect: [4]f32
  1323. tw := FONT_DEFAULT_ATLAS_SIZE
  1324. if fs.ValidateTexture(&s.fs, &font_dirty_rect) {
  1325. fdr := font_dirty_rect
  1326. r := Rect {
  1327. fdr[0],
  1328. fdr[1],
  1329. fdr[2] - fdr[0],
  1330. fdr[3] - fdr[1],
  1331. }
  1332. x := int(r.x)
  1333. y := int(r.y)
  1334. w := int(fdr[2]) - int(fdr[0])
  1335. h := int(fdr[3]) - int(fdr[1])
  1336. expanded_pixels := make([]Color, w * h, frame_allocator)
  1337. start := x + tw * y
  1338. for i in 0..<w*h {
  1339. px := i%w
  1340. py := i/w
  1341. dst_pixel_idx := (px) + (py * w)
  1342. src_pixel_idx := start + (px) + (py * tw)
  1343. src := s.fs.textureData[src_pixel_idx]
  1344. expanded_pixels[dst_pixel_idx] = {255,255,255, src}
  1345. }
  1346. rb.update_texture(font.atlas.handle, slice.reinterpret([]u8, expanded_pixels), r)
  1347. }
  1348. }
  1349. set_font :: proc(fh: Font_Handle) {
  1350. fh := fh
  1351. if s.batch_font == fh {
  1352. return
  1353. }
  1354. s.batch_font = fh
  1355. if s.batch_font != FONT_NONE {
  1356. update_font(s.batch_font)
  1357. }
  1358. if fh == 0 {
  1359. fh = s.default_font
  1360. }
  1361. font := &s.fonts[fh]
  1362. fs.SetFont(&s.fs, font.fontstash_handle)
  1363. }
  1364. DEPTH_START :: -0.99
  1365. DEPTH_INCREMENT :: (1.0/10000000.0)
  1366. _ :: jpeg
  1367. _ :: bmp
  1368. _ :: png
  1369. _ :: tga
  1370. Color_F32 :: [4]f32
  1371. f32_color_from_color :: proc(color: Color) -> Color_F32 {
  1372. return {
  1373. f32(color.r) / 255,
  1374. f32(color.g) / 255,
  1375. f32(color.b) / 255,
  1376. f32(color.a) / 255,
  1377. }
  1378. }