bevy_scriptum 0.11.0

Plugin for Bevy engine that allows you to write some of your game or application logic in a scripting language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! ![demo](demo.gif)
//!
//! bevy_scriptum is a a plugin for [Bevy](https://bevyengine.org/) that allows you to write some of your game or application logic in a scripting language.

//! ## Supported scripting languages/runtimes
//!
//! | language/runtime                                     | cargo feature | documentation chapter                                           |
//! | ---------------------------------------------------- | ------------- | --------------------------------------------------------------- |
//! | 🌙 LuaJIT                                            | `lua`         | [link](https://jarkonik.github.io/bevy_scriptum/lua/lua.html)   |
//! | 🌾 Rhai                                              | `rhai`        | [link](https://jarkonik.github.io/bevy_scriptum/rhai/rhai.html) |
//! | 💎 Ruby(currently only supported on Linux and MacOS) | `ruby`        | [link](https://jarkonik.github.io/bevy_scriptum/ruby/ruby.html) |
//!
//! Documentation book is available [here](https://jarkonik.github.io/bevy_scriptum/) 📖
//!
//! Full API docs are available at [docs.rs](https://docs.rs/bevy_scriptum/latest/bevy_scriptum/) 🧑‍💻
//!
//! bevy_scriptum's main advantages include:
//! - low-boilerplate
//! - easy to use
//! - asynchronicity with a promise-based API
//! - flexibility
//! - hot-reloading
//!
//! Scripts are separate files that can be hot-reloaded at runtime. This allows you to quickly iterate on your game or application logic without having to recompile it.
//!
//! All you need to do is register callbacks on your Bevy app like this:
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_scriptum::prelude::*;
//! # #[cfg(feature = "lua")]
//! use bevy_scriptum::runtimes::lua::prelude::*;
//!
//! # #[cfg(feature = "lua")]
//! App::new()
//!     .add_plugins(DefaultPlugins)
//!     .add_scripting::<LuaRuntime>(|runtime| {
//!          runtime.add_function(String::from("hello_bevy"), || {
//!            println!("hello bevy, called from script");
//!          });
//!     })
//!     .run();
//! ```
//! And you can call them in your scripts like this:
//! ```lua
//! hello_bevy()
//! ```
//!
//! Every callback function that you expose to the scripting language is also a Bevy system, so you can easily query and mutate ECS components and resources just like you would in a regular Bevy system:
//!
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_scriptum::prelude::*;
//! # #[cfg(feature = "lua")]
//! use bevy_scriptum::runtimes::lua::prelude::*;
//!
//! #[derive(Component)]
//! struct Player;
//!
//! # #[cfg(feature = "lua")]
//! App::new()
//!     .add_plugins(DefaultPlugins)
//!     .add_scripting::<LuaRuntime>(|runtime| {
//!         runtime.add_function(
//!             String::from("print_player_names"),
//!             |players: Query<&Name, With<Player>>| {
//!                 for player in &players {
//!                     println!("player name: {}", player);
//!                 }
//!             },
//!         );
//!     })
//!     .run();
//! ```
//!
//! You can also pass arguments to your callback functions, just like you would in a regular Bevy system - using `In` structs with tuples:
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_scriptum::prelude::*;
//! # #[cfg(feature = "lua")]
//! use bevy_scriptum::runtimes::lua::prelude::*;
//!
//! # #[cfg(feature = "lua")]
//! App::new()
//!     .add_plugins(DefaultPlugins)
//!     .add_scripting::<LuaRuntime>(|runtime| {
//!         runtime.add_function(
//!             String::from("fun_with_string_param"),
//!             |In((x,)): In<(String,)>| {
//!                 println!("called with string: '{}'", x);
//!             },
//!         );
//!     })
//!     .run();
//! ```
//! which you can then call in your script like this:
//! ```lua
//! fun_with_string_param("Hello world!")
//! ```
//!
//! ## Usage
//!
//! Add the following to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! bevy_scriptum = { version = "0.11", features = ["lua"] }
//! ```
//!
//! or execute `cargo add bevy_scriptum --features lua` from your project directory.
//!
//! You can now start exposing functions to the scripting language. For example, you can expose a function that prints a message to the console:
//!
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_scriptum::prelude::*;
//! # #[cfg(feature = "lua")]
//! use bevy_scriptum::runtimes::lua::prelude::*;
//!
//! # #[cfg(feature = "lua")]
//! App::new()
//!     .add_plugins(DefaultPlugins)
//!     .add_scripting::<LuaRuntime>(|runtime| {
//!        runtime.add_function(
//!            String::from("my_print"),
//!            |In((x,)): In<(String,)>| {
//!                println!("my_print: '{}'", x);
//!            },
//!        );
//!     })
//!     .run();
//! ```
//!
//! Then you can create a script file in `assets` directory called `script.lua` that calls this function:
//!
//! ```lua
//! my_print("Hello world!")
//! ```
//!
//! And spawn an entity with attached `Script` component with a handle to a script source file:
//!
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_scriptum::prelude::*;
//! # #[cfg(feature = "lua")]
//! use bevy_scriptum::runtimes::lua::prelude::*;
//!
//! # #[cfg(feature = "lua")]
//! App::new()
//!     .add_plugins(DefaultPlugins)
//!     .add_scripting::<LuaRuntime>(|runtime| {
//!        runtime.add_function(
//!            String::from("my_print"),
//!            |In((x,)): In<(String,)>| {
//!                println!("my_print: '{}'", x);
//!            },
//!        );
//!     })
//!     .add_systems(Startup,|mut commands: Commands, asset_server: Res<AssetServer>| {
//!         commands.spawn(Script::<LuaScript>::new(asset_server.load("script.lua")));
//!     })
//!     .run();
//! ```
//!
//! You should then see `my_print: 'Hello world!'` printed in your console.
//!
//! ## Provided examples
//!
//! You can also try running provided examples by cloning this repository and running `cargo run --example <example_name>_<language_name>`.  For example:
//!
//! ```bash
//! cargo run --example hello_world_lua
//! ```
//! The examples live in `examples` directory and their corresponding scripts live in `assets/examples` directory within the repository.
//!
//! ## Bevy compatibility
//!
//! | bevy version | bevy_scriptum version |
//! |--------------|-----------------------|
//! | 0.18         | 0.11                  |
//! | 0.17         | 0.10                  |
//! | 0.16         | 0.8-0.9               |
//! | 0.15         | 0.7                   |
//! | 0.14         | 0.6                   |
//! | 0.13         | 0.4-0.5               |
//! | 0.12         | 0.3                   |
//! | 0.11         | 0.2                   |
//! | 0.10         | 0.1                   |
//!
//! ## Promises - getting return values from scripts
//!
//! Every function called from script returns a promise that you can call `:and_then` with a callback function on. This callback function will be called when the promise is resolved, and will be passed the return value of the function called from script. For example:
//!
//! ```lua
//! get_player_name():and_then(function(name)
//!     print(name)
//! end)
//! ```
//! which will print out `John` when used with following exposed function:
//!
//! ```
//! use bevy::prelude::*;
//! use bevy_scriptum::prelude::*;
//! # #[cfg(feature = "lua")]
//! use bevy_scriptum::runtimes::lua::prelude::*;
//!
//! # #[cfg(feature = "lua")]
//! App::new()
//!    .add_plugins(DefaultPlugins)
//!    .add_scripting::<LuaRuntime>(|runtime| {
//!            runtime.add_function(String::from("get_player_name"), || String::from("John"));
//!    });
//! ````
//!
//! ## Access entity from script
//!
//! A variable called `entity` is automatically available to all scripts - it represents bevy entity that the `Script` component is attached to.
//! It exposes `index` property that returns bevy entity index.
//! It is useful for accessing entity's components from scripts.
//! It can be used in the following way:
//! ```lua
//! print("Current entity index: " .. entity.index)
//! ```
//!
//! `entity` variable is currently not available within promise callbacks.
//!
//! ## Contributing
//!
//! Contributions are welcome! Feel free to open an issue or submit a pull request.
//!
//! ## License
//!
//! bevy_scriptum is licensed under either of the following, at your option:
//! Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) or MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)

