Skip to content

Instantly share code, notes, and snippets.

@superlou
Created April 5, 2023 00:07
Show Gist options
  • Save superlou/a24e2ef881e6058d0890df78ccc3151f to your computer and use it in GitHub Desktop.
Save superlou/a24e2ef881e6058d0890df78ccc3151f to your computer and use it in GitHub Desktop.
Scripting speedy2d with Rhai
use std::time::Instant;
use std::rc::Rc;
use std::cell::RefCell;
use speedy2d::Window;
use speedy2d::window::{WindowHandler, WindowHelper};
use speedy2d::Graphics2D;
use speedy2d::color::Color;
use rhai::{Engine, Scope, AST};
struct SignWindowHandler {
engine: Engine,
ast: AST,
scope: Scope<'static>,
last_frame_time: Instant,
graphics: Rc<RefCell<Option<Graphics2D>>>,
}
impl WindowHandler for SignWindowHandler {
fn on_draw(&mut self, helper: &mut WindowHelper, graphics: &mut Graphics2D) {
let dt = self.last_frame_time.elapsed().as_secs_f32();
self.last_frame_time = Instant::now();
// ! mismatched types, expected struct Graphics2D, fount &mut Graphics2D
self.graphics.replace(Some(graphics));
let result = self.engine.call_fn::<()>(&mut self.scope, &mut self.ast, "draw", (dt,));
if let Err(err) = result {
dbg!(&err);
}
helper.request_redraw();
}
fn on_start(&mut self, _helper: &mut WindowHelper<()>, _info: speedy2d::window::WindowStartupInfo) {
let graphics = self.graphics.clone();
self.engine.register_fn("clear_screen", move || {
if let Some(g) = graphics.borrow_mut().as_mut() {
g.clear_screen(Color::from_rgb(0.0, 0.0, 0.0));
}
});
}
}
fn main() {
println!("Starting...");
let engine = Engine::new();
let ast = engine.compile_file("examples/display1/main.rhai".into()).unwrap();
let scope = Scope::new();
let window = Window::new_centered("Title", (640, 480)).unwrap();
let handler = SignWindowHandler {
engine,
ast,
scope: Scope::new(),
last_frame_time: Instant::now(),
graphics: Rc::new(RefCell::new(None))
};
window.run_loop(handler);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment