karl2d.odin 39 KB

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