karl2d.odin 44 KB

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