karl2d.odin 27 KB

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