mod assets;
mod callback;
mod components;
mod promise;
mod systems;

pub mod runtimes;

pub use crate::components::Script;
use assets::GetExtensions;
use promise::Promise;

use std::{
    any::TypeId,
    fmt::Debug,
    hash::Hash,
    marker::PhantomData,
    sync::{Arc, Mutex},
};

use bevy::{
    app::MainScheduleOrder,
    ecs::{component::Mutable, schedule::ScheduleLabel},
    prelude::*,
};
use callback::{Callback, IntoCallbackSystem};
use systems::{init_callbacks, log_errors, process_calls};
use thiserror::Error;

use self::{
    assets::ScriptLoader,
    systems::{process_new_scripts, reload_scripts},
};

#[cfg(any(feature = "rhai", feature = "lua"))]
const ENTITY_VAR_NAME: &str = "entity";

/// An error that can occur when internal [ScriptingPlugin] systems are being executed
#[derive(Error, Debug)]
pub enum ScriptingError {
    #[error("script runtime error:\n{0}")]
    RuntimeError(String),
    #[error("script compilation error:\n{0}")]
    CompileError(Box<dyn std::error::Error + Send>),
    #[error("no runtime resource present")]
    NoRuntimeResource,
    #[error("no settings resource present")]
    NoSettingsResource,
}

