Skip to content

Commit

Permalink
chore: Improve docs (#205)
Browse files Browse the repository at this point in the history
* Add more information to docs

* add information on world containers

* add edit url to mdbook
  • Loading branch information
makspll authored Jan 14, 2025
1 parent bc83c5a commit 39cf747
Show file tree
Hide file tree
Showing 6 changed files with 155 additions and 3 deletions.
17 changes: 16 additions & 1 deletion crates/bevy_mod_scripting_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,19 +126,34 @@ impl<P: IntoScriptPluginParams> Plugin for ScriptingPlugin<P> {

impl<P: IntoScriptPluginParams> ScriptingPlugin<P> {
/// 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<P>) -> &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<P>,
) -> &mut Self {
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<P>) -> &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
Expand Down
1 change: 1 addition & 0 deletions docs/book.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
39 changes: 38 additions & 1 deletion docs/src/Development/AddingLanguages/evaluating-feasibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Fn(&[Value]) -> 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<dyn Function>),
// other variants
}

pub trait Function {
fn call(&self, args: Vec<Value>) -> 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.

36 changes: 36 additions & 0 deletions docs/src/Development/AddingLanguages/necessary-features.md
Original file line number Diff line number Diff line change
@@ -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.

4 changes: 3 additions & 1 deletion docs/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
- [Evaluating Feasibility](./Development/AddingLanguages/evaluating-feasibility.md)
- [Necessary Features](./Development/AddingLanguages/necessary-features.md)
61 changes: 61 additions & 0 deletions docs/src/Summary/customizing-script-contexts.md
Original file line number Diff line number Diff line change
@@ -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::<MyResource>(|res| println!("My resource: {:?}", res));
Ok(())
});
```

0 comments on commit 39cf747

Please sign in to comment.