render_backend_gl.odin 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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 win32 "core:sys/windows"
  31. import "core:strings"
  32. import "core:slice"
  33. import la "core:math/linalg"
  34. _ :: la
  35. GL_State :: struct {
  36. width: int,
  37. height: int,
  38. allocator: runtime.Allocator,
  39. shaders: hm.Handle_Map(GL_Shader, Shader_Handle, 1024*10),
  40. dc: win32.HDC,
  41. vertex_buffer_gpu: u32,
  42. }
  43. GL_Shader_Constant_Buffer :: struct {
  44. gpu_data: rawptr,
  45. }
  46. GL_Shader :: struct {
  47. handle: Shader_Handle,
  48. // This is like the "input layout"
  49. vao: u32,
  50. program: u32,
  51. }
  52. s: ^GL_State
  53. gl_state_size :: proc() -> int {
  54. return size_of(GL_State)
  55. }
  56. gl_init :: proc(state: rawptr, window_handle: Window_Handle, swapchain_width, swapchain_height: int, allocator := context.allocator) {
  57. s = (^GL_State)(state)
  58. s.width = swapchain_width
  59. s.height = swapchain_height
  60. s.allocator = allocator
  61. hdc := win32.GetWindowDC(win32.HWND(window_handle))
  62. s.dc = hdc
  63. pfd := win32.PIXELFORMATDESCRIPTOR {
  64. size_of(win32.PIXELFORMATDESCRIPTOR),
  65. 1,
  66. win32.PFD_DRAW_TO_WINDOW | win32.PFD_SUPPORT_OPENGL | win32.PFD_DOUBLEBUFFER, // Flags
  67. win32.PFD_TYPE_RGBA, // The kind of framebuffer. RGBA or palette.
  68. 32, // Colordepth of the framebuffer.
  69. 0, 0, 0, 0, 0, 0,
  70. 0,
  71. 0,
  72. 0,
  73. 0, 0, 0, 0,
  74. 24, // Number of bits for the depthbuffer
  75. 8, // Number of bits for the stencilbuffer
  76. 0, // Number of Aux buffers in the framebuffer.
  77. win32.PFD_MAIN_PLANE,
  78. 0,
  79. 0, 0, 0,
  80. }
  81. fmt := win32.ChoosePixelFormat(hdc, &pfd)
  82. win32.SetPixelFormat(hdc, fmt, &pfd)
  83. ctx := win32.wglCreateContext(hdc)
  84. win32.wglMakeCurrent(hdc, ctx)
  85. win32.gl_set_proc_address(&win32.wglChoosePixelFormatARB, "wglChoosePixelFormatARB")
  86. win32.gl_set_proc_address(&win32.wglCreateContextAttribsARB, "wglCreateContextAttribsARB")
  87. pixel_format_ilist := [?]i32 {
  88. win32.WGL_DRAW_TO_WINDOW_ARB, 1,
  89. win32.WGL_SUPPORT_OPENGL_ARB, 1,
  90. win32.WGL_DOUBLE_BUFFER_ARB, 1,
  91. win32.WGL_PIXEL_TYPE_ARB, win32.WGL_TYPE_RGBA_ARB,
  92. win32.WGL_COLOR_BITS_ARB, 32,
  93. win32.WGL_DEPTH_BITS_ARB, 24,
  94. win32.WGL_STENCIL_BITS_ARB, 8,
  95. 0,
  96. }
  97. pixel_format: i32
  98. num_formats: u32
  99. valid_pixel_format := win32.wglChoosePixelFormatARB(hdc, raw_data(pixel_format_ilist[:]),
  100. nil, 1, &pixel_format, &num_formats)
  101. if !valid_pixel_format {
  102. log.panic("Could not find a valid pixel format for gl context")
  103. }
  104. win32.SetPixelFormat(hdc, pixel_format, nil)
  105. ctx = win32.wglCreateContextAttribsARB(hdc, nil, nil)
  106. win32.wglMakeCurrent(hdc, ctx)
  107. gl.load_up_to(3, 3, win32.gl_set_proc_address)
  108. gl.Enable(gl.DEPTH_TEST)
  109. gl.DepthFunc(gl.GREATER)
  110. //gl.CullFace(gl.FRONT)
  111. gl.GenBuffers(1, &s.vertex_buffer_gpu)
  112. gl.BindBuffer(gl.ARRAY_BUFFER, s.vertex_buffer_gpu)
  113. gl.BufferData(gl.ARRAY_BUFFER, VERTEX_BUFFER_MAX, nil, gl.DYNAMIC_DRAW)
  114. }
  115. gl_shutdown :: proc() {
  116. }
  117. gl_clear :: proc(color: Color) {
  118. c := f32_color_from_color(color)
  119. gl.ClearColor(c.r, c.g, c.b, c.a)
  120. gl.ClearDepth(-1)
  121. gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
  122. }
  123. gl_present :: proc() {
  124. win32.SwapBuffers(s.dc)
  125. }
  126. gl_draw :: proc(shd: Shader, texture: Texture_Handle, view_proj: Mat4, scissor: Maybe(Rect), vertex_buffer: []u8) {
  127. shader := hm.get(&s.shaders, shd.handle)
  128. if shader == nil {
  129. return
  130. }
  131. gl.EnableVertexAttribArray(0)
  132. gl.EnableVertexAttribArray(1)
  133. gl.EnableVertexAttribArray(2)
  134. gl.UseProgram(shader.program)
  135. mvp_loc := gl.GetUniformLocation(shader.program, "mvp")
  136. //mvp := la.transpose(view_proj)
  137. mvp := view_proj
  138. gl.UniformMatrix4fv(mvp_loc, 1, gl.FALSE, (^f32)(&mvp))
  139. gl.BindBuffer(gl.ARRAY_BUFFER, s.vertex_buffer_gpu)
  140. vb_data := gl.MapBuffer(gl.ARRAY_BUFFER, gl.WRITE_ONLY)
  141. {
  142. gpu_map := slice.from_ptr((^u8)(vb_data), VERTEX_BUFFER_MAX)
  143. copy(
  144. gpu_map,
  145. vertex_buffer,
  146. )
  147. }
  148. gl.UnmapBuffer(gl.ARRAY_BUFFER)
  149. gl.DrawArrays(gl.TRIANGLES, 0, i32(len(vertex_buffer)/shd.vertex_size))
  150. }
  151. gl_resize_swapchain :: proc(w, h: int) {
  152. }
  153. gl_get_swapchain_width :: proc() -> int {
  154. return s.width
  155. }
  156. gl_get_swapchain_height :: proc() -> int {
  157. return s.height
  158. }
  159. gl_flip_z :: proc() -> bool {
  160. return false
  161. }
  162. gl_set_internal_state :: proc(state: rawptr) {
  163. }
  164. gl_create_texture :: proc(width: int, height: int, format: Pixel_Format) -> Texture_Handle {
  165. return {}
  166. }
  167. gl_load_texture :: proc(data: []u8, width: int, height: int, format: Pixel_Format) -> Texture_Handle {
  168. return {}
  169. }
  170. gl_update_texture :: proc(th: Texture_Handle, data: []u8, rect: Rect) -> bool {
  171. return false
  172. }
  173. gl_destroy_texture :: proc(th: Texture_Handle) {
  174. }
  175. Shader_Compile_Result_OK :: struct {}
  176. Shader_Compile_Result_Error :: string
  177. Shader_Compile_Result :: union #no_nil {
  178. Shader_Compile_Result_OK,
  179. Shader_Compile_Result_Error,
  180. }
  181. compile_shader_from_source :: proc(shader_data: string, shader_type: gl.Shader_Type, err_buf: []u8, err_msg: ^string) -> (shader_id: u32, ok: bool) {
  182. shader_id = gl.CreateShader(u32(shader_type))
  183. length := i32(len(shader_data))
  184. shader_cstr := cstring(raw_data(shader_data))
  185. gl.ShaderSource(shader_id, 1, &shader_cstr, &length)
  186. gl.CompileShader(shader_id)
  187. result: i32
  188. gl.GetShaderiv(shader_id, gl.COMPILE_STATUS, &result)
  189. if result != 1 {
  190. info_len: i32
  191. gl.GetShaderInfoLog(shader_id, i32(len(err_buf)), &info_len, raw_data(err_buf))
  192. err_msg^ = string(err_buf[:info_len])
  193. gl.DeleteShader(shader_id)
  194. return 0, false
  195. }
  196. return shader_id, true
  197. }
  198. link_shader :: proc(vs_shader: u32, fs_shader: u32, err_buf: []u8, err_msg: ^string) -> (program_id: u32, ok: bool) {
  199. program_id = gl.CreateProgram()
  200. gl.AttachShader(program_id, vs_shader)
  201. gl.AttachShader(program_id, fs_shader)
  202. gl.LinkProgram(program_id)
  203. result: i32
  204. gl.GetProgramiv(program_id, gl.LINK_STATUS, &result)
  205. if result != 1 {
  206. info_len: i32
  207. gl.GetProgramInfoLog(program_id, i32(len(err_buf)), &info_len, raw_data(err_buf))
  208. err_msg^ = string(err_buf[:info_len])
  209. gl.DeleteProgram(program_id)
  210. return 0, false
  211. }
  212. return program_id, true
  213. }
  214. gl_load_shader :: proc(vs_source: string, fs_source: string, desc_allocator := frame_allocator, layout_formats: []Pixel_Format = {}) -> (handle: Shader_Handle, desc: Shader_Desc) {
  215. @static err: [1024]u8
  216. err_msg: string
  217. vs_shader, vs_shader_ok := compile_shader_from_source(vs_source, gl.Shader_Type.VERTEX_SHADER, err[:], &err_msg)
  218. if !vs_shader_ok {
  219. log.error(err_msg)
  220. return {}, {}
  221. }
  222. fs_shader, fs_shader_ok := compile_shader_from_source(fs_source, gl.Shader_Type.FRAGMENT_SHADER, err[:], &err_msg)
  223. if !fs_shader_ok {
  224. log.error(err_msg)
  225. return {}, {}
  226. }
  227. program, program_ok := link_shader(vs_shader, fs_shader, err[:], &err_msg)
  228. if !program_ok {
  229. log.error(err_msg)
  230. return {}, {}
  231. }
  232. stride: int
  233. {
  234. num_attribs: i32
  235. gl.GetProgramiv(program, gl.ACTIVE_ATTRIBUTES, &num_attribs)
  236. desc.inputs = make([]Shader_Input, num_attribs, desc_allocator)
  237. attrib_name_buf: [256]u8
  238. for i in 0..<num_attribs {
  239. attrib_name_len: i32
  240. attrib_size: i32
  241. attrib_type: u32
  242. gl.GetActiveAttrib(program, u32(i), i32(len(attrib_name_buf)), &attrib_name_len, &attrib_size, &attrib_type, raw_data(attrib_name_buf[:]))
  243. name_cstr := strings.clone_to_cstring(string(attrib_name_buf[:attrib_name_len]), desc_allocator)
  244. loc := gl.GetAttribLocation(program, name_cstr)
  245. log.info(loc)
  246. type: Shader_Input_Type
  247. switch attrib_type {
  248. case gl.FLOAT: type = .F32
  249. case gl.FLOAT_VEC2: type = .Vec2
  250. case gl.FLOAT_VEC3: type = .Vec3
  251. case gl.FLOAT_VEC4: type = .Vec4
  252. /* Possible (gl.) types:
  253. FLOAT, FLOAT_VEC2, FLOAT_VEC3, FLOAT_VEC4, FLOAT_MAT2,
  254. FLOAT_MAT3, FLOAT_MAT4, FLOAT_MAT2x3, FLOAT_MAT2x4,
  255. FLOAT_MAT3x2, FLOAT_MAT3x4, FLOAT_MAT4x2, FLOAT_MAT4x3,
  256. INT, INT_VEC2, INT_VEC3, INT_VEC4, UNSIGNED_INT,
  257. UNSIGNED_INT_VEC2, UNSIGNED_INT_VEC3, UNSIGNED_INT_VEC4,
  258. DOUBLE, DOUBLE_VEC2, DOUBLE_VEC3, DOUBLE_VEC4, DOUBLE_MAT2,
  259. DOUBLE_MAT3, DOUBLE_MAT4, DOUBLE_MAT2x3, DOUBLE_MAT2x4,
  260. DOUBLE_MAT3x2, DOUBLE_MAT3x4, DOUBLE_MAT4x2, or DOUBLE_MAT4x3 */
  261. case: log.errorf("Unknwon type: %v", attrib_type)
  262. }
  263. name := strings.clone(string(attrib_name_buf[:attrib_name_len]), desc_allocator)
  264. log.info(name)
  265. format := len(layout_formats) > 0 ? layout_formats[loc] : get_shader_input_format(name, type)
  266. desc.inputs[loc] = {
  267. name = name,
  268. register = int(loc),
  269. format = format,
  270. type = type,
  271. }
  272. input_format := get_shader_input_format(name, type)
  273. format_size := pixel_format_size(input_format)
  274. stride += format_size
  275. //
  276. //log.info(i, attrib_name_len, attrib_size, attrib_type, string(attrib_name_buf[:attrib_name_len]))
  277. }
  278. }
  279. shader := GL_Shader {
  280. program = program,
  281. }
  282. gl.GenVertexArrays(1, &shader.vao)
  283. gl.BindVertexArray(shader.vao)
  284. gl.BindBuffer(gl.ARRAY_BUFFER, s.vertex_buffer_gpu)
  285. offset: int
  286. for idx in 0..<len(desc.inputs) {
  287. input := desc.inputs[idx]
  288. //input_format := get_shader_input_format(input.name, input.type)
  289. input_format: Pixel_Format
  290. switch input.type {
  291. case .F32: input_format = .R_32_Float
  292. case .Vec2: input_format = .RG_32_Float
  293. case .Vec3: input_format = .RGB_32_Float
  294. case .Vec4: input_format = .RGBA_32_Float
  295. }
  296. format_size := pixel_format_size(input_format)
  297. //num_components := get_shader_format_num_components(input_format)
  298. gl.EnableVertexAttribArray(u32(idx))
  299. format, num_components, norm := gl_format_from_pixel_format(get_shader_input_format(input.name, input.type))
  300. gl.VertexAttribPointer(u32(idx), num_components, format, norm ? gl.TRUE : gl.FALSE, i32(stride), uintptr(offset))
  301. offset += format_size
  302. log.info(input.name)
  303. }
  304. {
  305. /*num_constant_buffers: i32
  306. gl.GetProgramiv(program, gl.ACTIVE_UNIFORM_BLOCKS, &num_attribs)
  307. desc.constant_buffers = make([]Shader_Constant_Buffer_Desc, num_constant_buffers, desc_allocator)
  308. shader.constant_buffers = make([]GL_Shader_Constant_Buffer, num_constant_buffers, s.allocator)
  309. for cb_idx in 0..<num_constant_buffers {
  310. buf: u32
  311. gl.GenBuffers(1, &buf)*/
  312. /*
  313. GetUniformIndices :: proc "c" (program: u32, uniformCount: i32, uniformNames: [^]cstring, uniformIndices: [^]u32) { impl_GetUniformIndices(program, uniformCount, uniformNames, uniformIndices) }
  314. GetActiveUniformsiv :: proc "c" (program: u32, uniformCount: i32, uniformIndices: [^]u32, pname: u32, params: [^]i32) { impl_GetActiveUniformsiv(program, uniformCount, uniformIndices, pname, params) }
  315. GetActiveUniformName :: proc "c" (program: u32, uniformIndex: u32, bufSize: i32, length: ^i32, uniformName: [^]u8) { impl_GetActiveUniformName(program, uniformIndex, bufSize, length, uniformName) }
  316. GetUniformBlockIndex :: proc "c" (program: u32, uniformBlockName: cstring) -> u32 { ret := impl_GetUniformBlockIndex(program, uniformBlockName); return ret }
  317. GetActiveUniformBlockiv :: proc "c" (program: u32, uniformBlockIndex: u32, pname: u32, params: [^]i32) { impl_GetActiveUniformBlockiv(program, uniformBlockIndex, pname, params) }
  318. */
  319. }
  320. h := hm.add(&s.shaders, shader)
  321. return h, desc
  322. }
  323. gl_format_from_pixel_format :: proc(f: Pixel_Format) -> (u32, i32, bool) {
  324. switch f {
  325. case .RGBA_32_Float: return gl.FLOAT, 4, false
  326. case .RGB_32_Float: return gl.FLOAT, 3, false
  327. case .RG_32_Float: return gl.FLOAT, 2, false
  328. case .R_32_Float: return gl.FLOAT, 1, false
  329. case .RGBA_8_Norm: return gl.INT, 4, true
  330. case .RG_8_Norm: return gl.INT, 2, true
  331. case .R_8_Norm: return gl.INT, 1, true
  332. case .R_8_UInt: return gl.INT, 1, true
  333. case .Unknown:
  334. }
  335. log.error("Unknown format")
  336. return 0, 0, false
  337. }
  338. gl_destroy_shader :: proc(h: Shader_Handle) {
  339. }
  340. gl_default_shader_vertex_source :: proc() -> string {
  341. return #load("default_shader_vertex.glsl")
  342. }
  343. gl_default_shader_fragment_source :: proc() -> string {
  344. return #load("default_shader_fragment.glsl")
  345. }