#[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone)]
pub enum ScriptSystemSet {
    Reload,
    Process,
}

/// Trait that represents a scripting runtime/engine. In practice it is
/// implemented for a scripint language interpreter and the implementor provides
/// function implementations for calling and registering functions within the interpreter.
pub trait Runtime: Resource + Default {
    type Schedule: ScheduleLabel + Debug + Clone + Eq + Hash + Default;
    type ScriptAsset: Asset + From<String> + GetExtensions;
    type ScriptData: Component<Mutability = Mutable>;
    type CallContext: Send + Clone;
    type Value: Send + Clone;
    type RawEngine;

    /// Provides mutable reference to raw scripting engine instance.
    /// Can be used to directly interact with an interpreter to use interfaces
    /// that bevy_scriptum does not provided adapters for.
    /// Using this function make the closure be executed on another thread for
    /// some runtimes. If you need to operate on non-`'static` borrows and/or
    /// `!Send` data, you can use `with_engine_mut` - it may not be implemented
    /// for some of the runtimes though.
    fn with_engine_send_mut<T: Send + 'static>(
        &mut self,
        f: impl FnOnce(&mut Self::RawEngine) -> T + Send + 'static,
    ) -> T;

    /// Provides immutable reference to raw scripting engine instance.
    /// Can be used to directly interact with an interpreter to use interfaces
    /// that bevy_scriptum does not provided adapters for.
    /// Using this function make the closure be executed on another thread for
    /// some runtimes. If you need to operate on non-`'static` borrows and/or
    /// `!Send` data, you can use `with_engine` - it may not be implemented
    /// for some of the runtimes though.
    fn with_engine_send<T: Send + 'static>(
        &self,
        f: impl FnOnce(&Self::RawEngine) -> T + Send + 'static,
    ) -> T;

    /// Provides mutable reference to raw scripting engine instance.
    /// Can be used to directly interact with an interpreter to use interfaces
    /// that bevy_scriptum does not provided adapters for.
    /// May not be implemented for runtimes which require the closure to pass
    /// thread boundary - use `with_engine_send_mut` then.
    fn with_engine_mut<T>(&mut self, f: impl FnOnce(&mut Self::RawEngine) -> T) -> T;

    /// Provides immutable reference to raw scripting engine instance.
    /// Can be used to directly interact with an interpreter to use interfaces
    /// that bevy_scriptum does not provided adapters for.
    /// May not be implemented for runtimes which require the closure to pass
    /// thread boundary - use `with_engine_send` then.
    fn with_engine<T>(&self, f: impl FnOnce(&Self::RawEngine) -> T) -> T;

    fn eval(
        &self,
        script: &Self::ScriptAsset,
        entity: Entity,
    ) -> Result<Self::ScriptData, ScriptingError>;

    /// Registers a new function within the scripting engine. Provided callback
    /// function will be called when the function with provided name gets called
    /// in script.
    fn register_fn(
        &mut self,
        name: String,
        arg_types: Vec<TypeId>,
        f: impl Fn(
            Self::CallContext,
            Vec<Self::Value>,
        ) -> Result<Promise<Self::CallContext, Self::Value>, ScriptingError>
        + Send
        + Sync
        + 'static,
    ) -> Result<(), ScriptingError>;

    /// Calls a function by name defined within the runtime in the context of the
    /// entity that haas been paassed. Can return a dynamically typed value
    /// that got returned from the function within a script.
    fn call_fn(
        &self,
        name: &str,
        script_data: &mut Self::ScriptData,
        entity: Entity,
        args: impl for<'a> FuncArgs<'a, Self::Value, Self> + Send + 'static,
    ) -> Result<Self::Value, ScriptingError>;

    /// Calls a function by value defined within the runtime in the context of the
    /// entity that haas been paassed. Can return a dynamically typed value
    /// that got returned from the function within a script.
    fn call_fn_from_value(
        &self,
        value: &Self::Value,
        context: &Self::CallContext,
        args: Vec<Self::Value>,
    ) -> Result<Self::Value, ScriptingError>;

    fn needs_rdynamic_linking() -> bool {
        false
    }
}

pub trait FuncArgs<'a, V, R: Runtime> {
    fn parse(self, engine: &'a R::RawEngine) -> Vec<V>;
}

/// An extension trait for [App] that allows to setup a scripting runtime `R`.
pub trait BuildScriptingRuntime {
    /// Returns a "runtime" type than can be used to setup scripting runtime(
    /// add scripting functions etc.).
    fn add_scripting<R: Runtime>(&mut self, f: impl Fn(ScriptingRuntimeBuilder<R>)) -> &mut Self;

    /// Returns a "runtime" type that can be used to add additional scripting functions from plugins etc.
    fn add_scripting_api<R: Runtime>(
        &mut self,
        f: impl Fn(ScriptingRuntimeBuilder<R>),
    ) -> &mut Self;
}

pub struct ScriptingRuntimeBuilder<'a, R: Runtime> {
    _phantom_data: PhantomData<R>,
    world: &'a mut World,
}

impl<'a, R: Runtime> ScriptingRuntimeBuilder<'a, R> {
    fn new(world: &'a mut World) -> Self {
        Self {
            _phantom_data: PhantomData,
            world,
        }
    }

    /// Registers a function for calling from within a script.
    /// Provided function needs to be a valid bevy system and its
    /// arguments and return value need to be convertible to runtime
    /// value types.
    pub fn add_function<In, Out, Marker>(
        self,
        name: String,
        fun: impl IntoCallbackSystem<R, In, Out, Marker>,
    ) -> Self
    where
        In: SystemInput,
    {
        let system = fun.into_callback_system(self.world);

        let mut callbacks_resource = self.world.resource_mut::<Callbacks<R>>();

        callbacks_resource.uninitialized_callbacks.push(Callback {
            name,
            system: Arc::new(Mutex::new(system)),
            calls: Arc::new(Mutex::new(vec![])),
        });

        self
    }
}

#[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone)]
pub enum ScriptSystems {
    Reload,
    InitCallbacks,
    ProcessNewScripts,
    ProcessCalls,
}

