Fluid Simulation

I was leaning towards this approach anyway - Erin mentioned it early in the thread, and my own experiments in this area lead me to similar conclusions. To hear you talk about using sensors in this way just adds weight to it.

Quote:
1) With the JBox2d testbed's software renderer, it's way too expensive to draw all the sensors (like, 10 fps vs. 50 fps expensive)....


Much as I think the TestBed is a great way to show off a bunch of the capabilities of Box2D, I don't think how it renders should ever be a consideration as to whether to try something or not. The debug rendering is about the most naive way it's possible to use OpenGL, and whilst it makes for simple debugging code, any rendering engine worth its salt has more sophisticated optimisations. So yes, slow debug drawing of sensors is not a problem, in my opinion.

Quote:
2) Fluid-solid interactions need to be handled properly if the particles don't have solid cores.


This is a really interesting topic I want to look into in more detail later. Although the solid-core particles aren't "correct" in terms of modelling the interaction between fluids and solids, I haven't yet found a better way to do it. The SPH article in Game Programming Gems 6 states that between fluids and static objects, the static object should just exert a big enough force along its collision normal to push the particle back out (which I'm pretty sure is exactly what Box2D does anyway). For collision with dynamic rigid body objects it seems to advocate an approach based on what looks like Verlet integration - which is obviously never going to work with Box2D, since it users Euler. I currently have no better answer for this than to do exactly what your code is doing now.

Quote:
3) There are a lot of pairs, so the maxPairs setting needs to be set pretty high (not a problem at all).


I know you can make the numbers bigger to cope with the number of pairs, but I wonder if doing so is an unwarranted waste of CPU cycles and/or memory, if we don't care about pairs for fluid/fluid interactions. That's why I'm wondering if they can be turned off, but to my mind that's the only special change that should need to happen in the engine (and, arguably, the engine should work that way anyway).

Quote:
What you'd do is just make the sensors have half the size of the neighborhood that you're looking at. Storing some of the SPH fields on each particle might help, too, as the pressure calculation step could then proceed pair-by-pair instead of particle-by-particle (which doubles the number of operations, hitting each pair twice).


