karl2d.odin 28 KB

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