impl BuildScriptingRuntime for App {
    /// Adds a scripting runtime. Registers required bevy systems that take
    /// care of processing and running the scripts.
    fn add_scripting<R: Runtime>(&mut self, f: impl Fn(ScriptingRuntimeBuilder<R>)) -> &mut Self {
        #[cfg(debug_assertions)]
        if R::needs_rdynamic_linking() && !is_rdynamic_linking() {
            panic!(
                "Missing `-rdynamic`: symbol resolution failed.\n\
             It is needed by {:?}.\n\
             Please add `println!(\"cargo:rustc-link-arg=-rdynamic\");` to your build.rs\n\
             or set `RUSTFLAGS=\"-C link-arg=-rdynamic\"`.",
                std::any::type_name::<R>()
            );
        }

        // Insert the runtime schedule after Update
        self.world_mut()
            .resource_mut::<MainScheduleOrder>()
            .insert_after(Update, R::Schedule::default());

        self.register_asset_loader(ScriptLoader::<R::ScriptAsset>::default())
            .init_schedule(R::Schedule::default())
            .init_asset::<R::ScriptAsset>()
            .init_resource::<Callbacks<R>>()
            .insert_resource(R::default())
            .configure_sets(
                R::Schedule::default(),
                (
                    ScriptSystems::Reload,
                    ScriptSystems::InitCallbacks.after(ScriptSystems::Reload),
                    ScriptSystems::ProcessNewScripts.after(ScriptSystems::InitCallbacks),
                    ScriptSystems::ProcessCalls.after(ScriptSystems::ProcessNewScripts),
                ),
            )
            .add_systems(
                R::Schedule::default(),
                (
                    reload_scripts::<R>.in_set(ScriptSystems::Reload),
                    init_callbacks::<R>
                        .pipe(log_errors)
                        .in_set(ScriptSystems::InitCallbacks)
                        .after(ScriptSystems::Reload),
                    process_new_scripts::<R>
                        .pipe(log_errors)
                        .in_set(ScriptSystems::ProcessNewScripts)
                        .after(ScriptSystems::InitCallbacks),
                    process_calls::<R>
                        .pipe(log_errors)
                        .in_set(ScriptSystems::ProcessCalls)
                        .after(ScriptSystems::ProcessNewScripts),
                ),
            );

        let runtime = ScriptingRuntimeBuilder::<R>::new(self.world_mut());
        f(runtime);

        self
    }

    /// Adds a way to add additional accesspoints to the scripting runtime. For example from plugins to add
    /// for example additional lua functions to the runtime.
    ///
    /// Be careful with calling this though, make sure that the `add_scripting` call is already called before calling this function.
    fn add_scripting_api<R: Runtime>(
        &mut self,
        f: impl Fn(ScriptingRuntimeBuilder<R>),
    ) -> &mut Self {
        let runtime = ScriptingRuntimeBuilder::<R>::new(self.world_mut());

        f(runtime);

        self
    }
}

/// A resource that stores all the callbacks that were registered using [AddScriptFunctionAppExt::add_function].
#[derive(Resource)]
struct Callbacks<R: Runtime> {
    uninitialized_callbacks: Vec<Callback<R>>,
    callbacks: Mutex<Vec<Callback<R>>>,
}

impl<R: Runtime> Default for Callbacks<R> {
    fn default() -> Self {
        Self {
            uninitialized_callbacks: Default::default(),
            callbacks: Default::default(),
        }
    }
}

#[cfg(all(debug_assertions, unix))]
pub extern "C" fn is_rdynamic_linking() -> bool {
    unsafe {
        // Get a function pointer to itself
        let addr = is_rdynamic_linking as *const libc::c_void;
        let mut info: libc::Dl_info = std::mem::zeroed();

        // Try to resolve symbol info
        let result = libc::dladdr(addr, &mut info);

        result != 0 && !info.dli_sname.is_null()
    }
}

#[cfg(any(not(debug_assertions), not(unix)))]
pub extern "C" fn is_rdynamic_linking() -> bool {
    // On Windows or in release builds, return a default value
    true
}

pub mod prelude {
    pub use crate::{BuildScriptingRuntime as _, Runtime as _, Script};
}