Skip to content

Instantly share code, notes, and snippets.

@Leinnan
Created August 20, 2025 12:06
Show Gist options
  • Save Leinnan/80e18cab024c9004d5169abd18e373b9 to your computer and use it in GitHub Desktop.
Save Leinnan/80e18cab024c9004d5169abd18e373b9 to your computer and use it in GitHub Desktop.
Raylib Context sample
use raylib::prelude::*;
use std::ops::{Deref, DerefMut};
#[allow(static_mut_refs)]
pub(crate) mod thread_assert {
static mut THREAD_ID: Option<std::thread::ThreadId> = None;
pub fn set_thread_id() {
unsafe {
THREAD_ID = Some(std::thread::current().id());
}
}
pub fn same_thread() {
unsafe {
thread_local! {
static CURRENT_THREAD_ID: std::thread::ThreadId = std::thread::current().id();
}
assert!(THREAD_ID.is_some());
assert!(THREAD_ID.unwrap() == CURRENT_THREAD_ID.with(|id| *id));
}
}
}
pub struct RaylibContext {
pub rl: RaylibHandle,
pub thread: RaylibThread,
}
impl RaylibContext {
pub fn start_drawing(&mut self) -> RaylibDrawHandle<'_> {
self.rl.begin_drawing(&self.thread)
}
}
impl Deref for RaylibContext {
type Target = RaylibHandle;
fn deref(&self) -> &Self::Target {
&self.rl
}
}
impl DerefMut for RaylibContext {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.rl
}
}
static mut CONTEXT: Option<RaylibContext> = None;
pub fn init_raylib() {
let (rl, thread) = raylib::init().size(640, 480).title("Hello, World").build();
thread_assert::set_thread_id();
unsafe {
CONTEXT = Some(RaylibContext { rl, thread });
}
}
#[allow(static_mut_refs)]
pub fn get_context() -> &'static mut RaylibContext {
thread_assert::same_thread();
unsafe { CONTEXT.as_mut().unwrap_or_else(|| panic!()) }
}
fn main() {
init_raylib();
let mut text = "NONE".to_string();
while !get_context().window_should_close() {
if let Some(key) = get_context().get_key_pressed() {
text = format!("Last Key Pressed: {:?}", key);
}
let pos = format!("Mouse Position: {:?}", get_context().get_mouse_position());
let time = get_context().get_frame_time().to_string();
let mut d = get_context().start_drawing();
d.clear_background(Color::WHITE);
d.draw_text("Hello, world!", 20, 12, 20, Color::BLACK);
d.draw_text(text.as_str(), 20, 55, 20, Color::BLACK);
d.draw_text(pos.as_str(), 20, 100, 20, Color::BLACK);
d.draw_text(time.as_str(), 20, 150, 20, Color::BLACK);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment