karl2d.odin 36 KB

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