karl2d.odin 37 KB

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