diff --git a/crates/bevy_mod_scripting_core/src/lib.rs b/crates/bevy_mod_scripting_core/src/lib.rs index b596ce2a..a25e3b6e 100644 --- a/crates/bevy_mod_scripting_core/src/lib.rs +++ b/crates/bevy_mod_scripting_core/src/lib.rs @@ -126,12 +126,16 @@ impl Plugin for ScriptingPlugin

{ impl ScriptingPlugin

{ /// Adds a context initializer to the plugin + /// + /// Initializers will be run every time a context is loaded or re-loaded pub fn add_context_initializer(&mut self, initializer: ContextInitializer

) -> &mut Self { self.context_initializers.push(initializer); self } - /// Adds a context pre-handling initializer to the plugin + /// Adds a context pre-handling initializer to the plugin. + /// + /// Initializers will be run every time before handling events. pub fn add_context_pre_handling_initializer( &mut self, initializer: ContextPreHandlingInitializer

, @@ -139,6 +143,17 @@ impl ScriptingPlugin

{ self.context_pre_handling_initializers.push(initializer); self } + + /// Adds a runtime initializer to the plugin. + /// + /// Initializers will be run after the runtime is created, but before any contexts are loaded. + pub fn add_runtime_initializer(&mut self, initializer: RuntimeInitializer

) -> &mut Self { + self.runtime_settings + .get_or_insert_with(Default::default) + .initializers + .push(initializer); + self + } } // One of registration of things that need to be done only once per app diff --git a/docs/book.toml b/docs/book.toml index 60a51257..942cf5d2 100644 --- a/docs/book.toml +++ b/docs/book.toml @@ -9,3 +9,4 @@ description = "Documentation for the Bevy Scripting library" [output.html] additional-js = ["multi-code-block.js"] git-repository-url = "https://github.com/makspll/bevy_mod_scripting" +edit-url-template = "https://github.com/makspll/bevy_mod_scripting/edit/main/{path}" diff --git a/docs/src/Development/AddingLanguages/evaluating-feasibility.md b/docs/src/Development/AddingLanguages/evaluating-feasibility.md index 2037574d..c72d1d3a 100644 --- a/docs/src/Development/AddingLanguages/evaluating-feasibility.md +++ b/docs/src/Development/AddingLanguages/evaluating-feasibility.md @@ -2,7 +2,44 @@ In order for a language to work well with BMS it's necessary it supports the following features: - [ ] Interoperability with Rust. If you can't call it from Rust easilly and there is no existing crate that can do it for you, it's a no-go. -- [ ] First class functions. Or at least the ability to call an arbitrary function with an arbitrary number of arguments from a script. Without this feature, you would need to separately generate code for the bevy bindings. This is painful and goes against the grain of the project. +- [ ] First class functions. Or at least the ability to call an arbitrary function with an arbitrary number of arguments from a script. Without this feature, you would need to separately generate code for the bevy bindings which is painful and goes against the grain of BMS. ## First Classs Functions +They don't necessarily have to be first class from the script POV, but they need to be first class from the POV of the host language. This means that the host language needs to be able to call a function with an arbitrary number of arguments. + +### Examples + +Let's say your language supports a `Value` type which can be returned to the script. And it has a `Value::Function` variant. The type on the Rust side would look something like this: + +```rust,ignore +pub enum Value { + Function(Arc Value>), + // other variants +} +``` + +This is fine, and can be integrated with BMS. Since an Fn function can be a closure capturing a `DynamicScriptFunction`. If there is no support for `FnMut` closures though, you might face issues in the implementation. Iterators in `bevy_mod_scripting_functions` for example use `DynamicScriptFunctionMut` which cannot work with `Fn` closures. + +Now let's imagine instead another language with a similar enum, supports this type instead: + +```rust +pub enum Value { + Function(Arc), + // other variants +} + +pub trait Function { + fn call(&self, args: Vec) -> Value; + + fn num_params() -> usize; +} +``` + +This implies that to call this function, you need to be able to know the amount of arguments it expects at COMPILE time. This is not compatibile with dynamic functions, and would require a lot of code generation to make work with BMS. +Languages with no support for dynamic functions are not compatible with BMS. + +## Interoperability with Rust + +Not all languages can easilly be called from Rust. Lua has a wonderful crate which works out the ffi and safety issues for us. But not all languages have this luxury. If you can't call it from Rust easilly and there is no existing crate that can do it for you, integrating with BMS might not be the best idea. + diff --git a/docs/src/Development/AddingLanguages/necessary-features.md b/docs/src/Development/AddingLanguages/necessary-features.md new file mode 100644 index 00000000..d1b0251b --- /dev/null +++ b/docs/src/Development/AddingLanguages/necessary-features.md @@ -0,0 +1,36 @@ +# Necessary Features + +In order for a language to be called "implemented" in BMS, it needs to support the following features: + +- Every script function which is registered on a type's namespace must: + - Be callable on a `ReflectReference` representing object of that type in the script + ```lua + local my_reference = ... + my_reference:my_Registered_function() + ``` + - If it's static it must be callable from a global proxy object for that type, i.e. + ```lua + MyType.my_static_function() + ``` +- `ReflectReferences` must support a set of basic features: + - Access to fields via reflection i.e.: + ```lua + local my_reference = ... + my_reference.my_field = 5 + print(my_reference.my_field) + ``` + - Basic operators and standard operations are overloaded with the appropriate standard dynamic function registered: + - Addition: dispatches to the `add` binary function on the type + - Multiplication: dispatches to the `mul` binary function on the type + - Division: dispatches to the `div` binary function on the type + - Subtraction: dispatches to the `sub` binary function on the type + - Modulo: dispatches to the `rem` binary function on the type + - Negation: dispatches to the `neg` unary function on the type + - Exponentiation: dispatches to the `pow` binary function on the type + - Equality: dispatches to the `eq` binary function on the type + - Less than: dispatches to the `lt` binary function on the type + - Length: calls the `len` method on `ReflectReference` or on the table if the value is one. + - Iteration: dispatches to the `iter` method on `ReflectReference` which returns an iterator function, this can be repeatedly called until it returns `ScriptValue::Unit` to signal the end of the iteration. + - Print: calls the `display_ref` method on `ReflectReference` or on the table if the value is one. +- Script handlers, loaders etc. must be implemented such that the `ThreadWorldContainer` is set for every interaction with script contexts, or anywhere else it might be needed. + diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 3c327cee..ced174f0 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -7,6 +7,7 @@ - [Managing Scripts](./Summary/managing-scripts.md) - [Running Scripts](./Summary/running-scripts.md) - [Controlling Script Bindings](./Summary/controlling-script-bindings.md) +- [Modifying Script Contexts](./Summary/customizing-script-contexts.md) # Scripting Reference @@ -24,4 +25,5 @@ - [Introduction](./Development/introduction.md) - [Setup](./Development/setup.md) - [New Languages](./Development/AddingLanguages/introduction.md) - - [Evaluating Feasibility](./Development/AddingLanguages/evaluating-feasibility.md) \ No newline at end of file + - [Evaluating Feasibility](./Development/AddingLanguages/evaluating-feasibility.md) + - [Necessary Features](./Development/AddingLanguages/necessary-features.md) \ No newline at end of file diff --git a/docs/src/Summary/customizing-script-contexts.md b/docs/src/Summary/customizing-script-contexts.md new file mode 100644 index 00000000..68cd7c53 --- /dev/null +++ b/docs/src/Summary/customizing-script-contexts.md @@ -0,0 +1,61 @@ +# Modifying Script Contexts + +You should be able to achieve what you need by registering script functions in most cases. However sometimes you might want to override the way contexts are loaded, or how the runtime is initialized. + +This is possible using `Context Initializers` and `Context Pre Handling Initializers` as well as `Runtime Initializers`. + + +## Context Initializers + +For example, let's say you want to set a dynamic amount of globals in your script, depending on some setting in your app. + +You could do this by customizing the scripting plugin: +```rust,ignore +let plugin = LuaScriptingPlugin::default(); +plugin.add_context_initializer(|script_id: &str, context: &mut Lua| { + let globals = context.globals(); + for i in 0..10 { + globals.set(i, i); + } + Ok(()) +}); + +app.add_plugins(plugin) +``` + +The above will run every time the script is loaded or re-loaded. + +## Context Pre Handling Initializers + +If you want to customize your context before every time it's about to handle events, you can use `Context Pre Handling Initializers`: +```rust,ignore +let plugin = LuaScriptingPlugin::default(); +plugin.add_context_pre_handling_initializer(|script_id: &str, entity: Entity, context: &mut Lua| { + let globals = context.globals(); + globals.set("script_name", script_id.to_owned()); + Ok(()) +}); +``` +## Runtime Initializers + +Some scripting languages, have the concept of a `runtime`. This is a global object which is shared between all contexts. You can customize this object using `Runtime Initializers`: +```rust,ignore +let plugin = SomeScriptingPlugin::default(); +plugin.add_runtime_initializer(|runtime: &mut Runtime| { + runtime.set_max_stack_size(1000); + Ok(()) +}); +``` + +## Accessing the World in Initializers + +You can access the world in these initializers by using the thread local: `ThreadWorldContainer`: +```rust,ignore + +let plugin = LuaScriptingPlugin::default(); +plugin.add_context_initializer(|script_id: &str, context: &mut Lua| { + let world = ThreadWorldContainer::get_world(); + world.with_resource::(|res| println!("My resource: {:?}", res)); + Ok(()) +}); +``` \ No newline at end of file