#Avian Physics
1 messages ยท Page 17 of 1
Anyways, the regression test works at least locally
If the CI agrees, my PR is ready again ๐
Nice, it should be good to go then ๐ I'll give it a final final look tomorrow when I'm not as tired, and get it merged
Sounds good! good night then ๐ค
Merged! ๐
Yay ๐
is there a way to set collisionlayers for all objects spawned from gltf scene?
Alrighty, here is finally the initial solver rework PR:
https://github.com/Jondolf/bevy_xpbd/pull/385
I might still add things to the description if I have energy for that ๐
Right now, I don't think so ๐ค
@visual sparrow Maybe we should change default_constructor to default_config, and add with_default_layers and with_default_density or something?
Or just add default_layers and default_density as their own properties
That would make sense, yeah
Btw, collision layers are not inherited, right?
They're not
Would that maybe make sense? When I add a collision layer on a rigid body with nested children, it would probably be useful
(at least in my own project, I manually cascade them after placing them on the rigid body)
If they were, there would need to be a separate mechanism to opt-out of inheritance
You could just take whichever CollisionLayers is closes to you in the hierarchy
Also I don't think e.g. Godot or Unity have layer inheritance(?)
So if your collider has an own CollisionLayers, that one wins
Ah, that's probably a good precedent then
I'll try to make a PR today then
Ping me if you want a review ๐
I'll try to take a look at this tomorrow, but it's probably wayyyy over my head haha
yeah I don't expect anyone to review that lol
inheritance doesn't always make sense, you might have parent having "human" layer, you wouldn't want the "gun" child object to be human too
default layers is good though
also, do all colliders have layers automatically added? adding access to it without getting it from query would be nice
that's basically what unity does, and with each object having multiple layers it'd be even better
no CollisionLayers isn't added automatically for colliders
is there any good reason not to?
It's not really required for collision detection, and not having it at all is equivalent to having CollisionLayers::default()
it's always used by shape/raycasts filter, is it possible to add layers to shapehitdata?
If you wanted to get the layers, you could query for them using the entities in the hit data
yeah, that's what i'm already doing, i'm just asking if it's a bad idea to streamline it
in unity you get it with collision.collider.layer or hit.collider.layer and that's it
You could make an argument for adding a ton of data to the hits, like the GlobalTransform, ColliderParent, or even Name, but I don't see much value in cloning data like this unless there is a very high usability gain involved. These things can be queried for, but the hit data should mostly contain what you can't query for (i.e. the actual data related to the hit geometry and the entities involved)
It might be a bit more annoying than in Unity, but with Rust and the ECS I don't think we can reasonably do what Unity does there
ok that's a fair point, but i use layers every time with ray/shape casts ๐ it's not that big of an issue though, i was just wondering if it'd be easy to get rid of the boilerplate
Okay wearing my ๐งช hat;
Currently, you might do something like this:
fn ray_cast(
query: Query<(&GlobalTransform, &CollisionLayers), With<Player>>,
spatial: SpatialQuery,
) {
for hit in spatial.ray_hits(...) {
if let Ok((global_transform, layers)) = query.get(hit.entity) {
// ...
}
}
}
I think I've had a similar idea some time before, but we could embrace the idea of spatial queries just being a special case of Query, and have something like this:
fn ray_cast(query: SpatialQuery<(&GlobalTransform, &CollisionLayers), With<Player>>) {
for (hit, (global_transform, layers)) in query.ray_hits(...) {
// ...
}
}
Internally it would be very similar to the existing approach, just abstracted away. And maybe we could figure out some optimizations too
If we wanted to go into even more ๐งช territory, we could make this agnostic to the spatial query backend, so you could even do ray casts on meshes like bevy_mod_raycast by just using a Mesh backend
I don't think this would even require breaking changes since SpatialQuery without components or filters would just return the spatial query results like it currently does
i never understood how spatialquery works, it just looks like magic to me ๐คทโโ๏ธ
Internally there's a SpatialQueryPipeline resource that maintains a bounding volume hierarchy for the world's colliders, SpatialQuery is just a system parameter that calls methods to query that BVH
i think you'd need to write a whole blog post to properly explain it ๐
Less magic to me than Physics.Raycast in Unity :P
maybe it's worth doing actually, trying to explain it could make something click for the ๐งช stuff
although basically equivalent
yeah unity source is closed so everything is magic there
idk about nvidia physx though
Spatial queries pretty much always have a BVH, that's what you have even in graphics for ray-tracing
i don't think unity's approach would work that well though, it just gives mutable access to a lot of stuff even without GetComponent
whole collider, the parent collider, tag, layer, transform, rigidbody... easier to just link you the doc
With this you could easily do that, but only get the components you actually need, and optionally have query filters on there too
Well it'd have the same limitations as Query does, i.e. you can't have other queries with mutable access to the same components unless the queries are disjoint
Same as the current SpatialQuery, just with Query functionality baked in to reduce the boilerplate
ah, the current one doesn't have any problems because it uses only physics pos+rot?
I can get rid of even that issue, just haven't had time for it yet
and entity/collisionlayers don't cause any conflicts because i never mutated them?
The SpatialQueryPipeline basically has a copy of the world's colliders and some other necessary components, and it's updated automatically, so SpatialQuery doesn't actually require World access at all (or currently it does, but I can get rid of it)
So it shouldn't cause any conflicts
then it sounds really good
i have no idea who needs stuff like this, but i think you'd eventually have to figure out something for the edge cases like that anyway
although nvm, i guess you could do that with query boilerplate too
yeah
I would also imagine that you can get that if you just have the Mesh and hit point
Dunno if we have a helper on Mesh for it though
just working on anything that needs to access uv/texture sounds like a much bigger headache than just getting that point
i've seen access to material being used for matching footstep sounds and decals though
PR here if you wanna take a look, no hurry though
https://github.com/Jondolf/bevy_xpbd/pull/386
I've used this once to allow clicking through transparent things: RaycastAll from the click and check to make sure that you're actually hitting a visible pixel
A lil branding for the docs
Still not 100% sure what I should do for the small icon
I think the feather in water scaled down 40% over the current small logo would look nice
Initially I had this but it's a bit hard to see the details
especially for the favicon
Might be better without the background color? Although there's less contrast
(I also simplified the ripples a bit for the icon)
gosh the logo is so awesome
in this case it's better without BG color imo
for light theme I currently just have a drop shadow to make it somewhat legible
think the border circle somehow clashes with the ripples (talking about the small logo with dark background color)
Tweaked a little so the icon is larger and the ripples are a bit thicker, I think this is probably good enough
kinda yes
it looks weird if it's just flat
The ripples trace the outlines of actual ellipses
Does this look better then?
I'd have to redo the lines at least since they look disconnected and are partially hidden if I do that
and now it's a half-sphere collider
if only we had half-spheres as a collider shape
I for one prefered the logo before, having the feather centered makes it have too much negative space, and the tilt made it more dynamic
same
tilt is for dynamic, not centered is for negative space ๐
if we look at other physics engine, https://www.havok.com/wp-content/uploads/2020/06/havok-logo-flat.png is going all in on "dynamic" and zero on physics, https://developer-blogs.nvidia.com/wp-content/uploads/2018/12/PhysX.png is "hey we're nvidia, need anything else?", https://box2d.org/images/logo.svg is "look, we do boxes, ok?"
I feel like this could maybe work for the icon, but for this banner logo imo it loses a part of the idea and cohesion
you could remove the ripples temporarily and add them when you have something that just clicks
Like the "Physics" text is blue to match the water as if it's underwater, for example
that looked like garbage
#art-audio-animation message
the current logo already went through a ton of designshedding(?)
Gut-reaction wise, I like this one the most ๐ But the ones right before and after it are pretty much equally as good
Here is a (hopefully not too strange) question
I'm currently working on adding some unit tests to my game and i'm testing a query that relies on &ShapeHits being on an entity
I don't add the full PhysicsPlugin to the world for this test, so I'm wondering if there is a way to add ShapeHits to an entity manually since the fields are private and it doesn't impl Default
hmm I should probably add a way to construct that manually, but I think you need SpatialQueryPlugin and PhysicsSetupPlugin for now
then it'll add it automatically for entities with ShapeCaster
(in Avian, there's a PhysicsSchedulePlugin which you could use instead of PhysicsSetupPlugin)
ah wait you might need PreparePlugin actually, since IIRC it adds some system sets used by SpatialQueryPlugin
I should really reduce the plugin dependencies here ๐ค you shouldn't need so many plugins for this
nice, I think I should be able to get it down to requiring just SpatialQueryPlugin though
or maybe not even that since I could just add ShapeHits with a lifecycle hook
@sleek thicket A slightly more refined version of the idea
Might need to tweak the sizes a bit more ๐ค
As far as the rebrand goes, will the high level API remain fairly consistent?
yes
module structure and system ordering will change but if you use the prelude and don't rely on too many internal system sets then not too much should be different API-wise
tilt in what way?
Are we not looking at it straight from the top? The feather isn't perfectly straight but that doesn't say much about the viewpoint
It'll vary based on the type of feather
They're both gorgeous ๐
Bottom one looks less boring
I like the original one since the color is more evenly distributed and the text and water match better, which was one of the reasons it was designed like that
and it's maybe more dynamic and not just a feather floating on water, which implies fluid simulation stronger (though I guess both kinda do)
the feather is also larger and more emphasized in the original one, and I consider the feather more important here
I like that the colors of white on top, blue on bottom match
make the 'i' in Avian blue and it will start looking like the Finnish flag ๐ซ๐ฎ /j
(ignore the instability at the end)
nah this is clearly better #art-audio-animation message
10 kg feathers vs. 10 kg weight
heheehehe
Is there an easy way to build a LayerMask from an enum that derives PhysicsLayer?
I think you can just do LayerMask::from(my_enum)
eyy, doing that and a bitwise or on the masks works, thanks!
i agree to keep the original, even with the tilted plane for the ripples
like you said: the symmetry between the text + ripple color is more important, followed by center balance + alignment of ripple + feather as the icon
if anyone asks why the water is not flat, tell them it's fluid dynamics and the feather is actually hitting a wave ๐
the top down view looks like you're looking through a scope and about to snipe a feather, all you need is the red dot
The logo and Bevy itself are pretty fitting for me considering the Finnish form of my first name originates from a Hebrew word meaning "dove" (the bird) and my last name in Finnish means "wave"
literally bird + wave
what an awesome origin story, your life's calling! only the beginning
were there any particular reasons for feather and water in the first place?
feather because it fits "avian" and physics, and the ripples because it looked boring with just the feather
initially I tried wind lines and stuff but the ripple was unique and looked nice
you could have a bird in water and it'd still fit avian
masterfully crafted by Nise #art-audio-animation message
a bird in water wouldn't have a physics association for me, and it'd just look like a modified Bevy logo
it'd also be hard to make in a way where it'd work in icon form, the feather is already not ideal even though it's pretty simple
feather is more of a byproduct of avian, it's not the first thing you'd think about when hearing it
it looks fine though, i'm just not sure why you're so fixated on it
and the ripples that cause so much headache
if you don't add the plane of reference then the feather can be in any orientation without any problems
people clearly preferred the ripples over the other variants I tried at least
like the wind ones
and with just the feather it looks super generic and boring
i don't even know what you can do with a feather to make it interesting
it doesn't have to be a feather either, but I do want something that fits both Bevy/birds and physics in some way, and the main viable options there imo are a feather or a wing
"Avian gives you wings" hehe
why not bird? you could make something like firefox but waterbird
hugging a sphere collider
If I do a full bird then it just looks like a clone or weird variant of the Bevy logo, and again it's hard to get a meaningful physics association there, especially if you want it to be visible as a 64x64 or even 32x32 pixel icon
Also my art skills would not be good enough to make a good-looking logo of a bird hugging a collider lol
I also want to keep it relatively minimalistic like Bevy's logo and Bevy itself, and a bird doing X action would be kinda hard to do in a minimalistic style
Why are you killing birds with blue marbles? 
it's not dead
and it can be anything. invisible or outline of a collider. or water.
It will be once it hits the ground and gets crushed by the oversized marble that knocked it out of the air 
it's static so it won't ๐
If there were wind lines on the right side it'd looks like the bird is getting sniped by a (friendly :D) cannon ball
reverse angry bird?
an AI is playing angry birds, but you need to build structures and stop birds midair to protect the pigs
ngl that's a pretty good idea lol
animal cruelty^2
and it's more than a good idea, it's actually worth making it
although it sounds like a flash/mobile game that might already exist
Yeah frankly this sounds genuinely good
did someone say flash/mobile game that might already exist? ๐
that's kinda our thing at Cult, Inc.
angry AT birdsโข
@vestal minnow I've left a review on the ColliderConstructor PR and a small code quality pass on the solver rework.
Thanks! I'll try to address them later today ๐
Already added some benchmark results
(I don't have much experience with proper benchmarking though so they're pretty basic)
Pretty good numbers then ๐
Feel free to disagree on many of them, a lot of them are "I personally like to track TODO comments with corresponding issues" and I know that is personal preference ๐
Any ideas how these improvements came to be?

Yeah some of them could definitely have issues, although it might be a bit weird to have issues for things that aren't even merged
but of course you can just mention that in the issue
I agree, but given that this PR will definitely get merged soon, I think it's fine
The PR has a good writeup about the performance!
alr ty :)
Moving the narrow phase outside of the substepping loop is a big one, and the main reason why performance doesn't degrade quite as quickly as the number of substeps is increased
Otherwise it's a bit harder to say, but I managed to remove a bunch of unnecessary allocations, and also use more par_iter in some places
Ah okay, that makes sense. How do you keep track of collisions after each solve then though?

