render_backend_gl.odin 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. #+build windows, darwin, linux
  2. #+private file
  3. package karl2d
  4. @(private="package")
  5. RENDER_BACKEND_INTERFACE_GL :: Render_Backend_Interface {
  6. state_size = gl_state_size,
  7. init = gl_init,
  8. shutdown = gl_shutdown,
  9. clear = gl_clear,
  10. present = gl_present,
  11. draw = gl_draw,
  12. resize_swapchain = gl_resize_swapchain,
  13. get_swapchain_width = gl_get_swapchain_width,
  14. get_swapchain_height = gl_get_swapchain_height,
  15. flip_z = gl_flip_z,
  16. set_internal_state = gl_set_internal_state,
  17. create_texture = gl_create_texture,
  18. load_texture = gl_load_texture,
  19. update_texture = gl_update_texture,
  20. destroy_texture = gl_destroy_texture,
  21. load_shader = gl_load_shader,
  22. destroy_shader = gl_destroy_shader,
  23. default_shader_vertex_source = gl_default_shader_vertex_source,
  24. default_shader_fragment_source = gl_default_shader_fragment_source,
  25. }
  26. import "base:runtime"
  27. import gl "vendor:OpenGL"
  28. import hm "handle_map"
  29. import "core:log"
  30. import "core:strings"
  31. import "core:slice"
  32. import la "core:math/linalg"
  33. _ :: la
  34. GL_State :: struct {
  35. window_handle: Window_Handle,
  36. width: int,
  37. height: int,
  38. allocator: runtime.Allocator,
  39. shaders: hm.Handle_Map(GL_Shader, Shader_Handle, 1024*10),
  40. ctx: GL_Context,
  41. vertex_buffer_gpu: u32,
  42. }
  43. GL_Shader_Constant_Buffer :: struct {
  44. buffer: u32,
  45. size: int,
  46. block_index: u32,
  47. }
  48. GL_Shader :: struct {
  49. handle: Shader_Handle,
  50. // This is like the "input layout"
  51. vao: u32,
  52. program: u32,
  53. constant_buffers: []GL_Shader_Constant_Buffer,
  54. }
  55. s: ^GL_State
  56. gl_state_size :: proc() -> int {
  57. return size_of(GL_State)
  58. }
  59. gl_init :: proc(state: rawptr, window_handle: Window_Handle, swapchain_width, swapchain_height: int, allocator := context.allocator) {
  60. s = (^GL_State)(state)
  61. s.window_handle = window_handle
  62. s.width = swapchain_width
  63. s.height = swapchain_height
  64. s.allocator = allocator
  65. ctx, ctx_ok := _gl_get_context(window_handle)
  66. if !ctx_ok {
  67. log.panic("Could not find a valid pixel format for gl context")
  68. }
  69. s.ctx = ctx
  70. _gl_load_procs()
  71. gl.Enable(gl.DEPTH_TEST)
  72. gl.DepthFunc(gl.GREATER)
  73. gl.GenBuffers(1, &s.vertex_buffer_gpu)
  74. gl.BindBuffer(gl.ARRAY_BUFFER, s.vertex_buffer_gpu)
  75. gl.BufferData(gl.ARRAY_BUFFER, VERTEX_BUFFER_MAX, nil, gl.DYNAMIC_DRAW)
  76. }
  77. gl_shutdown :: proc() {
  78. gl.DeleteBuffers(1, &s.vertex_buffer_gpu)
  79. _gl_destroy_context(s.ctx)
  80. }
  81. gl_clear :: proc(color: Color) {
  82. c := f32_color_from_color(color)
  83. gl.ClearColor(c.r, c.g, c.b, c.a)
  84. gl.ClearDepth(-1)
  85. gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
  86. }
  87. gl_present :: proc() {
  88. _gl_present(s.window_handle)
  89. }
  90. gl_draw :: proc(shd: Shader, texture: Texture_Handle, view_proj: Mat4, scissor: Maybe(Rect), vertex_buffer: []u8) {
  91. shader := hm.get(&s.shaders, shd.handle)
  92. if shader == nil {
  93. return
  94. }
  95. gl.EnableVertexAttribArray(0)
  96. gl.EnableVertexAttribArray(1)
  97. gl.EnableVertexAttribArray(2)
  98. gl.UseProgram(shader.program)
  99. // temp test
  100. {
  101. b := shader.constant_buffers[0]
  102. gl.BindBuffer(gl.UNIFORM_BUFFER, b.buffer)
  103. mvp := view_proj
  104. gl.BufferData(gl.UNIFORM_BUFFER, b.size, &mvp, gl.DYNAMIC_DRAW)
  105. gl.BindBufferBase(gl.UNIFORM_BUFFER, 0, b.buffer)
  106. //gl.UniformBlockBinding(shader.program, b.block_index, b.buffer)
  107. }
  108. gl.BindBuffer(gl.ARRAY_BUFFER, s.vertex_buffer_gpu)
  109. vb_data := gl.MapBuffer(gl.ARRAY_BUFFER, gl.WRITE_ONLY)
  110. {
  111. gpu_map := slice.from_ptr((^u8)(vb_data), VERTEX_BUFFER_MAX)
  112. copy(
  113. gpu_map,
  114. vertex_buffer,
  115. )
  116. }
  117. gl.UnmapBuffer(gl.ARRAY_BUFFER)
  118. gl.DrawArrays(gl.TRIANGLES, 0, i32(len(vertex_buffer)/shd.vertex_size))
  119. }
  120. gl_resize_swapchain :: proc(w, h: int) {
  121. }
  122. gl_get_swapchain_width :: proc() -> int {
  123. return s.width
  124. }
  125. gl_get_swapchain_height :: proc() -> int {
  126. return s.height
  127. }
  128. gl_flip_z :: proc() -> bool {
  129. return false
  130. }
  131. gl_set_internal_state :: proc(state: rawptr) {
  132. }
  133. gl_create_texture :: proc(width: int, height: int, format: Pixel_Format) -> Texture_Handle {
  134. return {}
  135. }
  136. gl_load_texture :: proc(data: []u8, width: int, height: int, format: Pixel_Format) -> Texture_Handle {
  137. return {}
  138. }
  139. gl_update_texture :: proc(th: Texture_Handle, data: []u8, rect: Rect) -> bool {
  140. return false
  141. }
  142. gl_destroy_texture :: proc(th: Texture_Handle) {
  143. }
  144. Shader_Compile_Result_OK :: struct {}
  145. Shader_Compile_Result_Error :: string
  146. Shader_Compile_Result :: union #no_nil {
  147. Shader_Compile_Result_OK,
  148. Shader_Compile_Result_Error,
  149. }
  150. compile_shader_from_source :: proc(shader_data: string, shader_type: gl.Shader_Type, err_buf: []u8, err_msg: ^string) -> (shader_id: u32, ok: bool) {
  151. shader_id = gl.CreateShader(u32(shader_type))
  152. length := i32(len(shader_data))
  153. shader_cstr := cstring(raw_data(shader_data))
  154. gl.ShaderSource(shader_id, 1, &shader_cstr, &length)
  155. gl.CompileShader(shader_id)
  156. result: i32
  157. gl.GetShaderiv(shader_id, gl.COMPILE_STATUS, &result)
  158. if result != 1 {
  159. info_len: i32
  160. gl.GetShaderInfoLog(shader_id, i32(len(err_buf)), &info_len, raw_data(err_buf))
  161. err_msg^ = string(err_buf[:info_len])
  162. gl.DeleteShader(shader_id)
  163. return 0, false
  164. }
  165. return shader_id, true
  166. }
  167. link_shader :: proc(vs_shader: u32, fs_shader: u32, err_buf: []u8, err_msg: ^string) -> (program_id: u32, ok: bool) {
  168. program_id = gl.CreateProgram()
  169. gl.AttachShader(program_id, vs_shader)
  170. gl.AttachShader(program_id, fs_shader)
  171. gl.LinkProgram(program_id)
  172. result: i32
  173. gl.GetProgramiv(program_id, gl.LINK_STATUS, &result)
  174. if result != 1 {
  175. info_len: i32
  176. gl.GetProgramInfoLog(program_id, i32(len(err_buf)), &info_len, raw_data(err_buf))
  177. err_msg^ = string(err_buf[:info_len])
  178. gl.DeleteProgram(program_id)
  179. return 0, false
  180. }
  181. return program_id, true
  182. }
  183. gl_load_shader :: proc(vs_source: string, fs_source: string, desc_allocator := frame_allocator, layout_formats: []Pixel_Format = {}) -> (handle: Shader_Handle, desc: Shader_Desc) {
  184. @static err: [1024]u8
  185. err_msg: string
  186. vs_shader, vs_shader_ok := compile_shader_from_source(vs_source, gl.Shader_Type.VERTEX_SHADER, err[:], &err_msg)
  187. if !vs_shader_ok {
  188. log.error(err_msg)
  189. return {}, {}
  190. }
  191. fs_shader, fs_shader_ok := compile_shader_from_source(fs_source, gl.Shader_Type.FRAGMENT_SHADER, err[:], &err_msg)
  192. if !fs_shader_ok {
  193. log.error(err_msg)
  194. return {}, {}
  195. }
  196. program, program_ok := link_shader(vs_shader, fs_shader, err[:], &err_msg)
  197. if !program_ok {
  198. log.error(err_msg)
  199. return {}, {}
  200. }
  201. stride: int
  202. {
  203. num_attribs: i32
  204. gl.GetProgramiv(program, gl.ACTIVE_ATTRIBUTES, &num_attribs)
  205. desc.inputs = make([]Shader_Input, num_attribs, desc_allocator)
  206. attrib_name_buf: [256]u8
  207. for i in 0..<num_attribs {
  208. attrib_name_len: i32
  209. attrib_size: i32
  210. attrib_type: u32
  211. gl.GetActiveAttrib(program, u32(i), i32(len(attrib_name_buf)), &attrib_name_len, &attrib_size, &attrib_type, raw_data(attrib_name_buf[:]))
  212. name_cstr := cstring(raw_data(attrib_name_buf[:attrib_name_len]))
  213. loc := gl.GetAttribLocation(program, name_cstr)
  214. if loc >= num_attribs {
  215. continue
  216. }
  217. type: Shader_Input_Type
  218. switch attrib_type {
  219. case gl.FLOAT: type = .F32
  220. case gl.FLOAT_VEC2: type = .Vec2
  221. case gl.FLOAT_VEC3: type = .Vec3
  222. case gl.FLOAT_VEC4: type = .Vec4
  223. /* Possible (gl.) types:
  224. FLOAT, FLOAT_VEC2, FLOAT_VEC3, FLOAT_VEC4, FLOAT_MAT2,
  225. FLOAT_MAT3, FLOAT_MAT4, FLOAT_MAT2x3, FLOAT_MAT2x4,
  226. FLOAT_MAT3x2, FLOAT_MAT3x4, FLOAT_MAT4x2, FLOAT_MAT4x3,
  227. INT, INT_VEC2, INT_VEC3, INT_VEC4, UNSIGNED_INT,
  228. UNSIGNED_INT_VEC2, UNSIGNED_INT_VEC3, UNSIGNED_INT_VEC4,
  229. DOUBLE, DOUBLE_VEC2, DOUBLE_VEC3, DOUBLE_VEC4, DOUBLE_MAT2,
  230. DOUBLE_MAT3, DOUBLE_MAT4, DOUBLE_MAT2x3, DOUBLE_MAT2x4,
  231. DOUBLE_MAT3x2, DOUBLE_MAT3x4, DOUBLE_MAT4x2, or DOUBLE_MAT4x3 */
  232. case: log.errorf("Unknwon type: %v", attrib_type)
  233. }
  234. name := strings.clone(string(attrib_name_buf[:attrib_name_len]), desc_allocator)
  235. format := len(layout_formats) > 0 ? layout_formats[loc] : get_shader_input_format(name, type)
  236. desc.inputs[loc] = {
  237. name = name,
  238. register = int(loc),
  239. format = format,
  240. type = type,
  241. }
  242. input_format := get_shader_input_format(name, type)
  243. format_size := pixel_format_size(input_format)
  244. stride += format_size
  245. }
  246. }
  247. shader := GL_Shader {
  248. program = program,
  249. }
  250. gl.GenVertexArrays(1, &shader.vao)
  251. gl.BindVertexArray(shader.vao)
  252. gl.BindBuffer(gl.ARRAY_BUFFER, s.vertex_buffer_gpu)
  253. offset: int
  254. for idx in 0..<len(desc.inputs) {
  255. input := desc.inputs[idx]
  256. format_size := pixel_format_size(input.format)
  257. gl.EnableVertexAttribArray(u32(idx))
  258. format, num_components, norm := gl_describe_pixel_format(input.format)
  259. gl.VertexAttribPointer(u32(idx), num_components, format, norm ? gl.TRUE : gl.FALSE, i32(stride), uintptr(offset))
  260. offset += format_size
  261. }
  262. {
  263. num_uniform_blocks: i32
  264. gl.GetProgramiv(program, gl.ACTIVE_UNIFORM_BLOCKS, &num_uniform_blocks)
  265. desc.constant_buffers = make([]Shader_Constant_Buffer_Desc, num_uniform_blocks, desc_allocator)
  266. shader.constant_buffers = make([]GL_Shader_Constant_Buffer, num_uniform_blocks, s.allocator)
  267. uniform_block_name_buf: [256]u8
  268. for cb_idx in 0..<num_uniform_blocks {
  269. name_len: i32
  270. gl.GetActiveUniformBlockName(program, u32(cb_idx), len(uniform_block_name_buf), &name_len, raw_data(&uniform_block_name_buf))
  271. name_cstr := cstring(raw_data(uniform_block_name_buf[:name_len]))
  272. idx := gl.GetUniformBlockIndex(program, name_cstr)
  273. if i32(idx) >= num_uniform_blocks {
  274. continue
  275. }
  276. size: i32
  277. // TODO investigate if we need std140 layout in the shader or what is fine?
  278. gl.GetActiveUniformBlockiv(program, idx, gl.UNIFORM_BLOCK_DATA_SIZE, &size)
  279. if size == 0 {
  280. log.errorf("Uniform block %v has size 0", name_cstr)
  281. continue
  282. }
  283. buf: u32
  284. gl.GenBuffers(1, &buf)
  285. gl.BindBuffer(gl.UNIFORM_BUFFER, buf)
  286. gl.BufferData(gl.UNIFORM_BUFFER, int(size), nil, gl.DYNAMIC_DRAW)
  287. //gl.UniformBlockBinding(program, idx, buf)
  288. gl.BindBufferBase(gl.UNIFORM_BUFFER, idx, buf)
  289. shader.constant_buffers[cb_idx] = {
  290. block_index = idx,
  291. buffer = buf,
  292. size = int(size),
  293. }
  294. desc.constant_buffers[cb_idx] = {
  295. name = strings.clone_from_cstring(name_cstr, desc_allocator),
  296. size = int(size),
  297. }
  298. }
  299. /*
  300. GetUniformIndices :: proc "c" (program: u32, uniformCount: i32, uniformNames: [^]cstring, uniformIndices: [^]u32) { impl_GetUniformIndices(program, uniformCount, uniformNames, uniformIndices) }
  301. GetActiveUniformsiv :: proc "c" (program: u32, uniformCount: i32, uniformIndices: [^]u32, pname: u32, params: [^]i32) { impl_GetActiveUniformsiv(program, uniformCount, uniformIndices, pname, params) }
  302. GetActiveUniformName :: proc "c" (program: u32, uniformIndex: u32, bufSize: i32, length: ^i32, uniformName: [^]u8) { impl_GetActiveUniformName(program, uniformIndex, bufSize, length, uniformName) }
  303. GetUniformBlockIndex :: proc "c" (program: u32, uniformBlockName: cstring) -> u32 { ret := impl_GetUniformBlockIndex(program, uniformBlockName); return ret }
  304. GetActiveUniformBlockiv :: proc "c" (program: u32, uniformBlockIndex: u32, pname: u32, params: [^]i32) { impl_GetActiveUniformBlockiv(program, uniformBlockIndex, pname, params) }
  305. */
  306. }
  307. h := hm.add(&s.shaders, shader)
  308. return h, desc
  309. }
  310. gl_describe_pixel_format :: proc(f: Pixel_Format) -> (format: u32, num_components: i32, normalized: bool) {
  311. switch f {
  312. case .RGBA_32_Float: return gl.FLOAT, 4, false
  313. case .RGB_32_Float: return gl.FLOAT, 3, false
  314. case .RG_32_Float: return gl.FLOAT, 2, false
  315. case .R_32_Float: return gl.FLOAT, 1, false
  316. case .RGBA_8_Norm: return gl.UNSIGNED_BYTE, 4, true
  317. case .RG_8_Norm: return gl.UNSIGNED_BYTE, 2, true
  318. case .R_8_Norm: return gl.UNSIGNED_BYTE, 1, true
  319. case .R_8_UInt: return gl.BYTE, 1, false
  320. case .Unknown:
  321. }
  322. log.error("Unknown format")
  323. return 0, 0, false
  324. }
  325. gl_destroy_shader :: proc(h: Shader_Handle) {
  326. }
  327. gl_default_shader_vertex_source :: proc() -> string {
  328. return #load("default_shader_vertex.glsl")
  329. }
  330. gl_default_shader_fragment_source :: proc() -> string {
  331. return #load("default_shader_fragment.glsl")
  332. }