├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── custom.md │ └── feature_request.md └── workflows │ ├── book.yml │ ├── deploy_book.yml │ └── rust.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── README.tpl ├── SECURITY.md ├── assets ├── examples │ ├── lua │ │ ├── call_function_from_rust.lua │ │ ├── current_entity.lua │ │ ├── custom_type.lua │ │ ├── ecs.lua │ │ ├── entity_variable.lua │ │ ├── function_params.lua │ │ ├── function_return_value.lua │ │ ├── hello_world.lua │ │ ├── multiple_plugins_plugin_a.lua │ │ ├── multiple_plugins_plugin_b.lua │ │ ├── promises.lua │ │ └── side_effects.lua │ ├── rhai │ │ ├── call_function_from_rust.rhai │ │ ├── current_entity.rhai │ │ ├── custom_type.rhai │ │ ├── ecs.rhai │ │ ├── entity_variable.rhai │ │ ├── function_params.rhai │ │ ├── function_return_value.rhai │ │ ├── hello_world.rhai │ │ ├── multiple_plugins_plugin_a.rhai │ │ ├── multiple_plugins_plugin_b.rhai │ │ ├── promises.rhai │ │ └── side_effects.rhai │ └── ruby │ │ ├── call_function_from_rust.rb │ │ ├── current_entity.rb │ │ ├── custom_type.rb │ │ ├── ecs.rb │ │ ├── entity_variable.rb │ │ ├── function_params.rb │ │ ├── function_return_value.rb │ │ ├── hello_world.rb │ │ ├── multiple_plugins_plugin_a.rb │ │ ├── multiple_plugins_plugin_b.rb │ │ ├── promises.rb │ │ └── side_effects.rb └── tests │ ├── lua │ ├── call_script_function_that_causes_runtime_error.lua │ ├── call_script_function_with_params.lua │ ├── entity_variable.lua │ ├── entity_variable_eval.lua │ ├── eval_that_causes_runtime_error.lua │ ├── pass_entity_from_script.lua │ ├── pass_vec3_from_script.lua │ ├── pass_vec3_to_script.lua │ ├── promise_runtime_error.lua │ ├── return_via_promise.lua │ ├── rust_function_gets_called_from_script.lua │ ├── rust_function_gets_called_from_script_with_multiple_params.lua │ ├── rust_function_gets_called_from_script_with_param.lua │ ├── script_function_gets_called_from_rust.lua │ ├── script_function_gets_called_from_rust_with_multiple_params.lua │ ├── script_function_gets_called_from_rust_with_single_param.lua │ └── side_effects.lua │ ├── rhai │ ├── call_script_function_that_causes_runtime_error.rhai │ ├── call_script_function_with_params.rhai │ ├── entity_variable.rhai │ ├── entity_variable_eval.rhai │ ├── eval_that_causes_runtime_error.rhai │ ├── pass_entity_from_script.rhai │ ├── pass_vec3_from_script.rhai │ ├── pass_vec3_to_script.rhai │ ├── promise_runtime_error.rhai │ ├── return_via_promise.rhai │ ├── rust_function_gets_called_from_script.rhai │ ├── rust_function_gets_called_from_script_with_multiple_params.rhai │ ├── rust_function_gets_called_from_script_with_param.rhai │ ├── script_function_gets_called_from_rust.rhai │ ├── script_function_gets_called_from_rust_with_multiple_params.rhai │ ├── script_function_gets_called_from_rust_with_single_param.rhai │ └── side_effects.rhai │ └── ruby │ ├── call_script_function_that_causes_runtime_error.rb │ ├── call_script_function_with_params.rb │ ├── entity_variable.rb │ ├── entity_variable_eval.rb │ ├── eval_that_causes_runtime_error.rb │ ├── pass_entity_from_script.rb │ ├── pass_vec3_from_script.rb │ ├── pass_vec3_to_script.rb │ ├── promise_runtime_error.rb │ ├── return_via_promise.rb │ ├── rust_function_gets_called_from_script.rb │ ├── rust_function_gets_called_from_script_with_multiple_params.rb │ ├── rust_function_gets_called_from_script_with_param.rb │ ├── script_function_gets_called_from_rust.rb │ ├── script_function_gets_called_from_rust_with_multiple_params.rb │ ├── script_function_gets_called_from_rust_with_single_param.rb │ └── side_effects.rb ├── book ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── book.toml ├── justfile └── src │ ├── SUMMARY.md │ ├── bevy_support_matrix.md │ ├── introduction.md │ ├── lib.rs │ ├── lua │ ├── builtin_types.md │ ├── builtin_variables.md │ ├── calling_rust_from_script.md │ ├── calling_script_from_rust.md │ ├── hello_world.md │ ├── installation.md │ ├── interacting_with_bevy.md │ ├── lua.md │ └── spawning_scripts.md │ ├── multiple_plugins.md │ ├── rhai │ ├── hello_world.md │ ├── installation.md │ └── rhai.md │ ├── ruby │ ├── builtin_types.md │ ├── calling_rust_from_script.md │ ├── calling_script_from_rust.md │ ├── hello_world.md │ ├── installation.md │ ├── interacting_with_bevy.md │ ├── ruby.md │ └── spawning_scripts.md │ ├── runtimes.md │ └── workflow │ ├── live_reload.md │ └── workflow.md ├── build.rs ├── demo.gif ├── examples ├── lua │ ├── call_function_from_rust.rs │ ├── current_entity.rs │ ├── custom_type.rs │ ├── ecs.rs │ ├── entity_variable.rs │ ├── function_params.rs │ ├── function_return_value.rs │ ├── hello_world.rs │ ├── multiple_plugins.rs │ ├── non_closure_system.rs │ ├── promises.rs │ └── side_effects.rs ├── rhai │ ├── call_function_from_rust.rs │ ├── current_entity.rs │ ├── custom_type.rs │ ├── ecs.rs │ ├── entity_variable.rs │ ├── function_params.rs │ ├── function_return_value.rs │ ├── hello_world.rs │ ├── multiple_plugins.rs │ ├── non_closure_system.rs │ ├── promises.rs │ └── side_effects.rs └── ruby │ ├── call_function_from_rust.rs │ ├── current_entity.rs │ ├── custom_type.rs │ ├── ecs.rs │ ├── entity_variable.rs │ ├── function_params.rs │ ├── function_return_value.rs │ ├── hello_world.rs │ ├── multiple_plugins.rs │ ├── promises.rs │ └── side_effects.rs ├── pull_request_template.md ├── src ├── assets.rs ├── callback.rs ├── components.rs ├── lib.rs ├── promise.rs ├── runtimes │ ├── lua.rs │ ├── mod.rs │ ├── rhai.rs │ └── ruby.rs └── systems.rs └── tests └── tests.rs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [jarkonik] 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/book.yml: -------------------------------------------------------------------------------- 1 | name: Book 2 | 3 | on: 4 | push: 5 | branches: ["main"] 6 | pull_request: 7 | branches: ["main"] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | with: 15 | fetch-depth: 0 16 | - name: Cache Ruby 17 | id: cache-ruby 18 | uses: actions/cache@v4 19 | with: 20 | path: rubies 21 | key: ${{ runner.os }}-ruby 22 | - name: Install Ruby 23 | if: steps.cache-ruby.outputs.cache-hit != 'true' 24 | env: 25 | CC: clang 26 | run: | 27 | url="https://cache.ruby-lang.org/pub/ruby/3.4/ruby-3.4.4.tar.gz" 28 | prefix=`pwd`/rubies/ruby-3.4 29 | mkdir rubies 30 | mkdir ruby_src 31 | curl -sSL $url | tar -xz 32 | cd ruby-3.4.4 33 | mkdir build 34 | cd build 35 | ../configure --without-shared --prefix=$prefix 36 | make install 37 | echo $prefix/bin >> $GITHUB_PATH 38 | - name: Add Ruby to PATH 39 | run: | 40 | prefix=`pwd`/rubies/ruby-3.4 41 | echo $prefix/bin >> $GITHUB_PATH 42 | - name: Install latest mdbook 43 | run: | 44 | tag=$(curl 'https://api.github.com/repos/rust-lang/mdbook/releases/latest' | jq -r '.tag_name') 45 | url="https://github.com/rust-lang/mdbook/releases/download/${tag}/mdbook-${tag}-x86_64-unknown-linux-gnu.tar.gz" 46 | mkdir mdbook 47 | curl -sSL $url | tar -xz --directory=./mdbook 48 | echo `pwd`/mdbook >> $GITHUB_PATH 49 | - name: Test Book 50 | run: | 51 | cd book 52 | export CARGO_MANIFEST_DIR=$(pwd) 53 | cargo build 54 | mdbook test -L target/debug/deps/ 55 | -------------------------------------------------------------------------------- /.github/workflows/deploy_book.yml: -------------------------------------------------------------------------------- 1 | name: Deploy book 2 | on: 3 | push: 4 | branches: 5 | - main 6 | 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | permissions: 11 | contents: write # To push a branch 12 | pages: write # To push to a GitHub Pages site 13 | id-token: write # To update the deployment status 14 | steps: 15 | - uses: actions/checkout@v4 16 | with: 17 | fetch-depth: 0 18 | - name: Install latest mdbook 19 | run: | 20 | tag=$(curl 'https://api.github.com/repos/rust-lang/mdbook/releases/latest' | jq -r '.tag_name') 21 | url="https://github.com/rust-lang/mdbook/releases/download/${tag}/mdbook-${tag}-x86_64-unknown-linux-gnu.tar.gz" 22 | mkdir mdbook 23 | curl -sSL $url | tar -xz --directory=./mdbook 24 | echo `pwd`/mdbook >> $GITHUB_PATH 25 | - name: Build Book 26 | run: | 27 | cd book 28 | mdbook build 29 | - name: Setup Pages 30 | uses: actions/configure-pages@v4 31 | - name: Upload artifact 32 | uses: actions/upload-pages-artifact@v3 33 | with: 34 | # Upload entire repository 35 | path: 'book/book' 36 | - name: Deploy to GitHub Pages 37 | id: deployment 38 | uses: actions/deploy-pages@v4 39 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: ["main"] 6 | pull_request: 7 | branches: ["main"] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | env: 16 | RUSTFLAGS: -D warnings 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Cache Ruby 20 | id: cache-ruby 21 | uses: actions/cache@v4 22 | with: 23 | path: rubies 24 | key: ${{ runner.os }}-ruby 25 | - name: Install Ruby 26 | if: steps.cache-ruby.outputs.cache-hit != 'true' 27 | env: 28 | CC: clang 29 | run: | 30 | url="https://cache.ruby-lang.org/pub/ruby/3.4/ruby-3.4.4.tar.gz" 31 | prefix=`pwd`/rubies/ruby-3.4 32 | mkdir rubies 33 | mkdir ruby_src 34 | curl -sSL $url | tar -xz 35 | cd ruby-3.4.4 36 | mkdir build 37 | cd build 38 | ../configure --without-shared --prefix=$prefix 39 | make install 40 | - name: Add Ruby to PATH 41 | run: | 42 | prefix=`pwd`/rubies/ruby-3.4 43 | echo $prefix/bin >> $GITHUB_PATH 44 | - name: Clippy 45 | run: cargo clippy --all-features --verbose -- -D warnings 46 | - name: Build 47 | run: cargo build --all-features --verbose 48 | - name: Run tests 49 | run: cargo test --all-features --verbose 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | .vscode 4 | .nvim.lua 5 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | yellow.egg4414@fastmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 1. Fork. 2 | 2. Create a pull request. 3 | 3. Make sure all automated checks pass. 4 | 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bevy_scriptum" 3 | authors = ["Jaroslaw Konik "] 4 | version = "0.9.1" 5 | edition = "2024" 6 | license = "MIT OR Apache-2.0" 7 | readme = "README.md" 8 | categories = ["game-development"] 9 | description = "Plugin for Bevy engine that allows you to write some of your game or application logic in a scripting language" 10 | repository = "https://github.com/jarkonik/bevy_scriptum" 11 | keywords = ["bevy", "lua", "scripting", "game", "script"] 12 | 13 | [features] 14 | lua = ["dep:mlua", "mlua/luajit"] 15 | rhai = ["dep:rhai"] 16 | ruby = ["dep:magnus", "dep:rb-sys"] 17 | 18 | [dependencies] 19 | bevy = { default-features = false, version = "0.16", features = ["bevy_asset", "bevy_log"] } 20 | serde = "1.0.162" 21 | rhai = { version = "1.14.0", features = [ 22 | "sync", 23 | "internals", 24 | "unchecked", 25 | ], optional = true } 26 | thiserror = "1.0.40" 27 | anyhow = "1.0.82" 28 | tracing = "0.1.40" 29 | mlua = { version = "0.9.8", features = [ 30 | "luajit", 31 | "vendored", 32 | "send", 33 | ], optional = true } 34 | magnus = { version = "0.7.1", optional = true } 35 | rb-sys = { version = "0.9", default-features = false, features = ["link-ruby", "ruby-static"], optional = true } 36 | crossbeam-channel = "0.5.15" 37 | libc = "0.2.172" 38 | 39 | [[example]] 40 | name = "call_function_from_rust_rhai" 41 | path = "examples/rhai/call_function_from_rust.rs" 42 | required-features = ["rhai"] 43 | 44 | [[example]] 45 | name = "current_entity_rhai" 46 | path = "examples/rhai/current_entity.rs" 47 | required-features = ["rhai"] 48 | 49 | [[example]] 50 | name = "custom_type_rhai" 51 | path = "examples/rhai/custom_type.rs" 52 | required-features = ["rhai"] 53 | 54 | [[example]] 55 | name = "ecs_rhai" 56 | path = "examples/rhai/ecs.rs" 57 | required-features = ["rhai"] 58 | 59 | [[example]] 60 | name = "entity_variable_rhai" 61 | path = "examples/rhai/entity_variable.rs" 62 | required-features = ["rhai"] 63 | 64 | [[example]] 65 | name = "function_params_rhai" 66 | path = "examples/rhai/function_params.rs" 67 | required-features = ["rhai"] 68 | 69 | [[example]] 70 | name = "hello_world_rhai" 71 | path = "examples/rhai/hello_world.rs" 72 | required-features = ["rhai"] 73 | 74 | [[example]] 75 | name = "multiple_plugins_rhai" 76 | path = "examples/rhai/multiple_plugins.rs" 77 | required-features = ["rhai"] 78 | 79 | [[example]] 80 | name = "non_closure_system_rhai" 81 | path = "examples/rhai/non_closure_system.rs" 82 | required-features = ["rhai"] 83 | 84 | [[example]] 85 | name = "promises_rhai" 86 | path = "examples/rhai/promises.rs" 87 | required-features = ["rhai"] 88 | 89 | [[example]] 90 | name = "side_effects_rhai" 91 | path = "examples/rhai/side_effects.rs" 92 | required-features = ["rhai"] 93 | 94 | [[example]] 95 | name = "function_return_value_rhai" 96 | path = "examples/rhai/function_return_value.rs" 97 | required-features = ["rhai"] 98 | 99 | [[example]] 100 | name = "call_function_from_rust_lua" 101 | path = "examples/lua/call_function_from_rust.rs" 102 | required-features = ["lua"] 103 | 104 | [[example]] 105 | name = "current_entity_lua" 106 | path = "examples/lua/current_entity.rs" 107 | required-features = ["lua"] 108 | 109 | [[example]] 110 | name = "custom_type_lua" 111 | path = "examples/lua/custom_type.rs" 112 | required-features = ["lua"] 113 | 114 | [[example]] 115 | name = "ecs_lua" 116 | path = "examples/lua/ecs.rs" 117 | required-features = ["lua"] 118 | 119 | [[example]] 120 | name = "entity_variable_lua" 121 | path = "examples/lua/entity_variable.rs" 122 | required-features = ["lua"] 123 | 124 | [[example]] 125 | name = "function_params_lua" 126 | path = "examples/lua/function_params.rs" 127 | required-features = ["lua"] 128 | 129 | [[example]] 130 | name = "hello_world_lua" 131 | path = "examples/lua/hello_world.rs" 132 | required-features = ["lua"] 133 | 134 | [[example]] 135 | name = "multiple_plugins_lua" 136 | path = "examples/lua/multiple_plugins.rs" 137 | required-features = ["lua"] 138 | 139 | [[example]] 140 | name = "non_closure_system_lua" 141 | path = "examples/lua/non_closure_system.rs" 142 | required-features = ["lua"] 143 | 144 | [[example]] 145 | name = "promises_lua" 146 | path = "examples/lua/promises.rs" 147 | required-features = ["lua"] 148 | 149 | [[example]] 150 | name = "side_effects_lua" 151 | path = "examples/lua/side_effects.rs" 152 | required-features = ["lua"] 153 | 154 | [[example]] 155 | name = "function_return_value_lua" 156 | path = "examples/lua/function_return_value.rs" 157 | required-features = ["lua"] 158 | 159 | [[example]] 160 | name = "call_function_from_rust_ruby" 161 | path = "examples/ruby/call_function_from_rust.rs" 162 | required-features = ["ruby"] 163 | 164 | [[example]] 165 | name = "current_entity_ruby" 166 | path = "examples/ruby/current_entity.rs" 167 | required-features = ["ruby"] 168 | 169 | [[example]] 170 | name = "custom_type_ruby" 171 | path = "examples/ruby/custom_type.rs" 172 | required-features = ["ruby"] 173 | 174 | [[example]] 175 | name = "ecs_ruby" 176 | path = "examples/ruby/ecs.rs" 177 | required-features = ["ruby"] 178 | 179 | [[example]] 180 | name = "entity_variable_ruby" 181 | path = "examples/ruby/entity_variable.rs" 182 | required-features = ["ruby"] 183 | 184 | [[example]] 185 | name = "function_params_ruby" 186 | path = "examples/ruby/function_params.rs" 187 | required-features = ["ruby"] 188 | 189 | [[example]] 190 | name = "function_return_value_ruby" 191 | path = "examples/ruby/function_return_value.rs" 192 | required-features = ["ruby"] 193 | 194 | [[example]] 195 | name = "hello_world_ruby" 196 | path = "examples/ruby/hello_world.rs" 197 | required-features = ["ruby"] 198 | 199 | [[example]] 200 | name = "multiple_plugins_ruby" 201 | path = "examples/ruby/multiple_plugins.rs" 202 | required-features = ["ruby"] 203 | 204 | [[example]] 205 | name = "promises_ruby" 206 | path = "examples/ruby/promises.rs" 207 | required-features = ["ruby"] 208 | 209 | [[example]] 210 | name = "side_effects_ruby" 211 | path = "examples/ruby/side_effects.rs" 212 | required-features = ["ruby"] 213 | 214 | [dev-dependencies] 215 | tracing-subscriber = "0.3.18" 216 | mlua = { version = "0.9.8", features = ["luajit", "vendored", "send"] } 217 | rhai = { version = "1.14.0", features = ["sync", "internals", "unchecked"] } 218 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bevy_scriptum 📜 2 | 3 | ![demo](demo.gif) 4 | 5 | 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. 6 | ### Supported scripting languages/runtimes 7 | 8 | | language/runtime | cargo feature | documentation chapter | 9 | | ------------------------------------------ | ------------- | --------------------------------------------------------------- | 10 | | 🌙 LuaJIT | `lua` | [link](https://jarkonik.github.io/bevy_scriptum/lua/lua.html) | 11 | | 🌾 Rhai | `rhai` | [link](https://jarkonik.github.io/bevy_scriptum/rhai/rhai.html) | 12 | | 💎 Ruby(currently only supported on Linux) | `ruby` | [link](https://jarkonik.github.io/bevy_scriptum/ruby/ruby.html) | 13 | 14 | Documentation book is available [here](https://jarkonik.github.io/bevy_scriptum/) 📖 15 | 16 | Full API docs are available at [docs.rs](https://docs.rs/bevy_scriptum/latest/bevy_scriptum/) 🧑‍💻 17 | 18 | bevy_scriptum's main advantages include: 19 | - low-boilerplate 20 | - easy to use 21 | - asynchronicity with a promise-based API 22 | - flexibility 23 | - hot-reloading 24 | 25 | 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. 26 | 27 | All you need to do is register callbacks on your Bevy app like this: 28 | ```rust 29 | use bevy::prelude::*; 30 | use bevy_scriptum::prelude::*; 31 | use bevy_scriptum::runtimes::lua::prelude::*; 32 | 33 | App::new() 34 | .add_plugins(DefaultPlugins) 35 | .add_scripting::(|runtime| { 36 | runtime.add_function(String::from("hello_bevy"), || { 37 | println!("hello bevy, called from script"); 38 | }); 39 | }) 40 | .run(); 41 | ``` 42 | And you can call them in your scripts like this: 43 | ```lua 44 | hello_bevy() 45 | ``` 46 | 47 | 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: 48 | 49 | ```rust 50 | use bevy::prelude::*; 51 | use bevy_scriptum::prelude::*; 52 | use bevy_scriptum::runtimes::lua::prelude::*; 53 | 54 | #[derive(Component)] 55 | struct Player; 56 | 57 | App::new() 58 | .add_plugins(DefaultPlugins) 59 | .add_scripting::(|runtime| { 60 | runtime.add_function( 61 | String::from("print_player_names"), 62 | |players: Query<&Name, With>| { 63 | for player in &players { 64 | println!("player name: {}", player); 65 | } 66 | }, 67 | ); 68 | }) 69 | .run(); 70 | ``` 71 | 72 | You can also pass arguments to your callback functions, just like you would in a regular Bevy system - using `In` structs with tuples: 73 | ```rust 74 | use bevy::prelude::*; 75 | use bevy_scriptum::prelude::*; 76 | use bevy_scriptum::runtimes::lua::prelude::*; 77 | 78 | App::new() 79 | .add_plugins(DefaultPlugins) 80 | .add_scripting::(|runtime| { 81 | runtime.add_function( 82 | String::from("fun_with_string_param"), 83 | |In((x,)): In<(String,)>| { 84 | println!("called with string: '{}'", x); 85 | }, 86 | ); 87 | }) 88 | .run(); 89 | ``` 90 | which you can then call in your script like this: 91 | ```lua 92 | fun_with_string_param("Hello world!") 93 | ``` 94 | 95 | ### Usage 96 | 97 | Add the following to your `Cargo.toml`: 98 | 99 | ```toml 100 | [dependencies] 101 | bevy_scriptum = { version = "0.9", features = ["lua"] } 102 | ``` 103 | 104 | or execute `cargo add bevy_scriptum --features lua` from your project directory. 105 | 106 | You can now start exposing functions to the scripting language. For example, you can expose a function that prints a message to the console: 107 | 108 | ```rust 109 | use bevy::prelude::*; 110 | use bevy_scriptum::prelude::*; 111 | use bevy_scriptum::runtimes::lua::prelude::*; 112 | 113 | App::new() 114 | .add_plugins(DefaultPlugins) 115 | .add_scripting::(|runtime| { 116 | runtime.add_function( 117 | String::from("my_print"), 118 | |In((x,)): In<(String,)>| { 119 | println!("my_print: '{}'", x); 120 | }, 121 | ); 122 | }) 123 | .run(); 124 | ``` 125 | 126 | Then you can create a script file in `assets` directory called `script.lua` that calls this function: 127 | 128 | ```lua 129 | my_print("Hello world!") 130 | ``` 131 | 132 | And spawn an entity with attached `Script` component with a handle to a script source file: 133 | 134 | ```rust 135 | use bevy::prelude::*; 136 | use bevy_scriptum::prelude::*; 137 | use bevy_scriptum::runtimes::lua::prelude::*; 138 | 139 | App::new() 140 | .add_plugins(DefaultPlugins) 141 | .add_scripting::(|runtime| { 142 | runtime.add_function( 143 | String::from("my_print"), 144 | |In((x,)): In<(String,)>| { 145 | println!("my_print: '{}'", x); 146 | }, 147 | ); 148 | }) 149 | .add_systems(Startup,|mut commands: Commands, asset_server: Res| { 150 | commands.spawn(Script::::new(asset_server.load("script.lua"))); 151 | }) 152 | .run(); 153 | ``` 154 | 155 | You should then see `my_print: 'Hello world!'` printed in your console. 156 | 157 | ### Provided examples 158 | 159 | You can also try running provided examples by cloning this repository and running `cargo run --example _`. For example: 160 | 161 | ```bash 162 | cargo run --example hello_world_lua 163 | ``` 164 | The examples live in `examples` directory and their corresponding scripts live in `assets/examples` directory within the repository. 165 | 166 | ### Bevy compatibility 167 | 168 | | bevy version | bevy_scriptum version | 169 | |--------------|-----------------------| 170 | | 0.16 | 0.8-0.9 | 171 | | 0.15 | 0.7 | 172 | | 0.14 | 0.6 | 173 | | 0.13 | 0.4-0.5 | 174 | | 0.12 | 0.3 | 175 | | 0.11 | 0.2 | 176 | | 0.10 | 0.1 | 177 | 178 | ### Promises - getting return values from scripts 179 | 180 | 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: 181 | 182 | ```lua 183 | get_player_name():and_then(function(name) 184 | print(name) 185 | end) 186 | ``` 187 | which will print out `John` when used with following exposed function: 188 | 189 | ```rust 190 | use bevy::prelude::*; 191 | use bevy_scriptum::prelude::*; 192 | use bevy_scriptum::runtimes::lua::prelude::*; 193 | 194 | App::new() 195 | .add_plugins(DefaultPlugins) 196 | .add_scripting::(|runtime| { 197 | runtime.add_function(String::from("get_player_name"), || String::from("John")); 198 | }); 199 | ```` 200 | 201 | ## Access entity from script 202 | 203 | A variable called `entity` is automatically available to all scripts - it represents bevy entity that the `Script` component is attached to. 204 | It exposes `index` property that returns bevy entity index. 205 | It is useful for accessing entity's components from scripts. 206 | It can be used in the following way: 207 | ```lua 208 | print("Current entity index: " .. entity.index) 209 | ``` 210 | 211 | `entity` variable is currently not available within promise callbacks. 212 | 213 | ### Contributing 214 | 215 | Contributions are welcome! Feel free to open an issue or submit a pull request. 216 | 217 | ### License 218 | 219 | bevy_scriptum is licensed under either of the following, at your option: 220 | 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) 221 | -------------------------------------------------------------------------------- /README.tpl: -------------------------------------------------------------------------------- 1 | # {{crate}} 📜 2 | 3 | {{readme}} 4 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Use this section to tell people about which versions of your project are 6 | currently being supported with security updates. 7 | 8 | | Version | Supported | 9 | | ------- | ------------------ | 10 | | 0.9 | :white_check_mark: | 11 | 12 | ## Reporting a Vulnerability 13 | 14 | Vulnerabilities should be reported at konikjar@gmail.com 15 | -------------------------------------------------------------------------------- /assets/examples/lua/call_function_from_rust.lua: -------------------------------------------------------------------------------- 1 | local my_state = { 2 | iterations = 0, 3 | } 4 | 5 | function on_update() 6 | my_state.iterations = my_state.iterations + 1; 7 | print("on_update called " .. my_state.iterations .. " times") 8 | 9 | if my_state.iterations >= 10 then 10 | print("calling quit"); 11 | quit(); 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /assets/examples/lua/current_entity.lua: -------------------------------------------------------------------------------- 1 | -- entity is a global variable that is set to the entity that is currently being processed, 2 | -- it is automatically available in all scripts 3 | 4 | -- get name of the entity 5 | get_name(entity):and_then(function(name) 6 | print(name) 7 | end) 8 | -------------------------------------------------------------------------------- /assets/examples/lua/custom_type.lua: -------------------------------------------------------------------------------- 1 | -- Create a new instance of MyType 2 | my_type = MyType(); 3 | -- Call registered method 4 | print(my_type:my_method()) 5 | -------------------------------------------------------------------------------- /assets/examples/lua/ecs.lua: -------------------------------------------------------------------------------- 1 | print_player_names() 2 | -------------------------------------------------------------------------------- /assets/examples/lua/entity_variable.lua: -------------------------------------------------------------------------------- 1 | -- entity is a global variable that is set to the entity that is currently being processed, 2 | -- it is automatically available in all scripts 3 | print("Current entity index: " .. entity.index) 4 | -------------------------------------------------------------------------------- /assets/examples/lua/function_params.lua: -------------------------------------------------------------------------------- 1 | fun_with_string_param("hello") 2 | fun_with_i64_param(5) 3 | fun_with_multiple_params(5, "hello") 4 | fun_with_i64_and_array_param(5, { 1, 2, "third element" }) 5 | -------------------------------------------------------------------------------- /assets/examples/lua/function_return_value.lua: -------------------------------------------------------------------------------- 1 | function get_value() 2 | return 42 3 | end 4 | -------------------------------------------------------------------------------- /assets/examples/lua/hello_world.lua: -------------------------------------------------------------------------------- 1 | hello_bevy(); 2 | -------------------------------------------------------------------------------- /assets/examples/lua/multiple_plugins_plugin_a.lua: -------------------------------------------------------------------------------- 1 | hello_from_plugin_a() -------------------------------------------------------------------------------- /assets/examples/lua/multiple_plugins_plugin_b.lua: -------------------------------------------------------------------------------- 1 | hello_from_plugin_b_with_parameters("hello", 42) -------------------------------------------------------------------------------- /assets/examples/lua/promises.lua: -------------------------------------------------------------------------------- 1 | get_player_name():and_then(function(name) 2 | print(name) 3 | end); 4 | -------------------------------------------------------------------------------- /assets/examples/lua/side_effects.lua: -------------------------------------------------------------------------------- 1 | spawn_entity(); 2 | -------------------------------------------------------------------------------- /assets/examples/rhai/call_function_from_rust.rhai: -------------------------------------------------------------------------------- 1 | let my_state = #{ 2 | iterations: 0, 3 | }; 4 | 5 | fn on_update() { 6 | my_state.iterations += 1; 7 | print("on_update called " + my_state.iterations + " times"); 8 | 9 | if (my_state.iterations >= 10) { 10 | print("calling quit"); 11 | quit(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /assets/examples/rhai/current_entity.rhai: -------------------------------------------------------------------------------- 1 | // entity is a global variable that is set to the entity that is currently being processed, 2 | // it is automatically available in all scripts 3 | 4 | // get name of the entity using registered function 5 | get_name(entity).then(|name| { 6 | print(name); 7 | }); 8 | 9 | // Rhai also supports calling functions with the dot operator 10 | entity.get_name().then(|name| { 11 | print(name); 12 | }) 13 | 14 | -------------------------------------------------------------------------------- /assets/examples/rhai/custom_type.rhai: -------------------------------------------------------------------------------- 1 | // Create a new instance of MyType 2 | let my_type = new_my_type(); 3 | // Call registered method 4 | print(my_type.my_method()); 5 | 6 | -------------------------------------------------------------------------------- /assets/examples/rhai/ecs.rhai: -------------------------------------------------------------------------------- 1 | print_player_names(); 2 | -------------------------------------------------------------------------------- /assets/examples/rhai/entity_variable.rhai: -------------------------------------------------------------------------------- 1 | // entity is a global variable that is set to the entity that is currently being processed, 2 | // it is automatically available in all scripts 3 | print("Current entity index: " + entity.index); 4 | -------------------------------------------------------------------------------- /assets/examples/rhai/function_params.rhai: -------------------------------------------------------------------------------- 1 | fun_with_string_param("hello"); 2 | fun_with_i64_param(5); 3 | fun_with_multiple_params(5, "hello"); 4 | fun_with_i64_and_array_param(5, [1, 2, "third element"]); 5 | -------------------------------------------------------------------------------- /assets/examples/rhai/function_return_value.rhai: -------------------------------------------------------------------------------- 1 | fn get_value() { 2 | 42 3 | } 4 | -------------------------------------------------------------------------------- /assets/examples/rhai/hello_world.rhai: -------------------------------------------------------------------------------- 1 | hello_bevy(); 2 | -------------------------------------------------------------------------------- /assets/examples/rhai/multiple_plugins_plugin_a.rhai: -------------------------------------------------------------------------------- 1 | hello_from_plugin_a(); -------------------------------------------------------------------------------- /assets/examples/rhai/multiple_plugins_plugin_b.rhai: -------------------------------------------------------------------------------- 1 | hello_from_plugin_b_with_parameters("hello", 42); -------------------------------------------------------------------------------- /assets/examples/rhai/promises.rhai: -------------------------------------------------------------------------------- 1 | get_player_name().then(|name| { 2 | print(name); 3 | }); 4 | -------------------------------------------------------------------------------- /assets/examples/rhai/side_effects.rhai: -------------------------------------------------------------------------------- 1 | spawn_entity(); 2 | -------------------------------------------------------------------------------- /assets/examples/ruby/call_function_from_rust.rb: -------------------------------------------------------------------------------- 1 | $my_state = { 2 | iterations: 0, 3 | } 4 | 5 | def on_update 6 | $my_state[:iterations] += 1 7 | puts("on_update called #{$my_state[:iterations]} times") 8 | 9 | if $my_state[:iterations] >= 10 10 | print("calling quit"); 11 | quit() 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /assets/examples/ruby/current_entity.rb: -------------------------------------------------------------------------------- 1 | get_name(Bevy::Entity.current).and_then do |name| 2 | puts(name) 3 | end 4 | -------------------------------------------------------------------------------- /assets/examples/ruby/custom_type.rb: -------------------------------------------------------------------------------- 1 | # Create a new instance of MyType 2 | my_type = MyType.new() 3 | # Call registered method 4 | puts(my_type.my_method) 5 | -------------------------------------------------------------------------------- /assets/examples/ruby/ecs.rb: -------------------------------------------------------------------------------- 1 | print_player_names 2 | -------------------------------------------------------------------------------- /assets/examples/ruby/entity_variable.rb: -------------------------------------------------------------------------------- 1 | # Bevy::Entity.current can be used to access the entity that is currently being processed 2 | puts("Current entity index: #{Bevy::Entity.current.index}") 3 | -------------------------------------------------------------------------------- /assets/examples/ruby/function_params.rb: -------------------------------------------------------------------------------- 1 | fun_with_string_param("hello") 2 | fun_with_i64_param(5) 3 | fun_with_multiple_params(5, "hello") 4 | fun_with_i64_and_array_param(5, [1, 2, "third element"]) 5 | -------------------------------------------------------------------------------- /assets/examples/ruby/function_return_value.rb: -------------------------------------------------------------------------------- 1 | def get_value 2 | 42 3 | end 4 | -------------------------------------------------------------------------------- /assets/examples/ruby/hello_world.rb: -------------------------------------------------------------------------------- 1 | hello_bevy() 2 | -------------------------------------------------------------------------------- /assets/examples/ruby/multiple_plugins_plugin_a.rb: -------------------------------------------------------------------------------- 1 | hello_from_plugin_a 2 | -------------------------------------------------------------------------------- /assets/examples/ruby/multiple_plugins_plugin_b.rb: -------------------------------------------------------------------------------- 1 | hello_from_plugin_b_with_parameters("hello", 42) 2 | -------------------------------------------------------------------------------- /assets/examples/ruby/promises.rb: -------------------------------------------------------------------------------- 1 | get_player_name.and_then do |name| 2 | puts name 3 | end 4 | -------------------------------------------------------------------------------- /assets/examples/ruby/side_effects.rb: -------------------------------------------------------------------------------- 1 | spawn_entity() 2 | -------------------------------------------------------------------------------- /assets/tests/lua/call_script_function_that_causes_runtime_error.lua: -------------------------------------------------------------------------------- 1 | function test_func() 2 | print("abc" + 5) 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/lua/call_script_function_with_params.lua: -------------------------------------------------------------------------------- 1 | State = { 2 | called_with = nil 3 | } 4 | 5 | function test_func(x) 6 | called_with = x 7 | end 8 | -------------------------------------------------------------------------------- /assets/tests/lua/entity_variable.lua: -------------------------------------------------------------------------------- 1 | function test_func() 2 | rust_func(entity.index) 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/lua/entity_variable_eval.lua: -------------------------------------------------------------------------------- 1 | index = entity.index 2 | 3 | function test_func() 4 | rust_func(index) 5 | end 6 | -------------------------------------------------------------------------------- /assets/tests/lua/eval_that_causes_runtime_error.lua: -------------------------------------------------------------------------------- 1 | mark_called() 2 | error() 3 | -------------------------------------------------------------------------------- /assets/tests/lua/pass_entity_from_script.lua: -------------------------------------------------------------------------------- 1 | function test_func() 2 | rust_func(entity) 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/lua/pass_vec3_from_script.lua: -------------------------------------------------------------------------------- 1 | function test_func() 2 | rust_func(Vec3(1.5, 2.5, -3.5)) 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/lua/pass_vec3_to_script.lua: -------------------------------------------------------------------------------- 1 | function test_func(vec3) 2 | assert(vec3.x == 1.5) 3 | assert(vec3.y == 2.5) 4 | assert(vec3.z == -3.5) 5 | mark_success() 6 | end 7 | -------------------------------------------------------------------------------- /assets/tests/lua/promise_runtime_error.lua: -------------------------------------------------------------------------------- 1 | function test_func() 2 | rust_func():and_then(function(x) 3 | print("abc" + 5) 4 | end) 5 | end 6 | -------------------------------------------------------------------------------- /assets/tests/lua/return_via_promise.lua: -------------------------------------------------------------------------------- 1 | State = { 2 | x = nil 3 | } 4 | 5 | function test_func() 6 | rust_func():and_then(function(x) 7 | State.x = x 8 | end) 9 | end 10 | -------------------------------------------------------------------------------- /assets/tests/lua/rust_function_gets_called_from_script.lua: -------------------------------------------------------------------------------- 1 | function test_func() 2 | rust_func() 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/lua/rust_function_gets_called_from_script_with_multiple_params.lua: -------------------------------------------------------------------------------- 1 | function test_func() 2 | rust_func(5, "test") 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/lua/rust_function_gets_called_from_script_with_param.lua: -------------------------------------------------------------------------------- 1 | function test_func() 2 | rust_func(5) 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/lua/script_function_gets_called_from_rust.lua: -------------------------------------------------------------------------------- 1 | State = { 2 | times_called = 0 3 | } 4 | 5 | function test_func() 6 | State.times_called = State.times_called + 1; 7 | end 8 | -------------------------------------------------------------------------------- /assets/tests/lua/script_function_gets_called_from_rust_with_multiple_params.lua: -------------------------------------------------------------------------------- 1 | State = { 2 | a_value = nil, 3 | b_value = nil 4 | } 5 | 6 | function test_func(a, b) 7 | State.a_value = a 8 | State.b_value = b 9 | end 10 | -------------------------------------------------------------------------------- /assets/tests/lua/script_function_gets_called_from_rust_with_single_param.lua: -------------------------------------------------------------------------------- 1 | State = { 2 | a_value = nil 3 | } 4 | 5 | function test_func(a) 6 | State.a_value = a 7 | end 8 | -------------------------------------------------------------------------------- /assets/tests/lua/side_effects.lua: -------------------------------------------------------------------------------- 1 | function test_func() 2 | spawn_entity() 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/rhai/call_script_function_that_causes_runtime_error.rhai: -------------------------------------------------------------------------------- 1 | fn test_func() { 2 | print("abc" * 5) 3 | } 4 | -------------------------------------------------------------------------------- /assets/tests/rhai/call_script_function_with_params.rhai: -------------------------------------------------------------------------------- 1 | fn test_func(x) { 2 | } 3 | -------------------------------------------------------------------------------- /assets/tests/rhai/entity_variable.rhai: -------------------------------------------------------------------------------- 1 | fn test_func() { 2 | rust_func(entity.index); 3 | } 4 | -------------------------------------------------------------------------------- /assets/tests/rhai/entity_variable_eval.rhai: -------------------------------------------------------------------------------- 1 | let index = entity.index; 2 | 3 | fn test_func() { 4 | rust_func(index); 5 | } 6 | -------------------------------------------------------------------------------- /assets/tests/rhai/eval_that_causes_runtime_error.rhai: -------------------------------------------------------------------------------- 1 | mark_called(); 2 | throw(); 3 | -------------------------------------------------------------------------------- /assets/tests/rhai/pass_entity_from_script.rhai: -------------------------------------------------------------------------------- 1 | fn test_func() { 2 | rust_func(entity); 3 | } 4 | -------------------------------------------------------------------------------- /assets/tests/rhai/pass_vec3_from_script.rhai: -------------------------------------------------------------------------------- 1 | fn test_func() { 2 | rust_func(new_vec3(1.5, 2.5, -3.5)); 3 | } 4 | -------------------------------------------------------------------------------- /assets/tests/rhai/pass_vec3_to_script.rhai: -------------------------------------------------------------------------------- 1 | fn test_func(vec3) { 2 | if type_of(vec3) != "Vec3" { throw() } 3 | if vec3.x != 1.5 { throw() } 4 | if vec3.y != 2.5 { throw() } 5 | if vec3.z != -3.5 { throw() } 6 | mark_success(); 7 | } 8 | -------------------------------------------------------------------------------- /assets/tests/rhai/promise_runtime_error.rhai: -------------------------------------------------------------------------------- 1 | fn test_func() { 2 | rust_func().then(|x| { 3 | print("abc" * 5) 4 | }) 5 | } 6 | -------------------------------------------------------------------------------- /assets/tests/rhai/return_via_promise.rhai: -------------------------------------------------------------------------------- 1 | let state = #{ 2 | x: 0 3 | }; 4 | 5 | fn test_func() { 6 | rust_func().then(|x| { 7 | state.x = x; 8 | }) 9 | } 10 | -------------------------------------------------------------------------------- /assets/tests/rhai/rust_function_gets_called_from_script.rhai: -------------------------------------------------------------------------------- 1 | fn test_func() { 2 | rust_func(); 3 | } 4 | -------------------------------------------------------------------------------- /assets/tests/rhai/rust_function_gets_called_from_script_with_multiple_params.rhai: -------------------------------------------------------------------------------- 1 | fn test_func() { 2 | rust_func(5, "test"); 3 | } 4 | -------------------------------------------------------------------------------- /assets/tests/rhai/rust_function_gets_called_from_script_with_param.rhai: -------------------------------------------------------------------------------- 1 | fn test_func() { 2 | rust_func(5); 3 | } 4 | -------------------------------------------------------------------------------- /assets/tests/rhai/script_function_gets_called_from_rust.rhai: -------------------------------------------------------------------------------- 1 | let state = #{ 2 | times_called: 0 3 | }; 4 | 5 | fn test_func() { 6 | state.times_called += 1; 7 | } 8 | -------------------------------------------------------------------------------- /assets/tests/rhai/script_function_gets_called_from_rust_with_multiple_params.rhai: -------------------------------------------------------------------------------- 1 | let state = #{ 2 | a_value: (), 3 | b_value: () 4 | }; 5 | 6 | fn test_func(a, b) { 7 | state.a_value = a; 8 | state.b_value = b; 9 | } 10 | -------------------------------------------------------------------------------- /assets/tests/rhai/script_function_gets_called_from_rust_with_single_param.rhai: -------------------------------------------------------------------------------- 1 | let state = #{ 2 | a_value: () 3 | }; 4 | 5 | fn test_func(a) { 6 | state.a_value = a 7 | } 8 | -------------------------------------------------------------------------------- /assets/tests/rhai/side_effects.rhai: -------------------------------------------------------------------------------- 1 | fn test_func() { 2 | spawn_entity() 3 | } 4 | -------------------------------------------------------------------------------- /assets/tests/ruby/call_script_function_that_causes_runtime_error.rb: -------------------------------------------------------------------------------- 1 | def test_func 2 | raise 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/ruby/call_script_function_with_params.rb: -------------------------------------------------------------------------------- 1 | $state = { 2 | 'called_with' => nil 3 | } 4 | 5 | def test_func(val) 6 | $state['called_with'] = val 7 | end 8 | -------------------------------------------------------------------------------- /assets/tests/ruby/entity_variable.rb: -------------------------------------------------------------------------------- 1 | def test_func 2 | rust_func(Bevy::Entity.current.index) 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/ruby/entity_variable_eval.rb: -------------------------------------------------------------------------------- 1 | $index = Bevy::Entity.current.index 2 | 3 | def test_func 4 | rust_func($index) 5 | end 6 | -------------------------------------------------------------------------------- /assets/tests/ruby/eval_that_causes_runtime_error.rb: -------------------------------------------------------------------------------- 1 | mark_called 2 | raise 3 | -------------------------------------------------------------------------------- /assets/tests/ruby/pass_entity_from_script.rb: -------------------------------------------------------------------------------- 1 | def test_func 2 | rust_func(Bevy::Entity.current) 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/ruby/pass_vec3_from_script.rb: -------------------------------------------------------------------------------- 1 | def test_func 2 | rust_func(Bevy::Vec3.new(1.5, 2.5, -3.5)) 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/ruby/pass_vec3_to_script.rb: -------------------------------------------------------------------------------- 1 | def test_func(vec3) 2 | raise unless vec3.is_a?(Bevy::Vec3) 3 | raise unless vec3.x == 1.5 4 | raise unless vec3.y == 2.5 5 | raise unless vec3.z == -3.5 6 | mark_success 7 | end 8 | -------------------------------------------------------------------------------- /assets/tests/ruby/promise_runtime_error.rb: -------------------------------------------------------------------------------- 1 | def test_func 2 | rust_func.and_then do |x| 3 | raise 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /assets/tests/ruby/return_via_promise.rb: -------------------------------------------------------------------------------- 1 | $state = { 2 | 'x' => nil 3 | } 4 | 5 | def test_func 6 | rust_func.and_then do |x| 7 | $state['x'] = x 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /assets/tests/ruby/rust_function_gets_called_from_script.rb: -------------------------------------------------------------------------------- 1 | def test_func 2 | rust_func 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/ruby/rust_function_gets_called_from_script_with_multiple_params.rb: -------------------------------------------------------------------------------- 1 | def test_func 2 | rust_func(5, 'test') 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/ruby/rust_function_gets_called_from_script_with_param.rb: -------------------------------------------------------------------------------- 1 | def test_func 2 | rust_func(5) 3 | end 4 | -------------------------------------------------------------------------------- /assets/tests/ruby/script_function_gets_called_from_rust.rb: -------------------------------------------------------------------------------- 1 | $state = { 2 | 'times_called' => 0 3 | } 4 | 5 | def test_func 6 | $state['times_called'] += 1 7 | end 8 | -------------------------------------------------------------------------------- /assets/tests/ruby/script_function_gets_called_from_rust_with_multiple_params.rb: -------------------------------------------------------------------------------- 1 | $state = { 2 | 'a_value' => nil, 3 | 'b_value' => nil 4 | } 5 | 6 | def test_func(a, b) 7 | $state['a_value'] = a 8 | $state['b_value'] = b 9 | end 10 | -------------------------------------------------------------------------------- /assets/tests/ruby/script_function_gets_called_from_rust_with_single_param.rb: -------------------------------------------------------------------------------- 1 | $state = { 2 | 'a_value' => nil 3 | } 4 | 5 | def test_func(a) 6 | $state['a_value'] = a 7 | end 8 | -------------------------------------------------------------------------------- /assets/tests/ruby/side_effects.rb: -------------------------------------------------------------------------------- 1 | def test_func 2 | spawn_entity 3 | end 4 | -------------------------------------------------------------------------------- /book/.gitignore: -------------------------------------------------------------------------------- 1 | book 2 | doctest_cache 3 | target 4 | -------------------------------------------------------------------------------- /book/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bevy_scriptum_book" 3 | publish = false 4 | edition = "2024" 5 | 6 | [dependencies] 7 | bevy_scriptum = { path = "../", features = ["ruby", "lua", "rhai"] } 8 | -------------------------------------------------------------------------------- /book/book.toml: -------------------------------------------------------------------------------- 1 | [book] 2 | authors = ["Jaroslaw Konik"] 3 | language = "en" 4 | multilingual = false 5 | src = "src" 6 | title = "bevy_scriptum" 7 | -------------------------------------------------------------------------------- /book/justfile: -------------------------------------------------------------------------------- 1 | export CARGO_MANIFEST_DIR := `pwd` 2 | 3 | build-deps: 4 | cargo clean && cargo build 5 | 6 | _test: 7 | mdbook test -L target/debug/deps/ 8 | 9 | test: build-deps _test 10 | 11 | test-watch: build-deps 12 | watchexec --exts md -r just _test 13 | 14 | serve: 15 | mdbook serve 16 | -------------------------------------------------------------------------------- /book/src/SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | - [Introduction](./introduction.md) 4 | - [Runtimes](./runtimes.md) 5 | - [Lua](./lua/lua.md) 6 | - [Installation](./lua/installation.md) 7 | - [Hello World](./lua/hello_world.md) 8 | - [Spawning scripts](./lua/spawning_scripts.md) 9 | - [Calling Rust from Lua](./lua/calling_rust_from_script.md) 10 | - [Calling Lua from Rust](./lua/calling_script_from_rust.md) 11 | - [Interacting with bevy in callbacks](./lua/interacting_with_bevy.md) 12 | - [Builtin types](./lua/builtin_types.md) 13 | - [Builtin variables](./lua/builtin_variables.md) 14 | - [Ruby](./ruby/ruby.md) 15 | - [Installation](./ruby/installation.md) 16 | - [Hello World](./ruby/hello_world.md) 17 | - [Spawning scripts](./ruby/spawning_scripts.md) 18 | - [Calling Rust from Ruby](./ruby/calling_rust_from_script.md) 19 | - [Calling Ruby from Rust](./ruby/calling_script_from_rust.md) 20 | - [Interacting with bevy in callbacks](./ruby/interacting_with_bevy.md) 21 | - [Builtin types](./ruby/builtin_types.md) 22 | - [Rhai](./rhai/rhai.md) 23 | - [Installation](./rhai/installation.md) 24 | - [Hello World(TBD)]() 25 | - [Multiple plugins](./multiple_plugins.md) 26 | - [Multiple runtimes(TBD)]() 27 | - [Implementing custom runtimes(TBD)]() 28 | - [Workflow](./workflow/workflow.md) 29 | - [Live-reload](./workflow/live_reload.md) 30 | - [Bevy support matrix](./bevy_support_matrix.md) 31 | -------------------------------------------------------------------------------- /book/src/bevy_support_matrix.md: -------------------------------------------------------------------------------- 1 | # Bevy support matrix 2 | 3 | | bevy version | bevy_scriptum version | 4 | | ------------ | --------------------- | 5 | | 0.16 | 0.8-0.9 | 6 | | 0.15 | 0.7 | 7 | | 0.14 | 0.6 | 8 | | 0.13 | 0.4-0.5 | 9 | | 0.12 | 0.3 | 10 | | 0.11 | 0.2 | 11 | | 0.10 | 0.1 | 12 | -------------------------------------------------------------------------------- /book/src/introduction.md: -------------------------------------------------------------------------------- 1 | # bevy_scriptum 📜 2 | 3 | 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. 4 | 5 | ## Supported scripting languages/runtimes 6 | 7 | | language/runtime | cargo feature | documentation chapter | 8 | | ---------------- | ------------- | --------------------------------------------------------------- | 9 | | 🌙 LuaJIT | `lua` | [link](https://jarkonik.github.io/bevy_scriptum/lua/lua.html) | 10 | | 🌾 Rhai | `rhai` | [link](https://jarkonik.github.io/bevy_scriptum/rhai/rhai.html) | 11 | | 💎 Ruby | `ruby` | [link](https://jarkonik.github.io/bevy_scriptum/ruby/ruby.html) | 12 | 13 | Documentation book is available [here](https://jarkonik.github.io/bevy_scriptum/) 📖 14 | 15 | Full API docs are available at [docs.rs](https://docs.rs/bevy_scriptum/latest/bevy_scriptum/) 🧑‍💻 16 | 17 | bevy_scriptum's main advantages include: 18 | 19 | - low-boilerplate 20 | - easy to use 21 | - asynchronicity with a promise-based API 22 | - flexibility 23 | - hot-reloading 24 | 25 | Scripts are separate files that can be hot-reloaded at runtime. This allows you to quickly iterate on your game logic without having to recompile it. 26 | 27 | All you need to do is register callbacks on your Bevy app like this: 28 | 29 | ```rust,no_run 30 | # extern crate bevy; 31 | # extern crate bevy_scriptum; 32 | 33 | use bevy::prelude::*; 34 | use bevy_scriptum::prelude::*; 35 | use bevy_scriptum::runtimes::lua::prelude::*; 36 | 37 | fn main() { 38 | App::new() 39 | .add_plugins(DefaultPlugins) 40 | .add_scripting::(|runtime| { 41 | runtime.add_function(String::from("hello_bevy"), || { 42 | println!("hello bevy, called from script"); 43 | }); 44 | }) 45 | .run(); 46 | } 47 | ``` 48 | 49 | And you can call them in your scripts like this: 50 | 51 | ```lua 52 | hello_bevy() 53 | ``` 54 | 55 | 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: 56 | 57 | ```rust,no_run 58 | # extern crate bevy; 59 | # extern crate bevy_ecs; 60 | # extern crate bevy_scriptum; 61 | 62 | use bevy::prelude::*; 63 | use bevy_scriptum::prelude::*; 64 | use bevy_scriptum::runtimes::lua::prelude::*; 65 | 66 | #[derive(Component)] 67 | struct Player; 68 | 69 | fn main() { 70 | App::new() 71 | .add_plugins(DefaultPlugins) 72 | .add_scripting::(|runtime| { 73 | runtime.add_function( 74 | String::from("print_player_names"), 75 | |players: Query<&Name, With>| { 76 | for player in &players { 77 | println!("player name: {}", player); 78 | } 79 | }, 80 | ); 81 | }) 82 | .run(); 83 | } 84 | ``` 85 | 86 | You can also pass arguments to your callback functions, just like you would in a regular Bevy system - using `In` structs with tuples: 87 | 88 | ```rust,no_run 89 | # extern crate bevy; 90 | # extern crate bevy_scriptum; 91 | 92 | use bevy::prelude::*; 93 | use bevy_scriptum::prelude::*; 94 | use bevy_scriptum::runtimes::lua::prelude::*; 95 | 96 | fn main() { 97 | App::new() 98 | .add_plugins(DefaultPlugins) 99 | .add_scripting::(|runtime| { 100 | runtime.add_function( 101 | String::from("fun_with_string_param"), 102 | |In((x,)): In<(String,)>| { 103 | println!("called with string: '{}'", x); 104 | }, 105 | ); 106 | }) 107 | .run(); 108 | } 109 | ``` 110 | 111 | which you can then call in your script like this: 112 | 113 | ```lua 114 | fun_with_string_param("Hello world!") 115 | ``` 116 | 117 | ### Usage 118 | 119 | Add the following to your `Cargo.toml`: 120 | 121 | ```toml 122 | [dependencies] 123 | bevy_scriptum = { version = "0.9", features = ["lua"] } 124 | ``` 125 | 126 | or execute `cargo add bevy_scriptum --features lua` from your project directory. 127 | 128 | You can now start exposing functions to the scripting language. For example, you can expose a function that prints a message to the console: 129 | 130 | ```rust,no_run 131 | # extern crate bevy; 132 | # extern crate bevy_scriptum; 133 | 134 | use bevy::prelude::*; 135 | use bevy_scriptum::prelude::*; 136 | use bevy_scriptum::runtimes::lua::prelude::*; 137 | 138 | fn main() { 139 | App::new() 140 | .add_plugins(DefaultPlugins) 141 | .add_scripting::(|runtime| { 142 | runtime.add_function( 143 | String::from("my_print"), 144 | |In((x,)): In<(String,)>| { 145 | println!("my_print: '{}'", x); 146 | }, 147 | ); 148 | }) 149 | .run(); 150 | } 151 | ``` 152 | 153 | Then you can create a script file in `assets` directory called `script.lua` that calls this function: 154 | 155 | ```lua 156 | my_print("Hello world!") 157 | ``` 158 | 159 | And spawn an entity with attached `Script` component with a handle to a script source file: 160 | 161 | ```rust,no_run 162 | # extern crate bevy; 163 | # extern crate bevy_scriptum; 164 | 165 | use bevy::prelude::*; 166 | use bevy_scriptum::prelude::*; 167 | use bevy_scriptum::runtimes::lua::prelude::*; 168 | 169 | fn main() { 170 | App::new() 171 | .add_plugins(DefaultPlugins) 172 | .add_scripting::(|runtime| { 173 | runtime.add_function( 174 | String::from("my_print"), 175 | |In((x,)): In<(String,)>| { 176 | println!("my_print: '{}'", x); 177 | }, 178 | ); 179 | }) 180 | .add_systems(Startup,|mut commands: Commands, asset_server: Res| { 181 | commands.spawn(Script::::new(asset_server.load("script.lua"))); 182 | }) 183 | .run(); 184 | } 185 | ``` 186 | 187 | You should then see `my_print: 'Hello world!'` printed in your console. 188 | 189 | ### Provided examples 190 | 191 | You can also try running provided examples by cloning this repository and running `cargo run --example _`. For example: 192 | 193 | ```bash 194 | cargo run --example hello_world_lua 195 | ``` 196 | 197 | The examples live in `examples` directory and their corresponding scripts live in `assets/examples` directory within the repository. 198 | 199 | ### Promises - getting return values from scripts 200 | 201 | 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: 202 | 203 | ```lua 204 | get_player_name():and_then(function(name) 205 | print(name) 206 | end) 207 | ``` 208 | 209 | which will print out `John` when used with following exposed function: 210 | 211 | ```rust,no_run 212 | # extern crate bevy; 213 | # extern crate bevy_scriptum; 214 | 215 | use bevy::prelude::*; 216 | use bevy_scriptum::prelude::*; 217 | use bevy_scriptum::runtimes::lua::prelude::*; 218 | 219 | fn main() { 220 | App::new() 221 | .add_plugins(DefaultPlugins) 222 | .add_scripting::(|runtime| { 223 | runtime.add_function(String::from("get_player_name"), || String::from("John")); 224 | }); 225 | } 226 | ``` 227 | 228 | ## Access entity from script 229 | 230 | A variable called `entity` is automatically available to all scripts - it represents bevy entity that the `Script` component is attached to. 231 | It exposes `index` property that returns bevy entity index. 232 | It is useful for accessing entity's components from scripts. 233 | It can be used in the following way: 234 | 235 | ```lua 236 | print("Current entity index: " .. entity.index) 237 | ``` 238 | 239 | `entity` variable is currently not available within promise callbacks. 240 | 241 | ### Contributing 242 | 243 | Contributions are welcome! Feel free to open an issue or submit a pull request. 244 | 245 | ### License 246 | 247 | bevy_scriptum is licensed under either of the following, at your option: 248 | 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) 249 | -------------------------------------------------------------------------------- /book/src/lib.rs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarkonik/bevy_scriptum/fa70abac23b32b70deb76e935819c62998bef1fd/book/src/lib.rs -------------------------------------------------------------------------------- /book/src/lua/builtin_types.md: -------------------------------------------------------------------------------- 1 | # Builtin types 2 | 3 | bevy_scriptum provides following types that can be used in Lua: 4 | 5 | - ```Vec3``` 6 | - ```BevyEntity``` 7 | 8 | ## Vec3 9 | 10 | ### Constructor 11 | 12 | `Vec3(x: number, y: number, z: number)` 13 | 14 | ### Properties 15 | 16 | - `x: number` 17 | - `y: number` 18 | - `z: number` 19 | 20 | 21 | ### Example Lua usage 22 | 23 | ```lua 24 | my_vec = Vec3(1, 2, 3) 25 | set_translation(entity, my_vec) 26 | ``` 27 | 28 | ### Example Rust usage 29 | 30 | ```rust,no_run 31 | # extern crate bevy; 32 | # extern crate bevy_scriptum; 33 | 34 | use bevy::prelude::*; 35 | use bevy_scriptum::prelude::*; 36 | use bevy_scriptum::runtimes::lua::prelude::*; 37 | 38 | fn main() { 39 | App::new() 40 | .add_plugins(DefaultPlugins) 41 | .add_scripting::(|runtime| { 42 | runtime.add_function(String::from("set_translation"), set_translation); 43 | }) 44 | .run(); 45 | } 46 | 47 | fn set_translation( 48 | In((entity, translation)): In<(BevyEntity, BevyVec3)>, 49 | mut entities: Query<&mut Transform>, 50 | ) { 51 | let mut transform = entities.get_mut(entity.0).unwrap(); 52 | transform.translation = translation.0; 53 | } 54 | ``` 55 | 56 | ## BevyEntity 57 | 58 | ### Constructor 59 | 60 | None - instances can only be acquired by using built-in `entity` global variable. 61 | 62 | ### Properties 63 | 64 | - `index: integer` 65 | 66 | ### Example Lua usage 67 | 68 | ```lua 69 | print(entity.index) 70 | pass_to_rust(entity) 71 | ``` 72 | 73 | ### Example Rust usage 74 | 75 | ```rust,no_run 76 | # extern crate bevy; 77 | # extern crate bevy_scriptum; 78 | 79 | use bevy::prelude::*; 80 | use bevy_scriptum::prelude::*; 81 | use bevy_scriptum::runtimes::lua::prelude::*; 82 | 83 | fn main() { 84 | App::new() 85 | .add_plugins(DefaultPlugins) 86 | .add_scripting::(|runtime| { 87 | runtime.add_function(String::from("pass_to_rust"), |In((entity,)): In<(BevyEntity,)>| { 88 | println!("pass_to_rust called with entity: {:?}", entity); 89 | }); 90 | }) 91 | .run(); 92 | } 93 | ``` 94 | -------------------------------------------------------------------------------- /book/src/lua/builtin_variables.md: -------------------------------------------------------------------------------- 1 | # Builtin variables 2 | 3 | ## entity 4 | 5 | A variable called `entity` is automatically available to all scripts - it represents bevy entity that the `Script` component is attached to. 6 | It exposes `index` property that returns bevy entity index. 7 | It is useful for accessing entity's components from scripts. 8 | It can be used in the following way: 9 | ```lua 10 | print("Current entity index: " .. entity.index) 11 | ``` 12 | 13 | `entity` variable is currently not available within promise callbacks. 14 | -------------------------------------------------------------------------------- /book/src/lua/calling_rust_from_script.md: -------------------------------------------------------------------------------- 1 | # Calling Rust from Lua 2 | 3 | To call a rust function from Lua first you need to register a function 4 | within Rust using builder pattern. 5 | 6 | ```rust,no_run 7 | # extern crate bevy; 8 | # extern crate bevy_scriptum; 9 | 10 | use bevy::prelude::*; 11 | use bevy_scriptum::prelude::*; 12 | use bevy_scriptum::runtimes::lua::prelude::*; 13 | 14 | fn main() { 15 | App::new() 16 | .add_plugins(DefaultPlugins) 17 | .add_scripting::(|runtime| { 18 | // `runtime` is a builder that you can use to register functions 19 | }) 20 | .run(); 21 | } 22 | ``` 23 | 24 | For example to register a function called `my_rust_func` you can do the following: 25 | 26 | ```rust,no_run 27 | # extern crate bevy; 28 | # extern crate bevy_scriptum; 29 | 30 | use bevy::prelude::*; 31 | use bevy_scriptum::prelude::*; 32 | use bevy_scriptum::runtimes::lua::prelude::*; 33 | 34 | fn main() { 35 | App::new() 36 | .add_plugins(DefaultPlugins) 37 | .add_scripting::(|runtime| { 38 | runtime.add_function(String::from("my_rust_func"), || { 39 | println!("my_rust_func has been called"); 40 | }); 41 | }) 42 | .run(); 43 | } 44 | ``` 45 | 46 | After you do that the function will be available to Lua code in your spawned scripts. 47 | 48 | ```lua 49 | my_rust_func() 50 | ``` 51 | 52 | Registered functions can also take parameters. A parameter can be any type 53 | that implements `FromLua`. 54 | 55 | Since a registered callback function is a Bevy system, the parameters are passed 56 | to it as `In` struct with tuple, which has to be the first parameter of the closure. 57 | 58 | ```rust,no_run 59 | # extern crate bevy; 60 | # extern crate bevy_scriptum; 61 | 62 | use bevy::prelude::*; 63 | use bevy_scriptum::prelude::*; 64 | use bevy_scriptum::runtimes::lua::prelude::*; 65 | 66 | fn main() { 67 | App::new() 68 | .add_plugins(DefaultPlugins) 69 | .add_scripting::(|runtime| { 70 | runtime.add_function(String::from("func_with_params"), |args: In<(String, i64)>| { 71 | println!("my_rust_func has been called with string {} and i64 {}", args.0.0, args.0.1); 72 | }); 73 | }) 74 | .run(); 75 | } 76 | ``` 77 | 78 | To make it look nicer you can destructure the `In` struct. 79 | 80 | ```rust,no_run 81 | # extern crate bevy; 82 | # extern crate bevy_scriptum; 83 | 84 | use bevy::prelude::*; 85 | use bevy_scriptum::prelude::*; 86 | use bevy_scriptum::runtimes::lua::prelude::*; 87 | 88 | fn main() { 89 | App::new() 90 | .add_plugins(DefaultPlugins) 91 | .add_scripting::(|runtime| { 92 | runtime.add_function(String::from("func_with_params"), |In((a, b)): In<(String, i64)>| { 93 | println!("my_rust_func has been called with string {} and i64 {}", a, b); 94 | }); 95 | }) 96 | .run(); 97 | } 98 | ``` 99 | 100 | The above function can be called from Lua 101 | 102 | ```lua 103 | func_with_params("abc", 123) 104 | ``` 105 | 106 | ## Return value via promise 107 | 108 | Any registered rust function that returns a value will retrurn a promise when 109 | called within a script. By calling `:and_then` on the promise you can register 110 | a callback that will receive the value returned from Rust function. 111 | 112 | ```rust,no_run 113 | # extern crate bevy; 114 | # extern crate bevy_scriptum; 115 | 116 | use bevy::prelude::*; 117 | use bevy_scriptum::prelude::*; 118 | use bevy_scriptum::runtimes::lua::prelude::*; 119 | 120 | fn main() { 121 | App::new() 122 | .add_plugins(DefaultPlugins) 123 | .add_scripting::(|runtime| { 124 | runtime.add_function(String::from("returns_value"), || { 125 | 123 126 | }); 127 | }) 128 | .run(); 129 | } 130 | ``` 131 | 132 | ```lua 133 | returns_value():and_then(function (value) 134 | print(value) -- 123 135 | end) 136 | ``` 137 | -------------------------------------------------------------------------------- /book/src/lua/calling_script_from_rust.md: -------------------------------------------------------------------------------- 1 | # Calling Lua from Rust 2 | 3 | To call a function defined in Lua 4 | 5 | ```lua 6 | function on_update() 7 | end 8 | ``` 9 | 10 | We need to acquire `LuaRuntime` resource within a bevy system. 11 | Then we will be able to call `call_fn` on it, providing the name 12 | of the function to call, `LuaScriptData` that has been automatically 13 | attached to entity after an entity with script attached has been spawned 14 | and its script evaluated, the entity and optionally some arguments. 15 | 16 | ```rust,no_run 17 | # extern crate bevy; 18 | # extern crate bevy_scriptum; 19 | 20 | use bevy::prelude::*; 21 | use bevy_scriptum::prelude::*; 22 | use bevy_scriptum::runtimes::lua::prelude::*; 23 | 24 | fn call_lua_on_update_from_rust( 25 | mut scripted_entities: Query<(Entity, &mut LuaScriptData)>, 26 | scripting_runtime: ResMut, 27 | ) { 28 | for (entity, mut script_data) in &mut scripted_entities { 29 | // calling function named `on_update` defined in lua script 30 | scripting_runtime 31 | .call_fn("on_update", &mut script_data, entity, ()) 32 | .unwrap(); 33 | } 34 | } 35 | ``` 36 | 37 | We can also pass some arguments by providing a tuple or `Vec` as the last 38 | `call_fn` argument. 39 | 40 | ```rust,no_run 41 | # extern crate bevy; 42 | # extern crate bevy_scriptum; 43 | 44 | use bevy::prelude::*; 45 | use bevy_scriptum::prelude::*; 46 | use bevy_scriptum::runtimes::lua::prelude::*; 47 | 48 | fn call_lua_on_update_from_rust( 49 | mut scripted_entities: Query<(Entity, &mut LuaScriptData)>, 50 | scripting_runtime: ResMut, 51 | ) { 52 | for (entity, mut script_data) in &mut scripted_entities { 53 | scripting_runtime 54 | .call_fn("on_update", &mut script_data, entity, (123, String::from("hello"))) 55 | .unwrap(); 56 | } 57 | } 58 | ``` 59 | 60 | They will be passed to `on_update` Lua function 61 | ```lua 62 | function on_update(a, b) 63 | print(a) -- 123 64 | print(b) -- hello 65 | end 66 | ``` 67 | 68 | Any type that implements `IntoLua` can be passed as an argument withing the 69 | tuple in `call_fn`. 70 | -------------------------------------------------------------------------------- /book/src/lua/hello_world.md: -------------------------------------------------------------------------------- 1 | # Hello World 2 | 3 | After you are done installing the required crates, you can start developing 4 | your first game or application using bevy_scriptum. 5 | 6 | To start using the library you need to first import some structs and traits 7 | with Rust `use` statements. 8 | 9 | For convenience there is a main "prelude" module provided called 10 | `bevy_scriptum::prelude` and a prelude for each runtime you have enabled as 11 | a create feature. 12 | 13 | You can now start exposing functions to the scripting language. For example, you can expose a function that prints a message to the console: 14 | 15 | ```rust,no_run 16 | # extern crate bevy; 17 | # extern crate bevy_scriptum; 18 | 19 | use bevy::prelude::*; 20 | use bevy_scriptum::prelude::*; 21 | use bevy_scriptum::runtimes::lua::prelude::*; 22 | 23 | fn main() { 24 | App::new() 25 | .add_plugins(DefaultPlugins) 26 | .add_scripting::(|runtime| { 27 | runtime.add_function( 28 | String::from("my_print"), 29 | |In((x,)): In<(String,)>| { 30 | println!("my_print: '{}'", x); 31 | }, 32 | ); 33 | }) 34 | .run(); 35 | } 36 | ``` 37 | 38 | Then you can create a script file in `assets` directory called `script.lua` that calls this function: 39 | 40 | ```lua 41 | my_print("Hello world!") 42 | ``` 43 | 44 | And spawn an entity with attached `Script` component with a handle to a script source file: 45 | 46 | ```rust,no_run 47 | # extern crate bevy; 48 | # extern crate bevy_scriptum; 49 | 50 | use bevy::prelude::*; 51 | use bevy_scriptum::prelude::*; 52 | use bevy_scriptum::runtimes::lua::prelude::*; 53 | 54 | fn main() { 55 | App::new() 56 | .add_plugins(DefaultPlugins) 57 | .add_scripting::(|runtime| { 58 | runtime.add_function( 59 | String::from("my_print"), 60 | |In((x,)): In<(String,)>| { 61 | println!("my_print: '{}'", x); 62 | }, 63 | ); 64 | }) 65 | .add_systems(Startup,|mut commands: Commands, asset_server: Res| { 66 | commands.spawn(Script::::new(asset_server.load("script.lua"))); 67 | }) 68 | .run(); 69 | } 70 | ``` 71 | 72 | You should then see `my_print: 'Hello world!'` printed in your console. 73 | -------------------------------------------------------------------------------- /book/src/lua/installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | Add the following to your `Cargo.toml`: 4 | 5 | ```toml 6 | [dependencies] 7 | bevy = "0.16" 8 | bevy_scriptum = { version = "0.9", features = ["lua"] } 9 | ``` 10 | 11 | If you need a different version of bevy you need to use a matching bevy_scriptum 12 | version according to the [bevy support matrix](../bevy_support_matrix.md) 13 | -------------------------------------------------------------------------------- /book/src/lua/interacting_with_bevy.md: -------------------------------------------------------------------------------- 1 | # Interacting with bevy in callbacks 2 | 3 | Every registered function is also just a regular Bevy system. 4 | 5 | That allows you to do anything you would do in a Bevy system. 6 | 7 | You could for example create a callback system function that prints names 8 | of all entities with `Player` component. 9 | 10 | ```rust,no_run 11 | # extern crate bevy; 12 | # extern crate bevy_ecs; 13 | # extern crate bevy_scriptum; 14 | 15 | use bevy::prelude::*; 16 | use bevy_scriptum::prelude::*; 17 | use bevy_scriptum::runtimes::lua::prelude::*; 18 | 19 | #[derive(Component)] 20 | struct Player; 21 | 22 | fn main() { 23 | App::new() 24 | .add_plugins(DefaultPlugins) 25 | .add_scripting::(|runtime| { 26 | runtime.add_function( 27 | String::from("print_player_names"), 28 | |players: Query<&Name, With>| { 29 | for player in &players { 30 | println!("player name: {}", player); 31 | } 32 | }, 33 | ); 34 | }) 35 | .run(); 36 | } 37 | ``` 38 | 39 | In script: 40 | 41 | ```lua 42 | print_player_names() 43 | ``` 44 | 45 | You can use functions that interact with Bevy entities and resources and 46 | take arguments at the same time. It could be used for example to mutate a 47 | component. 48 | 49 | ```rust,no_run 50 | # extern crate bevy; 51 | # extern crate bevy_ecs; 52 | # extern crate bevy_scriptum; 53 | 54 | use bevy::prelude::*; 55 | use bevy_scriptum::prelude::*; 56 | use bevy_scriptum::runtimes::lua::prelude::*; 57 | 58 | #[derive(Component)] 59 | struct Player { 60 | health: i32 61 | } 62 | 63 | fn main() { 64 | App::new() 65 | .add_plugins(DefaultPlugins) 66 | .add_scripting::(|runtime| { 67 | runtime.add_function( 68 | String::from("hurt_player"), 69 | |In((hit_value,)): In<(i32,)>, mut players: Query<&mut Player>| { 70 | let mut player = players.single_mut().unwrap(); 71 | player.health -= hit_value; 72 | }, 73 | ); 74 | }) 75 | .run(); 76 | } 77 | ``` 78 | 79 | And it could be called in script like: 80 | 81 | ```lua 82 | hurt_player(5) 83 | ``` 84 | -------------------------------------------------------------------------------- /book/src/lua/lua.md: -------------------------------------------------------------------------------- 1 | # Lua 2 | 3 | This chapter demonstrates how to work with bevy_scriptum when using Lua language runtime. 4 | -------------------------------------------------------------------------------- /book/src/lua/spawning_scripts.md: -------------------------------------------------------------------------------- 1 | # Spawning scripts 2 | 3 | To spawn a Lua script you will need to get a handle to a script asset using 4 | bevy's `AssetServer`. 5 | 6 | ```rust 7 | # extern crate bevy; 8 | # extern crate bevy_scriptum; 9 | 10 | use bevy::prelude::*; 11 | use bevy_scriptum::prelude::*; 12 | use bevy_scriptum::runtimes::lua::prelude::*; 13 | 14 | fn my_spawner(mut commands: Commands, assets_server: Res) { 15 | commands.spawn(Script::::new( 16 | assets_server.load("my_script.lua"), 17 | )); 18 | } 19 | ``` 20 | 21 | After they scripts have been evaled by bevy_scriptum, the entities that they've 22 | been attached to will get the `Script::` component stripped and instead 23 | ```LuaScriptData``` component will be attached. 24 | 25 | So to query scipted entities you could do something like: 26 | 27 | ```rust 28 | # extern crate bevy; 29 | # extern crate bevy_scriptum; 30 | 31 | use bevy::prelude::*; 32 | use bevy_scriptum::prelude::*; 33 | use bevy_scriptum::runtimes::lua::prelude::*; 34 | 35 | fn my_system( 36 | mut scripted_entities: Query<(Entity, &mut LuaScriptData)>, 37 | ) { 38 | for (entity, mut script_data) in &mut scripted_entities { 39 | // do something with scripted entities 40 | } 41 | } 42 | ``` 43 | -------------------------------------------------------------------------------- /book/src/multiple_plugins.md: -------------------------------------------------------------------------------- 1 | # Multiple plugins 2 | 3 | It is possible to split the definition of your callback functions up over multiple plugins. This enables you to split up your code by subject and keep the main initialization light and clean. 4 | This can be accomplished by using `add_scripting_api`. Be careful though, `add_scripting` has to be called before adding plugins. 5 | ```rust,no_run 6 | # extern crate bevy; 7 | # extern crate bevy_scriptum; 8 | 9 | use bevy::prelude::*; 10 | use bevy_scriptum::prelude::*; 11 | use bevy_scriptum::runtimes::lua::prelude::*; 12 | 13 | struct MyPlugin; 14 | impl Plugin for MyPlugin { 15 | fn build(&self, app: &mut App) { 16 | app.add_scripting_api::(|runtime| { 17 | runtime.add_function(String::from("hello_from_my_plugin"), || { 18 | info!("Hello from MyPlugin"); 19 | }); 20 | }); 21 | } 22 | } 23 | 24 | // Main 25 | fn main() { 26 | App::new() 27 | .add_plugins(DefaultPlugins) 28 | .add_scripting::(|_| { 29 | // nice and clean 30 | }) 31 | .add_plugins(MyPlugin) 32 | .run(); 33 | } 34 | ``` 35 | -------------------------------------------------------------------------------- /book/src/rhai/hello_world.md: -------------------------------------------------------------------------------- 1 | # Hello World 2 | -------------------------------------------------------------------------------- /book/src/rhai/installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | Add the following to your `Cargo.toml`: 4 | 5 | ```toml 6 | [dependencies] 7 | bevy = "0.16" 8 | bevy_scriptum = { version = "0.9", features = ["rhai"] } 9 | ``` 10 | 11 | If you need a different version of bevy you need to use a matching bevy_scriptum 12 | version according to the [bevy support matrix](../bevy_support_matrix.md) 13 | -------------------------------------------------------------------------------- /book/src/rhai/rhai.md: -------------------------------------------------------------------------------- 1 | # Rhai 2 | 3 | This chapter demonstrates how to work with bevy_scriptum when using Rhai language runtime. 4 | -------------------------------------------------------------------------------- /book/src/ruby/builtin_types.md: -------------------------------------------------------------------------------- 1 | # Builtin types 2 | 3 | bevy_scriptum provides following types that can be used in Ruby: 4 | 5 | - `Bevy::Vec3` 6 | - `Bevy::Entity` 7 | 8 | ## Bevy::Vec3 9 | 10 | ### Class Methods 11 | 12 | - `new(x, y, z)` 13 | - `current` 14 | 15 | ### Instance Methods 16 | 17 | - `x` 18 | - `y` 19 | - `z` 20 | 21 | ### Example Ruby usage 22 | 23 | ```ruby 24 | my_vec = Bevy::Vec3.new(1, 2, 3) 25 | set_translation(entity, my_vec) 26 | ``` 27 | 28 | ### Example Rust usage 29 | 30 | ```rust,no_run 31 | # extern crate bevy; 32 | # extern crate bevy_scriptum; 33 | 34 | use bevy::prelude::*; 35 | use bevy_scriptum::prelude::*; 36 | use bevy_scriptum::runtimes::ruby::prelude::*; 37 | 38 | fn main() { 39 | App::new() 40 | .add_plugins(DefaultPlugins) 41 | .add_scripting::(|runtime| { 42 | runtime.add_function(String::from("set_translation"), set_translation); 43 | }) 44 | .run(); 45 | } 46 | 47 | fn set_translation( 48 | In((entity, translation)): In<(BevyEntity, BevyVec3)>, 49 | mut entities: Query<&mut Transform>, 50 | ) { 51 | let mut transform = entities.get_mut(entity.0).unwrap(); 52 | transform.translation = translation.0; 53 | } 54 | ``` 55 | 56 | ## Bevy::Entity 57 | 58 | `Bevy::Entity.current` is currently not available within promise callbacks. 59 | 60 | ### Constructor 61 | 62 | None - instances can only be acquired by using `Bevy::Entity.current` 63 | 64 | ### Class method 65 | 66 | - `index` 67 | 68 | ### Example Ruby usage 69 | 70 | ```ruby 71 | puts(Bevy::Entity.current.index) 72 | pass_to_rust(Bevy::Entity.current) 73 | ``` 74 | 75 | ### Example Rust usage 76 | 77 | ```rust,no_run 78 | # extern crate bevy; 79 | # extern crate bevy_scriptum; 80 | 81 | use bevy::prelude::*; 82 | use bevy_scriptum::prelude::*; 83 | use bevy_scriptum::runtimes::ruby::prelude::*; 84 | 85 | fn main() { 86 | App::new() 87 | .add_plugins(DefaultPlugins) 88 | .add_scripting::(|runtime| { 89 | runtime.add_function(String::from("pass_to_rust"), |In((entity,)): In<(BevyEntity,)>| { 90 | println!("pass_to_rust called with entity: {:?}", entity); 91 | }); 92 | }) 93 | .run(); 94 | } 95 | ``` 96 | -------------------------------------------------------------------------------- /book/src/ruby/calling_rust_from_script.md: -------------------------------------------------------------------------------- 1 | # Calling Rust from Ruby 2 | 3 | To call a rust function from Ruby first you need to register a function 4 | within Rust using builder pattern. 5 | 6 | ```rust,no_run 7 | # extern crate bevy; 8 | # extern crate bevy_scriptum; 9 | 10 | use bevy::prelude::*; 11 | use bevy_scriptum::prelude::*; 12 | use bevy_scriptum::runtimes::ruby::prelude::*; 13 | 14 | fn main() { 15 | App::new() 16 | .add_plugins(DefaultPlugins) 17 | .add_scripting::(|runtime| { 18 | // `runtime` is a builder that you can use to register functions 19 | }) 20 | .run(); 21 | } 22 | ``` 23 | 24 | For example to register a function called `my_rust_func` you can do the following: 25 | 26 | ```rust,no_run 27 | # extern crate bevy; 28 | # extern crate bevy_scriptum; 29 | 30 | use bevy::prelude::*; 31 | use bevy_scriptum::prelude::*; 32 | use bevy_scriptum::runtimes::ruby::prelude::*; 33 | 34 | fn main() { 35 | App::new() 36 | .add_plugins(DefaultPlugins) 37 | .add_scripting::(|runtime| { 38 | runtime.add_function(String::from("my_rust_func"), || { 39 | println!("my_rust_func has been called"); 40 | }); 41 | }) 42 | .run(); 43 | } 44 | ``` 45 | 46 | After you do that the function will be available to Ruby code in your spawned scripts. 47 | 48 | ```ruby 49 | my_rust_func 50 | ``` 51 | 52 | Since a registered callback function is a Bevy system, the parameters are passed 53 | to it as `In` struct with tuple, which has to be the first parameter of the closure. 54 | 55 | ```rust,no_run 56 | # extern crate bevy; 57 | # extern crate bevy_scriptum; 58 | 59 | use bevy::prelude::*; 60 | use bevy_scriptum::prelude::*; 61 | use bevy_scriptum::runtimes::ruby::prelude::*; 62 | 63 | fn main() { 64 | App::new() 65 | .add_plugins(DefaultPlugins) 66 | .add_scripting::(|runtime| { 67 | runtime.add_function(String::from("func_with_params"), |args: In<(String, i64)>| { 68 | println!("my_rust_func has been called with string {} and i64 {}", args.0.0, args.0.1); 69 | }); 70 | }) 71 | .run(); 72 | } 73 | ``` 74 | 75 | To make it look nicer you can destructure the `In` struct. 76 | 77 | ```rust,no_run 78 | # extern crate bevy; 79 | # extern crate bevy_scriptum; 80 | 81 | use bevy::prelude::*; 82 | use bevy_scriptum::prelude::*; 83 | use bevy_scriptum::runtimes::ruby::prelude::*; 84 | 85 | fn main() { 86 | App::new() 87 | .add_plugins(DefaultPlugins) 88 | .add_scripting::(|runtime| { 89 | runtime.add_function(String::from("func_with_params"), |In((a, b)): In<(String, i64)>| { 90 | println!("my_rust_func has been called with string {} and i64 {}", a, b); 91 | }); 92 | }) 93 | .run(); 94 | } 95 | ``` 96 | 97 | The above function can be called from Ruby 98 | 99 | ```ruby 100 | func_with_params("abc", 123) 101 | ``` 102 | 103 | ## Return value via promise 104 | 105 | Any registered rust function that returns a value will retrurn a promise when 106 | called within a script. By calling `:and_then` on the promise you can register 107 | a callback that will receive the value returned from Rust function. 108 | 109 | ```rust,no_run 110 | # extern crate bevy; 111 | # extern crate bevy_scriptum; 112 | 113 | use bevy::prelude::*; 114 | use bevy_scriptum::prelude::*; 115 | use bevy_scriptum::runtimes::ruby::prelude::*; 116 | 117 | fn main() { 118 | App::new() 119 | .add_plugins(DefaultPlugins) 120 | .add_scripting::(|runtime| { 121 | runtime.add_function(String::from("returns_value"), || { 122 | 123 123 | }); 124 | }) 125 | .run(); 126 | } 127 | ``` 128 | 129 | ```ruby 130 | returns_value.and_then do |value| 131 | puts(value) # 123 132 | end 133 | ``` 134 | -------------------------------------------------------------------------------- /book/src/ruby/calling_script_from_rust.md: -------------------------------------------------------------------------------- 1 | # Calling Ruby from Rust 2 | 3 | To call a function defined in Ruby 4 | 5 | ```ruby 6 | def on_update 7 | end 8 | ``` 9 | 10 | We need to acquire `RubyRuntime` resource within a bevy system. 11 | Then we will be able to call `call_fn` on it, providing the name 12 | of the function to call, `RubyScriptData` that has been automatically 13 | attached to entity after an entity with script attached has been spawned 14 | and its script evaluated, the entity and optionally some arguments. 15 | 16 | ```rust,no_run 17 | # extern crate bevy; 18 | # extern crate bevy_scriptum; 19 | 20 | use bevy::prelude::*; 21 | use bevy_scriptum::prelude::*; 22 | use bevy_scriptum::runtimes::ruby::prelude::*; 23 | 24 | fn call_ruby_on_update_from_rust( 25 | mut scripted_entities: Query<(Entity, &mut RubyScriptData)>, 26 | scripting_runtime: ResMut, 27 | ) { 28 | for (entity, mut script_data) in &mut scripted_entities { 29 | // calling function named `on_update` defined in Ruby script 30 | scripting_runtime 31 | .call_fn("on_update", &mut script_data, entity, ()) 32 | .unwrap(); 33 | } 34 | } 35 | ``` 36 | 37 | We can also pass some arguments by providing a tuple or `Vec` as the last 38 | `call_fn` argument. 39 | 40 | ```rust,no_run 41 | # extern crate bevy; 42 | # extern crate bevy_scriptum; 43 | 44 | use bevy::prelude::*; 45 | use bevy_scriptum::prelude::*; 46 | use bevy_scriptum::runtimes::ruby::prelude::*; 47 | 48 | fn call_ruby_on_update_from_rust( 49 | mut scripted_entities: Query<(Entity, &mut RubyScriptData)>, 50 | scripting_runtime: ResMut, 51 | ) { 52 | for (entity, mut script_data) in &mut scripted_entities { 53 | scripting_runtime 54 | .call_fn("on_update", &mut script_data, entity, (123, String::from("hello"))) 55 | .unwrap(); 56 | } 57 | } 58 | ``` 59 | 60 | They will be passed to `on_update` Ruby function 61 | ```ruby 62 | def on_update(a, b) 63 | puts(a) # 123 64 | puts(b) # hello 65 | end 66 | ``` 67 | -------------------------------------------------------------------------------- /book/src/ruby/hello_world.md: -------------------------------------------------------------------------------- 1 | # Hello World 2 | 3 | After you are done installing the required crates, you can start developing 4 | your first game or application using bevy_scriptum. 5 | 6 | To start using the library you need to first import some structs and traits 7 | with Rust `use` statements. 8 | 9 | For convenience there is a main "prelude" module provided called 10 | `bevy_scriptum::prelude` and a prelude for each runtime you have enabled as 11 | a create feature. 12 | 13 | You can now start exposing functions to the scripting language. For example, you can expose a function that prints a message to the console: 14 | 15 | ```rust,no_run 16 | # extern crate bevy; 17 | # extern crate bevy_scriptum; 18 | 19 | use bevy::prelude::*; 20 | use bevy_scriptum::prelude::*; 21 | use bevy_scriptum::runtimes::ruby::prelude::*; 22 | 23 | fn main() { 24 | App::new() 25 | .add_plugins(DefaultPlugins) 26 | .add_scripting::(|runtime| { 27 | runtime.add_function( 28 | String::from("my_print"), 29 | |In((x,)): In<(String,)>| { 30 | println!("my_print: '{}'", x); 31 | }, 32 | ); 33 | }) 34 | .run(); 35 | } 36 | ``` 37 | 38 | Then you can create a script file in `assets` directory called `script.rb` that calls this function: 39 | 40 | ```ruby 41 | my_print("Hello world!") 42 | ``` 43 | 44 | And spawn an entity with attached `Script` component with a handle to a script source file: 45 | 46 | ```rust,no_run 47 | # extern crate bevy; 48 | # extern crate bevy_scriptum; 49 | 50 | use bevy::prelude::*; 51 | use bevy_scriptum::prelude::*; 52 | use bevy_scriptum::runtimes::ruby::prelude::*; 53 | 54 | fn main() { 55 | App::new() 56 | .add_plugins(DefaultPlugins) 57 | .add_scripting::(|runtime| { 58 | runtime.add_function( 59 | String::from("my_print"), 60 | |In((x,)): In<(String,)>| { 61 | println!("my_print: '{}'", x); 62 | }, 63 | ); 64 | }) 65 | .add_systems(Startup,|mut commands: Commands, asset_server: Res| { 66 | commands.spawn(Script::::new(asset_server.load("script.rb"))); 67 | }) 68 | .run(); 69 | } 70 | ``` 71 | 72 | You should then see `my_print: 'Hello world!'` printed in your console. 73 | -------------------------------------------------------------------------------- /book/src/ruby/installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | Ruby is currently only supported on Linux. 4 | 5 | ## Ruby 6 | 7 | To build `bevy_scriptum` with Ruby support a Ruby installation is needed to be 8 | present on your development machine. 9 | 10 | The easiest way to produce a compatible Ruby installation is to use [rbenv](https://rbenv.org/). 11 | 12 | After installing `rbenv` along with its `ruby-build` plugin you can build and 13 | install a Ruby installation that will work with `bevy_scriptum` by executing: 14 | 15 | ```sh 16 | CC=clang rbenv install 3.4.4 17 | ``` 18 | 19 | Above assumes that you also have `clang` installed on your system. 20 | For `clang` installation instruction consult your 21 | OS vendor provided documentation or [clang official webiste](https://clang.llvm.org). 22 | 23 | If you rather not use `rbenv` you are free to supply your own installation of 24 | Ruby provided the following is true about it: 25 | 26 | - it is compiled with `clang` 27 | - it is compiled as a static library 28 | - it is accessible as `ruby` within `PATH` or `RUBY` environment variable is set 29 | to path of desired `ruby` binary. 30 | 31 | ## Main Library 32 | 33 | Add the following to your `Cargo.toml`: 34 | 35 | ```toml 36 | [dependencies] 37 | bevy = "0.16" 38 | bevy_scriptum = { version = "0.9", features = ["ruby"] } 39 | ``` 40 | 41 | If you need a different version of bevy you need to use a matching bevy_scriptum 42 | version according to the [bevy support matrix](../bevy_support_matrix.md) 43 | 44 | Ruby also needs dynamic symbol resolution and since `bevy_scriptum` links Ruby 45 | statically the following `build.rs` file is needed to be present in project 46 | root directory. 47 | 48 | ```rust 49 | fn main() { 50 | println!("cargo:rustc-link-arg=-rdynamic"); 51 | } 52 | ``` 53 | -------------------------------------------------------------------------------- /book/src/ruby/interacting_with_bevy.md: -------------------------------------------------------------------------------- 1 | # Interacting with bevy in callbacks 2 | 3 | Every registered function is also just a regular Bevy system. 4 | 5 | That allows you to do anything you would do in a Bevy system. 6 | 7 | You could for example create a callback system function that prints names 8 | of all entities with `Player` component. 9 | 10 | ```rust,no_run 11 | # extern crate bevy; 12 | # extern crate bevy_ecs; 13 | # extern crate bevy_scriptum; 14 | 15 | use bevy::prelude::*; 16 | use bevy_scriptum::prelude::*; 17 | use bevy_scriptum::runtimes::ruby::prelude::*; 18 | 19 | #[derive(Component)] 20 | struct Player; 21 | 22 | fn main() { 23 | App::new() 24 | .add_plugins(DefaultPlugins) 25 | .add_scripting::(|runtime| { 26 | runtime.add_function( 27 | String::from("print_player_names"), 28 | |players: Query<&Name, With>| { 29 | for player in &players { 30 | println!("player name: {}", player); 31 | } 32 | }, 33 | ); 34 | }) 35 | .run(); 36 | } 37 | ``` 38 | 39 | In script: 40 | 41 | ```ruby 42 | print_player_names 43 | ``` 44 | 45 | You can use functions that interact with Bevy entities and resources and 46 | take arguments at the same time. It could be used for example to mutate a 47 | component. 48 | 49 | ```rust,no_run 50 | # extern crate bevy; 51 | # extern crate bevy_ecs; 52 | # extern crate bevy_scriptum; 53 | 54 | use bevy::prelude::*; 55 | use bevy_scriptum::prelude::*; 56 | use bevy_scriptum::runtimes::ruby::prelude::*; 57 | 58 | #[derive(Component)] 59 | struct Player { 60 | health: i32 61 | } 62 | 63 | fn main() { 64 | App::new() 65 | .add_plugins(DefaultPlugins) 66 | .add_scripting::(|runtime| { 67 | runtime.add_function( 68 | String::from("hurt_player"), 69 | |In((hit_value,)): In<(i32,)>, mut players: Query<&mut Player>| { 70 | let mut player = players.single_mut().unwrap(); 71 | player.health -= hit_value; 72 | }, 73 | ); 74 | }) 75 | .run(); 76 | } 77 | ``` 78 | 79 | And it could be called in script like: 80 | 81 | ```ruby 82 | hurt_player(5) 83 | ``` 84 | -------------------------------------------------------------------------------- /book/src/ruby/ruby.md: -------------------------------------------------------------------------------- 1 | # Ruby 2 | 3 | This chapter demonstrates how to work with bevy_scriptum when using Ruby language runtime. 4 | Ruby is currently only supported on Linux. 5 | -------------------------------------------------------------------------------- /book/src/ruby/spawning_scripts.md: -------------------------------------------------------------------------------- 1 | # Spawning scripts 2 | 3 | To spawn a Ruby script you will need to get a handle to a script asset using 4 | bevy's `AssetServer`. 5 | 6 | ```rust 7 | # extern crate bevy; 8 | # extern crate bevy_scriptum; 9 | 10 | use bevy::prelude::*; 11 | use bevy_scriptum::prelude::*; 12 | use bevy_scriptum::runtimes::ruby::prelude::*; 13 | 14 | fn my_spawner(mut commands: Commands, assets_server: Res) { 15 | commands.spawn(Script::::new( 16 | assets_server.load("my_script.rb"), 17 | )); 18 | } 19 | ``` 20 | 21 | After they scripts have been evaled by bevy_scriptum, the entities that they've 22 | been attached to will get the `Script::` component stripped and instead 23 | ```RubyScriptData``` component will be attached. 24 | 25 | So to query scipted entities you could do something like: 26 | 27 | ```rust 28 | # extern crate bevy; 29 | # extern crate bevy_scriptum; 30 | 31 | use bevy::prelude::*; 32 | use bevy_scriptum::prelude::*; 33 | use bevy_scriptum::runtimes::ruby::prelude::*; 34 | 35 | fn my_system( 36 | mut scripted_entities: Query<(Entity, &mut RubyScriptData)>, 37 | ) { 38 | for (entity, mut script_data) in &mut scripted_entities { 39 | // do something with scripted entities 40 | } 41 | } 42 | ``` 43 | -------------------------------------------------------------------------------- /book/src/runtimes.md: -------------------------------------------------------------------------------- 1 | # Runtimes 2 | 3 | This chapter demonstrates how to work with bevy_scriptum when using a specific runtime. 4 | -------------------------------------------------------------------------------- /book/src/workflow/live_reload.md: -------------------------------------------------------------------------------- 1 | # Live-reload 2 | 3 | ## Bevy included support 4 | 5 | To enable live reload it should be enough to enable `file-watcher` feature 6 | within bevy dependency in `Cargo.toml` 7 | 8 | ```toml 9 | bevy = { version = "0.16", features = ["file_watcher"] } 10 | ``` 11 | 12 | ## Init-teardown pattern 13 | 14 | It is useful to structure your application in a way that would allow making changes to 15 | the scripting code without restarting the application. 16 | 17 | A useful pattern is to hava three functions "init", "update" and "teardown". 18 | 19 | - "init" function will take care of starting the application(spawning the player, the level etc) 20 | 21 | - "update" function will run the main application logic 22 | 23 | - "teardown" function will despawn all the entities so application starts at fresh state. 24 | 25 | This pattern is very easy to implement in bevy_scriptum. All you need is to define all needed functions 26 | in script: 27 | 28 | ```lua 29 | player = { 30 | entity = nil 31 | } 32 | 33 | -- spawning all needed entities 34 | local function init() 35 | player.entity = spawn_player() 36 | end 37 | 38 | -- application logic here, should be called in a bevy system using call_fn 39 | local function update() 40 | (...) 41 | end 42 | 43 | -- despawning entities and possible other cleanup logic needed 44 | local function teardown() 45 | despawn(player.entity) 46 | end 47 | 48 | -- call init to start the application, this will be called on each file-watcher script 49 | -- reload 50 | init() 51 | ``` 52 | 53 | The function calls can be implemented on Rust side the following way: 54 | 55 | ```rust 56 | # extern crate bevy; 57 | # extern crate bevy_scriptum; 58 | 59 | use bevy::prelude::*; 60 | use bevy_scriptum::prelude::*; 61 | use bevy_scriptum::runtimes::lua::prelude::*; 62 | use bevy_scriptum::runtimes::lua::BevyVec3; 63 | 64 | fn init(mut commands: Commands, assets_server: Res) { 65 | commands.spawn(Script::::new( 66 | assets_server.load("scripts/game.lua"), 67 | )); 68 | } 69 | 70 | 71 | fn update( 72 | mut scripted_entities: Query<(Entity, &mut LuaScriptData)>, 73 | scripting_runtime: ResMut, 74 | ) { 75 | for (entity, mut script_data) in &mut scripted_entities { 76 | scripting_runtime 77 | .call_fn("update", &mut script_data, entity, ()) 78 | .unwrap(); 79 | } 80 | } 81 | 82 | 83 | fn teardown( 84 | mut ev_asset: EventReader>, 85 | scripting_runtime: ResMut, 86 | mut scripted_entities: Query<(Entity, &mut LuaScriptData)>, 87 | ) { 88 | for event in ev_asset.read() { 89 | if let AssetEvent::Modified { .. } = event { 90 | for (entity, mut script_data) in &mut scripted_entities { 91 | scripting_runtime 92 | .call_fn("teardown", &mut script_data, entity, ()) 93 | .unwrap(); 94 | } 95 | } 96 | } 97 | } 98 | ``` 99 | 100 | And to tie this all together we do the following: 101 | 102 | ```rust,no_run 103 | # extern crate bevy; 104 | # extern crate bevy_scriptum; 105 | 106 | use bevy::prelude::*; 107 | use bevy_scriptum::prelude::*; 108 | use bevy_scriptum::runtimes::lua::prelude::*; 109 | 110 | fn main() { 111 | App::new() 112 | .add_plugins(DefaultPlugins) 113 | .add_scripting::(|builder| { 114 | builder 115 | .add_function(String::from("spawn_player"), spawn_player) 116 | .add_function(String::from("despawn"), despawn); 117 | }) 118 | .add_systems(Startup, init) 119 | .add_systems(Update, (update, teardown)) 120 | .run(); 121 | } 122 | 123 | # fn init() {} 124 | # fn update() {} 125 | # fn despawn() {} 126 | # fn teardown() {} 127 | # fn spawn_player() {} 128 | ``` 129 | 130 | `despawn` can be implemented as: 131 | 132 | ```rust 133 | # extern crate bevy; 134 | # extern crate bevy_scriptum; 135 | 136 | use bevy::prelude::*; 137 | use bevy_scriptum::runtimes::lua::prelude::*; 138 | 139 | fn despawn(In((entity,)): In<(BevyEntity,)>, mut commands: Commands) { 140 | commands.entity(entity.0).despawn(); 141 | } 142 | ``` 143 | 144 | Implementation of `spawn_player` has been left out as an exercise for the reader. 145 | -------------------------------------------------------------------------------- /book/src/workflow/workflow.md: -------------------------------------------------------------------------------- 1 | # Workflow 2 | 3 | Demonstration of useful approaches when working with bevy_scriptum. 4 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | #[cfg(feature = "ruby")] 3 | { 4 | println!("cargo:rustc-link-arg=-rdynamic"); 5 | println!("cargo:rustc-link-arg=-lz"); 6 | println!("cargo:rustc-link-lib=z"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarkonik/bevy_scriptum/fa70abac23b32b70deb76e935819c62998bef1fd/demo.gif -------------------------------------------------------------------------------- /examples/lua/call_function_from_rust.rs: -------------------------------------------------------------------------------- 1 | use bevy::{app::AppExit, prelude::*}; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::lua::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_systems(Startup, startup) 9 | .add_systems(Update, call_lua_on_update_from_rust) 10 | .add_scripting::(|runtime| { 11 | runtime.add_function(String::from("quit"), |mut exit: EventWriter| { 12 | exit.write(AppExit::Success); 13 | }); 14 | }) 15 | .run(); 16 | } 17 | 18 | fn startup(mut commands: Commands, assets_server: Res) { 19 | commands.spawn(Script::::new( 20 | assets_server.load("examples/lua/call_function_from_rust.lua"), 21 | )); 22 | } 23 | 24 | fn call_lua_on_update_from_rust( 25 | mut scripted_entities: Query<(Entity, &mut LuaScriptData)>, 26 | scripting_runtime: ResMut, 27 | ) { 28 | for (entity, mut script_data) in &mut scripted_entities { 29 | scripting_runtime 30 | .call_fn("on_update", &mut script_data, entity, ()) 31 | .unwrap(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /examples/lua/current_entity.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::lua::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|runtime| { 9 | runtime.add_function( 10 | String::from("get_name"), 11 | |In((BevyEntity(entity),)): In<(BevyEntity,)>, names: Query<&Name>| { 12 | names.get(entity).unwrap().to_string() 13 | }, 14 | ); 15 | }) 16 | .add_systems(Startup, startup) 17 | .run(); 18 | } 19 | 20 | fn startup(mut commands: Commands, assets_server: Res) { 21 | commands.spawn(( 22 | Name::from("MyEntityName"), 23 | Script::::new(assets_server.load("examples/lua/current_entity.lua")), 24 | )); 25 | } 26 | -------------------------------------------------------------------------------- /examples/lua/custom_type.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::lua::prelude::*; 4 | use mlua::{UserData, UserDataMethods}; 5 | 6 | fn main() { 7 | App::new() 8 | .add_plugins(DefaultPlugins) 9 | .add_scripting::(|runtime| { 10 | runtime.add_function(String::from("hello_bevy"), || { 11 | println!("hello bevy, called from script"); 12 | }); 13 | }) 14 | .add_systems(Startup, startup) 15 | .run(); 16 | } 17 | 18 | #[derive(Clone)] 19 | struct MyType { 20 | my_field: u32, 21 | } 22 | 23 | impl UserData for MyType {} 24 | 25 | fn startup( 26 | mut commands: Commands, 27 | mut scripting_runtime: ResMut, 28 | assets_server: Res, 29 | ) { 30 | scripting_runtime.with_engine_mut(|engine| { 31 | engine 32 | .register_userdata_type::(|typ| { 33 | // Register a method on MyType 34 | typ.add_method("my_method", |_, my_type_instance: &MyType, ()| { 35 | Ok(my_type_instance.my_field) 36 | }) 37 | }) 38 | .unwrap(); 39 | 40 | // Register a "constructor" for MyType 41 | let my_type_constructor = engine 42 | .create_function(|_, ()| Ok(MyType { my_field: 42 })) 43 | .unwrap(); 44 | engine.globals().set("MyType", my_type_constructor).unwrap(); 45 | }); 46 | 47 | commands.spawn(Script::::new( 48 | assets_server.load("examples/lua/custom_type.lua"), 49 | )); 50 | } 51 | -------------------------------------------------------------------------------- /examples/lua/ecs.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::lua::prelude::*; 4 | 5 | #[derive(Component)] 6 | struct Player; 7 | 8 | fn main() { 9 | App::new() 10 | .add_plugins(DefaultPlugins) 11 | .add_scripting::(|runtime| { 12 | runtime.add_function( 13 | String::from("print_player_names"), 14 | |players: Query<&Name, With>| { 15 | for player in &players { 16 | println!("player name: {}", player); 17 | } 18 | }, 19 | ); 20 | }) 21 | .add_systems(Startup, startup) 22 | .run(); 23 | } 24 | 25 | fn startup(mut commands: Commands, assets_server: Res) { 26 | commands.spawn((Player, Name::new("John"))); 27 | commands.spawn((Player, Name::new("Mary"))); 28 | commands.spawn((Player, Name::new("Alice"))); 29 | 30 | commands.spawn(Script::::new( 31 | assets_server.load("examples/lua/ecs.lua"), 32 | )); 33 | } 34 | -------------------------------------------------------------------------------- /examples/lua/entity_variable.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::runtimes::lua::prelude::*; 3 | use bevy_scriptum::{prelude::*, BuildScriptingRuntime}; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|_| {}) 9 | .add_systems(Startup, startup) 10 | .run(); 11 | } 12 | 13 | fn startup(mut commands: Commands, assets_server: Res) { 14 | commands.spawn(Script::::new( 15 | assets_server.load("examples/lua/entity_variable.lua"), 16 | )); 17 | } 18 | -------------------------------------------------------------------------------- /examples/lua/function_params.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::lua::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|runtime| { 9 | runtime 10 | .add_function(String::from("fun_without_params"), || { 11 | println!("called without params"); 12 | }) 13 | .add_function( 14 | String::from("fun_with_string_param"), 15 | |In((x,)): In<(String,)>| { 16 | println!("called with string: '{}'", x); 17 | }, 18 | ) 19 | .add_function( 20 | String::from("fun_with_i64_param"), 21 | |In((x,)): In<(i64,)>| { 22 | println!("called with i64: {}", x); 23 | }, 24 | ) 25 | .add_function( 26 | String::from("fun_with_multiple_params"), 27 | |In((x, y)): In<(i64, String)>| { 28 | println!("called with i64: {} and string: '{}'", x, y); 29 | }, 30 | ) 31 | .add_function( 32 | String::from("fun_with_i64_and_array_param"), 33 | |In((x, y)): In<(i64, mlua::RegistryKey)>, runtime: Res| { 34 | runtime.with_engine(|engine| { 35 | println!( 36 | "called with i64: {} and dynamically typed array: [{:?}]", 37 | x, 38 | engine 39 | .registry_value::(&y) 40 | .unwrap() 41 | .pairs::() 42 | .map(|pair| pair.unwrap()) 43 | .map(|(_, v)| format!("{:?}", v)) 44 | .collect::>() 45 | .join(",") 46 | ); 47 | }); 48 | }, 49 | ); 50 | }) 51 | .add_systems(Startup, startup) 52 | .run(); 53 | } 54 | 55 | fn startup(mut commands: Commands, assets_server: Res) { 56 | commands.spawn(Script::::new( 57 | assets_server.load("examples/lua/function_params.lua"), 58 | )); 59 | } 60 | -------------------------------------------------------------------------------- /examples/lua/function_return_value.rs: -------------------------------------------------------------------------------- 1 | use bevy::{app::AppExit, prelude::*}; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::lua::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_systems(Startup, startup) 9 | .add_systems(Update, call_lua_on_update_from_rust) 10 | .add_scripting::(|runtime| { 11 | runtime.add_function(String::from("quit"), |mut exit: EventWriter| { 12 | exit.write(AppExit::Success); 13 | }); 14 | }) 15 | .run(); 16 | } 17 | 18 | fn startup(mut commands: Commands, assets_server: Res) { 19 | commands.spawn(Script::::new( 20 | assets_server.load("examples/lua/function_return_value.lua"), 21 | )); 22 | } 23 | 24 | fn call_lua_on_update_from_rust( 25 | mut scripted_entities: Query<(Entity, &mut LuaScriptData)>, 26 | scripting_runtime: ResMut, 27 | mut exit: EventWriter, 28 | ) { 29 | for (entity, mut script_data) in &mut scripted_entities { 30 | let val = scripting_runtime 31 | .call_fn("get_value", &mut script_data, entity, ()) 32 | .unwrap() 33 | .0; 34 | scripting_runtime.with_engine(|engine| { 35 | println!( 36 | "script returned: {}", 37 | engine.registry_value::(&val).unwrap() 38 | ); 39 | }); 40 | exit.write(AppExit::Success); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/lua/hello_world.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::lua::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|runtime| { 9 | runtime.add_function(String::from("hello_bevy"), || { 10 | println!("hello bevy, called from script"); 11 | }); 12 | }) 13 | .add_systems(Startup, startup) 14 | .run(); 15 | } 16 | 17 | fn startup(mut commands: Commands, assets_server: Res) { 18 | commands.spawn(Script::::new( 19 | assets_server.load("examples/lua/hello_world.lua"), 20 | )); 21 | } 22 | -------------------------------------------------------------------------------- /examples/lua/multiple_plugins.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::lua::prelude::*; 4 | 5 | // Plugin A 6 | struct PluginA; 7 | impl Plugin for PluginA { 8 | fn build(&self, app: &mut App) { 9 | app.add_scripting_api::(|runtime| { 10 | runtime.add_function(String::from("hello_from_plugin_a"), || { 11 | info!("Hello from Plugin A"); 12 | }); 13 | }) 14 | .add_systems(Startup, plugin_a_startup); 15 | } 16 | } 17 | 18 | fn plugin_a_startup(mut commands: Commands, assets_server: Res) { 19 | commands.spawn(Script::::new( 20 | assets_server.load("examples/lua/multiple_plugins_plugin_a.lua"), 21 | )); 22 | } 23 | 24 | // Plugin B 25 | struct PluginB; 26 | impl Plugin for PluginB { 27 | fn build(&self, app: &mut App) { 28 | app.add_scripting_api::(|runtime| { 29 | runtime.add_function( 30 | String::from("hello_from_plugin_b_with_parameters"), 31 | hello_from_b, 32 | ); 33 | }) 34 | .add_systems(Startup, plugin_b_startup); 35 | } 36 | } 37 | 38 | fn plugin_b_startup(mut commands: Commands, assets_server: Res) { 39 | commands.spawn(Script::::new( 40 | assets_server.load("examples/lua/multiple_plugins_plugin_b.lua"), 41 | )); 42 | } 43 | 44 | fn hello_from_b(In((text, x)): In<(String, i32)>) { 45 | info!("{} from Plugin B: {}", text, x); 46 | } 47 | 48 | // Main 49 | fn main() { 50 | App::new() 51 | .add_plugins(DefaultPlugins) 52 | .add_scripting::(|runtime| { 53 | runtime.add_function(String::from("hello_bevy"), || { 54 | info!("hello bevy, called from script"); 55 | }); 56 | }) 57 | .add_systems(Startup, main_startup) 58 | .add_plugins(PluginA) 59 | .add_plugins(PluginB) 60 | .run(); 61 | } 62 | 63 | fn main_startup(mut commands: Commands, assets_server: Res) { 64 | commands.spawn(Script::::new( 65 | assets_server.load("examples/lua/hello_world.lua"), 66 | )); 67 | } 68 | -------------------------------------------------------------------------------- /examples/lua/non_closure_system.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::lua::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|runtime| { 9 | runtime.add_function(String::from("hello_bevy"), hello_bevy_callback_system); 10 | }) 11 | .add_systems(Startup, startup) 12 | .run(); 13 | } 14 | 15 | fn startup(mut commands: Commands, assets_server: Res) { 16 | commands.spawn(Script::::new( 17 | assets_server.load("examples/lua/hello_world.lua"), 18 | )); 19 | } 20 | 21 | fn hello_bevy_callback_system() { 22 | println!("hello bevy, called from script"); 23 | } 24 | -------------------------------------------------------------------------------- /examples/lua/promises.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::lua::prelude::*; 4 | 5 | #[derive(Component)] 6 | struct Player; 7 | 8 | fn main() { 9 | App::new() 10 | .add_plugins(DefaultPlugins) 11 | .add_scripting::(|builder| { 12 | builder.add_function( 13 | String::from("get_player_name"), 14 | |player_names: Query<&Name, With>| player_names.single().expect("Missing player_names").to_string(), 15 | ); 16 | }) 17 | .add_systems(Startup, startup) 18 | .run(); 19 | } 20 | 21 | fn startup(mut commands: Commands, assets_server: Res) { 22 | commands.spawn((Player, Name::new("John"))); 23 | commands.spawn(Script::::new( 24 | assets_server.load("examples/lua/promises.lua"), 25 | )); 26 | } 27 | -------------------------------------------------------------------------------- /examples/lua/side_effects.rs: -------------------------------------------------------------------------------- 1 | use bevy::{app::AppExit, prelude::*}; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::lua::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | // This is just needed for headless console app, not needed for a regular bevy application 8 | // that uses a winit window 9 | .set_runner(move |mut app: App| { 10 | loop { 11 | app.update(); 12 | if let Some(exit) = app.should_exit() { 13 | return exit; 14 | } 15 | } 16 | }) 17 | .add_plugins(DefaultPlugins) 18 | .add_systems(Startup, startup) 19 | .add_systems(Update, print_entity_names_and_quit) 20 | .add_scripting::(|runtime| { 21 | runtime.add_function(String::from("spawn_entity"), spawn_entity); 22 | }) 23 | .run(); 24 | } 25 | 26 | fn spawn_entity(mut commands: Commands) { 27 | commands.spawn(Name::new("SpawnedEntity")); 28 | } 29 | 30 | fn startup(mut commands: Commands, assets_server: Res) { 31 | commands.spawn((Script::::new( 32 | assets_server.load("examples/lua/side_effects.lua"), 33 | ),)); 34 | } 35 | 36 | fn print_entity_names_and_quit(query: Query<&Name>, mut exit: EventWriter) { 37 | if !query.is_empty() { 38 | for e in &query { 39 | println!("{}", e); 40 | } 41 | exit.write(AppExit::Success); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /examples/rhai/call_function_from_rust.rs: -------------------------------------------------------------------------------- 1 | use bevy::{app::AppExit, prelude::*}; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::rhai::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_systems(Startup, startup) 9 | .add_systems(Update, call_rhai_on_update_from_rust) 10 | .add_scripting::(|runtime| { 11 | runtime.add_function(String::from("quit"), |mut exit: EventWriter| { 12 | exit.write(AppExit::Success); 13 | }); 14 | }) 15 | .run(); 16 | } 17 | 18 | fn startup(mut commands: Commands, assets_server: Res) { 19 | commands.spawn(Script::::new( 20 | assets_server.load("examples/rhai/call_function_from_rust.rhai"), 21 | )); 22 | } 23 | 24 | fn call_rhai_on_update_from_rust( 25 | mut scripted_entities: Query<(Entity, &mut RhaiScriptData)>, 26 | scripting_runtime: ResMut, 27 | ) { 28 | for (entity, mut script_data) in &mut scripted_entities { 29 | scripting_runtime 30 | .call_fn("on_update", &mut script_data, entity, ()) 31 | .unwrap(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /examples/rhai/current_entity.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::rhai::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|runtime| { 9 | runtime.add_function( 10 | String::from("get_name"), 11 | |In((entity,)): In<(Entity,)>, names: Query<&Name>| { 12 | names.get(entity).unwrap().to_string() 13 | }, 14 | ); 15 | }) 16 | .add_systems(Startup, startup) 17 | .run(); 18 | } 19 | 20 | fn startup(mut commands: Commands, assets_server: Res) { 21 | commands.spawn(( 22 | Name::from("MyEntityName"), 23 | Script::::new(assets_server.load("examples/rhai/current_entity.rhai")), 24 | )); 25 | } 26 | -------------------------------------------------------------------------------- /examples/rhai/custom_type.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::rhai::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|runtime| { 9 | runtime.add_function(String::from("hello_bevy"), || { 10 | println!("hello bevy, called from script"); 11 | }); 12 | }) 13 | .add_systems(Startup, startup) 14 | .run(); 15 | } 16 | 17 | #[derive(Clone)] 18 | struct MyType { 19 | my_field: u32, 20 | } 21 | 22 | fn startup( 23 | mut commands: Commands, 24 | mut scripting_runtime: ResMut, 25 | assets_server: Res, 26 | ) { 27 | scripting_runtime.with_engine_mut(|engine| { 28 | engine 29 | .register_type_with_name::("MyType") 30 | // Register a method on MyType 31 | .register_fn("my_method", |my_type_instance: &mut MyType| { 32 | my_type_instance.my_field 33 | }) 34 | // Register a "constructor" for MyType 35 | .register_fn("new_my_type", || MyType { my_field: 42 }); 36 | }); 37 | 38 | commands.spawn(Script::::new( 39 | assets_server.load("examples/rhai/custom_type.rhai"), 40 | )); 41 | } 42 | -------------------------------------------------------------------------------- /examples/rhai/ecs.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::rhai::prelude::*; 4 | 5 | #[derive(Component)] 6 | struct Player; 7 | 8 | fn main() { 9 | App::new() 10 | .add_plugins(DefaultPlugins) 11 | .add_scripting::(|runtime| { 12 | runtime.add_function( 13 | String::from("print_player_names"), 14 | |players: Query<&Name, With>| { 15 | for player in &players { 16 | println!("player name: {}", player); 17 | } 18 | }, 19 | ); 20 | }) 21 | .add_systems(Startup, startup) 22 | .run(); 23 | } 24 | 25 | fn startup(mut commands: Commands, assets_server: Res) { 26 | commands.spawn((Player, Name::new("John"))); 27 | commands.spawn((Player, Name::new("Mary"))); 28 | commands.spawn((Player, Name::new("Alice"))); 29 | 30 | commands.spawn(Script::::new( 31 | assets_server.load("examples/rhai/ecs.rhai"), 32 | )); 33 | } 34 | -------------------------------------------------------------------------------- /examples/rhai/entity_variable.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::runtimes::rhai::prelude::*; 3 | use bevy_scriptum::{prelude::*, BuildScriptingRuntime}; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|_| {}) 9 | .add_systems(Startup, startup) 10 | .run(); 11 | } 12 | 13 | fn startup(mut commands: Commands, assets_server: Res) { 14 | commands.spawn(Script::::new( 15 | assets_server.load("examples/rhai/entity_variable.rhai"), 16 | )); 17 | } 18 | -------------------------------------------------------------------------------- /examples/rhai/function_params.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::rhai::prelude::*; 4 | use rhai::ImmutableString; 5 | 6 | fn main() { 7 | App::new() 8 | .add_plugins(DefaultPlugins) 9 | .add_scripting::(|runtime| { 10 | runtime 11 | .add_function(String::from("fun_without_params"), || { 12 | println!("called without params"); 13 | }) 14 | .add_function( 15 | String::from("fun_with_string_param"), 16 | |In((x,)): In<(ImmutableString,)>| { 17 | println!("called with string: '{}'", x); 18 | }, 19 | ) 20 | .add_function( 21 | String::from("fun_with_i64_param"), 22 | |In((x,)): In<(i64,)>| { 23 | println!("called with i64: {}", x); 24 | }, 25 | ) 26 | .add_function( 27 | String::from("fun_with_multiple_params"), 28 | |In((x, y)): In<(i64, ImmutableString)>| { 29 | println!("called with i64: {} and string: '{}'", x, y); 30 | }, 31 | ) 32 | .add_function( 33 | String::from("fun_with_i64_and_array_param"), 34 | |In((x, y)): In<(i64, rhai::Array)>| { 35 | println!( 36 | "called with i64: {} and dynamically typed array: '{:?}'", 37 | x, y 38 | ); 39 | }, 40 | ); 41 | }) 42 | .add_systems(Startup, startup) 43 | .run(); 44 | } 45 | 46 | fn startup(mut commands: Commands, assets_server: Res) { 47 | commands.spawn(Script::::new( 48 | assets_server.load("examples/rhai/function_params.rhai"), 49 | )); 50 | } 51 | -------------------------------------------------------------------------------- /examples/rhai/function_return_value.rs: -------------------------------------------------------------------------------- 1 | use bevy::{app::AppExit, prelude::*}; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::rhai::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_systems(Startup, startup) 9 | .add_systems(Update, call_rhai_on_update_from_rust) 10 | .add_scripting::(|runtime| { 11 | runtime.add_function(String::from("quit"), |mut exit: EventWriter| { 12 | exit.write(AppExit::Success); 13 | }); 14 | }) 15 | .run(); 16 | } 17 | 18 | fn startup(mut commands: Commands, assets_server: Res) { 19 | commands.spawn(Script::::new( 20 | assets_server.load("examples/rhai/function_return_value.rhai"), 21 | )); 22 | } 23 | 24 | fn call_rhai_on_update_from_rust( 25 | mut scripted_entities: Query<(Entity, &mut RhaiScriptData)>, 26 | scripting_runtime: ResMut, 27 | mut exit: EventWriter, 28 | ) { 29 | for (entity, mut script_data) in &mut scripted_entities { 30 | let val = scripting_runtime 31 | .call_fn("get_value", &mut script_data, entity, ()) 32 | .unwrap() 33 | .0; 34 | println!("script returned: {}", val); 35 | exit.write(AppExit::Success); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /examples/rhai/hello_world.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::rhai::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|runtime| { 9 | runtime.add_function(String::from("hello_bevy"), || { 10 | println!("hello bevy, called from script"); 11 | }); 12 | }) 13 | .add_systems(Startup, startup) 14 | .run(); 15 | } 16 | 17 | fn startup(mut commands: Commands, assets_server: Res) { 18 | commands.spawn(Script::::new( 19 | assets_server.load("examples/rhai/hello_world.rhai"), 20 | )); 21 | } 22 | -------------------------------------------------------------------------------- /examples/rhai/multiple_plugins.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::rhai::prelude::*; 4 | use rhai::ImmutableString; 5 | 6 | // Plugin A 7 | struct PluginA; 8 | impl Plugin for PluginA { 9 | fn build(&self, app: &mut App) { 10 | app.add_scripting_api::(|runtime| { 11 | runtime.add_function(String::from("hello_from_plugin_a"), || { 12 | info!("Hello from Plugin A"); 13 | }); 14 | }) 15 | .add_systems(Startup, plugin_a_startup); 16 | } 17 | } 18 | 19 | fn plugin_a_startup(mut commands: Commands, assets_server: Res) { 20 | commands.spawn(Script::::new( 21 | assets_server.load("examples/rhai/multiple_plugins_plugin_a.rhai"), 22 | )); 23 | } 24 | 25 | // Plugin B 26 | struct PluginB; 27 | impl Plugin for PluginB { 28 | fn build(&self, app: &mut App) { 29 | app.add_scripting_api::(|runtime| { 30 | runtime.add_function( 31 | String::from("hello_from_plugin_b_with_parameters"), 32 | hello_from_b, 33 | ); 34 | }) 35 | .add_systems(Startup, plugin_b_startup); 36 | } 37 | } 38 | 39 | fn plugin_b_startup(mut commands: Commands, assets_server: Res) { 40 | commands.spawn(Script::::new( 41 | assets_server.load("examples/rhai/multiple_plugins_plugin_b.rhai"), 42 | )); 43 | } 44 | 45 | fn hello_from_b(In((text, x)): In<(ImmutableString, i64)>) { 46 | info!("{} from Plugin B: {}", text, x); 47 | } 48 | 49 | // Main 50 | fn main() { 51 | App::new() 52 | .add_plugins(DefaultPlugins) 53 | .add_scripting::(|runtime| { 54 | runtime.add_function(String::from("hello_bevy"), || { 55 | info!("hello bevy, called from script"); 56 | }); 57 | }) 58 | .add_systems(Startup, main_startup) 59 | .add_plugins(PluginA) 60 | .add_plugins(PluginB) 61 | .run(); 62 | } 63 | 64 | fn main_startup(mut commands: Commands, assets_server: Res) { 65 | commands.spawn(Script::::new( 66 | assets_server.load("examples/rhai/hello_world.rhai"), 67 | )); 68 | } 69 | -------------------------------------------------------------------------------- /examples/rhai/non_closure_system.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::rhai::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|runtime| { 9 | runtime.add_function(String::from("hello_bevy"), hello_bevy_callback_system); 10 | }) 11 | .add_systems(Startup, startup) 12 | .run(); 13 | } 14 | 15 | fn startup(mut commands: Commands, assets_server: Res) { 16 | commands.spawn(Script::::new( 17 | assets_server.load("examples/rhai/hello_world.rhai"), 18 | )); 19 | } 20 | 21 | fn hello_bevy_callback_system() { 22 | println!("hello bevy, called from script"); 23 | } 24 | -------------------------------------------------------------------------------- /examples/rhai/promises.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::rhai::prelude::*; 4 | 5 | #[derive(Component)] 6 | struct Player; 7 | 8 | fn main() { 9 | App::new() 10 | .add_plugins(DefaultPlugins) 11 | .add_scripting::(|builder| { 12 | builder.add_function( 13 | String::from("get_player_name"), 14 | |player_names: Query<&Name, With>| player_names.single().expect("Missing player_names").to_string(), 15 | ); 16 | }) 17 | .add_systems(Startup, startup) 18 | .run(); 19 | } 20 | 21 | fn startup(mut commands: Commands, assets_server: Res) { 22 | commands.spawn((Player, Name::new("John"))); 23 | commands.spawn(Script::::new( 24 | assets_server.load("examples/rhai/promises.rhai"), 25 | )); 26 | } 27 | -------------------------------------------------------------------------------- /examples/rhai/side_effects.rs: -------------------------------------------------------------------------------- 1 | use bevy::{app::AppExit, prelude::*}; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::rhai::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | // This is just needed for headless console app, not needed for a regular bevy application 8 | // that uses a winit window 9 | .set_runner(move |mut app: App| { 10 | loop { 11 | app.update(); 12 | if let Some(exit) = app.should_exit() { 13 | return exit; 14 | } 15 | } 16 | }) 17 | .add_plugins(DefaultPlugins) 18 | .add_systems(Startup, startup) 19 | .add_systems(Update, print_entity_names_and_quit) 20 | .add_scripting::(|runtime| { 21 | runtime.add_function(String::from("spawn_entity"), spawn_entity); 22 | }) 23 | .run(); 24 | } 25 | 26 | fn spawn_entity(mut commands: Commands) { 27 | commands.spawn(Name::new("SpawnedEntity")); 28 | } 29 | 30 | fn startup(mut commands: Commands, assets_server: Res) { 31 | commands.spawn((Script::::new( 32 | assets_server.load("examples/rhai/side_effects.rhai"), 33 | ),)); 34 | } 35 | 36 | fn print_entity_names_and_quit(query: Query<&Name>, mut exit: EventWriter) { 37 | if !query.is_empty() { 38 | for e in &query { 39 | println!("{}", e); 40 | } 41 | exit.write(AppExit::Success); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /examples/ruby/call_function_from_rust.rs: -------------------------------------------------------------------------------- 1 | use bevy::{app::AppExit, prelude::*}; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::ruby::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_systems(Startup, startup) 9 | .add_systems(Update, call_ruby_on_update_from_rust) 10 | .add_scripting::(|runtime| { 11 | runtime.add_function(String::from("quit"), |mut exit: EventWriter| { 12 | exit.write(AppExit::Success); 13 | }); 14 | }) 15 | .run(); 16 | } 17 | 18 | fn startup(mut commands: Commands, assets_server: Res) { 19 | commands.spawn(Script::::new( 20 | assets_server.load("examples/ruby/call_function_from_rust.rb"), 21 | )); 22 | } 23 | 24 | fn call_ruby_on_update_from_rust( 25 | mut scripted_entities: Query<(Entity, &mut RubyScriptData)>, 26 | scripting_runtime: ResMut, 27 | ) { 28 | for (entity, mut script_data) in &mut scripted_entities { 29 | scripting_runtime 30 | .call_fn("on_update", &mut script_data, entity, ()) 31 | .unwrap(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /examples/ruby/current_entity.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::ruby::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|runtime| { 9 | runtime.add_function( 10 | String::from("get_name"), 11 | |In((BevyEntity(entity),)): In<(BevyEntity,)>, names: Query<&Name>| { 12 | names.get(entity).unwrap().to_string() 13 | }, 14 | ); 15 | }) 16 | .add_systems(Startup, startup) 17 | .run(); 18 | } 19 | 20 | fn startup(mut commands: Commands, assets_server: Res) { 21 | commands.spawn(( 22 | Name::from("MyEntityName"), 23 | Script::::new(assets_server.load("examples/ruby/current_entity.rb")), 24 | )); 25 | } 26 | -------------------------------------------------------------------------------- /examples/ruby/custom_type.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::ScriptingError; 3 | use bevy_scriptum::prelude::*; 4 | use bevy_scriptum::runtimes::ruby::magnus; 5 | use bevy_scriptum::runtimes::ruby::magnus::Module as _; 6 | use bevy_scriptum::runtimes::ruby::magnus::Object as _; 7 | use bevy_scriptum::runtimes::ruby::prelude::*; 8 | 9 | fn main() { 10 | App::new() 11 | .add_plugins(DefaultPlugins) 12 | .add_scripting::(|runtime| { 13 | runtime.add_function(String::from("hello_bevy"), || { 14 | println!("hello bevy, called from script"); 15 | }); 16 | }) 17 | .add_systems(Startup, startup) 18 | .run(); 19 | } 20 | 21 | #[magnus::wrap(class = "MyType")] 22 | struct MyType { 23 | my_field: u32, 24 | } 25 | 26 | impl MyType { 27 | fn new() -> Self { 28 | Self { my_field: 42 } 29 | } 30 | 31 | fn my_method(&self) -> u32 { 32 | self.my_field 33 | } 34 | } 35 | 36 | fn startup( 37 | mut commands: Commands, 38 | scripting_runtime: ResMut, 39 | assets_server: Res, 40 | ) { 41 | scripting_runtime 42 | .with_engine_send(|ruby| { 43 | let my_type = ruby.define_class("MyType", ruby.class_object())?; 44 | my_type.define_singleton_method("new", magnus::function!(MyType::new, 0))?; 45 | my_type.define_method("my_method", magnus::method!(MyType::my_method, 0))?; 46 | 47 | Ok::<(), ScriptingError>(()) 48 | }) 49 | .unwrap(); 50 | 51 | commands.spawn(Script::::new( 52 | assets_server.load("examples/ruby/custom_type.rb"), 53 | )); 54 | } 55 | -------------------------------------------------------------------------------- /examples/ruby/ecs.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::ruby::prelude::*; 4 | 5 | #[derive(Component)] 6 | struct Player; 7 | 8 | fn main() { 9 | App::new() 10 | .add_plugins(DefaultPlugins) 11 | .add_scripting::(|runtime| { 12 | runtime.add_function( 13 | String::from("print_player_names"), 14 | |players: Query<&Name, With>| { 15 | for player in &players { 16 | println!("player name: {}", player); 17 | } 18 | }, 19 | ); 20 | }) 21 | .add_systems(Startup, startup) 22 | .run(); 23 | } 24 | 25 | fn startup(mut commands: Commands, assets_server: Res) { 26 | commands.spawn((Player, Name::new("John"))); 27 | commands.spawn((Player, Name::new("Mary"))); 28 | commands.spawn((Player, Name::new("Alice"))); 29 | 30 | commands.spawn(Script::::new( 31 | assets_server.load("examples/ruby/ecs.rb"), 32 | )); 33 | } 34 | -------------------------------------------------------------------------------- /examples/ruby/entity_variable.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::runtimes::ruby::prelude::*; 3 | use bevy_scriptum::{prelude::*, BuildScriptingRuntime}; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|_| {}) 9 | .add_systems(Startup, startup) 10 | .run(); 11 | } 12 | 13 | fn startup(mut commands: Commands, assets_server: Res) { 14 | commands.spawn(Script::::new( 15 | assets_server.load("examples/ruby/entity_variable.rb"), 16 | )); 17 | } 18 | -------------------------------------------------------------------------------- /examples/ruby/function_params.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::ruby::{RArray, prelude::*}; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|runtime| { 9 | runtime 10 | .add_function(String::from("fun_without_params"), || { 11 | println!("called without params"); 12 | }) 13 | .add_function( 14 | String::from("fun_with_string_param"), 15 | |In((x,)): In<(String,)>| { 16 | println!("called with string: '{}'", x); 17 | }, 18 | ) 19 | .add_function( 20 | String::from("fun_with_i64_param"), 21 | |In((x,)): In<(i64,)>| { 22 | println!("called with i64: {}", x); 23 | }, 24 | ) 25 | .add_function( 26 | String::from("fun_with_multiple_params"), 27 | |In((x, y)): In<(i64, String)>| { 28 | println!("called with i64: {} and string: '{}'", x, y); 29 | }, 30 | ) 31 | .add_function( 32 | String::from("fun_with_i64_and_array_param"), 33 | |In((x, y)): In<(i64, RArray)>, runtime: Res| { 34 | runtime.with_engine_send(move |ruby| { 35 | println!( 36 | "called with i64: {} and dynamically typed array: {:?}", 37 | x, 38 | ruby.get_inner(y.0) 39 | ); 40 | }); 41 | }, 42 | ); 43 | }) 44 | .add_systems(Startup, startup) 45 | .run(); 46 | } 47 | 48 | fn startup(mut commands: Commands, assets_server: Res) { 49 | commands.spawn(Script::::new( 50 | assets_server.load("examples/ruby/function_params.rb"), 51 | )); 52 | } 53 | -------------------------------------------------------------------------------- /examples/ruby/function_return_value.rs: -------------------------------------------------------------------------------- 1 | use bevy::{app::AppExit, prelude::*}; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::ruby::prelude::*; 4 | use magnus::TryConvert; 5 | use magnus::value::InnerValue; 6 | 7 | fn main() { 8 | App::new() 9 | .add_plugins(DefaultPlugins) 10 | .add_systems(Startup, startup) 11 | .add_systems(Update, call_lua_on_update_from_rust) 12 | .add_scripting::(|runtime| { 13 | runtime.add_function(String::from("quit"), |mut exit: EventWriter| { 14 | exit.write(AppExit::Success); 15 | }); 16 | }) 17 | .run(); 18 | } 19 | 20 | fn startup(mut commands: Commands, assets_server: Res) { 21 | commands.spawn(Script::::new( 22 | assets_server.load("examples/ruby/function_return_value.rb"), 23 | )); 24 | } 25 | 26 | fn call_lua_on_update_from_rust( 27 | mut scripted_entities: Query<(Entity, &mut RubyScriptData)>, 28 | scripting_runtime: ResMut, 29 | mut exit: EventWriter, 30 | ) { 31 | for (entity, mut script_data) in &mut scripted_entities { 32 | let val = scripting_runtime 33 | .call_fn("get_value", &mut script_data, entity, ()) 34 | .unwrap() 35 | .0; 36 | scripting_runtime.with_engine(|ruby| { 37 | let val: i32 = TryConvert::try_convert(val.get_inner_with(ruby)).unwrap(); 38 | println!("script returned: {}", val); 39 | }); 40 | exit.write(AppExit::Success); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/ruby/hello_world.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::ruby::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins(DefaultPlugins) 8 | .add_scripting::(|runtime| { 9 | runtime.add_function(String::from("hello_bevy"), || { 10 | println!("hello bevy, called from script"); 11 | }); 12 | }) 13 | .add_systems(Startup, startup) 14 | .run(); 15 | } 16 | 17 | fn startup(mut commands: Commands, assets_server: Res) { 18 | commands.spawn(Script::::new( 19 | assets_server.load("examples/ruby/hello_world.rb"), 20 | )); 21 | } 22 | -------------------------------------------------------------------------------- /examples/ruby/multiple_plugins.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::ruby::prelude::*; 4 | 5 | // Plugin A 6 | struct PluginA; 7 | impl Plugin for PluginA { 8 | fn build(&self, app: &mut App) { 9 | app.add_scripting_api::(|runtime| { 10 | runtime.add_function(String::from("hello_from_plugin_a"), || { 11 | info!("Hello from Plugin A"); 12 | }); 13 | }) 14 | .add_systems(Startup, plugin_a_startup); 15 | } 16 | } 17 | 18 | fn plugin_a_startup(mut commands: Commands, assets_server: Res) { 19 | commands.spawn(Script::::new( 20 | assets_server.load("examples/ruby/multiple_plugins_plugin_a.rb"), 21 | )); 22 | } 23 | 24 | // Plugin B 25 | struct PluginB; 26 | impl Plugin for PluginB { 27 | fn build(&self, app: &mut App) { 28 | app.add_scripting_api::(|runtime| { 29 | runtime.add_function( 30 | String::from("hello_from_plugin_b_with_parameters"), 31 | hello_from_b, 32 | ); 33 | }) 34 | .add_systems(Startup, plugin_b_startup); 35 | } 36 | } 37 | 38 | fn plugin_b_startup(mut commands: Commands, assets_server: Res) { 39 | commands.spawn(Script::::new( 40 | assets_server.load("examples/lua/multiple_plugins_plugin_b.lua"), 41 | )); 42 | } 43 | 44 | fn hello_from_b(In((text, x)): In<(String, i32)>) { 45 | info!("{} from Plugin B: {}", text, x); 46 | } 47 | 48 | // Main 49 | fn main() { 50 | App::new() 51 | .add_plugins(DefaultPlugins) 52 | .add_scripting::(|runtime| { 53 | runtime.add_function(String::from("hello_bevy"), || { 54 | info!("hello bevy, called from script"); 55 | }); 56 | }) 57 | .add_systems(Startup, main_startup) 58 | .add_plugins(PluginA) 59 | .add_plugins(PluginB) 60 | .run(); 61 | } 62 | 63 | fn main_startup(mut commands: Commands, assets_server: Res) { 64 | commands.spawn(Script::::new( 65 | assets_server.load("examples/ruby/hello_world.rb"), 66 | )); 67 | } 68 | -------------------------------------------------------------------------------- /examples/ruby/promises.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::ruby::prelude::*; 4 | 5 | #[derive(Component)] 6 | struct Player; 7 | 8 | fn main() { 9 | App::new() 10 | .add_plugins(DefaultPlugins) 11 | .add_scripting::(|builder| { 12 | builder.add_function( 13 | String::from("get_player_name"), 14 | |player_names: Query<&Name, With>| { 15 | player_names 16 | .single() 17 | .expect("Missing player_names") 18 | .to_string() 19 | }, 20 | ); 21 | }) 22 | .add_systems(Startup, startup) 23 | .run(); 24 | } 25 | 26 | fn startup(mut commands: Commands, assets_server: Res) { 27 | commands.spawn((Player, Name::new("John"))); 28 | commands.spawn(Script::::new( 29 | assets_server.load("examples/ruby/promises.rb"), 30 | )); 31 | } 32 | -------------------------------------------------------------------------------- /examples/ruby/side_effects.rs: -------------------------------------------------------------------------------- 1 | use bevy::{app::AppExit, prelude::*}; 2 | use bevy_scriptum::prelude::*; 3 | use bevy_scriptum::runtimes::ruby::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | // This is just needed for headless console app, not needed for a regular bevy application 8 | // that uses a winit window 9 | .set_runner(move |mut app: App| { 10 | loop { 11 | app.update(); 12 | if let Some(exit) = app.should_exit() { 13 | return exit; 14 | } 15 | } 16 | }) 17 | .add_plugins(DefaultPlugins) 18 | .add_systems(Startup, startup) 19 | .add_systems(Update, print_entity_names_and_quit) 20 | .add_scripting::(|runtime| { 21 | runtime.add_function(String::from("spawn_entity"), spawn_entity); 22 | }) 23 | .run(); 24 | } 25 | 26 | fn spawn_entity(mut commands: Commands) { 27 | commands.spawn(Name::new("SpawnedEntity")); 28 | } 29 | 30 | fn startup(mut commands: Commands, assets_server: Res) { 31 | commands.spawn((Script::::new( 32 | assets_server.load("examples/ruby/side_effects.rb"), 33 | ),)); 34 | } 35 | 36 | fn print_entity_names_and_quit(query: Query<&Name>, mut exit: EventWriter) { 37 | if !query.is_empty() { 38 | for e in &query { 39 | println!("{}", e); 40 | } 41 | exit.write(AppExit::Success); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /pull_request_template.md: -------------------------------------------------------------------------------- 1 | Fixes # 2 | 3 | ## Proposed Changes 4 | 5 | - 6 | - 7 | - 8 | -------------------------------------------------------------------------------- /src/assets.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | use bevy::{ 4 | asset::{io::Reader, Asset, AssetLoader, LoadContext}, 5 | tasks::ConditionalSendFuture, 6 | }; 7 | 8 | /// A loader for script assets. 9 | pub struct ScriptLoader> { 10 | _phantom_data: PhantomData, 11 | } 12 | 13 | impl> Default for ScriptLoader { 14 | fn default() -> Self { 15 | Self { 16 | _phantom_data: Default::default(), 17 | } 18 | } 19 | } 20 | 21 | /// Allows providing an allow-list for extensions of AssetLoader for a Script 22 | /// asset 23 | pub trait GetExtensions { 24 | fn extensions() -> &'static [&'static str]; 25 | } 26 | 27 | impl + GetExtensions> AssetLoader for ScriptLoader { 28 | type Asset = A; 29 | type Settings = (); 30 | type Error = anyhow::Error; 31 | 32 | fn load( 33 | &self, 34 | reader: &mut dyn Reader, 35 | _settings: &Self::Settings, 36 | _load_context: &mut LoadContext, 37 | ) -> impl ConditionalSendFuture> { 38 | Box::pin(async move { 39 | let mut bytes = Vec::new(); 40 | reader.read_to_end(&mut bytes).await?; 41 | 42 | let script_text = String::from_utf8(bytes.to_vec())?; 43 | let rhai_script: A = script_text.into(); 44 | Ok(rhai_script) 45 | }) 46 | } 47 | 48 | fn extensions(&self) -> &[&str] { 49 | A::extensions() 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/callback.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use core::any::TypeId; 3 | use std::sync::{Arc, Mutex}; 4 | 5 | use crate::{Runtime, promise::Promise}; 6 | 7 | /// A system that can be used to call a script function. 8 | pub struct CallbackSystem { 9 | pub(crate) system: Box>, Out = R::Value>>, 10 | pub(crate) arg_types: Vec, 11 | } 12 | 13 | pub(crate) struct FunctionCallEvent { 14 | pub(crate) params: Vec, 15 | pub(crate) promise: Promise, 16 | } 17 | 18 | type Calls = Arc>>>; 19 | 20 | /// A struct representing a Bevy system that can be called from a script. 21 | pub(crate) struct Callback { 22 | pub(crate) name: String, 23 | pub(crate) system: Arc>>, 24 | pub(crate) calls: Calls, 25 | } 26 | 27 | impl Clone for Callback { 28 | fn clone(&self) -> Self { 29 | Callback { 30 | name: self.name.clone(), 31 | system: self.system.clone(), 32 | calls: self.calls.clone(), 33 | } 34 | } 35 | } 36 | 37 | impl CallbackSystem { 38 | pub(crate) fn call( 39 | &mut self, 40 | call: &FunctionCallEvent, 41 | world: &mut World, 42 | ) -> R::Value { 43 | self.system.run(call.params.clone(), world) 44 | } 45 | } 46 | 47 | /// Allows converting to a wrapper type that the library uses internally for data 48 | pub(crate) trait IntoRuntimeValueWithEngine<'a, V, R: Runtime> { 49 | fn into_runtime_value_with_engine(value: V, engine: &'a R::RawEngine) -> R::Value; 50 | } 51 | 52 | /// Allows converting from a wrapper type that the library uses internally for data to underlying 53 | /// concrete type. 54 | pub(crate) trait FromRuntimeValueWithEngine<'a, R: Runtime> { 55 | fn from_runtime_value_with_engine(value: R::Value, engine: &'a R::RawEngine) -> Self; 56 | } 57 | 58 | /// Trait that alllows to convert a script callback function into a Bevy [`System`]. 59 | pub trait IntoCallbackSystem: IntoSystem 60 | where 61 | In: SystemInput, 62 | { 63 | /// Convert this function into a [CallbackSystem]. 64 | #[must_use] 65 | fn into_callback_system(self, world: &mut World) -> CallbackSystem; 66 | } 67 | 68 | impl IntoCallbackSystem for FN 69 | where 70 | FN: IntoSystem<(), Out, Marker>, 71 | Out: for<'a> IntoRuntimeValueWithEngine<'a, Out, R>, 72 | { 73 | fn into_callback_system(self, world: &mut World) -> CallbackSystem { 74 | let mut inner_system = IntoSystem::into_system(self); 75 | inner_system.initialize(world); 76 | let system_fn = move |_args: In>, world: &mut World| { 77 | let result = inner_system.run((), world); 78 | inner_system.apply_deferred(world); 79 | let mut runtime = world.get_resource_mut::().expect("No runtime resource"); 80 | 81 | runtime.with_engine_send_mut(move |engine| { 82 | Out::into_runtime_value_with_engine(result, engine) 83 | }) 84 | }; 85 | let system = IntoSystem::into_system(system_fn); 86 | CallbackSystem { 87 | arg_types: vec![], 88 | system: Box::new(system), 89 | } 90 | } 91 | } 92 | 93 | macro_rules! impl_tuple { 94 | ($($idx:tt $t:tt),+) => { 95 | impl IntoCallbackSystem, Out, Marker> 96 | for FN 97 | where 98 | FN: IntoSystem, Out, Marker>, 99 | Out: for<'a> IntoRuntimeValueWithEngine<'a, Out, RN>, 100 | $($t: Send + 'static + for<'a> FromRuntimeValueWithEngine<'a, RN>,)+ 101 | { 102 | fn into_callback_system(self, world: &mut World) -> CallbackSystem { 103 | let mut inner_system = IntoSystem::into_system(self); 104 | inner_system.initialize(world); 105 | let system_fn = move |args: In>, world: &mut World| { 106 | let mut runtime = world.get_resource_mut::().expect("No runtime resource"); 107 | 108 | let args = 109 | runtime.with_engine_send_mut(move |engine| { 110 | ( 111 | $($t::from_runtime_value_with_engine(args.get($idx).expect(&format!("Failed to get function argument for index {}", $idx)).clone(), engine), )+ 112 | ) 113 | }); 114 | 115 | let result = inner_system.run(args, world); 116 | inner_system.apply_deferred(world); 117 | let mut runtime = world.get_resource_mut::().expect("No runtime resource"); 118 | 119 | runtime.with_engine_send_mut(move |engine| { 120 | Out::into_runtime_value_with_engine(result, engine) 121 | }) 122 | }; 123 | let system = IntoSystem::into_system(system_fn); 124 | CallbackSystem { 125 | arg_types: vec![$(TypeId::of::<$t>(),)+], 126 | system: Box::new(system), 127 | } 128 | } 129 | } 130 | }; 131 | } 132 | 133 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V, 22 W, 23 X, 24 Y, 25 Z); 134 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V, 22 W, 23 X, 24 Y); 135 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V, 22 W, 23 X); 136 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V, 22 W); 137 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V); 138 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U); 139 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T); 140 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S); 141 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R); 142 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q); 143 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P); 144 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O); 145 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N); 146 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M); 147 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L); 148 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K); 149 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J); 150 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I); 151 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H); 152 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G); 153 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F); 154 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E); 155 | impl_tuple!(0 A, 1 B, 2 C, 3 D); 156 | impl_tuple!(0 A, 1 B, 2 C); 157 | impl_tuple!(0 A, 1 B); 158 | impl_tuple!(0 A); 159 | -------------------------------------------------------------------------------- /src/components.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | 3 | /// A component that represents a script. 4 | #[derive(Component)] 5 | pub struct Script { 6 | pub script: Handle, 7 | } 8 | 9 | impl Script { 10 | /// Create a new script component from a handle to a [Script] obtained using [AssetServer]. 11 | pub fn new(script: Handle) -> Self { 12 | Self { script } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/promise.rs: -------------------------------------------------------------------------------- 1 | use std::sync::{Arc, Mutex}; 2 | 3 | use crate::{Runtime, ScriptingError}; 4 | 5 | /// A struct that represents a function that will get called when the Promise is resolved. 6 | pub(crate) struct PromiseCallback { 7 | callback: V, 8 | following_promise: Arc>>, 9 | } 10 | 11 | /// Internal representation of a Promise. 12 | pub(crate) struct PromiseInner { 13 | pub(crate) callbacks: Vec>, 14 | #[allow(deprecated)] 15 | pub(crate) context: C, 16 | } 17 | 18 | /// A struct that represents a Promise. 19 | #[derive(Clone)] 20 | pub struct Promise { 21 | pub(crate) inner: Arc>>, 22 | } 23 | 24 | impl PromiseInner { 25 | /// Resolve the Promise. This will call all the callbacks that were added to the Promise. 26 | fn resolve(&mut self, runtime: &mut R, val: R::Value) -> Result<(), ScriptingError> 27 | where 28 | R: Runtime, 29 | { 30 | for callback in &self.callbacks { 31 | let next_val = 32 | runtime.call_fn_from_value(&callback.callback, &self.context, vec![val.clone()])?; 33 | 34 | callback 35 | .following_promise 36 | .lock() 37 | .expect("Failed to lock promise mutex") 38 | .resolve(runtime, next_val)?; 39 | } 40 | Ok(()) 41 | } 42 | } 43 | 44 | impl Promise { 45 | /// Acquire [Mutex] for writing the promise and resolve it. Call will be forwarded to [PromiseInner::resolve]. 46 | pub(crate) fn resolve( 47 | &mut self, 48 | runtime: &mut R, 49 | val: R::Value, 50 | ) -> Result<(), ScriptingError> 51 | where 52 | R: Runtime, 53 | { 54 | if let Ok(mut inner) = self.inner.lock() { 55 | inner.resolve(runtime, val)?; 56 | } 57 | Ok(()) 58 | } 59 | 60 | /// Register a callback that will be called when the [Promise] is resolved. 61 | #[cfg(any(feature = "rhai", feature = "lua", feature = "ruby"))] 62 | pub(crate) fn then(&mut self, callback: V) -> Self { 63 | let mut inner = self 64 | .inner 65 | .lock() 66 | .expect("Failed to lock inner promise mutex"); 67 | let following_inner = Arc::new(Mutex::new(PromiseInner { 68 | callbacks: vec![], 69 | context: inner.context.clone(), 70 | })); 71 | 72 | inner.callbacks.push(PromiseCallback { 73 | following_promise: following_inner.clone(), 74 | callback, 75 | }); 76 | 77 | Promise { 78 | inner: following_inner, 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/runtimes/lua.rs: -------------------------------------------------------------------------------- 1 | use bevy::{ 2 | asset::Asset, 3 | ecs::{component::Component, entity::Entity, resource::Resource, schedule::ScheduleLabel}, 4 | math::Vec3, 5 | reflect::TypePath, 6 | }; 7 | use mlua::{ 8 | FromLua, Function, IntoLua, IntoLuaMulti, Lua, RegistryKey, UserData, UserDataFields, 9 | UserDataMethods, Variadic, 10 | }; 11 | use serde::Deserialize; 12 | use std::sync::{Arc, Mutex}; 13 | 14 | use crate::{ 15 | ENTITY_VAR_NAME, FuncArgs, Runtime, ScriptingError, 16 | assets::GetExtensions, 17 | callback::{FromRuntimeValueWithEngine, IntoRuntimeValueWithEngine}, 18 | promise::Promise, 19 | }; 20 | 21 | type LuaEngine = Arc>; 22 | 23 | #[derive(Clone)] 24 | pub struct LuaValue(pub Arc); 25 | 26 | impl LuaValue { 27 | fn new<'a, T: IntoLua<'a>>(engine: &'a Lua, value: T) -> Self { 28 | Self(Arc::new( 29 | engine 30 | .create_registry_value(value) 31 | .expect("Error creating a registry key for value"), 32 | )) 33 | } 34 | } 35 | 36 | #[derive(Resource)] 37 | pub struct LuaRuntime { 38 | engine: LuaEngine, 39 | } 40 | 41 | #[derive(Debug, Clone, Copy)] 42 | pub struct BevyEntity(pub Entity); 43 | 44 | impl BevyEntity { 45 | pub fn index(&self) -> u32 { 46 | self.0.index() 47 | } 48 | } 49 | 50 | impl UserData for BevyEntity {} 51 | 52 | impl FromLua<'_> for BevyEntity { 53 | fn from_lua( 54 | value: mlua::prelude::LuaValue<'_>, 55 | _lua: &'_ Lua, 56 | ) -> mlua::prelude::LuaResult { 57 | match value { 58 | mlua::Value::UserData(ud) => Ok(*ud.borrow::()?), 59 | _ => panic!("got {:?} instead of BevyEntity", value), 60 | } 61 | } 62 | } 63 | 64 | #[derive(Debug, Clone, Copy)] 65 | pub struct BevyVec3(pub Vec3); 66 | 67 | impl BevyVec3 { 68 | pub fn new(x: f32, y: f32, z: f32) -> Self { 69 | BevyVec3(Vec3 { x, y, z }) 70 | } 71 | 72 | pub fn x(&self) -> f32 { 73 | self.0.x 74 | } 75 | 76 | pub fn y(&self) -> f32 { 77 | self.0.y 78 | } 79 | 80 | pub fn z(&self) -> f32 { 81 | self.0.z 82 | } 83 | } 84 | 85 | impl UserData for BevyVec3 {} 86 | 87 | impl FromLua<'_> for BevyVec3 { 88 | fn from_lua( 89 | value: mlua::prelude::LuaValue<'_>, 90 | _lua: &'_ Lua, 91 | ) -> mlua::prelude::LuaResult { 92 | match value { 93 | mlua::Value::UserData(ud) => Ok(*ud.borrow::()?), 94 | _ => panic!("got {:?} instead of BevyVec3", value), 95 | } 96 | } 97 | } 98 | 99 | impl Default for LuaRuntime { 100 | fn default() -> Self { 101 | let engine = LuaEngine::default(); 102 | 103 | { 104 | let engine = engine.lock().expect("Failed to lock engine"); 105 | engine 106 | .register_userdata_type::(|typ| { 107 | typ.add_field_method_get("index", |_, entity| Ok(entity.0.index())); 108 | }) 109 | .expect("Failed to register BevyEntity userdata type"); 110 | 111 | engine 112 | .register_userdata_type::>(|typ| { 113 | typ.add_method_mut("and_then", |engine, promise, callback: Function| { 114 | Ok(Promise::then(promise, LuaValue::new(engine, callback))) 115 | }); 116 | }) 117 | .expect("Failed to register Promise userdata type"); 118 | 119 | engine 120 | .register_userdata_type::(|typ| { 121 | typ.add_field_method_get("x", |_engine, vec| Ok(vec.0.x)); 122 | typ.add_field_method_get("y", |_engine, vec| Ok(vec.0.y)); 123 | typ.add_field_method_get("z", |_engine, vec| Ok(vec.0.z)); 124 | }) 125 | .expect("Failed to register BevyVec3 userdata type"); 126 | let vec3_constructor = engine 127 | .create_function(|_, (x, y, z)| Ok(BevyVec3(Vec3::new(x, y, z)))) 128 | .expect("Failed to create Vec3 constructor"); 129 | engine 130 | .globals() 131 | .set("Vec3", vec3_constructor) 132 | .expect("Failed to set Vec3 global"); 133 | } 134 | 135 | Self { engine } 136 | } 137 | } 138 | 139 | #[derive(ScheduleLabel, Clone, PartialEq, Eq, Debug, Hash, Default)] 140 | pub struct LuaSchedule; 141 | 142 | #[derive(Asset, Debug, Deserialize, TypePath)] 143 | pub struct LuaScript(pub String); 144 | 145 | impl GetExtensions for LuaScript { 146 | fn extensions() -> &'static [&'static str] { 147 | &["lua"] 148 | } 149 | } 150 | 151 | impl From for LuaScript { 152 | fn from(value: String) -> Self { 153 | Self(value) 154 | } 155 | } 156 | 157 | #[derive(Component)] 158 | pub struct LuaScriptData; 159 | 160 | impl Runtime for LuaRuntime { 161 | type Schedule = LuaSchedule; 162 | 163 | type ScriptAsset = LuaScript; 164 | 165 | type ScriptData = LuaScriptData; 166 | 167 | type CallContext = (); 168 | 169 | type Value = LuaValue; 170 | 171 | type RawEngine = Lua; 172 | 173 | fn eval( 174 | &self, 175 | script: &Self::ScriptAsset, 176 | entity: bevy::prelude::Entity, 177 | ) -> Result { 178 | self.with_engine(|engine| { 179 | engine 180 | .globals() 181 | .set(ENTITY_VAR_NAME, BevyEntity(entity)) 182 | .expect("Error setting entity global variable"); 183 | let result = engine.load(&script.0).exec(); 184 | engine 185 | .globals() 186 | .set(ENTITY_VAR_NAME, mlua::Value::Nil) 187 | .expect("Error clearing entity global variable"); 188 | result 189 | }) 190 | .map_err(|e| ScriptingError::RuntimeError(e.to_string()))?; 191 | Ok(LuaScriptData) 192 | } 193 | 194 | fn register_fn( 195 | &mut self, 196 | name: String, 197 | _arg_types: Vec, 198 | f: impl Fn( 199 | Self::CallContext, 200 | Vec, 201 | ) -> Result< 202 | crate::promise::Promise, 203 | crate::ScriptingError, 204 | > + Send 205 | + Sync 206 | + 'static, 207 | ) -> Result<(), crate::ScriptingError> { 208 | self.with_engine(|engine| { 209 | let func = engine 210 | .create_function(move |engine, args: Variadic| { 211 | let args = { args.into_iter().map(|x| LuaValue::new(engine, x)).collect() }; 212 | let result = f((), args).unwrap(); 213 | Ok(result) 214 | }) 215 | .unwrap(); 216 | engine 217 | .globals() 218 | .set(name, func) 219 | .expect("Error registering function in global lua scope"); 220 | }); 221 | Ok(()) 222 | } 223 | 224 | fn call_fn( 225 | &self, 226 | name: &str, 227 | _script_data: &mut Self::ScriptData, 228 | entity: bevy::prelude::Entity, 229 | args: impl for<'a> FuncArgs<'a, Self::Value, Self>, 230 | ) -> Result { 231 | self.with_engine(|engine| { 232 | engine 233 | .globals() 234 | .set(ENTITY_VAR_NAME, BevyEntity(entity)) 235 | .expect("Error setting entity global variable"); 236 | let func = engine 237 | .globals() 238 | .get::<_, Function>(name) 239 | .map_err(|e| ScriptingError::RuntimeError(e.to_string()))?; 240 | let args = args 241 | .parse(engine) 242 | .into_iter() 243 | .map(|a| engine.registry_value::(&a.0).unwrap()); 244 | let result = func 245 | .call::<_, mlua::Value>(Variadic::from_iter(args)) 246 | .map_err(|e| ScriptingError::RuntimeError(e.to_string()))?; 247 | engine 248 | .globals() 249 | .set(ENTITY_VAR_NAME, mlua::Value::Nil) 250 | .expect("Error clearing entity global variable"); 251 | Ok(LuaValue::new(engine, result)) 252 | }) 253 | } 254 | 255 | fn call_fn_from_value( 256 | &self, 257 | value: &Self::Value, 258 | _context: &Self::CallContext, 259 | args: Vec, 260 | ) -> Result { 261 | self.with_engine(|engine| { 262 | let val = engine 263 | .registry_value::(&value.0) 264 | .map_err(|e| ScriptingError::RuntimeError(e.to_string()))?; 265 | let args = args 266 | .into_iter() 267 | .map(|a| engine.registry_value::(&a.0).unwrap()); 268 | let result = val 269 | .call::<_, mlua::Value>(Variadic::from_iter(args)) 270 | .map_err(|e| ScriptingError::RuntimeError(e.to_string()))?; 271 | Ok(LuaValue::new(engine, result)) 272 | }) 273 | } 274 | 275 | fn with_engine_mut(&mut self, f: impl FnOnce(&mut Self::RawEngine) -> T) -> T { 276 | let mut engine = self.engine.lock().unwrap(); 277 | f(&mut engine) 278 | } 279 | 280 | fn with_engine(&self, f: impl FnOnce(&Self::RawEngine) -> T) -> T { 281 | let engine = self.engine.lock().unwrap(); 282 | f(&engine) 283 | } 284 | 285 | fn with_engine_send_mut( 286 | &mut self, 287 | f: impl FnOnce(&mut Self::RawEngine) -> T + Send + 'static, 288 | ) -> T { 289 | self.with_engine_mut(f) 290 | } 291 | 292 | fn with_engine_send( 293 | &self, 294 | f: impl FnOnce(&Self::RawEngine) -> T + Send + 'static, 295 | ) -> T { 296 | self.with_engine(f) 297 | } 298 | } 299 | 300 | impl<'a, T: IntoLuaMulti<'a>> IntoRuntimeValueWithEngine<'a, T, LuaRuntime> for T { 301 | fn into_runtime_value_with_engine(value: T, engine: &'a Lua) -> LuaValue { 302 | let mut iter = value.into_lua_multi(engine).unwrap().into_iter(); 303 | if iter.len() > 1 { 304 | unimplemented!("Returning multiple values from function"); 305 | } 306 | LuaValue(Arc::new(engine.create_registry_value(iter.next()).unwrap())) 307 | } 308 | } 309 | 310 | impl<'a, T: FromLua<'a>> FromRuntimeValueWithEngine<'a, LuaRuntime> for T { 311 | fn from_runtime_value_with_engine(value: LuaValue, engine: &'a Lua) -> Self { 312 | engine.registry_value(&value.0).unwrap() 313 | } 314 | } 315 | 316 | impl FuncArgs<'_, LuaValue, LuaRuntime> for () { 317 | fn parse(self, _engine: &Lua) -> Vec { 318 | Vec::new() 319 | } 320 | } 321 | 322 | impl<'a, T: IntoLua<'a>> FuncArgs<'a, LuaValue, LuaRuntime> for Vec { 323 | fn parse(self, engine: &'a Lua) -> Vec { 324 | self.into_iter().map(|x| LuaValue::new(engine, x)).collect() 325 | } 326 | } 327 | 328 | impl UserData for Promise<(), LuaValue> {} 329 | 330 | pub mod prelude { 331 | pub use super::{BevyEntity, BevyVec3, LuaRuntime, LuaScript, LuaScriptData}; 332 | } 333 | 334 | macro_rules! impl_tuple { 335 | ($($idx:tt $t:tt),+) => { 336 | impl<'a, $($t: IntoLua<'a>,)+> FuncArgs<'a, LuaValue, LuaRuntime> 337 | for ($($t,)+) 338 | { 339 | fn parse(self, engine: &'a Lua) -> Vec { 340 | vec![ 341 | $(LuaValue::new(engine, self.$idx), )+ 342 | ] 343 | } 344 | } 345 | }; 346 | } 347 | 348 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V, 22 W, 23 X, 24 Y, 25 Z); 349 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V, 22 W, 23 X, 24 Y); 350 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V, 22 W, 23 X); 351 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V, 22 W); 352 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V); 353 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U); 354 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T); 355 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S); 356 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R); 357 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q); 358 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P); 359 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O); 360 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N); 361 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M); 362 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L); 363 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K); 364 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J); 365 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I); 366 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H); 367 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G); 368 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F); 369 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E); 370 | impl_tuple!(0 A, 1 B, 2 C, 3 D); 371 | impl_tuple!(0 A, 1 B, 2 C); 372 | impl_tuple!(0 A, 1 B); 373 | impl_tuple!(0 A); 374 | -------------------------------------------------------------------------------- /src/runtimes/mod.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "lua")] 2 | pub mod lua; 3 | #[cfg(feature = "rhai")] 4 | pub mod rhai; 5 | #[cfg(feature = "ruby")] 6 | pub mod ruby; 7 | -------------------------------------------------------------------------------- /src/runtimes/rhai.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Debug; 2 | 3 | use bevy::{ 4 | asset::Asset, 5 | ecs::{component::Component, entity::Entity, resource::Resource, schedule::ScheduleLabel}, 6 | math::Vec3, 7 | reflect::TypePath, 8 | }; 9 | use rhai::{CallFnOptions, Dynamic, Engine, FnPtr, Scope, Variant}; 10 | use serde::Deserialize; 11 | 12 | use crate::{ 13 | ENTITY_VAR_NAME, FuncArgs, Runtime, ScriptingError, 14 | assets::GetExtensions, 15 | callback::{FromRuntimeValueWithEngine, IntoRuntimeValueWithEngine}, 16 | promise::Promise, 17 | }; 18 | 19 | #[derive(Asset, Debug, Deserialize, TypePath)] 20 | pub struct RhaiScript(pub String); 21 | 22 | impl GetExtensions for RhaiScript { 23 | fn extensions() -> &'static [&'static str] { 24 | &["rhai"] 25 | } 26 | } 27 | 28 | impl From for RhaiScript { 29 | fn from(value: String) -> Self { 30 | Self(value) 31 | } 32 | } 33 | 34 | #[derive(Resource)] 35 | pub struct RhaiRuntime { 36 | engine: rhai::Engine, 37 | } 38 | 39 | #[derive(ScheduleLabel, Clone, PartialEq, Eq, Debug, Hash, Default)] 40 | pub struct RhaiSchedule; 41 | 42 | /// A component that represents the data of a script. It stores the [rhai::Scope](basically the state of the script, any declared variable etc.) 43 | /// and [rhai::AST] which is a cached AST representation of the script. 44 | #[derive(Component)] 45 | pub struct RhaiScriptData { 46 | pub scope: rhai::Scope<'static>, 47 | pub(crate) ast: rhai::AST, 48 | } 49 | 50 | #[derive(Debug, Clone)] 51 | pub struct RhaiValue(pub rhai::Dynamic); 52 | 53 | #[derive(Clone)] 54 | pub struct BevyEntity(pub Entity); 55 | 56 | impl BevyEntity { 57 | pub fn index(&self) -> u32 { 58 | self.0.index() 59 | } 60 | } 61 | 62 | #[derive(Clone)] 63 | pub struct BevyVec3(pub Vec3); 64 | 65 | impl BevyVec3 { 66 | pub fn new(x: f32, y: f32, z: f32) -> Self { 67 | Self(Vec3::new(x, y, z)) 68 | } 69 | 70 | pub fn x(&self) -> f32 { 71 | self.0.x 72 | } 73 | 74 | pub fn y(&self) -> f32 { 75 | self.0.y 76 | } 77 | 78 | pub fn z(&self) -> f32 { 79 | self.0.z 80 | } 81 | } 82 | 83 | impl Runtime for RhaiRuntime { 84 | type Schedule = RhaiSchedule; 85 | type ScriptAsset = RhaiScript; 86 | type ScriptData = RhaiScriptData; 87 | #[allow(deprecated)] 88 | type CallContext = rhai::NativeCallContextStore; 89 | type Value = RhaiValue; 90 | type RawEngine = rhai::Engine; 91 | 92 | fn eval( 93 | &self, 94 | script: &Self::ScriptAsset, 95 | entity: Entity, 96 | ) -> Result { 97 | let mut scope = Scope::new(); 98 | scope.push(ENTITY_VAR_NAME, BevyEntity(entity)); 99 | 100 | let engine = &self.engine; 101 | 102 | let ast = engine 103 | .compile_with_scope(&scope, script.0.as_str()) 104 | .map_err(|e| ScriptingError::CompileError(Box::new(e)))?; 105 | 106 | engine 107 | .run_ast_with_scope(&mut scope, &ast) 108 | .map_err(|e| ScriptingError::RuntimeError(e.to_string()))?; 109 | 110 | scope.remove::(ENTITY_VAR_NAME).unwrap(); 111 | 112 | Ok(Self::ScriptData { ast, scope }) 113 | } 114 | 115 | fn register_fn( 116 | &mut self, 117 | name: String, 118 | arg_types: Vec, 119 | f: impl Fn( 120 | Self::CallContext, 121 | Vec, 122 | ) -> Result, ScriptingError> 123 | + Send 124 | + Sync 125 | + 'static, 126 | ) -> Result<(), ScriptingError> { 127 | self.engine 128 | .register_raw_fn(name, arg_types, move |context, args| { 129 | let args = args.iter_mut().map(|arg| RhaiValue(arg.clone())).collect(); 130 | #[allow(deprecated)] 131 | let promise = f(context.store_data(), args).unwrap(); 132 | Ok(promise) 133 | }); 134 | Ok(()) 135 | } 136 | 137 | fn call_fn( 138 | &self, 139 | name: &str, 140 | script_data: &mut Self::ScriptData, 141 | entity: Entity, 142 | args: impl for<'a> FuncArgs<'a, Self::Value, Self>, 143 | ) -> Result { 144 | let ast = script_data.ast.clone(); 145 | let scope = &mut script_data.scope; 146 | scope.push(ENTITY_VAR_NAME, BevyEntity(entity)); 147 | let options = CallFnOptions::new().eval_ast(false); 148 | let args = args 149 | .parse(&self.engine) 150 | .into_iter() 151 | .map(|a| a.0) 152 | .collect::>(); 153 | let result = self 154 | .engine 155 | .call_fn_with_options::(options, scope, &ast, name, args); 156 | scope.remove::(ENTITY_VAR_NAME).unwrap(); 157 | match result { 158 | Ok(val) => Ok(RhaiValue(val)), 159 | Err(e) => Err(ScriptingError::RuntimeError(e.to_string())), 160 | } 161 | } 162 | 163 | fn call_fn_from_value( 164 | &self, 165 | value: &Self::Value, 166 | context: &Self::CallContext, 167 | args: Vec, 168 | ) -> Result { 169 | let f = value.0.clone_cast::(); 170 | 171 | #[allow(deprecated)] 172 | let ctx = &context.create_context(&self.engine); 173 | 174 | let result = if args.len() == 1 && args.first().unwrap().0.is_unit() { 175 | f.call_raw(ctx, None, []) 176 | .map_err(|e| ScriptingError::RuntimeError(e.to_string()))? 177 | } else { 178 | let args = args.into_iter().map(|a| a.0).collect::>(); 179 | f.call_raw(ctx, None, args) 180 | .map_err(|e| ScriptingError::RuntimeError(e.to_string()))? 181 | }; 182 | 183 | Ok(RhaiValue(result)) 184 | } 185 | 186 | fn with_engine_mut(&mut self, f: impl FnOnce(&mut Self::RawEngine) -> T) -> T { 187 | f(&mut self.engine) 188 | } 189 | 190 | fn with_engine(&self, f: impl FnOnce(&Self::RawEngine) -> T) -> T { 191 | f(&self.engine) 192 | } 193 | 194 | fn with_engine_send_mut( 195 | &mut self, 196 | f: impl FnOnce(&mut Self::RawEngine) -> T + Send + 'static, 197 | ) -> T { 198 | self.with_engine_mut(f) 199 | } 200 | 201 | fn with_engine_send( 202 | &self, 203 | f: impl FnOnce(&Self::RawEngine) -> T + Send + 'static, 204 | ) -> T { 205 | self.with_engine(f) 206 | } 207 | } 208 | 209 | impl Default for RhaiRuntime { 210 | fn default() -> Self { 211 | let mut engine = Engine::new(); 212 | 213 | engine 214 | .register_type_with_name::("Entity") 215 | .register_get("index", |entity: &mut BevyEntity| entity.index()); 216 | #[allow(deprecated)] 217 | engine 218 | .register_type_with_name::>("Promise") 219 | .register_fn( 220 | "then", 221 | |promise: &mut Promise, 222 | callback: rhai::Dynamic| { 223 | Promise::then(promise, RhaiValue(callback)); 224 | }, 225 | ); 226 | 227 | engine 228 | .register_type_with_name::("Vec3") 229 | .register_fn("new_vec3", |x: f64, y: f64, z: f64| { 230 | BevyVec3(Vec3::new(x as f32, y as f32, z as f32)) 231 | }) 232 | .register_get("x", |vec: &mut BevyVec3| vec.x() as f64) 233 | .register_get("y", |vec: &mut BevyVec3| vec.y() as f64) 234 | .register_get("z", |vec: &mut BevyVec3| vec.z() as f64); 235 | #[allow(deprecated)] 236 | engine.on_def_var(|_, info, _| Ok(info.name != "entity")); 237 | 238 | RhaiRuntime { engine } 239 | } 240 | } 241 | 242 | impl<'a, T: Clone + Variant> IntoRuntimeValueWithEngine<'a, T, RhaiRuntime> for T { 243 | fn into_runtime_value_with_engine(value: T, _engine: &'a rhai::Engine) -> RhaiValue { 244 | RhaiValue(Dynamic::from(value)) 245 | } 246 | } 247 | 248 | impl FuncArgs<'_, RhaiValue, RhaiRuntime> for () { 249 | fn parse(self, _engnie: &rhai::Engine) -> Vec { 250 | Vec::new() 251 | } 252 | } 253 | impl FuncArgs<'_, RhaiValue, RhaiRuntime> for Vec { 254 | fn parse(self, _engine: &rhai::Engine) -> Vec { 255 | self.into_iter() 256 | .map(|v| RhaiValue(Dynamic::from(v))) 257 | .collect() 258 | } 259 | } 260 | 261 | impl FromRuntimeValueWithEngine<'_, RhaiRuntime> for T { 262 | fn from_runtime_value_with_engine(value: RhaiValue, _engine: &rhai::Engine) -> Self { 263 | value.0.clone_cast() 264 | } 265 | } 266 | 267 | pub mod prelude { 268 | pub use super::{BevyEntity, BevyVec3, RhaiRuntime, RhaiScript, RhaiScriptData}; 269 | } 270 | 271 | macro_rules! impl_tuple { 272 | ($($idx:tt $t:tt),+) => { 273 | impl<$($t: Clone +Variant,)+> FuncArgs<'_, RhaiValue, RhaiRuntime> 274 | for ($($t,)+) 275 | { 276 | fn parse(self, _engine: &rhai::Engine) -> Vec { 277 | vec![ 278 | $(RhaiValue(Dynamic::from(self.$idx)), )+ 279 | ] 280 | } 281 | } 282 | }; 283 | } 284 | 285 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V, 22 W, 23 X, 24 Y, 25 Z); 286 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V, 22 W, 23 X, 24 Y); 287 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V, 22 W, 23 X); 288 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V, 22 W); 289 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U, 21 V); 290 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T, 20 U); 291 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S, 19 T); 292 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R, 18 S); 293 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q, 17 R); 294 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P, 16 Q); 295 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O, 15 P); 296 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N, 14 O); 297 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M, 13 N); 298 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L, 12 M); 299 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K, 11 L); 300 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J, 10 K); 301 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I, 9 J); 302 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H, 8 I); 303 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H); 304 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G); 305 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F); 306 | impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E); 307 | impl_tuple!(0 A, 1 B, 2 C, 3 D); 308 | impl_tuple!(0 A, 1 B, 2 C); 309 | impl_tuple!(0 A, 1 B); 310 | impl_tuple!(0 A); 311 | -------------------------------------------------------------------------------- /src/systems.rs: -------------------------------------------------------------------------------- 1 | use bevy::{log::tracing, prelude::*}; 2 | use std::{ 3 | fmt::Display, 4 | sync::{Arc, Mutex}, 5 | }; 6 | 7 | use crate::{ 8 | Callback, Callbacks, Runtime, ScriptingError, 9 | callback::FunctionCallEvent, 10 | promise::{Promise, PromiseInner}, 11 | }; 12 | 13 | use super::components::Script; 14 | 15 | /// Reloads scripts when they are modified. 16 | pub(crate) fn reload_scripts( 17 | mut commands: Commands, 18 | mut ev_asset: EventReader>, 19 | mut scripts: Query<(Entity, &mut Script)>, 20 | ) { 21 | for ev in ev_asset.read() { 22 | if let AssetEvent::Modified { id } = ev { 23 | for (entity, script) in &mut scripts { 24 | if script.script.id() == *id { 25 | commands.entity(entity).remove::(); 26 | } 27 | } 28 | } 29 | } 30 | } 31 | 32 | /// Processes new scripts. Evaluates them and stores the script data in the entity. 33 | #[allow(clippy::type_complexity)] 34 | pub(crate) fn process_new_scripts( 35 | mut commands: Commands, 36 | mut added_scripted_entities: Query< 37 | (Entity, &mut Script), 38 | Without, 39 | >, 40 | scripting_runtime: ResMut, 41 | scripts: Res>, 42 | asset_server: Res, 43 | ) -> Result<(), ScriptingError> { 44 | for (entity, script_component) in &mut added_scripted_entities { 45 | tracing::trace!("evaulating a new script"); 46 | if let Some(script) = scripts.get(&script_component.script) { 47 | match scripting_runtime.eval(script, entity) { 48 | Ok(script_data) => { 49 | commands.entity(entity).insert(script_data); 50 | } 51 | Err(e) => { 52 | let path = asset_server 53 | .get_path(&script_component.script) 54 | .unwrap_or_default(); 55 | tracing::error!("error running script {} {}", path, e); 56 | } 57 | } 58 | } 59 | } 60 | Ok(()) 61 | } 62 | 63 | /// Initializes callbacks. Registers them in the scripting engine. 64 | pub(crate) fn init_callbacks(world: &mut World) -> Result<(), ScriptingError> { 65 | let mut callbacks_resource = world 66 | .get_resource_mut::>() 67 | .ok_or(ScriptingError::NoSettingsResource)?; 68 | 69 | let mut callbacks = callbacks_resource 70 | .uninitialized_callbacks 71 | .drain(..) 72 | .collect::>>(); 73 | 74 | for callback in callbacks.iter_mut() { 75 | if let Ok(mut system) = callback.system.lock() { 76 | system.system.initialize(world); 77 | 78 | let mut scripting_runtime = world 79 | .get_resource_mut::() 80 | .ok_or(ScriptingError::NoRuntimeResource)?; 81 | 82 | tracing::trace!("init_callbacks: registering callback: '{}'", callback.name); 83 | 84 | let callback = callback.clone(); 85 | 86 | let result = scripting_runtime.register_fn( 87 | callback.name, 88 | system.arg_types.clone(), 89 | move |context, params| { 90 | let promise = Promise { 91 | inner: Arc::new(Mutex::new(PromiseInner { 92 | callbacks: vec![], 93 | context, 94 | })), 95 | }; 96 | 97 | let mut calls = callback 98 | .calls 99 | .lock() 100 | .expect("Failed to lock callback calls mutex"); 101 | 102 | calls.push(FunctionCallEvent { 103 | promise: promise.clone(), 104 | params, 105 | }); 106 | Ok(promise) 107 | }, 108 | ); 109 | if let Err(e) = result { 110 | tracing::error!("error registering function: {}", e); 111 | } 112 | } 113 | } 114 | 115 | let callbacks_resource = world 116 | .get_resource_mut::>() 117 | .ok_or(ScriptingError::NoSettingsResource)?; 118 | callbacks_resource 119 | .callbacks 120 | .lock() 121 | .expect("Failed to lock callbacks mutex") 122 | .append(&mut callbacks.clone()); 123 | 124 | Ok(()) 125 | } 126 | 127 | /// Processes calls. Calls the user-defined callback systems 128 | pub(crate) fn process_calls(world: &mut World) -> Result<(), ScriptingError> { 129 | let callbacks_resource = world 130 | .get_resource::>() 131 | .ok_or(ScriptingError::NoSettingsResource)?; 132 | 133 | let callbacks = callbacks_resource 134 | .callbacks 135 | .lock() 136 | .expect("Failed to lock callbacks mutex") 137 | .clone(); 138 | 139 | for callback in callbacks.into_iter() { 140 | let calls = callback 141 | .calls 142 | .lock() 143 | .expect("Failed to lock callback calls mutex") 144 | .drain(..) 145 | .collect::>>(); 146 | for mut call in calls { 147 | tracing::trace!("process_calls: calling '{}'", callback.name); 148 | let mut system = callback 149 | .system 150 | .lock() 151 | .expect("Failed to lock callback system mutex"); 152 | let val = system.call(&call, world); 153 | let mut runtime = world 154 | .get_resource_mut::() 155 | .ok_or(ScriptingError::NoRuntimeResource)?; 156 | 157 | let result = call.promise.resolve(runtime.as_mut(), val); 158 | match result { 159 | Ok(_) => {} 160 | Err(e) => { 161 | tracing::error!("error resolving call: {} {}", callback.name, e); 162 | } 163 | } 164 | } 165 | } 166 | Ok(()) 167 | } 168 | 169 | /// Error logging system 170 | pub fn log_errors(In(res): In>) { 171 | if let Err(error) = res { 172 | tracing::error!("{}", error); 173 | } 174 | } 175 | --------------------------------------------------------------------------------