├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── assets ├── images │ ├── create.jpeg │ ├── export-1.jpeg │ ├── export-2.jpeg │ ├── rename.jpeg │ └── result.jpeg └── models │ ├── monkey.glb │ ├── rock.glb │ └── rock.gltf ├── examples ├── load_monkey.rs └── load_rocks.rs └── src ├── extras_collider.rs ├── lib.rs └── mesh_collider.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bevy_gltf_collider" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [profile.dev.package."*"] 7 | opt-level = 3 8 | 9 | [dependencies] 10 | bevy = { version = "0.13"} 11 | bevy_rapier3d = { version="0.25.0", features=['serde-serialize'] } 12 | serde_json = {version="1.0"} 13 | serde = {version="1.0"} 14 | bincode="1.3.3" 15 | [dev-dependencies] 16 | rand = "0.8.5" 17 | -------------------------------------------------------------------------------- /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 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Defernus 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 gltf collider generator 2 | 3 | Simple crate for [rapier3d](https://rapier.rs/) collider generation from [bevy](https://bevyengine.org/) scene loaded from gltf file. 4 | 5 | ## Usage 6 | 7 | Check [load_monkey example](./examples/load_monkey.rs). 8 | 9 | ## How to create gltf file in blender 10 | 11 | 1. Create a mesh for collider around your object (you can add more than one) 12 | ![collider](./assets/images/create.jpeg) 13 | 2. Rename all your colliders to `collider_*` 14 | ![rename](./assets/images/rename.jpeg) 15 | 3. Export your scene as gltf file 16 | ![export-1](./assets/images/export-1.jpeg) 17 | 4. Make sure to check this options: 18 | ![export-2](./assets/images/export-2.jpeg) 19 | 5. Load your scene in bevy and use `bevy_gltf_collider::get_scene_colliders` function to replace meshes with colliders 20 | ![bevy](./assets/images/result.jpeg) 21 | 22 | # License 23 | 24 | Bevy Gltf Collider Generator is distributed under the terms of both the MIT license and the 25 | Apache License (Version 2.0). 26 | 27 | See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT). 28 | -------------------------------------------------------------------------------- /assets/images/create.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Defernus/bevy_gltf_collider/73ea52bf5bcf986aa493a608bec39eeeb5b1b396/assets/images/create.jpeg -------------------------------------------------------------------------------- /assets/images/export-1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Defernus/bevy_gltf_collider/73ea52bf5bcf986aa493a608bec39eeeb5b1b396/assets/images/export-1.jpeg -------------------------------------------------------------------------------- /assets/images/export-2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Defernus/bevy_gltf_collider/73ea52bf5bcf986aa493a608bec39eeeb5b1b396/assets/images/export-2.jpeg -------------------------------------------------------------------------------- /assets/images/rename.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Defernus/bevy_gltf_collider/73ea52bf5bcf986aa493a608bec39eeeb5b1b396/assets/images/rename.jpeg -------------------------------------------------------------------------------- /assets/images/result.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Defernus/bevy_gltf_collider/73ea52bf5bcf986aa493a608bec39eeeb5b1b396/assets/images/result.jpeg -------------------------------------------------------------------------------- /assets/models/monkey.glb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Defernus/bevy_gltf_collider/73ea52bf5bcf986aa493a608bec39eeeb5b1b396/assets/models/monkey.glb -------------------------------------------------------------------------------- /assets/models/rock.glb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Defernus/bevy_gltf_collider/73ea52bf5bcf986aa493a608bec39eeeb5b1b396/assets/models/rock.glb -------------------------------------------------------------------------------- /assets/models/rock.gltf: -------------------------------------------------------------------------------- 1 | { 2 | "asset" : { 3 | "generator" : "Khronos glTF Blender I/O v3.4.50", 4 | "version" : "2.0" 5 | }, 6 | "scene" : 0, 7 | "scenes" : [ 8 | { 9 | "name" : "Scene", 10 | "nodes" : [ 11 | 0 12 | ] 13 | } 14 | ], 15 | "nodes" : [ 16 | { 17 | "extras" : { 18 | "collider_data" : "{\"colliders\":[{\"collider_type\":\"cuboid\",\"value\":[1,1,1],\"translation\":{\"x\":-0.000543,\"y\":0.087472,\"z\":-0.00163},\"rotation\":{\"x\":0,\"y\":0,\"z\":0,\"w\":1},\"scale\":{\"x\":0.107805,\"y\":0.081654,\"z\":0.13115}}]}" 19 | }, 20 | "mesh" : 0, 21 | "name" : "rock" 22 | } 23 | ], 24 | "meshes" : [ 25 | { 26 | "name" : "Cube.002", 27 | "primitives" : [ 28 | { 29 | "attributes" : { 30 | "POSITION" : 0, 31 | "TEXCOORD_0" : 1, 32 | "NORMAL" : 2 33 | }, 34 | "indices" : 3 35 | } 36 | ] 37 | } 38 | ], 39 | "accessors" : [ 40 | { 41 | "bufferView" : 0, 42 | "componentType" : 5126, 43 | "count" : 144, 44 | "max" : [ 45 | 0.11432164907455444, 46 | 0.175066277384758, 47 | 0.1504373848438263 48 | ], 49 | "min" : [ 50 | -0.11806125193834305, 51 | 0.0008127316832542419, 52 | -0.1440766304731369 53 | ], 54 | "type" : "VEC3" 55 | }, 56 | { 57 | "bufferView" : 1, 58 | "componentType" : 5126, 59 | "count" : 144, 60 | "type" : "VEC2" 61 | }, 62 | { 63 | "bufferView" : 2, 64 | "componentType" : 5126, 65 | "count" : 144, 66 | "type" : "VEC3" 67 | }, 68 | { 69 | "bufferView" : 3, 70 | "componentType" : 5123, 71 | "count" : 144, 72 | "type" : "SCALAR" 73 | } 74 | ], 75 | "bufferViews" : [ 76 | { 77 | "buffer" : 0, 78 | "byteLength" : 1728, 79 | "byteOffset" : 0, 80 | "target" : 34962 81 | }, 82 | { 83 | "buffer" : 0, 84 | "byteLength" : 1152, 85 | "byteOffset" : 1728, 86 | "target" : 34962 87 | }, 88 | { 89 | "buffer" : 0, 90 | "byteLength" : 1728, 91 | "byteOffset" : 2880, 92 | "target" : 34962 93 | }, 94 | { 95 | "buffer" : 0, 96 | "byteLength" : 288, 97 | "byteOffset" : 4608, 98 | "target" : 34963 99 | } 100 | ], 101 | "buffers" : [ 102 | { 103 | "byteLength" : 4896, 104 | "uri" : "data:application/octet-stream;base64,4PyFvTp1ozyLOms94PyFvTp1ozyLOms94PyFvTp1ozyLOms94PyFvTp1ozyLOms94PyFvTp1ozyLOms94PyFvTp1ozyLOms9vgd+vRNmET7OXoU9vgd+vRNmET7OXoU9vgd+vRNmET7OXoU9vgd+vRNmET7OXoU9vgd+vRNmET7OXoU9vgd+vRNmET7OXoU9eV2TvRTEyzzCRp69eV2TvRTEyzzCRp69eV2TvRTEyzzCRp69eV2TvRTEyzzCRp69eV2TvRTEyzzCRp69eV2TvRTEyzzCRp692WpuvVcUBj68fo292WpuvVcUBj68fo292WpuvVcUBj68fo292WpuvVcUBj68fo292WpuvVcUBj68fo292WpuvVcUBj68fo296rmNPZDHOTylpD896rmNPZDHOTylpD896rmNPZDHOTylpD896rmNPZDHOT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ywcLPwO7C7+TWCM/sB83P/e0lr7MPiI/TAQ7P4knsb1zaC0/mAt5vhIKeL/Emjo9GjJ1vvC7d79fPqG9TL4cvrALer/Kwhk+dYiUvfQceL9uCXG+aq89PbO7fL8JBRw+GyDaPestd7/7JHO+WQ0SPl79d7/w/k++JMAePgrmfL/C8uS7wxHgvv0XUT/5f8C+gAvSvoquTj9NJ9m+V3mhvpqMcT8dT889WNKVvqX5cj9qUe49F0pDPgxqdj/sRkU+DuJyPv86YD8BINe+r2OUPl83cz816ew96gesPh4Xaj+TI2e+BQBjADMACABkADcAZgASAD0AYQAPADIAEQBrAEIAFQBqAD8AbwAtAEkAbAAmAEMAKAB0AE8ALwB1AEoAcQAiAFcAcgAdAE4AGgB9AFsAIQB/AFUAewAHADUAegADAFoADACBADEAJACFAEEAhAAYAFkAgAAAADAAKwCPAFEAFgCIAEYAigAKAF4AjAAeAFAABAA2AGIACQA4AGUAZwA5ABMAYAA8AA4AEAA+AGkAFABEAGgAbQBFACwAbgBIACcAKQBLAHYALgBSAHMAdwBTACMAcABWABwAGwBUAH4AIABdAHwAeABcAAYAeQA0AAIADQBAAIMAJQBMAIYAhwBNABkAggBYAAEAKgBHAI0AFwA6AIkAiwA7AAsAjgBfAB8A" 105 | } 106 | ] 107 | } 108 | -------------------------------------------------------------------------------- /examples/load_monkey.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_gltf_collider::get_scene_colliders; 3 | use bevy_rapier3d::prelude::*; 4 | 5 | #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, States, Default)] 6 | enum GameState { 7 | #[default] 8 | Loading, 9 | Loaded, 10 | } 11 | 12 | #[derive(Default, Resource)] 13 | struct GameAssets { 14 | monkey_scene: Handle, 15 | monkey_colliders: Vec<(Collider, Transform)>, 16 | } 17 | 18 | fn main() { 19 | App::new() 20 | .add_plugins(DefaultPlugins) 21 | .init_state::() 22 | .insert_resource(ClearColor(Color::rgb(0.7, 0.9, 1.0))) 23 | .add_plugins((RapierPhysicsPlugin::::default(), RapierDebugRenderPlugin::default())) 24 | .insert_resource(AmbientLight { 25 | brightness: 0.5, 26 | ..default() 27 | }) 28 | .add_systems(OnEnter(GameState::Loading), (start_assets_loading,)) 29 | .add_systems(Update, (check_if_loaded,).run_if(in_state(GameState::Loading))) 30 | .add_systems(OnEnter(GameState::Loaded), (spawn_monkeys,)) 31 | .run(); 32 | } 33 | 34 | // load the monkey scene from the gltf file 35 | fn start_assets_loading(mut commands: Commands, asset_server: Res) { 36 | commands.insert_resource(GameAssets { 37 | monkey_scene: asset_server.load("models/monkey.glb#Scene0"), 38 | ..default() 39 | }); 40 | } 41 | 42 | // check if the monkey scene is loaded and if so, get the colliders from it 43 | fn check_if_loaded( 44 | mut scenes: ResMut>, 45 | mut game_assets: ResMut, 46 | mut meshes: ResMut>, 47 | mut game_state: ResMut>, 48 | ) { 49 | let scene = if let Some(scene) = scenes.get_mut(&game_assets.monkey_scene) { 50 | scene 51 | } else { 52 | return; 53 | }; 54 | 55 | // get_scene_colliders should be called only once per scene as it will remove the colliders meshes from it 56 | game_assets.monkey_colliders = get_scene_colliders(&mut meshes, &mut scene.world) 57 | .expect("Failed to create monkey colliders"); 58 | 59 | game_state.set(GameState::Loaded); 60 | } 61 | 62 | // spawn objects 63 | fn spawn_monkeys(mut commands: Commands, game_assets: Res) { 64 | // Add a camera so we can see the debug-render. 65 | commands.spawn(Camera3dBundle { 66 | transform: Transform::from_xyz(-5.0, 10.0, 30.0).looking_at(Vec3::ZERO, Vec3::Y), 67 | ..default() 68 | }); 69 | 70 | // Add directional light 71 | commands.spawn(DirectionalLightBundle { 72 | transform: Transform::from_xyz(4.0, 4.0, -4.0).looking_at(Vec3::ZERO, Vec3::Y), 73 | ..default() 74 | }); 75 | 76 | // Create the ground. 77 | commands.spawn(( 78 | Collider::cuboid(100.0, 1.0, 100.0), 79 | TransformBundle::from(Transform::from_xyz(0.0, -2.0, 0.0)), 80 | )); 81 | 82 | let base_pos = Vec3::new(0.0, 4.0, 0.0); 83 | let spread = 10.0; 84 | for i in 0..10 { 85 | let x = rand::random(); 86 | let y = rand::random(); 87 | let z = rand::random(); 88 | 89 | let pos = base_pos + (Vec3::new(x, y, z) * spread - Vec3::ONE * spread / 2.0); 90 | 91 | // Spawn monkeys 92 | commands 93 | .spawn(( 94 | RigidBody::Dynamic, 95 | Restitution::coefficient(0.7), 96 | Name::new(format!("monkey_{}", i)), 97 | SceneBundle { 98 | scene: game_assets.monkey_scene.clone(), 99 | transform: Transform::from_translation(pos), 100 | ..default() 101 | }, 102 | )) 103 | // Spawn colliders 104 | .with_children(|parent| { 105 | for (collider, transform) in game_assets.monkey_colliders.iter() { 106 | parent.spawn(( 107 | collider.clone(), 108 | TransformBundle::from_transform(*transform), 109 | )); 110 | } 111 | }); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /examples/load_rocks.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_gltf_collider::get_scene_colliders; 3 | use bevy_rapier3d::prelude::*; 4 | 5 | #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, States, Default)] 6 | enum GameState { 7 | #[default] 8 | Loading, 9 | Loaded, 10 | } 11 | 12 | #[derive(Default, Resource)] 13 | struct GameAssets { 14 | rock_scene: Handle, 15 | rock_colliders: Vec<(Collider, Transform)>, 16 | } 17 | 18 | fn main() { 19 | App::new() 20 | .add_plugins(DefaultPlugins) 21 | .init_state::() 22 | .insert_resource(ClearColor(Color::rgb(0.7, 0.9, 1.0))) 23 | .add_plugins((RapierPhysicsPlugin::::default(), RapierDebugRenderPlugin::default())) 24 | .insert_resource(AmbientLight { 25 | brightness: 0.5, 26 | ..default() 27 | }) 28 | .add_systems(OnEnter(GameState::Loading), (start_assets_loading,)) 29 | .add_systems(Update, (check_if_loaded,).run_if(in_state(GameState::Loading))) 30 | .add_systems(OnEnter(GameState::Loaded), (spawn_rocks,)) 31 | .run(); 32 | } 33 | 34 | // load the rock scene from the gltf file 35 | fn start_assets_loading(mut commands: Commands, asset_server: Res) { 36 | commands.insert_resource(GameAssets { 37 | rock_scene: asset_server.load("models/rock.gltf#Scene0"), 38 | ..default() 39 | }); 40 | } 41 | 42 | // check if the rock scene is loaded and if so, get the colliders from it 43 | fn check_if_loaded( 44 | mut scenes: ResMut>, 45 | mut game_assets: ResMut, 46 | mut meshes: ResMut>, 47 | mut game_state: ResMut>, 48 | ) { 49 | let scene = if let Some(scene) = scenes.get_mut(&game_assets.rock_scene) { 50 | scene 51 | } else { 52 | return; 53 | }; 54 | 55 | // get_scene_colliders should be called only once per scene as it will remove the colliders meshes from it 56 | game_assets.rock_colliders = get_scene_colliders(&mut meshes, &mut scene.world) 57 | .expect("Failed to create rock colliders"); 58 | 59 | game_state.set(GameState::Loaded); 60 | } 61 | 62 | // spawn objects 63 | fn spawn_rocks(mut commands: Commands, game_assets: Res) { 64 | // Add a camera so we can see the debug-render. 65 | commands.spawn(Camera3dBundle { 66 | transform: Transform::from_xyz(-1.0, 2.0, 7.0).looking_at(Vec3::ZERO, Vec3::Y), 67 | ..default() 68 | }); 69 | 70 | // Add directional light 71 | commands.spawn(DirectionalLightBundle { 72 | transform: Transform::from_xyz(4.0, 4.0, -4.0).looking_at(Vec3::ZERO, Vec3::Y), 73 | ..default() 74 | }); 75 | 76 | // Create the ground. 77 | commands.spawn(( 78 | Collider::cuboid(100.0, 1.0, 100.0), 79 | TransformBundle::from(Transform::from_xyz(0.0, -2.0, 0.0)), 80 | )); 81 | 82 | let base_pos = Vec3::new(0.0, 2.0, 0.0); 83 | let spread = 1.0; 84 | for i in 0..100 { 85 | let x = rand::random(); 86 | let y = rand::random(); 87 | let z = rand::random(); 88 | 89 | let pos = base_pos + (Vec3::new(x, y, z) * spread - Vec3::ONE * spread / 2.0); 90 | 91 | // Spawn rocks 92 | commands 93 | .spawn(( 94 | RigidBody::Dynamic, 95 | Restitution::coefficient(0.7), 96 | Name::new(format!("rock_{}", i)), 97 | SceneBundle { 98 | scene: game_assets.rock_scene.clone(), 99 | transform: Transform::from_translation(pos), 100 | ..default() 101 | }, 102 | )) 103 | // Spawn colliders 104 | .with_children(|parent| { 105 | for (collider, transform) in game_assets.rock_colliders.iter() { 106 | parent.spawn(( 107 | collider.clone(), 108 | TransformBundle::from_transform(*transform), 109 | )); 110 | } 111 | }); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/extras_collider.rs: -------------------------------------------------------------------------------- 1 | use bevy::{gltf::GltfExtras, prelude::*}; 2 | use bevy_rapier3d::prelude::Collider; 3 | use serde::Deserialize; 4 | use serde_json::Value; 5 | 6 | // example: {"colliders":[{"collider_type":"cuboid","value":[1,1,1],"translation":{"x":-0.000543,"y":0.087472,"z":-0.00163},"rotation":{"x":0,"y":0,"z":0,"w":1},"scale":{"x":0.107805,"y":0.081654,"z":0.13115}}]} 7 | 8 | #[derive(Debug, Deserialize)] 9 | struct Vec3Data { 10 | x: f32, 11 | y: f32, 12 | z: f32, 13 | } 14 | 15 | impl From for Vec3 { 16 | fn from(data: Vec3Data) -> Self { 17 | Vec3::new(data.x, data.y, data.z) 18 | } 19 | } 20 | 21 | #[derive(Debug, Deserialize)] 22 | struct QuatData { 23 | x: f32, 24 | y: f32, 25 | z: f32, 26 | w: f32, 27 | } 28 | 29 | impl From for Quat { 30 | fn from(data: QuatData) -> Self { 31 | Quat::from_xyzw(data.x, data.y, data.z, data.w) 32 | } 33 | } 34 | 35 | const COLLIDER_TYPE_CUBOID: &str = "cuboid"; 36 | // const COLLIDER_TYPE_SPHERE: &str = "sphere"; 37 | // const COLLIDER_TYPE_CYLINDER: &str = "cylinder"; 38 | 39 | #[derive(Debug, Deserialize)] 40 | struct ColliderData { 41 | collider_type: String, 42 | value: Value, 43 | translation: Option, 44 | rotation: Option, 45 | scale: Option, 46 | } 47 | 48 | #[derive(Debug, Deserialize)] 49 | struct Colliders { 50 | colliders: Vec, 51 | } 52 | 53 | #[derive(Debug, Deserialize)] 54 | struct ExtrasData { 55 | collider_data: String, 56 | } 57 | 58 | #[derive(Debug)] 59 | pub enum ColliderExtrasParsingError { 60 | InvalidColliderDataFormat(String), 61 | UnknownColliderType(String), 62 | InvalidColliderValue(Value), 63 | } 64 | 65 | pub(super) fn process_extras_collider( 66 | extras: &GltfExtras, 67 | ) -> Option, ColliderExtrasParsingError>> { 68 | let ExtrasData { collider_data } = match serde_json::from_str(&extras.value) { 69 | Ok(value) => value, 70 | Err(err) => { 71 | if err.is_data() { 72 | return None; 73 | } else { 74 | return Some(Err(ColliderExtrasParsingError::InvalidColliderDataFormat( 75 | err.to_string(), 76 | ))); 77 | } 78 | } 79 | }; 80 | 81 | let Colliders { colliders } = match serde_json::from_str(&collider_data) { 82 | Ok(value) => value, 83 | Err(err) => { 84 | return Some(Err(ColliderExtrasParsingError::InvalidColliderDataFormat( 85 | err.to_string(), 86 | ))) 87 | } 88 | }; 89 | 90 | let mut result = Vec::with_capacity(colliders.len()); 91 | 92 | for c in colliders.into_iter() { 93 | let collider = match c.collider_type.as_str() { 94 | COLLIDER_TYPE_CUBOID => { 95 | let value = match &c.value { 96 | Value::Array(value) => value, 97 | _ => { 98 | return Some(Err(ColliderExtrasParsingError::InvalidColliderValue( 99 | c.value.clone(), 100 | ))) 101 | } 102 | }; 103 | 104 | if value.len() != 3 { 105 | return Some(Err(ColliderExtrasParsingError::InvalidColliderValue( 106 | c.value.clone(), 107 | ))); 108 | } 109 | 110 | let mut args = [0.0; 3]; 111 | for (i, v) in value.iter().enumerate() { 112 | args[i] = match v { 113 | Value::Number(value) => value.as_f64().unwrap() as f32, 114 | _ => { 115 | return Some(Err(ColliderExtrasParsingError::InvalidColliderValue( 116 | v.clone(), 117 | ))) 118 | } 119 | }; 120 | } 121 | 122 | Collider::cuboid(args[0], args[1], args[2]) 123 | } 124 | _ => { 125 | return Some(Err(ColliderExtrasParsingError::UnknownColliderType( 126 | c.collider_type, 127 | ))); 128 | } 129 | }; 130 | 131 | let transform = Transform { 132 | translation: c.translation.map_or(Vec3::default(), |v| v.into()), 133 | rotation: c.rotation.map_or(Quat::default(), |v| v.into()), 134 | scale: c.scale.map_or(Vec3::default(), |v| v.into()), 135 | }; 136 | 137 | result.push((collider, transform)); 138 | } 139 | 140 | Some(Ok(result)) 141 | } 142 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | use bevy::{gltf::GltfExtras, prelude::*}; 2 | use bevy_rapier3d::prelude::Collider; 3 | use extras_collider::{process_extras_collider, ColliderExtrasParsingError}; 4 | use mesh_collider::{process_mesh_collider, ColliderMeshParsingError}; 5 | use serde::{Deserialize, Serialize}; 6 | 7 | pub mod extras_collider; 8 | pub mod mesh_collider; 9 | 10 | #[derive(Component, Reflect, Serialize, Deserialize, Default)] 11 | #[reflect(Component)] 12 | pub struct SerializedCollider { 13 | collider: Vec, 14 | } 15 | 16 | #[derive(Debug)] 17 | pub enum ColliderFromSceneError { 18 | MeshParsingError(ColliderMeshParsingError), 19 | ExtrasParsingError(ColliderExtrasParsingError), 20 | NoCollidersFound, 21 | } 22 | 23 | /// Get all colliders from a scene. 24 | /// 25 | /// It will search for all nodes with name starting with "collider" and will create a collider from the mesh. 26 | /// 27 | /// NOTE: should be called only once per scene as it will remove the colliders meshes from it. 28 | pub fn get_scene_colliders( 29 | meshes: &mut Assets, 30 | world: &mut World, 31 | ) -> Result, ColliderFromSceneError> { 32 | let mut result = Vec::new(); 33 | 34 | let mut extras_q = world.query::<&GltfExtras>(); 35 | for extras in extras_q.iter(world) { 36 | match process_extras_collider(extras) { 37 | None => {} 38 | Some(Err(err)) => return Err(ColliderFromSceneError::ExtrasParsingError(err)), 39 | Some(Ok(colliders)) => { 40 | for c in colliders { 41 | result.push(c); 42 | } 43 | } 44 | } 45 | } 46 | 47 | let mut entities_to_despawn = Vec::new(); 48 | let mut meshes_q = world.query::<(Entity, &Name, Option<&Children>)>(); 49 | for (entity, entity_name, children) in meshes_q.iter(world) { 50 | match process_mesh_collider(entity_name, children, world, meshes) { 51 | None => {} 52 | Some(Err(err)) => return Err(ColliderFromSceneError::MeshParsingError(err)), 53 | Some(Ok(collider)) => { 54 | let transform = *world.get::(entity).unwrap(); 55 | result.push((collider, transform)); 56 | entities_to_despawn.push(entity); 57 | } 58 | } 59 | } 60 | 61 | for e in entities_to_despawn { 62 | despawn_with_children_recursive(world, e); 63 | } 64 | 65 | Ok(result) 66 | } 67 | 68 | ///Pulls all of the scene colliders out of a scene, then parents them to a node with a matching suffix 69 | pub fn extract_insert_scene_colliders( 70 | meshes: &mut Assets, 71 | world: &mut World, 72 | ) -> Result, ColliderFromSceneError> { 73 | let mut result = Vec::new(); 74 | let mut entities_to_despawn = Vec::new(); 75 | let mut meshes_q = world.query::<(Entity, &Name, Option<&Children>)>(); 76 | let mut names_q = world.query::<(Entity, &Name)>(); 77 | 78 | for (entity, entity_name, children) in meshes_q.iter(world) { 79 | match process_mesh_collider(entity_name, children, world, meshes) { 80 | None => {} 81 | Some(Err(err)) => return Err(ColliderFromSceneError::MeshParsingError(err)), 82 | Some(Ok(collider)) => { 83 | let transform = *world.get::(entity).unwrap(); 84 | result.push((collider, transform, entity_name.clone())); 85 | entities_to_despawn.push(entity); 86 | } 87 | } 88 | } 89 | 90 | for e in entities_to_despawn { 91 | despawn_with_children_recursive(world, e); 92 | } 93 | 94 | //Go over all the found colliders and see if we can find an entity with a matching name 95 | result.iter_mut().for_each(|(collider, _transform, name)|{ 96 | let Some(new_ent_name) = name.split("collider_").last() else { 97 | return; 98 | }; 99 | 100 | let Some((new_ent, _new_name)) = names_q.iter(world).find(|val|{val.1.trim() == new_ent_name.trim()})else{ 101 | warn!("Could not find matching Node for collider: {}", name); 102 | return; 103 | }; 104 | 105 | //If we found one that matches go ahead and add the collider 106 | if let Ok(serialized_collider) = bincode::serialize(collider){ 107 | world.entity_mut(new_ent).insert(SerializedCollider{collider: serialized_collider}); 108 | }else{ 109 | error!("Could not serialize collider found in GLTF"); 110 | } 111 | }); 112 | 113 | Ok(result) 114 | } 115 | 116 | fn hydrate_serialized_colliders( 117 | colliders_to_add: Query<(&SerializedCollider, Entity), Added>, 118 | mut cmds: Commands, 119 | ) { 120 | colliders_to_add.iter().for_each(|(collider_to_add, entity)|{ 121 | let Ok(collider) = bincode::deserialize::(&collider_to_add.collider) else{ 122 | error!("Could not deserialize SerializedCollider from GLTF Scene to Rapier3d Collider!"); 123 | return; 124 | }; 125 | 126 | let Some(mut entcmds) = cmds.get_entity(entity) else{ 127 | warn!("Could not find entity to attach Deserialized Collider to!"); 128 | return; 129 | }; 130 | 131 | entcmds.insert(collider); 132 | }); 133 | } 134 | 135 | pub struct GLTFColliderPlugin; 136 | 137 | impl Plugin for GLTFColliderPlugin { 138 | fn build(&self, app: &mut App) { 139 | app.register_type::(); 140 | app.add_systems(Update, (hydrate_serialized_colliders,)); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/mesh_collider.rs: -------------------------------------------------------------------------------- 1 | use bevy::{ 2 | prelude::*, 3 | render::mesh::{Indices, VertexAttributeValues}, 4 | }; 5 | use bevy_rapier3d::prelude::Collider; 6 | 7 | const COLLIDER_MESH_NAME: &str = "collider"; 8 | 9 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 10 | pub enum ColliderFromMeshError { 11 | MissingPositions, 12 | MissingIndices, 13 | InvalidIndicesCount(usize), 14 | InvalidPositionsType(&'static str), 15 | } 16 | 17 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 18 | pub enum ColliderMeshParsingError { 19 | MissingMeshNode, 20 | MissingMesh, 21 | MeshColliderError(ColliderFromMeshError), 22 | } 23 | 24 | pub fn get_collider_from_mesh(mesh: &Mesh) -> Result { 25 | let positions = mesh 26 | .attribute(Mesh::ATTRIBUTE_POSITION) 27 | .map_or(Err(ColliderFromMeshError::MissingPositions), Ok)?; 28 | 29 | let indices = mesh 30 | .indices() 31 | .map_or(Err(ColliderFromMeshError::MissingIndices), Ok)?; 32 | 33 | let positions = match positions { 34 | VertexAttributeValues::Float32x3(positions) => positions, 35 | v => { 36 | return Err(ColliderFromMeshError::InvalidPositionsType( 37 | v.enum_variant_name(), 38 | )); 39 | } 40 | }; 41 | 42 | let indices: Vec = match indices { 43 | Indices::U32(indices) => indices.clone(), 44 | Indices::U16(indices) => indices.iter().map(|&i| i as u32).collect(), 45 | }; 46 | 47 | if indices.len() % 3 != 0 { 48 | return Err(ColliderFromMeshError::InvalidIndicesCount(indices.len())); 49 | } 50 | 51 | let triple_indices = indices.chunks(3).map(|v| [v[0], v[1], v[2]]).collect(); 52 | let vertices = positions 53 | .iter() 54 | .map(|v| Vec3::new(v[0], v[1], v[2])) 55 | .collect(); 56 | 57 | let collider = Collider::trimesh(vertices, triple_indices); 58 | 59 | Ok(collider) 60 | } 61 | 62 | pub(super) fn process_mesh_collider( 63 | node_name: &str, 64 | children: Option<&Children>, 65 | world: &World, 66 | meshes: &mut Assets, 67 | ) -> Option> { 68 | if !node_name.starts_with(COLLIDER_MESH_NAME) { 69 | return None; 70 | } 71 | 72 | let children = if let Some(children) = children { 73 | children 74 | } else { 75 | return Some(Err(ColliderMeshParsingError::MissingMeshNode)); 76 | }; 77 | 78 | let collider = children.iter().find_map(|&child| { 79 | if let Some(mesh) = world.get::>(child) { 80 | let mesh = meshes.remove(mesh).unwrap(); 81 | 82 | Some(get_collider_from_mesh(&mesh)) 83 | } else { 84 | None 85 | } 86 | }); 87 | 88 | Some( 89 | collider.map_or(Err(ColliderMeshParsingError::MissingMesh), |v| { 90 | v.map_err(ColliderMeshParsingError::MeshColliderError) 91 | }), 92 | ) 93 | } 94 | --------------------------------------------------------------------------------