karl2d.odin 31 KB

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