karl2d.odin 40 KB

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