Fluid Simulation

I don't know how well-researched you guys are about how to get SPH particles vs solid bodies interacting properly. If you know about this (white papers, source code examples, etc), it'd be useful to me to know about them. I haven't been able to find a huge amount of resources, but the ones I have found have all advocated a Verlet integration type approach, with two main rules:

1 - If a particle intersects with static geometry, just apply a big enough force in the right direction to push the particle back out again.

2 - If a particle intersects with dynamic geometry... It gets weird. All of the approaches I've seen represent a solid (but movable) body as a bunch of particles representing the verts, let them mix up in the fluid every frame, and at the end apply constraints to "pop" the particles back into something representing a solid shape.

The reason I bring all this up now is because I've been trying Boris' "option 5" from his earlier post. Namely, to filter all of the particles such that they just fall through the world, generating pairs but not generating any contact points, allowing me to iterate through the relevant pairs and dealing with them myself (I figured it was a step towards trying "option 3", where the particles don't exist in the broadphase at all and using AABB queries to find out what needs processing by hand). The prerequisite for both approaches is handling the interaction between fluid and non-fluid ourselves, and I think that's important. Representing particles as small circular solid bodies doesn't really work - the interactions with the static bodies aren't bad but, for instance, try making the box have a low enough density to float on the fluid. Doesn't work. I think if the fluid simulation is going to be "correct" or useful, the approach should really be non-solid particle bodies that are affected by the environment, and can apply forces to the movable parts of it.

Anyway, I've started by trying to get the particles to not intersect with the static geometry (no attempt at having them move the box yet). For debugging, my code draws pairs (in red) when intersections take place, and draws the points they should move to (blue points) to get out of the geometry. I've followed ewjordan's lead of just setting positions directly rather than calculating forces, since the particles don't really interact inside the engine anyway. I'm doing something wrong, though. The particles bleed and tunnel through the geometry whatever I try to do to seperate them from the solid geometry. If anyone knows how fluid/non-fluid interactions should work can take a look at it and let me know where I've gone wrong, that would be ace. I had to fudge b2World to give an accessor to the broadphase, so that I could examine the pairs - pretty simple, just add the following into b2World.h, somewhere public:

Code:
inline b2BroadPhase* GetBroadphase() { return m_broadPhase; }


(Also, I've not performance-profiled this approach yet, but from watching it onscreen it seems a lot quicker to me)
I don't know anything about fluid simulation. I'm leaving that to you. I'm just joining to help on the details side.

I was lying in bed last night, when it hit me how stupid I was being. There's another way of doing particles, which I should have thought of. It's the reason why the array of vectors is fine, I just couldn't remember it.

So what we do, is put rigid bodies in the broadphase, and particles in the array of vectors. We determine collisions between rigid bodies as Box2D does, neighbour between particles as you've been doing. But there's a much easier way of doing body-particle collisions: For each shape, loop over the squares is overlaps, or nearly overlaps, and determine it's neighbour particles. It's far easier to say "find the particle neighbors of this shape", than it is "find the shape neighbours of this particle".
Interesting idea, Boris. I'm not sure whether it'd be quicker to have each shape work out which grid squares it covers to build a neighbour list, or whether it makes more sense to still do AABB queries to find shapes, but do one query per grid square (assuming it contained particles), and store the results for each particle in that square to use, rather than have each particle compute AABBs for itself. I have a hunch that the answer to that might depend on how the user sets up the level/world (number, position, orientation and size of rigid shapes, number of particles, size of the grid), but either way it makes a lot of sense to consider shape intersections with grid squares rather than with particles, if such checks are needed.

I'm still testing pairs (with the particles existing in the broadphase but fully filtered against everything) to find fluid vs solid interactions to handle. I was tired last night, so the code I posted up had a pretty stupid omission, which was that I was moving particles to the edge of solid objects to try to stop intersections, but wasn't doing anything to change their linear velocity. As a quick hack I tried setting it to zero, which works pretty well at keeping the fluid from passing through the static geometry, but has the side-effect of making everything seem a lot more viscous, because particles in contact with rigid bodies move much more slowly, so kill off all the undercurrents and eddies. Right now I'm trying to look up (or work out) what the proper way to adjust the particle's velocity is but I'm not having much luck.
Hello again,

Sorry if people are getting tired of this now, I've noticed that not many threads seem to get this in-depth about stuff, but I'd like some more advice/opinions. What do people make of the way to handle fluid vs rigid body collisions described in this white paper?

http://www.iro.umontreal.ca/labs/infogr ... S/pvfs.pdf

I found the paper overall quite interesting, although most of it doesn't seem very practical for what we're trying to do. The main point of interest is section 6.1 (on page 7), which describes a way to get fluid particles interacting with moving rigid bodies nicely. Most of the maths makes sense, although a couple of bits seem to have been glossed over a bit, and it looks like it might have implications for how the update loop for a frame needs to happen. The way I'm reading it, it looks like the algorithm (as translated into the code for this Box2D test) looks something like this:

Code:
1 - Do a Box2D physics step on all of the particles. We somehow need to generate pairs with the rigid bodies, but I don't think we should be applying forces or moving the rigid bodies just yet.
2 - Resolve any intersections between particles and static geometry by pushing the particles back out and setting appropriate velocities for the next frame.
3 - Do the "magic maths" described in the paper for handling intersections with rigid, non-static bodies, and apply the resulting forces
4 - Do a Box2D physics step only on the rigid bodies, (i.e. don't step the particles), to move the bodies, resolve any intersections with other bodies, etc
5 - Do another pass between the particles and the (now moved) nonstatic rigic bodies, to move the particles out


Does that sound right? Is there a way of simplifying this process? Is there a way to tell Box2D "do a physics step for this subset of bodies, but not this other subset"?

The only other part of the paper I found a bit ambiguous was "We then compute the particle relative velocity V = vi - vp, where p is the body velocity at the contact point"... I presume what they mean is that I'd have to find the current velocity of the exact point in the body where the particle overlaps, given the body's current linear and angular velocity, but I have no idea how to calculate that.

I'm keen to find a way that this approach (or one like it) can be made to work, because then I think we'll have something which can really work well with Box2D.
No, you cannot tell it not to integrate just some bodies, but that should be easy enough to add. You have to be changing Box2Ds step function for your proposal anyway, as you are doing stuff halfway through a step.

Conveniently, there's a function for getting a bodies velocity at a particular point.
http://personal.boristhebrave.com/perma ... orldPoint()

No, things don't get too in depth here, for lack of enough people willing to talk. Don't think it's taboo, though 😉. You might want to try http://www.bulletphysics.com/Bullet/php ... um.php?f=4 , which is more generally oriented, and populated, I think.
Upon a quick reading, the method presented in that paper seems reasonable to me, if you can get it working (quite a few details to get right). The main claim they make is that they're able to get things stable, whereas they couldn't with impulse-based collision resolution, so that would be a definite plus.

The only thing that I would worry a little about is that things still might not interact very well with warm starting, because those impulses from the water are not getting stored away or anything. Pretty much every time I've added external interactions on top of Box2d, weird things happen when you stack objects. I'm not sure how significant a problem this would be, though, and to fix it might be a hassle.

Quote:
The only other part of the paper I found a bit ambiguous was "We then compute the particle relative velocity V = vi - vp, where p is the body velocity at the contact point"... I presume what they mean is that I'd have to find the current velocity of the exact point in the body where the particle overlaps, given the body's current linear and angular velocity, but I have no idea how to calculate that.

I agree with Boris on this one, just use the function provided. The only ambiguity remaining is what to take as the contact point, the current particle location (inside the body), or the raycast crossover point, or what; they will all reduce roughly to the same thing in the low velocity limit, so I suspect you can probably get away with just using the current particle location, otherwise you'll have to start special-casing for situations where the particle starts inside the body.

Also, the last step, removing particle-solid penetration once and for all, Box2d can do as part of the position correction it normally does. The only thing you may need to do is figure out how to enable that while disabling the velocity corrections (as you'll be applying those yourself).
Quote:
The only thing that I would worry a little about is that things still might not interact very well with warm starting, because those impulses from the water are not getting stored away or anything. Pretty much every time I've added external interactions on top of Box2d, weird things happen when you stack objects. I'm not sure how significant a problem this would be, though, and to fix it might be a hassle.


I have to confess that I don't really know what warm starting is, exactly - is it the clever stuff referred to earlier in the thread whereby the broadphase stores information about its previous states as an optimisation for future states, or is it something else?

I'm inclined to deal with any oddness to do with stuff like stacking as and when it arises rather than worry about it now. I think I'd have to see it in action to get an idea of what (if anything) is going wrong, and I can't adequately do that until I can get fluid vs solid interactions working to some level of realism. I'm focussing on that right now, as well as flitting between various approaches suggested by Boris in order to try to work out the most optimal trade-off between efficiency, realism and elegance in terms of how this will all interact with Box2d.

One thing I did want to ask - in your Java code, you update the particles like this:

Code:
for (int i=0; i<liquid.length; ++i) {
   liquid[i].m_xf.position.x += xchange[i] / multiplier;
   liquid[i].m_xf.position.y += ychange[i] / multiplier;
   liquid[i].m_linearVelocity.x += xchange[i] / (multiplier*deltaT);
   liquid[i].m_linearVelocity.y += ychange[i] / (multiplier*deltaT);
}


Which (given that the C++ version doesn't allow you to directly change those things on a body), I translated as this:

Code:
for (int i=0; i<NUM_PARTICLES; ++i)
{
   liquid[i]->SetXForm(liquid[i]->GetPosition() + b2Vec2(xchange[i] / multiplier, ychange[i] / multiplier),
         liquid[i]->GetAngle()); // I know, I could just use 0.0f for the angle

   liquid[i]->SetLinearVelocity(liquid[i]->GetLinearVelocity() +
         b2Vec2(xchange[i] / (multiplier*deltaT), ychange[i] / (multiplier*deltaT)));
}


Do you remember your reasoning forsetting the position and velocity directly, rather than applying a force or impulse? The reason I ask is that SetXForm has turned out to be rather expensive for me to call in a loop like that (something like 18% of the CPU time, in my current code) since it updates the broadphase for every particle, which I'm not sure is needed. Rather than breaking encapsulation in the C++ version to set those values directly, I've tried the code below to just apply an impulse and let Box2D cope with updating the particle positions and velocities on the next Step, and it seems to work quite well, but I wanted to make sure that there wasn't some big important reason for avoiding this that I've missed.

Code:
liquid[i]->ApplyImpulse(b2Vec2(xchange[i] / multiplier, ychange[i] / multiplier), liquid[i]->GetPosition());


Also, I think there's something else in your code that I'm not sure if I'm understanding properly. When you're calculating the forces between two particles, you're making changes to xchange[i] and ychange[i], but also xchange[j] and ychange[j]. To me this implies that you're doing that standard SPH optimisation of applying the calculated forces to both particles to avoid considering each particle twice (so, you calculate the forces for both i and j when considering ij, and then don't bother considering ji because you've already calculated the forces). But I don't see the code for skipping past pairs which have already been processed. Am I missing something there?
ElectroDruid wrote:
I have to confess that I don't really know what warm starting is, exactly - is it the clever stuff referred to earlier in the thread whereby the broadphase stores information about its previous states as an optimisation for future states, or is it something else?

More or less - it doesn't happen in the broadphase, but in the contact handling, but otherwise, you're right on, Box2d stores a predicted impulse as a starting value as it iterates.

Quote:
Do you remember your reasoning forsetting the position and velocity directly, rather than applying a force or impulse? The reason I ask is that SetXForm has turned out to be rather expensive for me to call in a loop like that (something like 18% of the CPU time, in my current code) since it updates the broadphase for every particle, which I'm not sure is needed. Rather than breaking encapsulation in the C++ version to set those values directly, I've tried the code below to just apply an impulse and let Box2D cope with updating the particle positions and velocities on the next Step, and it seems to work quite well, but I wanted to make sure that there wasn't some big important reason for avoiding this that I've missed.

I probably did that because I first got this running as a pure particle based Verlet-integrated demo (I don't think I ever posted that one), and this was the most literally direct translation. I don't think I was being particularly clever or anything.

Quote:
Also, I think there's something else in your code that I'm not sure if I'm understanding properly. When you're calculating the forces between two particles, you're making changes to xchange[i] and ychange[i], but also xchange[j] and ychange[j]. To me this implies that you're doing that standard SPH optimisation of applying the calculated forces to both particles to avoid considering each particle twice (so, you calculate the forces for both i and j when considering ij, and then don't bother considering ji because you've already calculated the forces). But I don't see the code for skipping past pairs which have already been processed. Am I missing something there?

The symmetric response is a bit more than an optimization, it's actually required for strict conservation of momentum, since the pressures at each particle location might be different and you could otherwise end up with unbalanced forces. It's a typical problem with discretization, that even though the continuous equations conserve everything exactly the discretized ones violate many conserved quantities slightly, in this case based on the particle-to-particle pressure difference. You may be able to optimize things a bit, but to some extent the simulation will then depend on which particles happen to be the "base" ones that pressures are calculated with respect to. Shouldn't be a huge deal, though, and it might be worth it to save a factor of 2 on the computation time. I sort of doubt if there would be much, if any, visual difference.
Just when you thought it was safe to return to the forums... 👿

My experiments with this have taken some unusual tangents. I hope that this is interesting or useful to people (and, I'll be honest, I kinda hope that I can get some help from those wiser than me, 'cos this stuff is HARD...) 😉

Here's the gist of what's in the attached code (you should be able to find the points of note by looking in the code for comments marked with "electrodruid").

PERFORMANCE:

- Having tried a bunch of different things, I've come to the conclusion that handling fluid particles is best kept away (for now) from Box2D's broadphase. I've profiled the hell out of the performance (you may have guessed by now that I want to make a game that heavily involves fluid), and Box2D is just too heavyweight for it. Perhaps in future the fluids could be wrapped into a controller, or some new addition directly into the engine, but for now I'm keeping things seperate. Box2D does no direct processing of the fluid particles whatsoever.

- Given the above, I've gone with using the grid system for spatial partitioning. I managed to get a considerable performance increase by taking the plunge and replacing the std::vector stuff with a little custom linked list class which can link cell lists together into a neighbour list, and then unlink them again without having to copy things. It involves some careful housekeeping, but it works pretty well.

- The custom grid/list shenanigans does its interaction with Box2D by running AABB broadphase tests in the cells which contain particles (excellent idea, Boris!). As yet I have no idea exactly how scalable this is to bigger levels/more objects in Box2D/more particles, but as a general approach I think this has the best shot of being workable.

- I had a stab at code to only process each particle pair once, but it didn't work so well. I think this is still possible (effectively doubling performance, or something close to that), but it needs to wait until some evening when I'm feeling brave enough to completely rewrite applyLiquidConstraints() from the ground up, I think.

INTERACTION WITH BOX2D (particularly with regards to floating things)

- I've not yet looked into a way to integrate this with the buoyancy controller, primarily because I'm not quite sure if my game will have big enough areas of standing fluid to warrant it, and partly because the original setup of the static test geometry in ewjordan's code

- I had a stab at going with the more "traditional" method for getting fluids to interact well with movable rigid bodies: namely, representing those bodies as spring-mass particle systems under Verlet integration, but getting that to play nicely with Box2D turned out to be a world of pain, so I've fallen back on trying to replicate the descriptions in that white paper. See below for my pleas for help. In the meantime, there's a #define in the header file which you can comment or uncomment to switch between Euler and Verlet integration and get (roughly) the same results. Broadly speaking, Verlet seems to be the more efficient option even without the "tradional" method of rigid body interaction, because you can just set particle positions according to whatever constraints you want, and the integrator will work out velocities for you.

PLEA FOR HELP

My attempts to replicate the approach in the white paper haven't been entirely successful, although I've got closer by fudging the numbers a bit. I had hoped that simply by adjusting the density of the b2Shapes (and therefore the mass of the b2Bodies) I could neatly control whether something would float or sink, but that's not working for me. You'll see the code (particularly in processWorldInteractions()) is littered with comments along the lines of "I don't quite know how to do this bit". I've tried countless cominbations of the code using a "infinite number of monkeys at keyboards" approach, but nothing quite gets it right. The problem (as I see it) is that however light I make the bodies, they will not float, and furthermore, the lighter the bodies are, the less rotational inertia they have, so the bigger their tendency to spin uncontrollably and go crazy. I can (mostly) fix the spinning problem by having dense bodies with angular damping, and I can increase buoyancy by artificially applying a force to negate (some of) the effects of gravity when a body touches a fluid particle, but it's all a bit hacky, and the numbers aren't easy to balance. If anyone has the time or inclination to take a look at my code and tell me what stupid thing I'm getting wrong, I'd be eternally grateful.
Wow, this is looking really good. Excellent work, ElectroDruid.

I've been lurking this thread for quite some time, and am pleased that it is progressing. I am also interested in adding fluids to my game.

Also, I think that it would be nice if the code was put onto something like gitweb, which would make it easier for people to fork the code and contribute any improvements back.

ElectroDruid wrote:
PLEA FOR HELP [...]

My initial thought when reading this is "why do particles have rotational inertia, anyway?" My (limited) understanding is that when representing shapes as particles only the position matters, and rotation of the shape happens when reforming the particles back into the original shape after stepping through the fluid simulation. Is particle rotation being used, or could it be disabled without adverse effects?

I'll look through the code and white paper and see what I can figure out.


In conclusion: excellent work, keep it up!

Original thread: https://box2d.org/forum/viewtopic.php?t=574