petrikvladimir / pyphysx

Python Wrapper for Nvidia PhysX simulator.
GNU General Public License v3.0
102 stars 21 forks source link

Implementing random force #33

Closed organic-chemistry closed 3 years ago

organic-chemistry commented 3 years ago

Hello, I would be interested to use your library for molecular dynamics purpose. For this I would need to be able to add random force on all rigid bodys at every time step. Is it possible to implement? Could you recommend a way to do it? Best

petrikvladimir commented 3 years ago

Hello, something like this?

anim_07_random_force

scene = Scene()
scene.add_actor(RigidStatic.create_plane(material=Material(static_friction=0.1, dynamic_friction=0.1, restitution=0.5)))

actors = []
for i in range(-5, 5):
    for j in range(-5, 5):
        actor = RigidDynamic()
        actor.attach_shape(Shape.create_box([0.2] * 3, Material(restitution=1.)))
        actor.set_global_pose([j * 0.25, 0.25 * i, 0.1])
        actor.set_mass(1.)
        scene.add_actor(actor)
        actor.disable_gravity()
        actors.append(actor)

render = PyPhysxViewer(video_filename='videos/07_random_force.gif')
render.add_physx_scene(scene)

rate = Rate(48)
while render.is_active:
    for actor in actors:
        fy = np.random.randn()
        actor.add_force([0., fy, 0.], ForceMode.FORCE)
    scene.simulate(rate.period())
    render.update()
    rate.sleep()
organic-chemistry commented 3 years ago

Yes exactly. But do the forces sum and everytime I add a force I need to delete the previously added force?

petrikvladimir commented 3 years ago

The python function just calls the corresponding c++ function described here: https://gameworksdocs.nvidia.com/PhysX/4.1/documentation/physxguide/Manual/RigidBodyDynamics.html

"The forces acting on a body are accumulated before each simulation frame, applied to the simulation, and then reset to zero in preparation for the next frame." Therefore, the forces are zeroed after calling scene.simulate().

You can also choose other 'force modes', e.g.: "_The PxForceMode member defaults to PxForceMode::eFORCE to apply simple forces. There are other possibilities. For example PxForceMode::eIMPULSE will apply an impulsive force. PxForceMode::eVELOCITYCHANGE will do the same, but also ignore the mass of the body, effectively leading to an instantaneous velocity change. See the API documentation of PxForceMode for the other possibilities."

organic-chemistry commented 3 years ago

Ok thank you for the info and for taking the time ! Best