Pymunk Documentation

repository·master·Indexed 22 days ago

https://github.com/viblo/pymunk

Pymunk is a pythonic 2D rigid body physics library built on top of the Munk2D (a fork of Chipmunk2D) engine, designed for games, simulations, and scientific demos. Version 7.3.0 includes features such as the Batch API for high-performance data retrieval, integration with Matplotlib via pymunk.matplotlib_util for visualization, and support for Pypy to improve execution speed. The library handles collision detection using GJK/EPA algorithms and provides a suite of unit tests and built-in examples.

Tokens
34.3K
Snippets
103
Records
171
Agent score
77%

What's inside pymunk

  1. Explore Pymunk showcase examples

    master

    Pymunk can be used to power a wide variety of applications, ranging from complex 2D games to physics simulations. Notable examples include:

    Games

    • Suika in Python: A reimplementation of the Suika Game where fruits are combined to make larger fruits. Source Code
    • PyKart: A driving game featuring physics-based vehicles in generated landscapes. Play on Itch.io
    • Guide The Ball: A level-based ball-guiding game that demonstrates how to combine Pymunk with Kivy for Android mobile deployment. Source Code
    • My Sincerest Apologies: A combat game (Winner of PyWeek 24). Teardown
    • Beneath the Ice: A submarine exploration and puzzle adventure (Winner of PyWeek 22).
    • Invisipin: A Pachinko-like puzzle game (Winner of PyWeek 20).
    • Angry Birds in Python: A recreation of Angry Birds using Pygame and Pymunk. Source Code
    • SubTerrex: A cave exploration game involving descending on ropes.
  2. Explore the Pymunk submodules

    master

    The pymunk package is organized into several specialized submodules. Depending on your needs, you can use different modules for geometry, batch processing, constraints, or visualization utilities:

    • pymunk.autogeometry: Automated geometry generation.
    • pymunk.batch: For efficient batch processing of physics operations.
    • pymunk.constraints: For defining physical constraints between bodies (e.g., joints, springs).
    • pymunk.vec2d: 2D vector math operations.
    • Visualization Utilities: Specialized modules for rendering the physics simulation in different frameworks:
      • pymunk.matplotlib_util
      • pymunk.pygame_util
      • pymunk.pyglet_util
    • pymunk.examples: Contains sample code and demonstrations.
    • pymunk.tests: Internal test suite.
  3. Understand the relationship between Pymunk and Chipmunk

    master
    Pymunk is a Python wrapper built on top of the Chipmunk C-library. While Pymunk provides a Pythonic interface, the core physics concepts are shared with Chipmunk. For deeper conceptual understanding of the physics engine, you can refer to the official Chipmunk documentation, keeping in mind that Pymunk is the Python-specific implementation.
  4. Understanding units in Pymunk

    master

    Pymunk is unit-less. It does not enforce specific units like kilograms or meters. The units you use are determined by the values you pass to the functions:

    • If you pass seconds to a time parameter, your time unit is seconds.
    • If you pass pixels to a distance parameter, your distance unit is pixels.
    • Derived units (like velocity) will naturally follow your chosen base units (e.g., pixels/second).
  5. How the Pymunk physics simulation works

    master

    Pymunk is a Pythonic wrapper around the Chipmunk2D C-library. The physics simulation follows a standard Euler integration method. The simulation step (typically triggered by cpSpaceStep() in the underlying C code) follows these four stages:

    1. Integration of positions: The engine integrates the positions of all objects and identifies colliding pairs.
    2. Pre-calculation: Properties for contacts and joints (such as mass properties and bounce velocities) are pre-calculated.
    3. Integration of velocities: The engine integrates the velocities of all objects.
    4. Solver iterations: The engine runs a set number of solver iterations to resolve velocity constraints.

    Because position integration happens before velocity integration, the engine avoids moving objects into intersecting positions before the collision is even detected, which improves stability.

  6. Use the Batch API for efficient data retrieval and updates

    master

    Introduced in Pymunk 6.6.0 (experimental) and expanded in 6.7.0, the Batch API allows you to retrieve or set body and collision data in batches. This is optimized for high-performance processing, such as when integrating with NumPy.

    When to use the Batch API

    • High body counts: For CPython users, the Batch API becomes significantly faster than the normal API once you have more than 5 bodies in a space. At high volumes (e.g., 10,000+ bodies), the Batch API can be 30x-40x faster than the normal API.
    • Large scale updates: Use the Batch Set API to update properties like position, angle, and velocity for many bodies at once.

    When to use the Normal API

    • Low body counts: If you are only managing a very small number of bodies (e.g., 1 body), the normal API is faster due to lower overhead.
  7. Thread safety rules for Pymunk objects

    master

    Pymunk objects are not thread-safe. You must not access the same object from multiple threads simultaneously without using your own synchronization primitives (like locks).

    This restriction applies to:

    • Space
    • Body
    • Shape
    • Constraint
    • Callback data

    Crucially, this includes concurrent reads if another thread might mutate or destroy the object being read.

    Safe Pattern: It is safe to use separate Space instances in separate threads, provided that those spaces and all objects attached to them (bodies, shapes, etc.) are not shared between threads.

  8. Calculate world coordinates for shapes

    master

    When manually drawing shapes (e.g., using Pygame) instead of using space.debug_draw, you must account for the body's position and rotation to find the world-space coordinates of shape endpoints.

    For a Segment shape, the world position of an endpoint a is calculated as: world_point = body.position + shape.a.rotated(body.angle)

    Where:

    • body.position is the center of the body.
    • shape.a is the local coordinate of the endpoint.
    • .rotated(body.angle) applies the body's current rotation to the local vector.
    def draw_lines(screen, lines):
        for line in lines:
            body = line.body
            # Calculate world positions of endpoints
            pv1 = body.position + line.a.rotated(body.angle)
            pv2 = body.position + line.b.rotated(body.angle)
            # ... convert to screen coordinates and draw ...
  9. How to manage the center of gravity

    master

    The center of gravity is a critical property of a Body. By default, for many shapes, the center of gravity is at the origin of the shape's local coordinates. If the center of gravity is not at the center of the shape, the object will rotate around that offset point.

    Ways to adjust or manage the center of gravity:

    • Adjust the shape coordinates: Instead of defining a shape from (0,0) to (6,6), define it from (-3,-3) to (3,3) to center it.
    • Directly on the body: Set body.center_of_gravity = (x, y).
    • Using Transforms: Use pymunk.Transform.translation(x, y) when creating a Poly shape to offset it relative to the body.

    Note: pymunk.Circle and boxes created via pymunk.Poly.create_box automatically have their center of gravity in the middle.

  10. Memory management and Weak References in Pymunk

    master

    Pymunk manages memory for Chipmunk C structs (like Body) by allocating them on the C side when Python objects are instantiated.

    To prevent memory leaks, Pymunk uses ffi.gc with custom free functions to ensure that C-side memory is deallocated when the corresponding Python object is garbage collected.

    Important: When working with low-level memory management or extending the library, be aware that the order of freeing objects is critical to avoid memory errors or crashes.

  11. Core concepts of Pymunk: Bodies, Shapes, Constraints, and Spaces

    master

    Pymunk is built around four fundamental abstractions that work together to create a physics simulation:

    1. Rigid Bodies (pymunk.Body): These hold physical properties like mass, position, rotation, and velocity. They do not have a shape by themselves. In games, a Body typically has a 1:1 correlation to a sprite; you should use the body's position and rotation to draw your graphics.
    2. Collision Shapes (pymunk.Circle, pymunk.Segment, pymunk.Poly): Shapes are attached to bodies to define their physical boundaries for collision detection. You can attach multiple shapes to a single body to create complex collision geometry.
    3. Constraints/Joints (pymunk.constraint.PinJoint, pymunk.constraint.SimpleMotor, etc.): These are attached between two bodies to restrict their movement (e.g., keeping them at a fixed distance).
    4. Spaces (pymunk.Space): The simulation unit. You add bodies, shapes, and constraints to a Space, and it manages their interactions. The simulation progresses by calling pymunk.Space.step(dt) to move time forward.
  12. How collision detection is handled in Pymunk

    master
    Collision detection is managed by the underlying Chipmunk2D C-library. For complex shapes such as polygons and segment shapes, Chipmunk utilizes the GJK/EPA (Gilbert-Johnson-Keerthi / Expanding Polytope Algorithm) algorithms to detect collisions.