I suppose this is the argument for keeping the pairs in. Processing things pair-by-pair seems like an easy way to halve (or nearly halve) the processing time involved. Perhaps this is the solution, then? To accept the consequences of having to tune the maximum number of pairs to be very high, in order to then use those pairs to resolve SPH in a more efficient way? If that seems like a reasonable trade-off (as I say, I still don't know enough about the internals to know whether or not it is), then we've got the ability to do full, fast SPH without having to change a single line of Box2D.

I'd love to hear Erin's thoughts on this. As I say, I'm quite happy to try making adjustments to the engine if they're needed, but if it turns out that the best solution is to leave everything as it is, then that's great - I'll get right on it and see what the results are.
ElectroDruid wrote:
This is a really interesting topic I want to look into in more detail later. Although the solid-core particles aren't "correct" in terms of modelling the interaction between fluids and solids, I haven't yet found a better way to do it.

The main thing that you need in addition to preventing penetration (which hard-core particles will do) is to add to each particle's pressure term based on the presence of the solid body; I think the contribution due to this is pretty straightforward, and it should be explained in most SPH papers. It also may be preferable to keep particles a certain distance away from the "walls," as otherwise they seem to clump along edges.
I'm looking into adding sensors to each particle to let Box2D detect the particle radii for me, but I've run into a brick wall with the pairs. I had to set b2_maxProxies to 65536 (setting it to anything bigger than 65536 makes the program not run at all), so that b2_maxPairs goes up to 524288 to cope with all the pairs, and even then I can only run 500 or so particles, otherwise I just instantly get asserts about running over b2_maxPairs. I know that part of the problem is the dimensions of the box which the particles get created/recreated inside, but even expanding this (multiplying the width by 10, which is way too wide to look good inside the test geometry) creates problems before too long. Fluid starts to form, but at some point the number of overlapping sensors just gets too high.

Given that my aim is to do these optimisations to increase the number of particles it's possible to use in a fluid, not decrease, I think this pairs problem might turn out to be a killer for the sensors approach without a bit of a rethink. In what appears to be an increasing tendency for me to make numbered lists ( 😉 ), I think there are two things I need to make sure I completely understand. Assume that I don't want to change the fluid's behaviour in any way at this point, except to get it to run faster.

1 - rad is defined in the code as 0.6f, which is the radius I've given to my sensors. What exactly does this value represent? Is it the radius around a given particle in which to look for neighbours which will affect it (in which case that needs to be the radius for my sensors)? Or is it the preferred distance between any two particles (in which case I could make the sensor radius 0.3f, and just use the SPH to push particles apart until their sensors no longer overlap)? Setting the sensor radius to 0.3f seems to fix the problem (for 1000 particles at least), but I want to be sure I fully understand what size the sensors need to be, and why.

2 - If rad needs to be 0.6f (or if it needs to be 0.3f but it turns out that increasing the number of fluid particles just causes asserts again, in a way I can't rectify by adjusting the size of the "spawning box"), can anyone see a reason why I couldn't add an additional flag to a sensor shape to stop pairs being generated? I know I'd lose the ability to then iterate through pairs rather than particles for the SPH, but I think there are other ways around that.
ElectroDruid wrote:
I'm looking into adding sensors to each particle to let Box2D detect the particle radii for me, but I've run into a brick wall with the pairs. I had to set b2_maxProxies to 65536 (setting it to anything bigger than 65536 makes the program not run at all), so that b2_maxPairs goes up to 524288 to cope with all the pairs, and even then I can only run 500 or so particles, otherwise I just instantly get asserts about running over b2_maxPairs. I know that part of the problem is the dimensions of the box which the particles get created/recreated inside, but even expanding this (multiplying the width by 10, which is way too wide to look good inside the test geometry) creates problems before too long. Fluid starts to form, but at some point the number of overlapping sensors just gets too high.

Yup, I'm seeing the same thing when I try this in Java. I checked the actual fluid simulation stats, and it looks like for ~1000 particles, there are at least 20 or 30 thousand necessary pair calculations (i.e. ones that make it through the early exit tests and actually contribute to pressures) even once things settle down.

It's a lot of pairs (and contacts) to handle, indeed. More on this below...

Quote:
1 - rad is defined in the code as 0.6f, which is the radius I've given to my sensors. What exactly does this value represent? Is it the radius around a given particle in which to look for neighbours which will affect it (in which case that needs to be the radius for my sensors)? Or is it the preferred distance between any two particles (in which case I could make the sensor radius 0.3f, and just use the SPH to push particles apart until their sensors no longer overlap)? Setting the sensor radius to 0.3f seems to fix the problem (for 1000 particles at least), but I want to be sure I fully understand what size the sensors need to be, and why.

It's both the cutoff radius for the effect and the unadjusted preferred distance (see below) - if things are further apart, they are ignored altogether.

Which means that a sensor radius of half that value would be correct. However, it is not exactly the preferred distance between the particles, because a global pressure adjustment is applied (where the 'p' variable is turned into the 'pressure' one) before applying forces.

It would probably be a fairly simple matter to calculate the actual preferred distance, FWIW.

Quote:
2 - If rad needs to be 0.6f (or if it needs to be 0.3f but it turns out that increasing the number of fluid particles just causes asserts again, in a way I can't rectify by adjusting the size of the "spawning box"), can anyone see a reason why I couldn't add an additional flag to a sensor shape to stop pairs being generated? I know I'd lose the ability to then iterate through pairs rather than particles for the SPH, but I think there are other ways around that.

Currently you can't avoid generating pairs, but you can avoid creating contacts in response by using filtering. But if you were to do that, you'd need to be doing your own broadphase anyways, in which case you don't even need sensors at all, you can just use tiny solid bodies as collision proxies, just like the original Java demo. Which may end up as the best solution, to be fair.

Something I wanted to get back to: for every one of the pairs that's generated by a sensor overlap, we also get a contact, which has to pass through a whole bunch of internal computations. This is going to add some factors to the performance drain, and there may be callbacks registered that might make this even worse. Even just attaching sensors to the fluid particles and doing nothing with them, my framerate drops from ~45 fps to ~10, and a lot of this is due to the contacts (when I filter them out, it only goes down to 25 or 30, but notice that if we want to read overlaps, we cannot filter them away).

I'm wondering if maybe the best thing to do is stick with the separate grid broadphase and just try to get that running well, and put more of the focus on integrating with heightfield water so you don't need as many particles to fill volume. I still think a well optimized C++ version should outperform the Java one by quite a bit, especially if you can figure out some cache friendly optimizations. There will still be some broadphase duplication, but based on what I'm seeing, the Box2d pipeline may carry too much baggage along with the pairs in service of solving contacts to make it fast enough for our purposes here (which is to read off simple proximity queries as fast as humanly possible without worrying about generating actual contacts or performing overlap tests or anything of the sort, since we'll be recomputing a lot of that stuff when calculating pressures anyways).

There is still the other option, I think BorisTheBrave brought it up, which would be to create another b2BroadPhase and use that directly, just for the liquid (without hooking it into the engine at all, so it would just have the barest of pair handling features). That's definitely a reasonable approach, though I'm not sure how performance will be relative to a grid; particle heavy simulations with constant interaction scales are pretty good on grids since you can pick the grid size very easily, though there will always be cases where sweep-and-prune can do better (or worse). If you can't get the grid thing working right, keep that in mind, it should be relatively simple to hook it up, though I don't know that anyone else has done something like that yet. Erin's broadphase test in the testbed would probably be a good place to start looking at how to do that.

Sorry if I keep going back and forth on this, to be honest I'm not sure what the best approach is, it seems tough to find the right tradeoffs here.
Maybe it's because I still don't understand enough about what pairs are, what they're used for, and why they're generated, but I'm still not convinced that the best approach is a DIY broad-phase rather than finding a good way to turn off the pairs generation.

Look at it this way: There is no sensible way that we can (or should) tell Box2D not to process the particles at all. There's the immediate practical reason that there is just no way to do so within the engine (even shapes that are filtered against each other generate pairs), and there's also the "these things still need to exist even if we only partially process them" aspect - the particles obey gravity, are affected by external forces, collide with static and dynamic rigid body geometry. If we somehow could tell Box2D not to do all of this to the particles for us, and then try to handle the gravity, forces, and interactions with non-fluids ourselves, we might as well not be using Box2D at all, and we'll certainly generate overheads (and probably new types of glitches) by still trying to give the illusion that the fluids and the solids both exist in the same space and interact properly.

So, we could allow Box2D to process all of the particles in the way it's doing now, but also use the grid system (or a second broadphase). This is proven to work - we can see it running right now - but we're duplicating a lot of work. By my reckoning, my test in C++ currently spends about 35% of the frame solving stuff in the broadphase, and spends another 35% managing the grid. The figures are rough, but they give an idea. If we can tool up the Box2D broadphase to tell us which particles are in the neighbours range by adding sensors, sure we'll increase the workload that Box2D has to do processing overlapping sensors (of which the number of pairs seems to be the primary issue), but we should be able to get rid of the grid system at that point, so we gain all of that grid processing time back. The grid also has issues with scaling and tuning, i.e if you want to make levels bigger you need to redefine the grid cell sizes and bounds every time, which doesn't seem very friendly to the end user. We can certaintly write a more sophisticated version of the grid, perhaps some kind of quadtree, but the fact remains that we're still duplicating work that Box2D is already doing in terms of knowing how shapes are arranged in a space.

So I guess I'm still stuck on my original question: Why does Box2D generate pairs for sensors, and does it seem safe and reasonable to add a parameter to allow the user to "opt out" of having it generate pairs? My understanding is that a pair is generated in order to help to detect overlapping shapes and to push them apart, but if we don't want Box2D to actually push the shapes apart (because we're going to do that part, the SPH, ourselves) then maybe we don't need the pair? Or do pairs serve another purpose, something more fundamental to the engine that I'm misunderstanding? I'm looking for a clean way to stop fluid particle sensors creating pairs with each other, without disrupting the Box2D codebase too much, but it would help if I had a better handle on exactly what it is I'm trying to disable.


EDIT: A complete tangent, but this is not something I'd thought of before - Are AABB broadphase queries likely to be a speedy enough alternative to the grid system? Is there some reason you didn't use those in the Java version?

EDIT TO THE ABOVE EDIT: Just tried the broadphase queries, and the performance suffers quite badly compared to the grid method. Argh, back to the drawing board... Perhaps this whole post is a big pile of stinky pants, and this whole line of enquiry is a dead end after all. I've got a few more avenues to explore, and input is, as always, greatly appreciated, but I'm beginning to run out of ideas.
Sensors still do all the collision detection stuff. They need to, in order to pass events correctly. Hence they still generate pairs, and contacts etc.

AABB queries are pretty snappy, I bet. The problem is that they don't store anything from frame to frame, so the recalculate a lot, while the broadphase stuff carefully keeps track as it goes so it never needs recalculate anything.

To spell it out once again, a proxy is just a abstracted shape, and a pair is an abstracted contact, that is generated when two shape AABBs overlap [2]. Each has a few extra parameters to persist nicely in the broadphase. The exception is filtering: in that case a pair is still created, but no corresponding contact is.

My view is that this is great, and it would be good to use this system for particles, too. But it's a bit heavy. While it's unlikely for a shape to have more than 8 or so contacts (it's surrounded, then), this is the norm for particles, as they aren't so fussy about overlap. If we don't mind the memory and re-allocation requirements, we could use the broadphase [1]. What's more, the mores stuff in the broadphase, the slower it gets.

The array of vectors doesn't suffer from this. It's memory footprint is significantly smaller, and it doesn't track as much data, specifically the extra overhead of each extra particle is constant, while it's not for Box2Ds broadphase. But you need to get the neighbour list (aka contact list) from scratch each time, and it works best with things of homogenous size (the same size as the cells).

So that's why I felt the array of vectors is a better choice than the broadphase.
The difficulty comes that we need the particles to interact with Box2D.
So we have the following options, at least:

1) Use just the Box2D broadphase, as is. Particles are implemented as a shape type similar to circles, and generate contacts.
2) Use just the Box2D broadphase and the array of vectors, and enter particles in both. Particles can at least be represented as solid cores in the broadphase, then, meaning not too many pairs, without hurting the ability to calculate neighbours.
3) Use just the array of vectors, and determine collisions using QueryAABB. We would not easily be able to use the solver in this case for particle-body interations. Having not actually looked into how the java code deals with this, I cannot say how bad that is.
4) Use the array of vectors, and "second class citizens" of the Box2D broadphase. By this, I mean we do not insert particles into the broadphase, but we do track some persistence data on where they *would* go. So this is essentially (3), only hacking in some extra stuff into the broadphase to allow persistent QueryAABBs. I'm not even sure how plausible that is.
5) Insert the particles into the broadphase as fully filtered. You can still access pairs data this way, while no contacts are generated. Essentially, the particles would be like AABBs where you cannot loop over the neighbours in any particular order. Fortunately, you don't need to for your application. Unfortunately, looping over pairs means looping over all pairs in the world, not just fluid ones. Unless there are further hacks to the broadphase.

