Controlling Velocity Interaction (Or controlling entities)

Discuss any questions about BEPUphysics or problems encountered.
Post Reply
Oatmeal
Posts: 3
Joined: Wed Oct 29, 2014 12:47 pm

Controlling Velocity Interaction (Or controlling entities)

Post by Oatmeal »

I'm having difficulty controlling the way entities interact with each other. I need to have entities in my game that move at constant velocities (such as the player and some enemies/npcs, dynamic or not) interact with each other, and some other (dynamic) entities (not moved by editing the velocities) with controllable behaviour (ie. one control would be limiting max velocity such as a clamp operation done every frame on linear velocity before running Update() on a physics space).

For example, if I were to have a dynamic box (no localtensor, so no rotation, represents a player character) with a mass of 1 unit constantly moving forward 1meter(s)/second to collide with another dynamic box (rotation enabled, represents an object that can be interacted with) that has a mass of 1 unit on a flat plane, the expected behaviour is that the object box is pushed along with the box.

This is sort of what happens, although it is not perfect because it seems the object box gets "snagged" by the triangle data's lines on a flat plane mesh I am using (happens whether it is a mobile mesh entity or a static mesh. The mesh is flat so there is are no problems with that, using a few box colliders for the floor is the same effect) for the floor and then strays from the direction it is being pushed in, sometimes a little violently, and may even be thrown in the air a little. I don't know if that is supposed to happen but for now it does not matter as much to me as everything else I will explain. So for the most part the behaviour is expected.

If I increase the mass (twice, thrice, etc.) of the box that represents the player the behaviour that is expected also happens for the most part (distance the object is expected to travel is somewhat inconsistent), that the object box is flinged ahead more as the mass of the player box increases.

Now, this is all well but I need to be able to create a different sort of behaviour. I need it so that no matter what velocities the player box may be traveling at, or even what mass it has, the player box should gently brush aside the object box instead of flinging it upon impact (because the velocity of the player character will be well above 1 meters/second there will be a lot of force applied even at similar mass relationships) and not lose it's own velocity (setting the object box's mass at a higher ratio than the player box yields the effect that I want for the object but not the player as the player now does not move at it's full velocity set every frame). The way I am currently moving the player box is by setting the linear velocity every frame (the change between desired velocity and current velocity is added to the current velocity every frame, works better than setting the velocity directly because gravity starts becoming an issue) and it works just fine for moving it so I would like to continue to be able to do this.

