Forum Replies Created
-
AuthorPosts
-
ArthurBlocked
A solution for recording a scene without using SofaPython3. In fact it is a different process entirely that fakes inputs to the gui
If you are running sofa on a linux desktop you can record a running sofa scene with the following python script (N.B. you might have add the –start flag to the runSofa command).
import os import pyautogui import time ##This is needed if you want to record on a desktop with more than one window to make the sofa # gui the active window os.system("wmctrl -l > /tmp/window_list.txt") sofa_window = None with open("/tmp/window_list.txt", "r") as ping: line = ping.readline() while line: if "Sofa -" in line: print(line) i = line.index("Sofa -") sofa_window = line[i:-1] line = ping.readline() cmd_string = 'wmctrl -a "'+sofa_window+ '" ' print(cmd_string) os.system(cmd_string) # this will begin recording wait ten wall clock seconds (not simulator secdons and end the recording pyautogui.write('v', 0.5) time.sleep(10) pyautogui.write('v', 0.5)
Also if you are running a version of sofa that is not compatible with the recording functionality in SofaPython3 or for whatever reason you can’t get that recoding to work there is a work around I have found. If you have a headless server with sofa installed on it you can record videos with the following (tested with python3 code).
import time import subprocess class SofaRecorder: def __init__(self, running_on_headless_server=False): self.x_server = None self.pyautogui = None self.headless = running_on_headless_server def start_x_server(self): if self.x_server == None and self.headless: self.x_server = subprocess.Popen(["sudo","X","-config", "/dummy.conf"]) time.sleep(3) #wait for process to get online # pyautogui cannot be imported until there is a display to connect to process launches import pyautogui self.pyautogui = pyautogui def start_recording(self): self.start_x_server() time.sleep(1) self.pyautogui.write('v') def stop_recording(self): self.pyautogui.write('v') time.sleep(1) def stop_x_server(self): subprocess.Popen(["sudo", "kill", str(self.x_server.pid)]) time.sleep(1) self.x_server = None # example of usage if __name__ == "__main__": recorder = SofaRecorder(running_on_headless_server=True) # if the x_server is not started before the sofa gui launches # the sofa process will seg fault recorder.start_x_server() # without the -g batch option this launches a sofa gui sofa_process = subprocess.Popen(["runSofa", "--start"]) recorder.start_recording() print('recording started') time.sleep(30) #note this records for 10 wall clock seconds not seconds in the simulator recorder.stop_recording() print('recording stoppped') time.sleep(3) sofa_process.terminate() print("sofa terminated") time.sleep(3) recorder.stop_x_server() print('x server terminated')
These are the dependencies I had to install on my docker container which already had sofa set up in it:
sudo PIP_TARGET=/usr/lib/python3.7/dist-packages python3.7 -m pip install \ pynput pyautogui sudo DEBIAN_FRONTEND=noninteractive apt-get install -y python3-tk python3-dev sudo apt-get update sudo apt-get install -y xserver-xorg-video-dummy x11-utilss export DISPLAY=:0
and dummy.conf is
Section "Monitor" Identifier "Monitor0" HorizSync 28.0-80.0 VertRefresh 48.0-75.0 # https://arachnoid.com/modelines/ # 1920x1080 @ 60.00 Hz (GTF) hsync: 67.08 kHz; pclk: 172.80 MHz Modeline "1920x1080_60.00" 172.80 1920 2040 2248 2576 1080 1081 1084 1118 -HSync +Vsync EndSection Section "Device" Identifier "Card0" Driver "dummy" VideoRam 256000 EndSection Section "Screen" DefaultDepth 24 Identifier "Screen0" Device "Card0" Monitor "Monitor0" SubSection "Display" Depth 24 Modes "1920x1080_60.00" EndSubSection EndSection
ArthurBlockedThanks @felixvanneste,
My problem is that I do not know how to get the triangular collision mesh from volume_collision.stl to appear on the leg on the robot. Rather it appears on the leg the is in a fixed position. (I need it on the one that is in the mapped position). The the example this is from gets the points to be mapped with:
# mapped collision (with reduce size) mappedCollisionLeg = mappedLeg.createChild('mappedCollisionLeg' + str(i)) mappedCollisionLeg.createObject('MechanicalObject', template='Vec3d', name='mappedCollisionLeg') mappedCollisionLeg.createObject('Point', color='1 0 0 1', group='1', translation=framePosition[i]) mappedCollisionLeg.createObject('SubsetMapping', indices='@../../../' + strLink0 + strLink1 + str( i) + strLink2 + '/boxROICollision.indices', input='@../../mappedLeg' + str(i) + '/mappedLeg')
And I was wondering how to do this kind of mapping but also include triangles (or have the collision mesh be there).
I was also wondering if there is a reason “BilateralInteractionConstraint” was not used in the SOFIA demo where the mappings are used instead? Is there any reason that “BilateralInteractionConstraint” would not work with a reduced model?
Arthur
ArthurBlockedWhile I don’t oppose moving to github discussions, it would be sad to have all the past discussions on here go to waste.
It would be great if the current forum was archived somewhere where people could still find it and search it.
Overall I think github discussions may be a better platform, but I do like how all the plugins and features can be discussed in one place and I would like to see that continue.
10 January 2021 at 20:56 in reply to: Error into use the LinearSolverConstraintCorrection with SofaCUDA types #18170ArthurBlockedHi @Hugo,
Is there any update for open use of sofaCudaSolver?
Is there someone you could direct me to in order to ask about academic use?
Best,
ArthurArthurBlockedHi @jnbrunet,
I believe that example is out of date with SofaPython3. I was able to find a solution though. It still requires a display — so unless there is a way to set the QApplication display to offscreen in sofapython3, it is still not ideal for running on a server. That said this is my solution:
# encoding: utf-8 # !/usr/bin/python3 import Sofa import SofaRuntime import Sofa.Gui class scene_interface: """Scene_interface provides step and reset methods""" def __init__(self, dt=0.01, max_steps=300): self.dt = dt # max_steps, how long the simulator should run. Total length: dt*max_steps self.max_steps = max_steps # root node in the simulator self.root = None # the current step in the simulation self.current_step = 0 # Register all the common component in the factory. SofaRuntime.importPlugin('SofaOpenglVisual') SofaRuntime.importPlugin("SofaComponentAll") self.root = Sofa.Core.Node("myroot") ### create some objects to observe self.place_objects_in_scene(self.root) # place light and a camera self.root.addObject("LightManager") self.root.addObject("SpotLight", position=[0,10,0], direction=[0,-1,0]) self.root.addObject("InteractiveCamera", name="camera", position=[0,10, 0], lookAt=[0,0,0], distance=37, fieldOfView=45, zNear=0.63, zFar=55.69) # start the simulator Sofa.Simulation.init(self.root) # start the gui Sofa.Gui.GUIManager.Init("Recorded_Episode", "qt") Sofa.Gui.GUIManager.createGUI(self.root, __file__) def place_objects_in_scene(self, root): ### these are just some things that stay still and move around # so you know the animation is actually happening root.gravity = [0, -1., 0] root.addObject("VisualStyle", displayFlags="showWireframe showBehaviorModels showAll") root.addObject("MeshGmshLoader", name="meshLoaderCoarse", filename="mesh/liver.msh") root.addObject("MeshObjLoader", name="meshLoaderFine", filename="mesh/liver-smooth.obj") root.addObject("EulerImplicitSolver") root.addObject("CGLinearSolver", iterations="200", tolerance="1e-09", threshold="1e-09") liver = root.addChild("liver") liver.addObject("TetrahedronSetTopologyContainer", name="topo", src="@../meshLoaderCoarse" ) liver.addObject("TetrahedronSetGeometryAlgorithms", template="Vec3d", name="GeomAlgo") liver.addObject("MechanicalObject", template="Vec3d", name="MechanicalModel", showObject="1", showObjectScale="3") liver.addObject("TetrahedronFEMForceField", name="fem", youngModulus="1000", poissonRatio="0.4", method="large") liver.addObject("MeshMatrixMass", massDensity="1") liver.addObject("FixedConstraint", indices="2 3 50") def step(self): # step through time # this steps the simulation Sofa.Simulation.animate(self.root, self.dt) # just to keep track of where we are self.current_step += 1 ### A better example would also show how to read and edit values through scripts # which would likely be useful if you are running without a normal gui # return true if done return self.current_step >= self.max_steps # save a screenshot from the position of where we set the camera above def record_frame(self, filename): Sofa.Gui.GUIManager.SaveScreenshot(filename) def main(): a = scene_interface() done = False while not done: factor = a.current_step done = a.step() a.record_frame(str(factor) + ".png") if __name__ == '__main__': main()
ArthurBlockedHi @jnbrunet,
That has got the GUI working! (EDIT: specifically the change to qglviewer fixed it)
However, I am trying to use this to view a simulation that is controlled by another python script, which steps the animation forward using the “Sofa.Simulation.animate” function. However when I try to use that with the gui, use of that function and “Sofa.Gui.GUIManager.MainLoop” seem to be mutually exclusive. Is this the case?
If so, is there a way to use the gui or record screenshots at every time step without needing to use MainLoop?
ArthurBlockedHi @jnbrunet,
The edit you suggested successfully opens a Gui!
However, once I try to add something to the scene I get the
[ERROR] [SofaRuntime] RuntimeError: basic_string::_M_construct null not valid
error again:This is my code now:
import Sofa import Sofa.Core import Sofa.Simulation import Sofa.Gui import SofaRuntime SofaRuntime.importPlugin('SofaOpenglVisual') print ("Supported GUIs are " + Sofa.Gui.GUIManager.ListSupportedGUI(",")) root = Sofa.Core.Node("root") # Create the rest of the scene here... def Sphere(rootNode, name, position, color): #Creating the sphere sphere = rootNode.addChild(name) sphere.addObject('MechanicalObject', name="mstate", template="Rigid3", position=position) #### Visualization of the sphere sphereVisu = sphere.addChild("VisualModel") sphereVisu.loader = sphereVisu.addObject('MeshObjLoader', name="loader", filename="mesh/ball.obj", scale=0.5) sphereVisu.addObject('OglModel', name="model", src="@loader", color=color) sphereVisu.addObject('RigidMapping') return sphere Sphere(root, "hi", "0 0 0", None) # Initialize all components found in the scene Sofa.Simulation.init(root) # Launch the GUI Sofa.Gui.GUIManager.Init("simple_scene", "qt") Sofa.Gui.GUIManager.createGUI(root, __file__) Sofa.Gui.GUIManager.MainLoop(root) Sofa.Gui.GUIManager.closeGUI()
This is my output:
(base) sofauser@carbon:~/workdir/simple_control_policy$ python gui_sofa.py [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaOpenglVisual.so Supported GUIs are batch,qglviewer,qt libGL error: failed to open /dev/dri/card0: Permission denied libGL error: failed to load driver: nouveau [WARNING] [RealGUI] Global Bounding Box seems very small; Your viewer settings (based on the bbox) are likely invalid, switching to default value of [-1,-1,-1,1,1,1].This is caused by using component which does not implement properly the updateBBox function.You can remove this warning by manually forcing a value in the parameter bbox="minX minY minZ maxX maxY maxZ" in your root node QtViewer: OpenGL 3.3 (Core Profile) Mesa 20.0.8 context created. [WARNING] [SofaViewer] Could not create file '/builds/src/share/textures/SOFA_logo.bmp' Valid extensions: dds [WARNING] [SofaSimulationTree] the library has not been cleaned up (sofa::simulation::tree::cleanup() has never been called, see sofa/helper/init.h) (base) sofauser@carbon:~/workdir/simple_control_policy$ python gui_sofa.py [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaOpenglVisual.so Supported GUIs are batch,qglviewer,qt libGL error: failed to open /dev/dri/card0: Permission denied libGL error: failed to load driver: nouveau QtViewer: OpenGL 3.3 (Core Profile) Mesa 20.0.8 context created. [WARNING] [SofaViewer] Could not create file '/builds/src/share/textures/SOFA_logo.bmp' Valid extensions: dds [ERROR] [SofaRuntime] RuntimeError: basic_string::_M_construct null not valid Traceback (most recent call last): File "gui_sofa.py", line 34, in <module> Sofa.Gui.GUIManager.createGUI(root, __file__) [WARNING] [SofaSimulationTree] the library has not been cleaned up (sofa::simulation::tree::cleanup() has never been called, see sofa/helper/init.h) (base) sofauser@carbon:~/workdir/simple_control_policy$
And this is my output without trying to add the sphere which opens the gui successfully.
(base) sofauser@carbon:~/workdir/simple_control_policy$ python gui_sofa.py [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaOpenglVisual.so Supported GUIs are batch,qglviewer,qt libGL error: failed to open /dev/dri/card0: Permission denied libGL error: failed to load driver: nouveau [WARNING] [RealGUI] Global Bounding Box seems very small; Your viewer settings (based on the bbox) are likely invalid, switching to default value of [-1,-1,-1,1,1,1].This is caused by using component which does not implement properly the updateBBox function.You can remove this warning by manually forcing a value in the parameter bbox="minX minY minZ maxX maxY maxZ" in your root node QtViewer: OpenGL 3.3 (Core Profile) Mesa 20.0.8 context created. [WARNING] [SofaViewer] Could not create file '/builds/src/share/textures/SOFA_logo.bmp' Valid extensions: dds
ArthurBlockedHi @jnbrunet,
This is the exact script I’m using, I’ve added the two lines you suggested to this file: https://github.com/sofa-framework/SofaPython3/blob/master/examples/SofaGui.py
So it looks like this:
import Sofa import Sofa.Core import Sofa.Simulation import Sofa.Gui import SofaRuntime SofaRuntime.importPlugin('SofaOpenglVisual') print ("Supported GUIs are " + Sofa.Gui.GUIManager.ListSupportedGUI(",")) root = Sofa.Core.Node("root") # Create the rest of the scene here... # Initialize all components found in the scene Sofa.Simulation.init(root) # Launch the GUI Sofa.Gui.GUIManager.Init("simple_scene", "qt") Sofa.Gui.GUIManager.createGUI(root) Sofa.Gui.GUIManager.MainLoop(root) Sofa.Gui.GUIManager.closeGUI()
I still get the original error though (though with fewer warnings):
(base) sofauser@carbon:/builds/plugins/SofaPython3/examples$ python SofaGui.py [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaOpenglVisual.so Supported GUIs are batch,qglviewer,qt libGL error: failed to open /dev/dri/card0: Permission denied libGL error: failed to load driver: nouveau [WARNING] [RealGUI] Global Bounding Box seems very small; Your viewer settings (based on the bbox) are likely invalid, switching to default value of [-1,-1,-1,1,1,1].This is caused by using component which does not implement properly the updateBBox function.You can remove this warning by manually forcing a value in the parameter bbox="minX minY minZ maxX maxY maxZ" in your root node [ERROR] [SofaRuntime] RuntimeError: basic_string::_M_construct null not valid Traceback (most recent call last): File "SofaGui.py", line 24, in <module> Sofa.Gui.GUIManager.createGUI(root) [WARNING] [SofaSimulationTree] the library has not been cleaned up (sofa::simulation::tree::cleanup() has never been called, see sofa/helper/init.h) (base) sofauser@carbon:/builds/plugins/SofaPython3/examples$
ArthurBlockedHi @jnbrunet,
Thanks for your response!
Using runSofa works fine (the gui loads and I can run the scene). It even has the same libGL error when it is working.
This is the terminal output from (working) runSofa:
(base) sofauser@carbon:/pkgs/dl/examples/sofa_start$ runSofa [INFO] [runSofa] PluginRepository paths = /builds/build/master/lib:/builds/build/master/plugins [INFO] [runSofa] DataRepository paths = /builds/src/share:/builds/src/examples [INFO] [runSofa] GuiDataRepository paths = /builds/src/applications/projects/runSofa/resources:/builds/src/modules/SofaGuiQt/src/sofa/gui/qt/resources Created directory: /builds/build/master//config Created directory: /builds/build/master//screenshots [INFO] [runSofa] Loading automatically plugin list in /builds/build/master/lib/plugin_list.conf [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralVisual.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGraphComponent.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralMeshCollision.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaBoundaryCondition.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralAnimationLoop.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralDeformable.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralEngine.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralExplicitOdeSolver.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralImplicitOdeSolver.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralLinearSolver.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralRigid.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralObjectInteraction.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralSimpleFem.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralTopology.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaTopologyMapping.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaUserInteraction.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaConstraint.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralLoader.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaSparseSolver.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaPreconditioner.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaHaptics.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaValidation.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaDenseSolver.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaNonUniformFem.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaOpenglVisual.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscTopology.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscExtra.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscForceField.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscEngine.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscSolver.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscFem.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscMapping.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaExporter.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libCImgPlugin.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscCollision.so [INFO] [SofaPython3] Initializing with python version 3.7.4 (default, Aug 13 2019, 20:39:44) [GCC 7.3.0] [INFO] [SofaPython3] Registering a scene loader for [.py, .py3, .pyscn, .py3scn] files. [INFO] [SofaPython3] Shared library name is 'libpython3.7m.so' [INFO] [SofaPython3] Intializing python [INFO] [SofaPython3] Added '/builds/build/master/python3/site-packages' to sys.path [INFO] [SofaPython3] Added '/builds/src/applications/plugins/SofaTest/python' to sys.path [INFO] [SofaPython3] Added '/builds/build/master/lib/python3/site-packages' to sys.path [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaPython3.so [INFO] [GUIManager] INFO(SofaGUI): lastUsedGUI.ini not found; using default GUI. libGL error: failed to open /dev/dri/card0: Permission denied libGL error: failed to load driver: nouveau Warning: Setting a new default format with a different version or profile after the global shared context is created may cause issues with context sharing. The constructor with a QGLFormat is deprecated, use the regular contructor instead. [INFO] [SceneCheckerVisitor] Validating node "root" with checks: [SceneCheckDuplicatedName, SceneCheckMissingRequiredPlugin, SceneCheckUsingAlias] [INFO] [SceneCheckerVisitor] Finished validating node "root". (base) sofauser@carbon:/pkgs/dl/examples/sofa_start$
17 December 2020 at 19:12 in reply to: [SOLVED] How to make a PythonScript controller with SofaPython3 #18050ArthurBlockedThanks @jnbrunet,
that has done it!
On a side note, I was wondering if there is an established way to reset a sofa simulation in SofaPython3, I would want it to have the same effect as, the “Reset Scene” button does in the gui – all the objects go back to their original locations, the clock is set to zero, and the python controllers are reloaded and run again.
Thank you again!
Arthur
16 December 2020 at 18:43 in reply to: [SOLVED] How to make a PythonScript controller with SofaPython3 #18043ArthurBlockedHi @jnbrunet,
The full output is posted below, the whole example is posted here in https://github.com/ripl-ttic/SofaFramework-Docker/tree/python3 [Edit: I inadvertently pushed to this branch this afternoon, but for record keeping as well, look at commit 4a975fc53a215f547d353917d990fd01d8f0428b for the example][NB: this is not the master branch].
The full environment is specified in Dockerfile, you can build with ./build.sh and then run the environment with ./launch.sh, or x-docker_launch.sh, once you are in run the example with “runSofa block_test.py –start”.
sofauser@carbon:~/workdir/simple_control_policy$ runSofa block_test.py --start [INFO] [runSofa] PluginRepository paths = /builds/build/master/lib:/builds/build/master/plugins [INFO] [runSofa] DataRepository paths = /builds/src/share:/builds/src/examples [INFO] [runSofa] GuiDataRepository paths = /builds/src/applications/projects/runSofa/resources:/builds/src/modules/SofaGuiQt/src/sofa/gui/qt/resources [INFO] [runSofa] Loading automatically plugin list in /builds/build/master/lib/plugin_list.conf [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralVisual.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGraphComponent.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralMeshCollision.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaBoundaryCondition.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralAnimationLoop.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralDeformable.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralEngine.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralExplicitOdeSolver.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralImplicitOdeSolver.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralLinearSolver.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralRigid.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralObjectInteraction.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralSimpleFem.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralTopology.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaTopologyMapping.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaUserInteraction.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaConstraint.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaGeneralLoader.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaSparseSolver.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaPreconditioner.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaHaptics.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaValidation.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaDenseSolver.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaNonUniformFem.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaOpenglVisual.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscTopology.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscExtra.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscForceField.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscEngine.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscSolver.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscFem.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscMapping.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaExporter.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libCImgPlugin.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaMiscCollision.so [INFO] [SofaPython3] Initializing with python version 3.7.5 (default, Nov 7 2019, 10:50:52) [GCC 8.3.0] [INFO] [SofaPython3] Registering a scene loader for [.py, .py3, .pyscn, .py3scn] files. [INFO] [SofaPython3] Shared library name is 'libpython3.7m.so' [INFO] [SofaPython3] Intializing python [INFO] [SofaPython3] Added '/builds/build/master/python3/site-packages' to sys.path [INFO] [SofaPython3] Added '/builds/src/applications/plugins/SofaTest/python' to sys.path [INFO] [SofaPython3] Added '/builds/build/master/lib/python3/site-packages' to sys.path [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSofaPython3.so libGL error: failed to open /dev/dri/card0: Permission denied libGL error: failed to load driver: nouveau Warning: Setting a new default format with a different version or profile after the global shared context is created may cause issues with context sharing. The constructor with a QGLFormat is deprecated, use the regular contructor instead. [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSTLIB.so [INFO] [PluginManager] Loaded plugin: /builds/build/master/lib/libSoftRobots.so [DEPRECATED] [DAGNode(root)] The Node.createChild method is deprecated since sofa 19.06.To remove this warning message, use 'addChild'. [DEPRECATED] [DAGNode(two_cell_robot)] The Node.createChild method is deprecated since sofa 19.06.To remove this warning message, use 'addChild'. [DEPRECATED] [DAGNode(two_cell_robot)] The Node.createChild method is deprecated since sofa 19.06.To remove this warning message, use 'addChild'. [DEPRECATED] [DAGNode(two_cell_robot)] The Node.createChild method is deprecated since sofa 19.06.To remove this warning message, use 'addChild'. [WARNING] [OglModel(OglModel)] Template ExtVec3f incorrect, used Vec3d [INFO] [SceneCheckerVisitor] Validating node "root" with checks: [SceneCheckDuplicatedName, SceneCheckMissingRequiredPlugin, SceneCheckUsingAlias] [WARNING] [SceneCheckMissingRequiredPlugin] This scene is using component defined in plugins but is not importing the required plugins. Your scene may not work on a sofa environment with different pre-loaded plugins. To fix your scene and remove this warning you just need to cut & paste the following lines at the begining of your scene (if it is a .scn): <RequiredPlugin pluginName='SofaConstraint'/> <!-- Needed to use components [FreeMotionAnimationLoop, GenericConstraintSolver, LinearSolverConstraintCorrection, ]--> <RequiredPlugin pluginName='SofaOpenglVisual'/> <!-- Needed to use components [OglModel, ]--> <RequiredPlugin pluginName='SofaSparseSolver'/> <!-- Needed to use components [SparseLDLSolver, ]--> <RequiredPlugin pluginName='SofaTopologyMapping'/> <!-- Needed to use components [Tetra2TriangleTopologicalMapping, ]--> [WARNING] [SceneCheckUsingAlias] This scene is using hard coded aliases. Aliases can be very confusing, use with caution. - MeshTopology: 2 created with alias "Mesh" [INFO] [SceneCheckerVisitor] Finished validating node "root". [WARNING] [SurfacePressureConstraint(SurfacePressureConstraint)] The field named 'visualization' is now deprecated. To remove this warning message, the field 'visualization' should be replaced by the field 'drawPressure'. [WARNING] [SurfacePressureConstraint(SurfacePressureConstraint)] The field named 'showVisuScale' is now deprecated. To remove this warning message, the field 'showVisuScale' should be replaced by the field 'drawScale'. [WARNING] [SurfacePressureConstraint(SurfacePressureConstraint)] The field named 'visualization' is now deprecated. To remove this warning message, the field 'visualization' should be replaced by the field 'drawPressure'. [WARNING] [SurfacePressureConstraint(SurfacePressureConstraint)] The field named 'showVisuScale' is now deprecated. To remove this warning message, the field 'showVisuScale' should be replaced by the field 'drawScale'. 0.6001 terminate called after throwing an instance of 'pybind11::error_already_set' what(): RuntimeError: Unable to cast Python instance to C++ type (compile in debug mode for details) At: block_test.py(145): my_animation /builds/build/master/lib/python3/site-packages/splib/animation/animate.py(88): update /builds/build/master/lib/python3/site-packages/splib/animation/animate.py(133): computeAnimations /builds/build/master/lib/python3/site-packages/splib/animation/animate.py(126): onAnimateBeginEvent ########## SIG 6 - SIGABRT: usually caused by an abort() or assert() ########## -> /builds/build/master/lib/libSofaHelper.so.20.06.99(sofa::helper::BackTrace::dump()+0x20) [0x7feab0516a70] -> /builds/build/master/lib/libSofaHelper.so.20.06.99(sofa::helper::BackTrace::sig(int)+0x358) [0x7feab0517008] -> /lib/x86_64-linux-gnu/libc.so.6(+0x3f040) [0x7feaad853040] -> /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xc7) [0x7feaad852fb7] -> /lib/x86_64-linux-gnu/libc.so.6(abort+0x141) [0x7feaad854921] -> /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0x8c957) [0x7feaae466957] -> /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0x92ae6) [0x7feaae46cae6] -> /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0x92b21) [0x7feaae46cb21] -> /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0x92d54) [0x7feaae46cd54] -> /builds/build/master/lib/python3/site-packages/Sofa/Core.cpython-37m-x86_64-linux-gnu.so(+0x9bf75) [0x7fea6adddf75] -> /builds/build/master/lib/python3/site-packages/Sofa/Core.cpython-37m-x86_64-linux-gnu.so(+0x9b1ff) [0x7fea6addd1ff] -> /builds/build/master/lib/python3/site-packages/Sofa/Core.cpython-37m-x86_64-linux-gnu.so(+0x9b5ab) [0x7fea6addd5ab] -> /builds/build/master/lib/libSofaSimulationCore.so.20.06.99(void sofa::simulation::Visitor::for_each<sofa::simulation::PropagateEventVisitor, sofa::simulation::Node, sofa::simulation::Node::Sequence<sofa::core::objectmodel::BaseObject, true>, sofa::core::objectmodel::BaseObject>(sofa::simulation::PropagateEventVisitor*, sofa::simulation::Node*, sofa::simulation::Node::Sequence<sofa::core::objectmodel::BaseObject, true> const&, void (sofa::simulation::PropagateEventVisitor::*)(sofa::simulation::Node*, sofa::core::objectmodel::BaseObject*))+0xf9) [0x7feab1aa5519] -> /builds/build/master/lib/libSofaSimulationCore.so.20.06.99(sofa::simulation::PropagateEventVisitor::processNodeTopDown(sofa::simulation::Node*)+0x20) [0x7feab1aa53d0] -> /builds/build/master/lib/libSofaSimulationGraph.so.20.06.99(sofa::simulation::graph::DAGNode::executeVisitorTopDown(sofa::simulation::Visitor*, std::__cxx11::list<sofa::simulation::graph::DAGNode*, std::allocator<sofa::simulation::graph::DAGNode*> >&, std::map<sofa::simulation::graph::DAGNode*, sofa::simulation::graph::DAGNode::StatusStruct, std::less<sofa::simulation::graph::DAGNode*>, std::allocator<std::pair<sofa::simulation::graph::DAGNode* const, sofa::simulation::graph::DAGNode::StatusStruct> > >&, sofa::simulation::graph::DAGNode*)+0x392) [0x7feac3038122] -> /builds/build/master/lib/libSofaSimulationGraph.so.20.06.99(sofa::simulation::graph::DAGNode::doExecuteVisitor(sofa::simulation::Visitor*, bool)+0x19d) [0x7feac303761d] -> /builds/build/master/lib/libSofaConstraint.so(sofa::component::animationloop::FreeMotionAnimationLoop::step(sofa::core::ExecParams const*, double)+0xb97) [0x7feaa2bd91b7] -> /builds/build/master/lib/libSofaSimulationCore.so.20.06.99(sofa::simulation::Simulation::animate(sofa::simulation::Node*, double)+0x58) [0x7feab1aa71d8] -> /builds/build/master/lib/libSofaGuiQt.so.20.06.99(sofa::gui::qt::RealGUI::step()+0xca) [0x7feac26f16da] -> /opt/qt512/lib/libQt5Core.so.5(QMetaObject::activate(QObject*, int, int, void**)+0x865) [0x7feab57523f5] -> /opt/qt512/lib/libQt5Core.so.5(QTimer::timeout(QTimer::QPrivateSignal)+0x37) [0x7feab575f2d7] -> /opt/qt512/lib/libQt5Core.so.5(QTimer::timerEvent(QTimerEvent*)+0x28) [0x7feab575f638] -> /opt/qt512/lib/libQt5Core.so.5(QObject::event(QEvent*)+0x9b) [0x7feab5752f1b] -> /opt/qt512/lib/libQt5Widgets.so.5(QApplicationPrivate::notify_helper(QObject*, QEvent*)+0x9c) [0x7feab61cee4c] -> /opt/qt512/lib/libQt5Widgets.so.5(QApplication::notify(QObject*, QEvent*)+0x2f0) [0x7feab61d6430] -> /opt/qt512/lib/libQt5Core.so.5(QCoreApplication::notifyInternal2(QObject*, QEvent*)+0x118) [0x7feab57227f8] -> /opt/qt512/lib/libQt5Core.so.5(QTimerInfoList::activateTimers()+0x409) [0x7feab577ed99] -> /opt/qt512/lib/libQt5Core.so.5(+0x2ef561) [0x7feab577f561] -> /usr/lib/x86_64-linux-gnu/libglib-2.0.so.0(g_main_context_dispatch+0x2e7) [0x7feaa92b5417] -> /usr/lib/x86_64-linux-gnu/libglib-2.0.so.0(+0x4c650) [0x7feaa92b5650] -> /usr/lib/x86_64-linux-gnu/libglib-2.0.so.0(g_main_context_iteration+0x2c) [0x7feaa92b56dc] -> /opt/qt512/lib/libQt5Core.so.5(QEventDispatcherGlib::processEvents(QFlags<QEventLoop::ProcessEventsFlag>)+0x5f) [0x7feab577f92f] -> /opt/qt512/lib/libQt5Core.so.5(QEventLoop::exec(QFlags<QEventLoop::ProcessEventsFlag>)+0x13a) [0x7feab5720a4a] -> /opt/qt512/lib/libQt5Core.so.5(QCoreApplication::exec()+0x90) [0x7feab5729c50] -> /builds/build/master/lib/libSofaGuiQt.so.20.06.99(sofa::gui::qt::RealGUI::mainLoop()+0x162) [0x7feac26e7bd2] -> /builds/build/master/lib/libSofaGuiCommon.so.20.06.99(sofa::gui::GUIManager::MainLoop(boost::intrusive_ptr<sofa::simulation::Node>, char const*)+0x60) [0x7feac221ed20] -> runSofa() [0x413740] -> /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe7) [0x7feaad835bf7] -> runSofa() [0x40ea2a] Aborted (core dumped)
16 December 2020 at 06:24 in reply to: [SOLVED] How to make a PythonScript controller with SofaPython3 #18033ArthurBlockedDear @Pasquale94 ,
I am having the same issue and I was wondering if you would post your solution?
I used to change the pressures in 2.7 with:
self.pressureConstraint1.findData(‘value’).value = str(pressureValue)but now when I try to do this with SofaPython3, I get an error like this:
terminate called after throwing an instance of ‘pybind11::error_already_set’
what(): RuntimeError: Unable to cast Python instance to C++ type (compile in debug mode for details)My exact code is posted below: see line 145 in the animate function.
Best,
Arthurimport Sofa import SofaRuntime import sys import os #from stlib3.physics.constraints import FixedBox from stlib3.scene import Scene from splib.animation import AnimationManager, addAnimation #from elasticmaterialobject import ElasticMaterialObject #from stlib3.physics.deformable.elasticmaterialobject import ElasticMaterialObject #from softrobots.actuators import PneumaticCavity import time import math import numpy as np import timeit path = os.path.dirname(os.path.abspath(__file__)) + '/' meshpath = path+"mesh/" # scene helper function, defining materials and constraints def createSceneReal(rootNode, dt): # this sets gravity and dt in the simulator rootNode = Scene(rootNode, gravity=[0.0, -0.0, 0], dt=dt) # marks a required plugin and some visual style stuff rootNode.addObject('RequiredPlugin', pluginName='SoftRobots') rootNode.addObject('VisualStyle', displayFlags='showVisualModels hideBehaviorModels showCollisionModels hideBoundingCollisionModels hideForceFields showInteractionForceFields hideWireframe') # animation loop used for legrangian constraints rootNode.addObject('FreeMotionAnimationLoop') # linear solver (with parameters from example file) rootNode.addObject('GenericConstraintSolver', name='gencs', maxIterations='500', printLog='0', tolerance='0.0000001') # set color of background, just visual style rootNode.addObject('BackgroundSetting', color='0 0.168627 0.211765') # YM of the material. All in kg / m / s volumeMeshFileName=meshpath+"two_cell_robot_solid.msh" name="two_cell_robot" rotation=[0.0, 0.0, 0.0] translation=[0.0, 0.0, 0.0] scale=[1.0, 1.0, 1.0] surfaceMeshFileName=None collisionMesh=None withConstrain=True surfaceColor=[1.0, 1.0, 1.0] poissonRatio=0.3 youngModulus=1800 totalMass=1.0 solver=None # elestic material from prefab '''two_cell_robot = ElasticMaterialObject(name="two_cell_robot", attachedTo=rootNode, volumeMeshFileName=meshpath+"two_cell_robot_solid.msh", surfaceMeshFileName=None, youngModulus=YoungModulus, withConstrain=True, totalMass=1.0, translation=None, rotaiton=None, scale=[1.,1.0,1.0], collisionMesh=None, surfaceColor=None) ''' two_cell_robot = rootNode.createChild( 'two_cell_robot' ) two_cell_robot.addObject('MeshGmshLoader', name='loader', filename=volumeMeshFileName, rotation=rotation, translation=translation, scale3d=scale) two_cell_robot.addObject( 'EulerImplicitSolver', name='integration') two_cell_robot.addObject( 'SparseLDLSolver', name="solver") two_cell_robot.addObject( 'TetrahedronSetTopologyContainer', src="@loader", name="container") two_cell_robot.addObject( 'MechanicalObject', template='Vec3d', name='dofs') #topology="@container", two_cell_robot.addObject( 'UniformMass', totalMass=totalMass, name='mass') two_cell_robot.addObject( 'TetrahedronFEMForceField', template='Vec3d', method='large', name='forcefield', poissonRatio=poissonRatio, youngModulus=youngModulus) two_cell_robot.addObject( 'LinearSolverConstraintCorrection', template='Vec3d', solverName='solver') #two_cell_robot.addObject( 'FixedConstraint', template='Vec3d', topology="@container" ) #vm = two_cell_robot.createChild( 'VisualModel' ) #vm.addObject( 'MeshSTLLoader', template='') #vm.addObject( 'OglModel', template='Vec3d', topology="@/two_cell_robot/container" ) #vm.addObject( 'BarycentricMapping', template='Vec3d,Vec3d', input="@../" , output="@./" ) # impose the constraints TODO: get these constraints so I can add gravity. #two_cell_robot.addObject("FixedConstraint", indices=fixed_const_str) # create the two actuators cavity1 = two_cell_robot.createChild('cavity1') cavity1.addObject('MeshSTLLoader', name='loader', filename=meshpath + "two_cell_robot_cell1.stl", translation="0 0 0") cavity1.addObject('Mesh', src='@loader', name='topo') cavity1.addObject('MechanicalObject', name='cavity') cavity1.addObject('SurfacePressureConstraint', name="SurfacePressureConstraint", template='Vec3d', value="0.6001", triangles='@topo.triangles', visualization='0', showVisuScale='0.0002', valueType="pressure") cavity1.addObject('BarycentricMapping', name='mapping', mapForces='false', mapMasses='false') cavity2 = two_cell_robot.createChild('cavity2') cavity2.addObject('MeshSTLLoader', name='loader', filename=meshpath + "two_cell_robot_cell2.stl", translation="0 0 0") cavity2.addObject('Mesh', src='@loader', name='topo') cavity2.addObject('MechanicalObject', name='cavity') cavity2.addObject('SurfacePressureConstraint', name="SurfacePressureConstraint", template='Vec3d', value="0.0001", triangles='@topo.triangles', visualization='0', showVisuScale='0.0002', valueType="pressure") cavity2.addObject('BarycentricMapping', name='mapping', mapForces='false', mapMasses='false') # two_cell_robot visualization two_cell_robotVisu = two_cell_robot.createChild('visu') two_cell_robotVisu.addObject('TriangleSetTopologyContainer', name='container') two_cell_robotVisu.addObject('TriangleSetTopologyModifier') #two_cell_robotVisu.addObject('TriangleSetTopologyAlgorithms', template='Vec3d') two_cell_robotVisu.addObject('TriangleSetGeometryAlgorithms', template='Vec3d') two_cell_robotVisu.addObject('Tetra2TriangleTopologicalMapping', name='Mapping', input="@../container", output="@container") two_cell_robotVisu.addObject('OglModel', template='ExtVec3f', color='0.3 0.2 0.2 0.6', translation=translation) two_cell_robotVisu.addObject('IdentityMapping') return two_cell_robot # "Main" function that runSofa uses to build the scene. def createScene(rootNode): dt = 0.001 # set the time step for the simulator # set length scale ''' # information about the output. info_arr = np.array([float(length_scale), 0, dt, num_nodes]) print "info array ", info_arr print "number of nodes", num_nodes, " num end nodes ", len(fixed_const_lst), " num mid nodes ", len(middle_nodes_lst) ''' # simulation timer start = timeit.default_timer() #animation function called at each step def my_animation(target, factor): factor = factor*2*np.pi pressureValue1 = target["two_cell_robot.cavity1.SurfacePressureConstraint.value"].getValueString() print(pressureValue1) pressureValue1 = float(pressureValue1) target.two_cell_robot.cavity1.SurfacePressureConstraint.findData('value').value = str(0.1) print(dir(target.two_cell_robot.cavity1.SurfacePressureConstraint)) print(target.two_cell_robot.cavity1.SurfacePressureConstraint.pressure.value) target.two_cell_robot.cavity1.SurfacePressureConstraint.findData('value').value = str(10.0) print(factor) # the exit func is called when duration of time has elapsed, it marks the simulation time # saves it, and saves the collected data to an array. And exits the simulation with sys exit def ExitFunc(target, factor): # save the various data. runtime = timeit.default_timer() - start print("runtime", runtime) sys.exit(0) def getObject(self, name): return name # this is the Sofa animation function we pass it our animation function # and along with the exit function. createSceneReal(rootNode, dt) AnimationManager(rootNode) addAnimation(my_animation, {"target": rootNode}, duration=2.0, mode="once", onDone=ExitFunc) return rootNode
ArthurBlockedOn a related note, another question for @olivier-goury and @felixvanneste: will Model Order Reduction be compatible with python3 in the near future?
EDIT: My original follow up has seemed to disappear after I tried to edit it. I have posted it below.
Hello @olivier-goury @felixvanneste,
I found your contact info on the MOR github page and I was wondering if you could help me out here.
I have changed my setup a bit but I am still getting the exact same error. (my code can be found here https://github.com/ripl-ttic/SofaFramework-Docker/tree/problem_illustration) [NB: it is not the master branch]
About: I am using ubuntu 18.04 and a set of compatible Sofa/STLIB/SoftRobots, (I couldn’t find a version of STLIB and SoftRobots that was compatible with 20.06 so I am using verions that were compatible with the master branch of sofa)
My environment is fully specified in the Docker file in this git repo where I have specified the commit of each library package I am using. https://github.com/ripl-ttic/SofaFramework-Docker/tree/problem_illustration/Dockerfile
I chose to do this so I could run STLIB and SoftRobots in a stable way, if there is a way to run STLIB/SoftRobots/MOR with Sofa20.06 I could not find it.
To run the code without docker you will need to copy the DiskModelOrderReduction.ipynb file from /workdir/MOR_test and run that.
see also the readme.md on that repo for instructions on running the code.
Note: in order to run jupyter notebooks in docker you need to have x11 forwarding, I use x-docker to do this.
ArthurBlockedHello @olivier-goury @felixvanneste,
I found your contact info on the MOR github page and I was wondering if you could help me out here.
I have changed my setup a bit but I am still getting the exact same error. (my code and files can be found here https://github.com/ripl-ttic/SofaFramework-Docker/tree/problem_illustration). [NB: the branch is not the master branch]
About: I am using ubuntu 18.04 and a set of compatible Sofa/STLIB/SoftRobots from this fall, (I couldn’t find a version of STLIB and SoftRobots that was compatible with 20.06 so I am using verions that were compatible with the master branch of sofa)
My environment is fully specified in the Docker file in this git repo where I have specified the commit of each library package I am using. https://github.com/ripl-ttic/SofaFramework-Docker/tree/problem_illustration/Dockerfile
I chose to do this so I could run STLIB and SoftRobots in a stable way, if there is a way to run STLIB/SoftRobots/MOR with Sofa20.06 I could not find it.
To run the code without docker you will need to copy the DiskModelOrderReduction.ipynb file from /workdir/MOR_test and run that.
Note: in order to run jupyter notebooks in docker you need to have x11 forwarding, I use x-docker to do this.
ArthurBlockedArthurBlockedHi @Hugo,
How would one do this in python, say within an animate function:
“I never captured a screenshot from Python, but if you mimic keyboard action : ALT+C it should work. ”
I would like to record video using v20.06 (with python2 scripts). And if I can mimic keyboard input it should be as easy as mimicking a “v” so this sounds ideal.
Best,
ArthurEDIT:
Working with Sofa v20.12 and SofaPython3 I found a solution. (Currently the pygame example code isn’t compatible, but this worked for me).
# encoding: utf-8 # !/usr/bin/python3 import Sofa import SofaRuntime import Sofa.Gui class scene_interface: """Scene_interface provides step and reset methods""" def __init__(self, dt=0.01, max_steps=300): self.dt = dt # max_steps, how long the simulator should run. Total length: dt*max_steps self.max_steps = max_steps # root node in the simulator self.root = None # the current step in the simulation self.current_step = 0 # Register all the common component in the factory. SofaRuntime.importPlugin('SofaOpenglVisual') SofaRuntime.importPlugin("SofaComponentAll") self.root = Sofa.Core.Node("myroot") ### create some objects to observe self.place_objects_in_scene(self.root) # place light and a camera self.root.addObject("LightManager") self.root.addObject("SpotLight", position=[0,10,0], direction=[0,-1,0]) self.root.addObject("InteractiveCamera", name="camera", position=[0,10, 0], lookAt=[0,0,0], distance=37, fieldOfView=45, zNear=0.63, zFar=55.69) # start the simulator Sofa.Simulation.init(self.root) # start the gui Sofa.Gui.GUIManager.Init("Recorded_Episode", "qt") Sofa.Gui.GUIManager.createGUI(self.root, __file__) def place_objects_in_scene(self, root): ### these are just some things that stay still and move around # so you know the animation is actually happening root.gravity = [0, -1., 0] root.addObject("VisualStyle", displayFlags="showWireframe showBehaviorModels showAll") root.addObject("MeshGmshLoader", name="meshLoaderCoarse", filename="mesh/liver.msh") root.addObject("MeshObjLoader", name="meshLoaderFine", filename="mesh/liver-smooth.obj") root.addObject("EulerImplicitSolver") root.addObject("CGLinearSolver", iterations="200", tolerance="1e-09", threshold="1e-09") liver = root.addChild("liver") liver.addObject("TetrahedronSetTopologyContainer", name="topo", src="@../meshLoaderCoarse" ) liver.addObject("TetrahedronSetGeometryAlgorithms", template="Vec3d", name="GeomAlgo") liver.addObject("MechanicalObject", template="Vec3d", name="MechanicalModel", showObject="1", showObjectScale="3") liver.addObject("TetrahedronFEMForceField", name="fem", youngModulus="1000", poissonRatio="0.4", method="large") liver.addObject("MeshMatrixMass", massDensity="1") liver.addObject("FixedConstraint", indices="2 3 50") def step(self): # step through time # this steps the simulation Sofa.Simulation.animate(self.root, self.dt) # just to keep track of where we are self.current_step += 1 ### A better example would also show how to read and edit values through scripts # which would likely be useful if you are running without a normal gui # return true if done return self.current_step >= self.max_steps # save a screenshot from the position of where we set the camera above def record_frame(self, filename): Sofa.Gui.GUIManager.SaveScreenshot(filename) def main(): a = scene_interface() done = False while not done: factor = a.current_step done = a.step() a.record_frame(str(factor) + ".png") if __name__ == '__main__': main()
For reference I built with
SofaPython3 commit: 184206f126acf0c5d45416fc23cb37baf1971fa5
and Sofa commit:184206f126acf0c5d45416fc23cb37baf1971fa5ArthurBlockedThanks Hugo,
I think Lagrange multipliers are the solution to my issue that will work for what I want to do down the line.
Thanks!
Arthur
-
AuthorPosts