1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
#![allow(clippy::unnecessary_cast)]
use crate::{make_isometry, prelude::*};
#[cfg(feature = "collider-from-mesh")]
use bevy::render::mesh::{Indices, VertexAttributeValues};
use bevy::{log, prelude::*};
use collision::contact_query::UnsupportedShape;
use itertools::Either;
use parry::shape::{RoundShape, SharedShape, TypedShape};
#[cfg(feature = "2d")]
mod primitives2d;
#[cfg(feature = "3d")]
mod primitives3d;
#[cfg(feature = "2d")]
pub(crate) use primitives2d::{EllipseWrapper, RegularPolygonWrapper};
impl<T: IntoCollider<Collider>> From<T> for Collider {
fn from(value: T) -> Self {
value.collider()
}
}
/// Parameters controlling the VHACD convex decomposition.
///
/// See <https://github.com/Unity-Technologies/VHACD#parameters> for details.
#[derive(Clone, PartialEq, Debug, Reflect)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(PartialEq, Debug)]
pub struct VhacdParameters {
/// Maximum concavity.
///
/// Default: 0.1 (in 2D), 0.01 (in 3D).
/// Valid range `[0.0, 1.0]`.
pub concavity: Scalar,
/// Controls the bias toward clipping along symmetry planes.
///
/// Default: 0.05.
/// Valid Range: `[0.0, 1.0]`.
pub alpha: Scalar,
/// Controls the bias toward clipping along revolution planes.
///
/// Default: 0.05.
/// Valid Range: `[0.0, 1.0]`.
pub beta: Scalar,
/// Resolution used during the voxelization stage.
///
/// Default: 256 (in 2D), 64 (in 3D).
pub resolution: u32,
/// Controls the granularity of the search for the best
/// clipping plane during the decomposition.
///
/// Default: 4
pub plane_downsampling: u32,
/// Controls the precision of the convex-hull generation
/// process during the clipping plane selection stage.
///
/// Default: 4
pub convex_hull_downsampling: u32,
/// Controls the way the input mesh or polyline is being
/// voxelized.
///
/// Default: `FillMode::FloodFill { detect_cavities: false, detect_self_intersections: false }`
pub fill_mode: FillMode,
/// Controls whether the convex-hull should be approximated during the decomposition stage.
/// Setting this to `true` increases performances with a slight degradation of the decomposition
/// quality.
///
/// Default: true
pub convex_hull_approximation: bool,
/// Controls the max number of convex-hull generated by the convex decomposition.
///
/// Default: 1024
pub max_convex_hulls: u32,
}
impl Default for VhacdParameters {
fn default() -> Self {
Self {
#[cfg(feature = "3d")]
resolution: 64,
#[cfg(feature = "3d")]
concavity: 0.01,
#[cfg(feature = "2d")]
resolution: 256,
#[cfg(feature = "2d")]
concavity: 0.1,
plane_downsampling: 4,
convex_hull_downsampling: 4,
alpha: 0.05,
beta: 0.05,
convex_hull_approximation: true,
max_convex_hulls: 1024,
fill_mode: FillMode::FloodFill {
detect_cavities: false,
#[cfg(feature = "2d")]
detect_self_intersections: false,
},
}
}
}
impl From<VhacdParameters> for parry::transformation::vhacd::VHACDParameters {
fn from(value: VhacdParameters) -> Self {
Self {
concavity: value.concavity,
alpha: value.alpha,
beta: value.beta,
resolution: value.resolution,
plane_downsampling: value.plane_downsampling,
convex_hull_downsampling: value.convex_hull_downsampling,
fill_mode: value.fill_mode.into(),
convex_hull_approximation: value.convex_hull_approximation,
max_convex_hulls: value.max_convex_hulls,
}
}
}
/// Controls how the voxelization determines which voxel needs
/// to be considered empty, and which ones will be considered full.
#[derive(Hash, Clone, Copy, PartialEq, Eq, Debug, Reflect)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Hash, PartialEq, Debug)]
pub enum FillMode {
/// Only consider full the voxels intersecting the surface of the
/// shape being voxelized.
SurfaceOnly,
/// Use a flood-fill technique to consider fill the voxels intersecting
/// the surface of the shape being voxelized, as well as all the voxels
/// bounded of them.
FloodFill {
/// Detects holes inside of a solid contour.
detect_cavities: bool,
/// Attempts to properly handle self-intersections.
#[cfg(feature = "2d")]
detect_self_intersections: bool,
},
}
impl From<FillMode> for parry::transformation::voxelization::FillMode {
fn from(value: FillMode) -> Self {
match value {
FillMode::SurfaceOnly => Self::SurfaceOnly,
FillMode::FloodFill {
detect_cavities,
#[cfg(feature = "2d")]
detect_self_intersections,
} => Self::FloodFill {
detect_cavities,
#[cfg(feature = "2d")]
detect_self_intersections,
},
}
}
}
bitflags::bitflags! {
/// Flags used for the preprocessing of a triangle mesh collider.
#[repr(transparent)]
#[derive(Hash, Clone, Copy, PartialEq, Eq, Debug, Reflect)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect_value(Serialize, Deserialize))]
#[reflect_value(Hash, PartialEq, Debug)]
pub struct TrimeshFlags: u8 {
/// If set, the half-edge topology of the trimesh will be computed if possible.
const HALF_EDGE_TOPOLOGY = 0b0000_0001;
/// If set, the half-edge topology and connected components of the trimesh will be computed if possible.
///
/// Because of the way it is currently implemented, connected components can only be computed on
/// a mesh where the half-edge topology computation succeeds. It will no longer be the case in the
/// future once we decouple the computations.
const CONNECTED_COMPONENTS = 0b0000_0010;
/// If set, any triangle that results in a failing half-hedge topology computation will be deleted.
const DELETE_BAD_TOPOLOGY_TRIANGLES = 0b0000_0100;
/// If set, the trimesh will be assumed to be oriented (with outward normals).
///
/// The pseudo-normals of its vertices and edges will be computed.
const ORIENTED = 0b0000_1000;
/// If set, the duplicate vertices of the trimesh will be merged.
///
/// Two vertices with the exact same coordinates will share the same entry on the
/// vertex buffer and the index buffer is adjusted accordingly.
const MERGE_DUPLICATE_VERTICES = 0b0001_0000;
/// If set, the triangles sharing two vertices with identical index values will be removed.
///
/// Because of the way it is currently implemented, this methods implies that duplicate
/// vertices will be merged. It will no longer be the case in the future once we decouple
/// the computations.
const DELETE_DEGENERATE_TRIANGLES = 0b0010_0000;
/// If set, two triangles sharing three vertices with identical index values (in any order) will be removed.
///
/// Because of the way it is currently implemented, this methods implies that duplicate
/// vertices will be merged. It will no longer be the case in the future once we decouple
/// the computations.
const DELETE_DUPLICATE_TRIANGLES = 0b0100_0000;
/// If set, a special treatment will be applied to contact manifold calculation to eliminate
/// or fix contacts normals that could lead to incorrect bumps in physics simulation
/// (especially on flat surfaces).
///
/// This is achieved by taking into account adjacent triangle normals when computing contact
/// points for a given triangle.
const FIX_INTERNAL_EDGES = 0b1000_0000 | Self::ORIENTED.bits() | Self::MERGE_DUPLICATE_VERTICES.bits();
}
}
impl From<TrimeshFlags> for parry::shape::TriMeshFlags {
fn from(value: TrimeshFlags) -> Self {
Self::from_bits(value.bits().into()).unwrap()
}
}
/// A collider used for detecting collisions and generating contacts.
///
/// ## Creation
///
/// `Collider` has tons of methods for creating colliders of various shapes:
///
/// ```
#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
/// # use bevy::prelude::*;
/// #
/// # fn setup(mut commands: Commands) {
/// // Create a ball collider with a given radius
#[cfg_attr(feature = "2d", doc = "commands.spawn(Collider::circle(0.5));")]
#[cfg_attr(feature = "3d", doc = "commands.spawn(Collider::sphere(0.5));")]
/// // Create a capsule collider with a given radius and height
/// commands.spawn(Collider::capsule(0.5, 2.0));
/// # }
/// ```
///
/// Colliders on their own only detect contacts and generate
/// [collision events](ContactReportingPlugin#collision-events).
/// To make colliders apply contact forces, they have to be attached
/// to [rigid bodies](RigidBody):
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// // Spawn a dynamic body that falls onto a static platform
/// fn setup(mut commands: Commands) {
/// commands.spawn((
/// RigidBody::Dynamic,
#[cfg_attr(feature = "2d", doc = " Collider::circle(0.5),")]
#[cfg_attr(feature = "3d", doc = " Collider::sphere(0.5),")]
/// TransformBundle::from_transform(Transform::from_xyz(0.0, 2.0, 0.0)),
/// ));
#[cfg_attr(
feature = "2d",
doc = " commands.spawn((RigidBody::Static, Collider::rectangle(5.0, 0.5)));"
)]
#[cfg_attr(
feature = "3d",
doc = " commands.spawn((RigidBody::Static, Collider::cuboid(5.0, 0.5, 5.0)));"
)]
/// }
/// ```
///
/// Colliders can be further configured using various components like [`Friction`], [`Restitution`],
/// [`Sensor`], [`CollisionLayers`], and [`CollisionMargin`].
///
/// In addition, Avian automatically adds some other components for colliders, like the following:
///
/// - [`ColliderParent`]
/// - [`ColliderAabb`]
/// - [`CollidingEntities`]
/// - [`ColliderDensity`]
/// - [`ColliderMassProperties`]
///
/// If you need to specify the shape of the collider statically, use [`ColliderConstructor`] and build your collider
/// with the [`Collider::try_from_constructor`] method.
/// This can also be done automatically by simply placing the [`ColliderConstructor`] on an entity.
///
#[cfg_attr(
feature = "3d",
doc = "Colliders can also be generated automatically for meshes and scenes. See [`ColliderConstructor`] and [`ColliderConstructorHierarchy`]."
)]
///
/// ### Multiple colliders
///
/// It can often be useful to attach multiple colliders to the same rigid body.
///
/// This can be done in two ways. Either use [`Collider::compound`] to have one collider that consists of many
/// shapes, or for more control, spawn several collider entities as the children of a rigid body:
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// fn setup(mut commands: Commands) {
/// // Spawn a rigid body with one collider on the same entity and two as children
/// commands
#[cfg_attr(
feature = "2d",
doc = " .spawn((RigidBody::Dynamic, Collider::circle(0.5)))"
)]
#[cfg_attr(
feature = "3d",
doc = " .spawn((RigidBody::Dynamic, Collider::sphere(0.5)))"
)]
/// .with_children(|children| {
/// // Spawn the child colliders positioned relative to the rigid body
#[cfg_attr(
feature = "2d",
doc = " children.spawn((
Collider::circle(0.5),
TransformBundle::from_transform(Transform::from_xyz(2.0, 0.0, 0.0)),
));
children.spawn((
Collider::circle(0.5),
TransformBundle::from_transform(Transform::from_xyz(-2.0, 0.0, 0.0)),
));"
)]
#[cfg_attr(
feature = "3d",
doc = " children.spawn((
Collider::sphere(0.5),
TransformBundle::from_transform(Transform::from_xyz(2.0, 0.0, 0.0)),
));
children.spawn((
Collider::sphere(0.5),
TransformBundle::from_transform(Transform::from_xyz(-2.0, 0.0, 0.0)),
));"
)]
/// });
/// }
/// ```
///
/// Colliders can be arbitrarily nested and transformed relative to the parent.
/// The rigid body that a collider is attached to can be accessed using the [`ColliderParent`] component.
///
/// The benefit of using separate entities for the colliders is that each collider can have its own
/// [friction](Friction), [restitution](Restitution), [collision layers](CollisionLayers),
/// and other configuration options, and they send separate [collision events](ContactReportingPlugin#collision-events).
///
/// ## See more
///
/// - [Rigid bodies](RigidBody)
/// - [Density](ColliderDensity)
/// - [Friction] and [restitution](Restitution) (bounciness)
/// - [Collision layers](CollisionLayers)
/// - [Sensors](Sensor)
/// - [Collision margins for adding extra thickness to colliders](CollisionMargin)
#[cfg_attr(
feature = "3d",
doc = "- Generating colliders for meshes and scenes with [`ColliderConstructor`] and [`ColliderConstructorHierarchy`]"
)]
/// - [Get colliding entities](CollidingEntities)
/// - [Collision events](ContactReportingPlugin#collision-events)
/// - [Accessing, filtering and modifying collisions](Collisions)
/// - [Manual contact queries](contact_query)
///
/// ## Advanced usage
///
/// Internally, `Collider` uses the shapes provided by `parry`. If you want to create a collider
/// using these shapes, you can simply use `Collider::from(SharedShape::some_method())`.
///
/// To get a reference to the internal [`SharedShape`], you can use the [`Collider::shape()`]
/// or [`Collider::shape_scaled()`] methods.
///
/// `Collider` is currently not `Reflect`. If you need to reflect it, you can use [`ColliderConstructor`] as a workaround.
#[derive(Clone, Component)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct Collider {
/// The raw unscaled collider shape.
shape: SharedShape,
/// The scaled version of the collider shape.
///
/// If the scale is `Vector::ONE`, this will be `None` and `unscaled_shape`
/// will be used instead.
scaled_shape: SharedShape,
/// The global scale used for the collider shape.
scale: Vector,
}
impl From<SharedShape> for Collider {
fn from(value: SharedShape) -> Self {
Self {
shape: value.clone(),
scaled_shape: value,
scale: Vector::ONE,
}
}
}
impl Default for Collider {
fn default() -> Self {
#[cfg(feature = "2d")]
{
Self::rectangle(0.5, 0.5)
}
#[cfg(feature = "3d")]
{
Self::cuboid(0.5, 0.5, 0.5)
}
}
}
impl std::fmt::Debug for Collider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.shape_scaled().as_typed_shape() {
TypedShape::Ball(shape) => write!(f, "{:?}", shape),
TypedShape::Cuboid(shape) => write!(f, "{:?}", shape),
TypedShape::RoundCuboid(shape) => write!(f, "{:?}", shape),
TypedShape::Capsule(shape) => write!(f, "{:?}", shape),
TypedShape::Segment(shape) => write!(f, "{:?}", shape),
TypedShape::Triangle(shape) => write!(f, "{:?}", shape),
TypedShape::RoundTriangle(shape) => write!(f, "{:?}", shape),
TypedShape::TriMesh(_) => write!(f, "Trimesh (not representable)"),
TypedShape::Polyline(_) => write!(f, "Polyline (not representable)"),
TypedShape::HalfSpace(shape) => write!(f, "{:?}", shape),
TypedShape::HeightField(shape) => write!(f, "{:?}", shape),
TypedShape::Compound(_) => write!(f, "Compound (not representable)"),
TypedShape::Custom(shape) => write!(f, "{:?}", shape),
#[cfg(feature = "3d")]
TypedShape::ConvexPolyhedron(shape) => write!(f, "{:?}", shape),
#[cfg(feature = "3d")]
TypedShape::Cylinder(shape) => write!(f, "{:?}", shape),
#[cfg(feature = "3d")]
TypedShape::Cone(shape) => write!(f, "{:?}", shape),
#[cfg(feature = "3d")]
TypedShape::RoundCylinder(shape) => write!(f, "{:?}", shape),
#[cfg(feature = "3d")]
TypedShape::RoundCone(shape) => write!(f, "{:?}", shape),
#[cfg(feature = "3d")]
TypedShape::RoundConvexPolyhedron(shape) => write!(f, "{:?}", shape),
#[cfg(feature = "2d")]
TypedShape::ConvexPolygon(shape) => write!(f, "{:?}", shape),
#[cfg(feature = "2d")]
TypedShape::RoundConvexPolygon(shape) => write!(f, "{:?}", shape),
}
}
}
impl AnyCollider for Collider {
fn aabb(&self, position: Vector, rotation: impl Into<Rotation>) -> ColliderAabb {
let aabb = self
.shape_scaled()
.compute_aabb(&make_isometry(position, rotation));
ColliderAabb {
min: aabb.mins.into(),
max: aabb.maxs.into(),
}
}
fn mass_properties(&self, density: Scalar) -> ColliderMassProperties {
let props = self.shape_scaled().mass_properties(density);
ColliderMassProperties {
mass: Mass(props.mass()),
inverse_mass: InverseMass(props.inv_mass),
#[cfg(feature = "2d")]
inertia: Inertia(props.principal_inertia()),
#[cfg(feature = "3d")]
inertia: Inertia(props.reconstruct_inertia_matrix().into()),
#[cfg(feature = "2d")]
inverse_inertia: InverseInertia(1.0 / props.principal_inertia()),
#[cfg(feature = "3d")]
inverse_inertia: InverseInertia(props.reconstruct_inverse_inertia_matrix().into()),
center_of_mass: CenterOfMass(props.local_com.into()),
}
}
fn contact_manifolds(
&self,
other: &Self,
position1: Vector,
rotation1: impl Into<Rotation>,
position2: Vector,
rotation2: impl Into<Rotation>,
prediction_distance: Scalar,
) -> Vec<ContactManifold> {
contact_query::contact_manifolds(
self,
position1,
rotation1,
other,
position2,
rotation2,
prediction_distance,
)
}
}
impl ScalableCollider for Collider {
fn scale(&self) -> Vector {
self.scale()
}
fn set_scale(&mut self, scale: Vector, detail: u32) {
self.set_scale(scale, detail)
}
}
impl Collider {
/// Returns the raw unscaled shape of the collider.
pub fn shape(&self) -> &SharedShape {
&self.shape
}
/// Returns the shape of the collider with the scale from its `GlobalTransform` applied.
pub fn shape_scaled(&self) -> &SharedShape {
&self.scaled_shape
}
/// Sets the unscaled shape of the collider. The collider's scale will be applied to this shape.
pub fn set_shape(&mut self, shape: SharedShape) {
self.shape = shape;
// TODO: The number of subdivisions probably shouldn't be hard-coded
if let Ok(scaled) = scale_shape(&self.shape, self.scale, 10) {
self.scaled_shape = scaled;
} else {
log::error!("Failed to create convex hull for scaled collider.");
}
}
/// Returns the global scale of the collider.
pub fn scale(&self) -> Vector {
self.scale
}
/// Set the global scaling factor of this shape.
///
/// If the scaling factor is not uniform, and the scaled shape can’t be
/// represented as a supported shape, the shape is approximated as
/// a convex polygon or polyhedron using `num_subdivisions`.
///
/// For example, if a ball was scaled to an ellipse, the new shape would be approximated.
pub fn set_scale(&mut self, scale: Vector, num_subdivisions: u32) {
if scale == self.scale {
return;
}
if scale == Vector::ONE {
// Trivial case.
self.scaled_shape = self.shape.clone();
self.scale = Vector::ONE;
return;
}
if let Ok(scaled) = scale_shape(&self.shape, scale, num_subdivisions) {
self.scaled_shape = scaled;
self.scale = scale;
} else {
log::error!("Failed to create convex hull for scaled collider.");
}
}
/// Projects the given `point` onto `self` transformed by `translation` and `rotation`.
/// The returned tuple contains the projected point and whether it is inside the collider.
///
/// If `solid` is true and the given `point` is inside of the collider, the projection will be at the point.
/// Otherwise, the collider will be treated as hollow, and the projection will be at the collider's boundary.
pub fn project_point(
&self,
translation: impl Into<Position>,
rotation: impl Into<Rotation>,
point: Vector,
solid: bool,
) -> (Vector, bool) {
let projection = self.shape_scaled().project_point(
&make_isometry(translation, rotation),
&point.into(),
solid,
);
(projection.point.into(), projection.is_inside)
}
/// Computes the minimum distance between the given `point` and `self` transformed by `translation` and `rotation`.
///
/// If `solid` is true and the given `point` is inside of the collider, the returned distance will be `0.0`.
/// Otherwise, the collider will be treated as hollow, and the distance will be the distance
/// to the collider's boundary.
pub fn distance_to_point(
&self,
translation: impl Into<Position>,
rotation: impl Into<Rotation>,
point: Vector,
solid: bool,
) -> Scalar {
self.shape_scaled().distance_to_point(
&make_isometry(translation, rotation),
&point.into(),
solid,
)
}
/// Tests whether the given `point` is inside of `self` transformed by `translation` and `rotation`.
pub fn contains_point(
&self,
translation: impl Into<Position>,
rotation: impl Into<Rotation>,
point: Vector,
) -> bool {
self.shape_scaled()
.contains_point(&make_isometry(translation, rotation), &point.into())
}
/// Computes the time of impact and normal between the given ray and `self`
/// transformed by `translation` and `rotation`.
///
/// The returned tuple is in the format `(time_of_impact, normal)`.
///
/// ## Arguments
///
/// - `ray_origin`: Where the ray is cast from.
/// - `ray_direction`: What direction the ray is cast in.
/// - `max_time_of_impact`: The maximum distance that the ray can travel.
/// - `solid`: If true and the ray origin is inside of a collider, the hit point will be the ray origin itself.
/// Otherwise, the collider will be treated as hollow, and the hit point will be at the collider's boundary.
pub fn cast_ray(
&self,
translation: impl Into<Position>,
rotation: impl Into<Rotation>,
ray_origin: Vector,
ray_direction: Vector,
max_time_of_impact: Scalar,
solid: bool,
) -> Option<(Scalar, Vector)> {
let hit = self.shape_scaled().cast_ray_and_get_normal(
&make_isometry(translation, rotation),
&parry::query::Ray::new(ray_origin.into(), ray_direction.into()),
max_time_of_impact,
solid,
);
hit.map(|hit| (hit.time_of_impact, hit.normal.into()))
}
/// Tests whether the given ray intersects `self` transformed by `translation` and `rotation`.
///
/// ## Arguments
///
/// - `ray_origin`: Where the ray is cast from.
/// - `ray_direction`: What direction the ray is cast in.
/// - `max_time_of_impact`: The maximum distance that the ray can travel.
pub fn intersects_ray(
&self,
translation: impl Into<Position>,
rotation: impl Into<Rotation>,
ray_origin: Vector,
ray_direction: Vector,
max_time_of_impact: Scalar,
) -> bool {
self.shape_scaled().intersects_ray(
&make_isometry(translation, rotation),
&parry::query::Ray::new(ray_origin.into(), ray_direction.into()),
max_time_of_impact,
)
}
/// Creates a collider with a compound shape defined by a given vector of colliders with a position and a rotation.
///
/// Especially for dynamic rigid bodies, compound shape colliders should be preferred over triangle meshes and polylines,
/// because convex shapes typically provide more reliable results.
///
/// If you want to create a compound shape from a 3D triangle mesh or 2D polyline, consider using the
/// [`Collider::convex_decomposition`] method.
pub fn compound(
shapes: Vec<(
impl Into<Position>,
impl Into<Rotation>,
impl Into<Collider>,
)>,
) -> Self {
let shapes = shapes
.into_iter()
.map(|(p, r, c)| {
(
make_isometry(*p.into(), r.into()),
c.into().shape_scaled().clone(),
)
})
.collect::<Vec<_>>();
SharedShape::compound(shapes).into()
}
/// Creates a collider with a circle shape defined by its radius.
#[cfg(feature = "2d")]
pub fn circle(radius: Scalar) -> Self {
SharedShape::ball(radius).into()
}
/// Creates a collider with a sphere shape defined by its radius.
#[cfg(feature = "3d")]
pub fn sphere(radius: Scalar) -> Self {
SharedShape::ball(radius).into()
}
/// Creates a collider with an ellipse shape defined by a half-width and half-height.
#[cfg(feature = "2d")]
pub fn ellipse(half_width: Scalar, half_height: Scalar) -> Self {
SharedShape::new(EllipseWrapper(Ellipse::new(
half_width as f32,
half_height as f32,
)))
.into()
}
/// Creates a collider with a rectangle shape defined by its extents.
#[cfg(feature = "2d")]
pub fn rectangle(x_length: Scalar, y_length: Scalar) -> Self {
SharedShape::cuboid(x_length * 0.5, y_length * 0.5).into()
}
/// Creates a collider with a cuboid shape defined by its extents.
#[cfg(feature = "3d")]
pub fn cuboid(x_length: Scalar, y_length: Scalar, z_length: Scalar) -> Self {
SharedShape::cuboid(x_length * 0.5, y_length * 0.5, z_length * 0.5).into()
}
/// Creates a collider with a rectangle shape defined by its extents and rounded corners.
#[cfg(feature = "2d")]
pub fn round_rectangle(x_length: Scalar, y_length: Scalar, border_radius: Scalar) -> Self {
SharedShape::round_cuboid(x_length * 0.5, y_length * 0.5, border_radius).into()
}
/// Creates a collider with a cuboid shape defined by its extents and rounded corners.
#[cfg(feature = "3d")]
pub fn round_cuboid(
x_length: Scalar,
y_length: Scalar,
z_length: Scalar,
border_radius: Scalar,
) -> Self {
SharedShape::round_cuboid(
x_length * 0.5,
y_length * 0.5,
z_length * 0.5,
border_radius,
)
.into()
}
/// Creates a collider with a cylinder shape defined by its radius
/// on the `XZ` plane and its height along the `Y` axis.
#[cfg(feature = "3d")]
pub fn cylinder(radius: Scalar, height: Scalar) -> Self {
SharedShape::cylinder(height * 0.5, radius).into()
}
/// Creates a collider with a cone shape defined by the radius of its base
/// on the `XZ` plane and its height along the `Y` axis.
#[cfg(feature = "3d")]
pub fn cone(radius: Scalar, height: Scalar) -> Self {
SharedShape::cone(height * 0.5, radius).into()
}
/// Creates a collider with a capsule shape defined by its radius
/// and its height along the `Y` axis, excluding the hemispheres.
pub fn capsule(radius: Scalar, length: Scalar) -> Self {
SharedShape::capsule(
(Vector::Y * length * 0.5).into(),
(Vector::NEG_Y * length * 0.5).into(),
radius,
)
.into()
}
/// Creates a collider with a capsule shape defined by its radius and endpoints `a` and `b`.
pub fn capsule_endpoints(radius: Scalar, a: Vector, b: Vector) -> Self {
SharedShape::capsule(a.into(), b.into(), radius).into()
}
/// Creates a collider with a [half-space](https://en.wikipedia.org/wiki/Half-space_(geometry)) shape
/// defined by the outward normal of its planar boundary.
pub fn half_space(outward_normal: Vector) -> Self {
SharedShape::halfspace(nalgebra::Unit::new_normalize(outward_normal.into())).into()
}
/// Creates a collider with a segment shape defined by its endpoints `a` and `b`.
pub fn segment(a: Vector, b: Vector) -> Self {
SharedShape::segment(a.into(), b.into()).into()
}
/// Creates a collider with a triangle shape defined by its points `a`, `b` and `c`.
pub fn triangle(a: Vector, b: Vector, c: Vector) -> Self {
SharedShape::triangle(a.into(), b.into(), c.into()).into()
}
/// Creates a collider with a regular polygon shape defined by the circumradius and the number of sides.
#[cfg(feature = "2d")]
pub fn regular_polygon(circumradius: f32, sides: usize) -> Self {
RegularPolygon::new(circumradius, sides).collider()
}
/// Creates a collider with a polyline shape defined by its vertices and optionally an index buffer.
pub fn polyline(vertices: Vec<Vector>, indices: Option<Vec<[u32; 2]>>) -> Self {
let vertices = vertices.into_iter().map(|v| v.into()).collect();
SharedShape::polyline(vertices, indices).into()
}
/// Creates a collider with a triangle mesh shape defined by its vertex and index buffers.
///
/// Note that the resulting collider will be hollow and have no interior. This makes it more prone to tunneling and other collision issues.
///
/// The [`CollisionMargin`] component can be used to add thickness to the shape if needed.
/// For thin shapes like triangle meshes, it can help improve collision stability and performance.
pub fn trimesh(vertices: Vec<Vector>, indices: Vec<[u32; 3]>) -> Self {
let vertices = vertices.into_iter().map(|v| v.into()).collect();
SharedShape::trimesh(vertices, indices).into()
}
/// Creates a collider with a triangle mesh shape defined by its vertex and index buffers
/// and flags controlling the preprocessing.
///
/// Note that the resulting collider will be hollow and have no interior. This makes it more prone to tunneling and other collision issues.
///
/// The [`CollisionMargin`] component can be used to add thickness to the shape if needed.
/// For thin shapes like triangle meshes, it can help improve collision stability and performance.
pub fn trimesh_with_config(
vertices: Vec<Vector>,
indices: Vec<[u32; 3]>,
flags: TrimeshFlags,
) -> Self {
let vertices = vertices.into_iter().map(|v| v.into()).collect();
SharedShape::trimesh_with_flags(vertices, indices, flags.into()).into()
}
/// Creates a collider shape with a compound shape obtained from the decomposition of a given polyline
/// defined by its vertex and index buffers.
#[cfg(feature = "2d")]
pub fn convex_decomposition(vertices: Vec<Vector>, indices: Vec<[u32; 2]>) -> Self {
let vertices = vertices.iter().map(|v| (*v).into()).collect::<Vec<_>>();
SharedShape::convex_decomposition(&vertices, &indices).into()
}
/// Creates a collider shape with a compound shape obtained from the decomposition of a given trimesh
/// defined by its vertex and index buffers.
#[cfg(feature = "3d")]
pub fn convex_decomposition(vertices: Vec<Vector>, indices: Vec<[u32; 3]>) -> Self {
let vertices = vertices.iter().map(|v| (*v).into()).collect::<Vec<_>>();
SharedShape::convex_decomposition(&vertices, &indices).into()
}
/// Creates a collider shape with a compound shape obtained from the decomposition of a given polyline
/// defined by its vertex and index buffers. The given [`VhacdParameters`] are used for configuring
/// the decomposition process.
#[cfg(feature = "2d")]
pub fn convex_decomposition_with_config(
vertices: Vec<Vector>,
indices: Vec<[u32; 2]>,
params: &VhacdParameters,
) -> Self {
let vertices = vertices.iter().map(|v| (*v).into()).collect::<Vec<_>>();
SharedShape::convex_decomposition_with_params(&vertices, &indices, ¶ms.clone().into())
.into()
}
/// Creates a collider shape with a compound shape obtained from the decomposition of a given trimesh
/// defined by its vertex and index buffers. The given [`VhacdParameters`] are used for configuring
/// the decomposition process.
#[cfg(feature = "3d")]
pub fn convex_decomposition_with_config(
vertices: Vec<Vector>,
indices: Vec<[u32; 3]>,
params: VhacdParameters,
) -> Self {
let vertices = vertices.iter().map(|v| (*v).into()).collect::<Vec<_>>();
SharedShape::convex_decomposition_with_params(&vertices, &indices, ¶ms.clone().into())
.into()
}
/// Creates a collider with a [convex polygon](https://en.wikipedia.org/wiki/Convex_polygon) shape obtained after computing
/// the [convex hull](https://en.wikipedia.org/wiki/Convex_hull) of the given points.
#[cfg(feature = "2d")]
pub fn convex_hull(points: Vec<Vector>) -> Option<Self> {
let points = points.iter().map(|v| (*v).into()).collect::<Vec<_>>();
SharedShape::convex_hull(&points).map(Into::into)
}
/// Creates a collider with a [convex polyhedron](https://en.wikipedia.org/wiki/Convex_polytope) shape obtained after computing
/// the [convex hull](https://en.wikipedia.org/wiki/Convex_hull) of the given points.
#[cfg(feature = "3d")]
pub fn convex_hull(points: Vec<Vector>) -> Option<Self> {
let points = points.iter().map(|v| (*v).into()).collect::<Vec<_>>();
SharedShape::convex_hull(&points).map(Into::into)
}
/// Creates a collider with a heightfield shape.
///
/// A 2D heightfield is a segment along the `X` axis, subdivided at regular intervals.
///
/// `heights` is a list indicating the altitude of each subdivision point, and `scale` controls
/// the scaling factor along each axis.
#[cfg(feature = "2d")]
pub fn heightfield(heights: Vec<Scalar>, scale: Vector) -> Self {
SharedShape::heightfield(heights.into(), scale.into()).into()
}
/// Creates a collider with a heightfield shape.
///
/// A 3D heightfield is a rectangle on the `XZ` plane, subdivided in a grid pattern at regular intervals.
///
/// `heights` is a matrix indicating the altitude of each subdivision point. The number of rows indicates
/// the number of subdivisions along the `X` axis, while the number of columns indicates the number of
/// subdivisions along the `Z` axis.
///
/// `scale` controls the scaling factor along each axis.
#[cfg(feature = "3d")]
pub fn heightfield(heights: Vec<Vec<Scalar>>, scale: Vector) -> Self {
let row_count = heights.len();
let column_count = heights[0].len();
let data: Vec<Scalar> = heights.into_iter().flatten().collect();
assert_eq!(
data.len(),
row_count * column_count,
"Each row in `heights` must have the same amount of points"
);
let heights = nalgebra::DMatrix::from_vec(row_count, column_count, data);
SharedShape::heightfield(heights, scale.into()).into()
}
/// Creates a collider with a triangle mesh shape from a `Mesh`.
///
/// Note that the resulting collider will be hollow and have no interior. This makes it more prone to tunneling and other collision issues.
///
/// The [`CollisionMargin`] component can be used to add thickness to the shape if needed.
/// For thin shapes like triangle meshes, it can help improve collision stability and performance.
///
/// ## Example
///
/// ```
/// use avian3d::prelude::*;
/// use bevy::prelude::*;
///
/// fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
/// let mesh = Mesh::from(Cuboid::default());
/// commands.spawn((
/// Collider::trimesh_from_mesh(&mesh).unwrap(),
/// PbrBundle {
/// mesh: meshes.add(mesh),
/// ..default()
/// },
/// ));
/// }
/// ```
#[cfg(feature = "collider-from-mesh")]
pub fn trimesh_from_mesh(mesh: &Mesh) -> Option<Self> {
extract_mesh_vertices_indices(mesh).map(|(vertices, indices)| {
SharedShape::trimesh_with_flags(
vertices,
indices,
TrimeshFlags::MERGE_DUPLICATE_VERTICES.into(),
)
.into()
})
}
/// Creates a collider with a triangle mesh shape from a `Mesh` using the given [`TrimeshFlags`]
/// for controlling the preprocessing.
///
/// Note that the resulting collider will be hollow and have no interior. This makes it more prone to tunneling and other collision issues.
///
/// The [`CollisionMargin`] component can be used to add thickness to the shape if needed.
/// For thin shapes like triangle meshes, it can help improve collision stability and performance.
///
/// ## Example
///
/// ```
/// use avian3d::prelude::*;
/// use bevy::prelude::*;
///
/// fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
/// let mesh = Mesh::from(Cuboid::default());
/// commands.spawn((
/// Collider::trimesh_from_mesh_with_config(&mesh, TrimeshFlags::all()).unwrap(),
/// PbrBundle {
/// mesh: meshes.add(mesh),
/// ..default()
/// },
/// ));
/// }
/// ```
#[cfg(feature = "collider-from-mesh")]
pub fn trimesh_from_mesh_with_config(mesh: &Mesh, flags: TrimeshFlags) -> Option<Self> {
extract_mesh_vertices_indices(mesh).map(|(vertices, indices)| {
SharedShape::trimesh_with_flags(vertices, indices, flags.into()).into()
})
}
/// Creates a collider with a convex polygon shape obtained from the convex hull of a `Mesh`.
///
/// ## Example
///
/// ```
/// use avian3d::prelude::*;
/// use bevy::prelude::*;
///
/// fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
/// let mesh = Mesh::from(Cuboid::default());
/// commands.spawn((
/// Collider::convex_hull_from_mesh(&mesh).unwrap(),
/// PbrBundle {
/// mesh: meshes.add(mesh),
/// ..default()
/// },
/// ));
/// }
/// ```
#[cfg(feature = "collider-from-mesh")]
pub fn convex_hull_from_mesh(mesh: &Mesh) -> Option<Self> {
extract_mesh_vertices_indices(mesh)
.and_then(|(vertices, _)| SharedShape::convex_hull(&vertices).map(|shape| shape.into()))
}
/// Creates a compound shape obtained from the decomposition of a `Mesh`.
///
/// ## Example
///
/// ```
/// use avian3d::prelude::*;
/// use bevy::prelude::*;
///
/// fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
/// let mesh = Mesh::from(Cuboid::default());
/// commands.spawn((
/// Collider::convex_decomposition_from_mesh(&mesh).unwrap(),
/// PbrBundle {
/// mesh: meshes.add(mesh),
/// ..default()
/// },
/// ));
/// }
/// ```
#[cfg(feature = "collider-from-mesh")]
pub fn convex_decomposition_from_mesh(mesh: &Mesh) -> Option<Self> {
extract_mesh_vertices_indices(mesh).map(|(vertices, indices)| {
SharedShape::convex_decomposition(&vertices, &indices).into()
})
}
/// Creates a compound shape obtained from the decomposition of a `Mesh`
/// with the given [`VhacdParameters`] passed to the decomposition algorithm.
///
/// ## Example
///
/// ```
/// use avian3d::prelude::*;
/// use bevy::prelude::*;
///
/// fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
/// let mesh = Mesh::from(Cuboid::default());
/// let config = VhacdParameters {
/// convex_hull_approximation: false,
/// ..default()
/// };
/// commands.spawn((
/// Collider::convex_decomposition_from_mesh_with_config(&mesh, &config).unwrap(),
/// PbrBundle {
/// mesh: meshes.add(mesh),
/// ..default()
/// },
/// ));
/// }
/// ```
#[cfg(feature = "collider-from-mesh")]
pub fn convex_decomposition_from_mesh_with_config(
mesh: &Mesh,
parameters: &VhacdParameters,
) -> Option<Self> {
extract_mesh_vertices_indices(mesh).map(|(vertices, indices)| {
SharedShape::convex_decomposition_with_params(
&vertices,
&indices,
¶meters.clone().into(),
)
.into()
})
}
/// Attempts to create a collider with the given [`ColliderConstructor`].
/// By using this, you can serialize and deserialize the collider's creation method
/// separately from the collider itself via the [`ColliderConstructor`] enum.
///
#[cfg_attr(
feature = "collider-from-mesh",
doc = "Returns `None` in the following cases:
- The given [`ColliderConstructor`] requires a mesh, but none was provided.
- Creating the collider from the given [`ColliderConstructor`] failed."
)]
#[cfg_attr(
not(feature = "collider-from-mesh"),
doc = "Returns `None` if creating the collider from the given [`ColliderConstructor`] failed."
)]
pub fn try_from_constructor(
collider_constructor: ColliderConstructor,
#[cfg(feature = "collider-from-mesh")] mesh: Option<&Mesh>,
) -> Option<Self> {
match collider_constructor {
#[cfg(feature = "2d")]
ColliderConstructor::Circle { radius } => Some(Self::circle(radius)),
#[cfg(feature = "3d")]
ColliderConstructor::Sphere { radius } => Some(Self::sphere(radius)),
#[cfg(feature = "2d")]
ColliderConstructor::Ellipse {
half_width,
half_height,
} => Some(Self::ellipse(half_width, half_height)),
#[cfg(feature = "2d")]
ColliderConstructor::Rectangle { x_length, y_length } => {
Some(Self::rectangle(x_length, y_length))
}
#[cfg(feature = "3d")]
ColliderConstructor::Cuboid {
x_length,
y_length,
z_length,
} => Some(Self::cuboid(x_length, y_length, z_length)),
#[cfg(feature = "2d")]
ColliderConstructor::RoundRectangle {
x_length,
y_length,
border_radius,
} => Some(Self::round_rectangle(x_length, y_length, border_radius)),
#[cfg(feature = "3d")]
ColliderConstructor::RoundCuboid {
x_length,
y_length,
z_length,
border_radius,
} => Some(Self::round_cuboid(
x_length,
y_length,
z_length,
border_radius,
)),
#[cfg(feature = "3d")]
ColliderConstructor::Cylinder { radius, height } => {
Some(Self::cylinder(radius, height))
}
#[cfg(feature = "3d")]
ColliderConstructor::Cone { radius, height } => Some(Self::cone(radius, height)),
ColliderConstructor::Capsule { radius, height } => Some(Self::capsule(radius, height)),
ColliderConstructor::CapsuleEndpoints { radius, a, b } => {
Some(Self::capsule_endpoints(radius, a, b))
}
ColliderConstructor::HalfSpace { outward_normal } => {
Some(Self::half_space(outward_normal))
}
ColliderConstructor::Segment { a, b } => Some(Self::segment(a, b)),
ColliderConstructor::Triangle { a, b, c } => Some(Self::triangle(a, b, c)),
#[cfg(feature = "2d")]
ColliderConstructor::RegularPolygon {
circumradius,
sides,
} => Some(Self::regular_polygon(circumradius, sides)),
ColliderConstructor::Polyline { vertices, indices } => {
Some(Self::polyline(vertices, indices))
}
ColliderConstructor::Trimesh { vertices, indices } => {
Some(Self::trimesh(vertices, indices))
}
ColliderConstructor::TrimeshWithConfig {
vertices,
indices,
flags,
} => Some(Self::trimesh_with_config(vertices, indices, flags)),
#[cfg(feature = "2d")]
ColliderConstructor::ConvexDecomposition { vertices, indices } => {
Some(Self::convex_decomposition(vertices, indices))
}
#[cfg(feature = "3d")]
ColliderConstructor::ConvexDecomposition { vertices, indices } => {
Some(Self::convex_decomposition(vertices, indices))
}
#[cfg(feature = "2d")]
ColliderConstructor::ConvexDecompositionWithConfig {
vertices,
indices,
params,
} => Some(Self::convex_decomposition_with_config(
vertices, indices, ¶ms,
)),
#[cfg(feature = "3d")]
ColliderConstructor::ConvexDecompositionWithConfig {
vertices,
indices,
params,
} => Some(Self::convex_decomposition_with_config(
vertices, indices, params,
)),
#[cfg(feature = "2d")]
ColliderConstructor::ConvexHull { points } => Self::convex_hull(points),
#[cfg(feature = "3d")]
ColliderConstructor::ConvexHull { points } => Self::convex_hull(points),
#[cfg(feature = "2d")]
ColliderConstructor::Heightfield { heights, scale } => {
Some(Self::heightfield(heights, scale))
}
#[cfg(feature = "3d")]
ColliderConstructor::Heightfield { heights, scale } => {
Some(Self::heightfield(heights, scale))
}
#[cfg(feature = "collider-from-mesh")]
ColliderConstructor::TrimeshFromMesh => Self::trimesh_from_mesh(mesh?),
#[cfg(all(feature = "collider-from-mesh", feature = "default-collider"))]
ColliderConstructor::TrimeshFromMeshWithConfig(flags) => {
Self::trimesh_from_mesh_with_config(mesh?, flags)
}
#[cfg(feature = "collider-from-mesh")]
ColliderConstructor::ConvexDecompositionFromMesh => {
Self::convex_decomposition_from_mesh(mesh?)
}
#[cfg(all(feature = "collider-from-mesh", feature = "default-collider"))]
ColliderConstructor::ConvexDecompositionFromMeshWithConfig(params) => {
Self::convex_decomposition_from_mesh_with_config(mesh?, ¶ms)
}
#[cfg(feature = "collider-from-mesh")]
ColliderConstructor::ConvexHullFromMesh => Self::convex_hull_from_mesh(mesh?),
}
}
}
#[cfg(feature = "collider-from-mesh")]
type VerticesIndices = (Vec<nalgebra::Point3<Scalar>>, Vec<[u32; 3]>);
#[cfg(feature = "collider-from-mesh")]
fn extract_mesh_vertices_indices(mesh: &Mesh) -> Option<VerticesIndices> {
let vertices = mesh.attribute(Mesh::ATTRIBUTE_POSITION)?;
let indices = mesh.indices()?;
let vtx: Vec<_> = match vertices {
VertexAttributeValues::Float32(vtx) => Some(
vtx.chunks(3)
.map(|v| [v[0] as Scalar, v[1] as Scalar, v[2] as Scalar].into())
.collect(),
),
VertexAttributeValues::Float32x3(vtx) => Some(
vtx.iter()
.map(|v| [v[0] as Scalar, v[1] as Scalar, v[2] as Scalar].into())
.collect(),
),
_ => None,
}?;
let idx = match indices {
Indices::U16(idx) => idx
.chunks_exact(3)
.map(|i| [i[0] as u32, i[1] as u32, i[2] as u32])
.collect(),
Indices::U32(idx) => idx.chunks_exact(3).map(|i| [i[0], i[1], i[2]]).collect(),
};
Some((vtx, idx))
}
fn scale_shape(
shape: &SharedShape,
scale: Vector,
num_subdivisions: u32,
) -> Result<SharedShape, UnsupportedShape> {
let scale = scale.abs();
match shape.as_typed_shape() {
TypedShape::Cuboid(s) => Ok(SharedShape::new(s.scaled(&scale.abs().into()))),
TypedShape::RoundCuboid(s) => Ok(SharedShape::new(RoundShape {
border_radius: s.border_radius,
inner_shape: s.inner_shape.scaled(&scale.abs().into()),
})),
TypedShape::Capsule(c) => match c.scaled(&scale.abs().into(), num_subdivisions) {
None => {
log::error!("Failed to apply scale {} to Capsule shape.", scale);
Ok(SharedShape::ball(0.0))
}
Some(Either::Left(b)) => Ok(SharedShape::new(b)),
Some(Either::Right(b)) => Ok(SharedShape::new(b)),
},
TypedShape::Ball(b) => {
#[cfg(feature = "2d")]
{
if scale.x == scale.y {
Ok(SharedShape::ball(b.radius * scale.x.abs()))
} else {
// A 2D circle becomes an ellipse when scaled non-uniformly.
Ok(SharedShape::new(EllipseWrapper(Ellipse {
half_size: Vec2::splat(b.radius as f32) * scale.f32().abs(),
})))
}
}
#[cfg(feature = "3d")]
match b.scaled(&scale.abs().into(), num_subdivisions) {
None => {
log::error!("Failed to apply scale {} to Ball shape.", scale);
Ok(SharedShape::ball(0.0))
}
Some(Either::Left(b)) => Ok(SharedShape::new(b)),
Some(Either::Right(b)) => Ok(SharedShape::new(b)),
}
}
TypedShape::Segment(s) => Ok(SharedShape::new(s.scaled(&scale.into()))),
TypedShape::Triangle(t) => Ok(SharedShape::new(t.scaled(&scale.into()))),
TypedShape::RoundTriangle(t) => Ok(SharedShape::new(RoundShape {
border_radius: t.border_radius,
inner_shape: t.inner_shape.scaled(&scale.into()),
})),
TypedShape::TriMesh(t) => Ok(SharedShape::new(t.clone().scaled(&scale.into()))),
TypedShape::Polyline(p) => Ok(SharedShape::new(p.clone().scaled(&scale.into()))),
TypedShape::HalfSpace(h) => match h.scaled(&scale.into()) {
None => {
log::error!("Failed to apply scale {} to HalfSpace shape.", scale);
Ok(SharedShape::ball(0.0))
}
Some(scaled) => Ok(SharedShape::new(scaled)),
},
TypedShape::HeightField(h) => Ok(SharedShape::new(h.clone().scaled(&scale.into()))),
#[cfg(feature = "2d")]
TypedShape::ConvexPolygon(cp) => match cp.clone().scaled(&scale.into()) {
None => {
log::error!("Failed to apply scale {} to ConvexPolygon shape.", scale);
Ok(SharedShape::ball(0.0))
}
Some(scaled) => Ok(SharedShape::new(scaled)),
},
#[cfg(feature = "2d")]
TypedShape::RoundConvexPolygon(cp) => match cp.inner_shape.clone().scaled(&scale.into()) {
None => {
log::error!(
"Failed to apply scale {} to RoundConvexPolygon shape.",
scale
);
Ok(SharedShape::ball(0.0))
}
Some(scaled) => Ok(SharedShape::new(RoundShape {
border_radius: cp.border_radius,
inner_shape: scaled,
})),
},
#[cfg(feature = "3d")]
TypedShape::ConvexPolyhedron(cp) => match cp.clone().scaled(&scale.into()) {
None => {
log::error!("Failed to apply scale {} to ConvexPolyhedron shape.", scale);
Ok(SharedShape::ball(0.0))
}
Some(scaled) => Ok(SharedShape::new(scaled)),
},
#[cfg(feature = "3d")]
TypedShape::RoundConvexPolyhedron(cp) => {
match cp.clone().inner_shape.scaled(&scale.into()) {
None => {
log::error!(
"Failed to apply scale {} to RoundConvexPolyhedron shape.",
scale
);
Ok(SharedShape::ball(0.0))
}
Some(scaled) => Ok(SharedShape::new(RoundShape {
border_radius: cp.border_radius,
inner_shape: scaled,
})),
}
}
#[cfg(feature = "3d")]
TypedShape::Cylinder(c) => match c.scaled(&scale.abs().into(), num_subdivisions) {
None => {
log::error!("Failed to apply scale {} to Cylinder shape.", scale);
Ok(SharedShape::ball(0.0))
}
Some(Either::Left(b)) => Ok(SharedShape::new(b)),
Some(Either::Right(b)) => Ok(SharedShape::new(b)),
},
#[cfg(feature = "3d")]
TypedShape::RoundCylinder(c) => {
match c.inner_shape.scaled(&scale.abs().into(), num_subdivisions) {
None => {
log::error!("Failed to apply scale {} to RoundCylinder shape.", scale);
Ok(SharedShape::ball(0.0))
}
Some(Either::Left(scaled)) => Ok(SharedShape::new(RoundShape {
border_radius: c.border_radius,
inner_shape: scaled,
})),
Some(Either::Right(scaled)) => Ok(SharedShape::new(RoundShape {
border_radius: c.border_radius,
inner_shape: scaled,
})),
}
}
#[cfg(feature = "3d")]
TypedShape::Cone(c) => match c.scaled(&scale.into(), num_subdivisions) {
None => {
log::error!("Failed to apply scale {} to Cone shape.", scale);
Ok(SharedShape::ball(0.0))
}
Some(Either::Left(b)) => Ok(SharedShape::new(b)),
Some(Either::Right(b)) => Ok(SharedShape::new(b)),
},
#[cfg(feature = "3d")]
TypedShape::RoundCone(c) => match c.inner_shape.scaled(&scale.into(), num_subdivisions) {
None => {
log::error!("Failed to apply scale {} to RoundCone shape.", scale);
Ok(SharedShape::ball(0.0))
}
Some(Either::Left(scaled)) => Ok(SharedShape::new(RoundShape {
border_radius: c.border_radius,
inner_shape: scaled,
})),
Some(Either::Right(scaled)) => Ok(SharedShape::new(RoundShape {
border_radius: c.border_radius,
inner_shape: scaled,
})),
},
TypedShape::Compound(c) => {
let mut scaled = Vec::with_capacity(c.shapes().len());
for (iso, shape) in c.shapes() {
scaled.push((
#[cfg(feature = "2d")]
make_isometry(
Vector::from(iso.translation) * scale,
Rotation::radians(iso.rotation.angle()),
),
#[cfg(feature = "3d")]
make_isometry(
Vector::from(iso.translation) * scale,
Quaternion::from(iso.rotation),
),
scale_shape(shape, scale, num_subdivisions)?,
));
}
Ok(SharedShape::compound(scaled))
}
TypedShape::Custom(_id) => {
#[cfg(feature = "2d")]
if _id == 1 {
if let Some(ellipse) = shape.as_shape::<EllipseWrapper>() {
return Ok(SharedShape::new(EllipseWrapper(Ellipse {
half_size: ellipse.half_size * scale.f32().abs(),
})));
}
} else if _id == 2 {
if let Some(polygon) = shape.as_shape::<RegularPolygonWrapper>() {
if scale.x == scale.y {
return Ok(SharedShape::new(RegularPolygonWrapper(
RegularPolygon::new(
polygon.circumradius() * scale.x.abs() as f32,
polygon.sides,
),
)));
} else {
let vertices = polygon
.vertices(0.0)
.into_iter()
.map(|v| v.adjust_precision().into())
.collect::<Vec<_>>();
return scale_shape(
&SharedShape::convex_hull(&vertices).unwrap(),
scale,
num_subdivisions,
);
}
}
}
Err(parry::query::Unsupported)
}
}
}