1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
use static_assertions::assert_not_impl_all;
use std::ffi::{c_void, CString};
use std::mem::MaybeUninit;
use std::ptr::NonNull;
use crate::geo::Size;
use crate::window::{Window, WindowContextKind};
use crate::{bind, Result, Sdl, SdlError};
pub mod attribute;
mod buffer;
mod context_switch;
mod flag;
pub use buffer::*;
pub use context_switch::*;
pub use flag::*;
pub struct GlContext<'window> {
ctx: NonNull<c_void>,
window: &'window Window<'window>,
}
impl std::fmt::Debug for GlContext<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GlContext")
.field("window", &self.window)
.finish_non_exhaustive()
}
}
assert_not_impl_all!(GlContext: Send, Sync);
impl<'window> GlContext<'window> {
#[must_use]
pub fn new(window: &'window Window) -> Option<Self> {
if let WindowContextKind::OpenGl = window.state().context_kind {
let raw = unsafe { bind::SDL_GL_CreateContext(window.as_ptr()) };
NonNull::new(raw).map(|ctx| Self { ctx, window })
} else {
None
}
}
#[must_use]
pub fn as_ptr(&self) -> *mut c_void {
self.ctx.as_ptr()
}
pub fn drawable_size(&self) -> Size {
let (mut width, mut height) = (MaybeUninit::uninit(), MaybeUninit::uninit());
unsafe {
bind::SDL_GL_GetDrawableSize(
self.window.as_ptr(),
width.as_mut_ptr(),
height.as_mut_ptr(),
);
}
Size {
width: unsafe { width.assume_init() } as u32,
height: unsafe { height.assume_init() } as u32,
}
}
#[must_use]
pub fn supported_extension(&self, name: &'static str) -> bool {
let cstr = CString::new(name).unwrap();
unsafe { bind::SDL_GL_ExtensionSupported(cstr.as_ptr()) != 0 }
}
pub fn load_lib(&self, path: &str) -> Result<()> {
let cstr = CString::new(path).unwrap();
let ret = unsafe { bind::SDL_GL_LoadLibrary(cstr.as_ptr()) };
if ret != 0 {
return Err(SdlError::Others { msg: Sdl::error() });
}
Ok(())
}
pub fn unload_lib_all(&self) {
unsafe { bind::SDL_GL_UnloadLibrary() }
}
#[must_use]
pub unsafe fn proc_address(&self, proc: &str) -> *mut c_void {
let cstr = CString::new(proc).unwrap();
unsafe { bind::SDL_GL_GetProcAddress(cstr.as_ptr()) }
}
}
impl<'window> Drop for GlContext<'window> {
fn drop(&mut self) {
unsafe {
bind::SDL_GL_UnloadLibrary();
bind::SDL_GL_DeleteContext(self.ctx.as_ptr());
}
}
}