/*
* This file is part of laurelin/client
* Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
*
* Licensed under GPL-3.0-only.
* See LICENSE for licensing information.
*/
use std::sync::Mutex;
use bevy_mod_scripting::prelude::*;
use bevy::prelude::*;
use bevy_console::PrintConsoleLine;
pub struct LuaPlugin;
impl Plugin for LuaPlugin {
fn build(&self, app: &mut App) {
app.add_startup_system(load_scripts)
.add_script_host::<LuaScriptHost<()>, _>(CoreStage::PostUpdate)
.add_script_handler_stage::<LuaScriptHost<()>, _, 0, 0>(CoreStage::PostUpdate)
.add_api_provider::<LuaScriptHost<()>>(Box::new(LuaAPIProvider))
.add_api_provider::<LuaScriptHost<()>>(Box::new(LuaBevyAPIProvider));
}
}
fn load_scripts(asset_server: Res<AssetServer>, mut commands: Commands) {
let script_paths = vec!["ui_play.lua"];
let mut scripts = vec![];
for path in script_paths {
let handle = asset_server.load::<LuaFile, &str>(&format!("scripts/{}", path));
scripts.push(Script::<LuaFile>::new(path.to_string(), handle));
}
commands
.spawn(())
.insert(ScriptCollection::<LuaFile> { scripts });
}
pub struct LuaAPIProvider;
impl APIProvider for LuaAPIProvider {
type APITarget = Mutex<Lua>;
type DocTarget = LuaDocFragment;
type ScriptContext = Mutex<Lua>;
fn attach_api(&mut self, api: &mut Self::APITarget) -> Result<(), ScriptError> {
let api = api.get_mut().unwrap();
api.globals()
.set(
"print_to_console",
api.create_function(|ctx, msg: String| {
// retrieve the world pointer
let world = ctx.get_world()?;
let mut world = world.write();
let mut events: Mut<Events<PrintConsoleLine>> =
world.get_resource_mut().unwrap();
events.send(PrintConsoleLine::new(msg.into()));
Ok(())
})
.map_err(ScriptError::new_other)?,
)
.map_err(ScriptError::new_other)?;
api.globals()
.set(
"print",
api.create_function(|_ctx, msg: String| {
info!("{}", msg);
Ok(())
})
.map_err(ScriptError::new_other)?,
)
.map_err(ScriptError::new_other)?;
Ok(())
}
}