Hm, ok, that's actually quite a lot of options. I was just spinning out ideas there, I really cannot say whether they either make sense. Performance is such a tricky beast. Perhaps it's best to get (1) or/or (3), the easiest, up and running before doing anything else.

[1]: There's nothing stopping you increasing it beyond 65k pairs, you just need change some types from shorts to ints, and a bitmask somewhere.
[2]: No exceptions. Not for sensors, not for filtering.
I *think* I understood all of that, Boris, and it sounds like you're considerably wiser in these matters than me 🙄

I'm getting some understanding about why Box2D was built the way it was, and that (short of Erin going "Okay! I'm going to add a multipurpose particle physics system to the engine!", which sounds almost like bolting an entirely new engine onto the side of the current one) it's going to stay that way, optimised for rigid bodies, not so good at particles. Having tried some stuff, I'm flip-flopping back to the idea that the grid (or some similarly-designed data structure) is the only way that this is going to work with any acceptable degree of efficiency.

So, if I've understood your options correctly, I've already tried and ruled out a bunch of them:

Quote:
1) Use just the Box2D broadphase, as is....

This is my no-grid approach using sensors, I think. Too many pairs to be viable, and from what you've said, just making the numbers bigger isn't going to fix the problem, because the approach is flawed. Box2D is not built for this.

