Newbie Questions by any other name...

I hope that this is the right venue for these sorts of questions. I've been pretty impressed with the courtesy I've seen in this forum, and I hope it extends to what are almost surely stupid questions on my part.

I am currently flirting with the development of a game whose central mechanic is both two-dimensional and physics-based, which is what led me to Jbox2D, but now I'm concerned that I'm far out of my depth. Although the documentation of the library is fantastic, the absolute lack of tutorials or simple user guides (unfortunately my illiteracy in C++ rules out the otherwise wonderful Box2D User Manual) leaves me at your mercy, Box2D forums! Of course, if there is a better place for me to be asking for this kind of help, let me know, and I'll be on my way.

The game I am trying to design is fairly simple, as a concept. The game environment consists of a two-dimensional field of play which is populated by, in its most basic form, a goal zone and a charged particle. The object of the game is to force the charged particle into the goal zone. The player is limited in his/her interaction with the particle, in that he/she can only place other charged particles, which push and pull the target particle through the electric force. There is no gravity, and in its most basic form there aren't even obstacles other than rectangular walls which the particles can bounce off of. Naturally the particles can also bounce off of one another, too.

Again, this is only the most basic form of the game, and many other objects and features are planned, but I want to have a robust, expandable version of the game working with only the simplest elements before I start getting crazy with features. From the features that I've already mentioned, it becomes clear that I need a 2D rigid-physics engine with capable collision detection, and after searching around, Box2D comes as the most lauded, but there are some things giving me quite a bit of conceptual trouble.

Box2D, like most other 2D physics engines I've encountered, seems to be based around gravity as a force, which is unfortunately of little use to me. What I need to be able to simulate is the interaction between point charges that move freely in a two-dimensional space. Over a weekend of fevered python-scripting I hacked out the particulars of the force interactions in a step-based simulator (and the port of this code into Java has gone smoothly), but I'm having trouble building classes and methods that fit into the JBox2D framework. I don't want to waste this forum's time with beginner's questions, but I'm having a great deal of trouble understanding how the World class interacts with its contained Body objects during the step. That is, I'm having trouble determining how the World updates its elements, and how I might be able to inject my implementation of electric force interaction into that update-cycle.

So, for the tl;dr crowd, here are my questions in short:

1. Does JBox2D support forces other than gravity, such as electromagnetism; if not, does it provide a framework for defining custom forces, possibly with moving source-points, that allows them to be smoothly integrated into the simulation?

2. Is there a relatively simple explanation of the process the World class goes through when stepping through the simulation? If not, that's fine. I'm sure I'll figure it out eventually.

3. Are there any resources/tutorials for JBox2D other than the javadoc/source code and the Box2D user manual? I suspect the answer is no, as I've searched fairly extensively for such a thing, but in case I overlooked something it would be good to know. If not, I'll just get back to reading/drowning in the source code.

