karl2d.odin 35 KB

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