### List Pymunk Examples Source: https://github.com/viblo/pymunk/blob/master/docs/src/installation.rst Lists all available example scripts included with the Pymunk installation. This helps users discover and choose which examples to run. ```shell > python -m pymunk.examples -l ``` -------------------------------- ### Run Pymunk Example Source: https://github.com/viblo/pymunk/blob/master/docs/src/installation.rst Executes a specific Pymunk example, such as the 'breakout' game. This allows users to see Pymunk in action and understand its capabilities. ```shell > python -m pymunk.examples.breakout ``` -------------------------------- ### Run a Pymunk Example Source: https://github.com/viblo/pymunk/blob/master/README.rst Command to run a specific example from the Pymunk installation. ```bash > python -m pymunk.examples.index_video ``` -------------------------------- ### List Pymunk Examples Source: https://github.com/viblo/pymunk/blob/master/README.rst Command to list available examples included in the Pymunk installation. ```bash > python -m pymunk.examples -l ``` -------------------------------- ### Install Build Tools (Linux) Source: https://github.com/viblo/pymunk/blob/master/docs/src/installation.rst Installs essential build tools on Debian/Ubuntu-based Linux systems using apt-get. This includes a C-compiler necessary for compiling Pymunk and its dependencies. ```shell > sudo apt-get install build-essential ``` -------------------------------- ### Pymunk Quick Start Example Source: https://github.com/viblo/pymunk/blob/master/README.rst A basic example demonstrating how to create a physics simulation with Pymunk. It includes setting up a space, defining gravity, creating a rigid body, attaching a box shape with mass, adding them to the simulation, and stepping through the simulation. ```python import pymunk space = pymunk.Space() space.gravity = 0,-981 body = pymunk.Body() body.position = 50,100 poly = pymunk.Poly.create_box(body) poly.mass = 10 space.add(body, poly) print_options = pymunk.SpaceDebugDrawOptions() for _ in range(100): space.step(0.02) space.debug_draw(print_options) ``` -------------------------------- ### List Available Pymunk Examples Source: https://github.com/viblo/pymunk/blob/master/docs/src/examples.rst Shows how to list all available example scripts within the Pymunk library using the command-line interface. This helps users discover and select which examples to run. ```bash $"\n"python -m pymunk.examples -l ``` -------------------------------- ### Install Pymunk with Pip Source: https://github.com/viblo/pymunk/blob/master/docs/src/installation.rst Installs the Pymunk library using pip, the standard Python package installer. This is the most common method for installing Pymunk on various platforms. ```shell > pip install pymunk ``` -------------------------------- ### Verify Pymunk Installation Source: https://github.com/viblo/pymunk/blob/master/docs/src/installation.rst Runs the built-in test suite for Pymunk to confirm a successful installation. This command executes Pymunk's tests, ensuring the library is functioning correctly. ```shell > python -m pymunk.tests -f test ``` -------------------------------- ### Run Pymunk Example Module Source: https://github.com/viblo/pymunk/blob/master/docs/src/examples.rst Demonstrates how to run a specific Pymunk example script using the Python module execution feature. This is useful for testing or viewing individual example functionalities. ```bash $"\n"python -m pymunk.examples.breakout ``` -------------------------------- ### Install Pymunk Dependencies (Debian/Ubuntu) Source: https://github.com/viblo/pymunk/blob/master/docs/src/installation.rst Installs essential development headers and libraries required for CFFI, a key dependency for Pymunk, on Debian/Ubuntu-based systems. This command ensures that CFFI can be compiled and installed correctly. ```bash sudo apt-get install python-dev libffi-dev ``` -------------------------------- ### Compile Chipmunk Extension Module Source: https://github.com/viblo/pymunk/blob/master/docs/src/installation.rst Builds the C extension module for Pymunk, which interfaces with the Chipmunk physics library. This is typically handled automatically during installation but can be run manually. ```shell > python setup.py build_ext ``` -------------------------------- ### Install Pymunk in Editable Mode Source: https://github.com/viblo/pymunk/blob/master/docs/src/installation.rst Installs Pymunk in development mode from its source code. This allows for direct modification of the library's code and immediate testing without reinstallation. ```shell > python -m pip install -e . ``` -------------------------------- ### Setup Pymunk Physics Space Source: https://github.com/viblo/pymunk/blob/master/additional_examples/newtons_cradle.ipynb Initializes a pymunk physics space with specified gravity and damping. The space object manages all physics objects and simulation steps. ```Python def setup_space(): space = pymunk.Space() space.gravity = 0,-9820 space.damping = 0.99 return space ``` -------------------------------- ### Pymunk Setup Script Source: https://github.com/viblo/pymunk/blob/master/docs/src/advanced.rst Describes the setup.py file's function in managing Pymunk's build process, including custom commands for compiling Chipmunk from source using a build_ext extension. ```python setup.py Except for the standard setup stuff this file also contain the custom build commands to build Chipmunk from source, using a build_ext extension. ``` -------------------------------- ### Setup Matplotlib and Import Pymunk Source: https://github.com/viblo/pymunk/blob/master/additional_examples/matplotlib_util_demo.ipynb Initializes matplotlib for inline display and imports necessary components from pymunk and its utilities. This sets up the environment for physics simulation and visualization. ```Python %matplotlib inline import matplotlib.pyplot as plt #from matplotlib import animation #from IPython.display import HTML import pymunk from pymunk.vec2d import Vec2d from pymunk.examples.shapes_for_draw_demos import fill_space import pymunk.matplotlib_util ``` -------------------------------- ### Install Build Tools (OSX) Source: https://github.com/viblo/pymunk/blob/master/docs/src/installation.rst Installs Xcode Command Line Tools on macOS, which provides a GCC-compatible C-compiler. This is often required if Pymunk needs to be compiled from source on OSX. ```shell > xcode-select --install ``` -------------------------------- ### Pymunk Examples Directory Source: https://github.com/viblo/pymunk/blob/master/docs/src/advanced.rst Indicates the location and purpose of the pymunk/examples directory, which houses a collection of usage examples designed to demonstrate Pymunk's most common features. ```python pymunk/examples/* Collection of examples of usages of Pymunk. Tries to showcase most common features of Pymunk. ``` -------------------------------- ### Pymunk Animation Setup and Execution Source: https://github.com/viblo/pymunk/blob/master/additional_examples/newtons_cradle.ipynb Configures Matplotlib for animation, initializes the Pymunk space and objects, applies an impulse, and sets up the animation loop. The animation steps the physics simulation and redraws the scene. ```Python fig = plt.figure() ax = plt.axes(xlim=(0, 600), ylim=(0, 600)) ax.set_aspect("equal") space = setup_space() setup_balls(space) o = pymunk.matplotlib_util.DrawOptions(ax) space.shapes[1].body.apply_impulse_at_local_point((-12000,0)) def init(): space.debug_draw(o) return [] def animate(dt): #we run the animation with half speed intentionally to make it a little nicer to look at for x in range(10): space.step(1/50/10/2) ax.clear() space.debug_draw(o) return [] frames = 105 anim = animation.FuncAnimation(fig, animate, init_func=init, frames=frames, interval=20, blit=False) HTML(anim.to_html5_video()) ``` -------------------------------- ### Install Pymunk with Conda Source: https://github.com/viblo/pymunk/blob/master/docs/src/installation.rst Installs Pymunk from the conda-forge channel using the Conda package manager. This is an alternative installation method, often preferred for managing complex dependencies. ```shell > conda install -c conda-forge pymunk ``` -------------------------------- ### Compile Chipmunk In-Place Source: https://github.com/viblo/pymunk/blob/master/docs/src/installation.rst Compiles the Chipmunk C extension module and places the output directly into the source directory. This is useful for development when working directly with the source code. ```shell > python setup.py build_ext --inplace ``` -------------------------------- ### Setup Pymunk Balls Source: https://github.com/viblo/pymunk/blob/master/additional_examples/newtons_cradle.ipynb Creates and adds circular bodies (balls) to the pymunk space, attaching them with pin joints to a static body. Each ball has mass, radius, and elasticity defined. ```Python def setup_balls(space): width = 600 height = 600 for x in range(-100,150,50): x += width / 2 offset_y = height/2 mass = 10 radius = 25 moment = pymunk.moment_for_circle(mass, 0, radius, (0,0)) body = pymunk.Body(mass, moment) body.position = x, -125+offset_y body.start_position = Vec2d(*body.position) shape = pymunk.Circle(body, radius) shape.elasticity = 0.9999999 space.add(body, shape) pj = pymunk.PinJoint(space.static_body, body, (x, 125+offset_y), (0,0)) space.add(pj) ``` -------------------------------- ### Pymunk Installation and Usage Source: https://github.com/viblo/pymunk/blob/master/docs/src/index.rst This snippet includes directives for including other documentation files and links to external resources like PyPI, issue tracker, and source repository. It implies Python usage for the Pymunk library. ```python .. include:: ../../README.rst Contents -------- .. toctree:: :maxdepth: 3 installation overview pymunk examples showcase tutorials benchmarks advanced changelog Downloads Issue Tracker Source Repository license Indices and tables ------------------ * :ref:`genindex` * :ref:`modindex` * :ref:`search` ``` -------------------------------- ### Install Pymunk Dependencies on Termux (Android) Source: https://github.com/viblo/pymunk/blob/master/docs/src/installation.rst Installs necessary Python and CFFI dependencies for Pymunk on Android via Termux. This includes Python, development headers, and a C compiler. ```shell $ pkg install python python-dev clang libffi-dev ``` -------------------------------- ### Pyodide Initialization and Python Execution Source: https://github.com/viblo/pymunk/blob/master/dump/pyodide/bench_draw.html This JavaScript code initializes Pyodide, installs the Pillow library using micropip, and provides a function to run Python code. It fetches Python code from a specified file (`bench_draw.py`), executes it with a given command, and displays the output or errors in the console. ```javascript // init Pyodide async function main() { output.value = "Loading Pyodide...\n"; let pyodide = await loadPyodide(); output.value += "Installing MicroPip...\n"; await pyodide.loadPackage("micropip"); const micropip = pyodide.pyimport("micropip"); output.value += "Installing Pillow...\n"; await micropip.install('Pillow'); output.value += "Ready!\n"; return pyodide; } let pyodideReadyPromise = main(); async function runPython(cmd) { let pyodide = await pyodideReadyPromise; try { let r = await fetch("bench_draw.py"); let code = await r.text(); let output = pyodide.runPython(code + "\n" + cmd); addToOutput(output); } catch (err) { addToOutput(err); } } ``` -------------------------------- ### Install Pymunk using conda Source: https://github.com/viblo/pymunk/blob/master/README.rst Installs Pymunk from the conda-forge channel using conda. ```bash > conda install -c conda-forge pymunk ``` -------------------------------- ### Import Libraries Source: https://github.com/viblo/pymunk/blob/master/additional_examples/newtons_cradle.ipynb Imports essential libraries for plotting, animation, and the Pymunk physics engine. Includes Matplotlib for visualization and IPython for displaying the animation. ```Python #%matplotlib inline import matplotlib.pyplot as plt from matplotlib import animation from IPython.display import HTML ``` ```Python import pymunk from pymunk.vec2d import Vec2d import pymunk.matplotlib_util ``` -------------------------------- ### Pymunk Shape Creation and Transformation Source: https://github.com/viblo/pymunk/blob/master/docs/src/overview.rst Demonstrates creating a box shape and applying transformations to a polygon shape. Includes examples of setting the center of gravity and using translation transforms. ```python import pymunk # Example of creating a box shape # Assuming 'b' is a pymunk.Body object # box_shape = pymunk.Poly.create_box(b, size=(6, 6)) # Example of creating a segment shape # segment_shape = pymunk.Segment(body, (-3, -3), (-3, -3), 0) # Directly adjusting the center of gravity # body.center_of_gravity = (3, 3) # Transforming a polygon shape with translation # poly_shape = pymunk.Poly(body, [...], pymunk.Transform.translation(3, 3)) ``` -------------------------------- ### Pymunk Pygame Simulation Setup and Drawing Source: https://github.com/viblo/pymunk/blob/master/docs/src/tutorials/SlideAndPinJoint.rst Demonstrates how to integrate pymunk with Pygame for simulation rendering. It initializes Pygame, creates a pymunk space with gravity, sets up a DrawOptions object for Pygame surfaces, and uses space.debug_draw() to render all simulation elements. Key imports are 'pygame', 'pymunk', and 'pymunk.pygame_util'. ```python import sys, random import pygame import pymunk import pymunk.pygame_util # Assuming add_ball function is defined elsewhere # def add_ball(space): # ... def main(): pygame.init() screen = pygame.display.set_mode((600, 600)) pygame.display.set_caption("Pymunk Simulation") clock = pygame.time.Clock() space = pymunk.Space() space.gravity = (0.0, 900.0) balls = [] draw_options = pymunk.pygame_util.DrawOptions(screen) ticks_to_next_ball = 10 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit(0) ticks_to_next_ball -= 1 if ticks_to_next_ball <= 0: ticks_to_next_ball = 25 ball_shape = add_ball(space) balls.append(ball_shape) space.step(1/50.0) screen.fill((255,255,255)) space.debug_draw(draw_options) pygame.display.flip() clock.tick(50) if __name__ == '__main__': main() ``` -------------------------------- ### Pymunk Python Code Example: Using empty_callback Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Demonstrates the usage of the new `empty_callback` for efficiently resetting any callback to its default state. ```python import pymunk space = pymunk.Space() # Assume a collision handler is set def my_collision_handler(arbiter, space, body_a, body_b): print("Collision detected!") return True # Or False, depending on logic space.on_collision(my_collision_handler, my_collision_handler) # To reset the handler to default (no operation) space.on_collision(pymunk.empty_callback, pymunk.empty_callback) # Now, collision events will not trigger any custom logic. ``` -------------------------------- ### Pymunk Collision Handler Callback Example Source: https://github.com/viblo/pymunk/blob/master/docs/src/benchmarks.rst Demonstrates how to set up a collision handler in Pymunk to intercept collision events. This example shows defining a callback function that returns false, effectively stopping the collision processing, and assigning it to the pre-solve phase of a default collision handler. ```Python h = s.add_default_collision_handler() def f(arb): return False h.pre_solve = f s.step(0.01) ``` -------------------------------- ### Install Pymunk using pip Source: https://github.com/viblo/pymunk/blob/master/README.rst Installs Pymunk from PyPI using pip. It has one direct dependency, CFFI, which is installed automatically. ```bash > pip install pymunk ``` -------------------------------- ### Pymunk Python Code Example: Using Space.step() with Dynamic Bodies Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Illustrates a requirement for dynamic bodies in Pymunk. A dynamic body must have a non-zero mass when `Space.step()` is called, which can be set directly or via attached shapes' mass/density. ```python # Example demonstrating the requirement for non-zero mass on dynamic bodies import pymunk space = pymunk.Space() # Dynamic body with zero mass - will cause an error during step() # dynamic_body = pymunk.Body(mass=0, moment=pymunk.moment_for_circle(1, 0, 10)) # space.add(dynamic_body) # Correct way: Ensure mass is non-zero dynamic_body_with_mass = pymunk.Body(mass=1, moment=pymunk.moment_for_circle(1, 0, 10)) space.add(dynamic_body_with_mass) # Or set mass via shape # shape = pymunk.Circle(dynamic_body_with_mass, 10) # shape.density = 1 # This will set the body's mass if it's zero # space.step(0.1) # This call requires dynamic bodies to have non-zero mass. ``` -------------------------------- ### Pymunk Drawing Options Source: https://github.com/viblo/pymunk/blob/master/additional_examples/newtons_cradle.ipynb Details the use of `pymunk.matplotlib_util.DrawOptions` for rendering Pymunk simulations within a Matplotlib Axes object. It highlights the current approach of clearing and redrawing, suggesting custom drawing for optimization. ```APIDOC pymunk.matplotlib_util.DrawOptions(ax) - Initializes drawing options for a Matplotlib Axes object. - Parameters: - ax: The Matplotlib Axes object to draw on. - Description: - This class provides a way to draw Pymunk physics objects onto a Matplotlib Axes. - The current implementation clears the axes and redraws each frame, which can be inefficient for complex scenes. - For better performance, consider writing custom drawing code inspired by this utility. - Usage: - o = pymunk.matplotlib_util.DrawOptions(ax) - space.debug_draw(o) - Related: - `animation.FuncAnimation`: Used to create the animation loop. - `ax.clear()`: Clears the Matplotlib axes before redrawing. ``` -------------------------------- ### Pymunk Shape Mass and Body Calculation Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Introduces a feature allowing users to directly set the mass of shapes, with Pymunk automatically calculating the corresponding body mass and moment of inertia. This simplifies physics setup. ```python # Conceptual example: # body = pymunk.Body(mass=1.0, moment=1.0) # shape = pymunk.Circle(body, radius) # shape.mass = 5.0 # Pymunk automatically updates body.mass and body.moment ``` -------------------------------- ### Pymunk DampedSpring and DampedRotarySpring Property Access Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Notes the ability to get the `force_func` and `torque_func` properties for `DampedSpring` and `DampedRotarySpring` respectively, indicating improved introspection or access to these callback functions. ```APIDOC DampedSpring.force_func - Allows getting the currently assigned force function. DampedRotarySpring.torque_func - Allows getting the currently assigned torque function. ``` -------------------------------- ### Pymunk Get Position and Angle Benchmark Source: https://github.com/viblo/pymunk/blob/master/docs/src/benchmarks.rst Measures the performance overhead of reading position and angle from Pymunk objects. This is a common operation in simulations, performed frequently per object per frame. The benchmark code is found in `pymunk-get.py`. ```Python t += b.position.x + b.position.y + b.angle ``` -------------------------------- ### Pymunk API Documentation Reference Source: https://github.com/viblo/pymunk/blob/master/docs/src/tutorials/SlideAndPinJoint.rst Links to the Pymunk API documentation. This section serves as a reference point for detailed information on Pymunk's classes, methods, and functionalities, complementing the Munk2D C-library documentation. ```APIDOC Pymunk API Documentation: :doc:`../pymunk` Related Munk2D C-library Documentation: https://viblo.github.io/Munk2D/ ``` -------------------------------- ### Initialize Pymunk Simulation with Pygame Source: https://github.com/viblo/pymunk/blob/master/docs/src/tutorials/SlideAndPinJoint.rst Sets up a Pygame window and initializes a Pymunk physics simulation. It configures the simulation's gravity and includes a basic game loop to handle events, clear the screen, step the physics simulation, and update the display. ```python import sys import pygame import pymunk def main(): pygame.init() screen = pygame.display.set_mode((600, 600)) pygame.display.set_caption("Joints. Just wait, and the L will tip over") clock = pygame.time.Clock() space = pymunk.Space() space.gravity = (0.0, 900.0) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit(0) screen.fill((255,255,255)) space.step(1/50.0) pygame.display.flip() clock.tick(50) if __name__ == '__main__': sys.exit(main()) ``` -------------------------------- ### Pymunk Pygame Initialization and Main Loop Source: https://github.com/viblo/pymunk/blob/master/docs/src/tutorials/SlideAndPinJoint.rst Sets up a Pygame window and a Pymunk simulation space. It initializes Pygame, creates a display surface, sets up the simulation gravity, adds initial objects (like the L-shape), and enters a main loop to update the simulation and render it using pymunk.pygame_util.DrawOptions. The loop handles object creation and simulation steps. ```python import sys, random random.seed(1) # make the simulation the same each time, easier to debug import pygame import pymunk import pymunk.pygame_util def main(): pygame.init() screen = pygame.display.set_mode((600, 600)) pygame.display.set_caption("Joints. Just wait and the L will tip over") clock = pygame.time.Clock() space = pymunk.Space() space.gravity = (0.0, 900.0) lines = add_L(space) balls = [] draw_options = pymunk.pygame_util.DrawOptions(screen) ticks_to_next_ball = 10 while True: # ... simulation update and rendering logic ... pass # Placeholder for loop body ``` -------------------------------- ### Pymunk Initialization and Dependencies Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Details on how Pymunk is initialized and its dependencies. Notably, Pymunk 2.0.0 removed the explicit `pymunk.init()` call, making initialization automatic upon import. Dependency on setuptools was also removed. ```APIDOC Initialization: - Automatic on import: As of Pymunk 2.0.0, Pymunk initializes automatically when imported, removing the need for an explicit `pymunk.init()` call. Dependencies: - Chipmunk: Pymunk is a Python wrapper for the Chipmunk physics library, and updates to Chipmunk often drive Pymunk releases. - msvcrt.dll: On Windows, Pymunk 2.0.0 reduced its dependency to only `msvcrt.dll`. - setuptools: Dependency on setuptools was removed in Pymunk 2.0.0. ``` -------------------------------- ### Pymunk Core Concepts Overview Source: https://github.com/viblo/pymunk/blob/master/docs/src/tutorials/SlideAndPinJoint.rst Provides a high-level overview of the core concepts in Munk2D and Pymunk. It defines rigid bodies, collision shapes, constraints/joints, and spaces, explaining their roles in a physics simulation. ```APIDOC Rigid bodies: A rigid body holds the physical properties of an object. (mass, position, rotation, velocity, etc.) It does not have a shape by itself. If you've done physics with particles before, rigid bodies differ mostly in that they are able to rotate. Collision shapes: By attaching shapes to bodies, you can define the body's shape. You can attach many shapes to a single body to define a complex shape, or none if it doesn't require a shape. Constraints/joints: You can attach joints between two bodies to constrain their behavior. Spaces: Spaces are the basic simulation unit in Munk2D. You add bodies, shapes and joints to a space, and then update the space as a whole. ``` -------------------------------- ### Pymunk Core Classes Overview Source: https://github.com/viblo/pymunk/blob/master/docs/src/overview.rst Introduces the four fundamental classes used in Pymunk for physics simulation: Body for physical properties, Shapes for defining collision geometry, Constraints for linking bodies, and Space for managing the simulation environment. ```APIDOC pymunk.Body: Represents a rigid body holding physical properties like mass, position, rotation, and velocity. Bodies do not have shapes by themselves but are essential for rotation and movement. pymunk.Circle, pymunk.Segment, pymunk.Poly: These classes define the collision shapes attached to bodies. Multiple shapes can be attached to a single body to create complex geometries. A Circle is created at its center, and Poly.create_box creates a box with its center of gravity in the middle. pymunk.constraint.PinJoint, pymunk.constraint.SimpleMotor (and others): Constraints are used to link two bodies together, restricting their relative motion or applying forces. Examples include keeping bodies at a fixed distance or applying continuous rotation. pymunk.Space: The primary simulation unit. Bodies, shapes, and constraints are added to a Space, and the simulation progresses by calling the step function to advance time. ``` -------------------------------- ### Pymunk CFFI Backend Wrapper Source: https://github.com/viblo/pymunk/blob/master/docs/src/advanced.rst Details the pymunk/_chipmunk_cffi.py file, which acts as a wrapper for the _cffi_backend.py script, facilitating switching between Cffi's abi and api modes, primarily for experimental use. ```python pymunk/_chipmunk_cffi.py This file only contains a call to _cffi_backend .py, and exists mostly as a wrapper to be able to switch between abi and api mode of Cffi. This is currently not in use in the released code, but is used during experimentation. ``` -------------------------------- ### Pymunk Sphinx Extension Source: https://github.com/viblo/pymunk/blob/master/docs/src/advanced.rst Highlights the autoexample.py script within the docs/src/ext directory, which functions as a Sphinx extension to automatically extract and generate documentation from top-level docstrings. ```python docs/src/ext/autoexample.py A Sphinx extension that scans a directory and extracts the toplevel docstring. Used to autogenerate the examples documentation. ``` -------------------------------- ### Run Python with Optimizations Source: https://github.com/viblo/pymunk/blob/master/docs/src/overview.rst Execute Python scripts with optimizations enabled to potentially improve performance by disabling non-critical asserts. ```bash python -O mycode.py ``` -------------------------------- ### Create and Populate Pymunk Space Source: https://github.com/viblo/pymunk/blob/master/additional_examples/matplotlib_util_demo.ipynb Creates a pymunk physics space and populates it with objects using the `fill_space` utility function. This prepares the simulation environment for drawing. ```Python space = pymunk.Space() captions = fill_space(space, (1,1,0,1)) ``` -------------------------------- ### Pymunk Tests Directory Source: https://github.com/viblo/pymunk/blob/master/docs/src/advanced.rst Describes the pymunk/tests directory, containing unit tests for Pymunk. While not exhaustive, it covers most of the core functionalities. ```python pymunk/tests/* Collection of (unit) tests. Does not cover all cases, but most core ``` -------------------------------- ### Pymunk Build Configuration Source: https://github.com/viblo/pymunk/blob/master/docs/src/advanced.rst Details the role of pymunk_extension_build.py in configuring the build process for Chipmunk2D using Cffi, enabling the creation of pyd files for low-level bindings. ```python pymunk/pymunk_extension_build.py The low level Chipmunk bindings are located in this file. Contains configuration for how to build Chipmunk2D by Cffi into a pyd file. ``` -------------------------------- ### Pymunk Citation File (CITATION.cff) Source: https://github.com/viblo/pymunk/blob/master/docs/src/showcase.rst This snippet demonstrates the structure of a CITATION.cff file, which is a standard format for software citation. It includes essential metadata like package name, version, authors, and license, formatted in YAML. ```yaml cff-version: 1.2.0 message: If you use Pymunk in a published work, please cite it. # This is a placeholder for the actual citation details. # Please refer to the Pymunk GitHub repository for the most up-to-date citation information. # Example structure: # package-name: pymunk # version: 6.5.0 # description: A pure Python 2D physics library. # authors: # - family-names: "" # Replace with actual author family names # given-names: "" # Replace with actual author given names # license: MIT # repository: https://github.com/viblo/pymunk # url: https://github.com/viblo/pymunk # keywords: # - physics # - 2d # - simulation # - python ``` -------------------------------- ### pymunk.pygame_util Module Documentation Source: https://github.com/viblo/pymunk/blob/master/docs/src/pymunk.pygame_util.rst Directive to generate documentation for the pymunk.pygame_util Python module, including special members like __init__. ```APIDOC .. automodule:: pymunk.pygame_util :special-members: __init__ ``` -------------------------------- ### Pymunk Module API Source: https://github.com/viblo/pymunk/blob/master/docs/src/pymunk.rst Documents the main pymunk module, including its special members like __init__, __matmul__, __add__, etc. This section provides an overview of the module's core functionalities and how to interact with them. ```APIDOC .. automodule:: pymunk :special-members: __init__, __matmul__, __add__,__sub__,__mul__,__floordiv__,__truediv__,__neg__,__pos__,__abs__ ``` -------------------------------- ### Pymunk Pygame Simulation Loop Source: https://github.com/viblo/pymunk/blob/master/docs/src/tutorials/SlideAndPinJoint.rst The main function to run the Pymunk physics simulation within a Pygame window. It initializes Pygame, sets up the physics space with gravity, manages object creation (balls and static shapes), handles user input, steps the simulation, and renders the scene using Pymunk's debug drawing capabilities. ```python import sys, random random.seed(1) # make the simulation the same each time, easier to debug import pygame import pymunk import pymunk.pygame_util # Assume to_pygame, add_ball, and add_static_L are defined elsewhere # def to_pygame(p): # def add_ball(space): # def add_static_l(space): def main(): pygame.init() screen = pygame.display.set_mode((600, 600)) pygame.display.set_caption("Joints. Just wait and the L will tip over") clock = pygame.time.Clock() space = pymunk.Space() space.gravity = (0.0, 900.0) # Add the static L shape (or dynamic L shape in later examples) lines = add_static_L(space) balls = [] draw_options = pymunk.pygame_util.DrawOptions(screen) ticks_to_next_ball = 10 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit(0) # Spawn new balls periodically ticks_to_next_ball -= 1 if ticks_to_next_ball <= 0: ticks_to_next_ball = 25 ball_shape = add_ball(space) balls.append(ball_shape) # Step the physics simulation space.step(1/50.0) # Drawing screen.fill((255,255,255)) space.debug_draw(draw_options) pygame.display.flip() clock.tick(50) if __name__ == '__main__': main() ``` -------------------------------- ### Customizable Compilation for ARM/Android Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Describes how Pymunk's compilation process can be customized for environments like ARM/Android by overriding compiler and linker settings using environment variables. This facilitates building Pymunk without patching its source code. ```bash export CC="arm-linux-gnueabihf-gcc" export CFLAGS="-march=armv7-a -mfloat-abi=hard -mfpu=neon" export LD="arm-linux-gnueabihf-ld" export LDFLAGS="-march=armv7-a -mfloat-abi=hard -mfpu=neon" ``` -------------------------------- ### Pymunk Space Step Stability Source: https://github.com/viblo/pymunk/blob/master/docs/src/overview.rst Illustrates the importance of a constant time step (dt) for Pymunk's Space.step function to ensure simulation stability. Mentions calling step multiple times per frame. ```python import pymunk # Assuming 'space' is a pymunk.Space object # dt = 1/60.0 # Example fixed time step # space.step(dt) # To improve stability, call space.step multiple times per frame if needed: # for _ in range(num_steps): # space.step(dt) ``` -------------------------------- ### Run Pymunk Tests Source: https://github.com/viblo/pymunk/blob/master/docs/src/advanced.rst Execute the unit tests included in the pymunk.tests package. Tests can be filtered using a string argument for more targeted execution. ```python python -m pymunk.tests ``` ```python python -m pymunk.tests -f testRestitution ``` ```python python -m pymunk.tests -h ``` -------------------------------- ### Using float('inf') and importing constraints Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Shows the replacement of pymunk.inf with Python's standard float('inf') and the renaming of the constraint module. ```python # Use standard float('inf') instead of pymunk.inf value = float('inf') # Import from the new module name import pymunk.constraints ``` -------------------------------- ### Add Ball to Pymunk Space Source: https://github.com/viblo/pymunk/blob/master/docs/src/tutorials/SlideAndPinJoint.rst Defines a function to create a dynamic ball (body and shape) in a pymunk simulation. It sets properties like mass, radius, position, and friction, then adds the ball to the provided physics space. Dependencies include 'pymunk' and 'random'. ```python import random import pymunk def add_ball(space): mass = 3 radius = 25 body = pymunk.Body() x = random.randint(120, 300) body.position = x, 50 shape = pymunk.Circle(body, radius) shape.mass = mass shape.friction = 1 space.add(body, shape) return shape ``` -------------------------------- ### MyPy vs Pyright Type Checking Differences Source: https://github.com/viblo/pymunk/blob/master/TODO.txt Highlights observed differences and issues between the MyPy and Pyright type checkers, particularly concerning Python's type hinting system and specific language features. ```Python # Issue: Setters cannot have different types from getters in MyPy # https://github.com/python/mypy/issues/3004 # This implies a strictness in MyPy regarding property type consistency. # Issue: __path__ not supported in packages in MyPy # https://github.com/python/mypy/issues/1422 # Indicates MyPy's handling of package internal variables. # Pyright behavior: Type requirements for __add__ not the same as for + # https://github.com/microsoft/pyright/issues/992 # Suggests Pyright might have different interpretations or stricter rules for operator overloading. # Note: Pyright maintainer is praised for quick responses and fixes. # MyPy issue tracker is also fast to respond, with GvR actively participating. ``` -------------------------------- ### Add Ball to Space (Pymunk) Source: https://github.com/viblo/pymunk/blob/master/docs/src/tutorials/SlideAndPinJoint.rst Adds a circular ball (pymunk.Circle) with specified mass and radius to a Pymunk simulation space at a random horizontal position near the top. It creates a pymunk.Body and a pymunk.Circle shape, sets their properties, and adds them to the space. ```python import pymunk import random def add_ball(space): """Add a ball to the given space at a random position""" mass = 3 radius = 25 body = pymunk.Body() x = random.randint(120,300) body.position = x, 50 shape = pymunk.Circle(body, radius, (0,0)) shape.mass shape.friction = 1 space.add(body, shape) return shape ``` -------------------------------- ### Creating a Static L-Shape Source: https://github.com/viblo/pymunk/blob/master/docs/src/tutorials/SlideAndPinJoint.rst Defines a static L-shaped structure using Pymunk segments. This involves creating a static body, defining two segments for the L's arms, setting their mass and friction, and adding them to the physics space. ```python def add_static_L(space): # Create a static body for the rotation center rotation_center_body = pymunk.Body(body_type=pymunk.Body.STATIC) rotation_center_body.position = (300, 300) # Create the dynamic body for the L-shape body = pymunk.Body() body.position = (300, 300) # Define the segments of the L-shape l1 = pymunk.Segment(body, (-150, 0), (255.0, 0.0), 5.0) l2 = pymunk.Segment(body, (-150.0, 0), (-150.0, -50.0), 5.0) # Set friction and mass for the segments l1.friction = 1 l2.friction = 1 l1.mass = 8 l2.mass = 1 # Add the segments, body, and a pin joint to the space # The pin joint connects the L-shape body to the static rotation center rotation_center_joint = pymunk.PinJoint( body, rotation_center_body, (0, 0), (0, 0) ) space.add(l1, l2, body, rotation_center_joint) return l1, l2 ``` -------------------------------- ### Pymunk Space Simulation Step Source: https://github.com/viblo/pymunk/blob/master/docs/src/overview.rst The Space class is responsible for running the physics simulation. The core of the simulation loop involves advancing time using the step function, which updates the positions and velocities of all simulated objects. ```APIDOC pymunk.Space.step(dt): Advances the simulation by a given time step. - dt: The time delta for the simulation step. This should typically be a small, fixed value for stable simulations. Usage: space.step(1/60.0) # Advance simulation by 1/60th of a second ``` -------------------------------- ### Interactive Animation Overlay (HTML, CSS, JavaScript) Source: https://github.com/viblo/pymunk/blob/master/docs/src/index.rst This snippet defines an HTML structure for an interactive overlay, styled with CSS to cover the page, and controlled by JavaScript to show an animation and allow dismissal. ```html
Click to dismiss. Animation by Er Robin at codepen.io
``` ```css #bd-2021 { position: fixed; /* Sit on top of the page content */ display: none; /* Hidden by default */ width: 100%; /* Full width (cover the whole page) */ height: 100%; /* Full height (cover the whole page) */ top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.5); /* Black background with opacity */ z-index: 2; /* Specify a stack order in case you're using a different order for other elements */ cursor: pointer; /* Add a pointer on hover */ } #bd-2021 > span { color: gray; position: absolute; bottom: 0; z-index: 3; font-size: x-small; } #bd-2021 > canvas { position: absolute; top: 0; left: 0; opacity: 90%; } ``` ```javascript let now = new Date(); if (now.getDate() == 11 && now.getMonth() == 3){ $("#bd-2021").show(); anim(function(){ $("#bd-2021").fadeOut(1000); }); } $("#bd-2021").click(function(){ $(this).hide() }) ``` -------------------------------- ### moment_for_poly, area_for_poly, and apply_force/impulse Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Details changes to moment_for_poly and area_for_poly argument types, and default values for apply_force_at_local_point and apply_impulse_at_world_point. ```python # moment_for_poly/area_for_poly expect Sequence of tuples poly_points = [(x1, y1), (x2, y2)] moment = pymunk.moment_for_poly(mass, poly_points) # apply_force_at_local_point has default point body.apply_force_at_local_point((0, 100), point=(0, 0)) # apply_impulse_at_world_point requires point argument body.apply_impulse_at_world_point((0, 100), point=(0, 0)) ``` -------------------------------- ### Pymunk Batch API Benchmark Source: https://github.com/viblo/pymunk/blob/master/docs/src/benchmarks.rst Compares the performance of the new experimental batch API for retrieving and setting body properties (position, angle, velocity) against the traditional non-batch API. This benchmark assesses efficiency gains, especially with a large number of bodies. ```Python # Benchmark code for batch API is in pymunk-batch-api.py # Example usage would involve fetching/setting properties in batches. ``` -------------------------------- ### Pymunk API Change: Unified Space.query Methods Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Describes the unification of `Space.query` methods to include sensor shapes, which were previously filtered out by nearest methods. ```APIDOC Space.query_point(point, layers=ALL_LAYERS, group=0) - Now includes sensor shapes in the query results. Space.query_segment(a, b, radius, layers=ALL_LAYERS, group=0) - Now includes sensor shapes in the query results. Space.nearest(point, max_dist, layers=ALL_LAYERS, group=0) - Now includes sensor shapes in the query results. ``` -------------------------------- ### Pymunk Pickle and Copy Support Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Details on Pymunk's serialization capabilities, including pickle support for most objects and the availability of a copy() method. It notes that pickle compatibility for Spaces with callback functions depends on the pickle protocol version. ```python import pickle import copy # Example usage (conceptual): # my_space = pymunk.Space() # pickled_space = pickle.dumps(my_space) # unpickled_space = pickle.loads(pickled_space) # my_shape = pymunk.Circle(body, radius) # copied_shape = my_shape.copy() ``` -------------------------------- ### Pymunk Callback Handling Source: https://github.com/viblo/pymunk/blob/master/docs/src/advanced.rst Explains the purpose of pymunk/_callbacks.py, a file dedicated to consolidating callback functions that cannot be directly associated with a class structure. ```python pymunk/_callbacks.py Callbacks cannot be specified on a class, so they are all gathered here. ``` -------------------------------- ### Pymunk Poly.create_box Helper Source: https://github.com/viblo/pymunk/blob/master/docs/src/overview.rst A convenience method for creating a rectangular polygon shape. It simplifies the process of defining a box-shaped physics object with its center of gravity correctly positioned. ```APIDOC pymunk.Poly.create_box(body, size, radius=0): Creates a box shape for the given body. - body: The pymunk.Body to attach the shape to. - size: A tuple (width, height) defining the dimensions of the box. - radius: The radius for rounded corners (default is 0 for sharp corners). Returns: A pymunk.Poly object representing the box shape. ``` -------------------------------- ### Transform helper methods and autogeometry changes Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Highlights the addition of helper methods for creating transforms (translate, scale, rotate) and changes in autogeometry functions regarding input types and return values. ```python # Transform helpers translate_transform = Transform.translation(x, y) scale_transform = Transform.scale(sx, sy) rotate_transform = Transform.rotation(angle) # Autogeometry sample_func expects tuple # Autogeometry segment_func replaced by PolylineSet return ``` -------------------------------- ### Include pymunk.js for Batch Operations Source: https://github.com/viblo/pymunk/blob/master/docs/src/pymunk.batch.rst This snippet indicates the inclusion of a JavaScript file named 'pymunk.js' within the documentation's HTML structure. It suggests that JavaScript might be used for handling batch operations related to the pymunk library. ```html ``` -------------------------------- ### PyInstaller compatibility and Debug logging Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Notes improvements for Pymunk to work with bundlers like PyInstaller and the addition of debug logging for C memory issues. ```python # No code change needed for PyInstaller compatibility # Debug logging can be enabled via Python's logging module import logging logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### Pymunk 5.7.0 Fixes and Improvements Source: https://github.com/viblo/pymunk/blob/master/CHANGELOG.rst Summarizes key changes in Pymunk 5.7.0, including fixes for PyInstaller, performance improvements for Vec2d, handling of springs, ordered bodies/constraints, and the introduction of Space.use_spatial_hash. ```python # Enable spatial hash for potential performance gains space.use_spatial_hash() # Debug drawing of springs with 0 length is now handled. # Bodies and constraints are ordered when accessed from the space. ```