/* * This file is part of sdbclient * Copyright (C) 2022 Jonni Liljamo * * 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::, _>(CoreStage::PostUpdate) .add_script_handler_stage::, _, 0, 0>(CoreStage::PostUpdate) .add_api_provider::>(Box::new(LuaAPIProvider)) .add_api_provider::>(Box::new(LuaBevyAPIProvider)); } } fn load_scripts(asset_server: Res, mut commands: Commands) { let script_paths = vec!["ui_play.lua"]; let mut scripts = vec![]; for path in script_paths { let handle = asset_server.load::(&format!("scripts/{}", path)); scripts.push(Script::::new(path.to_string(), handle)); } commands .spawn(()) .insert(ScriptCollection:: { scripts }); } pub struct LuaAPIProvider; impl APIProvider for LuaAPIProvider { type APITarget = Mutex; type DocTarget = LuaDocFragment; type ScriptContext = Mutex; 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> = 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(()) } }