├── .github ├── dependabot.yml └── workflows │ ├── dependencies.yml │ └── main.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── assets ├── LICENSE └── NotoEmoji-Regular.ttf ├── codecov.yml ├── deny.toml ├── examples ├── authoritative_rts.rs ├── deterministic_boids.rs ├── simple_button.rs └── tic_tac_toe.rs ├── src ├── client.rs ├── lib.rs └── server.rs └── tests └── netcode.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: / 5 | schedule: 6 | interval: weekly 7 | labels: 8 | - "dependencies" 9 | - package-ecosystem: github-actions 10 | directory: / 11 | schedule: 12 | interval: weekly 13 | labels: 14 | - "github actions" 15 | -------------------------------------------------------------------------------- /.github/workflows/dependencies.yml: -------------------------------------------------------------------------------- 1 | name: Dependencies 2 | on: 3 | push: 4 | branches: 5 | - master 6 | paths: 7 | - "Cargo.toml" 8 | - "Cargo.lock" 9 | - "deny.toml" 10 | pull_request: 11 | paths: 12 | - "Cargo.toml" 13 | - "Cargo.lock" 14 | - "deny.toml" 15 | schedule: 16 | - cron: "0 0 * * 0" 17 | env: 18 | CARGO_TERM_COLOR: always 19 | jobs: 20 | dependencies: 21 | name: Check dependencies 22 | runs-on: ubuntu-latest 23 | steps: 24 | - name: Clone repo 25 | uses: actions/checkout@v5 26 | 27 | - name: Check dependencies 28 | uses: EmbarkStudios/cargo-deny-action@v2 29 | with: 30 | command-arguments: -D warnings 31 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Main 2 | on: 3 | push: 4 | branches: 5 | - master 6 | paths-ignore: 7 | - ".gitignore" 8 | - ".github/dependabot.yml" 9 | - "deny.toml" 10 | pull_request: 11 | paths-ignore: 12 | - ".gitignore" 13 | - ".github/dependabot.yml" 14 | - "deny.toml" 15 | env: 16 | CARGO_TERM_COLOR: always 17 | jobs: 18 | typos: 19 | name: Typos 20 | runs-on: ubuntu-latest 21 | steps: 22 | - name: Clone repo 23 | uses: actions/checkout@v5 24 | 25 | - name: Check typos 26 | uses: crate-ci/typos@v1.38.0 27 | 28 | format: 29 | name: Format 30 | runs-on: ubuntu-latest 31 | steps: 32 | - name: Clone repo 33 | uses: actions/checkout@v5 34 | 35 | - name: Cache crates 36 | uses: Swatinem/rust-cache@v2 37 | 38 | - name: Install Taplo 39 | run: cargo install --locked taplo-cli 40 | 41 | - name: Format 42 | run: | 43 | cargo fmt --all --check 44 | taplo fmt --check 45 | 46 | lint: 47 | name: Lint 48 | runs-on: ubuntu-latest 49 | steps: 50 | - name: Clone repo 51 | uses: actions/checkout@v5 52 | 53 | - name: Instal stable toolchain 54 | uses: dtolnay/rust-toolchain@stable 55 | with: 56 | components: clippy 57 | 58 | - name: Cache crates 59 | uses: Swatinem/rust-cache@v2 60 | 61 | - name: Clippy 62 | run: cargo clippy --tests --examples -- -D warnings 63 | 64 | - name: Rustdoc 65 | run: cargo rustdoc -- -D warnings 66 | 67 | doctest: 68 | name: Doctest 69 | runs-on: ubuntu-latest 70 | steps: 71 | - name: Clone repo 72 | uses: actions/checkout@v5 73 | 74 | - name: Instal stable toolchain 75 | uses: dtolnay/rust-toolchain@stable 76 | 77 | - name: Cache crates 78 | uses: Swatinem/rust-cache@v2 79 | 80 | - name: Test doc 81 | run: cargo test --doc 82 | 83 | feature-combinations: 84 | name: Feature combinations 85 | runs-on: ubuntu-latest 86 | steps: 87 | - name: Clone repo 88 | uses: actions/checkout@v5 89 | 90 | - name: Instal stable toolchain 91 | uses: dtolnay/rust-toolchain@stable 92 | 93 | - name: Cache crates 94 | uses: Swatinem/rust-cache@v2 95 | 96 | - name: Install Cargo Hack 97 | run: cargo install cargo-hack 98 | 99 | - name: Check feature combinations 100 | run: cargo hack check --feature-powerset 101 | env: 102 | RUSTFLAGS: -Aunused -Dwarnings 103 | 104 | test: 105 | name: Test 106 | runs-on: ubuntu-latest 107 | steps: 108 | - name: Clone repo 109 | uses: actions/checkout@v5 110 | 111 | - name: Instal stable toolchain 112 | uses: dtolnay/rust-toolchain@stable 113 | 114 | - name: Cache crates 115 | uses: Swatinem/rust-cache@v2 116 | 117 | - name: Install LLVM tools 118 | run: rustup component add llvm-tools-preview 119 | 120 | - name: Install Tarpaulin 121 | run: cargo install cargo-tarpaulin 122 | 123 | - name: Test 124 | run: cargo tarpaulin --engine llvm --out lcov 125 | 126 | - name: Upload code coverage results 127 | if: github.actor != 'dependabot[bot]' 128 | uses: actions/upload-artifact@v4 129 | with: 130 | name: code-coverage-report 131 | path: lcov.info 132 | 133 | codecov: 134 | name: Upload to Codecov 135 | if: github.actor != 'dependabot[bot]' 136 | needs: [typos, format, lint, doctest, feature-combinations, test] 137 | runs-on: ubuntu-latest 138 | steps: 139 | - name: Clone repo 140 | uses: actions/checkout@v5 141 | 142 | - name: Download code coverage results 143 | uses: actions/download-artifact@v5 144 | with: 145 | name: code-coverage-report 146 | 147 | - name: Upload to Codecov 148 | uses: codecov/codecov-action@v5 149 | with: 150 | token: ${{ secrets.CODECOV_TOKEN }} 151 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries 2 | target 3 | 4 | # Neovim 5 | neovim.json 6 | 7 | # Code coverage 8 | html 9 | 10 | # For library 11 | Cargo.lock 12 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | ## [0.11.2] - 2025-10-05 11 | 12 | ### Fixed 13 | 14 | - Handle jumping between `ClientState::Connected` states. 15 | 16 | ## [0.11.1] - 2025-10-04 17 | 18 | ### Fixed 19 | 20 | - Handle transports that immediately jump into the connected state. 21 | 22 | ## [0.11.0] - 2025-09-26 23 | 24 | ### Changed 25 | 26 | - Update to `bevy_replicon` 0.35. 27 | 28 | ## [0.10.0] - 2025-08-11 29 | 30 | ### Changed 31 | 32 | - Update to `bevy_replicon` 0.34. 33 | - Update to `bevy_renet` 2.0.0. 34 | - Trigger disconnect when entities with `ConnectedClient` are despawned. 35 | 36 | ## [0.9.0] - 2025-03-24 37 | 38 | ### Changed 39 | 40 | - Update to `bevy_replicon` 0.32. 41 | - Rename `RenetChannelsExt::get_server_configs` into `RenetChannelsExt::server_configs`. 42 | - Rename `RenetChannelsExt::get_client_configs` into `RenetChannelsExt::client_configs`. 43 | 44 | ## [0.8.0] - 2025-03-13 45 | 46 | ### Changed 47 | 48 | - Update to `bevy_replicon` 0.31. 49 | 50 | ## [0.7.0] - 2025-02-04 51 | 52 | ### Changed 53 | 54 | - Update to `bevy_replicon` 0.30. 55 | - `bevy_replicon_renet::client::RepliconRenetClientPlugin` now should be imported as `bevy_replicon_renet::RepliconRenetClientPlugin`. 56 | - `bevy_replicon_renet::server::RepliconRenetServerPlugin` now should be imported as `bevy_replicon_renet::RepliconRenetServerPlugin`. 57 | 58 | ## [0.6.0] - 2024-12-25 59 | 60 | ### Changed 61 | 62 | - Update to `bevy_replicon` 0.29 and `renet` 1.0.0. 63 | 64 | ## [0.5.1] - 2024-11-29 65 | 66 | ### Added 67 | 68 | - Extension traits for conversion between Renet's and Replicon's `ClientId`s. 69 | 70 | ## [0.5.0] - 2024-09-04 71 | 72 | ### Changed 73 | 74 | - Update to `bevy_replicon` 0.28. 75 | 76 | ## [0.4.0] - 2024-07-21 77 | 78 | ### Added 79 | 80 | - `server` and `client` features to disable unneeded functionality. 81 | 82 | ### Changed 83 | 84 | - Update to `bevy_replicon` 0.27. 85 | - Move to a dedicated repository. 86 | - Move `RepliconRenetServerPlugin` to `server` module. 87 | - Move `RepliconRenetClientPlugin` to `client` module. 88 | 89 | ## [0.3.0] - 2024-05-26 90 | 91 | ### Changed 92 | 93 | - Update to `bevy_replicon` 0.26. 94 | 95 | ### Fixed 96 | 97 | - Properly set `RepliconClientStatus::Connecting` when `RenetClient` is connecting. 98 | 99 | ## [0.2.0] - 2024-05-11 100 | 101 | ### Changed 102 | 103 | - Update to `bevy_replicon` 0.25. 104 | 105 | ## [0.1.0] - 2024-05-06 106 | 107 | First release after I/O abstraction. 108 | 109 | [unreleased]: https://github.com/simgine/bevy_replicon_renet/compare/v0.11.2...HEAD 110 | [0.11.2]: https://github.com/simgine/bevy_replicon_renet/compare/v0.11.1...v0.11.2 111 | [0.11.1]: https://github.com/simgine/bevy_replicon_renet/compare/v0.11.0...v0.11.1 112 | [0.11.0]: https://github.com/simgine/bevy_replicon_renet/compare/v0.10.0...v0.11.0 113 | [0.10.0]: https://github.com/simgine/bevy_replicon_renet/compare/v0.9.0...v0.10.0 114 | [0.9.0]: https://github.com/simgine/bevy_replicon_renet/compare/v0.8.0...v0.9.0 115 | [0.8.0]: https://github.com/simgine/bevy_replicon_renet/compare/v0.7.0...v0.8.0 116 | [0.7.0]: https://github.com/simgine/bevy_replicon_renet/compare/v0.6.0...v0.7.0 117 | [0.6.0]: https://github.com/simgine/bevy_replicon_renet/compare/v0.5.1...v0.6.0 118 | [0.5.1]: https://github.com/simgine/bevy_replicon_renet/compare/v0.5.0...v0.5.1 119 | [0.5.0]: https://github.com/simgine/bevy_replicon_renet/compare/v0.4.0...v0.5.0 120 | [0.4.0]: https://github.com/simgine/bevy_replicon_renet/releases/tag/v0.4.0 121 | [0.3.0]: https://github.com/simgine/bevy_replicon/compare/v0.2.0...v0.3.0 122 | [0.2.0]: https://github.com/simgine/bevy_replicon/compare/v0.1.0...v0.2.0 123 | [0.1.0]: https://github.com/simgine/bevy_replicon/releases/tag/v0.1.0 124 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bevy_replicon_renet" 3 | version = "0.11.2" 4 | authors = [ 5 | "Hennadii Chernyshchyk ", 6 | "koe ", 7 | ] 8 | edition = "2024" 9 | description = "Integration with renet for bevy_replicon" 10 | readme = "README.md" 11 | repository = "https://github.com/simgine/bevy_replicon_renet" 12 | keywords = [ 13 | "bevy", 14 | "multiplayer", 15 | "netcode", 16 | "replication", 17 | "server-authoritative", 18 | ] 19 | categories = ["game-development", "network-programming"] 20 | license = "MIT OR Apache-2.0" 21 | include = ["/src", "/tests", "/examples", "LICENSE*"] 22 | 23 | [package.metadata.docs.rs] 24 | rustdoc-args = ["-Zunstable-options", "--cfg", "docsrs"] 25 | all-features = true 26 | 27 | [dependencies] 28 | bevy_replicon = { version = "0.35", default-features = false } 29 | bevy_renet = { version = "2.0", default-features = false } 30 | bevy = { version = "0.16", default-features = false, features = ["bevy_log"] } 31 | 32 | [dev-dependencies] 33 | bevy = { version = "0.16", default-features = false, features = [ 34 | "bevy_gizmos", 35 | "bevy_state", 36 | "bevy_text", 37 | "bevy_ui_picking_backend", 38 | "bevy_ui", 39 | "bevy_window", 40 | "default_font", 41 | "serialize", 42 | "x11", 43 | ] } 44 | clap = { version = "4.1", features = ["derive"] } 45 | fastrand = "2.3" 46 | fastrand-contrib = "0.1" 47 | pathfinding = "4.14" 48 | serde = "1.0" 49 | test-log = "0.2" 50 | 51 | [features] 52 | default = ["client", "server", "renet_netcode"] 53 | server = ["bevy_replicon/server"] 54 | client = ["bevy_replicon/client"] 55 | 56 | # Re-exports of renet features 57 | renet_netcode = ["bevy_renet/netcode"] 58 | renet_steam = ["bevy_renet/steam"] 59 | 60 | [lints.clippy] 61 | type_complexity = "allow" 62 | 63 | [[test]] 64 | name = "netcode" 65 | required-features = ["server", "client", "renet_netcode"] 66 | 67 | [[example]] 68 | name = "authoritative_rts" 69 | required-features = ["server", "client", "renet_netcode"] 70 | 71 | [[example]] 72 | name = "deterministic_boids" 73 | required-features = ["server", "client", "renet_netcode"] 74 | 75 | [[example]] 76 | name = "simple_button" 77 | required-features = ["server", "client", "renet_netcode"] 78 | 79 | [[example]] 80 | name = "tic_tac_toe" 81 | required-features = ["server", "client", "renet_netcode"] 82 | -------------------------------------------------------------------------------- /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 | Copyright (c) 2023 Hennadii Chernyshchyk 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bevy Replicon Renet 2 | 3 | [![crates.io](https://img.shields.io/crates/v/bevy_replicon_renet)](https://crates.io/crates/bevy_replicon_renet) 4 | [![docs.rs](https://docs.rs/bevy_replicon_renet/badge.svg)](https://docs.rs/bevy_replicon_renet) 5 | [![license](https://img.shields.io/crates/l/bevy_replicon_renet)](#license) 6 | [![codecov](https://codecov.io/gh/simgine/bevy_replicon_renet/graph/badge.svg?token=ZrlFB8wBpO)](https://codecov.io/gh/simgine/bevy_replicon_renet) 7 | 8 | An integration of [`bevy_renet`](https://github.com/lucaspoffo/renet/tree/master/bevy_renet) as a messaging backend for [`bevy_replicon`](https://github.com/simgine/bevy_replicon). 9 | 10 | ## Getting Started 11 | 12 | Check out the [getting started guide](https://docs.rs/bevy_replicon_renet). 13 | 14 | See also [examples](examples). 15 | 16 | ## Compatible versions 17 | 18 | | bevy_renet | bevy_replicon | bevy_replicon_renet | 19 | | ---------- | ------------- | ------------------- | 20 | | 2.0.0 | 0.35 | 0.11 | 21 | | 2.0.0 | 0.34 | 0.10 | 22 | | 1.0.0 | 0.32 | 0.9 | 23 | | 1.0.0 | 0.31 | 0.8 | 24 | | 1.0.0 | 0.30 | 0.7 | 25 | | 1.0.0 | 0.29 | 0.6 | 26 | | 0.0.12 | 0.28 | 0.5 | 27 | | 0.0.12 | 0.27 | 0.4 | 28 | | 0.0.11 | 0.26 | 0.3 | 29 | | 0.0.11 | 0.25 | 0.2 | 30 | | 0.0.11 | 0.24 | 0.1 | 31 | 32 | ## License 33 | 34 | Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or [MIT License](LICENSE-MIT) at your option. 35 | -------------------------------------------------------------------------------- /assets/LICENSE: -------------------------------------------------------------------------------- 1 | This Font Software is licensed under the SIL Open Font License, 2 | Version 1.1. 3 | 4 | This license is copied below, and is also available with a FAQ at: 5 | http://scripts.sil.org/OFL 6 | 7 | ----------------------------------------------------------- 8 | SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 9 | ----------------------------------------------------------- 10 | 11 | PREAMBLE 12 | The goals of the Open Font License (OFL) are to stimulate worldwide 13 | development of collaborative font projects, to support the font 14 | creation efforts of academic and linguistic communities, and to 15 | provide a free and open framework in which fonts may be shared and 16 | improved in partnership with others. 17 | 18 | The OFL allows the licensed fonts to be used, studied, modified and 19 | redistributed freely as long as they are not sold by themselves. The 20 | fonts, including any derivative works, can be bundled, embedded, 21 | redistributed and/or sold with any software provided that any reserved 22 | names are not used by derivative works. The fonts and derivatives, 23 | however, cannot be released under any other type of license. The 24 | requirement for fonts to remain under this license does not apply to 25 | any document created using the fonts or their derivatives. 26 | 27 | DEFINITIONS 28 | "Font Software" refers to the set of files released by the Copyright 29 | Holder(s) under this license and clearly marked as such. This may 30 | include source files, build scripts and documentation. 31 | 32 | "Reserved Font Name" refers to any names specified as such after the 33 | copyright statement(s). 34 | 35 | "Original Version" refers to the collection of Font Software 36 | components as distributed by the Copyright Holder(s). 37 | 38 | "Modified Version" refers to any derivative made by adding to, 39 | deleting, or substituting -- in part or in whole -- any of the 40 | components of the Original Version, by changing formats or by porting 41 | the Font Software to a new environment. 42 | 43 | "Author" refers to any designer, engineer, programmer, technical 44 | writer or other person who contributed to the Font Software. 45 | 46 | PERMISSION & CONDITIONS 47 | Permission is hereby granted, free of charge, to any person obtaining 48 | a copy of the Font Software, to use, study, copy, merge, embed, 49 | modify, redistribute, and sell modified and unmodified copies of the 50 | Font Software, subject to the following conditions: 51 | 52 | 1) Neither the Font Software nor any of its individual components, in 53 | Original or Modified Versions, may be sold by itself. 54 | 55 | 2) Original or Modified Versions of the Font Software may be bundled, 56 | redistributed and/or sold with any software, provided that each copy 57 | contains the above copyright notice and this license. These can be 58 | included either as stand-alone text files, human-readable headers or 59 | in the appropriate machine-readable metadata fields within text or 60 | binary files as long as those fields can be easily viewed by the user. 61 | 62 | 3) No Modified Version of the Font Software may use the Reserved Font 63 | Name(s) unless explicit written permission is granted by the 64 | corresponding Copyright Holder. This restriction only applies to the 65 | primary font name as presented to the users. 66 | 67 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 68 | Software shall not be used to promote, endorse or advertise any 69 | Modified Version, except to acknowledge the contribution(s) of the 70 | Copyright Holder(s) and the Author(s) or with their explicit written 71 | permission. 72 | 73 | 5) The Font Software, modified or unmodified, in part or in whole, 74 | must be distributed entirely under this license, and must not be 75 | distributed under any other license. The requirement for fonts to 76 | remain under this license does not apply to any document created using 77 | the Font Software. 78 | 79 | TERMINATION 80 | This license becomes null and void if any of the above conditions are 81 | not met. 82 | 83 | DISCLAIMER 84 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 85 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 86 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 87 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 88 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 89 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 90 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 91 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 92 | OTHER DEALINGS IN THE FONT SOFTWARE. 93 | -------------------------------------------------------------------------------- /assets/NotoEmoji-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simgine/bevy_replicon_renet/6c967e502d460b72938951bdbf6af5e41f00b999/assets/NotoEmoji-Regular.ttf -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | coverage: 2 | status: 3 | project: off 4 | patch: off 5 | -------------------------------------------------------------------------------- /deny.toml: -------------------------------------------------------------------------------- 1 | [licenses] 2 | allow = [ 3 | "Apache-2.0", 4 | "BSD-2-Clause", 5 | "BSD-3-Clause", 6 | "BSL-1.0", 7 | "CC0-1.0", 8 | "ISC", 9 | "MIT", 10 | "MIT-0", 11 | "Unicode-3.0", 12 | "Zlib", 13 | ] 14 | 15 | [advisories] 16 | version = 2 17 | ignore = ["RUSTSEC-2024-0436"] 18 | 19 | [bans] 20 | skip-tree = ["bevy"] 21 | -------------------------------------------------------------------------------- /examples/authoritative_rts.rs: -------------------------------------------------------------------------------- 1 | //! An RTS demo with authoritative replication: the server executes all game logic, 2 | //! and clients primarily render. 3 | //! 4 | //! This uses more bandwidth than deterministic replication, but it's 5 | //! more secure because clients don't necessarily need the full state, and it's 6 | //! easier to implement because it removes the determinism requirement from the 7 | //! game logic. 8 | //! 9 | //! In this example, clients don't predict or rollback. They simply wait for 10 | //! state updates from the server. It's a common strategy for RTS because the 11 | //! input delay won't be noticeable. 12 | 13 | use std::{ 14 | f32::consts::TAU, 15 | net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket}, 16 | time::SystemTime, 17 | }; 18 | 19 | use bevy::{ 20 | color::palettes::tailwind::{ 21 | BLUE_500, GREEN_500, LIME_500, ORANGE_500, PINK_500, PURPLE_500, RED_500, TEAL_500, 22 | YELLOW_500, 23 | }, 24 | ecs::entity::MapEntities, 25 | platform::collections::HashMap, 26 | prelude::*, 27 | render::primitives::Aabb, 28 | }; 29 | use bevy_replicon::prelude::*; 30 | use bevy_replicon_renet::{ 31 | RenetChannelsExt, RepliconRenetPlugins, 32 | netcode::{ 33 | ClientAuthentication, NetcodeClientTransport, NetcodeServerTransport, ServerAuthentication, 34 | ServerConfig, 35 | }, 36 | renet::{ConnectionConfig, RenetClient, RenetServer}, 37 | }; 38 | use clap::{Parser, ValueEnum}; 39 | use pathfinding::prelude::*; 40 | use serde::{Deserialize, Serialize}; 41 | 42 | fn main() { 43 | App::new() 44 | .init_resource::() // Parse CLI before creating window. 45 | .add_plugins((DefaultPlugins, RepliconPlugins, RepliconRenetPlugins)) 46 | .init_resource::() 47 | .init_resource::() 48 | .replicate::() 49 | .replicate::() 50 | .replicate_as::() 51 | .add_client_trigger::(Channel::Unordered) 52 | .add_client_trigger::(Channel::Unordered) 53 | .add_mapped_client_trigger::(Channel::Unordered) 54 | .add_observer(apply_team_request) 55 | .add_observer(trigger_unit_spawn) 56 | .add_observer(apply_unit_spawn) 57 | .add_observer(init_unit) 58 | .add_observer(select_units) 59 | .add_observer(end_selection) 60 | .add_observer(clear_selection) 61 | .add_observer(trigger_units_move) 62 | .add_observer(apply_units_move) 63 | .add_systems(Startup, setup) 64 | .add_systems(OnEnter(ClientState::Connected), trigger_team_request) 65 | .add_systems( 66 | FixedUpdate, 67 | move_units.run_if(in_state(ClientState::Disconnected)), 68 | ) 69 | .add_systems( 70 | Update, 71 | ( 72 | draw_selection.run_if(|r: Res| r.active), 73 | draw_selected, 74 | ), 75 | ) 76 | .run(); 77 | } 78 | 79 | fn setup(mut commands: Commands, cli: Res, channels: Res) -> Result<()> { 80 | const PROTOCOL_ID: u64 = 0; 81 | commands.spawn(Camera2d); 82 | commands.spawn(( 83 | Node { 84 | flex_direction: FlexDirection::Column, 85 | align_self: AlignSelf::FlexEnd, 86 | align_content: AlignContent::FlexEnd, 87 | ..Default::default() 88 | }, 89 | children![ 90 | Text::new("Left-click and drag to select"), 91 | Text::new("Middle-click to spawn unit"), 92 | Text::new("Right-click to move"), 93 | ], 94 | )); 95 | 96 | match *cli { 97 | Cli::Singleplayer { team } => { 98 | info!("starting singleplayer as `{team:?}`"); 99 | commands.client_trigger(TeamRequest { team }); 100 | commands.insert_resource(team); 101 | } 102 | Cli::Server { port, team } => { 103 | info!("starting server as `{team:?}` at port {port}"); 104 | 105 | // Backend initialization 106 | let server_channels_config = channels.server_configs(); 107 | let client_channels_config = channels.client_configs(); 108 | 109 | let server = RenetServer::new(ConnectionConfig { 110 | server_channels_config, 111 | client_channels_config, 112 | ..Default::default() 113 | }); 114 | 115 | let current_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?; 116 | let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, port))?; 117 | let server_config = ServerConfig { 118 | current_time, 119 | max_clients: 1, 120 | protocol_id: PROTOCOL_ID, 121 | authentication: ServerAuthentication::Unsecure, 122 | public_addresses: Default::default(), 123 | }; 124 | let transport = NetcodeServerTransport::new(server_config, socket)?; 125 | 126 | commands.insert_resource(server); 127 | commands.insert_resource(transport); 128 | 129 | // The server can also trigger client events. 130 | // These are re-emitted as `FromClient` with `ClientId::Server`. 131 | // This allows the code to work simultaneously in both client and listen-server modes. 132 | commands.client_trigger(TeamRequest { team }); 133 | commands.insert_resource(team); 134 | commands.spawn(Text::new("Server")); 135 | } 136 | Cli::Client { port, ip, team } => { 137 | info!("connecting to {ip}:{port}"); 138 | 139 | // Backend initialization 140 | let server_channels_config = channels.server_configs(); 141 | let client_channels_config = channels.client_configs(); 142 | 143 | let client = RenetClient::new(ConnectionConfig { 144 | server_channels_config, 145 | client_channels_config, 146 | ..Default::default() 147 | }); 148 | 149 | let current_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?; 150 | let client_id = current_time.as_millis() as u64; 151 | let server_addr = SocketAddr::new(ip, port); 152 | let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))?; 153 | let addr = socket.local_addr()?; 154 | let authentication = ClientAuthentication::Unsecure { 155 | client_id, 156 | protocol_id: PROTOCOL_ID, 157 | server_addr, 158 | user_data: None, 159 | }; 160 | let transport = NetcodeClientTransport::new(current_time, authentication, socket)?; 161 | 162 | commands.insert_resource(client); 163 | commands.insert_resource(transport); 164 | 165 | commands.insert_resource(team); 166 | commands.spawn(Text(format!("Client: {addr}"))); 167 | } 168 | } 169 | 170 | Ok(()) 171 | } 172 | 173 | /// Sends the client's team choice to the server. 174 | fn trigger_team_request(mut commands: Commands, team: Res) { 175 | commands.client_trigger(TeamRequest { team: *team }); 176 | } 177 | 178 | /// Assigns a team to a player. 179 | fn apply_team_request( 180 | trigger: Trigger>, 181 | mut events: EventWriter, 182 | mut teams: ResMut, 183 | ) { 184 | if let Some((client_id, team)) = teams.iter().find(|&(_, team)| *team == trigger.team) { 185 | error!( 186 | "`{}` requested team `{team:?}`, but it's already taken by `{client_id}`", 187 | trigger.client_id, 188 | ); 189 | let client = trigger 190 | .client_id 191 | .entity() 192 | .expect("server can't request an invalid team"); 193 | events.write(DisconnectRequest { client }); 194 | return; 195 | } 196 | 197 | info!( 198 | "associating `{}` with team `{:?}`", 199 | trigger.client_id, trigger.team 200 | ); 201 | 202 | teams.insert(trigger.client_id, trigger.team); 203 | } 204 | 205 | /// Requests spawning a unit at the click location. 206 | /// 207 | /// We could network the [`Pointer`] event directly, but it carries a lot of 208 | /// extra data and we only care about middle clicks. Instead, we created a 209 | /// custom event and trigger it on clicks. 210 | /// 211 | /// This also makes the logic independent of camera position - even though in 212 | /// this demo the camera cannot move. 213 | fn trigger_unit_spawn( 214 | trigger: Trigger>, 215 | mut commands: Commands, 216 | camera: Single<(&Camera, &GlobalTransform)>, 217 | ) -> Result<()> { 218 | if trigger.button != PointerButton::Middle { 219 | return Ok(()); 220 | } 221 | 222 | let (camera, transform) = *camera; 223 | let position = camera.viewport_to_world_2d(transform, trigger.pointer_location.position)?; 224 | 225 | commands.client_trigger(UnitSpawn { position }); 226 | 227 | Ok(()) 228 | } 229 | 230 | /// Applies a spawn request. 231 | /// 232 | /// Executed on server and singleplayer. 233 | /// The unit will be replicated back to clients. 234 | fn apply_unit_spawn( 235 | trigger: Trigger>, 236 | mut commands: Commands, 237 | teams: Res, 238 | ) { 239 | let Some(&team) = teams.get(&trigger.client_id) else { 240 | error!( 241 | "`{}` attempted to spawn a unit but has no team", 242 | trigger.client_id 243 | ); 244 | return; 245 | }; 246 | 247 | commands.spawn(( 248 | Unit { team }, 249 | Transform::from_translation(trigger.position.extend(0.0)), 250 | )); 251 | } 252 | 253 | /// Initializes visuals for the unit. 254 | /// 255 | /// We don't replicate materials and meshes, since they aren't dynamically 256 | /// generated and are already known to clients. Instead, we replicate only 257 | /// the minimal information needed, such as the team, to pick the correct 258 | /// material. If units had different meshes, we would replicate the unit 259 | /// type and initialize the corresponding mesh on the client. 260 | /// 261 | /// Works for initialization on both the server (when a unit 262 | /// is spawned) and the client (when the unit is replicated). 263 | fn init_unit( 264 | trigger: Trigger, 265 | unit_mesh: Local, 266 | unit_materials: Local, 267 | mut units: Query<(&Unit, &mut Mesh2d, &mut MeshMaterial2d)>, 268 | ) { 269 | let (unit, mut mesh, mut material) = units.get_mut(trigger.target()).unwrap(); 270 | **mesh = unit_mesh.0.clone(); 271 | **material = unit_materials.get(&unit.team).unwrap().clone(); 272 | } 273 | 274 | /// Selects the player's units within a selection rectangle. 275 | /// 276 | /// The selection is local to the player and is not networked. 277 | fn select_units( 278 | trigger: Trigger>, 279 | mut commands: Commands, 280 | mut selection: ResMut, 281 | team: Res, 282 | camera: Single<(&Camera, &GlobalTransform)>, 283 | units: Query<(Entity, &Unit, &GlobalTransform, &Aabb, Has)>, 284 | ) -> Result<()> { 285 | if trigger.button != PointerButton::Primary { 286 | return Ok(()); 287 | } 288 | 289 | let (camera, transform) = *camera; 290 | 291 | let origin = camera.viewport_to_world_2d( 292 | transform, 293 | trigger.pointer_location.position - trigger.distance, 294 | )?; 295 | let end = camera.viewport_to_world_2d(transform, trigger.pointer_location.position)?; 296 | 297 | selection.rect = Rect::from_corners(origin, end); 298 | selection.active = true; 299 | 300 | for (unit_entity, unit, transform, aabb, prev_selected) in &units { 301 | let center = transform.translation_vec3a() + aabb.center; 302 | let rect = Rect::from_center_half_size(center.truncate(), aabb.half_extents.truncate()); 303 | let selected = !selection.rect.intersect(rect).is_empty(); 304 | if selected != prev_selected { 305 | if selected && unit.team == *team { 306 | commands.entity(unit_entity).insert(Selected); 307 | } else { 308 | commands.entity(unit_entity).remove::(); 309 | } 310 | } 311 | } 312 | 313 | Ok(()) 314 | } 315 | 316 | /// Stops displaying the selection rectangle. 317 | fn end_selection(_trigger: Trigger>, mut rect: ResMut) { 318 | rect.active = false; 319 | } 320 | 321 | fn clear_selection( 322 | trigger: Trigger>, 323 | mut commands: Commands, 324 | units: Query>, 325 | ) { 326 | if trigger.button != PointerButton::Primary { 327 | return; 328 | } 329 | for unit in &units { 330 | commands.entity(unit).remove::(); 331 | } 332 | } 333 | 334 | /// Requests movement into a location for previously the selected units. 335 | fn trigger_units_move( 336 | trigger: Trigger>, 337 | mut commands: Commands, 338 | camera: Single<(&Camera, &GlobalTransform)>, 339 | units: Populated>, 340 | ) -> Result<()> { 341 | if trigger.button != PointerButton::Secondary { 342 | return Ok(()); 343 | } 344 | 345 | let (camera, transform) = *camera; 346 | let position = camera.viewport_to_world_2d(transform, trigger.pointer_location.position)?; 347 | 348 | commands.client_trigger(UnitsMove { 349 | units: units.iter().collect(), 350 | position, 351 | }); 352 | 353 | Ok(()) 354 | } 355 | 356 | const MOVE_SPACING: f32 = 30.0; 357 | 358 | /// Applies a move request to the specified units. 359 | /// 360 | /// Each unit receives a unique `Command::Move`, arranged in a grid formation 361 | /// centered on the requested position. The grid is oriented toward that position. 362 | fn apply_units_move( 363 | trigger: Trigger>, 364 | teams: Res, 365 | mut slots: Local>, 366 | mut positions: Local>, 367 | mut units: Query<(&Unit, &GlobalTransform, &mut Command)>, 368 | ) { 369 | // Validate the received data since the client could be malicious. 370 | // For example, on the client side we skip empty selections, but a modified 371 | // client could bypass this and cause a division by zero on the server. 372 | if trigger.units.is_empty() { 373 | error!("`{}` attempted to move zero units", trigger.client_id); 374 | return; 375 | } 376 | 377 | let Some(&client_team) = teams.get(&trigger.client_id) else { 378 | error!( 379 | "`{}` attempted to move units but has no team", 380 | trigger.client_id 381 | ); 382 | return; 383 | }; 384 | 385 | positions.clear(); 386 | positions.reserve(trigger.units.len()); 387 | for (unit, transform, _) in units.iter_many(&trigger.units) { 388 | if unit.team != client_team { 389 | error!( 390 | "`{}` has team `{client_team:?}`, but tried to move unit with team `{:?}`", 391 | trigger.client_id, unit.team 392 | ); 393 | return; 394 | } 395 | 396 | positions.push(transform.translation().truncate()); 397 | } 398 | 399 | let units_count = trigger.units.len(); 400 | let cols = (units_count as f32).sqrt().ceil() as usize; 401 | let rows = units_count.div_ceil(cols); 402 | let centering_offset = -Vec2::new(cols as f32 - 1.0, rows as f32 - 1.0) / 2.0 * MOVE_SPACING; 403 | 404 | // Orientation basis to make grid facing from group centroid toward the click. 405 | let positions_sum = positions.iter().sum::(); 406 | let centroid = positions_sum / units_count as f32; 407 | let forward = (trigger.position - centroid).normalize_or(Vec2::Y); 408 | let right = Vec2::new(forward.y, -forward.x); 409 | let rotation = Mat2::from_cols(right, forward); 410 | 411 | slots.clear(); 412 | slots.reserve(units_count); 413 | for index in 0..units_count { 414 | let row = index / cols; 415 | let col = index % cols; 416 | 417 | let grid_position = centering_offset + Vec2::new(col as f32, row as f32) * MOVE_SPACING; 418 | slots.push(trigger.position + rotation * grid_position); 419 | } 420 | 421 | // Pick closest slot for each unit using 422 | // Hungarian with squared distance as cost. 423 | let weights: Matrix<_> = positions 424 | .iter() 425 | .map(|p| { 426 | slots 427 | .iter() 428 | .map(|s| p.distance_squared(*s) as i64) 429 | .collect::>() 430 | }) 431 | .collect(); 432 | let (_, unit_to_slot) = kuhn_munkres_min(&weights); 433 | 434 | let mut iter = units.iter_many_mut(&trigger.units); 435 | for &slot_index in &unit_to_slot { 436 | let (.., mut command) = iter.fetch_next().unwrap(); 437 | *command = Command::Move(slots[slot_index]); 438 | } 439 | } 440 | 441 | /// Moves and spaces units. 442 | /// 443 | /// Steers moving units toward their targets. Applies the separation 444 | /// force from the [Boids](https://en.wikipedia.org/wiki/Boids) 445 | /// model to reduce crowding. 446 | /// 447 | /// Also resolves overlaps by applying simple circle–collision physics. 448 | fn move_units( 449 | mut cached_units: Local>, 450 | time: Res