Class World

java.lang.Object
org.jbox2d.dynamics.World

public class World extends Object
The world-class manages all physics entities, dynamic simulation, and asynchronous queries. The world also contains efficient memory management facilities.
Author:
Daniel Murphy
Repolink:
Github: erincatto/box2d include/box2d/b2_world.h Lines 43 - 346
  • Field Details

    • WORLD_POOL_SIZE

      public static final int WORLD_POOL_SIZE
      See Also:
    • WORLD_POOL_CONTAINER_SIZE

      public static final int WORLD_POOL_CONTAINER_SIZE
      See Also:
    • NEW_FIXTURE

      public static final int NEW_FIXTURE
      See Also:
    • LOCKED

      public static final int LOCKED
      See Also:
    • CLEAR_FORCES

      public static final int CLEAR_FORCES
      See Also:
    • activeContacts

      public int activeContacts
    • contactPoolCount

      public int contactPoolCount
    • flags

      protected int flags
    • contactManager

      protected ContactManager contactManager
  • Constructor Details

    • World

      public World(Vec2 gravity)
      Construct a world object.
      Parameters:
      gravity - The world gravity vector.
      Repolink:
      Github: erincatto/box2d include/box2d/b2_world.h Lines 49 - 51
    • World

      public World(Vec2 gravity, WorldPool pool)
      Construct a world object.
      Parameters:
      gravity - The world gravity vector.
      pool - The world pool that provides pooling for all objects used in the engine.
    • World

      public World(Vec2 gravity, WorldPool pool, BroadPhaseStrategy strategy)
      Construct a world object.
      Parameters:
      gravity - The world gravity vector.
      pool - The world pool that provides pooling for all objects used in the engine.
      strategy - The broad phase strategy.
    • World

      public World(Vec2 gravity, WorldPool pool, BroadPhase broadPhase)
      Construct a world object.
      Parameters:
      gravity - The world gravity vector.
  • Method Details

    • setAllowSleep

      public void setAllowSleep(boolean flag)
    • setSubStepping

      public void setSubStepping(boolean subStepping)
    • isSubStepping

      public boolean isSubStepping()
    • isAllowSleep

      public boolean isAllowSleep()
    • getDestructionListener

      public DestructionListener getDestructionListener()
    • getParticleDestructionListener

      public ParticleDestructionListener getParticleDestructionListener()
    • setParticleDestructionListener

      public void setParticleDestructionListener(ParticleDestructionListener listener)
    • popContact

      public Contact popContact(Fixture fixtureA, int indexA, Fixture fixtureB, int indexB)
    • pushContact

      public void pushContact(Contact contact)
    • getPool

      public WorldPool getPool()
    • setDestructionListener

      public void setDestructionListener(DestructionListener listener)
      Register a destruction listener. The listener is owned by you and must remain in scope.
    • setContactFilter

      public void setContactFilter(ContactFilter filter)
      Register a contact filter to provide specific control over collision. Otherwise, the default filter is used (_defaultFilter). The listener is owned by you and must remain in scope.
    • setContactListener

      public void setContactListener(ContactListener listener)
      Register a contact event listener. The listener is owned by you and must remain in scope.
    • setDebugDraw

      public void setDebugDraw(DebugDraw debugDraw)
      Register a routine for debug drawing. The debug draw functions are called inside with World.DrawDebugData method. The debug draw object is owned by you and must remain in scope.
    • createBody

      public Body createBody(BodyDef def)
      create a rigid body given a definition. No reference to the definition is retained.
      Warning:
      This function is locked during callbacks.
    • destroyBody

      public void destroyBody(Body body)
      Destroy a rigid body given a definition. No reference to the definition is retained. This function is locked during callbacks.
      Warning:
      This automatically deletes all associated shapes and joints., This function is locked during callbacks.
    • createJoint

      public Joint createJoint(JointDef def)
      create a joint to constrain bodies together. No reference to the definition is retained. This may cause the connected bodies to cease colliding.
      Warning:
      This function is locked during callbacks.
    • destroyJoint

      public void destroyJoint(Joint j)
      destroy a joint. This may cause the connected bodies to begin colliding.
      Warning:
      This function is locked during callbacks.
    • step

      public void step(float timeStep, int velocityIterations, int positionIterations)
      Take a time step. This performs collision detection, integration, and constraint solution.

      Box2D uses a computational algorithm called an integrator. Integrators simulate the physics equations at discrete points of time. This goes along with the traditional game loop where we essentially have a flip book of movement on the screen. So we need to pick a time step for Box2D. Generally physics engines for games like a time step at least as fast as 60Hz or 1/60 seconds. You can get away with larger time steps, but you will have to be more careful about setting up the definitions for your world. We also don't like the time step to change much. A variable time step produces variable results, which makes it difficult to debug.

      In addition to the integrator, Box2D also uses a larger bit of code called a constraint solver. The constraint solver solves all the constraints in the simulation, one at a time. A single constraint can be solved perfectly. However, when we solve one constraint, we slightly disrupt other constraints. To get a good solution, we need to iterate over all constraints a number of times.

      There are two phases in the constraint solver: a velocity phase and a position phase. In the velocity phase the solver computes the impulses necessary for the bodies to move correctly. In the position phase the solver adjusts the positions of the bodies to reduce overlap and joint detachment. Each phase has its own iteration count. In addition, the position phase may exit iterations early if the errors are small.

      The suggested iteration count for Box2D is 8 for velocity and 3 for position. You can tune this number to your liking, just keep in mind that this has a trade-off between performance and accuracy. Using fewer iterations increases performance but accuracy suffers. Likewise, using more iterations decreases performance but improves the quality of your simulation.

      Note that the time step and the iteration count are completely unrelated. An iteration is not a sub-step. One solver iteration is a single pass over all the constraints within a time step. You can have multiple passes over the constraints within a single time step.

      Source: Box2D 2.4.1 Hello Box2D

      To make a realistic looking simulation, you will generally set the timeStep value to match the number of times per second you will be calling the world's Step() function in your game.

      The velocity iterations and position iterations settings affect the way bodies will react when they collide. Typically in Box2D when a collision between two objects is detected, those objects are overlapping (stuck into other) and some calculation needs to be done to figure out how each body should move or rotate so that they are not overlapping any more. Making these values higher will give you a more correct simulation, at the cost of some performance.

      Firstly, these values are only relevant to collision resolution, so if nothing is colliding then they are not used at all. When two things collide, to resolve the collision (push both bodies so they don't overlap any more) they need to have their position and velocity changed. The need for changing the position should be obvious - this is to correct the overlap. The velocity also needs to be changed, for example to make sure that a ball bounces off a wall correctly, or to make something rotate if it is hit off-center.

      The exact details of which body should move where, what their new velocities should be, whether their angular velocity should also be affected etc, is handled by an iterative solver. This means that the calculation does not give you a perfect result the first time, but each time you do it the result gets more accurate.

      Source: iforce2d Box2D C++ tutorials - World settings

      Parameters:
      timeStep - The amount of time to simulate, this should not vary.
      velocityIterations - The number of iterations in the velocity phase of the constraint solver.
      positionIterations - The number of iterations in the position phase of the constraint solver.
      Repolink:
      Github: erincatto/box2d include/box2d/b2_world.h Lines 94 - 101
    • clearForces

      public void clearForces()
      Call this after you are done with time steps to clear the forces. You normally call this after each call to Step, unless you are performing sub-steps. By default, forces will be automatically cleared, so you don't need to call this function.
      See Also:
      Repolink:
      Github: erincatto/box2d include/box2d/b2_world.h Lines 103 - 110
    • drawDebugData

      public void drawDebugData()
      Call this to draw shapes and other debug draw data.
      Repolink:
      Github: erincatto/box2d include/box2d/b2_world.h Lines 112 - 113
    • queryAABB

      public void queryAABB(QueryCallback callback, AABB aabb)
      Query the world for all fixtures that potentially overlap the provided AABB.
      Parameters:
      callback - A user implemented callback class.
      aabb - The query box. The axis-aligned bounding box.
    • queryAABB

      public void queryAABB(QueryCallback callback, ParticleQueryCallback particleCallback, AABB aabb)
      Query the world for all fixtures and particles that potentially overlap the provided AABB.
      Parameters:
      callback - A user implemented callback class.
      particleCallback - A callback for particles.
      aabb - The query box. The axis-aligned bounding box.
    • queryAABB

      public void queryAABB(ParticleQueryCallback particleCallback, AABB aabb)
      Query the world for all particles that potentially overlap the provided AABB.
      Parameters:
      particleCallback - The callback for particles.
      aabb - The query box. The axis-aligned bounding box.
    • raycast

      public void raycast(RayCastCallback callback, Vec2 point1, Vec2 point2)
      Ray-cast the world for all fixtures in the path of the ray. Your callback controls whether you get the closest point, any point, or n-points. The ray-cast ignores shapes that contain the starting point.
      Parameters:
      callback - A user implemented callback class.
      point1 - The ray starting point.
      point2 - The ray ending point.
    • raycast

      public void raycast(RayCastCallback callback, ParticleRaycastCallback particleCallback, Vec2 point1, Vec2 point2)
      Ray-cast the world for all fixtures and particles in the path of the ray. Your callback controls whether you get the closest point, any point, or n-points. The ray-cast ignores shapes that contain the starting point.
      Parameters:
      callback - A user implemented callback class.
      particleCallback - The particle callback class.
      point1 - The ray starting point
      point2 - The ray ending point
    • raycast

      public void raycast(ParticleRaycastCallback particleCallback, Vec2 point1, Vec2 point2)
      Ray-cast the world for all particles in the path of the ray. Your callback controls whether you get the closest point, any point, or n-points.
      Parameters:
      particleCallback - The particle callback class.
      point1 - The ray starting point
      point2 - The ray ending point
    • getBodyList

      public Body getBodyList()
      Get the world body list. With the returned body, use Body.getNext to get the next body in the world list. A null body indicates the end of the list.
      Returns:
      The head of the world body list.
    • getJointList

      public Joint getJointList()
      Get the world joint list. With the returned joint, use Joint.getNext to get the next joint in the world list. A null joint indicates the end of the list.
      Returns:
      The head of the world joint list.
    • getContactList

      public Contact getContactList()
      Get the world contact list. With the returned contact, use Contact.getNext to get the next contact in the world list. A null contact indicates the end of the list.
      Returns:
      The head of the world contact list.
      Warning:
      contacts are created and destroyed in the middle of a time step. Use ContactListener to avoid missing contacts.
    • isSleepingAllowed

      public boolean isSleepingAllowed()
    • setSleepingAllowed

      public void setSleepingAllowed(boolean sleepingAllowed)
    • setWarmStarting

      public void setWarmStarting(boolean flag)
      Enable/disable warm starting. For testing.
    • isWarmStarting

      public boolean isWarmStarting()
    • setContinuousPhysics

      public void setContinuousPhysics(boolean flag)
      Enable/disable continuous physics. For testing.
    • isContinuousPhysics

      public boolean isContinuousPhysics()
    • getProxyCount

      public int getProxyCount()
      Get the number of broad-phase proxies.
    • getBodyCount

      public int getBodyCount()
      Get the number of bodies.
    • getJointCount

      public int getJointCount()
      Get the number of joints.
    • getContactCount

      public int getContactCount()
      Get the number of contacts (each may have 0 or more contact points).
    • getTreeHeight

      public int getTreeHeight()
      Get the height of the dynamic tree.
    • getTreeBalance

      public int getTreeBalance()
      Get the balance of the dynamic tree.
    • getTreeQuality

      public float getTreeQuality()
      Get the quality of the dynamic tree.
    • setGravity

      public void setGravity(Vec2 gravity)
      Change the global gravity vector.
    • getGravity

      public Vec2 getGravity()
      Get the global gravity vector.
    • isLocked

      public boolean isLocked()
      Is the world locked (in the middle of a time step).
    • setAutoClearForces

      public void setAutoClearForces(boolean flag)
      Set flag to control automatic clearing of forces after each time step.
    • getAutoClearForces

      public boolean getAutoClearForces()
      Get the flag that controls automatic clearing of forces after each time step.
    • getContactManager

      public ContactManager getContactManager()
      Get the contact manager for testing purposes
    • getProfile

      public Profile getProfile()
    • createParticle

      public int createParticle(ParticleDef def)
      Create a particle whose properties have been defined. No reference to the definition is retained. A simulation step must occur before it's possible to interact with a newly created particle. For example, DestroyParticleInShape() will not destroy a particle until Step() has been called.
      Returns:
      The index of the particle.
      Warning:
      This function is locked during callbacks.
    • destroyParticle

      public void destroyParticle(int index)
      Destroy a particle. The particle is removed after the next step.
    • destroyParticle

      public void destroyParticle(int index, boolean callDestructionListener)
      Destroy a particle. The particle is removed after the next step.
      Parameters:
      index - Index of the particle to destroy.
      callDestructionListener - Whether to call the destruction listener just before the particle is destroyed.
    • destroyParticlesInShape

      public int destroyParticlesInShape(Shape shape, Transform xf)
      Destroy particles inside a shape without enabling the destruction callback for destroyed particles. This function is locked during callbacks. For more information see DestroyParticleInShape(Shape&, Transform&,bool).
      Parameters:
      shape - Shape which encloses particles that should be destroyed.
      xf - Transform applied to the shape.
      Returns:
      Number of particles destroyed.
      Warning:
      This function is locked during callbacks.
    • destroyParticlesInShape

      public int destroyParticlesInShape(Shape shape, Transform xf, boolean callDestructionListener)
      Destroy particles inside a shape. This function is locked during callbacks. In addition, this function immediately destroys particles in the shape in contrast to DestroyParticle() which defers the destruction until the next simulation step.
      Parameters:
      shape - Shape which encloses particles that should be destroyed.
      xf - Transform applied to the shape.
      callDestructionListener - Whether to call the world b2DestructionListener for each particle destroyed.
      Returns:
      Number of particles destroyed.
      Warning:
      This function is locked during callbacks.
    • createParticleGroup

      public ParticleGroup createParticleGroup(ParticleGroupDef def)
      Create a particle group whose properties have been defined. No reference to the definition is retained.
      Warning:
      This function is locked during callbacks.
    • joinParticleGroups

      public void joinParticleGroups(ParticleGroup groupA, ParticleGroup groupB)
      Join two particle groups.
      Parameters:
      groupA - The first group. Expands to encompass the second group.
      groupB - The second group. It is destroyed.
      Warning:
      This function is locked during callbacks.
    • destroyParticlesInGroup

      public void destroyParticlesInGroup(ParticleGroup group, boolean callDestructionListener)
      Destroy particles in a group. This function is locked during callbacks.
      Parameters:
      group - The particle group to destroy.
      callDestructionListener - Whether to call the world b2DestructionListener for each particle is destroyed.
      Warning:
      This function is locked during callbacks.
    • destroyParticlesInGroup

      public void destroyParticlesInGroup(ParticleGroup group)
      Destroy particles in a group without enabling the destruction callback for destroyed particles. This function is locked during callbacks.
      Parameters:
      group - The particle group to destroy.
      Warning:
      This function is locked during callbacks.
    • getParticleGroupList

      public ParticleGroup[] getParticleGroupList()
      Get the world particle group list. With the returned group, use ParticleGroup::GetNext to get the next group in the world list. A NULL group indicates the end of the list.
      Returns:
      The head of the world particle group list.
    • getParticleGroupCount

      public int getParticleGroupCount()
      Get the number of particle groups.
    • getParticleCount

      public int getParticleCount()
      Get the number of particles.
    • getParticleMaxCount

      public int getParticleMaxCount()
      Get the maximum number of particles.
    • setParticleMaxCount

      public void setParticleMaxCount(int count)
      Set the maximum number of particles.
    • setParticleDensity

      public void setParticleDensity(float density)
      Change the particle density.
    • getParticleDensity

      public float getParticleDensity()
      Get the particle density.
    • setParticleGravityScale

      public void setParticleGravityScale(float gravityScale)
      Change the particle gravity scale. Adjusts the effect of the global gravity vector on particles. Default value is 1.0f.
    • getParticleGravityScale

      public float getParticleGravityScale()
      Get the particle gravity scale.
    • setParticleDamping

      public void setParticleDamping(float damping)
      Damping is used to reduce the velocity of particles. The damping parameter can be larger than 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is large.
    • getParticleDamping

      public float getParticleDamping()
      Get damping for particles
    • setParticleRadius

      public void setParticleRadius(float radius)
      Change the particle radius. You should set this only once, on world start. If you change the radius during execution, existing particles may explode, shrink, or behave unexpectedly.
    • getParticleRadius

      public float getParticleRadius()
      Get the particle radius.
    • getParticleFlagsBuffer

      public int[] getParticleFlagsBuffer()
      Get the particle data.
      Returns:
      The pointer to the head of the particle data.
    • getParticlePositionBuffer

      public Vec2[] getParticlePositionBuffer()
    • getParticleVelocityBuffer

      public Vec2[] getParticleVelocityBuffer()
    • getParticleColorBuffer

      public ParticleColor[] getParticleColorBuffer()
    • getParticleGroupBuffer

      public ParticleGroup[] getParticleGroupBuffer()
    • getParticleUserDataBuffer

      public Object[] getParticleUserDataBuffer()
    • setParticleFlagsBuffer

      public void setParticleFlagsBuffer(int[] buffer, int capacity)
      Set a buffer for particle data.
      Parameters:
      buffer - Is a pointer to a block of memory.
      capacity - Is the number of values in the block.
    • setParticlePositionBuffer

      public void setParticlePositionBuffer(Vec2[] buffer, int capacity)
    • setParticleVelocityBuffer

      public void setParticleVelocityBuffer(Vec2[] buffer, int capacity)
    • setParticleColorBuffer

      public void setParticleColorBuffer(ParticleColor[] buffer, int capacity)
    • setParticleUserDataBuffer

      public void setParticleUserDataBuffer(Object[] buffer, int capacity)
    • getParticleContacts

      public ParticleContact[] getParticleContacts()
      Get contacts between particles
    • getParticleContactCount

      public int getParticleContactCount()
    • getParticleBodyContacts

      public ParticleBodyContact[] getParticleBodyContacts()
      Get contacts between particles and bodies
    • getParticleBodyContactCount

      public int getParticleBodyContactCount()
    • computeParticleCollisionEnergy

      public float computeParticleCollisionEnergy()
      Compute the kinetic energy that can be lost by damping force