Quote:
2) Use just the Box2D broadphase and the array of vectors, and enter particles in both.

This sounds like it describes ewjordan's approach, which is my baseline frame of reference as well. I'm still not happy about the idea of duplicating the work, but it stands head and shoulders above anything else I've tried. There are still some possibilities in this field I haven't tried - I have an idea for a custom-built hand-crafted linked-list approach which might just be the answer, although it'll be a headache to write.

Quote:
3) Use just the array of vectors, and determine collisions using QueryAABB.

This is interesting. I take it that what you mean from this is that the particles never get entered into the Box2D world as shapes at all, but just query the shapes that are in the world, and change their own behaviour (and/or those of the shapes they're interacting with) when collisions or overlaps occur? I honestly wouldn't like to guess at what this would do for performance, but the implications are intriguing. Whilst I think the solver is doing the right thing for the interactions between fluids and solid geometry, it's likely that a custom approach is needed for dynamic bodies, so although this would be tough to program it might be the only way to get the "correct" interactions. Plus, imagine that small, fast, empty Box2D broadphase...

Quote:
4) Use the array of vectors, and "second class citizens" of the Box2D broadphase.

Sounds like 3 but with more "juice". Something worth considering if 3 turns out to be a huge success and we want to see how far we can really push things, but I wouldn't dive into this straight away.

