This commit is contained in:
Jaroslaw Konik 2025-05-25 07:56:35 +02:00
parent 9e3dce14a2
commit 04d2b6b93b
9 changed files with 55 additions and 57 deletions

View file

@ -1,10 +1,10 @@
use bevy::prelude::*; use bevy::prelude::*;
use bevy_scriptum::ScriptingError;
use bevy_scriptum::prelude::*; use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::ruby::magnus; use bevy_scriptum::runtimes::ruby::magnus;
use bevy_scriptum::runtimes::ruby::magnus::Module as _; use bevy_scriptum::runtimes::ruby::magnus::Module as _;
use bevy_scriptum::runtimes::ruby::magnus::Object as _; use bevy_scriptum::runtimes::ruby::magnus::Object as _;
use bevy_scriptum::runtimes::ruby::prelude::*; use bevy_scriptum::runtimes::ruby::prelude::*;
use bevy_scriptum::ScriptingError;
fn main() { fn main() {
App::new() App::new()
@ -39,7 +39,7 @@ fn startup(
assets_server: Res<AssetServer>, assets_server: Res<AssetServer>,
) { ) {
scripting_runtime scripting_runtime
.with_engine_thread(|ruby| { .with_engine_send(|ruby| {
let my_type = ruby.define_class("MyType", ruby.class_object())?; let my_type = ruby.define_class("MyType", ruby.class_object())?;
my_type.define_singleton_method("new", magnus::function!(MyType::new, 0))?; my_type.define_singleton_method("new", magnus::function!(MyType::new, 0))?;
my_type.define_method("my_method", magnus::method!(MyType::my_method, 0))?; my_type.define_method("my_method", magnus::method!(MyType::my_method, 0))?;

View file

@ -1,6 +1,6 @@
use bevy::prelude::*; use bevy::prelude::*;
use bevy_scriptum::prelude::*; use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::ruby::{prelude::*, RArray}; use bevy_scriptum::runtimes::ruby::{RArray, prelude::*};
fn main() { fn main() {
App::new() App::new()
@ -31,7 +31,7 @@ fn main() {
.add_function( .add_function(
String::from("fun_with_i64_and_array_param"), String::from("fun_with_i64_and_array_param"),
|In((x, y)): In<(i64, RArray)>, runtime: Res<RubyRuntime>| { |In((x, y)): In<(i64, RArray)>, runtime: Res<RubyRuntime>| {
runtime.with_engine_thread(move |ruby| { runtime.with_engine_send(move |ruby| {
println!( println!(
"called with i64: {} and dynamically typed array: {:?}", "called with i64: {} and dynamically typed array: {:?}",
x, x,

View file

@ -1,8 +1,8 @@
use bevy::{app::AppExit, prelude::*}; use bevy::{app::AppExit, prelude::*};
use bevy_scriptum::prelude::*; use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::ruby::prelude::*; use bevy_scriptum::runtimes::ruby::prelude::*;
use magnus::value::InnerValue;
use magnus::TryConvert; use magnus::TryConvert;
use magnus::value::InnerValue;
fn main() { fn main() {
App::new() App::new()
@ -33,7 +33,7 @@ fn call_lua_on_update_from_rust(
.call_fn("get_value", &mut script_data, entity, ()) .call_fn("get_value", &mut script_data, entity, ())
.unwrap() .unwrap()
.0; .0;
scripting_runtime.with_engine_thread(move |ruby| { scripting_runtime.with_engine(|ruby| {
let val: i32 = TryConvert::try_convert(val.get_inner_with(&ruby)).unwrap(); let val: i32 = TryConvert::try_convert(val.get_inner_with(&ruby)).unwrap();
println!("script returned: {}", val); println!("script returned: {}", val);
}); });

View file

@ -2,7 +2,7 @@ use bevy::prelude::*;
use core::any::TypeId; use core::any::TypeId;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use crate::{promise::Promise, Runtime}; use crate::{Runtime, promise::Promise};
/// A system that can be used to call a script function. /// A system that can be used to call a script function.
pub struct CallbackSystem<R: Runtime> { pub struct CallbackSystem<R: Runtime> {
@ -79,7 +79,7 @@ where
let mut runtime = world.get_resource_mut::<R>().expect("No runtime resource"); let mut runtime = world.get_resource_mut::<R>().expect("No runtime resource");
if R::needs_own_thread() { if R::needs_own_thread() {
runtime.with_engine_thread_mut(move |engine| { runtime.with_engine_send_mut(move |engine| {
Out::into_runtime_value_with_engine(result, engine) Out::into_runtime_value_with_engine(result, engine)
}) })
} else { } else {

View file

@ -305,7 +305,7 @@ pub trait Runtime: Resource + Default {
/// Provides mutable reference to raw scripting engine instance. /// Provides mutable reference to raw scripting engine instance.
/// Can be used to directly interact with an interpreter to use interfaces /// Can be used to directly interact with an interpreter to use interfaces
/// that bevy_scriptum does not provided adapters for. /// that bevy_scriptum does not provided adapters for.
fn with_engine_thread_mut<T: Send + 'static>( fn with_engine_send_mut<T: Send + 'static>(
&mut self, &mut self,
f: impl FnOnce(&mut Self::RawEngine) -> T + Send + 'static, f: impl FnOnce(&mut Self::RawEngine) -> T + Send + 'static,
) -> T; ) -> T;
@ -313,7 +313,7 @@ pub trait Runtime: Resource + Default {
/// Provides immutable reference to raw scripting engine instance. /// Provides immutable reference to raw scripting engine instance.
/// Can be used to directly interact with an interpreter to use interfaces /// Can be used to directly interact with an interpreter to use interfaces
/// that bevy_scriptum does not provided adapters for. /// that bevy_scriptum does not provided adapters for.
fn with_engine_thread<T: Send + 'static>( fn with_engine_send<T: Send + 'static>(
&self, &self,
f: impl FnOnce(&Self::RawEngine) -> T + Send + 'static, f: impl FnOnce(&Self::RawEngine) -> T + Send + 'static,
) -> T; ) -> T;
@ -342,12 +342,12 @@ pub trait Runtime: Resource + Default {
name: String, name: String,
arg_types: Vec<TypeId>, arg_types: Vec<TypeId>,
f: impl Fn( f: impl Fn(
Self::CallContext, Self::CallContext,
Vec<Self::Value>, Vec<Self::Value>,
) -> Result<Promise<Self::CallContext, Self::Value>, ScriptingError> ) -> Result<Promise<Self::CallContext, Self::Value>, ScriptingError>
+ Send + Send
+ Sync + Sync
+ 'static, + 'static,
) -> Result<(), ScriptingError>; ) -> Result<(), ScriptingError>;
/// Calls a function by name defined within the runtime in the context of the /// Calls a function by name defined within the runtime in the context of the

View file

@ -13,10 +13,10 @@ use serde::Deserialize;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use crate::{ use crate::{
ENTITY_VAR_NAME, FuncArgs, Runtime, ScriptingError,
assets::GetExtensions, assets::GetExtensions,
callback::{FromRuntimeValueWithEngine, IntoRuntimeValueWithEngine}, callback::{FromRuntimeValueWithEngine, IntoRuntimeValueWithEngine},
promise::Promise, promise::Promise,
FuncArgs, Runtime, ScriptingError, ENTITY_VAR_NAME,
}; };
type LuaEngine = Arc<Mutex<Lua>>; type LuaEngine = Arc<Mutex<Lua>>;
@ -197,14 +197,14 @@ impl Runtime for LuaRuntime {
name: String, name: String,
_arg_types: Vec<std::any::TypeId>, _arg_types: Vec<std::any::TypeId>,
f: impl Fn( f: impl Fn(
Self::CallContext, Self::CallContext,
Vec<Self::Value>, Vec<Self::Value>,
) -> Result< ) -> Result<
crate::promise::Promise<Self::CallContext, Self::Value>, crate::promise::Promise<Self::CallContext, Self::Value>,
crate::ScriptingError, crate::ScriptingError,
> + Send > + Send
+ Sync + Sync
+ 'static, + 'static,
) -> Result<(), crate::ScriptingError> { ) -> Result<(), crate::ScriptingError> {
self.with_engine(|engine| { self.with_engine(|engine| {
let func = engine let func = engine
@ -283,14 +283,14 @@ impl Runtime for LuaRuntime {
f(&engine) f(&engine)
} }
fn with_engine_thread_mut<T: Send + 'static>( fn with_engine_send_mut<T: Send + 'static>(
&mut self, &mut self,
f: impl FnOnce(&mut Self::RawEngine) -> T + Send + 'static, f: impl FnOnce(&mut Self::RawEngine) -> T + Send + 'static,
) -> T { ) -> T {
self.with_engine_mut(f) self.with_engine_mut(f)
} }
fn with_engine_thread<T: Send + 'static>( fn with_engine_send<T: Send + 'static>(
&self, &self,
f: impl FnOnce(&Self::RawEngine) -> T + Send + 'static, f: impl FnOnce(&Self::RawEngine) -> T + Send + 'static,
) -> T { ) -> T {

View file

@ -11,10 +11,10 @@ use rhai::{CallFnOptions, Dynamic, Engine, FnPtr, Scope, Variant};
use serde::Deserialize; use serde::Deserialize;
use crate::{ use crate::{
ENTITY_VAR_NAME, FuncArgs, Runtime, ScriptingError,
assets::GetExtensions, assets::GetExtensions,
callback::{FromRuntimeValueWithEngine, IntoRuntimeValueWithEngine}, callback::{FromRuntimeValueWithEngine, IntoRuntimeValueWithEngine},
promise::Promise, promise::Promise,
FuncArgs, Runtime, ScriptingError, ENTITY_VAR_NAME,
}; };
#[derive(Asset, Debug, Deserialize, TypePath)] #[derive(Asset, Debug, Deserialize, TypePath)]
@ -118,12 +118,12 @@ impl Runtime for RhaiRuntime {
name: String, name: String,
arg_types: Vec<std::any::TypeId>, arg_types: Vec<std::any::TypeId>,
f: impl Fn( f: impl Fn(
Self::CallContext, Self::CallContext,
Vec<Self::Value>, Vec<Self::Value>,
) -> Result<Promise<Self::CallContext, Self::Value>, ScriptingError> ) -> Result<Promise<Self::CallContext, Self::Value>, ScriptingError>
+ Send + Send
+ Sync + Sync
+ 'static, + 'static,
) -> Result<(), ScriptingError> { ) -> Result<(), ScriptingError> {
self.engine self.engine
.register_raw_fn(name, arg_types, move |context, args| { .register_raw_fn(name, arg_types, move |context, args| {
@ -192,14 +192,14 @@ impl Runtime for RhaiRuntime {
f(&self.engine) f(&self.engine)
} }
fn with_engine_thread_mut<T: Send + 'static>( fn with_engine_send_mut<T: Send + 'static>(
&mut self, &mut self,
f: impl FnOnce(&mut Self::RawEngine) -> T + Send + 'static, f: impl FnOnce(&mut Self::RawEngine) -> T + Send + 'static,
) -> T { ) -> T {
self.with_engine_mut(f) self.with_engine_mut(f)
} }
fn with_engine_thread<T: Send + 'static>( fn with_engine_send<T: Send + 'static>(
&self, &self,
f: impl FnOnce(&Self::RawEngine) -> T + Send + 'static, f: impl FnOnce(&Self::RawEngine) -> T + Send + 'static,
) -> T { ) -> T {

View file

@ -14,20 +14,20 @@ use bevy::{
tasks::futures_lite::io, tasks::futures_lite::io,
}; };
use magnus::{ use magnus::{
DataType, DataTypeFunctions, IntoValue, Object, RClass, RModule, Ruby, TryConvert, TypedData,
block::Proc, block::Proc,
data_type_builder, function, data_type_builder, function,
value::{Lazy, ReprValue}, value::{Lazy, ReprValue},
DataType, DataTypeFunctions, IntoValue, Object, RClass, RModule, Ruby, TryConvert, TypedData,
}; };
use magnus::{method, prelude::*}; use magnus::{method, prelude::*};
use rb_sys::{ruby_init_stack, VALUE}; use rb_sys::{VALUE, ruby_init_stack};
use serde::Deserialize; use serde::Deserialize;
use crate::{ use crate::{
FuncArgs, Runtime, ScriptingError,
assets::GetExtensions, assets::GetExtensions,
callback::{FromRuntimeValueWithEngine, IntoRuntimeValueWithEngine}, callback::{FromRuntimeValueWithEngine, IntoRuntimeValueWithEngine},
promise::Promise, promise::Promise,
FuncArgs, Runtime, ScriptingError,
}; };
#[derive(Resource)] #[derive(Resource)]
@ -323,16 +323,14 @@ impl Runtime for RubyRuntime {
type RawEngine = magnus::Ruby; type RawEngine = magnus::Ruby;
// TODO: it should be somehow possible to remove 'static here fn with_engine_send_mut<T: Send + 'static>(
fn with_engine_thread_mut<T: Send + 'static>(
&mut self, &mut self,
f: impl FnOnce(&mut Self::RawEngine) -> T + Send + 'static, f: impl FnOnce(&mut Self::RawEngine) -> T + Send + 'static,
) -> T { ) -> T {
self.execute_in_thread_mut(f) self.execute_in_thread_mut(f)
} }
// TODO: it should be somehow possible to remove 'static here fn with_engine_send<T: Send + 'static>(
fn with_engine_thread<T: Send + 'static>(
&self, &self,
f: impl FnOnce(&Self::RawEngine) -> T + Send + 'static, f: impl FnOnce(&Self::RawEngine) -> T + Send + 'static,
) -> T { ) -> T {
@ -374,14 +372,14 @@ impl Runtime for RubyRuntime {
name: String, name: String,
_arg_types: Vec<std::any::TypeId>, _arg_types: Vec<std::any::TypeId>,
f: impl Fn( f: impl Fn(
Self::CallContext, Self::CallContext,
Vec<Self::Value>, Vec<Self::Value>,
) -> Result< ) -> Result<
crate::promise::Promise<Self::CallContext, Self::Value>, crate::promise::Promise<Self::CallContext, Self::Value>,
crate::ScriptingError, crate::ScriptingError,
> + Send > + Send
+ Sync + Sync
+ 'static, + 'static,
) -> Result<(), crate::ScriptingError> { ) -> Result<(), crate::ScriptingError> {
type CallbackClosure = Box< type CallbackClosure = Box<
dyn Fn( dyn Fn(

View file

@ -6,7 +6,7 @@ use bevy::ecs::system::RunSystemOnce as _;
#[cfg(any(feature = "rhai", feature = "lua", feature = "ruby"))] #[cfg(any(feature = "rhai", feature = "lua", feature = "ruby"))]
use bevy::prelude::*; use bevy::prelude::*;
#[cfg(any(feature = "rhai", feature = "lua", feature = "ruby"))] #[cfg(any(feature = "rhai", feature = "lua", feature = "ruby"))]
use bevy_scriptum::{prelude::*, FuncArgs, Runtime}; use bevy_scriptum::{FuncArgs, Runtime, prelude::*};
#[cfg(any(feature = "rhai", feature = "lua", feature = "ruby"))] #[cfg(any(feature = "rhai", feature = "lua", feature = "ruby"))]
static TRACING_SUBSCRIBER: OnceLock<()> = OnceLock::new(); static TRACING_SUBSCRIBER: OnceLock<()> = OnceLock::new();
@ -621,7 +621,7 @@ mod lua_tests {
#[cfg(feature = "ruby")] #[cfg(feature = "ruby")]
mod ruby_tests { mod ruby_tests {
use bevy::prelude::*; use bevy::prelude::*;
use bevy_scriptum::runtimes::ruby::{prelude::*, RubyScriptData}; use bevy_scriptum::runtimes::ruby::{RubyScriptData, prelude::*};
use magnus::value::ReprValue; use magnus::value::ReprValue;
impl AssertStateKeyValue for RubyRuntime { impl AssertStateKeyValue for RubyRuntime {
@ -630,7 +630,7 @@ mod ruby_tests {
fn assert_state_key_value_i64(world: &World, _entity_id: Entity, key: &str, value: i64) { fn assert_state_key_value_i64(world: &World, _entity_id: Entity, key: &str, value: i64) {
let runtime = world.get_resource::<RubyRuntime>().unwrap(); let runtime = world.get_resource::<RubyRuntime>().unwrap();
let key = key.to_string(); let key = key.to_string();
runtime.with_engine_thread(move |engine| { runtime.with_engine_send(move |engine| {
let state: magnus::value::Value = engine.eval("$state").unwrap(); let state: magnus::value::Value = engine.eval("$state").unwrap();
let res: i64 = state.funcall_public("[]", (key,)).unwrap(); let res: i64 = state.funcall_public("[]", (key,)).unwrap();
assert_eq!(res, value) assert_eq!(res, value)
@ -640,7 +640,7 @@ mod ruby_tests {
fn assert_state_key_value_i32(world: &World, _entity_id: Entity, key: &str, value: i32) { fn assert_state_key_value_i32(world: &World, _entity_id: Entity, key: &str, value: i32) {
let runtime = world.get_resource::<RubyRuntime>().unwrap(); let runtime = world.get_resource::<RubyRuntime>().unwrap();
let key = key.to_string(); let key = key.to_string();
runtime.with_engine_thread(move |engine| { runtime.with_engine_send(move |engine| {
let state: magnus::value::Value = engine.eval("$state").unwrap(); let state: magnus::value::Value = engine.eval("$state").unwrap();
let res: i32 = state.funcall_public("[]", (key,)).unwrap(); let res: i32 = state.funcall_public("[]", (key,)).unwrap();
assert_eq!(res, value) assert_eq!(res, value)
@ -656,7 +656,7 @@ mod ruby_tests {
let runtime = world.get_resource::<RubyRuntime>().unwrap(); let runtime = world.get_resource::<RubyRuntime>().unwrap();
let key = key.to_string(); let key = key.to_string();
let value = value.to_string(); let value = value.to_string();
runtime.with_engine_thread(move |engine| { runtime.with_engine_send(move |engine| {
let state: magnus::value::Value = engine.eval("$state").unwrap(); let state: magnus::value::Value = engine.eval("$state").unwrap();
let res: String = state.funcall_public("[]", (key,)).unwrap(); let res: String = state.funcall_public("[]", (key,)).unwrap();
assert_eq!(res, value); assert_eq!(res, value);
@ -670,7 +670,7 @@ mod ruby_tests {
app.add_scripting::<RubyRuntime>(|_| {}); app.add_scripting::<RubyRuntime>(|_| {});
let runtime = app.world().get_resource::<RubyRuntime>().unwrap(); let runtime = app.world().get_resource::<RubyRuntime>().unwrap();
runtime.with_engine_thread(|engine| { runtime.with_engine_send(|engine| {
let symbol_string: String = engine.eval(":test_symbol.inspect").unwrap(); let symbol_string: String = engine.eval(":test_symbol.inspect").unwrap();
assert_eq!(symbol_string, ":test_symbol") assert_eq!(symbol_string, ":test_symbol")
}); });