BTW @vestal minnow for my own project, I need to create a quake-style first person controller and HL2-style picking up objects. I've nearly started work on that today, but decided that maybe it would be best to wait until the Avian stuff is merged so I don't have to change things again. I'll definitely put these two into their own crates for other people to reuse, but I wanted to ask if that is something you'd be interested in upstreaming. My own guess is probably not, since these things are tend to be fairly specific to a given game, but then again rapier comes with a builtin character controller, so idk
See "Collision Detection Refactor" section in the PR, and the TGS section in the Solver2D post
you can just store contact data in local space and approximate the current data at each substep based on the current poses of the bodies
I would probably be interested in potentially adding a kinematic character controller of some kind, with a collide-and-slide style algorithm along with the usual slope snapping, stair climbing etc., something like what Rapier has (although I really dislike some of its design choices)
Either way I'd probably start in a separate crate
I'm not entirely sure if it makes sense living in the physics engine itself anyway, even if there was an "official" solution
Yeah, agreed
Oh and also in these benches the old and new version were both using the same number of substeps to make it comparable, but for the new solver, I've cut the old default substep count of 12 in half to just 6 since its enough for stability for like 95% of cases. So if we're looking at default performance, the difference is even bigger
hmm thats nice 
IIRC Box2D V3 (which has a very similar solver) has just 4 substeps by default, so we could probably reduce it even further
quake-style with diagonal bug and weird acceleration?
Diagonal bug not, but weird acceleration is kind of a feature of this style of character controller, haha
i guess you could just make a toggle for max speed/acceleration
I'll iterate and see what feels best ๐
i basically had that in unity but decided to focus on other stuff so i don't burn out and start procrastinating
still ended up procrastinating
Yeah, Iโve wasted ages on character controllers as well
There's soooooo much to tweak
i wanted to finish making anti-gravity that feels good, instead i came with realization of why it felt bad but got stuck with solution
i basically expect that moving doesn't move camera on right/up axis, only forward...
and that given same input and no manual camera rotation, you'd end up in same place and same rotation...
and i keep breaking either one or the other
How do you best handle moving platforms with them?
@quartz heart if you use spring+hovering collider (which i recommend if there's no good argument against it), you just get underlying platform's acceleration/speed and add it to character
i think very very valet video even covered that
Yeah thatโs what I did, but was wondering if there are smarter/better ways to handle it? (Some suggest parenting, but Iโm not in favor of that)
parenting fucked me over so many times that i learned to avoid it entirely
Can I quote you on that? ๐
edited it a bit to make it even better out of context ๐ now you can
anyways, thinking with plain logic is probably the best thing to approach most problems, and turning player into platform's child is basically welding player to it
or even worse, if you rescale the platform then you also rescale player/decals, so you probably don't wanna touch scale either way
hey @vestal minnow how's going?
I just wanna say that XPBD is fantastic and really easy to use, which i really love!
But could've be possible to add the point where the ray hits to RayHitData, in form of a Vec2 (or Vec3 if you're using 3D)?
Mostly because i'm using a raycast to check if the player touched the ground with spatial_query.ray_hits(...) (spawning a small ray pointing at negative Y), but i want to use that raycast to snap the player to where the raycast hit.
I tried to use time_of_impact for that, but its not enough info, and it only works great at 60fps, so its not framerate independant.
let end = pos + (dir * hit.time_of_impact);
ooo let me give it a try hold on
i managed to make it work, but the raycast's size has to be the size of the player + 0.1, but yea, thank you for the workaround :D, i'll use it for now
still, adding a point: Vec2/Vec3 to RayHitData could've be a nice feature to add
it's not a workaround, it's boilerplate
for the stuff that i want to do, it is a workaround
spherecast would account for player radius but might have weird side-effects with slopes/stairs
for raycast you can just subtract it let end = pos + (dir * (hit.time_of_impact - player_radius - 0.1));
yeah, that's why i was planning to use 3 raycasts
one in the middle, one on the left, and the last one on the right of the player
once i tried hovering collider approach i liked it so much that now i'd attempt to use it even if it's a bad idea
if it works, it ain't a bad idea lmao
for 2d with sprites it'd probably cause some headache though
yeah, but probably because there's not a lot of stuff in xpbd yet
unrelated
i mean, you could fix some issues by freezing rotations
https://www.youtube.com/watch?v=qdskE8PJy6Q
^ this is what i'm talking about, just for context
A detailed look at how we built our physics-based character controller in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam
BUY NOW!! https://toyful.games/vvv-buy
~ More from Toyful Games ~
- Animation Deep Dive mentioned in the video - https://toyful.games/blog/character-animations
- Custom Car Physics in Unity...
TNUA also ended up using it, no idea if it has anything for 2d+sprite
you could fix some issues in 2d if you have rotation axis freeze on the rigidbodies afaik
rotation isn't the issue
you just do it exactly the same as you'd do it without the floating collider
the issue is matching sprites, not impossible but might kill the good part of the controller
you could have a few sprites for landing, but then you'd have to match the offset
yeah, that was one of the ideas i had to fix this issue in particular, but i discarded it
i messed around with sidescroller and without sprites it felt really good though, so i'm just wondering how it'd be with them (if done properly)
yeah, it could've be a cool experiment lmao
if let Some(hit) = physics.cast_ray(DIY)
{ player.falling_duration = 0.0; // == player.grounded = true;
if hit.normal.dot(up) > 0.95
{ let offset = ground_rest_distance - hit.time_of_impact;
let upward_velocity = lv.0.dot(up);
let force = (offset * strength) - (upward_velocity * damping);
lv.0 += up * force;
} }
else
{ player.falling_duration += time_delta; // == player.grounded = false;
lv.0 -= 10.0 * time_delta; // gravity
}
that's basically the main chunk of code + slope check + grounded/coyote time
play around with it and see how it feels
YOOOO THANK YOU SO MUCH!
sure, i'll give it a try!
watch the very very valet devs' videos to actually understand it and good luck
sure sure, thank you for all of this info man, appreciate it :D
did some math and it apparently is bullshit
Just saw xpbd is rebranding into avain. I'm currently using xpbd for collision detection in my game. I wonder if the new avain package would change a lot on how collision API looks like? I don't care much about the underlying solver logic. I'm mostly concerned from API perspective. Thanks
Which parts of the API are you using? The contact data types have a few changed and added properties, and the narrow phase's systems have changed a bit
The narrow phase also runs in PhysicsSchedule instead of SubstepSchedule
I'm using RigidBody::Kinematic to mark an entity to detect collision events. I'm not using anything like force, friction, but directly modify the object's LinearVelocity for movement. I'm also using PhysicsLayer, CollisionLayer to filter different types of collisions
Yeah there shouldn't really be any breaking changes for that in terms of collision detection
I did realize though that I should probably move generate_constraints back to the solver for now so that the narrow phase and solver wouldn't be coupled... I'd just like to merge it into the narrow phase eventually since it'd be much more efficient, but I can't do that yet since it'd kinda break PostProcessCollisions
I'm a beginner, and I encountered a problem shown in a video while learning about FixedJoint in avian3d. I created two Cuboids and connected them with a FixedJoint, then placed them on the ground. They suddenly exploded and flew away. What's causing this problem?
commands.spawn((
PbrBundle {
mesh: meshes.add(Cuboid::new(20., 0.5, 20.)),
material: materials.add(Color::Srgba(ORANGE)),
transform: Transform::from_xyz(0., -0.25, 0.),
..default()
},
RigidBody::Static,
Collider::cuboid(20., 0.5, 20.),
Name::new("Ground"),
));
let cuboid_mesh_handle = meshes.add(Cuboid::default());
let cuboid_collider = Collider::cuboid(1., 1., 1.);
let red_cuboid = commands
.spawn((
PbrBundle {
mesh: cuboid_mesh_handle.clone(),
material: materials.add(Color::Srgba(RED)),
transform: Transform::from_xyz(-1.5, 0.5, 0.),
..default()
},
RigidBody::Dynamic,
cuboid_collider.clone(),
RedCuboid,
Name::new("Red Cuboid"),
))
.id();
let blue_cuboid = commands
.spawn((
PbrBundle {
mesh: cuboid_mesh_handle,
material: materials.add(Color::Srgba(BLUE)),
transform: Transform::from_xyz(1.5, 0.5, 0.),
..default()
},
RigidBody::Dynamic,
cuboid_collider,
BlueCuboid,
Name::new("Blue Cuboid"),
))
.id();
commands.spawn(
FixedJoint::new(red_cuboid, blue_cuboid)
.with_local_anchor_1(Vec3::X * 1.5)
.with_local_anchor_2(Vec3::NEG_X * 1.5)
);```
Hmm, this seems to be an issue with how the collision and joint interact ๐ค it works better if you drop the boxes from higher, but it's still a bit explosive on the initial contact. I'll investigate
Btw what branch or version are you testing this on? bevy_xpbd 0.4, the repository's solver-rework branch, or something else?
Throwing a cuboid from a high place also causes it to explode, but it only explodes at the beginning. After exploding and falling down, it returns to normal. I'm using the avian branch of bevy_xpbd.
Okay that's "good" in the sense that it's not a regression with the new solver at least, since the avian branch still has the old solver for now. Of course this needs to get fixed though
Does it only explode when the boxes land perfectly flat? Like, if you rotate them slightly, is it better?
After rotating the cuboid, it also immediately explodes and flies away. It doesn't seem to improve the situation.
If you increase the compliance value, the intensity of the explosion decreases. However, there's a chance that it will fold up. This means two cuboids rotate 90 degrees along the anchor point and stick together, similar to how paper folds.
There's also this issue with a near-identical scenario
https://github.com/Jondolf/bevy_xpbd/issues/229
There, a small rotation fixed it, at least with a rotation about the X axis
It's really weird though, since it seems to only be an issue for the initial angular correction when something affects the bodies the first time (collision, another joint, etc.)
Almost makes it seem like there's some singularity or the correction sign is somehow flipped, but I don't understand what could be causing it, the angular correction is computed exactly like the XPBD rigid body simulation paper suggests
doesn't seem like a rotation normalization issue either
The revolute joint is fine, even with angle limits set to zero, but the fixed joint and prismatic joint both have this issue since they use the same angular correction
wait what
I tried the solver-rework branch of bevy_xpbd and encountered the same issues. The cuboids still explode and fly away, and increasing compliance results in folding.
HUH??? Okay so the angular correction seems to be flipped, negating it makes things work perfectly fine I think
but how tf did it work at all after the initial explosiveness if the correction was opposite from what it's supposed to be???
Either way I'm pretty sure I fixed it, but I need to test more though since I'm very confused
This should fix it
https://github.com/Jondolf/bevy_xpbd/pull/388
The PR targets main but I'll add it to avian as well
@visual sparrow comments for the collider constructor hierarchy PR should be addressed
https://github.com/Jondolf/bevy_xpbd/pull/386
Sweet! I'm right in the middle of finishing the first draft of the June edition of This Month in Rust GameDev, so I'll check it out in an hour or so ๐
Done. LGTM, I'd just add a test for it ๐
Thanks! Yeah, I'll add a test or two
I'll also try to do some more review work on the contact solver PR tomorrow
added a test
Don't worry, crabs can regrow lost limbs!
Brilliant ๐
Shouldn't that test also check the generated densities?
The test above it checks densities
Ah yeah right, whoops
I could technically also combine the tests
Okay I'll combine them real quick
I think there is one edge case where you could do
.with_density_for_name("my_mesh", 2.0)
.without_constructor_for_name("my_mesh")
.with_constructor_for_name("my_mesh", CONSTRUCTOR)
and it wouldn't have the specified density since the config was reset, but I'm not sure if there's a good solution to that, and idk why someone would first remove the constructor and add it back again
Can we just rename it to without_config_for_name?
(tbh I'd drop the _for_name from all calls while we're on it)
hmm but that sounds like "use default config"
how about just skip?
I can do this in a follow-up probably
Maybe, not sure though... I'm trying to think of a similar Bevy API to use as reference
I was considering insert_constructor and remove like how you insert and remove components, resources, etc. but I'm not sure if it really works here
although internally it does use a HashMap which has insert and remove
HMM interesting
only when running on Windows, and it happened twice in a row so probably not spurious
Why does your physics library need graphics in CI? 
Checks that colliders are generated correctly for glTF scenes
which requires way too many plugins for some reason
Ah, yea the gltf stuff is a mess
They holds meshes, which are in bevy_render and lights which as a in bevy_pbr so I guess you'd end up with graphics ... If it's only a runtime issue you could at least just not add the plugins for rendering

updated the test and CI somehow works again, maybe CI can't load the scene multiple times during the same run or something
merging :P
Cross-posting here: https://discord.com/channels/691052431525675048/1256845212823846983 Need some help. Thanks
(responded ^)
hhh time to manually port the changes on main to avian I guess, can't just do a merge because of the module structure changes etc.
nvm git seems to be smarter than I thought, although I do need to fix some things manually
Hmm, I'm wondering if I should keep the bevy-0.14 branch without breaking changes (mainly the collider hierarchy stuff) and leave them for Avian even though they're currently on main
The plan was kinda that the bevy_xpbd release would be just a 0.14 upgrade (and maybe some fixes) and Avian would have the new stuff, so maybe I should leave the collider hierarchy stuff out of the bevy_xpbd release as well
Makes sense to me to leave it out
Hello. I am currently trying to use bevy_xpbd colliders as sensors for my AI agents. Basically, each monster has a child sphere collider with the following components/config:
Collider, CollisionLayers (memberships: [Layer::Ability], filters: [Layer::Character]), Sensor, TransformBundle
... and a couple of my own components to identify / use the sensors for finding the player and directing the monsters. As you can see, these sensors cannot collide with each other because of my layers. I would expect ECS to be able to handle a fairly large number of entities like this, but with even a hundred or so monsters with sensors in this configuration, the game slows to a crawl. When I check the profiler it's all physics steps. Can you recommend any best-practices I may be missing for making this more performant?
i think it's still a bit too early for best practices, xpbd/avian is far from being finished (but afaik avian has improved performance a lot compared to xpbd)
Do you happen to have the names of the systems which are causing performance issues in the profile?
There was that one demo of about 15k projectiles being simulated at 60 fps even without the colliders being sensors, so a hundred should definitely be fine. Make sure you're running in release mode or with debug mode optimizations
As for best practices, you could reduce the SubstepCount since you probably don't need many if you're just using sensors
I expect that I should be able to get this kind of performance. I'll let you know the exact system tomorrow and see if I can't figure out whats wrong
While using the solver-rework branch of bevy_xpbd, I've discovered an issue with joints. Entities with anchor values of Vec3::NEG_X * 1.5, Vec3::NEG_Z, and Vec3::ZERO experience a sinking phenomenon. I've tested anchor values along the positive and negative X and Z axes, as well as Vec3::ZERO, and this sinking occurs with all joints. However, the issue doesn't appear when joints are not used.
However, when I control the movement of the red Cuboid, no sinking occurs. It seems that sinking only happens when the objects are in a resting state. Interestingly, when I removed my control system, the objects didn't sink even when at rest.
fn move_red_cuboid(
mut red_cuboid_linear_velocity: Query<&mut LinearVelocity, With<RedCuboid>>,
keyboard: Res<ButtonInput<KeyCode>>,
time: Res<Time>,
) {
let speed = 10.0_f32 * time.delta_seconds();
let mut linear_velocity = Vec3::ZERO;
if keyboard.pressed(KeyCode::ArrowUp) {
linear_velocity.z -= speed;
}
if keyboard.pressed(KeyCode::ArrowDown) {
linear_velocity.z += speed;
}
if keyboard.pressed(KeyCode::ArrowLeft) {
linear_velocity.x -= speed;
}
if keyboard.pressed(KeyCode::ArrowRight) {
linear_velocity.x += speed;
}
if keyboard.pressed(KeyCode::KeyQ) {
linear_velocity.y += speed * 6.;
}
if keyboard.pressed(KeyCode::KeyE) {
linear_velocity.y -= speed * 6.;
}
linear_velocity =
linear_velocity.clamp(Vec3::new(-200., -600., -200.), Vec3::new(200., 600., 200.));
if let Ok(mut red_cuboid_linear_velocity) = red_cuboid_linear_velocity.get_single_mut() {
red_cuboid_linear_velocity.0 += linear_velocity;
}
}
The same code works without issues in both the avian branch of bevy_xpbd and in bevy_rapier.
Yeah this seems to be a sleeping issue with joints not waking up bodies correctly, so the blue cube is sleeping but the red one isn't, which causes weird issues
fixing it now
@wanton scaffold I pushed a fix to solver-rework, so it should hopefully work now
I just made it so that bodies that are jointed together can't sleep, for now. We'll rework sleeping once we have simulation islands, which should fix these issues the "proper" way
I'm playing around with it but I'm not getting anywhere. Here's a cap of the profiler. I'm spawning one monster every frame to avoid spiking the CPU, and you can see when they start spawning lol
Worth noting that every frame looks like this too
This bundle is the only thing on the collider. Nothing crazy. I've disabled all of my physics related systems to make sure I'm not the problem
Setting the size of the collider to something small, like 2.0, causes the problem to go away because they no longer collide
I am compiling to release mode
Here you can see my colliders. I suppose it may be possible that the custom collider for my terrain is slow to collide with?
Lol yeah that was it.
I think it has something to do with the concavity of my mesh but I don't understand enough about mesh generation to make an efficient mesh
๐ฆ
Are the colliders supposed to be that big? It looks like they're all overlapping
They are sensors for the ai agents, so they have to be large enough for the agents to see
Okay phew, managed to fix a pretty nasty stability bug introduced by the solver rework, that was a stressful one ๐
I had accidentally made rotations ignore the center of mass again, which basically reverted this PR's fix
I only noticed it as bodies sometimes just sinking through the ground when they have offset child colliders with large densities, and I thought I had some big error in the actual solver... glad that's not the case lol
making an issue to add a test for the rotation behavior ASAP, I don't want to encounter this again
oh nice, this also fixes a stability regression for the collider_constructors example
@visual sparrow I addressed almost all of the feedback on the solver rework PR (except the tracking issue ones, I'll open a bunch of issues after the release though) and fixed a bunch of bugs I found testing individual features more thoroughly.
I believe it should be good now, so I think I'll merge it to avian now . We're kinda getting low on time here and there's still a couple of PRs I'd like to get in :P
Sure ๐
quick joint cleanup PR
https://github.com/Jondolf/bevy_xpbd/pull/390
(I'll merge in a bit)
Nice changes ๐
I like the renames
where is SubstepSet::SolveUserConstraints in the avian branch?
SubstepSolverSet::SolveUserConstraints
SolverSet and SubstepSolverSet are separate because parts of the solver are not in the substepping loop anymore
thanks
i'm refactoring my project to run on 0.14 so i need some help with finding missing stuff from bevy xpbd to avian
This PR has a changelog and migration guide for the solver rework, although they're not entirely comprehensive since there's so much stuff
That field doesn't exist anymore since collision detection is no longer substepped for performance reasons, what are you using it for?
just for solving collisions myself
for kinematic bodies
i took it from an example code...
so i just remove this line?
You can most likely just remove the if statement
alright
The kinematic_character_3d (and 2D) examples have also been updated if you were using that collision logic, it's a bit difficult to handle without stability issues
The new implementation of the collision logic is here
I struggled with porting it properly for quite a while
(note: I also haven't tested too many cases with it, mainly the demo scenes in the examples)
Here's another juicy PR: Swept CCD!
https://github.com/Jondolf/bevy_xpbd/pull/391
Tomorrow I will merge that, make one more feature PR (a slightly smaller one), and focus on release prep and docs for the rest of the day
Originally I said that I'd try getting a bunch of joint improvements in, but I don't think that's reasonable at this point unfortunately. While I technically do have some more joint things implemented locally, I think they need more time to bake and it wouldn't make sense pushing them in as last minute changes
I'll have to really speedrun my release prep though if 0.14 really releases in like 20 hours 
if it's a new feature then yeah, but improvements and bugfixes are worth it
Almost all of my joint changes are either (1) new features, (2) stability improvements that have other weird issues that need investigating, or (3) large refactors to structure things better
And for Avian 0.2 I'd like to implement simulation islands, which will probably require joints to be reworked in other ways
so I'd prefer waiting for that
Don't worry, rendering on web broke again 
Okay good for me I guess ๐
does that mean multi-threading?
Yeah with parallel islands you could solve constraints for disjoint sets of bodies in parallel
Rapier has that, for example
The other main use of islands is proper sleeping
sleep is for the weak
Our per-body sleeping is cursed and buggy, which is why I've limited it only to bodies that aren't interacting with other dynamic bodies
thankfully i don't even need that
Box2D and Bepu use islands only for sleeping and have graph coloring for multithreading
that would be the next big step after islands in terms of parallelism
Rapier also used to have graph coloring but struggled to make it worth the overhead, but afaik Seb plans on trying again at some point
it probably depends on the game more than anything
Box2D V3 and Bepu have definitely made it work really well at least
does any of them have a native integration with an ecs engine though
no
I've been designing some parts of the new solver with the mindset that it could maybe be decoupled from the ECS in the future, although it's still very ECS-focused at the moment of course
wouldn't a separate engine be better for that
or is there enough overlap to make it worth it
Might not be worth it in practice, but just from an experimentation standpoint it could be interesting
and an alternative for Rapier that the rest of the ecosystem can also benefit from would be nice, although maybe unrealistic while maintaining "ECS-nativeness"
But in theory, the ECS mostly just handles system ordering and acts as a storage for the physics data, so I think it could maybe be possible to abstract things so that the data backend and solver are generic and can live without the ECS
(of course the APIs wouldn't translate over, but you could have a Rapier-like API that is independent of Bevy as an option)
But like, the contact solving system/function for example is just this
fn solve_contacts(
bodies: &mut Query<RigidBodyQuery>,
constraints: &mut [ContactConstraint],
delta_secs: Scalar,
iterations: usize,
use_bias: bool,
max_overlap_solve_speed: Scalar,
) {
for _ in 0..iterations {
for constraint in &mut *constraints {
let Ok([mut body1, mut body2]) =
bodies.get_many_mut([constraint.entity1, constraint.entity2])
else {
continue;
};
constraint.solve(
&mut body1,
&mut body2,
delta_secs,
use_bias,
max_overlap_solve_speed,
);
}
}
}
the engine would just need the constraint to take a generic AnyRigidBody type, and the place where you get the rigid body can be a Query/Arena/whatever, no ECS is inherently needed
the same applies to a lot of places, although of course some things are currently a lot trickier and more coupled with the ECS
Seeing code like that makes me yearn for the day Bevy becomes an industry standard. C++ is such a drag in comparison.
There are better more human numbers you can add like a damping ratio instead of coefficient
but requires a bit more effort to make it work
the only thing that players see is what works ๐
I mean that's a bit reductive though because by using damping and strength coefficients directly you'll run into not working far easier
it also makes maintaining/adjusting it hard as fuck
it's just 2 lines of code that can be easily replaced, what are you talking about
i just got the result i wanted within a minute and moved on to work on other stuff
once it breaks i'll revisit it, you can link to better stuff if you have something
Could you elaborate on which parameters one should tweak instead? I'm interested ๐
well the most important part I've found is just the damping ratio which is just ratio = c / 2sqrt(mk) so you can solve that out to c = 2r / sqrt(mk) and plug it into the original dampened spring formula
or at least the easiest one to implement
m = mass, k = strength coefficient, c = damping coefficient
though honestly I think ideally we'd leave all this to the physics simulation and just use a spring joint or something
I just think the inputs are better as a damping ratio and angular frequency or some form of frequency
damping ratio just means 0..1 => very bouncy and will overshoot the target, 1 => just reaches the target with no overshooting, 1.. => reaches the target without overshooting but slower
A natural frequency and damping ratio like aceeri mentioned. This is one of the reasons why soft constraints are so nice, they're stable and intuitive to tune. I added a write-up on how they work in the solver rework lol
https://github.com/Jondolf/bevy_xpbd/blob/avian/src%2Fdynamics%2Fsolver%2Fsoftness_parameters%2FREADME.md
see also the references at the end, mostly Erin's slides on soft constraints
and yeah it's based on the harmonic oscillator, you can also find the formulae for the frequency and damping ratio there
Oh, I remember this from a transistor course I took ๐ Didn't know I could use it for springs, but yeah, makes sense when you consider them harmonic oscillators. Thanks @royal helm and @vestal minnow ๐
What's a good name for a component that adds artificial thickness to colliders, ContactSkin, CollisionMargin, or something else? Rapier uses ContactSkin, and Bullet/Godot uses collision margin
Box2D V2 used polygon skin for polygon shapes
Although Box2D removed polygon skins for V3 since they no longer need it to prevent tunneling and improve stacking, but in our case (and Rapier) we also support 3D, and contact skins can be good for trimesh collisions for performance and stability
@vestal minnow I'm trying to setup a RevoluteJoint and running into some problems: https://github.com/janhohenheim/avian_playground/blob/main/src/bin/joint.rs
Contribute to janhohenheim/avian_playground development by creating an account on GitHub.
First one is that the simulation behaves differently when I have the with_children blocks compared to when I leave them in.
The difference in hierarchy is this:
- RigidBody + Collider
- No children
vs
- No children
- RigidBody + Collider
- PbrBundle
Should these two behave differently?
If so, my bad
Thanks
Just remove the two with_children calls and you'll hopefully see what I mean
(this is uses your avian branch)
okay so even just the existence of children makes it break, it can even be an entity with no components
probably something in either init_transforms or some propagation system
Thanks for looking into it ๐ The other issue I had is that when I remove the children and make both objects RigidBody::Dynamic, it behaves a bit explosively. Is that because an impulse is generated when the two "ends" of the joint "snap" together? Sorry, I don't have the right terminology, haha
Maybe for context, at the end of the day what I want is a trash container like this
You can see that the lid can be "flipped" open. I assume that's what a RevoluteJoint is for.
Problem is, when I spawn these guys in my game, they all do some explosive thing first before settling down
Yeah if I remove the transforms completely and just use Position and Rotation, it works... just need to trace down what exactly causes the issue
You can see the initial configuration is like this
That red line is the separation between the anchors
The anchors should match
So it snaps them together
So if I line everything up on spawn neatly, there won't be any explosive behavior?
Hopefully yes
I'll try, thanks!
(after I fix the transform issue)
Only issue with that is that I spawn these objects based on a GLTF and it will be hard to perfectly line them up there. I guess I'll have to change their Transform after spawning to align the anchors.
Eventually I'd like to make it so that you can just configure one anchor, and the other one will be configured to match automatically
IIRC Godot doesn't even have configurable anchors really, you just position the bodies and the joint frames are set accordingly (although it means you can't nicely offset the anchors afaik)
What are joint frames?
Wait, so how would Godot know that I want the lid attached to that part of the body? Would I need to set the origins accordingly?
I think so, yes, it doesn't really have an anchor thing
Unless the transform acts as the joint frame? idk
only adds, or can subtract too?
The intended use is that it adds, but I guess technically it could subtract too
then margin makes more sense
Margin is more intuitive to me than skin
One concern with CollisionMargin is that it could be confused with SpeculativeMargin which is different
just add it to docs
I think the names are clear enough in this case
NotColliderMargin /s
it's not like it's something cursed like CollisionMargin and ColliderMargin
unity collision.collider PTSD
wait it has that? 
kinda, if you use collision then it points to parent rigidbody object, collision.collider is the object that actually got hit
yeah in bevy_xpbd it's the opposite, the returned entity is the actual collider and the body can be queried for separately
idk how much physx API influenced the decisions but it might be the reason
wait what
using an empty with_children call affects it 
.with_children(|parent| {})
this is some cursed shit right here
that is cursed indeed ๐
Is there
for the Avian logo yet? ๐
Not yet, I need to make that
:avien:
I think with_children just initializes Children for the parent even if there are actually no children
that kinda feels like a bug to me
If it does, that definitely sounds like a bug since the rest of the Bevy API around moving children and parents is documented to automatically remove Children from a parent that has no children as a result of said operation
It runs the PushChildren command which calls push_children on the parent, checks if it has Children, and if not, inserts it
no checks of whether the child list is empty from what I can see
Yeah I call bug
easy fix if someone want to PR that soon
On it 
@edgy light done: https://github.com/bevyengine/bevy/pull/14109
Objective
The Bevy API around manipulating hierarchies removes Children if the operation results in an entity having no children. This means that Children is guaranteed to hold actual children. How...
well uhmmm theres something wrong with the player physics on my game lol
it could be related to the custom system i made for the player physics and collision detection
Nice flight mechanics! ๐
i'm not even using avian here, its just the 0.14 branch of bevy xpbd
but i'm guessing the physics of kinematic bodies got changed?
no, I don't think anything changed there
huh
the main changes on the bevy-0.14 branch are related to transform propagation stuff and (obviously) migrating to 0.14
and sensors not contributing to mass properties
this is really weird
ok i think i discovered whats happening
the speed became too fast for some reason
perhaps i should use delta time?
maybe, I'm not sure what your code looks like so it's hard to say
i mean i wasnt using it before...
sigh this seems to be a regression between main and bevy-0.14
need to go through the commits I guess, probably related to transform propagation or system ordering changes
i suspect this player physics bug is ocurring due to some change in bevy systems
I guess this could maybe be related to your issue too @shrewd wharf ๐ค
yep
Hmm? I thought it didnโt happen on bevy-0.14, which is what @shrewd wharf is using
it does
Ah, I misread then
doesn't need the joint either
just a rigid body that has a collider, and a non-physics child
the collision solver system is in the defined set and schedule from xpbd
as how it was shown in some example ive seen some time ago
solve collisions is just this:
fn solve_collisions(
collisions: Res<Collisions>,
mut player_query: Query<(&mut Position, &mut LinearVelocity), With<Player>>
) {
for contacts in collisions.iter() {
if !contacts.during_current_substep {
continue;
}
let is_first: bool;
let (mut position, mut linear_velocity) =
if let Ok(player) = player_query.get_mut(contacts.entity1) {
is_first = true;
player
} else if let Ok(player) = player_query.get_mut(contacts.entity2) {
is_first = false;
player
} else {
continue;
};
for manifold in contacts.manifolds.iter() {
let normal = if is_first {
-manifold.global_normal1(&Rotation::ZERO)
} else {
-manifold.global_normal2(&Rotation::ZERO)
};
for contact in manifold.contacts.iter().filter(|c| c.penetration > 0.0) {
position.0 += normal * contact.penetration;
if normal.y != 0.0 {
linear_velocity.y = 0.0;
}
if normal.x != 0.0 {
linear_velocity.x = 0.0;
}
}
}
}
}
two things i noticed so far: the velocity is going too fast, so i multiplied by delta on the player input system, while commenting out the collision solver
but when i bring the collision solver back, the player goes all crazy again
FYI this can be simplified by using CollidingEntities, like seen here: https://github.com/janhohenheim/foxtrot/blob/main/src/world_interaction/interaction_ui.rs#L37
huh
Donโt need to find out which of the two collision entities is player that way ๐
what is InteractionOpportunity?
That's a tag I add to objects to mean "you can press e to interact with this entity and bring up a Yarn Spinner dialog". Donโt think that is relevant to your use case.
The idea is as follows
- check collisions between the player and something else
- the "something else"s might be an interaction opportunity or a descendant of one. If yes, proceed
- validate that the player is facing the right direction. If yes, proceed
- show the interaction prompt on screen
Only the first part there should be relevant to you
so when it checks collisions you stop the player velocity, right?
Nope, I let all collisions be handled by XPBD alone
huh
because i remember kinematic bodies on xpbd doesnt have any collision
it has to be done manually
The player character and NPCs are dynamic rigid bodies using the Tnua character controller
ah...
I would advise you to also use that one to save yourself quite some time, as character controllers can be quite a rabbit hole. Except of course if you want to manually do it because youโre curious ๐
I assume you know about collide and slide?
wdym
That is the name of the algorithm that one would commonly use when implementing your style of character controller by hand
Let me fetch you a video
eh... idk
How to make actually decent collision for your custom character controller. Hopefully you find this helpful and people will finally stop saying "jUsT uSe DyNaMiC rIgIdBoDy!!!1!!11!!"
Chapters:
00:00 - Intro
01:09 - Algorithm
05:11 - Implementation
Improved Collision detection and Response (Fauerby Paper):
https://www.peroxide.dk/papers/collisi...
it was working before so why bother
and my game doesnt have any slopes
(at least yet)
Exactly that one ๐
(this implementation isn't perfect though afaik, but decent)
Hey, you do you, but I find that learning from well-known sources is often more conductive to my own understanding ๐
My hand-rolled collision logic for the character controller on the avian branch is kind of a hybrid between the old "naive" approach, collide and slide, and speculative collision
Yeah, the part where he re-normalizes and scales after the collision to regain magnitude is wonky
but perhaps
i could use that tutorial to write another collision system and figure out where it goes wrong
Okay I can confirm the regression was caused by #380, the rigid body transform propagation speed-up PR
now tracking down the exact issue...
so it is truly related to my issue?
Does your character have child entities?
only a sprite bundle
but the player also has a shape caster
but thats only for making the player able to jump
try removing the child and maybe enable debug rendering so you still see the player
hmmm
if i remove it, code will panic everywhere
i will just enable the debug rendering
btw this shape caster is a component, not a child
i noticed that the player velocity is too slippery
i cant just abrutbly stop it by setting velocity to 0
this is weird
The regression is related specifically to child entities on rigid bodies so if you have an entity with a sprite bundle as a child then it is likely that it could be related
hmmm
thats weird
this child is only for rendering
as you can see here
the child is for being able to "rotate" the player but the hitbox doesnt actually rotate
yes I know it's weird ๐ it doesn't matter what components the child has, the bug causes issues as long as there is some child
I'm debugging it rn
now that you said it... it actually makes sense
the player was flying like its constantly colliding with something on the same space as the player
which explains why it doesnt stop by setting velocity to 0
Good thing we found the bug in a relatively isolated example. This would be really weird to even discover otherwise.
yeah we definitely can't ship with this
nasty to track down the exact problem though
Okay fingers crossed I fixed it ๐ค I'll test a bit more and make a PR
I believe the issue is that my propagate_transforms_physics system (which updates the GlobalTransforms of physics entities and their descendants) only iterates through entities that are marked as ancestors of physics entities. This is the intended design, but it means that it skips updating GlobalTransform for entities that have children that are all non-physics entities.
The sync_simple_transform_physics system just needs to be changed to update the transforms of physics entities that are not ancestors of other physics entities, not just those that have no children at all
@shrewd wharf could you try the fix-transform-update-bug branch?
okay
wait i'm compiling here
well nvm
i thought that was because the rust compiling cache got bugged out
but i think you bugged something on your project @vestal minnow
I've gotten that error tons of times randomly on long compiles
I don't think it's something in the project itself
I'm not getting it rn at least, and CI passes fine
its saying that multiple defined symbols has been found
well let me try to compile it outside of rustrover
fatal error LNK1169
could probably try to cargo clean or remove target if you haven't already
yeah its what i did before
i will compile again everything but outside of rustrover... idk if its related
perhaps theres something wrong on my cargo.toml?
looks fine
FYI cargo clean -p <name_of_your_binary> is enough for these kinds of issues
That will save you a ton of time ๐
how does your config.toml look?
If you have one
i dont have one
Also not a global one?
Ah nice thanks, I've just been yeeting the whole target all this time ๐
@shrewd wharf it would be in "C:\Users\<your name>\.cargo\config.toml"
Does that file exist?
huh, then I'm also out of ideas
You could switch to LLD and try again
LLD is faster than the default linker anyways
hmmm
Hold up, are you on nightly?
nope
ah heck
Then I can't really say much other than "nightly + my own personal config works", sorry :/
If you want to try that, here's the relevant entry for your global config.toml:
[build]
rustc-wrapper = "C:/Users/<your_name>/.cargo/bin/sccache.exe"
[target.x86_64-pc-windows-msvc]
linker = "rust-lld.exe" # Use LLD Linker
rustdocflags = ["-Clinker=rust-lld.exe"] # Rustdoc does not use the same linker as the compiler by default.
rustflags = [
"-Zshare-generics=n", # (Nightly) Needs to be disabled when using dynamic linking.
"-Zthreads=0", # (Nightly) Use improved multithreading with the recommended amount of threads.
]
Then run these
rustup default nightly
cargo install -f cargo-binutils
rustup component add llvm-tools-preview
cargo install -f sccache --locked
sccache won't help with your issue, but it's good to have anyways because it will cache your build artefacts
You probably also want to use features = "dynamic_linking" on your Bevy dependency
lld is only available for nightly?
Nope, but nightly will generally help with compile times
That's from the feature dynamic_linking
Can you copy-paste your entire cargo.toml?
In the meanwhile I'm merging the fix PR anyways and also adding it to avian, I'm pretty sure it should fix at least the issue in the avian_playground
and if not, I'll just make another PR ๐
Nice! Thanks for testing ๐
And thanks @visual sparrow for discovering this and for the good test case
will you merge this branch into the 0.14 one?
ah right
btw i have another unrelated question: since the beginning of the game ive been using a separated Collider entity for each block in the world, do you think thats an unoptimized approach? and is there a way of making a custom mesh collider or something?
It's not ideal, but if performance isn't too bad then it's probably alright
doesnt seems to affect perfomance because i once tried to figure out the lag spikes when loading chunks and deactivated the collision generation to see if thats causing it, but apparently its not, lol
Could optimize it by merging colliders in some way, and by only having colliders for the surface if you don't need them underground
greedy meshing perhaps...
yup something like that maybe
but again, if it's not causing any issues, then it might not be worth it to optimize prematurely (unless you want to of course)
true
i did one simple optimization though
before, i was literally despawning and spawning all collider entities again every time you placed/destroyed a block
but now it will only spawn/despawn a collider entity when necessary
only when it detects that there is a collider entity for a block that doesnt exist anymore, or if there is a block with no collider
i dont know how expensive it is to be spawning/despawning entities but this should help
Last proper PR for Avian 0.1, collision margins:
https://github.com/Jondolf/bevy_xpbd/pull/393
Now doc improvements and release notes
reviewing now
reviewed ๐
Finally managed to punch open the trash containers with a RevoluteJoint, yay! ๐
Whoa, nice!
Bonus: punching crates around
Very happy with how it's working. Thanks for making Avian exist @vestal minnow ๐
Secret footage of a man beating up Box2D with Avian (jk Box2D is amazing)
I really love this inconsistency, just fell for it myself ๐
Cylinder::new(radius, height)
Collider::cylinder(height, radius)
my colliders existed before Bevy's primitive shapes 
That's what you get for not upstreaming them /s
changing the argument order would be a wonderfully implicit and extremely breaking change... though of course we could technically start embracing Collider::from conversions more and
most of the constructors
do one release with a breaking change where you newtype all the f32 to Radius(f32) and the like, then a breaking change when you change the order ๐
I'd go ahead and change it for avian. Having people change their literal crate dependency is about as big of a signifier of "there be breaking changes here" as it gets.
And by change it, I mean go ahead and remove the constructors in favor of Collider:from
or at least deprecate them
Or, secret sneaky third variant: deprecate Collider::cylinder and change the argument order, tell the user about it in the deprecation message 
That's somewhat sketchy because we can't do that for half-spaces, heightfields, trimeshes, convex polyhedra, convex hulls, compound shapes etc. without copying the types and doing some (potentially expensive) conversion to the parry equivalents. And then there are constructors like capsule_endpoints
and round_rectangle/round_cuboid
Yeah, I meant just removing the constructors that can be expressed in terms of Bevy primitives
Hmm, I kinda wish the primitives looked like ColliderConstructor, then it would be only a single From
And we could add variant ColliderConstructor::BevyPrimitive(...) to the ColliderConstructor and remove all of its redundancy as well
Even Segment2d/Segment3d don't work as Collider::segment because it still doesn't use an endpoint representation
(even though I've complained about it like 4 times... I need to make a PR for it lol)
I feel like the API would end up being too patchy and inconsistent if we removed/deprecated the constructors right now
About half of the constructors would still need to exist, and some shapes would end up having both the From impl and a similar constructor anyway (like the line segment)
Hmm I see. Fair enough, you're right ๐
But you gotta change that cylinder constructor at least ๐
Yeah I'll clean up all the inconsistencies with Bevy, I think capsules are similarly inconsistent
ah and of course we should add support for like six more shapes added in 0.14
that'll be for Avian 0.2 though, there's no time for that lol
your game looks great right now haha
Aww thanks โค๏ธ
I swear I'm so happy that I can punch these fellas around haha
I'm deliberating if I really want to do this
it'll break basically every character controller's collider lol
I feel like this is something you have to do at some point, and I don't think you'll get a better opportunity than the Avian release. Maybe proactively do some PRs to character controllers using XPBD? TBH I only know of Tnua, the rest off the top of my head use rapier.
The only sneaky thing I can think of is adding #[deprecated("hey, this is not really deprecated, just wanted to let you know that the params for this method flipped. Carry on!")
yeah, doing this earlier than later is better
Or deprecate new() in favor of new_for_real_for_real and then replace the old new with the new one in a future update
wanderlust has a branch that uses xpbd but I'm lazy and never finished it
Off-topic: Oh my gosh your GitHub profile pic is so cute haha
ty hehe, its tiki from an instagram account I follow
birds looking into mirrors is a favorite of mine
oh wait
github profile pic
thats from false knees comics, the lucky birb one
Oh, your Discord pic is also a bird? I thought it was a big ol' caterpillar ๐
False Knees is a webcomic written by Joshua Barkman. All silly nonsense is my own.
honestly, the more I've dealt with character controllers (specifically wanderlust), the more I'm convinced a library isn't going to work for it
I think just providing methods for basic tasks like the collide & slide stuff is a better idea
with controllers you have to basically have everything configurable
collide & slide, a basic grounded detection method, the rest are kind of iffy and too specific
I think ideally I'd like to have some type of collide and slide for kinematic bodies built-in, and have the rest be fully optional and/or 3rd party
yeah
I definitely think we should add a collide & slide to xpbd, since I don't really see much variance happening there
plus its useful even for things outside of controllers imo
but ya, @vestal minnow I think this is a good change to make now
just put it somewhere with a warning in release notes so people see it and can change their code
yeah it'll be in the migration guide and release notes
(which I have not had time to really even start yet, I'm screwed lmao)
I'll copy some stuff from PR descriptions and other write-ups I've done
I'd say don't worry too much about releasing it as soon as 0.14 comes out, this seems to be a pretty big release for xpbd/avian
Merging
if you need any proofreading through stuff feel free to ping me, I'm not sure I'd be much help with other stuff lol
Your write-ups and PR descriptions were really in-depth and understandable. I think you should be good by just frankensteining the release notes together ๐
Yeah same, feel free to ping me for editing
I've been really wanting to look into the new solver stuff though, I checked out that box2d solver stuff a while ago, but I got distracted
(Also for adding it to next month's issue of This Month in Rust GameDev, wink wink nudge nudge)
I'll probably do the bevy_xpbd 0.5 release (for easy 0.14 migration and to mark things as deprecated) pretty much immediately, and maybe prep a bit longer for Avian unless I manage to speedrun the release notes tomorrow
I should have everything code-wise ready now though, just need to do the migration guide and release notes and stuff
also some kind of demonstration videos and updated benchmarks probably
Merging
Another quick cleanup PR, adding #[reflect(Serialize, Deserialize)] for types, and adding other missing derives and type registrations
https://github.com/Jondolf/bevy_xpbd/pull/395
hmmm I wonder what I should do with the release tags on GitHub
I guess I could rename them to something like v0.4.0-legacy, as long as GitHub doesn't count renames as new releases lol
testing on another repo
maybe xpbd-v0.4.0 is more intuitive?
yeah, that'd probably be good
Okay it looks like I can't rename tags on GitHub so I'll just have to create new ones, but I can swap tags for releases without it counting as a new release
I think I can live with that
no but I think the tags are the actual timestamps to the code base at the time they were made.. so all the xpbd-vx.y.z releases would have the same code
I'm pretty sure you can remove tags tho ๐ค
you can yes
nvm ignore this, you can just set whatever commit you want as the target of the tag
no you can't GitHub requires it to be a "recent commit" for whatever reason??
Do I need to create branches for all the old releases to be able to make new tags for them? That feels very dumb
Isn't GitHub Tags just a frontend for actual Git tags? Surely you can retarget those
Adding some more reflect stuff to it as review comments
@vestal minnow done. Whew, that took longer than I thought ๐
welp
I probably should have just done a PR on your PR instead, haha
Thanks, I'll go over it in a bit, currently struggling with renaming git tags #off-topic message
I think we broke GitHub
it duplicated some things and failed to auto-resolve some conversations
fixing things now
Hehe. But why didn't you just click on "accept suggestion" instead?
I batch accepted them and tried to commit everything at once
You can do that? ๐
There's "Add suggestion to batch"
when in the file changes view
I'm not committing like 60 suggestions individually ๐
Yeah fair enough ๐
TIL, thanks!
Phew, I finally managed to rename all the tags without breaking things
Drafts for release notes and migration guides for both bevy_xpbd 0.5 and Avian 0.1 are now largely ready in terms of what I'll put on GitHub
Now I need to make the more complete release notes / blog post for Avian though (which will take a while...)
@vestal minnow I'm currently writing a plugin for Avian and am thinking about which schedule to run it in. Since I'm reacting to user code that happens in Update, I think I should run in PostUpdate. But since Avian can have its schedule configured by the user, it seems like it would make even more sense to just use whatever schedule Avian uses. So I thought I could just take PhysicsSetupPlugin while building my plugin and check which schedule it uses, but that field is private. Is there a way to find out which schedule the user configured for Avian? Or should I just not try to be smart and let the user fully handle the schedule manually? I feel like that might be a footgun since it would not make sense to run the Avian schedule before a plugin that does Avian stuff.
Oh wait, I think you already wrote about this: https://docs.rs/bevy_xpbd_3d/latest/bevy_xpbd_3d/plugins/struct.PhysicsPlugins.html#custom-plugins
A plugin group containing all of Bevy XPBDโs plugins.
I could still make the schedule fields public if that's useful
Probably best to have only one way of doing things
That section is about making plugins and adding systems into physics schedules, but that's slightly different from adding systems to the schedule that the PhysicsSchedule is run in
(i.e. PostUpdate by default)
Hmm, fair enough
But yeah if it's a plugin for Avian then you can probably add that in the PhysicsSchedule unless you need stuff to run before PhysicsSet::Prepare
I'm just adding some forces and doing spatial queries, so I think I should be good ๐
Any recommendations on where to put it SystemSet-wise?
There's now PhysicsStepSet::First which is empty by default to make it easier to run stuff before physics logic
probably doesn't matter too much where it is though, as long as it's before the solver (or specifically SolverSet::Substep) if you run in PhysicsSchedule
Do you think I should place it inside First or before it?
Inside, right?
Just want to form a good precedent for other plugins so that users that have multiple Avian-based plugins don't get a headache when ordering them.
Probably inside it, but maybe have your own public system set there so users can order relative to it if there are issues
although yeah other 3rd party plugins could have conflicts I guess
It's kinda hard to say where exactly third party plugins should place their logic or to predict what orderings users are going to use
If you want the most niche place to apply forces in the PhysicsSchedule, that'd probably be SolverSet::PreSubstep (or I guess some collision detection system set but those would make no semantic sense)
If others place it into First and also expose their sets, it should be easy for the user to order them.
Simply do app.configure_sets(PhysicsSet, (AvianPluginOne::First, AvianPluginTwo::First).chain())
Sorry to say but this looks like trash (containers) ๐คฃ.
Jokes aside, I wanna see more of this!
Any devlog to follow along?
hehehe
Thanks :> I didn't publish anything yet because I'm still prototyping systems, so everything looks pretty meh.
I know it doesn't matter for a technical audience, but there's this part in me that says "noooo don't show others the ugly greyboxing levels", haha
I understand, just donโt fall into the trap like we did, being now close to release and didnโt do any devlog ๐คฃ
When do write a devlog, make sure to add it to This Month in Rust GameDev ๐
Well the current project is still done in unity ๐. VR support is not there yet in bevyโฆ.
Heck!
At least we use ecs ๐ , unityโs has many problems tough, especially their physics implementation is very problematic when it comes to performance and sync points.
Really? I would have expected such a mature ecosystem to have that under control ๐
We had to do horrible things to our implementation to achieve required framerate, and most performance is used by unity (physics, netcode serialization + graphics on the CPU)
Let us know the issues you have! We want to fix them!
I will, but the project started a longer time ago, so the current vr support wasn't even available.
also we need a fully production ready networking library which works with physics... and lightyear (or xpbd) didn't exist when we started 
ah misunderstood, yeah makes complete sense
okay nice, I can at least go sleep since 0.14 seems to be at least 15 hours away still
I was about to pull an all-nighter lol
currently at 31k characters (including white space) for Avian release notes and still a lot left...
I also need to update my website since I'm not sure if it even supports some things I want to add
Get some sleep!
But we all are looking forward to the release โบ๏ธ, but take the time it needs, many crates arenโt ready yet!
the ci indicator thing is broken on avian branch readme
Yup, that's because it points to https://github.com/Jondolf/avian/actions/workflows/ci.yml/badge.svg?branch=main which doesn't exist yet. It should automatically get fixed once I rename the repo
ah, alright ๐
Is it more efficient to call cast_ray_predicate over cast_ray and filtering later?
Second question: if I don't really care about the solid parameter, what's a better default? true or false? It only has an effect when the ray origin is inside a collider, right?
cast_ray gets the closest hit, so if you filtered it afterwards, you'd have to call it many times in cases where the hit doesn't satisfy the filter (assuming you want to find the closest valid hit), and update the query filter each time to exclude the entity from the previous filtered hit.
cast_ray_predicate gets the closest hit that satisfies the predicate. Its more efficient than potentially calling cast_ray multiple times, since the filtering is integrated into the traversal of the acceleration structure and it only needs to traverse once
Oh, that makes sense. My confusion came from the fact that I was working with shape_intersections, which returns a Vec, so I got a few wires crossed and thought cast_ray also returned a Vec
But yeah, considering that cast_ray only returns one entity, this makes sense ๐
Yeah, it only has an effect when the ray origin is inside a collider. Setting solid to true can be a bit more efficient since the algo can just return a hit with a zero time of impact when it detects that the origin is inside of the shape. With false, it would need to do an extra step to find the hit on the boundary of the shape
perfect, thanks!
(The way it finds the hit on the boundary for non-solid cases is actually by shifting the origin outside of the shape in the direction of the ray, and performing a second ray cast in the opposite direction. So it's two casts instead of one, at least for some shapes)
bevy_xpbd 0.5 released #crates message
see the release message :P
(im joking)
I have the release notes "done" but I need to do a quality pass and port them to my website (I wrote the notes in Obsidian)

very excited for avian
i tried it out with a demo occurus had made ( not in vr ) and it felt awesome
avg obsidian chad, fk em notion guys ๐
Yeah I'm happy that people seem to be having a good experience with the new solver so far, it's pretty scary to just throw all of that away in favor of a completely different approach ๐
the old solver had issues with small things just
falling through other objects
( not even that small of objects )
@vestal minnow do you mind quickly bumping the avian branch to bevy 0.14.0?
That way, I can already update the plugin I'm working on ๐
ah wait, 0.14.0-rc is compatible with 0.14.0 ofc
ignore me ๐
Which component would i need to query to update the shape and TOI for a shape caster at runtime?
my website is saying that the post is a 30 min read and it's still not even entirely done yet 
I'll release Avian some time tomorrow (or technically today, it's 2 AM), I want to polish things a bit more and actually be awake for the release
I'm not entirely sure if I understood what you mean, but ShapeCaster holds the shape, and ShapeHits holds the hits, which are updated every frame. Do you want to actually recompute the hits immediately in a system without a frame delay?
Sorry yeah I figured it out hahah, I was thinking back to my unit test where ShapeHits had to be inserted by one of the setup systems
Ah okay, np ๐
@visual sparrow Not sure how to best share this, but does this look fine for the collider constructor section? No idea if this is readable ๐
probably should've done two screenshots
I was literally just going to turn off my PC to go to bed ๐
lemme check
Looks great! Only note I'd add is that ColliderConstructorHierarchy still waits for a scene to load if you place it on one ๐
Very excited to see this in action with the revamped Blender workflow ๐
Thanks, I'll add that ๐
Excited to release tomorrow, I'd say the release notes are about 95% ready now
I have quite a few assets for this one lol
is there any way to add a collider and set its center of mass to be a specific value? I tried with the component but it seems to get overwritten ๐ค
Not 100% sure, but I think you need to manually give the body a non-zero Mass as well
If you have colliders with non-zero density, they will also contribute to the center of mass
oh wait "add a collider"
did that question make sense? I have a truck that I want the center of mass to be near the wheels rather than like.. the center of the truck
Okay so we should probably make this more straightforward in some way, but I think this works
// Replace with your collider
let collider = Collider::cuboid(1.0, 1.0, 1.0);
let mass_properties = MassPropertiesBundle {
center_of_mass: CenterOfMass(my_center_of_mass),
..MassPropertiesBundle::new_computed(&collider, 1.0)
};
commands.spawn((
RigidBody::Dynamic,
collider,
// Remove collider's effect on mass props since we're adding them manually
ColliderDensity::ZERO,
mass_properties,
// ...
));
If it's multiple colliders for one body, it's probably a bit trickier, but you can shift the center of mass a bit if you just give the body some Mass manually and set its CenterOfMass
(I need to go to bed now)
Hey all -- is there a way to rotate a cylinder collider so its axis points along the X axis instead of the Y axis, without having to put it into a child & applying a rotation Transform to the child?
Right now I have to create an entity containing Collider::cylinder(width, radius) and a Transform that does the rotation, and add it as a child of a RigidBody with no colliders, and I'm wondering if the collider could go on the parent RigidBody directly instead
You could rotate the parent, without a child~~, or if it still exists capsule_endpoints can sort of do that too iirc~~ nvm that's for capsules, you said cylinder
Hmm I don't think I can rotate the parent. So I'm trying to add cylinder wheels to the sides of a flat cuboid plank (i.e. a skateboard). The wheels and plank are both root entities (no parent). To attach them with a RevoluteJoint I'd need to use the same aligned_axis for both, but the cuboid's +X goes to its right, while the wheel's rotation axis is +Y. I want to preserve the cuboid's frame so that +X means "local right", so I think I need to change the wheel so that its rotation axis is on +X instead.
Maybe I should just do a capsule with 1e-3 radius and use capsule_endpoints ah nah that would give me a long stick
Don't the joints allow an already existing rotation? ๐ค
That would just be a very thing capsule tho, basically a line
Hmm let me check. I remember trying this a few days ago and it exploded instead (presumably trying to align the axes that the joint thought were offset by 90ยบ)
You could also make a compound collider to make it extra cursed ๐ค
That might work ๐ค
Oh cool, it worked! Now I just have to do the same thing with the meshes
@vestal minnow when I'm looking at an entity holding a RigidBody, is there any way of iterating over its colliders other than manually traversing the descendants? There isn't anything analogous to ColliderParent like RigidBodyColliders, right?
Not currently
If I have to do this by hand, I imagine it can be optimized by only looking at branches with AncestorMarker<Collider>. Is there anything convenient exposed for that?
There's no specialized traversal API for that, no
Alright, I'll roll my own for the moment then
thanks for the quick reply though ๐
You could probably implement a RigidBodyColliders component with OnAdd observers
By having on_add hooks on Collider and then inserting them into their ColliderParent?
(and probably also on_remove)
Add initial colliders when the rigid body is added by traversing descendants, and then later colliders can be added when OnAdd is triggered for ColliderParent
(I need to go for like an hour)
Two noob questions:
- This is an alternative to Rapier, right?
- Is there a compatible fluid solver for bevy_xpbd? (alt. in Dimforge is Salva)
(Jondolf I know your answer to 2 hehe)
- This is an alternative to Rapier's Bevy plugin
bevy_rapierspecifically. It currently can't be used outside of Bevy. Unlike Rapier, this is built specifically for Bevy with its ECS, which makes it more native in a way. - Not currently and I don't have immediate plans for a proper integration. I did manage to get a proof of concept for a Salva integration working a while ago though
Also, I'm releasing a large rework of bevy_xpbd today, which includes a rebranding to Avian :)
There will be a pretty in-depth blog post about it
Thank you for the response. Do you happen to have the proof of concept in (2) handy e.g. github?
Is coupling fluid sim decidedly not part of this project or is there just a lack of interest?
Not on GitHub, but here's a quick video #off-topic message. It was mostly just a weekend project for fun :P
Fluid simulation is something that would most likely be better as a third party plugin. I don't think there's anything that inherently requires it to be a part of the core engine, and there are a lot of different ways to do fluid simulation depending on what quality and performance is needed. And then rendering fluids is its own can of worms.
I'd definitely be interested in having a third party fluid simulation plugin with an integration for bevy_xpbd/Avian, but it's not something I can personally prioritize working on any time soon. There are so many other important things to work on, and fluid simulation is still relatively niche in terms of game development, especially since accurate fluids are very difficult to pull off in real time at large scales, especially in 3D.
i don't think i've ever seen water simulation out of particles actually being used in games, it's usually just height+vector field and erosion
i guess terraria could count though
Noita ๐
noita is a special case, it simulates everything
In this 2019 GDC session, Nolla Games' Petri Purho talks about the technical details of Noita's physics engine, including scaling up the falling sand simulation to support large continuous worlds and integrating destructible rigid body physics, while demonstrating the emergent physics based gameplay.
Register for GDC: https://ubm.io/341ZiaZ
Jo...
The implementation is actually pretty simple
@vestal minnow Noita is Finnish, so you could just go over and ask the devs directly to implement that for Avian ๐
he's totally right about design though, it's hard to actually make it into a fun game
meanwhile height fields and erosion are actually useful for simulation games or making the terrain for any other genre
Currently building the Avian docs locally to find this out, but is there something like cast_aabb?
I'm trying to port a piece of code that uses Source engine's TraceHull
Performs an AABB hull (axis-aligned bounding box, aka not rotated) trace with the given trace data.
Clientside entities will not be hit by traces. This can be changed after next update. This function may not always give desired results clientside due to certain physics mechanisms not existing on the client. Use it serverside for accurate results.
There's aabb_intersections_with_aabb but no actual AABB casts/sweeps
I'm pretty sure Parry doesn't have shape casting for AABBs
I'll do a cuboid shape cast then, close enough I suppose
barry when ๐
Ideally I'd like to upstream all the generally useful algorithms and things for Bevy itself, and only leave the more niche stuff to a third party lib
Generally useful things would include geometric queries (ray casts, shape casts, intersection tests, point queries...), support mapping, Quickhull, earclipping, etc.
Niche things would include trimesh colliders, convex polyhedra, heightfields, compound shapes, mass property computation, EPA, SAT stuff, and convex decomposition
We also need a good BVH for the spatial queries (and maybe a better broad phase), and for that I'm looking at integrating Griffin's OBVHS once it supports 2D and more query types
Fair enough, that makes sense
Yeah mass property probably doesn't mean much without physics in place, does it?
yooo
honestly expected a bigger diff, although some other things were merged earlier already, and the solver was also rewritten multiple times before the "final" version
like originally I just had basic Sequential Impulses instead of TGS Soft
I just realized something interesting about the BVHs ... My BVH used to be ~5x slower to build than parry. ~450ms where parry got 90ms. But after optimization that's about 3x now ... Looking at the tray racing benchmarks, OBVHS also has a 3x slower build on medium, which matches roughly my construction parameters ... I wonder if we can make a wrapper around OBVHS that adds the nice ergonomics of ploc-bvh (having a bevy_math based API), while getting all of the features I never built like multi threading and actual construction parameters ๐ค
@vestal minnow FYI some stuff on main is still pointing to the RC, e.g. https://github.com/Jondolf/avian/blob/main/crates/avian2d/Cargo.toml#L52
congrats on the Avian merge though ๐
huh, thanks, I'll fix that
would've been embarassing to release with that lol
I did fix it on main iirc, but I guess it changed back when I merged
Just noticed because I'm patching my avian fork to bevy 0.14.0-dev to use https://github.com/bevyengine/bevy/pull/14159 in my plugin, haha
we have competition (they have stopped maintenance ages ago tho)
gotta claim the #1 spot on GitHub lmao
wait how are we just a bit over a hundred stars away from bevy_rapier ๐
hehehehehe
Whoop whoop ๐ I thought we were way behind ๐
oops gotta change that link
@vestal minnow
Support for custom joints and other constraints using XPBD
still on your readme
That's not an error, joints still use XPBD for now since reworking them would've delayed things way too much
I'll probably rework them in the future tho
Whats this the rename happened? Now the channel just needs to be renamed 