Quote:
5) Insert the particles into the broadphase as fully filtered.

"Fully filtered" as in "filtered to not even generate contacts with the non-fluid particles"? At first glance I could see no advantage to this approach whatsoever, because it combines the annoyance of having to have all of the particles exist in the broadphase with the annoyance of having to handle fluid vs nonfluid interactions yourself, as in 3) and 4). But it's possible that it would be quicker to iterate through and process all of the pairs to find the fluid vs. nonfluid interactions than it would be to QueryAABB each particle just to see if such an interaction needs to be handled (and ignore the fluid vs. fluid pairs, because the grid will handle those anyway).

Just when I thought I was out of options, you've given me a LOT of food for thought, and things to try. There's hope yet! Thank you, Boris! 😀
Yes, looks like you've got my rambling. But (1) still isn't out of the question. Box2D may not be built with particles in mind, but is was built on solid foundations, and with generality in mind. Though I've argued that it's broadphase is not the best for dealing with particles alone, I am not convinced that it's worse than the other options for mixing particles and bodies.

Also: Would I be right in saying that interactions between dynamic bodies and particles also depends on the particles pressure, and therefore wouldn't be good to solve in Box2Ds solver stage.
BorisTheBrave wrote:
Yes, looks like you've got my rambling. But (1) still isn't out of the question. Box2D may not be built with particles in mind, but is was built on solid foundations, and with generality in mind. Though I've argued that it's broadphase is not the best for dealing with particles alone, I am not convinced that it's worse than the other options for mixing particles and bodies.

I played around a bit yesterday, and it's looking to me like the real slowdown might be the contact generation, not the broadphase itself, which is pretty fast - in fact the overhead of the broadphase is almost entirely there in my earlier demo, as although the AABBs are smaller (they just cover the particle cores - hit 'b' and the demo will show them), it's the edge swaps that tend to dominate broadphase processing time, and those all happen anyways.

Just to be clear, ElectroDruid - I think the real problem is not the pairs, exactly, but what happens by default when a pair is generated. The engine does a lot in response to a pair being reported (generating contacts, which also need to be collision-checked, etc.), usually because it's necessary to have this info for solids. We're talking about a special case, though, where we're never going to need detailed contact or overlap information, so it's extraneous. But we actually need the pairs, since those are what tell us that overlaps have occurred, so it's more a matter of making sure that the path from broadphase->pair->fluid solver is extremely tight than trying to reduce the actual number of pairs created.

Today if I have a chance I'm going to see if I can flag fluid shapes and filter out fluid-fluid collisions very early in the detection process while storing pair info away for the real fluid solve (this would avoid both contact generation and the need to directly query the broadphase to get overlaps, which while fast, is going to be slower than leaving the bodies in it - the broadphase is optimized for the fact that things tend to stay the same over time).
Quote:
Also: Would I be right in saying that interactions between dynamic bodies and particles also depends on the particles pressure, and therefore wouldn't be good to solve in Box2Ds solver stage.

Yup. This is also why I think it would be good to have the things actually in the engine - assuming a fluid particle has both a neighborhood radius and a solid core, my previous demo just resolved solid interactions by colliding the core, since I was handling the neighborhood radius external to the engine. But we really should use that neighborhood circle to deal with interactions between fluid and solid, which means it should have a legitimate Box2d representation. Fluid-solid overlaps should generate contacts, though I'm not entirely sure yet whether those contacts should participate in warm starting or the other Box2d goodness; for a first step, I'd say leave it out, because adding new contact types and changing the type of solving that happens is going to be a pretty invasive change requiring a lot of debugging.

I'll post an update later today if I figure anything out.
ewjordan wrote:
I played around a bit yesterday, and it's looking to me like the real slowdown might be the contact generation.

Can you clarify here? Do you mean a lot of time was spent allocating contacts and inserting into contact lists, or do you mean a lot of time was spent in b2Contact::Evaluate, events etc. As the latter is avoidable merely by creating a new shape type for particles, and providing do-nothing contacts for each possible shape-particle pairing.
Though it sounds like working with pairs themselves is more effective solution, if less elegant.

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