Anyway, thanks for enduring my beginner's questions. Just so you know, I'm also more or less a beginner as a programmer in general, too (I'm only in my second semester as a Computer Science bachelor at Uni), and so if this is the wrong place to be looking for help, please let me know. Any help is appreciated!

Peter
Hi, I can only answer your first question: JBox2D doesn't support force fields, which I think is the thing you are after, but it implements a general body.applyForce which can be used to create one. The implementation, though, is up to you.

I would also like a precise answer to the second and third question you asked...
Basic answer, but for #3 I assume you have looked at the testbed tests that come with the source. They show how to implement most of the basic things.

For the forces, I had a simple class called from the poststep in one of my games to apply a "magnetic" force (attract or repulse). It is takes in a list of targets and applies a force upon them based on their distance from the source fixture.

Code:
   /**
     * Class used to apply "magnetic" forces.
     */
    static class MagneticSteppable implements Steppable {
       /** Listing of the bodies to apply the effect to. */
      private HashMap<Body, Integer> targets;
       /** Shape indicating the area of effect. Must be a Circle or Polygon and usually a sensor. */
       private Fixture fixture;
      /** Maximum distance the body could be from the origin and still have the effect applied. */
      private float maxDist;
      /** Maximum effect that could be applied (if distance is 0). */
      private float magnitude;
      /** Whether to attract the bodies to the origin or repel them from it. */
       private boolean attract;

       public MagneticSteppable(final Fixture fixtureToMagnetize, final float maxDist,
             final HashMap<Body, Integer> curntContacts, final float magnitude, final boolean attract) {
          this.fixture = fixtureToMagnetize;
          this.maxDist = maxDist * maxDist; // Square it so we can avoid the squareroot when calc distances.
          this.targets = curntContacts;
          this.magnitude = magnitude;
          this.attract = attract;
       }

       /** Apply the effect to any of the relevant bodies.*/
       @Override
      public void step(final float dt) {
          Set<Body> contacts = targets.keySet();
          if (contacts.isEmpty()) return;

          // Get the current center of the shape and use as our origin.
          Vec2 origin;
          Shape shape = fixture.getShape();
          if (shape.getType() == ShapeType.CIRCLE) {
             final CircleShape circle = (CircleShape) shape;
//             origin = XForm.mul(fixture.getBody().getXForm(), circle.getMemberLocalPosition());
             origin = new Vec2();
             Transform transform = fixture.getBody().getTransform();
             Mat22.mulToOut(transform.R, circle.m_p, origin);
             origin.addLocal(transform.position);
          } else if (shape.getType() == ShapeType.POLYGON) {
             final PolygonShape poly = (PolygonShape) shape;
//             origin = poly.centroid(fixture.getBody().getXForm());
             origin = poly.centroid(fixture.getBody().getTransform());
          } else {
             // Not a supported shape. Probably a PointShape or EdgeShape.
             return;
          }

          // Loop through all bodies in contact with the field and apply force.
         Vec2 distVec;
          for (Body target : contacts) {
             if (attract) {
                distVec = origin.sub(target.getWorldCenter()); // attract (toward origin)
             } else {
                distVec = target.getWorldCenter().sub(origin); // repel (away from origin)
             }
             // Force equal to magnitude is applied when the center of the body is at maxdist. If is it
             // closer to the center then the force is higher (clamped to prevent infinity), further is
             // less (approaching 0 at maxDist).
            float amt = (magnitude / MathHelper.clampMin(distVec.lengthSquared() / maxDist, 0.01f)) * dt;
               if (amt > 0f) {
                   distVec.normalize();
                   // mulLocal since we are done with this Vec (created each time via sub call).
                  target.applyForce(distVec.mulLocal(amt), target.getWorldCenter());
               }
          }
      }
    }
I was going back through the codebase myself for the first time in a while and saw question #2, so I decided to write it up, as it helps me understand the process if I do. With lots of gory detail. I am certainly no authority, so correct me where I'm wrong.

PREPARE THE CONTACTS:

A. [b2ContactManager::FindNewContacts] The contact manager checks for new contacts.
1. It queries all the neighbors of any fixture that was added or moved since the last check.
2. For every pair of fixtures from the query, it creates a new contact unless both fixtures are in the same body, a contact between them already exists, neither body is dynamic, a joint between the contacts' bodies is marked for non-collision, or b2ContactFilter::ShouldCollide returns false.

B. [b2ContactManager::Collide] The contact manager goes through every contact, old and new, checking for new collisions.
1, If both bodies are asleep, or the awake one is static, the contact is skipped, but still persists.
2. If the body is marked for refiltering, it tests whether neither body is dynamic, a joint between the contacts' bodies is marked for non-collision, or b2ContactFilter::ShouldCollide returns false. If so, it destroys the contact. b2ContactListener::EndContact can be called if the fixtures were previously touching.
3. The fixtures' AABBs are again checked, and if the contacts don't overlap, the contact is destroyed. b2ContactListener::EndContact can be called if the fixtures were previously touching.

C. [b2Contact::Update] Each contact that makes it through that phase is updated.
1. The contact is re-enabled from any previous disabling.
2. Contacts involving a sensor (or two) are special-cased to just test for overlap. If so, they are counted as touching.
3. Non-sensor contacts are evaluated based upon the type of the two shapes. This creates manifolds. There's a good description of manifolds in section 4.8 of the manual. If there are any manifolds, that means the shapes are touching.
4. After the update, if the contacts just started touching, b2ContactListener::BeginContact is called, or if the contacts just stopped touching, b2ContactListener::EndContact is called.
5. If they are now touching, b2ContactListener::PreSolve is called. This is where you can disable the contact.

SOLVE THE WORLD:

D. [b2World::Solve] The world is broken up into groups of interacting bodies called islands.
1. A root body is found. This will be a dynamic body that is not asleep nor inactive, and not part of a previous island.
2. Every body connected to the root body by a contact or a joint will be added. It won't add bodies that are in a previous island or are connected indirectly through a static body. Bodies across contacts won't be added if: they aren't touching, the contact was disabled in the pre-solve event or the body is a sensor. Bodies across joints won't be added if the body is inactive.
3. All bodies in the island are woken up.

E. [b2Island::Solve] The island is solved.
1. Black magic. Honestly, I don't want to figure out what goes on here. Basically, a lot of integration and such is done and bam, new positions and velocities for all the bodies.
2. For each contact in the island, it figures out the b2ContactImpulse and calls b2ContactListener::PostSolve.
3. Stuff that should be is put to sleep.

F. [b2World::Solve] After all the islands are processed, some cleanup is done on the world.
1. All of the fixtures are actually moved in the broadphase.
2. The contact manager checks for new contacts (repeat step A).

SOLVE TIME OF IMPACT:

G. [b2World::SolveTOI] Time of impact is solved iteratively.
1. The two fixtures that come into contact first during the entire step are found. (This is called a time of impact event). The only contacts allowed are those that are enabled, don't involve sensors, have a body that's both awake and not static, and have one body that isn't dynamic or is a bullet.
2. This contact is allowed to be used for more than one time of impact event, since the fixtures involved will move.
3. An island is made out of bodies just connected by contacts. Bodies that are sensors or are non-bullet dynamic bodies are not added.
4. As each new body is added, it is swept back to the point of contact, and the contact is updated (repeating step C and calling events). If there's no contact at that point or the contact was disabled in the b2ContactListener::PreSolve event, it's not added and reverted back to its original position.

H. [b2Island::SolveTOI] Time of impact is solved for the island.
1. Deep black magic.
2. Like before (E.2), it calls all the b2ContactListener::PostSolve events.

I. [b2World::SolveTOI] The time of impact is cleaned up for this iteration.
1. Fixtures are actually moved.
2. The contact manager checks for new contacts (repeat step A).
3. There's a comment here that says it's supposed to be able to destroy contacts, calling b2ContactListener::EndContact. Could be it's supposed to do the same at the end of the normal solve (F.2). It never does. If you want to be sure that your contacts are all really valid, you could hack access to the contact manager and call b2ContactManager::Collide, or put it as the last line of the b2World::Step function. That is probably far too expensive to be worth it. I think this came up during the discussion of callback design and Erin didn't do it for this reason.


Substepping: If you set the substepping flag, the first call will solve the world (D-F) and run one TOI iteration (G-I). Until the whole step's TOI iterations are complete, further calls will only run a single TOI iteration (G-I). There's also a weird thing with time. I don't really understand substepping.

A note on callbacks (most of this info is in the docs). As far as I can tell:

As long as there's a listener, BeginContact will always have a later matching EndContact, and that EndContact can occur outside of the step only when you destroy the contact, which will always be implicit, occuring when you destroy one of the fixtures, one of their bodies or disable one of their bodies. (Could also happen if you call b2ContactManager::Collide outside the step like I mentioned.) This means that you can keep a reference to a contact between BeginContact and EndContact.

PreSolve and PostSolve only occur inbetween BeginContact and EndContact. PreSolve will always come before PostSolve, but PostSolve, while it usually will, won't always occur. One significant case is that it does not occur if you disable the contact in the PreSolve event.

With TOI enabled, every single one of the callbacks can be called multiple times per fixture pair in a single step. Even if the fixtures are the same, they could be called with a different contact.
Hangar, you deserve a medal! Great explanation!
I took a look again and noticed that there were a few things that I just got completely wrong, like the fact that the broadphase doesn't look through every single pair each frame, it only looks at fixtures that moved. There were also a couple details that changed, but they seem rather minor.
Yeah, you were basically right though

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