karl2d.odin 32 KB

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