karl2d.odin 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  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. allocator := context.allocator, loc := #caller_location) -> ^State {
  23. assert(s == nil, "Don't call 'init' twice.")
  24. s = new(State, allocator, loc)
  25. s.allocator = allocator
  26. s.custom_context = context
  27. s.width = window_width
  28. s.height = window_height
  29. s.win = WINDOW_INTERFACE_WIN32
  30. win = s.win
  31. window_state_alloc_error: runtime.Allocator_Error
  32. s.window_state, window_state_alloc_error = mem.alloc(win.state_size())
  33. log.assertf(window_state_alloc_error == nil, "Failed allocating memory for window state: %v", window_state_alloc_error)
  34. win.init(s.window_state, window_width, window_height, window_title, allocator)
  35. s.window = win.window_handle()
  36. s.rb = BACKEND_D3D11
  37. rb = s.rb
  38. rb_alloc_error: runtime.Allocator_Error
  39. s.rb_state, rb_alloc_error = mem.alloc(rb.state_size())
  40. log.assertf(rb_alloc_error == nil, "Failed allocating memory for rendering backend: %v", rb_alloc_error)
  41. s.proj_matrix = make_default_projection(window_width, window_height)
  42. s.view_matrix = 1
  43. rb.init(s.rb_state, s.window, window_width, window_height, allocator)
  44. s.vertex_buffer_cpu = make([]u8, VERTEX_BUFFER_MAX, allocator, loc)
  45. white_rect: [16*16*4]u8
  46. slice.fill(white_rect[:], 255)
  47. s.shape_drawing_texture = rb.load_texture(white_rect[:], 16, 16)
  48. s.default_shader = load_shader(string(DEFAULT_SHADER_SOURCE))
  49. return s
  50. }
  51. // Returns true if the program wants to shut down. This happens when for example pressing the close
  52. // button on the window. The application can decide if it wants to shut down or if it wants to show
  53. // some kind of confirmation dialogue and shut down later.
  54. //
  55. // Commonly used for creating the "main loop" of a game.
  56. shutdown_wanted :: proc() -> bool {
  57. return s.shutdown_wanted
  58. }
  59. // Closes the window and cleans up the internal state.
  60. shutdown :: proc() {
  61. assert(s != nil, "You've called 'shutdown' without calling 'init' first")
  62. rb.destroy_texture(s.shape_drawing_texture)
  63. destroy_shader(s.default_shader)
  64. rb.shutdown()
  65. delete(s.vertex_buffer_cpu, s.allocator)
  66. win.shutdown()
  67. a := s.allocator
  68. free(s.window_state, a)
  69. free(s.rb_state, a)
  70. free(s, a)
  71. s = nil
  72. }
  73. // Clear the backbuffer with supplied color.
  74. clear :: proc(color: Color) {
  75. rb.clear(color)
  76. }
  77. // Present the backbuffer. Call at end of frame to make everything you've drawn appear on the screen.
  78. present :: proc() {
  79. draw_current_batch()
  80. rb.present()
  81. }
  82. // Call at start or end of frame to process all events that have arrived to the window.
  83. //
  84. // WARNING: Not calling this will make your program impossible to interact with.
  85. process_events :: proc() {
  86. s.keys_went_up = {}
  87. s.keys_went_down = {}
  88. s.mouse_delta = {}
  89. s.mouse_wheel_delta = 0
  90. win.process_events()
  91. events := win.get_events()
  92. for &event in events {
  93. switch &e in event {
  94. case Window_Event_Close_Wanted:
  95. s.shutdown_wanted = true
  96. case Window_Event_Key_Went_Down:
  97. s.keys_went_down[e.key] = true
  98. s.keys_is_held[e.key] = true
  99. case Window_Event_Key_Went_Up:
  100. s.keys_is_held[e.key] = false
  101. s.keys_went_up[e.key] = true
  102. case Window_Event_Mouse_Move:
  103. prev_pos := s.mouse_position
  104. s.mouse_position = e.position
  105. s.mouse_delta = prev_pos - s.mouse_position
  106. case Window_Event_Mouse_Wheel:
  107. s.mouse_wheel_delta = e.delta
  108. }
  109. }
  110. win.clear_events()
  111. }
  112. get_screen_width :: proc() -> int {
  113. return rb.get_swapchain_width()
  114. }
  115. get_screen_height :: proc() -> int {
  116. return rb.get_swapchain_height()
  117. }
  118. set_window_position :: proc(x: int, y: int) {
  119. win.set_position(x, y)
  120. }
  121. set_window_size :: proc(width: int, height: int) {
  122. panic("Not implemented")
  123. }
  124. // Flushes the current batch. This sends off everything to the GPU that has been queued in the
  125. // current batch. Normally, you do not need to do this manually. It is done automatically when these
  126. // procedures run:
  127. // present
  128. // set_camera
  129. // set_shader
  130. //
  131. // TODO: complete this list and motivate why it needs to happen on those procs (or do that in the
  132. // docs for those procs).
  133. draw_current_batch :: proc() {
  134. shader := s.batch_shader.? or_else s.default_shader
  135. rb.draw(shader, s.batch_texture, s.proj_matrix * s.view_matrix, s.vertex_buffer_cpu[:s.vertex_buffer_cpu_used])
  136. s.vertex_buffer_cpu_used = 0
  137. }
  138. //-------//
  139. // INPUT //
  140. //-------//
  141. // Returns true if a keyboard key went down between the current and the previous frame. Set when
  142. // 'process_events' runs (probably once per frame).
  143. key_went_down :: proc(key: Keyboard_Key) -> bool {
  144. return s.keys_went_down[key]
  145. }
  146. // Returns true if a keyboard key went up (was released) between the current and the previous frame.
  147. // Set when 'process_events' runs (probably once per frame).
  148. key_went_up :: proc(key: Keyboard_Key) -> bool {
  149. return s.keys_went_up[key]
  150. }
  151. // Returns true if a keyboard is currently being held down. Set when 'process_events' runs (probably
  152. // once per frame).
  153. key_is_held :: proc(key: Keyboard_Key) -> bool {
  154. return s.keys_is_held[key]
  155. }
  156. mouse_button_went_down :: proc(button: Mouse_Button) -> bool {
  157. panic("not implemented")
  158. }
  159. mouse_button_went_up :: proc(button: Mouse_Button) -> bool {
  160. panic("not implemented")
  161. }
  162. mouse_button_is_held :: proc(button: Mouse_Button) -> bool {
  163. panic("not implemented")
  164. }
  165. get_mouse_wheel_delta :: proc() -> f32 {
  166. return s.mouse_wheel_delta
  167. }
  168. get_mouse_position :: proc() -> Vec2 {
  169. return s.mouse_position
  170. }
  171. //---------//
  172. // DRAWING //
  173. //---------//
  174. draw_rect :: proc(r: Rect, c: Color) {
  175. if s.batch_texture != TEXTURE_NONE && s.batch_texture != s.shape_drawing_texture {
  176. draw_current_batch()
  177. }
  178. s.batch_texture = s.shape_drawing_texture
  179. batch_vertex({r.x, r.y}, {0, 0}, c)
  180. batch_vertex({r.x + r.w, r.y}, {1, 0}, c)
  181. batch_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
  182. batch_vertex({r.x, r.y}, {0, 0}, c)
  183. batch_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
  184. batch_vertex({r.x, r.y + r.h}, {0, 1}, c)
  185. }
  186. draw_rect_ex :: proc(r: Rect, origin: Vec2, rot: f32, c: Color) {
  187. if s.batch_texture != TEXTURE_NONE && s.batch_texture != s.shape_drawing_texture {
  188. draw_current_batch()
  189. }
  190. s.batch_texture = s.shape_drawing_texture
  191. tl, tr, bl, br: Vec2
  192. // Rotation adapted from Raylib's "DrawTexturePro"
  193. if rot == 0 {
  194. x := r.x - origin.x
  195. y := r.y - origin.y
  196. tl = { x, y }
  197. tr = { x + r.w, y }
  198. bl = { x, y + r.h }
  199. br = { x + r.w, y + r.h }
  200. } else {
  201. sin_rot := math.sin(rot * math.RAD_PER_DEG)
  202. cos_rot := math.cos(rot * math.RAD_PER_DEG)
  203. x := r.x
  204. y := r.y
  205. dx := -origin.x
  206. dy := -origin.y
  207. tl = {
  208. x + dx * cos_rot - dy * sin_rot,
  209. y + dx * sin_rot + dy * cos_rot,
  210. }
  211. tr = {
  212. x + (dx + r.w) * cos_rot - dy * sin_rot,
  213. y + (dx + r.w) * sin_rot + dy * cos_rot,
  214. }
  215. bl = {
  216. x + dx * cos_rot - (dy + r.h) * sin_rot,
  217. y + dx * sin_rot + (dy + r.h) * cos_rot,
  218. }
  219. br = {
  220. x + (dx + r.w) * cos_rot - (dy + r.h) * sin_rot,
  221. y + (dx + r.w) * sin_rot + (dy + r.h) * cos_rot,
  222. }
  223. }
  224. batch_vertex(tl, {0, 0}, c)
  225. batch_vertex(tr, {1, 0}, c)
  226. batch_vertex(br, {1, 1}, c)
  227. batch_vertex(tl, {0, 0}, c)
  228. batch_vertex(br, {1, 1}, c)
  229. batch_vertex(bl, {0, 1}, c)
  230. }
  231. draw_rect_outline :: proc(r: Rect, thickness: f32, color: Color) {
  232. t := thickness
  233. // Based on DrawRectangleLinesEx from Raylib
  234. top := Rect {
  235. r.x,
  236. r.y,
  237. r.w,
  238. t,
  239. }
  240. bottom := Rect {
  241. r.x,
  242. r.y + r.h - t,
  243. r.w,
  244. t,
  245. }
  246. left := Rect {
  247. r.x,
  248. r.y + t,
  249. t,
  250. r.h - t * 2,
  251. }
  252. right := Rect {
  253. r.x + r.w - t,
  254. r.y + t,
  255. t,
  256. r.h - t * 2,
  257. }
  258. draw_rect(top, color)
  259. draw_rect(bottom, color)
  260. draw_rect(left, color)
  261. draw_rect(right, color)
  262. }
  263. draw_circle :: proc(center: Vec2, radius: f32, color: Color, segments := 16) {
  264. if s.batch_texture != TEXTURE_NONE && s.batch_texture != s.shape_drawing_texture {
  265. draw_current_batch()
  266. }
  267. s.batch_texture = s.shape_drawing_texture
  268. prev := center + {radius, 0}
  269. for s in 1..=segments {
  270. sr := (f32(s)/f32(segments)) * 2*math.PI
  271. rot := linalg.matrix2_rotate(sr)
  272. p := center + rot * Vec2{radius, 0}
  273. batch_vertex(prev, {0, 0}, color)
  274. batch_vertex(p, {1, 0}, color)
  275. batch_vertex(center, {1, 1}, color)
  276. prev = p
  277. }
  278. }
  279. draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  280. p := Vec2{start.x, start.y + thickness*0.5}
  281. s := Vec2{linalg.length(end - start), thickness}
  282. origin := Vec2 {0, thickness*0.5}
  283. r := Rect {p.x, p.y, s.x, s.y}
  284. rot := math.atan2(end.y - start.y, end.x - start.x)
  285. draw_rect_ex(r, origin, rot * math.DEG_PER_RAD, color)
  286. }
  287. draw_texture :: proc(tex: Texture, pos: Vec2, tint := WHITE) {
  288. draw_texture_ex(
  289. tex,
  290. {0, 0, f32(tex.width), f32(tex.height)},
  291. {pos.x, pos.y, f32(tex.width), f32(tex.height)},
  292. {},
  293. 0,
  294. tint,
  295. )
  296. }
  297. draw_texture_rect :: proc(tex: Texture, rect: Rect, pos: Vec2, tint := WHITE) {
  298. draw_texture_ex(
  299. tex,
  300. rect,
  301. {pos.x, pos.y, rect.w, rect.h},
  302. {},
  303. 0,
  304. tint,
  305. )
  306. }
  307. draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rotation: f32, tint := WHITE) {
  308. if tex.width == 0 || tex.height == 0 {
  309. return
  310. }
  311. if s.batch_texture != TEXTURE_NONE && s.batch_texture != tex.handle {
  312. draw_current_batch()
  313. }
  314. flip_x, flip_y: bool
  315. src := src
  316. dst := dst
  317. if src.w < 0 {
  318. flip_x = true
  319. src.w = -src.w
  320. }
  321. if src.h < 0 {
  322. flip_y = true
  323. src.h = -src.h
  324. }
  325. if dst.w < 0 {
  326. dst.w *= -1
  327. }
  328. if dst.h < 0 {
  329. dst.h *= -1
  330. }
  331. s.batch_texture = tex.handle
  332. tl, tr, bl, br: Vec2
  333. // Rotation adapted from Raylib's "DrawTexturePro"
  334. if rotation == 0 {
  335. x := dst.x - origin.x
  336. y := dst.y - origin.y
  337. tl = { x, y }
  338. tr = { x + dst.w, y }
  339. bl = { x, y + dst.h }
  340. br = { x + dst.w, y + dst.h }
  341. } else {
  342. sin_rot := math.sin(rotation * math.RAD_PER_DEG)
  343. cos_rot := math.cos(rotation * math.RAD_PER_DEG)
  344. x := dst.x
  345. y := dst.y
  346. dx := -origin.x
  347. dy := -origin.y
  348. tl = {
  349. x + dx * cos_rot - dy * sin_rot,
  350. y + dx * sin_rot + dy * cos_rot,
  351. }
  352. tr = {
  353. x + (dx + dst.w) * cos_rot - dy * sin_rot,
  354. y + (dx + dst.w) * sin_rot + dy * cos_rot,
  355. }
  356. bl = {
  357. x + dx * cos_rot - (dy + dst.h) * sin_rot,
  358. y + dx * sin_rot + (dy + dst.h) * cos_rot,
  359. }
  360. br = {
  361. x + (dx + dst.w) * cos_rot - (dy + dst.h) * sin_rot,
  362. y + (dx + dst.w) * sin_rot + (dy + dst.h) * cos_rot,
  363. }
  364. }
  365. ts := Vec2{f32(tex.width), f32(tex.height)}
  366. up := Vec2{src.x, src.y} / ts
  367. us := Vec2{src.w, src.h} / ts
  368. c := tint
  369. uv0 := up
  370. uv1 := up + {us.x, 0}
  371. uv2 := up + us
  372. uv3 := up
  373. uv4 := up + us
  374. uv5 := up + {0, us.y}
  375. if flip_x {
  376. uv0.x += us.x
  377. uv1.x -= us.x
  378. uv2.x -= us.x
  379. uv3.x += us.x
  380. uv4.x -= us.x
  381. uv5.x += us.x
  382. }
  383. if flip_y {
  384. uv0.y += us.y
  385. uv1.y += us.y
  386. uv2.y -= us.y
  387. uv3.y += us.y
  388. uv4.y -= us.y
  389. uv5.y -= us.y
  390. }
  391. batch_vertex(tl, uv0, c)
  392. batch_vertex(tr, uv1, c)
  393. batch_vertex(br, uv2, c)
  394. batch_vertex(tl, uv3, c)
  395. batch_vertex(br, uv4, c)
  396. batch_vertex(bl, uv5, c)
  397. }
  398. draw_text :: proc(text: string, pos: Vec2, font_size: f32, color: Color) {
  399. }
  400. //--------------------//
  401. // TEXTURE MANAGEMENT //
  402. //--------------------//
  403. load_texture_from_file :: proc(filename: string) -> Texture {
  404. img, img_err := image.load_from_file(filename, options = {.alpha_add_if_missing}, allocator = context.temp_allocator)
  405. if img_err != nil {
  406. log.errorf("Error loading texture %v: %v", filename, img_err)
  407. return {}
  408. }
  409. backend_tex := rb.load_texture(img.pixels.buf[:], img.width, img.height)
  410. return {
  411. handle = backend_tex,
  412. width = img.width,
  413. height = img.height,
  414. }
  415. }
  416. destroy_texture :: proc(tex: Texture) {
  417. rb.destroy_texture(tex.handle)
  418. }
  419. //---------//
  420. // SHADERS //
  421. //---------//
  422. load_shader :: proc(shader_source: string, layout_formats: []Shader_Input_Format = {}) -> Shader {
  423. handle, desc := rb.load_shader(shader_source, context.temp_allocator, layout_formats)
  424. if handle == SHADER_NONE {
  425. log.error("Failed loading shader")
  426. return {}
  427. }
  428. shd := Shader {
  429. handle = handle,
  430. constant_buffers = make([]Shader_Constant_Buffer, len(desc.constant_buffers), s.allocator),
  431. constant_lookup = make(map[string]Shader_Constant_Location, s.allocator),
  432. inputs = slice.clone(desc.inputs, s.allocator),
  433. input_overrides = make([]Shader_Input_Value_Override, len(desc.inputs), s.allocator),
  434. }
  435. for &input in shd.inputs {
  436. input.name = strings.clone(input.name, s.allocator)
  437. }
  438. for cb_idx in 0..<len(desc.constant_buffers) {
  439. cb_desc := &desc.constant_buffers[cb_idx]
  440. shd.constant_buffers[cb_idx] = {
  441. cpu_data = make([]u8, desc.constant_buffers[cb_idx].size, s.allocator),
  442. }
  443. for &v in cb_desc.variables {
  444. if v.name == "" {
  445. continue
  446. }
  447. shd.constant_lookup[strings.clone(v.name, s.allocator)] = v.loc
  448. switch v.name {
  449. case "mvp":
  450. shd.constant_builtin_locations[.MVP] = v.loc
  451. }
  452. }
  453. }
  454. for &d in shd.default_input_offsets {
  455. d = -1
  456. }
  457. input_offset: int
  458. for &input in shd.inputs {
  459. default_format := get_shader_input_default_type(input.name, input.type)
  460. if default_format != .Unknown {
  461. shd.default_input_offsets[default_format] = input_offset
  462. }
  463. input_offset += shader_input_format_size(input.format)
  464. }
  465. shd.vertex_size = input_offset
  466. return shd
  467. }
  468. destroy_shader :: proc(shader: Shader) {
  469. rb.destroy_shader(shader.handle)
  470. for c in shader.constant_buffers {
  471. delete(c.cpu_data)
  472. }
  473. delete(shader.constant_buffers)
  474. for k, _ in shader.constant_lookup {
  475. delete(k)
  476. }
  477. delete(shader.constant_lookup)
  478. for i in shader.inputs {
  479. delete(i.name)
  480. }
  481. delete(shader.inputs)
  482. delete(shader.input_overrides)
  483. }
  484. get_default_shader :: proc() -> Shader {
  485. return s.default_shader
  486. }
  487. set_shader :: proc(shader: Maybe(Shader)) {
  488. if maybe_handle_equal(shader, s.batch_shader) {
  489. return
  490. }
  491. draw_current_batch()
  492. s.batch_shader = shader
  493. }
  494. set_shader_constant :: proc(shd: Shader, loc: Shader_Constant_Location, val: any) {
  495. draw_current_batch()
  496. if int(loc.buffer_idx) >= len(shd.constant_buffers) {
  497. log.warnf("Constant buffer idx %v is out of bounds", loc.buffer_idx)
  498. return
  499. }
  500. sz := reflect.size_of_typeid(val.id)
  501. b := &shd.constant_buffers[loc.buffer_idx]
  502. if int(loc.offset) + sz > len(b.cpu_data) {
  503. 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))
  504. return
  505. }
  506. mem.copy(&b.cpu_data[loc.offset], val.data, sz)
  507. }
  508. override_shader_input :: proc(shader: Shader, input: int, val: any) {
  509. sz := reflect.size_of_typeid(val.id)
  510. assert(sz < SHADER_INPUT_VALUE_MAX_SIZE)
  511. if input >= len(shader.input_overrides) {
  512. log.errorf("Input override out of range. Wanted to override input %v, but shader only has %v inputs", input, len(shader.input_overrides))
  513. return
  514. }
  515. o := &shader.input_overrides[input]
  516. o.val = {}
  517. if sz > 0 {
  518. mem.copy(raw_data(&o.val), val.data, sz)
  519. }
  520. o.used = sz
  521. }
  522. shader_input_format_size :: proc(f: Shader_Input_Format) -> int {
  523. switch f {
  524. case .Unknown: return 0
  525. case .RGBA32_Float: return 32
  526. case .RGBA8_Norm: return 4
  527. case .RGBA8_Norm_SRGB: return 4
  528. case .RGB32_Float: return 12
  529. case .RG32_Float: return 8
  530. case .R32_Float: return 4
  531. }
  532. return 0
  533. }
  534. //-------------------------------//
  535. // CAMERA AND COORDINATE SYSTEMS //
  536. //-------------------------------//
  537. set_camera :: proc(camera: Maybe(Camera)) {
  538. if camera == s.batch_camera {
  539. return
  540. }
  541. draw_current_batch()
  542. s.batch_camera = camera
  543. s.proj_matrix = make_default_projection(s.width, s.height)
  544. if c, c_ok := camera.?; c_ok {
  545. origin_trans := linalg.matrix4_translate(vec3_from_vec2(-c.origin))
  546. translate := linalg.matrix4_translate(vec3_from_vec2(c.target))
  547. scale := linalg.matrix4_scale(Vec3{1/c.zoom, 1/c.zoom, 1})
  548. rot := linalg.matrix4_rotate_f32(c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  549. camera_matrix := translate * scale * rot * origin_trans
  550. s.view_matrix = linalg.inverse(camera_matrix)
  551. } else {
  552. s.view_matrix = 1
  553. }
  554. }
  555. screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  556. panic("not implemented")
  557. }
  558. //------//
  559. // MISC //
  560. //------//
  561. set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  562. panic("not implemented")
  563. }
  564. // Restore the internal state using the pointer returned by `init`. Useful after reloading the
  565. // library (for example, when doing code hot reload).
  566. set_internal_state :: proc(state: ^State) {
  567. s = state
  568. rb = s.rb
  569. win = s.win
  570. rb.set_internal_state(s.rb_state)
  571. win.set_internal_state(s.window_state)
  572. }
  573. //---------------------//
  574. // TYPES AND CONSTANTS //
  575. //---------------------//
  576. // A RGBA (Red, Greeen, Blue, Alpha) color. Each channel can have a value between 0 and 255.
  577. Color :: [4]u8
  578. // A two dimensinal vector.
  579. Vec2 :: [2]f32
  580. // A three dimensinal vector.
  581. Vec3 :: [3]f32
  582. // A 4x4 column-major matrix.
  583. Mat4 :: matrix[4,4]f32
  584. // A two dimensional vector of integer numeric type.
  585. Vec2i :: [2]int
  586. // A rectangle that sits at position (x, y) and has size (w, h).
  587. Rect :: struct {
  588. x, y: f32,
  589. w, h: f32,
  590. }
  591. Texture :: struct {
  592. handle: Texture_Handle,
  593. width: int,
  594. height: int,
  595. }
  596. Camera :: struct {
  597. target: Vec2,
  598. origin: Vec2,
  599. rotation: f32,
  600. zoom: f32,
  601. }
  602. Shader_Handle :: distinct Handle
  603. SHADER_NONE :: Shader_Handle {}
  604. Shader :: struct {
  605. handle: Shader_Handle,
  606. constant_buffers: []Shader_Constant_Buffer,
  607. constant_lookup: map[string]Shader_Constant_Location,
  608. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location),
  609. inputs: []Shader_Input,
  610. input_overrides: []Shader_Input_Value_Override,
  611. default_input_offsets: [Shader_Default_Inputs]int,
  612. vertex_size: int,
  613. }
  614. Shader_Constant_Buffer :: struct {
  615. cpu_data: []u8,
  616. }
  617. SHADER_INPUT_VALUE_MAX_SIZE :: 256
  618. Shader_Input_Value_Override :: struct {
  619. val: [SHADER_INPUT_VALUE_MAX_SIZE]u8,
  620. used: int,
  621. }
  622. Shader_Input_Type :: enum {
  623. F32,
  624. Vec2,
  625. Vec3,
  626. Vec4,
  627. }
  628. Shader_Builtin_Constant :: enum {
  629. MVP,
  630. }
  631. Shader_Default_Inputs :: enum {
  632. Unknown,
  633. Position,
  634. UV,
  635. Color,
  636. }
  637. Shader_Input :: struct {
  638. name: string,
  639. register: int,
  640. type: Shader_Input_Type,
  641. format: Shader_Input_Format,
  642. }
  643. Shader_Constant_Location :: struct {
  644. buffer_idx: u32,
  645. offset: u32,
  646. }
  647. Shader_Input_Format :: enum {
  648. Unknown,
  649. RGBA32_Float,
  650. RGBA8_Norm,
  651. RGBA8_Norm_SRGB,
  652. RGB32_Float,
  653. RG32_Float,
  654. R32_Float,
  655. }
  656. Handle :: hm.Handle
  657. Texture_Handle :: distinct Handle
  658. TEXTURE_NONE :: Texture_Handle {}
  659. // This keeps track of the internal state of the library. Usually, you do not need to poke at it.
  660. // It is created and kept as a global variable when 'init' is called. However, 'init' also returns
  661. // the pointer to it, so you can later use 'set_internal_state' to restore it (after for example hot
  662. // reload).
  663. State :: struct {
  664. allocator: runtime.Allocator,
  665. custom_context: runtime.Context,
  666. win: Window_Interface,
  667. window_state: rawptr,
  668. rb: Rendering_Backend_Interface,
  669. rb_state: rawptr,
  670. shutdown_wanted: bool,
  671. mouse_position: Vec2,
  672. mouse_delta: Vec2,
  673. mouse_wheel_delta: f32,
  674. keys_went_down: #sparse [Keyboard_Key]bool,
  675. keys_went_up: #sparse [Keyboard_Key]bool,
  676. keys_is_held: #sparse [Keyboard_Key]bool,
  677. window: Window_Handle,
  678. width: int,
  679. height: int,
  680. shape_drawing_texture: Texture_Handle,
  681. batch_camera: Maybe(Camera),
  682. batch_shader: Maybe(Shader),
  683. batch_texture: Texture_Handle,
  684. view_matrix: Mat4,
  685. proj_matrix: Mat4,
  686. vertex_buffer_cpu: []u8,
  687. vertex_buffer_cpu_used: int,
  688. default_shader: Shader,
  689. }
  690. // Support for up to 255 mouse buttons. Cast an int to type `Mouse_Button` to use things outside the
  691. // options presented here.
  692. Mouse_Button :: enum {
  693. Left,
  694. Right,
  695. Middle,
  696. Max = 255,
  697. }
  698. WHITE :: Color { 255, 255, 255, 255 }
  699. BLACK :: Color { 0, 0, 0, 255 }
  700. BLANK :: Color { 0, 0, 0, 0}
  701. // These are from Raylib. They are here so you can easily port a Raylib program to Karl2D.
  702. RL_LIGHTGRAY :: Color { 200, 200, 200, 255 }
  703. RL_GRAY :: Color { 130, 130, 130, 255 }
  704. RL_DARKGRAY :: Color { 80, 80, 80, 255 }
  705. RL_YELLOW :: Color { 253, 249, 0, 255 }
  706. RL_GOLD :: Color { 255, 203, 0, 255 }
  707. RL_ORANGE :: Color { 255, 161, 0, 255 }
  708. RL_PINK :: Color { 255, 109, 194, 255 }
  709. RL_RED :: Color { 230, 41, 55, 255 }
  710. RL_MAROON :: Color { 190, 33, 55, 255 }
  711. RL_GREEN :: Color { 0, 228, 48, 255 }
  712. RL_LIME :: Color { 0, 158, 47, 255 }
  713. RL_DARKGREEN :: Color { 0, 117, 44, 255 }
  714. RL_SKYBLUE :: Color { 102, 191, 255, 255 }
  715. RL_BLUE :: Color { 0, 121, 241, 255 }
  716. RL_DARKBLUE :: Color { 0, 82, 172, 255 }
  717. RL_PURPLE :: Color { 200, 122, 255, 255 }
  718. RL_VIOLET :: Color { 135, 60, 190, 255 }
  719. RL_DARKPURPLE :: Color { 112, 31, 126, 255 }
  720. RL_BEIGE :: Color { 211, 176, 131, 255 }
  721. RL_BROWN :: Color { 127, 106, 79, 255 }
  722. RL_DARKBROWN :: Color { 76, 63, 47, 255 }
  723. RL_WHITE :: WHITE
  724. RL_BLACK :: BLACK
  725. RL_BLANK :: BLANK
  726. RL_MAGENTA :: Color { 255, 0, 255, 255 }
  727. RL_RAYWHITE :: Color { 245, 245, 245, 255 }
  728. // Based on Raylib / GLFW
  729. Keyboard_Key :: enum {
  730. None = 0,
  731. // Alphanumeric keys
  732. Apostrophe = 39,
  733. Comma = 44,
  734. Minus = 45,
  735. Period = 46,
  736. Slash = 47,
  737. Zero = 48,
  738. One = 49,
  739. Two = 50,
  740. Three = 51,
  741. Four = 52,
  742. Five = 53,
  743. Six = 54,
  744. Seven = 55,
  745. Eight = 56,
  746. Nine = 57,
  747. Semicolon = 59,
  748. Equal = 61,
  749. A = 65,
  750. B = 66,
  751. C = 67,
  752. D = 68,
  753. E = 69,
  754. F = 70,
  755. G = 71,
  756. H = 72,
  757. I = 73,
  758. J = 74,
  759. K = 75,
  760. L = 76,
  761. M = 77,
  762. N = 78,
  763. O = 79,
  764. P = 80,
  765. Q = 81,
  766. R = 82,
  767. S = 83,
  768. T = 84,
  769. U = 85,
  770. V = 86,
  771. W = 87,
  772. X = 88,
  773. Y = 89,
  774. Z = 90,
  775. Left_Bracket = 91,
  776. Backslash = 92,
  777. Right_Bracket = 93,
  778. Grave = 96,
  779. // Function keys
  780. Space = 32,
  781. Escape = 256,
  782. Enter = 257,
  783. Tab = 258,
  784. Backspace = 259,
  785. Insert = 260,
  786. Delete = 261,
  787. Right = 262,
  788. Left = 263,
  789. Down = 264,
  790. Up = 265,
  791. Page_Up = 266,
  792. Page_Down = 267,
  793. Home = 268,
  794. End = 269,
  795. Caps_Lock = 280,
  796. Scroll_Lock = 281,
  797. Num_Lock = 282,
  798. Print_Screen = 283,
  799. Pause = 284,
  800. F1 = 290,
  801. F2 = 291,
  802. F3 = 292,
  803. F4 = 293,
  804. F5 = 294,
  805. F6 = 295,
  806. F7 = 296,
  807. F8 = 297,
  808. F9 = 298,
  809. F10 = 299,
  810. F11 = 300,
  811. F12 = 301,
  812. Left_Shift = 340,
  813. Left_Control = 341,
  814. Left_Alt = 342,
  815. Left_Super = 343,
  816. Right_Shift = 344,
  817. Right_Control = 345,
  818. Right_Alt = 346,
  819. Right_Super = 347,
  820. Menu = 348,
  821. // Keypad keys
  822. KP_0 = 320,
  823. KP_1 = 321,
  824. KP_2 = 322,
  825. KP_3 = 323,
  826. KP_4 = 324,
  827. KP_5 = 325,
  828. KP_6 = 326,
  829. KP_7 = 327,
  830. KP_8 = 328,
  831. KP_9 = 329,
  832. KP_Decimal = 330,
  833. KP_Divide = 331,
  834. KP_Multiply = 332,
  835. KP_Subtract = 333,
  836. KP_Add = 334,
  837. KP_Enter = 335,
  838. KP_Equal = 336,
  839. }
  840. // Used by API builder. Everything after this constant will not be in karl2d_api.txt
  841. API_END :: true
  842. batch_vertex :: proc(v: Vec2, uv: Vec2, color: Color) {
  843. v := v
  844. if s.vertex_buffer_cpu_used == len(s.vertex_buffer_cpu) {
  845. panic("Must dispatch here")
  846. }
  847. shd := s.batch_shader.? or_else s.default_shader
  848. base_offset := s.vertex_buffer_cpu_used
  849. pos_offset := shd.default_input_offsets[.Position]
  850. uv_offset := shd.default_input_offsets[.UV]
  851. color_offset := shd.default_input_offsets[.Color]
  852. mem.set(&s.vertex_buffer_cpu[base_offset], 0, shd.vertex_size)
  853. if pos_offset != -1 {
  854. (^Vec2)(&s.vertex_buffer_cpu[base_offset + pos_offset])^ = {v.x, v.y}
  855. }
  856. if uv_offset != -1 {
  857. (^Vec2)(&s.vertex_buffer_cpu[base_offset + uv_offset])^ = uv
  858. }
  859. if color_offset != -1 {
  860. (^Color)(&s.vertex_buffer_cpu[base_offset + color_offset])^ = color
  861. }
  862. override_offset: int
  863. for &o, idx in shd.input_overrides {
  864. input := &shd.inputs[idx]
  865. sz := shader_input_format_size(input.format)
  866. if o.used != 0 {
  867. mem.copy(&s.vertex_buffer_cpu[base_offset + override_offset], raw_data(&o.val), o.used)
  868. }
  869. override_offset += sz
  870. }
  871. s.vertex_buffer_cpu_used += shd.vertex_size
  872. }
  873. VERTEX_BUFFER_MAX :: 1000000
  874. DEFAULT_SHADER_SOURCE :: #load("shader.hlsl")
  875. @(private="file")
  876. s: ^State
  877. win: Window_Interface
  878. rb: Rendering_Backend_Interface
  879. maybe_handle_equal :: proc(m1: Maybe($T), m2: Maybe(T)) -> bool {
  880. if m1 == nil && m2 == nil {
  881. return true
  882. }
  883. m1v, m1v_ok := m1.?
  884. m2v, m2v_ok := m2.?
  885. if !m1v_ok || !m2v_ok {
  886. return false
  887. }
  888. return m1v.handle == m2v.handle
  889. }
  890. get_shader_input_default_type :: proc(name: string, type: Shader_Input_Type) -> Shader_Default_Inputs {
  891. if name == "POS" && type == .Vec2 {
  892. return .Position
  893. } else if name == "UV" && type == .Vec2 {
  894. return .UV
  895. } else if name == "COL" && type == .Vec4 {
  896. return .Color
  897. }
  898. return .Unknown
  899. }
  900. get_shader_input_format :: proc(name: string, type: Shader_Input_Type) -> Shader_Input_Format {
  901. default_type := get_shader_input_default_type(name, type)
  902. if default_type != .Unknown {
  903. switch default_type {
  904. case .Position: return .RG32_Float
  905. case .UV: return .RG32_Float
  906. case .Color: return .RGBA8_Norm
  907. case .Unknown: unreachable()
  908. }
  909. }
  910. switch type {
  911. case .F32: return .R32_Float
  912. case .Vec2: return .RG32_Float
  913. case .Vec3: return .RGB32_Float
  914. case .Vec4: return .RGBA32_Float
  915. }
  916. return .Unknown
  917. }
  918. vec3_from_vec2 :: proc(v: Vec2) -> Vec3 {
  919. return {
  920. v.x, v.y, 0,
  921. }
  922. }
  923. temp_cstring :: proc(str: string, loc := #caller_location) -> cstring {
  924. return strings.clone_to_cstring(str, context.temp_allocator, loc)
  925. }
  926. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  927. return linalg.matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  928. }
  929. _ :: bmp
  930. _ :: png
  931. _ :: tga