I think a good way to describe what I want is something that I have tried and seems to have the similar effect I want. That is, I used a kinematic box to represent a player, and used the character controller to represent the object. By setting the controller to ridiculous settings for traction, forces, glue, etc. I was able to have the fast moving kinematic box (just moves in a back and forth pattern, and it is kinematic because I don't want it to lose any velocity upon hitting objects) push the object gently along with it in it's path and not fling it across the scene (which is what happens without adjusting the settings). The issue is that I don't think I need a character controller for every physics object like that in the game, it would get ridiculous to have hundreds of controllers representing some debris objects, and I'd like to be able to use dynamic entities for the players/npcs so they can move each other as well (perhaps not in the exact same relationship as this though, but simialrly),

So is there a way I can achieve this sort of relationship with the "player" and "object" dynamic entities? In this particular case, to restrain the impact the player moving has into the object entities, ensure the player does not lose velocity upon impact, and keeping the relationships of other object entities amongst themselves the same. I feel like the answer might lie in the collision events that take place during the physics calculations ie. PairUpdating, but I really don't know how I would do it even with that. Also, this is only one step of the way for me as I mentioned earlier that I plan to have players/npcs interact with each other in a similar way (players colliding into enemies/npcs but not flinging them away because of mass/velocities and also being able to control the velocities of the players and enemies upon the impact(s) ) but I feel if I can get this one thing done first then I can start trying to figure it out more myself. If I'm not being clear enough, please let me know.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Controlling Velocity Interaction (Or controlling entitie

Post by Norbo »

This is sort of what happens, although it is not perfect because it seems the object box gets "snagged" by the triangle data's lines on a flat plane mesh I am using (happens whether it is a mobile mesh entity or a static mesh. The mesh is flat so there is are no problems with that, using a few box colliders for the floor is the same effect) for the floor and then strays from the direction it is being pushed in, sometimes a little violently, and may even be thrown in the air a little.
Meshes use the index buffer of a mesh to determine connectivity. If the index buffer does not imply that an edge is shared between two triangles, the collision system will treat the triangles as separate. This makes the border between triangles act like a bump, since objects can hit the edge of triangles.

To fix this, make sure the vertex/index arrays represent a connected mesh rather than a triangle soup.
So is there a way I can achieve this sort of relationship with the "player" and "object" dynamic entities?
As far as the interaction between players and objects goes, it sounds like a kinematic box for the player and a tightly controlled representation for the objects would be the right choice. CharacterControllers aren't necessary for the other objects- you could very cheaply represent them as dynamic objects which you control the velocity of. The character's horizontal motion constraint just fights all motion, so if that was producing acceptable results, then just setting the linear velocity of the dynamic object to zero would do the trick much more quickly.
keeping the relationships of other object entities amongst themselves the same
I'm not entirely sure what this implies. Would this mean you want completely normal physical behavior for object-object interactions, with no arbitrary velocity control at all? If so, then you will indeed have to detect when the player is colliding in order to know when to damp out collision responses. This is a nonphysical operation, so it necessitates some kind of hack.

You may even want to completely replace player-object collision response. That is, use collision rules to turn off collision response between the players and objects. Then, when detecting a collision between a player and an object, apply whatever impulses/velocities you want for gameplay. To detect the collision, either use collision events or just scan the player's collision pair list for active collisions. To scan existing collisions, check the entity.CollisionInformation.Pairs list. Each pair has a Colliding property which returns true if there is a collision in progress, and a Contacts list which contains the set of generated contacts. It also contains references to the involved collidables/entities.
Oatmeal
Posts: 3
Joined: Wed Oct 29, 2014 12:47 pm

Re: Controlling Velocity Interaction (Or controlling entitie

Post by Oatmeal »

Hi Norbo,
Meshes use the index buffer of a mesh to determine connectivity. If the index buffer does not imply that an edge is shared between two triangles, the collision system will treat the triangles as separate. This makes the border between triangles act like a bump, since objects can hit the edge of triangles.

To fix this, make sure the vertex/index arrays represent a connected mesh rather than a triangle soup.
You are absolutely right as I used a much larger plane mesh with only 4 vertices and it greatly reduced the bumping and tossing. The reason I am using a plane mesh with many extra vertices is to provide accurate collision for more complex mobile mesh shapes (the less triangle information and the more the vertices are spread out, the more glitch like collision is with these shapes. For example I dropped a roughly box like mobile mesh shape, a phone stand, onto the mesh and it always gets stuck into the mesh and acts crazy unless I use the triangle soup mesh with extra vertices). I believe by connected mesh you mean using "Solid" for mesh solidity? With the plane mesh I am using, it tells me it can't create a solid mesh with no volume exception so I just used the clockwise option. I'll try creating a different mesh with extra vertices later and see if I still get the exception.

I also found this was not the only thing causing the bumping and tossing between the entities in my game. I discovered that because I am using the update loop that runs every frame to change the velocity that it probably caused the rest of the inconsistencies (thanks to deltatime since it is only variable that changes). After spending the day testing options I simply moved the velocity changing to a fixed update loop instead (20 updates per second) and it removed the rest of the inconsistencies and now the expected behaviour occurs where the player object pushes other objects with equal or less mass along with it and does not fling it ahead or at any odd direction at any point.

For this following paragraph I feel like it should be it's own thread but I still feel like it's very relevant so I'll just post it anyway. It is however not as smooth as I like and I am not sure I like having user input controls used in the fixed update loop rather than the update loop. I'm not sure there is any other way I could do this though but it is okay for now. I did find something I really did not like however. Although I moved the velocity change scripting to a fixed update loop, BEPU still runs in the update loop. I thought I could save some cpu usage by moving it to the fixed update loop but it only seemed to increase cpu usage no matter how much I decreased maximum timesteps or used internal timestepping or not (for fixed update it seems internal timestepping is better to use because calculating the blend amount and asking for interpolation updates myself ate a lot of cpu usage. It is odd because when the space runs in the update loop, internal timestepping really slows down the system although I still have to enable buffered states because the game engine I am integrating this physics system with, Unity3D, runs very erratic without buffered states enabled even if I don't touch and use the interpolated states. I still do not know why that happens). It is currently relatively rather high, I am ran about 1600 dynamic box entities, all inactive/sleeping, at about 10ms, almost an entire frame at 60 fps). Of course, increasing the timestep duration (currently have it at 1.0/60.0) to 1.0/30.0 etc. saves a lot of cpu usage but it causes bad simulations. Even at 1.0/30.0 timestep duration, bouncy objects might bounce infinitely, falling objects might get a little stuck, and some objects might continue to violently vibrate, against other objects that also have bounciness enabled even if bounciness is very little between both materials. Adjusting the iteration count options did not help for this situation either.

At the very least it turns out the bumping and tossing of "object" entities was my fault and it is mostly solved for now.
I'm not entirely sure what this implies. Would this mean you want completely normal physical behavior for object-object interactions, with no arbitrary velocity control at all? If so, then you will indeed have to detect when the player is colliding in order to know when to damp out collision responses. This is a nonphysical operation, so it necessitates some kind of hack.
Not exactly, I want to be able to control the velocities of the entities. But I do not want to just limit the velocity of the "object" entities every frame. Because then when object entities collide with other object entities instead of the player the objects won't push and collide each other very far, and also won't travel very far when adding forces and such. Also, setting the mass of the objects relatively higher than the player will limit the velocity it is traveling at and for some objects it should not do that. An example would be like a player running through some debris objects that should be pushed aside gently but not impede movement. Basically, I want it so Object to Object interaction remains as normal, Players treat the objects as relatively varying low mass so it can push them aside without losing velocity, Objects treat player's collisions as limited velocity (so a player running at 5 meters/second does not transfer that full velocity to the object), and finally, have players and npcs/enemies push each other around like objects but also with limited velocities when colliding so they do not toss each other away. Using a kinematic object for the player would not work well if I want to have players also able to move around npcs. I do believe that you are right and that is what I need as well as physical operations.
You may even want to completely replace player-object collision response. That is, use collision rules to turn off collision response between the players and objects. Then, when detecting a collision between a player and an object, apply whatever impulses/velocities you want for gameplay. To detect the collision, either use collision events or just scan the player's collision pair list for active collisions. To scan existing collisions, check the entity.CollisionInformation.Pairs list. Each pair has a Colliding property which returns true if there is a collision in progress, and a Contacts list which contains the set of generated contacts. It also contains references to the involved collidables/entities.
I would disable the narrowphase for the Player group and object group? I'm not quite sure how I can input create my own velocities/impulses after that. I think I can use the collision events but I am still not sure which ones I need exactly or rather how to calculate the velocities/impulses and limit them upon collisions. The collision pairs also look good to use about the same, however I am still not sure how I would go about it exactly. Before I thought in sort of pseudocode I would do something like this:

//Assuming this is the player
void PairCollisionEvent(vars)
//If Entity collided with is debris, make sure it does not fly across the screen
if (entityB.Tag is Debris)
entityB.LinearVelocity = Clamp( entityB.LinearVelocity )
//If Enemy collided with me, make sure I don't fly around the screen
if (entityB.Tag is Enemy)
entityA.LinearVelocity = Clamp(entityA.LinearVelocity )

I don't think it's that simple as debris objects may already be moving around with their velocities and touching the player would make them instantly lose their velocity instead of "bouncing" of the player and continue traveling. At least the debris should be somewhat controlled. But this is the sort of general idea I was thinking about before.

Thank you for the help.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Controlling Velocity Interaction (Or controlling entitie

Post by Norbo »

The reason I am using a plane mesh with many extra vertices is to provide accurate collision for more complex mobile mesh shapes (the less triangle information and the more the vertices are spread out, the more glitch like collision is with these shapes. For example I dropped a roughly box like mobile mesh shape, a phone stand, onto the mesh and it always gets stuck into the mesh and acts crazy unless I use the triangle soup mesh with extra vertices).
It sounds like there is inconsistent winding in the mesh. One-sided triangle collision uses winding to determine which direction is 'out'. Colliding objects will be shoved out along that direction. If triangles have inconsistent winding, some triangles will pull objects into the mesh, while others push out. This tends to cause horrible behavior. To fix it, just make sure the mesh triangles have consistent winding.

If double-sided triangles are used, they may be getting stuck behidn something. Such triangles will resist being pulled back out. One-sided meshes are usually a better idea for this reason. (Continuous collision detection is supported for meshes, but it is not cheap and cannot guarantee perfect nonpenetration.)
I believe by connected mesh you mean using "Solid" for mesh solidity? With the plane mesh I am using, it tells me it can't create a solid mesh with no volume exception so I just used the clockwise option.
Solid just means a MobileMesh will consider its interior to be filled. Objects inside the MobileMesh will be pushed out. This is why a plane can't be Solid: it has no interior. To use Solid, the mesh must 1) have consistent winding, 2) have volume, 3) be a single closed surface.

When I said connected mesh, I was referring to the relationship between the vertex list and index list. For example, here is an example of a single "unconnected" quad's vertices and indices:

vertices[0] = {0, 0, 0}
vertices[1] = {1, 1, 0}
vertices[2] = {0, 1, 0}
vertices[3] = {0, 0, 0}
vertices[4] = {1, 0, 0}
vertices[5] = {1, 1, 0}

indices[0] = 0
indices[1] = 1
indices[2] = 2
indices[3] = 3
indices[4] = 4
indices[5] = 5

In this case, the index list isn't really doing anything useful, and the vertex list contains two redundant entries at the diagonal edge of the quad. The collision system will consider these two triangles to be fully separate, and there will be a bump at the diagonal border.

In contrast, a "connected" quad could look like this:

vertices[0] = {0, 0, 0}
vertices[1] = {1, 0, 0}
vertices[2] = {0, 1, 0}
vertices[3] = {1, 1, 0}

indices[0] = 0
indices[1] = 3
indices[2] = 2
indices[3] = 0
indices[4] = 1
indices[5] = 3

In this case, there are no redundant vertex definitions. The index list points to the unique vertices. The diagonal edge between vertex 0 and vertex 3 is shared by both of the quad's triangles, since vertex indices 0 and 3 are in both triangles. This lets the collision system know that it should smooth this edge out as if it is a continuous surface.

Note that you should avoid MobileMeshShapes whenever possible. A MobileMeshShape in the form of a box is vastly more expensive than a simple BoxShape. If you need concavity, consider using a few simple primitives combined together into a CompoundShape.
It is however not as smooth as I like and I am not sure I like having user input controls used in the fixed update loop rather than the update loop. I'm not sure there is any other way I could do this though but it is okay for now. I did find something I really did not like however. Although I moved the velocity change scripting to a fixed update loop, BEPU still runs in the update loop. I thought I could save some cpu usage by moving it to the fixed update loop but it only seemed to increase cpu usage no matter how much I decreased maximum timesteps or used internal timestepping or not (for fixed update it seems internal timestepping is better to use because calculating the blend amount and asking for interpolation updates myself ate a lot of cpu usage. It is odd because when the space runs in the update loop, internal timestepping really slows down the system although I still have to enable buffered states because the game engine I am integrating this physics system with, Unity3D, runs very erratic without buffered states enabled even if I don't touch and use the interpolated states. I still do not know why that happens).
I would recommend more rigorously isolating and measuring the performance issues. Indirect estimates aren't very useful for optimization or tracking down problems.

That said, if the SpaceUpdate is called from a fixed update loop, using Space.Update(dt) (that is, internal time stepping) should do almost nothing. The fixed updates already force the correct number of updates to occur, and the interpolation won't be useful because the time steps should always be very close to a full time step if the Space.TimeStepSettings.TimeStepDuration is set to an appropriate value. It just adds a little overhead for no gain.
It is currently relatively rather high, I am ran about 1600 dynamic box entities, all inactive/sleeping, at about 10ms, almost an entire frame at 60 fps). Of course, increasing the timestep duration (currently have it at 1.0/60.0) to 1.0/30.0 etc. saves a lot of cpu usage but it causes bad simulations. Even at 1.0/30.0 timestep duration, bouncy objects might bounce infinitely, falling objects might get a little stuck, and some objects might continue to violently vibrate, against other objects that also have bounciness enabled even if bounciness is very little between both materials. Adjusting the iteration count options did not help for this situation either.
While 30hz definitely does interfere with oscillation-style behavior, what you described sounds worse than it should be.

Further, 10ms is quite high for only ~1600 sleeping objects. If this is running on an old or mobile platform, particularly on a single thread, that might be more reasonable. For comparison, 5600 sleeping objects in 10400 inactive collisions takes 4ms in the latest source version on my desktop. (Notably, I'd like to get this down to <<1ms in future versions; there's no real reason why a bunch of inactive objects need any compute time.)

You may want to create and test out a representative simulation in the BEPUphysicsDemos to see if it's any different. This isolates it from any environmental factors like Unity's runtime. If the isolated demo is still anomalously slow or unstable, I could take a look at it and figure out what is contributing.
I would disable the narrowphase for the Player group and object group?
No; collision response is the process of determining what velocities to apply based on the data provided by collision detection. Broad phase and narrow phase are responsible for collision detection, and the solver is responsible for collision response. So, you'd want to use the NoSolver rule.
Oatmeal
Posts: 3
Joined: Wed Oct 29, 2014 12:47 pm

Re: Controlling Velocity Interaction (Or controlling entitie

Post by Oatmeal »

Thank you for the response, I saw this as soon as you posted but I have not had a chance to do anything this week and the half of last. Tackling it now.
It sounds like there is inconsistent winding in the mesh. One-sided triangle collision uses winding to determine which direction is 'out'. Colliding objects will be shoved out along that direction. If triangles have inconsistent winding, some triangles will pull objects into the mesh, while others push out. This tends to cause horrible behavior. To fix it, just make sure the mesh triangles have consistent winding.
Yep, this is the problem, it seems otherwise box colliders are fine.
While 30hz definitely does interfere with oscillation-style behavior, what you described sounds worse than it should be.

Further, 10ms is quite high for only ~1600 sleeping objects. If this is running on an old or mobile platform, particularly on a single thread, that might be more reasonable. For comparison, 5600 sleeping objects in 10400 inactive collisions takes 4ms in the latest source version on my desktop. (Notably, I'd like to get this down to <<1ms in future versions; there's no real reason why a bunch of inactive objects need any compute time.)
There's not much of a problem with no bounciness in the materials of course, but I think I will need this for some objects. The issue seems to be when many entities are near each other, bounciness enabled (>0f), collide and rest on each other. Stacking seems to be okay, at least with some spheres. However, the higher the bounciness the more unstable it is as well. The infinite bouncing occurs for example when a sphere has a bounciness of >0.70f and a box collider floor has a bounciness of >0.75f. It is not concrete however and happens when there is generally high amounts of bounciness between the two interacting objects. Increasing the default position damping from 0.03f to 0.15f or higher seems to help, changing the frictions did not, however it changes the behavior of that object quite a bit. Is the way to properly control bounciness or is there something else I should try? The simulations beside this, are reasonable so if possible I'd like to just use 30hz instead of 60hz.

I am running a single-thread, laptop with an intel i7-3610qm. There are also about two hundred entities (boxes) falling infinitely too, I removed them, it's about 5-5.5ms, not counting moving graphics to where the physics objects are of course (that is about another 2ms that can't be reduced). I do need to update to the latest source however so I will try that out next.
You may want to create and test out a representative simulation in the BEPUphysicsDemos to see if it's any different. This isolates it from any environmental factors like Unity's runtime. If the isolated demo is still anomalously slow or unstable, I could take a look at it and figure out what is contributing.
Installed XNA, ran the compiled executable, and it seems to run very smoothly on the same laptop. While running broad phase stress test, the one with sleeping box objects and a ball you can click/throw to activate them, I noted that when most active there were about 2,500 active objects and about 400 collision pairs and it said the physics time was about 2.2ms. It is at 1.5ms when starting the test and throwing the ball, has 5 active objects. I don't BEPU is the problem but I don't know if there is anything else I can try to configure it to run better with Unity. As I've said, I've tried using different combinations of timestep durations, max steps, internal or no internal timestepping, and fixed or game update loop, but the best combination seemed to be no internal timestepping with a game update loop and it seems like it shouldn't be running that slow.
No; collision response is the process of determining what velocities to apply based on the data provided by collision detection. Broad phase and narrow phase are responsible for collision detection, and the solver is responsible for collision response. So, you'd want to use the NoSolver rule.
As for the collision stuff, I decided to try limiting the velocities first instead of trying to determine the velocities (I feel like that would be too difficult for me to attempt). I tried to limit the velocities of the debris entities using the "During" physics events. However, it seems that only the immediate pairs/objects touching the player are affected. When there are other entities touching the entities that are moved by the player in the same update, it seems they are hit by the original force of the entity that was touched by the player. So while the objects that are touched are pushed aside in a more soft manner, the objects touching the touched objects are not. I tried to use recursion within the collision event (PairTouching, also used PairTouched) to limit all pairs that have touched the pair and are also objects I should be limiting but it didn't seem to work. Also, the angular velocities of the entities are increased heavily now when pushing the limited objects, especially when corners meet. I think I will have to limit the angular velocities as well now.

Also, the player's velocity, when running into a bunch of these objects huddled together, is still slowed down. I think I will have to change the player to a kinematic object. However, It will be much harder to have that player respect other kinematic objects such as walls, and interact with enemy kinematic objects like physics objects. The limiting of the debris entities are still a problem for me, kinematic or not however.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Controlling Velocity Interaction (Or controlling entitie

Post by Norbo »

Is the way to properly control bounciness or is there something else I should try?
Increasing the CollisionResponseSettings.BouncinessVelocityThreshold sufficiently will probably get rid of the infinite bounces, assuming there is not something strange causing issues. This tuning parameter just damps out bounces below the threshold.
I don't BEPU is the problem but I don't know if there is anything else I can try to configure it to run better with Unity.
It may still be worth trying to create a custom simulation in the demos with a better match to the unity-side simulation to narrow down potential differences. If they're not almost the same simulation, there will be too many unknowns to extract much useful information.
I tried to limit the velocities of the debris entities using the "During" physics events.
If you mean the collision events with present tense names, watch out- those events are fired from different threads when the engine uses multithreading, so accessing any shared state (like entity velocities) is unsafe.
I tried to use recursion within the collision event (PairTouching, also used PairTouched) to limit all pairs that have touched the pair and are also objects I should be limiting but it didn't seem to work.
Collision detection runs before collision response, so the collision constraints will not be robustly hindered by velocity changes performed during collision detection. Using a deferred event (past-tense names) would technically be able to limit it since it runs at the end of the time step, but as you discovered, it can be tricky to 'undo' a propagated physical response.
I decided to try limiting the velocities first instead of trying to determine the velocities (I feel like that would be too difficult for me to attempt).
It depends what kind of behavior you're looking for. It would be difficult to recreate the full proper physical response, yes, but if you would be okay with just a gentle position-based shove 'away' from the center of the character, then it's not too hard. Something as simple as taking the offset between the entities' positions and applying a force based on the distance might work, depending on the specifics of the desired behavior. To avoid accumulating too much force and launching an object, you could measure the relative velocity along the axis of force (e.g. dot(b.LinearVelocity - a.LinearVelocity, offsetDirection)) and clamp the amount of force applied to avoid exceeding a certain maximum velocity threshold.
Post Reply