karl2d.odin 32 KB

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