| 1 |
""" |
| 2 |
.. _collision_example: |
| 3 |
|
| 4 |
Collision |
| 5 |
~~~~~~~~~ |
| 6 |
Perform a collision detection between two meshes. |
| 7 |
|
| 8 |
This example use the :meth:`~pyvista.PolyDataFilters.collision` |
| 9 |
filter to detect the faces from one sphere colliding with another |
| 10 |
sphere. |
| 11 |
|
| 12 |
.. note:: |
| 13 |
Due to the nature of the :vtk:`vtkCollisionDetectionFilter`, |
| 14 |
repeated uses of this method will be slower that using the |
| 15 |
:vtk:`vtkCollisionDetectionFilter` directly. The first |
| 16 |
update of the filter creates two instances of :vtk:`vtkOBBTree`, |
| 17 |
which can be subsequently updated by modifying the transform or |
| 18 |
matrix of the input meshes. |
| 19 |
|
| 20 |
This method assumes no transform and is easier to use for |
| 21 |
single collision tests, but it is recommended to use a |
| 22 |
combination of ``pyvista`` and ``vtk`` for rapidly computing |
| 23 |
repeated collisions. See the `Collision Detection Example |
| 24 |
<https://kitware.github.io/vtk-examples/site/Python/Visualization/CollisionDetection/>`_ |
| 25 |
|
| 26 |
|
| 27 |
""" |
| 28 |
|
| 29 |
import numpy as np |
| 30 |
import pyvista as pv |
| 31 |
|
| 32 |
pv.set_plot_theme('document') |
| 33 |
|
| 34 |
|
| 35 |
# %% |
| 36 |
# Create the main mesh and the secondary "moving" mesh |
| 37 |
# |
| 38 |
# Collision faces will be plotted on this sphere, and to do so we |
| 39 |
# initialize an initial ``"collisions"`` mask. |
| 40 |
sphere0 = pv.Sphere() |
| 41 |
sphere0['collisions'] = np.zeros(sphere0.n_cells, dtype=bool) |
| 42 |
|
| 43 |
# This mesh will be the moving mesh |
| 44 |
sphere1 = pv.Sphere(radius=0.6, center=(-1, 0, 0)) |
| 45 |
|
| 46 |
# %% |
| 47 |
# Set up the plotter open a movie, and write a frame after moving the sphere. |
| 48 |
# |
| 49 |
|
| 50 |
pl = pv.Plotter() |
| 51 |
pl.enable_hidden_line_removal() |
| 52 |
pl.add_mesh(sphere0, scalars='collisions', show_scalar_bar=False, cmap='bwr') |
| 53 |
pl.camera_position = 'xz' |
| 54 |
pl.add_mesh(sphere1, style='wireframe', color='green', line_width=5) |
| 55 |
|
| 56 |
# for this example |
| 57 |
pl.open_gif('collision_movie.gif') |
| 58 |
|
| 59 |
# alternatively, to disable movie generation: |
| 60 |
# pl.show(auto_close=False, interactive=False) |
| 61 |
|
| 62 |
delta_x = 0.1 |
| 63 |
for _ in range(int(2 / delta_x)): |
| 64 |
sphere1.translate([delta_x, 0, 0], inplace=True) |
| 65 |
col, n_contacts = sphere0.collision(sphere1) |
| 66 |
|
| 67 |
collision_mask = np.zeros(sphere0.n_cells, dtype=bool) |
| 68 |
if n_contacts: |
| 69 |
collision_mask[col['ContactCells']] = True |
| 70 |
sphere0['collisions'] = collision_mask |
| 71 |
pl.write_frame() |
| 72 |
|
| 73 |
# alternatively, disable movie plotting and simply render the image |
| 74 |
# pl.render() |
| 75 |
|
| 76 |
pl.close() |
| 77 |
# %% |
| 78 |
# .. tags:: filter |