code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
'''
Created on 2009-12-02
@author: beaudoin
'''
import wx, PyUtils, GLUtils
from Handle import BaseHandle, Handle
from PosableCharacter import PosableCharacter
from ToolSet import ToolSet
from EditorWindow import EditorWindow
from MathLib import Vector3d, Point3d, Trajectory3dv
class Model(object):
def __init__(self, nbEditors = 5):
self._nbEditors = nbEditors
app = wx.GetApp()
app.addControllerObserver(self)
app = wx.GetApp()
glCanvas = app.getGLCanvas()
self._container = glCanvas.addGLUITool( GLUtils.GLUIContainer )
self._sizer = GLUtils.GLUIBoxSizer(GLUtils.GLUI_HORIZONTAL)
self._container.setSizer(self._sizer)
self._optionsObservable = PyUtils.Observable()
self._create()
self._toolSet = ToolSet(app.getToolPanel(), self)
def addOptionsObserver(self, observer):
"""Adds an observer for the options of the style edition model."""
self._optionsObservable.addObserver(observer)
def displayInterface(self, display):
"""Indicates wheter the interface for editing style should be displayed."""
if display != self.getDisplayInterface() :
self._container.setVisible(display)
self._container.getParent().layout()
self._optionsObservable.notifyObservers()
def getDisplayInterface(self):
"""Indicates wheter the interface for editing style is currently displayed."""
return self._container.isVisible()
def update(self, observable, data= None):
"""Called whenever something important is modified, recreate everything."""
self._destroy()
self._create()
def _destroy(self):
self._handles = []
self._editors = []
self._container.detachAllChildren()
self._container.getParent().layout()
def _create(self):
"""Creates the basic model class for the simple keyframe editor. Characters are always forced to left stance."""
app = wx.GetApp()
try:
self._controller = app.getController(0)
except IndexError:
return
self._character = self._controller.getCharacter()
handlesSide = []
handlesFront = []
self._handles = []
handlesSide.append( self._addHandle( 'SWING_Shoulder', 2, 'SWING_Elbow', minValue = -3.14, maxValue = 3.14 ) )
handlesSide.append( self._addHandle( 'STANCE_Shoulder', 2, 'STANCE_Elbow', minValue = -3.14, maxValue = 3.14 ) )
handlesSide.append( self._addHandle( 'SWING_Elbow', 0, reverseOppositeJoint = True, minValue = -2.8, maxValue = 0 ) )
handlesSide.append( self._addHandle( 'STANCE_Elbow', 0, type = 'reverseCircular', reverseOppositeJoint = True,minValue = 0, maxValue = 2.8 ) )
handlesSide.append( self._addHandle( 'SWING_Ankle', 0, 'SWING_ToeJoint' ) )
handlesSide.append( self._addHandle( 'STANCE_Ankle', 0, 'STANCE_ToeJoint' ) )
handlesSide.append( self._addHandle( 'pelvis_lowerback', 2, 'lowerback_torso', minValue = -1.2, maxValue = 1.2 ) )
handlesSide.append( self._addHandle( 'lowerback_torso', 2, 'torso_head', minValue = -1.2, maxValue = 1.2 ) )
handlesSide.append( self._addHandle( 'torso_head', 2, minValue = -1.2, maxValue = 1.2 ) )
handlesFront.append( self._addHandle( 'SWING_Shoulder', 1, 'SWING_Elbow', type = 'reverseCircular', reverseOppositeJoint = True, minValue = -2, maxValue = 2 ) )
handlesFront.append( self._addHandle( 'STANCE_Shoulder', 1, 'STANCE_Elbow', type = 'reverseCircular', reverseOppositeJoint = True, minValue = -2, maxValue = 2 ) )
handlesFront.append( self._addHandle( 'SWING_Shoulder', 0, type = 'reversePerpendicular', minValue = -3.3, maxValue = 3.3 ) )
handlesFront.append( self._addHandle( 'STANCE_Shoulder', 0, type = 'perpendicular', minValue = -3.3, maxValue = 3.3 ) )
handlesFront.append( self._addHandle( 'pelvis_lowerback', 1, 'lowerback_torso', reverseOppositeJoint = True, minValue = -1.2, maxValue = 1.2 ) )
handlesFront.append( self._addHandle( 'lowerback_torso', 1, 'torso_head', reverseOppositeJoint = True, minValue = -1.2, maxValue = 1.2 ) )
handlesFront.append( self._addHandle( 'torso_head', 1, reverseOppositeJoint = True, minValue = -1.2, maxValue = 1.2 ) )
stanceKneeHandle = Handle( self._controller, 'STANCE_Knee', 0, minValue = 0.1, maxValue = 2.2 )
self._handles.append( stanceKneeHandle )
swingFootHandleSagittal = BaseHandle( self._controller.getSwingFootTrajectoryDeltaSagittal() )
swingFootHandleCoronal = BaseHandle( self._controller.getSwingFootTrajectoryDeltaCoronal() )
swingFootHandleHeight = BaseHandle( self._controller.getSwingFootTrajectoryDeltaHeight() )
self._handles.append( swingFootHandleSagittal )
self._handles.append( swingFootHandleCoronal )
self._handles.append( swingFootHandleHeight )
self._editors = []
self._times = [ i / float(self._nbEditors-1) for i in range(self._nbEditors) ]
for handle in self._handles:
handle.forceKeyframesAt([0,1],self._times)
for handle in self._handles:
handle.enforceSymmetry()
stanceFootToSwingFootTrajectory = Trajectory3dv()
stanceFootToSwingFootTrajectory.addKnot(0,Vector3d(-0.2,0,-0.4))
stanceFootToSwingFootTrajectory.addKnot(0.5,Vector3d(-0.2,0.125,0))
stanceFootToSwingFootTrajectory.addKnot(1,Vector3d(-0.2,0,0.4))
glCanvasSize = wx.GetApp().getGLCanvas().GetSize()
minWidth = glCanvasSize.x / self._nbEditors - 50
minHeight = glCanvasSize.y / 2
for i, time in enumerate(self._times) :
posableCharacter = PosableCharacter(PyUtils.copy(self._character), self._controller)
if i == 0 or i == self._nbEditors-1:
checkBoxVisible = False
else :
checkBoxVisible = True
editor = EditorWindow( self._container,
posableCharacter = posableCharacter,
handlesSide = handlesSide,
handlesFront = handlesFront,
stanceKneeHandle = stanceKneeHandle,
swingFootHandleSagittal = swingFootHandleSagittal,
swingFootHandleCoronal = swingFootHandleCoronal,
swingFootHandleHeight = swingFootHandleHeight,
time = time,
controller = self._controller,
stanceFootToSwingFootTrajectory = stanceFootToSwingFootTrajectory,
minWidth = minWidth, minHeight = minHeight,
checkBoxVisible = checkBoxVisible )
functor = SetKeyframeVisibilityFunctor(self,i)
editor.addCheckBoxCallback( functor.execute )
self._sizer.add(editor, 0, GLUtils.GLUI_EXPAND )
self._editors.append(editor)
self._container.getParent().layout()
def setKeyframeVisibility(self, i, visible):
"""Sets wheter the keyframes of the editor at index i should be visible/editable or not."""
if visible == self.isKeyframeVisible(i) : return
time = self._times[i]
if visible:
for handle in self._handles:
handle.addKeyframeAt(time)
else:
for handle in self._handles:
index = handle.getIndexForTime(time)
if index is not None :
handle.removeKeyframe( index )
def isKeyframeVisible(self, i):
"""Returns true if the keyframes of editor at index i are visible/editable."""
time = self._times[i]
return self._handles[0].hasKeyframeAtTime(time)
def getHandles(self):
"""Return the list of handles."""
return self._handles
def _updateKeyframes(self):
"""Make sure the keyframes are at the right location."""
self._keyframeTimes = [ time for (time, state) in zip(self._times, self._keyframeVisible) if state ]
def _addHandle(self, jointName, componentIndex, handleInfo = None, type = 'circular', reverseOppositeJoint = False, minValue = -10000, maxValue = 10000 ):
"""
Adds a handle to the model.
handleInfo can be the name of an joint where the handle should be located
"""
oppositeJointName = jointName.replace("STANCE_","TEMP_").replace("SWING_","STANCE_").replace("TEMP_","SWING_")
try:
handleJointName = handleInfo.replace("STANCE_","l").replace("SWING_","r")
posInChild = self._character.getJointByName(handleJointName).getParentJointPosition()
except AttributeError:
posInChild = Point3d(0,0,0)
handle = Handle(self._controller, jointName, componentIndex, type, posInChild, oppositeJointName, reverseOppositeJoint, minValue, maxValue )
self._handles.append( handle )
return handle
class SetKeyframeVisibilityFunctor(object):
def __init__(self,model,i):
self._model = model
self._i = i
def execute(self,state):
self._model.setKeyframeVisibility(self._i,state)
| Python |
from Model import Model
| Python |
'''
Created on 2009-11-23
@author: beaudoin
'''
import UI, wx
class ToolSet(UI.ToolSets.ToolsetBase):
def __init__(self, toolPanel, model):
"""Adds a tool set for the keyframe editor to a toolpanel."""
super(ToolSet,self).__init__()
self._toolPanel = toolPanel
self._toolSet = toolPanel.createToolSet( "Style Editor" )
self.addOption( "Edit style", model.getDisplayInterface, model.displayInterface )
# Add this as an observer
model.addOptionsObserver(self)
# Initial update
self.update() | Python |
'''
Created on 2009-09-08
@author: beaudoin
Contains a abstract syntactic tree visitor for printing
nested function calls in a nice way. Used for cleaning-up
output of the serialize method.
See the python standard ast module for details.
'''
import ast
class Fancify( ast.NodeVisitor ):
def __init__(self):
super( Fancify, self ).__init__()
self._tabLevel = 0
self._spacesPerTab = 4
def visitListElements(self, elements):
"""Inserts commas between elements and will go multi-line if needed."""
# Try single line
content = ", ".join( elements ) + " "
nbCR = content.count('\n')
long = len(content) > 100 or nbCR > 0
veryLong = long and nbCR > 40
if long:
# Too long, go multi-line
spacer = "\n" + " " * (self._tabLevel * self._spacesPerTab)
if veryLong : spacer = "\n" + spacer
content = spacer
spacer = "," + spacer
content += spacer.join( elements )
if veryLong :
content += "\n" + " " * ((self._tabLevel-1) * self._spacesPerTab)
else :
content += " "
return content
def visitListType(self, list):
"""Visits anything that looks like a list of AST nodes."""
self._tabLevel += 1
elements = map( self.visit, list )
result = self.visitListElements( elements )
self._tabLevel -= 1
return result
def visit_Call(self, node):
"""Fancify a function a call or an object creation."""
assert node.starargs is None and node.kwargs is None, "Star arguments not supported by fancify"
return self.visit(node.func) + "( " + self.visitListType( node.args + node.keywords ) + ")"
def visit_List(self, node):
"""Fancify a list."""
return "[ " + self.visitListType( node.elts ) + "]"
def visit_Dict(self, node):
"""Fancify a dictionary."""
self._tabLevel += 1
keys = map( self.visit, node.keys )
values = map( self.visit, node.values )
elements = []
for key, value in zip(keys,values):
elements.append( key + ' : ' + value )
result = "{ " + self.visitListElements( elements ) + "}"
self._tabLevel -= 1
return result
def visit_Tuple(self, node):
"""Fancify a tuple."""
return "( " + self.visitListType( node.elts ) + ")"
def visit_Name(self, node):
"""Visits a simple identifier"""
return node.id
def visit_Attribute(self, node):
"""Visits an 'object.attribute' node"""
return self.visit(node.value) + '.' + node.attr
def visit_keyword(self, node):
"""Fancify a keyword within a function a call or an object creation."""
return str(node.arg) + " = " + self.visit( node.value )
def visit_Str(self, node):
"""Fancify a simple string"""
return repr(node.s)
def visit_Num(self, node):
"""Fancify a number"""
return str(node.n)
def generic_visit(self, node):
return "\n".join( map( self.visit, ast.iter_child_nodes(node) ) )
| Python |
'''
Created on 2009-10-06
@author: beaudoin
A collection of useful functions for creating stock rigid bodies
'''
import Physics, MathLib, Mesh, PyUtils, math
from MathLib import Point3d, Vector3d
def createBox( size=(1,1,1), colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create a rigid body for a box of the specified size. Other rigid body parameters can be specified with keyword arguments, look at
App.Proxys.RigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, size[0]*size[1]*size[2] )
from App import Proxys
proxy = Proxys.RigidBody( **kwargs )
return _createBox( proxy, size, colour, moiScale, withMesh )
def createArticulatedBox( size=(1,1,1), colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create an articulated rigid body for a box of the specified size. Other articulated rigid body parameters can be specified with keyword arguments, look at
App.Proxys.ArticulatedRigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If mass is negative, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, size[0]*size[1]*size[2] )
from App import Proxys
proxy = Proxys.ArticulatedRigidBody( **kwargs )
return _createBox( proxy, size, colour, moiScale, withMesh )
def createTaperedBox( size=(1,1,1), colour=(0.6,0.6,0.6), exponentBottom = 5, exponentTop = 5, exponentSide = 5, moiScale = 1, withMesh = True, **kwargs ):
"""
Create a rigid body for a box of the specified size with tapered ends. Other rigid body parameters can be specified with keyword arguments, look at
App.Proxys.RigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, size[0]*size[1]*size[2] )
from App import Proxys
proxy = Proxys.RigidBody( **kwargs )
return _createTaperedBox( proxy, size, colour, exponentBottom, exponentTop, exponentSide, moiScale, withMesh )
def createArticulatedTaperedBox( size=(1,1,1), colour=(0.6,0.6,0.6), exponentBottom = 5, exponentTop = 5, exponentSide = 5, moiScale = 1, withMesh = True, **kwargs ):
"""
Create an articulated rigid body for a box of the specified size with tapered ends. Other articulated rigid body parameters can be specified with keyword arguments, look at
App.Proxys.ArticulatedRigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If mass is negative, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, size[0]*size[1]*size[2] )
from App import Proxys
proxy = Proxys.ArticulatedRigidBody( **kwargs )
return _createTaperedBox( proxy, size, colour, exponentBottom, exponentTop, exponentSide, moiScale, withMesh )
def createEllipsoid( radius=(1,1,1), colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create a rigid body for an ellipsoid with the specified attributes . Other rigid body parameters can be specified with keyword arguments, look at
App.Proxys.RigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, 4.0/3.0 * math.pi*radius*radius*radius )
from App import Proxys
proxy = Proxys.RigidBody( **kwargs )
return _createEllipsoid( proxy, radius, colour, moiScale, withMesh )
def createArticulatedEllipsoid( radius=(1,1,1), colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create an articulated rigid body for an ellipsoid with the specified attributes . Other rigid body parameters can be specified with keyword arguments, look at
App.Proxys.RigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, 4.0/3.0 * math.pi*radius[0]*radius[1]*radius[2] )
from App import Proxys
proxy = Proxys.ArticulatedRigidBody( **kwargs )
return _createEllipsoid( proxy, radius, colour, moiScale, withMesh )
def createCylinder( axis=1, basePos=-1, tipPos=1, radius=1, colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create a rigid body for a cylinder with the specified attributes (axis is 0:x, 1:y, 2:z). Other rigid body parameters can be specified with keyword arguments, look at
App.Proxys.RigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, math.pi*radius*radius*math.fabs(tipPos-basePos) )
from App import Proxys
proxy = Proxys.RigidBody( **kwargs )
return _createCylinder( proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh )
def createArticulatedCylinder( axis=1, basePos=-1, tipPos=1, radius=1, colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create an articulated rigid body for a cylinder with the specified attributes (axis is 0:x, 1:y, 2:z). Other articulated rigid body parameters can be specified with keyword arguments, look at
App.Proxys.ArticulatedRigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, math.pi*radius*radius*math.fabs(tipPos-basePos) )
from App import Proxys
proxy = Proxys.ArticulatedRigidBody( **kwargs )
return _createCylinder( proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh )
def createCone( axis=1, basePos=-1, tipPos=1, radius=1, colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create a rigid body for a cone with the specified attributes (axis is 0:x, 1:y, 2:z). Other rigid body parameters can be specified with keyword arguments, look at
App.Proxys.RigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, math.pi*radius*radius*math.fabs(tipPos-basePos) )
from App import Proxys
proxy = Proxys.RigidBody( **kwargs )
return _createCone( proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh )
def createArticulatedCone( axis=1, basePos=-1, tipPos=1, radius=1, colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create an articulated rigid body for a cone with the specified attributes (axis is 0:x, 1:y, 2:z). Other articulated rigid body parameters can be specified with keyword arguments, look at
App.Proxys.ArticulatedRigidBody for more details on available arguments. The following arguments will not be used:
meshes, moi, cdps.
If a negative mass parameter is specified, it will be scaled by the box volume and made positive.
"""
_fixMass( kwargs, math.pi*radius*radius*math.fabs(tipPos-basePos) )
from App import Proxys
proxy = Proxys.ArticulatedRigidBody( **kwargs )
return _createCone( proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh )
def _fixMass( kwargs, volume ):
"""
Private function.
If kwargs['mass'] is defined and negative, it is made positive and scaled by volume. (Considered as density.)
"""
try:
if kwargs['mass'] < 0 :
kwargs['mass'] = -kwargs['mass'] * volume
except KeyError:
pass
def _createBox( proxy, size, colour, moiScale, withMesh ):
"""
Private function.
Use createBox() or createArticulatedBox() instead.
"""
# Mesh and cdps will be set manually
proxy.meshes = None
proxy.cdps = None
# Compute box moi
size = PyUtils.toVector3d(size)
proxy.moi = MathLib.Vector3d( size.y*size.y + size.z*size.z,
size.x*size.x + size.z*size.z,
size.x*size.x + size.y*size.y, ) * 1.0/12.0 * proxy.mass * moiScale
box = proxy.createAndFillObject()
cdp = Physics.BoxCDP()
halfSize = PyUtils.toVector3d(size) * 0.5
cdp.setPoint1( MathLib.Point3d( halfSize * -1 ) )
cdp.setPoint2( MathLib.Point3d( halfSize ) )
box.addCollisionDetectionPrimitive( cdp )
if withMesh:
mesh = Mesh.createBox( size = size, colour = colour )
box.addMesh(mesh)
return box
def _createTaperedBox( proxy, size, colour, exponentBottom, exponentTop, exponentSide, moiScale, withMesh ):
"""
Private function.
Use createTaperedBox() or createArticulatedTaperedBox() instead.
"""
taperedBox = _createBox( proxy, size, colour, moiScale = moiScale, withMesh = False )
if withMesh:
mesh = Mesh.createEllipsoid(position=(0,0,0), radius=(size[0]/2.0, size[1]/2.0, size[2]/2.0), colour = colour,
exponentBottom = exponentBottom,
exponentTop = exponentTop,
exponentSide = exponentSide)
taperedBox.addMesh(mesh)
return taperedBox
def _createEllipsoid( proxy, radius, colour, moiScale, withMesh ):
"""
Private function.
Use createEllipsoid() or createArticulatedEllipsoid() instead.
"""
# Mesh and cdps will be set manually
proxy.meshes = None
proxy.cdps = None
# Compute box moi
moi = [0,0,0]
for i in range(3):
j = (i+1)%3
k = (i+2)%3
moi[i] = proxy.mass * (radius[j]*radius[j]+radius[k]*radius[k]) / 5.0
proxy.moi = PyUtils.toVector3d(moi) * moiScale
ellipsoid = proxy.createAndFillObject()
cdp = Physics.SphereCDP()
cdp.setCenter( Point3d(0,0,0) )
cdp.setRadius( min(radius) )
ellipsoid.addCollisionDetectionPrimitive( cdp )
if withMesh:
mesh = Mesh.createEllipsoid((0,0,0), radius, colour)
ellipsoid.addMesh(mesh)
return ellipsoid
def _createCylinder( proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh ):
"""
Private function.
Use createCylinder() or createArticulatedCylinder() instead.
"""
if axis != 0 and axis != 1 and axis != 2 :
raise ValueError( 'Axis must be 0 for x, 1 for y or 2 for z.' )
# Mesh and cdps will be set manually
proxy.meshes = None
proxy.cdps = None
# Compute box moi
moi = [0,0,0]
height = math.fabs(tipPos-basePos)
for i in range(3):
if i == axis :
moi[i] = proxy.mass*radius*radius / 2.0
else :
moi[i] = proxy.mass*(3*radius*radius + height*height) / 12.0
### HACK!
moi[i] = max(moi[i], 0.01)
proxy.moi = PyUtils.toVector3d(moi) * moiScale
cylinder = proxy.createAndFillObject()
basePoint = [0,0,0]
tipPoint = [0,0,0]
basePoint[axis] = basePos
tipPoint[axis] = tipPos
basePoint3d = PyUtils.toPoint3d(basePoint)
tipPoint3d = PyUtils.toPoint3d(tipPoint)
baseToTipVector3d = Vector3d(basePoint3d, tipPoint3d)
if baseToTipVector3d.isZeroVector() :
raise ValueError( 'Invalid points for cylinder: base and tip are equal!' )
baseToTipUnitVector3d = baseToTipVector3d.unit()
if height <= radius*2.0 :
cdp = Physics.SphereCDP()
cdp.setCenter( basePoint3d + baseToTipVector3d*0.5 )
cdp.setRadius( height/2.0 )
else:
cdp = Physics.CapsuleCDP()
cdp.setPoint1( basePoint3d + baseToTipUnitVector3d * radius )
cdp.setPoint2( tipPoint3d + baseToTipUnitVector3d * -radius )
cdp.setRadius( radius )
cylinder.addCollisionDetectionPrimitive( cdp )
if withMesh:
mesh = Mesh.createCylinder( basePoint, tipPoint, radius, colour )
cylinder.addMesh(mesh)
return cylinder
def _createCone( proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh ):
"""
Private function.
Use createCone() or createCone() instead.
"""
if axis != 0 and axis != 1 and axis != 2 :
raise ValueError( 'Axis must be 0 for x, 1 for y or 2 for z.' )
# Mesh and cdps will be set manually
proxy.meshes = None
proxy.cdps = None
# Compute box moi
moi = [0,0,0]
height = math.fabs(tipPos-basePos)
for i in range(3):
if i == axis :
moi[i] = proxy.mass*radius*radius * 3.0 / 10.0
else :
moi[i] = proxy.mass*(radius*radius/4.0 + height*height) * 3.0 / 5.0
proxy.moi = PyUtils.toVector3d(moi) * moiScale
cone = proxy.createAndFillObject()
basePoint = [0,0,0]
tipPoint = [0,0,0]
basePoint[axis] = basePos
tipPoint[axis] = tipPos
basePoint3d = PyUtils.toPoint3d(basePoint)
tipPoint3d = PyUtils.toPoint3d(tipPoint)
baseToTipVector3d = Vector3d(basePoint3d, tipPoint3d)
if baseToTipVector3d.isZeroVector() :
raise ValueError( 'Invalid points for cone: base and tip are equal!' )
baseToTipUnitVector3d = baseToTipVector3d.unit()
if height <= radius*2.0 :
cdp = Physics.SphereCDP()
cdp.setCenter( basePoint3d + baseToTipVector3d*0.5 )
cdp.setRadius( height/2.0 )
else:
cdp = Physics.CapsuleCDP()
cdp.setPoint1( basePoint3d + baseToTipUnitVector3d * radius )
cdp.setPoint2( tipPoint3d + baseToTipUnitVector3d * -radius )
cdp.setRadius( radius )
cone.addCollisionDetectionPrimitive( cdp )
if withMesh:
mesh = Mesh.createCone( basePoint, tipPoint, radius, colour )
cone.addMesh(mesh)
return cone
| Python |
'''
Created on 2009-09-16
@author: beaudoin
A Python version of the C++ Observable class found in Utils
'''
class Observable(object):
def __init__(self):
self._observers = []
self._hasChanged = False
self._batchChangeDepth = 0
def setChanged(self):
"""Protected. Indicate that the object has changed."""
self._hasChanged = True
def clearChanged(self):
"""Protected. Indicate that the object changes have been sent to every observer."""
self._hasChanged = False
def notifyObservers(self, data = None):
"""Protected. Notify observers that a change has occurred.
Doesn't notify if a batch change is going on."""
self.setChanged()
self.notifyObserversIfChanged( data )
def notifyObserversIfChanged(self, data = None ):
"""Protected. Notify observers only if the object has been modified.
Doesn't notify if a batch change is going on."""
if not self.isDoingBatchChanges() and self.hasChanged():
for observer in self._observers:
observer.update( data )
self.clearChanged()
def hasChanged(self):
"""Return true if this object has changed since last notification."""
return self._hasChanged
def isDoingBatchChanges(self):
"""Returns true if this object is currently going through a batch of changes."""
return self._batchChangeDepth > 0
def beginBatchChanges(self):
"""Indicates that we want to begin performing batch changes on this object.
Every call to beginBatchChanges() should be matched by a call to endBatchChanges(),
observers will only be notified when the first begin is closed by the last end.
The call to endBatchChanges() should usually be in a finally clause."""
self._batchChangeDepth += 1
def endBatchChanges(self):
"""Indicates that we want to end performing batch changes on this object.
Every call to beginBatchChanges() should be matched by a call to endBatchChanges(),
observers will only be notified when the first begin is closed by the last end.
The call to endBatchChanges() should usually be in a finally clause."""
self._batchChangeDepth -= 1
self.notifyObserversIfChanged()
def addObserver(self, observer):
"""Adds an observer to this object. Observers need to have a method:
update( observable, data = None )
Where observable is an observable object and data is an arbitrary data object."""
self._observers.append( observer )
def deleteObserver(self, observer):
"""Removes the specified observer from the list of observers."""
self._observers.remove(observer)
def countObservers(self):
"""Returns the number of observers of this object."""
return len( self._observers )
@classmethod
def typeName(cls):
"""Returns the name of the class."""
return cls.__name__
| Python |
'''
Created on 2009-09-02
@author: beaudoin
'''
def callOnObjectOrList( objectOrList, function ):
"""Apply the specified function on :
- The single element passed as first parameter
- The list of elements passed as first parameter, if this is a list or tuple
- The list of values passed as first parameter if this is a dict
The passed function should receive a single parameter.
Does not return anything, so whatever is returned by function is lost."""
if hasattr( objectOrList, 'values' ):
for object in objectOrList.values(): function(object)
elif hasattr( objectOrList, '__iter__' ):
for object in objectOrList: function(object)
else:
function( objectOrList )
def callOnObjectOrListAndEnumerate( objectOrList, function ):
"""Apply the specified function on :
- The single element passed as first parameter
- The list of elements passed as first parameter, if this is a list or tuple
- The list of values passed as first parameter if this is a dict
The passed function should receive two parameters: an index or the object.
Does not return anything, so whatever is returned by function is lost."""
if hasattr( objectOrList, 'values' ):
for i, object in enumerate(objectOrList.values()): function(i,object)
elif hasattr( objectOrList, '__iter__' ):
for i, object in enumerate(objectOrList): function(i,object)
else:
function( 0, objectOrList )
def _moduleExist( moduleNames ):
"""Checks that the specified module can be loaded in the current python path.
moduleNames is a list containing every element of the module name. For example,
module 'Data.Character.Robot' would be [ 'Data', 'Character', 'Robot' ] """
import sys, os
for path in sys.path :
fileName = os.path.join( path, *moduleNames )
if os.path.exists( fileName + '.py' ) : return True
return False
def _getData( dataModule ):
"""Private function. Access the data contained in the specified dataModule"""
# First check if file exist.
# This is better than using the python exception handling, since we don't want to
# inadvertently catch exceptions generated during module importation.
modules = dataModule.split('.')
if modules[0] != "Data" : modules.insert(0, "Data")
if not _moduleExist( modules ) :
modules.append( modules[-1] )
if not _moduleExist( modules ) :
raise ImportError( "Can't find data module '" + dataModule + "'." )
moduleName = '.'.join(modules)
module = __import__( moduleName, globals(), locals(), ["data"] )
reload( module )
try:
return module.data
except( AttributeError ):
raise ImportError( "Data module '" + dataModule + "' doesn't contain a variable named 'data'." )
def load( dataModule, *args ):
"""Loads the object contained in the specified data module.
A data module is a python-style name for a module located under the
'Data' package. For example to load the data contained
into 'Data/Character/Robot/Controllers/Walk.py', call
load( "Character.Robot.Controllers.Walk" ).
As a shortcut, if the specified dataModule is a package, the
function will look for a module having the exact name of the package.
For example, load( "Character.Robot" ) is the same as load( "Character.Robot.Robot" ).
Any extra parameter passed to the function are passed to the load method
of the loaded object. Returns the loaded object. """
data = _getData( dataModule )
return data.load(*args)
def loadRename( dataModule, objectName, *args ):
"""Loads the object contained in the specified data module.
A data module is a python-style name for a module located under the
'Data' package. For example to load the data contained
into 'Data/Character/Robot/Controllers/Walk.py', call
load( "Character.Robot.Controllers.Walk" ).
As a shortcut, if the specified dataModule is a package, the
function will look for a module having the exact name of the package.
For example, load( "Character.Robot" ) is the same as load( "Character.Robot.Robot" ).
Any extra parameter passed to the function are passed to the load method
of the loaded object. Returns the loaded object. """
data = _getData( dataModule )
data.name = objectName
return data.load(*args)
def loadMany( dataModule, count, *args ):
"""Loads 'count' instances of the object contained in the specified data module.
See 'load' for more details on what is a dataModule.
If they have a 'name' attribute, an underscore and a number starting at '_0' will be appended to each instance.
If they have a 'pos' attribute, then the positions will be moved around.
Returns a list of all the loaded object. """
from MathLib import Vector3d
data = _getData( dataModule )
result = []
for i in range(0,count):
dataCopy = data
try: dataCopy.name = data.name + "_" + str(i)
except AttributeError: pass
try: dataCopy.pos += Vector3d(10,10,10) * i
except AttributeError: pass
result.append( dataCopy.load(*args) )
return result
def getClassName( object ):
"""
Returns the name of the class of the specified object.
The object must have a method typeName() that returns the name of the class (i.e. "class ClassName" or "ClassName").
"""
return object.typeName().split(' ')[-1]
def getProxyClass( object ):
"""
This function returns the proxy class for specified object. This class will
have the following methods:
wrap(object) : returns the proxy class for the specified object
getIcon() : returns the filename of a png icon that represents the object
getName(object) : returns a string that can be used to identify the object
Moreover, the proxy class can be constructed using all the accessible members
of the wrapped object.
"""
from App import Proxys
className = getClassName(object)
try:
# Create an instance of the equivalent python wrapper class
return Proxys.__dict__[className]
except NameError:
raise NameError( "No proxy class known for object of type '%s'." % className )
def wrap( object, recursive = True ):
"""
This function creates an instance of the correct proxy class to wrap the specified object.
The proxy class will have the exact same name, but the class will come from the App.Proxys package.
As a container, specify the object (not proxy object) to which this object will be attached with an HAS_A or HAS_MANY relationship.
As an index, specify the position at which this object appear in the list of his container. Only useful with an HAS_MANY relationship.
Pass recursive = False to only wrap non-object members. The members containing object references or list of objects will not be wrapped and will be None.
"""
if object is None : return None
return getProxyClass(object).wrap( object, recursive )
def serialize(object):
"""Tries to create a serialized version of the object. Wrap it if needed."""
try: proxyClass = getProxyClass(object)
except AttributeError:
result = repr( object )
if result[0]=='<' :
raise TypeError( "Cannot wrap object " + result + ". Missing typeName() or proxy class." )
return result
return repr( getProxyClass(object).wrap( object, True ) )
def copy(object, *args):
"""Copy the object."""
copiedWrapper = wrapCopy( object )
try: copiedWrapper.name = copiedWrapper.name + "_Copy"
except AttributeError: pass
return copiedWrapper.createAndFillObject(None, *args)
def wrapCopy(object):
"""Wrap a copy of the object."""
from App import Proxys
return eval( serialize(object), Proxys.__dict__ )
def toVector3d( tuple ):
"""Converts a tuple to a Vector3d. If it is already a ThreeTuple, return it as a vector."""
from MathLib import Vector3d, ThreeTuple
if tuple is None: return None
if isinstance( tuple, ThreeTuple ) : return Vector3d(tuple)
if len(tuple) != 3:
raise TypeError( "A Vector3D should be a 3-tuple" )
return Vector3d( tuple[0], tuple[1], tuple[2] )
def fromVector3d( vec ):
"""Converts a Vector3D to a tuple"""
if vec is None: return None
return (vec.x, vec.y, vec.z)
def toPoint3d( tuple ):
"""Converts a tuple to a Point3D. If it is already a Point3D, return it."""
from MathLib import Point3d, ThreeTuple
if tuple is None: return None
if isinstance( tuple, ThreeTuple ) : return Point3d(tuple)
if len(tuple) != 3:
raise TypeError( "A Point3D should be a 3-tuple" )
return Point3d( tuple[0], tuple[1], tuple[2] )
def fromPoint3d( pt ):
"""Converts a Point3d to a tuple"""
if pt is None: return None
return (pt.x, pt.y, pt.z)
def angleAxisToQuaternion( tuple ):
"""Converts a 2-tuple (angle, (axis_x, axis_y, axis_z)) to a Quaternion. If it is already a Quaternion, return it."""
from MathLib import Quaternion
if tuple is None: return None
if isinstance( tuple, Quaternion ) : return tuple
if len(tuple) != 2:
raise TypeError( "An angle-axis quaternion should be a 2-tuple" )
q = Quaternion()
q.setToRotationQuaternion( tuple[0], toVector3d( tuple[1] ) )
return q
def angleAxisFromQuaternion( quat ):
"""Converts Quaterion to a 2-tuple (angle, (axis_x, axis_y, axis_z))"""
if quat is None: return None
return ( quat.getAngle(), fromVector3d( quat.getAxis() ) )
def toTrajectory1d( tupleList ):
"""Converts a list of 2-tuple to a Core.Trajectory1d"""
from MathLib import Trajectory1d
if tupleList is None: return None
traj = Trajectory1d()
for tuple in tupleList:
if len(tuple) != 2 : raise TypeError( "A Trajectory1d should be a list of 2-tuples" )
traj.addKnot( tuple[0], tuple[1] )
return traj
def fromTrajectory1d( traj ):
"""Converts Core.Trajectory1d to a list of 2-tuple"""
if traj is None: return None
return [ (traj.getKnotPosition(i), traj.getKnotValue(i)) for i in range(traj.getKnotCount()) ]
def fancify( expr ):
"""Add new line, spaces and intentation to the passed expression"""
import ast
import Fancify
tree = ast.parse( expr )
return Fancify.Fancify().visit(tree)
def sameObject( obj1, obj2 ):
"""True if the two objects are the same. Very similar to the "is" python keyword, but returns
true if both objects are different SWIG wrapper of the same object."""
try:
return obj1.this == obj2.this
except AttributeError:
return obj1 is obj2
def sameObjectInList( object, objectList ):
"""True if the object is in the list. See sameObject for an explanation on how the comparison is made."""
for other in objectList:
if sameObject(object, other):
return True
return False
def safeEqual( obj1, obj2 ):
"""True if both objects are None or both are equals."""
try: return obj1 == obj2
except (ValueError, TypeError): return False
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
import warnings
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function %s." % func.__name__,
category=DeprecationWarning, stacklevel = 2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def unCamelCase(inString):
"""Takes a string in camel case and remove camel case, inserting spaces and capitalize."""
import string
result = []
prev = 0
for i, char in enumerate(inString):
if i == 0: continue
if char in string.uppercase:
result.append( inString[prev:i] )
prev = i
result.append( inString[prev:] )
return ' '.join(result).capitalize()
def convertController(controllerFileName, character = None ):
"""
Takes the filename to an old-style controller file and converts it to the new format.
If a character is provided it is used for loading, otherwise the 1st character of the application is used.
"""
import wx, Core
character = wx.GetApp().getCharacter( character )
if character is None:
character = wx.GetApp().getCharacter(0)
if character is None:
raise AttributeError( "No character provided, and none found in the application" )
controller = Core.SimBiController(character)
controller.loadFromFile( controllerFileName )
print fancify( repr( wrap( controller ) ) )
def _buildGetterOrSetter( prefix, varName ):
"""Utility function used by getterName and setterName."""
if varName[0] == '_' :
varName = varName[1:]
return prefix + varName[0].upper() + varName[1:]
def getterName( varName ):
"""
Given that the string varName holds a variable (prefixed with _ or not), this method returns the standard
name of the getter for that variable. i.e. 'getVarName'
"""
return _buildGetterOrSetter( 'get', varName )
def setterName( varName ):
"""
Given that the string varName holds a variable (prefixed with _ or not), this method returns the standard
name of the setter for that variable. i.e. 'setVarName'
"""
return _buildGetterOrSetter( 'set', varName )
| Python |
from Utils import *
from Enum import enum
from Observable import Observable
import Mesh
import RigidBody | Python |
'''
Created on 2009-10-06
@author: beaudoin
A collection of useful functions for creating stock meshes
'''
import GLUtils, PyUtils, MathLib, math
from MathLib import Point3d, Vector3d
def create( vertices, faces, colour=(0.6,0.6,0.6) ):
"""
Creates a mesh having the specified vertices and faces.
Vertices should be a list of 3-tuples of float or Point3d (positions).
Faces should be a list of tuples of indices.
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
mesh = GLUtils.GLMesh()
for vertex in vertices:
mesh.addVertex( PyUtils.toPoint3d(vertex) )
for face in faces:
poly = GLUtils.GLIndexedPoly()
for index in face:
poly.addVertexIndex( index )
mesh.addPoly(poly)
try:
mesh.setColour( *colour )
except TypeError:
mesh.setColour( *(colour + (1,)) )
mesh.computeNormals()
return mesh
def createBox( size=(1,1,1), position=(0,0,0), colour=(0.6,0.6,0.6) ):
"""
Creates the mesh for a box having the specified size and a specified position.
The size should be a 3-tuple (xSize, ySize, zSize).
The position should be a 3-tuple.
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
size = PyUtils.toVector3d(size)
position = PyUtils.toPoint3d(position)
vertices = []
delta = MathLib.Vector3d()
for repeat in range(3):
for x in (-0.5,0.5) :
delta.x = size.x * x
for y in (-0.5,0.5) :
delta.y = size.y * y
for z in (-0.5,0.5) :
delta.z = size.z * z
vertices.append( position + delta )
faces = [(0,1,3,2),(5,4,6,7), # YZ Faces
(9,13,15,11),(12,8,10,14), # XY Faces
(18,19,23,22),(17,16,20,21)] # XZ Faces
return create( vertices, faces, colour )
def createTaperedBox( position=(0,0,0), size=(1,1,1), colour=(0.6,0.6,0.6), samplesY = 20, samplesXZ = 20, exponentBottom = 4, exponentTop = 4, exponentSide = 4 ):
"""
Creates the mesh for a box having the specified size and a specified position.
The size should be a 3-tuple (xSize, ySize, zSize).
The position should be a 3-tuple.
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
return createEllipsoid( position, (size[0]/2.0,size[1]/2.0,size[2]/2.0), colour, samplesY, samplesXZ, exponentBottom, exponentTop, exponentSide )
def createSphere( position=(0,0,0), radius=1, colour=(0.6,0.6,0.6), samplesY = 20, samplesXZ = 20 ):
"""
Creates the mesh for an sphere having the specified position and radius
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
return createEllipsoid( position, (radius,radius,radius), colour, samplesY, samplesXZ )
def createEllipsoid( position=(0,0,0), radius=(1,1,1), colour=(0.6,0.6,0.6), samplesY = 20, samplesXZ = 20, exponentBottom = 2, exponentTop = 2, exponentSide = 2 ):
"""
Creates the mesh for an ellipsoid having the specified position and radius
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
if exponentBottom < 2.0 or exponentTop < 2.0 or exponentSide < 2.0 :
raise ValueError( 'Exponents for ellipsoid must all be under 2.0!' )
position = PyUtils.toPoint3d(position)
vertices = []
for i in range(1,samplesY):
thetaI = i*math.pi/float(samplesY)
if i < samplesY / 2 :
n = exponentTop
else:
n = exponentBottom
cos = math.cos(thetaI)
y = cos * radius[1]
scaleXZ = math.pow( 1-math.pow(math.fabs(cos),n), 1.0/float(n) )
for j in range(0,samplesXZ):
thetaJ = j*2.0*math.pi/float(samplesXZ)
n = exponentSide
cos = math.cos(thetaJ)
x = cos * scaleXZ * radius[0]
z = math.pow( 1-math.pow(math.fabs(cos),n), 1.0/float(n) ) * math.copysign(1, math.sin(thetaJ)) * scaleXZ * radius[2]
vertices.append( position + Vector3d(x,y,z) )
vertices.append( position + Vector3d(0,radius[1],0) )
vertices.append( position + Vector3d(0,-radius[1],0) )
faces = []
for i in range(0,(samplesY-2)*samplesXZ,samplesXZ) :
for j in range(0,samplesXZ) :
faces.append( (i+j, i+(j+1)%samplesXZ, i+samplesXZ+(j+1)%samplesXZ, i+samplesXZ+j) )
for i in range(0,samplesXZ) :
base = (samplesY-2)*samplesXZ
faces.append( ((i+1)%samplesXZ, i, (samplesY-1)*samplesXZ) )
faces.append( (base+i, base+(i+1)%samplesXZ, (samplesY-1)*samplesXZ+1) )
return create( vertices, faces, colour )
def createCylinder( basePoint=(0,-1,0), tipPoint=(0,1,0), radius = 1.0, colour=(0.6,0.6,0.6), samples = 20 ):
"""
Creates the mesh for a cylinder between the two specified points.
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
basePoint = PyUtils.toPoint3d(basePoint)
tipPoint = PyUtils.toPoint3d(tipPoint)
baseToTipVector = Vector3d(basePoint,tipPoint)
if baseToTipVector.isZeroVector() :
raise ValueError( 'Invalid points for cylinder: base and tip are equal!' )
baseToTipUnitVector = baseToTipVector.unit()
xUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(0,0,1) )
if xUnitVector.length() < 0.5 :
xUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(0,-1,0) )
xUnitVector.toUnit()
yUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(-1,0,0) )
if yUnitVector.length() < 0.5 :
yUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(0,1,0) )
yUnitVector.toUnit()
vertices = []
for i in range(samples):
theta = i * 2 * math.pi / float(samples)
vertices.append( basePoint + xUnitVector * math.cos(theta) * radius + yUnitVector * math.sin(theta) * radius )
for i in range(samples):
theta = i * 2 * math.pi / float(samples)
vertices.append( tipPoint + xUnitVector * math.cos(theta) * radius + yUnitVector * math.sin(theta) * radius )
for i in range(samples):
theta = i * 2 * math.pi / float(samples)
vertices.append( basePoint + xUnitVector * math.cos(theta) * radius + yUnitVector * math.sin(theta) * radius )
vertices.append( tipPoint + xUnitVector * math.cos(theta) * radius + yUnitVector * math.sin(theta) * radius )
faces = [ range(0,samples), range(samples,2*samples) ]
for i in range(0,2*samples,2) :
base = 2*samples
size = 2*samples
faces.append( (base+i, base+i+1, base+(i+3)%size, base+(i+2)%size ) )
return create( vertices, faces, colour )
def createCone( basePoint=(0,-1,0), tipPoint=(0,1,0), radius = 1.0, colour=(0.6,0.6,0.6), samples = 20 ):
"""
Creates the mesh for a cone between the two specified points.
Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
"""
basePoint = PyUtils.toPoint3d(basePoint)
tipPoint = PyUtils.toPoint3d(tipPoint)
baseToTipVector = Vector3d(basePoint,tipPoint)
if baseToTipVector.isZeroVector() :
raise ValueError( 'Invalid points for cylinder: base and tip are equal!' )
baseToTipUnitVector = baseToTipVector.unit()
xUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(0,0,1) )
if xUnitVector.length() < 0.5 :
xUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(0,-1,0) )
xUnitVector.toUnit()
yUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(-1,0,0) )
if yUnitVector.length() < 0.5 :
yUnitVector = baseToTipUnitVector.crossProductWith( Vector3d(0,1,0) )
yUnitVector.toUnit()
vertices = []
for i in range(samples):
theta = i * 2 * math.pi / float(samples)
vertices.append( basePoint + xUnitVector * math.cos(theta) * radius + yUnitVector * math.sin(theta) * radius )
for i in range(samples):
theta = i * 2 * math.pi / float(samples)
vertices.append( basePoint + xUnitVector * math.cos(theta) * radius + yUnitVector * math.sin(theta) * radius )
vertices.append( tipPoint )
faces = [ range(0,samples) ]
for i in range(0,samples) :
base = samples
size = samples
faces.append( (base+i, base+(i+1)%size, 2*samples ) )
return create( vertices, faces, colour )
| Python |
'''
Created on 2009-09-28
@author: beaudoin
'''
def enum( *args ):
"""
Creates an enum class.
Pass a dictionnary { choice : value, ... }
Here, choice needs to be a string and value is an integer
Can also pass a list or a tuple, then the values will be given automatically, starting at 0
Instances of this class can have any of the values available in choices
Examples:
Colors = enum( {"red" : 10, "green" : 20, "yellow" : 30} )
Colors.int( "red" ) ==> 10
Colors.str( 20 ) ==> green
x = Colors("red")
x ==> "red"
str(x) ==> red
int(x) ==> 10
x.set( "green" )
x.set( 30 )
"""
@classmethod
def toInt(cls,choice):
"""Return the value associated with the choice (an integer)."""
if choice is None : return None
return cls.choicesDict[choice]
@classmethod
def toStr(cls,value):
"""Return the choice associated with the value (a string)."""
if value is None : return None
return cls.valuesDict[value]
@classmethod
def values(cls):
"""Return the choice associated with the value (a string)."""
return valuesDict.keys()
@classmethod
def choices(cls):
"""Return the choice associated with the value (a string)."""
return choicesDict.keys()
def __init__(self, value=None):
"""Initialize a new instance of this enum class"""
self.set(value)
def __repr__(self):
"""A representation of this object"""
if self.value is None : return repr(None)
return repr( str(self) )
def __int__(self):
"""Return the value currently associated with this variable"""
return int( self.value )
def __str__(self):
"""Return the value currently associated with this variable"""
if self.value is None : return str(None)
return self.toStr( self.value )
def __eq__(self,other):
"""Checks that this enum is equal to the other, which can be an enum of the same type, a value, or a string."""
if isinstance(other, basestring) : return other == str(self)
return self.value == int(other)
def __ne__(self,other):
"""Checks that this enum is equal to the other, which can be an enum of the same type, a value, or a string."""
return not self == other
def set(self, value):
"""Changes the value of self"""
if value is None : self.value = None
try: self.value = value.value
except AttributeError:
if isinstance(value, int) : self.value = value
elif isinstance(value, basestring) : self.value = self.toInt(value)
else: raise ValueError( "Trying to set an enum with an invalid type. Only int and str can be used." )
return self
# Reverse the dictionary
if len(args) == 1 and isinstance(args[0], dict) :
choicesDict = args[0]
else:
choicesDict = {}
for i, choice in enumerate( args ) : choicesDict[choice] = i
try: del i
except UnboundLocalError: pass
valuesDict = {}
for choice, value in choicesDict.iteritems(): valuesDict[value] = choice
try: del choice
except UnboundLocalError: pass
try: del value
except UnboundLocalError: pass
try: del args
except UnboundLocalError: pass
return type('Enum',(object,),locals())
| Python |
'''
Created on 2009-11-27
@author: beaudoin
'''
import Core
import random, math
from MathLib import Point3d, Vector3d
class WalkController(Core.IKVMCController):
def __init__(self, character):
super(WalkController,self).__init__(character)
def typeName(self):
return self.__class__.__name__
def initialSetup(self):
"""Call this method for the first setup of the dance controller"""
self.desiredCoronalStepLength = 0.04
self.defaultStepSize = 0.275
self.legLength = 1
self.setupParameters()
def setupParameters(self):
"""Called whenever parameters are setup"""
self.getState(0).setDuration( Core.cvar.SimGlobals_stepTime )
#now prepare the step information for the following step:
footStart = self.getStanceFootPos().z
sagittalPlaneFutureFootPos = footStart + self.defaultStepSize
self.swingFootTrajectory.clear()
self.setSagittalBalanceFootPlacement( 1 )
self.swingFootTrajectory.addKnot(0, Point3d(0, 0.04, self.getSwingFootPos().z - footStart));
self.swingFootTrajectory.addKnot(0.5, Point3d(0, 0.05 + 0.1 + Core.cvar.SimGlobals_stepHeight, 0.5 * self.getSwingFootPos().z + sagittalPlaneFutureFootPos * 0.5 - footStart));
self.swingFootTrajectory.addKnot(1, Point3d(0, 0.05 + 0, sagittalPlaneFutureFootPos - footStart));
def performPreTasks(self, contactForces):
"""Performs all the tasks that need to be done before the physics simulation step."""
v = self.getV()
d = self.getD()
self.velDSagittal = Core.cvar.SimGlobals_VDelSagittal
curState = self.getCurrentState()
fLean = Core.cvar.SimGlobals_rootSagittal
traj = curState.getTrajectory("root")
component = traj.getTrajectoryComponent(2)
component.offset = fLean;
traj = curState.getTrajectory("pelvis_lowerback")
component = traj.getTrajectoryComponent(2)
component.offset = fLean*1.5;
traj = curState.getTrajectory("lowerback_torso")
component = traj.getTrajectoryComponent(2)
component.offset = fLean*2.5;
traj = curState.getTrajectory("torso_head")
component = traj.getTrajectoryComponent(2)
component.offset = fLean*3.0;
traj = curState.getTrajectory("STANCE_Knee")
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_stanceKnee
self.legOrientation = Core.cvar.SimGlobals_duckWalk
super(WalkController,self).performPreTasks(contactForces)
def performPostTasks(self, dt, contactForces):
"""Performs all the tasks that need to be done after the physics simulation step."""
step = Vector3d(self.getStanceFootPos(), self.getSwingFootPos())
step = self.getCharacterFrame().inverseRotate(step)
phi = self.getPhase()
if step.z > 0.7 :
self.setPhase( 1.0 )
if super(WalkController,self).performPostTasks(dt, contactForces):
v = self.getV()
print "step: %3.5f %3.5f %3.5f. Vel: %3.5f %3.5f %3.5f. phi = %f\n" % (step.x, step.y, step.z, v.x, v.y, v.z, phi);
self.setupParameters()
| Python |
'''
Created on 2009-11-27
@author: beaudoin
'''
import Core
import random, math
from MathLib import Point3d, Vector3d
class DanceController(Core.IKVMCController):
def __init__(self, character):
super(DanceController,self).__init__(character)
def typeName(self):
return self.__class__.__name__
def initialSetup(self):
"""Call this method for the first setup of the dance controller"""
self.desiredCoronalStepLength = -0.02
self.silly = 0;
self.cnt = 0.0001;
self.sillySign = 1;
self.silly2 = 0;
self.cnt2 = 0.0003;
self.sillySign2 = 1;
self.defaultStepSize = 0.275
self.legLength = 1
self.setupParameters()
def setupParameters(self):
"""Called whenever parameters are setup"""
self.getState(0).setDuration( Core.cvar.SimGlobals_stepTime )
#now prepare the step information for the following step:
footStart = self.getStanceFootPos().z
sagittalPlaneFutureFootPos = footStart + self.defaultStepSize
self.swingFootTrajectory.clear()
self.setSagittalBalanceFootPlacement( 1 )
# self.swingFootTrajectory.addKnot(0, Point3d(0, 0.04, self.getSwingFootPos().z - footStart));
# self.swingFootTrajectory.addKnot(0.5, Point3d(0, 0.05 + 0.1 + Core.cvar.SimGlobals_stepHeight, 0.5 * self.getSwingFootPos().z + sagittalPlaneFutureFootPos * 0.5 - footStart));
# self.swingFootTrajectory.addKnot(1, Point3d(0, 0.05 + 0, sagittalPlaneFutureFootPos - footStart));
self.swingFootTrajectory.addKnot(0, Point3d(0, 0.06 + 0.1, 0))
self.swingFootTrajectory.addKnot(0.75, Point3d(0, 0.08 + 0.1 + Core.cvar.SimGlobals_stepHeight, 0.15))
self.swingFootTrajectory.addKnot(1.0, Point3d(0, 0.08 + Core.cvar.SimGlobals_stepHeight/2, 0.15))
# controller->swingFootTrajectory.addKnot(1, Point3d(0, 0.05, 0.27));
takeAStep = False
idleMotion = False
if self.doubleStanceMode and idleMotion:
if random.random() < 0.2:
Core.cvar.SimGlobals_upperBodyTwist = (random.random() - 0.5)
elif random.random() < 0.2:
self.doubleStanceMode = False
Core.cvar.SimGlobals_desiredHeading += Core.cvar.SimGlobals_upperBodyTwist + (random.random() - 0.5)
Core.cvar.SimGlobals_upperBodyTwist = 0;
takeAStep = True;
v = self.getV()
print "v.x: %f, v.z: %f" % (v.x, v.z)
if math.fabs(v.x) < 0.1 and \
math.fabs(v.z) < 0.05 and \
math.fabs(Core.cvar.SimGlobals_VDelSagittal) <= 0.1 and \
shouldComeToStop :
if not self.doubleStanceMode :
# check out the distance between the feet...
fMidPoint = Vector3d(self.stanceFoot.getCMPosition(), self.swingFoot.getCMPosition())
errV = self.characterFrame.inverseRotate(self.doubleStanceCOMError)
if errV.length() < 0.05 and fMidPoint.length() < 0.2 and fMidPoint.length() > 0.05 :
self.doubleStanceMode = True;
def checkStanceState(self):
"""Checks the stance state"""
if self.getDoubleStanceCOMError().length() > 0.06 :
if self.doubleStanceMode :
print "Should take a step...\n"
self.doubleStanceMode = False
def performPreTasks(self, contactForces):
"""Performs all the tasks that need to be done before the physics simulation step."""
v = self.getV()
d = self.getD()
self.checkStanceState()
self.velDSagittal = Core.cvar.SimGlobals_VDelSagittal
curState = self.getCurrentState()
# fLean = 0
# errM = v.z - self.velDSagittal
# sign = math.copysign( 1, errM )
# errM = math.fabs(errM)
# if errM > 0.3 :
# fLean += -(errM*sign - 0.3*sign) / 5.0
# if fLean > 0.15 :
# fLean = 0.15
# if fLean < -0.15 :
# fLean = -0.15
fLean = Core.cvar.SimGlobals_rootSagittal
sign = 1
if self.getStance() == Core.LEFT_STANCE :
sign = -1
self.silly += self.sillySign * self.cnt
if self.silly > 0.15 : self.sillySign = -1
if self.silly < -0.15 : self.sillySign = 1
traj = curState.getTrajectory("root")
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_upperBodyTwist/2.0 * sign
traj = curState.getTrajectory("pelvis_lowerback")
component = traj.getTrajectoryComponent(2)
component.offset = fLean*1.5
component = traj.getTrajectoryComponent(1)
component.offset = self.silly *1.5* sign
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_upperBodyTwist * sign
traj = curState.getTrajectory("lowerback_torso")
component = traj.getTrajectoryComponent(2)
component.offset = fLean*2.5
component = traj.getTrajectoryComponent(1)
component.offset = self.silly *2.5* sign
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_upperBodyTwist*2.0 * sign
traj = curState.getTrajectory("torso_head")
component = traj.getTrajectoryComponent(2)
component.offset = fLean*3.0
component = traj.getTrajectoryComponent(1)
component.offset = self.silly * 1 * sign
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_upperBodyTwist*3.0 * sign
self.silly2 += self.sillySign2 * self.cnt2
if self.silly2 > 0.15 : self.sillySign2 = -1
if self.silly2 < -0.2 : self.sillySign2 = 1
traj = curState.getTrajectory("lShoulder")
component = traj.getTrajectoryComponent(2)
component.offset = self.silly2*10.0
component = traj.getTrajectoryComponent(0)
component.offset = self.silly2*-2.0
component = traj.getTrajectoryComponent(1)
component.offset = self.silly2*self.silly2*25
traj = curState.getTrajectory("rShoulder")
component = traj.getTrajectoryComponent(2)
component.offset = self.silly2*10.0
component = traj.getTrajectoryComponent(0)
component.offset = self.silly2*-2.0
component = traj.getTrajectoryComponent(1)
component.offset = self.silly2*self.silly2*-25
self.velDLateral = 0.0
self.coronalPlaneOffset = 0
# tmp = (0.8 - self.getPhase()) / 0.6
# if tmp < 0 : tmp = 0
# if tmp > 1 : tmp = 1
# if math.fabs(v.x) > 0.1 or math.fabs(d.x) > 0.05 :
# tmp = 0
# tmp = 0
# controller.coronalBalanceFootPlacement = 1-tmp
self.setCoronalBalanceFootPlacement( 1 )
if self.doubleStanceMode :
self.setPhase( 0.3 )
traj = curState.getTrajectory("STANCE_Knee")
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_stanceKnee
traj = curState.getTrajectory("SWING_Knee")
component = traj.getTrajectoryComponent(0)
component.offset = Core.cvar.SimGlobals_stanceKnee
self.legOrientation = Core.cvar.SimGlobals_duckWalk
super(DanceController,self).performPreTasks(contactForces)
def performPostTasks(self, dt, contactForces):
"""Performs all the tasks that need to be done after the physics simulation step."""
step = Vector3d(self.getStanceFootPos(), self.getSwingFootPos())
step = self.getCharacterFrame().inverseRotate(step)
phi = self.getPhase()
if step.z > 0.7 or (math.fabs(step.x) > 0.45 and phi > 0.5) :
self.setPhase( 1.0 )
if super(DanceController,self).performPostTasks(dt, contactForces):
v = self.getV()
print "step: %3.5f %3.5f %3.5f. Vel: %3.5f %3.5f %3.5f. phi = %f\n" % (step.x, step.y, step.z, v.x, v.y, v.z, phi);
self.setupParameters()
| Python |
from DanceController import DanceController
from WalkController import WalkController | Python |
import Utils
Utils.test() | Python |
'''
Created on 2009-09-26
@author: beaudoin
'''
import wx, UI
class Animation(object):
# Available speeds on the buttons
_buttonSpeeds = ( '1/16', '1/8', '1/4', '1/2', '1', '2', '4' )
def __init__(self, toolPanel):
"""Adds a tool set for animation information to a toolpanel."""
self._toolPanel = toolPanel
self._toolSet = toolPanel.createToolSet( "Animation" )
app = wx.GetApp()
speedButtonPanel = self._toolSet.addTool( wx.Panel )
animButtonPanel = self._toolSet.addTool( wx.Panel )
self._speedButtons = [ SpeedButton( speedButtonPanel, label = speed, size=(28,28) ) for speed in Animation._buttonSpeeds ]
self._restartButton = wx.BitmapButton( animButtonPanel, bitmap = wx.Bitmap('../data/ui/restart.png', wx.BITMAP_TYPE_PNG) )
self._playButton = wx.BitmapButton( animButtonPanel, bitmap = wx.Bitmap('../data/ui/play.png', wx.BITMAP_TYPE_PNG) )
self._pauseButton = wx.BitmapButton( animButtonPanel, bitmap = wx.Bitmap('../data/ui/pause.png', wx.BITMAP_TYPE_PNG) )
self._stepButton = wx.BitmapButton( animButtonPanel, bitmap = wx.Bitmap('../data/ui/step.png', wx.BITMAP_TYPE_PNG) )
self._stepButton.SetBitmapDisabled( wx.Bitmap('../data/ui/stepDisabled.png', wx.BITMAP_TYPE_PNG) )
for speedButton in self._speedButtons:
speedButton.Bind( wx.EVT_BUTTON, lambda event: app.setSimulationSecondsPerSecond( event.GetEventObject()._labelValue ) )
self._restartButton.Bind( wx.EVT_BUTTON, lambda e: app.restoreActiveSnapshot(False) )
self._playButton.Bind( wx.EVT_BUTTON, lambda e: app.setAnimationRunning(True) )
self._pauseButton.Bind( wx.EVT_BUTTON, lambda e: app.setAnimationRunning(False) )
self._stepButton.Bind( wx.EVT_BUTTON, lambda e: app.simulationFrame() )
hBoxSpeedButton = wx.BoxSizer( wx.HORIZONTAL )
hBoxSpeedButton.AddStretchSpacer()
for speedButton in self._speedButtons:
hBoxSpeedButton.Add( speedButton,0, wx.EXPAND )
hBoxSpeedButton.AddStretchSpacer()
speedButtonPanel.SetSizerAndFit(hBoxSpeedButton)
self._hBoxAnimButtons = wx.BoxSizer( wx.HORIZONTAL )
self._hBoxAnimButtons.AddStretchSpacer()
self._hBoxAnimButtons.Add(self._restartButton)
self._hBoxAnimButtons.Add(self._playButton)
self._hBoxAnimButtons.Add(self._pauseButton)
self._hBoxAnimButtons.Add(self._stepButton)
self._hBoxAnimButtons.AddStretchSpacer()
animButtonPanel.SetSizerAndFit(self._hBoxAnimButtons)
# Add this as an observer
app.addAnimationObserver(self)
# Initial update
self.update()
def update(self, data = None):
"""Called whenever the animation is updated in the application."""
app = wx.GetApp()
simulationSecondsPerSeconds = app.getSimulationSecondsPerSecond()
for speedButton in self._speedButtons:
speedButton.Enable( simulationSecondsPerSeconds != speedButton._labelValue )
self._hBoxAnimButtons.Show( self._playButton, not app.isAnimationRunning() )
self._hBoxAnimButtons.Show( self._pauseButton, app.isAnimationRunning() )
self._stepButton.Enable( not app.isAnimationRunning() )
self._hBoxAnimButtons.Layout()
class SpeedButton(wx.Button):
"""A private internal class that keeps a button together with its numeric speed"""
def __init__(self, parent, id = wx.ID_ANY, label = '', pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0,
validator = wx.DefaultValidator, name='' ):
super(SpeedButton, self).__init__(parent, id, label, pos, size, style, validator, name)
self._labelValue = eval(label+".0") | Python |
'''
Created on 2009-10-02
@author: beaudoin
'''
import wx, UI, PyUtils
class SnapshotTree(object):
def __init__(self, toolPanel):
"""Adds a tool set for animation information to a toolpanel."""
self._toolPanel = toolPanel
self._toolSet = toolPanel.createToolSet( "Snapshots", resizable = True )
app = wx.GetApp()
buttonPanel = self._toolSet.addTool( wx.Panel )
self._takeSnapshotButton = wx.BitmapButton( buttonPanel, bitmap = wx.Bitmap('../data/ui/takeSnapshotButton.png', wx.BITMAP_TYPE_PNG) )
self._takeSnapshotButton.SetBitmapDisabled( wx.Bitmap('../data/ui/takeSnapshotButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._dontRestoreControllerParamsButton = UI.Ext.ToggleBitmapButton( buttonPanel, bitmap = wx.Bitmap('../data/ui/restoreControllerParams.png', wx.BITMAP_TYPE_PNG) )
self._dontRestoreControllerParamsButton.SetBitmapSelected( wx.Bitmap('../data/ui/dontRestoreControllerParams.png', wx.BITMAP_TYPE_PNG) )
self._previousButton = wx.BitmapButton( buttonPanel, bitmap = wx.Bitmap('../data/ui/previousSnapshotButton.png', wx.BITMAP_TYPE_PNG) )
self._previousButton.SetBitmapDisabled( wx.Bitmap('../data/ui/previousSnapshotButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._restoreButton = wx.BitmapButton( buttonPanel, bitmap = wx.Bitmap('../data/ui/restoreSnapshotButton.png', wx.BITMAP_TYPE_PNG) )
self._restoreButton.SetBitmapDisabled( wx.Bitmap('../data/ui/restoreSnapshotButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._nextButton = wx.BitmapButton( buttonPanel, bitmap = wx.Bitmap('../data/ui/nextSnapshotButton.png', wx.BITMAP_TYPE_PNG) )
self._nextButton.SetBitmapDisabled( wx.Bitmap('../data/ui/nextSnapshotButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._takeSnapshotButton.Bind( wx.EVT_BUTTON, lambda e: app.takeSnapshot() )
self._previousButton.Bind( wx.EVT_BUTTON, lambda e: app.previousSnapshot(self.restoreControllerParams()) )
self._restoreButton.Bind( wx.EVT_BUTTON, lambda e: app.restoreActiveSnapshot(self.restoreControllerParams()) )
self._nextButton.Bind( wx.EVT_BUTTON, lambda e: app.nextSnapshot(self.restoreControllerParams()) )
self._hBoxButtons = wx.BoxSizer( wx.HORIZONTAL )
self._hBoxButtons.Add(self._takeSnapshotButton)
self._hBoxButtons.AddStretchSpacer(1)
self._hBoxButtons.Add(self._dontRestoreControllerParamsButton)
self._hBoxButtons.Add(self._previousButton)
self._hBoxButtons.Add(self._restoreButton)
self._hBoxButtons.Add(self._nextButton)
buttonPanel.SetSizerAndFit(self._hBoxButtons)
self._infoTree = self._toolSet.addTool( UI.InfoTreeBasic, 1, object = app.getSnapshotTree(), desiredHeight = 200, autoVisible = True, onUpdate = self.update )
self._infoTree.Bind( wx.EVT_TREE_ITEM_ACTIVATED , self.selectSnapshot )
self._activeTreeItemId = None
#
# Public methods
#
def restoreControllerParams(self):
"""Return true if we should restore the controller parameters when moving around, false if not."""
return not self._dontRestoreControllerParamsButton.IsSelected()
#
# Callbacks
#
def selectSnapshot(self, event):
"""Select the snapshot double-clicked at."""
item = event.GetItem()
try:
nodeData = self._infoTree.GetItemPyData(item)
snapshot = nodeData.getObject()
snapshot.restore(self.restoreControllerParams())
except AttributeError:
event.Skip()
def update(self, data = None):
"""Called whenever the tree is updated."""
try:
tree = self._infoTree
rootItem = tree.GetRootItem()
nodeData = tree.GetItemPyData( rootItem )
snapshot = nodeData.getObject().getCurrentSnapshot()
except AttributeError: return
if self._activeTreeItemId != None :
currentSnapshot = tree.GetItemPyData( self._activeTreeItemId )
if PyUtils.sameObject(currentSnapshot, snapshot) : return
tree.SetItemBold( self._activeTreeItemId, False )
# Look for the new item
activeList = [tree.GetFirstChild(rootItem)[0]]
while len(activeList) > 0 :
treeItemId = activeList.pop()
if not treeItemId.IsOk(): continue
object = tree.GetItemPyData( treeItemId ).getObject()
if PyUtils.sameObject(snapshot, object) :
self._activeTreeItemId = treeItemId
tree.SetItemBold( treeItemId, True )
return
activeList.append( tree.GetFirstChild(treeItemId)[0] )
activeList.append( tree.GetNextSibling(treeItemId) )
| Python |
'''
Created on 2009-09-26
@author: beaudoin
'''
import UI, wx, math
class _OptionData(object):
def __init__(self, checkBox, getter, setter):
self.checkBox = checkBox
self.getter = getter
self.setter = setter
self.update()
def update(self):
self.checkBox.SetValue( self.getter() )
def set(self):
self.setter(self.checkBox.IsChecked())
class _SliderData(object):
def __init__(self, slider, valueWidget, getter, setter, min, max):
self.slider = slider
self.valueWidget = valueWidget
self.getter = getter
self.setter = setter
self.min = min
self.max = max
self.update()
def update(self):
value = self.getter()
if value < self.min : value = self.min
if value > self.max : value = self.max
convertedValue = int((value-self.min)/float(self.max-self.min) * (self.slider.GetMax()-self.slider.GetMin()) + self.slider.GetMin())
self.slider.SetValue(convertedValue)
self.valueWidget.SetLabel( "%.2f" % value )
def set(self):
value = self.getSliderValue()
self.setter(value)
self.valueWidget.SetLabel( "%.2f" % value )
def getSliderValue(self):
convertedValue = self.slider.GetValue()
return float((convertedValue-self.slider.GetMin())/float(self.slider.GetMax()-self.slider.GetMin()) * (self.max-self.min) + self.min)
class ToolsetBase(object):
def __init__(self):
"""Abstract base class for toolsets that can contain options.
The subclass must contain a self._toolSet member."""
self._dataList = []
def update(self, data = None):
"""Called whenever the animation is updated in the application."""
for data in self._dataList:
data.update()
def addOption(self, label, getter, setter):
"""Adds a new option to the panel, with its getter and setter."""
checkBox = self._toolSet.addTool( wx.CheckBox, label = label, size=(-1,22) )
data = _OptionData(checkBox, getter, setter)
checkBox.Bind( wx.EVT_CHECKBOX, lambda e: data.set() )
self._dataList.append( data )
return checkBox, data
def addSlider(self, label, min, max, step, getter, setter, labelWidth = 75, valueWidth = 40):
"""Adds a new horizontal slider to the panel, with its getter and setter."""
toolPanel = self._toolSet.addTool( wx.Panel )
sizer = wx.BoxSizer( wx.HORIZONTAL )
labelWidget = wx.StaticText( toolPanel, label = label, size=(labelWidth,-1) )
slider = wx.Slider( toolPanel, size=(-1,22), style = wx.SL_HORIZONTAL, minValue = 0, maxValue = math.ceil(float(max-min)/float(step)) )
slider.SetLineSize( step )
valueWidget = wx.StaticText( toolPanel, label = "0", size=(valueWidth,-1) )
sizer.Add(labelWidget, 0, wx.ALIGN_CENTER)
sizer.Add(slider, 1, wx.EXPAND)
sizer.Add(valueWidget, 0, wx.ALIGN_CENTER)
toolPanel.SetSizerAndFit( sizer )
data = _SliderData(slider, valueWidget, getter, setter, min, max)
slider.Bind( wx.EVT_SCROLL, lambda e: data.set() )
self._dataList.append( data )
return slider, data
def addButton(self, label, action):
"""Adds a new option button the panel, with its action (a parameter-less function)."""
button = self._toolSet.addTool( wx.Button, label = label, flag=0 )
button.Bind(wx.EVT_BUTTON, lambda event: action() )
return button
| Python |
'''
Created on 2009-09-26
@author: beaudoin
'''
import UI, wx
from ToolsetBase import ToolsetBase
class Options(ToolsetBase):
def __init__(self, toolPanel):
"""Adds a tool set for various options information to a toolpanel."""
super(Options, self).__init__()
self._toolPanel = toolPanel
self._toolSet = toolPanel.createToolSet( "Options" )
app = wx.GetApp()
self.addOption( "Show collision volumes", app.getDrawCollisionVolumes, app.drawCollisionVolumes )
self.addOption( "Capture screenshots", app.getCaptureScreenShots, app.captureScreenShots )
self.addOption( "Kinematic motion", app.getKinematicMotion, app.setKinematicMotion)
# Add this as an observer
app.addOptionsObserver(self)
# Initial update
self.update() | Python |
'''
Created on 2009-09-26
@author: beaudoin
'''
import UI, wx
from ToolsetBase import ToolsetBase
class Camera(ToolsetBase):
def __init__(self, toolPanel):
"""Adds a tool set for camera information to a toolpanel."""
super(Camera, self).__init__()
self._toolPanel = toolPanel
self._toolSet = toolPanel.createToolSet( "Camera" )
app = wx.GetApp()
self.addOption( "Follow character", app.doesCameraFollowCharacter, app.setCameraFollowCharacter )
self.addOption( "Auto orbit", app.doesCameraAutoOrbit, app.setCameraAutoOrbit )
# Add this as an observer
app.addCameraObserver(self)
# Initial update
self.update()
| Python |
'''
Created on 2009-09-26
@author: beaudoin
'''
import UI, wx, PyUtils, os, Core
class ControllerTree(object):
"""A toolset that can be used to display an editable tree of the loaded controllers."""
def __init__(self, toolPanel):
"""Adds a tool set that display a tree of controllers to a toolpanel."""
self._toolPanel = toolPanel
toolSet = toolPanel.createToolSet( "Controller Tree", resizable = True )
self._toolSet = toolSet
self._buttonToolbar = toolSet.addTool( ButtonToolbar, 0 )
self._infoTree = toolSet.addTool( UI.InfoTree, 1, object = wx.GetApp().getControllerList(), desiredHeight = 450 )
self._infoTree.Bind( wx.EVT_TREE_SEL_CHANGED, self._buttonToolbar.updateButtons )
self._buttonToolbar.setTree( self._infoTree.getTree() )
#
# Callbacks
#
def updateButtons(self, event):
_updateButtonState
class ButtonToolbar(wx.Panel):
"""Private class that provide a toolbar for actions available on a controller tree."""
def __init__(self,*args, **kwargs):
super(ButtonToolbar,self).__init__(*args,**kwargs)
self._replaceCurvesButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/replaceCurvesButton.png', wx.BITMAP_TYPE_PNG) )
self._replaceCurvesButton.SetBitmapDisabled( wx.Bitmap('../data/ui/replaceCurvesButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._addCurvesButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/addCurvesButton.png', wx.BITMAP_TYPE_PNG) )
self._addCurvesButton.SetBitmapDisabled( wx.Bitmap('../data/ui/addCurvesButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._recenterButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/recenter.png', wx.BITMAP_TYPE_PNG) )
self._recenterButton.SetBitmapDisabled( wx.Bitmap('../data/ui/recenterDisabled.png', wx.BITMAP_TYPE_PNG) )
self._stepUntilBreakButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/stepUntilBreak.png', wx.BITMAP_TYPE_PNG) )
self._stepUntilBreakButton.SetBitmapDisabled( wx.Bitmap('../data/ui/stepUntilBreakDisabled.png', wx.BITMAP_TYPE_PNG) )
self._saveButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/save.png', wx.BITMAP_TYPE_PNG) )
self._saveButton.SetBitmapDisabled( wx.Bitmap('../data/ui/saveDisabled.png', wx.BITMAP_TYPE_PNG) )
self._saveCharacterStateButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/saveCharacterState.png', wx.BITMAP_TYPE_PNG) )
self._saveCharacterStateButton.SetBitmapDisabled( wx.Bitmap('../data/ui/saveCharacterStateDisabled.png', wx.BITMAP_TYPE_PNG) )
# self._addButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/plusButton.png', wx.BITMAP_TYPE_PNG) )
# self._addButton.SetBitmapDisabled( wx.Bitmap('../data/ui/plusButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
# self._removeButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/minusButton.png', wx.BITMAP_TYPE_PNG) )
# self._removeButton.SetBitmapDisabled( wx.Bitmap('../data/ui/minusButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
# self._upButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/upButton.png', wx.BITMAP_TYPE_PNG) )
# self._upButton.SetBitmapDisabled( wx.Bitmap('../data/ui/upButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
# self._downButton = wx.BitmapButton( self, bitmap = wx.Bitmap('../data/ui/downButton.png', wx.BITMAP_TYPE_PNG) )
# self._downButton.SetBitmapDisabled( wx.Bitmap('../data/ui/downButtonDisabled.png', wx.BITMAP_TYPE_PNG) )
self._hBoxButtonBar = wx.BoxSizer(wx.HORIZONTAL)
self._hBoxButtonBar.Add( self._replaceCurvesButton, 0, wx.EXPAND )
self._hBoxButtonBar.Add( self._addCurvesButton, 0, wx.EXPAND )
self._hBoxButtonBar.Add( self._recenterButton, 0, wx.EXPAND )
self._hBoxButtonBar.Add( self._stepUntilBreakButton, 0, wx.EXPAND )
self._hBoxButtonBar.AddStretchSpacer()
self._hBoxButtonBar.Add( self._saveButton, 0, wx.EXPAND )
self._hBoxButtonBar.Add( self._saveCharacterStateButton, 0, wx.EXPAND )
# self._hBoxButtonBar.Add( self._addButton, 0, wx.EXPAND )
# self._hBoxButtonBar.Add( self._removeButton, 0, wx.EXPAND )
# self._hBoxButtonBar.Add( self._upButton, 0, wx.EXPAND )
# self._hBoxButtonBar.Add( self._downButton, 0, wx.EXPAND )
self.SetSizer( self._hBoxButtonBar )
self._replaceCurvesButton.Bind( wx.EVT_BUTTON, self.replaceCurves )
self._addCurvesButton.Bind( wx.EVT_BUTTON, self.addCurves )
self._recenterButton.Bind( wx.EVT_BUTTON, self.recenter )
self._stepUntilBreakButton.Bind( wx.EVT_BUTTON, self.stepUntilBreak )
self._saveButton.Bind( wx.EVT_BUTTON, self.saveController )
self._saveCharacterStateButton.Bind( wx.EVT_BUTTON, self.saveCharacterState )
self._tree = None
self._saveNumber = 0
self._dirName = os.path.join( 'Data', 'Temp' )
self._lastSave = (None,None,None) # a triplet: controller, saveNumberForController, saveNumberForCharacterState
#
# Public methods
#
def setTree(self, tree):
"""Sets the tree attached to this button toolbar."""
self._tree = tree
self.updateButtons()
#
# Callbacks
#
def updateButtons(self, event = None):
"""Adjust button states based on the current selection"""
treeItemId = self._tree.GetSelection()
operations = save = plus = minus = up = down = False
if treeItemId.IsOk():
element = self._tree.GetItemPyData( treeItemId )
operations = save = True
self._replaceCurvesButton.Enable(operations)
self._addCurvesButton.Enable(operations)
self._recenterButton.Enable(operations)
self._stepUntilBreakButton.Enable(operations)
self._saveButton.Enable(save)
self._saveCharacterStateButton.Enable(save)
# self._addButton.Enable(plus)
# self._removeButton.Enable(minus)
# self._upButton.Enable(up)
# self._downButton.Enable(down)
def replaceCurves(self, event = None):
"""Replace all the curves with the selected ones."""
app = wx.GetApp()
app.clearCurves()
self.addCurves( event )
def addCurves(self, event = None):
"""Add all the curves under a node to the application."""
app = wx.GetApp()
treeItemId = self._tree.GetSelection()
if not treeItemId.IsOk(): return
# Name that node by going back to the top of the tree
nameStack = []
currTreeItemId = treeItemId
rootTreeItemId = self._tree.GetRootItem()
while currTreeItemId.IsOk() and currTreeItemId != rootTreeItemId:
nameStack.insert(0, self._tree.GetItemText(currTreeItemId))
currTreeItemId = self._tree.GetItemParent(currTreeItemId)
# Now, recursively go down the tree from the current node
curveList = app.getCurveList()
curveList.beginBatchChanges()
try: self._addCurves( treeItemId, nameStack )
finally: curveList.endBatchChanges()
def saveController(self, event = None):
"""Save the currently selected controller"""
controller = self._getSelectedController()
if controller is None : return
saveNumber = self._saveNumber
if PyUtils.sameObject( self._lastSave[0], controller ) :
if self._lastSave[2] is not None :
saveNumber = self._lastSave[2]
controllerName = controller.getName()
dialogTitle = "Save %s Controller" % controllerName
fileName = "%s_%d.py" % (controllerName, saveNumber)
dialog = wx.FileDialog(self, dialogTitle, self._dirName, fileName, "*.py", wx.SAVE | wx.OVERWRITE_PROMPT )
dialog.CenterOnScreen()
if dialog.ShowModal() == wx.ID_OK:
if saveNumber != self._saveNumber:
self._lastSave = (None, None, None)
else:
self._lastSave = (controller, self._saveNumber, None)
self._saveNumber += 1
fileName=dialog.GetFilename()
self._dirName=dialog.GetDirectory()
pathName = os.path.join(self._dirName,fileName)
file = open(pathName,'w')
file.write( "from App.Proxys import *\n\ndata = %s" % PyUtils.fancify( PyUtils.serialize(controller)) )
file.close()
dialog.Destroy()
def recenter(self, event = None):
"""Recenter the character attached to the currently selected controller"""
controller = self._getSelectedController()
if controller is None : return
app = wx.GetApp()
app.recenterCharacter( controller.getCharacter() )
def stepUntilBreak(self, event = None):
"""Steps the selected controller until its phase resets to zero"""
controller = self._getSelectedController()
if controller is None : return
app = wx.GetApp()
app.advanceAnimationUntilControllerEnds( controller )
def saveCharacterState(self, event = None):
"""Saves the selected character state"""
controller = self._getSelectedController()
if controller is None : return
app = wx.GetApp()
character = controller.getCharacter()
saveNumber = self._saveNumber
if PyUtils.sameObject( self._lastSave[0], controller ) :
if self._lastSave[1] is not None :
saveNumber = self._lastSave[1]
controllerName = controller.getName()
dialogTitle = "Save Character State for %s" % controllerName
fileName = "%sState_%d.rs" % (controllerName, saveNumber)
dialog = wx.FileDialog(self, dialogTitle, self._dirName, fileName, "*.rs", wx.SAVE | wx.OVERWRITE_PROMPT )
dialog.CenterOnScreen()
if dialog.ShowModal() == wx.ID_OK:
if saveNumber != self._saveNumber:
self._lastSave = (None, None, None)
else:
self._lastSave = (controller, None, self._saveNumber)
self._saveNumber += 1
fileName=dialog.GetFilename()
self._dirName=dialog.GetDirectory()
pathName = os.path.join(self._dirName,fileName)
stateArray = Core.ReducedCharacterStateArray()
if controller.getStance() == Core.RIGHT_STANCE:
character.getReverseStanceState(stateArray)
else:
character.getState(stateArray)
character.saveReducedStateToFile( str(pathName), stateArray )
dialog.Destroy()
#
# Private methods
#
def _getSelectedController(self):
"""Go up to the root to find the selected controller. None if no controller was selected."""
treeItemId = self._tree.GetSelection()
rootTreeItemId = self._tree.GetRootItem()
controller = None
while treeItemId.IsOk() and treeItemId != rootTreeItemId:
try: controller = self._tree.GetItemPyData(treeItemId).getObject()
except AttributeError: controller = None
treeItemId = self._tree.GetItemParent(treeItemId)
if controller is None or not isinstance(controller,Core.SimBiController):
return None
return controller
def _addCurves(self, treeItemId, nameStack):
"""PRIVATE. Recursively add curves under this treeItemId."""
from App.Proxys import Member
app = wx.GetApp()
controller = self._getSelectedController()
phiPtr = controller.getPhiPtr()
nodeData = self._tree.GetItemPyData( treeItemId )
if nodeData is None : return
try:
# Assume the tree node contains an object
object = nodeData.getObject()
except AttributeError:
object = None
if object is not None:
proxyObject = PyUtils.wrap(object, recursive = False)
for i in range( proxyObject.getMemberCount() ):
value, member = proxyObject.getValueAndInfo(i)
if value is None: continue
if isinstance( member, Member.Trajectory1d ):
name = " : ".join(nameStack[1:])
if member.name != "baseTrajectory" :
name += " : " + member.fancyName
app.addCurve( name, value, phiPtr )
# Recurse on the child nodes
currTreeItemId, cookie = self._tree.GetFirstChild( treeItemId )
while currTreeItemId.IsOk():
newNameStack = nameStack[:]
newNameStack.append( self._tree.GetItemText(currTreeItemId) )
self._addCurves( currTreeItemId, newNameStack )
currTreeItemId, cookie = self._tree.GetNextChild( treeItemId, cookie )
| Python |
from ToolsetBase import ToolsetBase
from ControllerTree import ControllerTree
from Animation import Animation
from Options import Options
from Camera import Camera
from SnapshotTree import SnapshotTree | Python |
'''
Created on 2009-08-30
@author: beaudoin
Allows creation of a vertical collection of collapsible tool sets
'''
import wx
class ToolSet(wx.Panel):
"""A simple class that maintain tools and that can be hidden or showed."""
_triUp = None
_triDown = None
def __init__(self, parent, id = wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.TAB_TRAVERSAL,
name='', resizable = False ):
super(ToolSet, self).__init__(parent, id, pos, size, style, name)
# Load the bitmaps if needed
if ToolSet._triUp is None :
ToolSet._triRight = wx.Bitmap('../data/ui/triRight.png', wx.BITMAP_TYPE_PNG)
ToolSet._triDown = wx.Bitmap('../data/ui/triDown.png', wx.BITMAP_TYPE_PNG)
# Setup a link to the parent, to refresh it when tool sets open or close
self._parentVBox = parent._vBox
# Setup the tool set title
self._title = wx.Panel(self)
self._title.SetBackgroundColour( (180,180,180) )
titleLabel = wx.StaticText(self._title,label=name)
self._titleBitmap = wx.StaticBitmap(self._title, bitmap = ToolSet._triDown )
titleHBox = wx.BoxSizer(wx.HORIZONTAL)
titleHBox.Add( self._titleBitmap, 0, wx.CENTER | wx.ALL, 3 )
titleHBox.Add( titleLabel, 1, wx.ALL, 3 )
self._title.SetSizer( titleHBox )
# A 1 px panel for spacing
spacing = wx.Panel(self, size=(-1,1) )
spacing.SetBackgroundColour( (150,150,150) )
self._vBox = wx.BoxSizer(wx.VERTICAL)
self._vBox.Add( self._title, 0, wx.EXPAND )
self._vBox.Add( spacing, 0, wx.EXPAND )
# Create the panel
# If the tool set is resizable, create the panel in a sash window
if resizable:
# Setup the main tool set panel
self._sashWindow = wx.SashWindow(self)
self._sashWindow.SetSashVisible( wx.SASH_BOTTOM, True )
self._vBox.Add( self._sashWindow, 0, wx.EXPAND )
self._panel = wx.Panel(self._sashWindow)
self._vBoxSashWindow = wx.BoxSizer(wx.VERTICAL)
self._vBoxSashWindow.Add( self._panel, 0, wx.EXPAND )
self._sashWindow.SetSizer( self._vBoxSashWindow )
self._sashWindow.Bind( wx.EVT_SASH_DRAGGED, self.toolSetResize )
else:
# Setup the main tool set panel
self._panel = wx.Panel(self)
self._vBox.Add( self._panel, 0, wx.EXPAND )
# Create the sizer for the panel
self._panelVBox = wx.BoxSizer(wx.VERTICAL)
self._panel.SetSizer( self._panelVBox )
self.SetSizer( self._vBox )
# Setup initial state
self._opened = True
# Bind events
self._title.Bind( wx.EVT_LEFT_DCLICK, self.processOpenClose )
titleLabel.Bind( wx.EVT_LEFT_DCLICK, self.processOpenClose )
self._titleBitmap.Bind( wx.EVT_LEFT_DOWN, self.processOpenClose )
self._titleBitmap.Bind( wx.EVT_LEFT_DCLICK, self.processOpenClose )
#
# Event handlers
def processOpenClose( self, event ):
"""Change the state from open to close and vice-versa"""
self.setOpen( not self._opened )
def toolSetResize( self, event ):
"""Change the size of the tool set"""
if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE :
return
self._panelVBox.SetMinSize( (-1, event.GetDragRect().height) )
self.refreshAll()
#
# public methods
def setOpen( self, opened ):
"""Indicates whether this tool set should be open or not"""
if self._opened == opened :
return
self._opened = opened;
try:
self._sashWindow.Show( opened )
except AttributeError:
self._panel.Show( opened )
if opened :
self._titleBitmap.SetBitmap( ToolSet._triDown )
else :
self._titleBitmap.SetBitmap( ToolSet._triRight )
self._parentVBox.Layout()
self.GetParent().FitInside()
self.GetParent().Refresh()
def addTool(self, widgetClass, proportion=0, flag=wx.EXPAND, border=0, desiredHeight = 0, **argkw ):
"""Adds the specified widget as a tool in the tool set
widgetCreator is a standard wxWidget class, such as wx.panel,
you can pass any wxWidget creation argument you want in argkw.
The method returns the newly created widget."""
widget = widgetClass( self._panel, **argkw )
self._panelVBox.Add( widget, proportion, flag, border )
minSize = self._panelVBox.GetMinSizeTuple()
self._panelVBox.SetMinSize((minSize[0],desiredHeight))
self.refreshAll()
return widget
def refreshAll(self):
"""Refresh the content of the tool set"""
self._panel.Fit()
try:
self._sashWindow.Fit()
except AttributeError: pass
self.Fit()
self.GetParent().Layout()
class ToolPanel(wx.ScrolledWindow):
"""A simple class that maintain tool sets and that can be scrolled."""
def __init__(self, parent, id = wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style= wx.HSCROLL | wx.VSCROLL,
name='toolPanel' ):
super(ToolPanel, self).__init__(parent, id, pos, size, style, name)
self._vBox = wx.BoxSizer(wx.VERTICAL)
self.SetSizer( self._vBox )
# Enable vertical scrolling by 10 pixel increments
self.SetScrollRate(0,10)
def createToolSet(self, toolSetName, resizable = False):
"""Creates a new tool set and adds it to the ToolPanel.
The user should then add tools to the tool set in any way he wishes
"""
toolSet = ToolSet(self, name=toolSetName, resizable = resizable )
self._vBox.Add( toolSet, 0, wx.EXPAND )
self.Layout()
return toolSet
| Python |
'''
Created on 2009-09-30
@author: beaudoin
'''
import wx, GLUtils, PyUtils
class CurveEditorCollection(GLUtils.GLUIContainer):
"""A collection of curve editor that observes the curve editors of the application."""
def __init__( self, parent, x=0, y=0, width=0, height=0, minWidth=-1, minHeight=-1 ):
super(CurveEditorCollection,self).__init__(parent,x,y,width,height,minWidth,minHeight)
sizer = GLUtils.GLUIBoxSizer( GLUtils.GLUI_HORIZONTAL )
self.setSizer(sizer)
app = wx.GetApp()
self._appCurveList = app.getCurveList()
self._appCurveList.addObserver(self)
self._curveEditorList = []
def _removeCurveEditors(self, start=None, end=None):
"""Private. This method removes curve editors from the curve editor list.
Objects removed are in the range [start,end).
Runs from object 0 when start==None and until the end when end==None."""
if start is None : start = 0
if end is None : end = len( self._curveEditorList )
for curveEditor in self._curveEditorList[start:end]:
self.detachChild( curveEditor )
del self._curveEditorList[start:end]
def _insertCurveEditor(self, index, curve):
"""Private. This method inserts at the specified index a curve editor that wraps the specified App.Curve."""
curveEditor = GLUtils.GLUICurveEditor( self )
curveEditor.setTrajectory( curve.getTrajectory1d() )
curveEditor.setCurrTime( curve.getPhiPtr() )
curveEditor.setTitle( curve.getName() )
curveEditor.setMinSize(200,200)
self.getSizer().add( curveEditor )
self._curveEditorList.insert(index, curveEditor)
def getTrajectory(self, index):
"""Return the trajectory attached to the curve editor number 'index'."""
return self._curveEditorList[index].getTrajectory()
def update(self, data = None):
"""Called whenever the curve list is updated. Make sure the curve editor list match the application curve list."""
count = self._appCurveList.getCount()
for i in range(count):
inCurve = self._appCurveList.get(i)
inTrajectory1d = inCurve.getTrajectory1d()
try:
outTrajectory1d = self.getTrajectory(i)
areSameObject = PyUtils.sameObject(inTrajectory1d, outTrajectory1d)
except IndexError:
outTrajectory1d = None
areSameObject = False
if not areSameObject:
# Need to delete or insert
# First, check how many curves we should delete
delete = 1
try:
while not PyUtils.sameObject( inTrajectory1d, self.getTrajectory(i+delete) ) :
delete += 1
except IndexError:
delete = 0
if delete > 0 :
# Delete the specified controllers
self._removeCurveEditors(i,i+delete)
else :
# Insert the specified controller
self._insertCurveEditor(i, inCurve)
# Delete any remaining controllers
self._removeCurveEditors(count)
self.getParent().layout()
| Python |
'''
Created on 2009-12-02
@author: beaudoin
'''
import GLUtils
from OpenGL.GL import *
class ControlPoint(object):
"""Base class for any type of control point.
Derived classes must implement:
getPos() returns the x, y position of the control point."""
def __init__( self ):
super(ControlPoint,self).__init__()
self._previousMousePos = None
def draw(self):
xPos, yPos = self.getPos()
glVertex2d( xPos, yPos )
def setPreviousMousePos(self, pos ):
self._previousMousePos = pos
def unsetPreviousMousePos(self):
self._previousMousePos = None
def moveToPos(self, pos):
if self._previousMousePos is None :
self._previousMousePos = pos
self.setPos(pos)
self._previousMousePos = pos
class WindowWithControlPoints(GLUtils.GLUIWindow):
"""
Base class for a simple GL window that can contain various control points.
Derived class should not perform their drawing in draw() but instead in
drawContent()
The control points will be drawn on top of that.
At that point, the drawing area will be configured to the specified values (minPosY, maxPosY
"""
def __init__( self, parent, x=0, y=0, width=0, height=0, minWidth=-1, minHeight=-1, boundsX = (-1,1), boundsY = (-1,1), forceAspectRatio = None ):
"""
Initializes a window that can have control points.
boundsX indicate the (min, max) X values to display
boundsY indicate the (min, max) Y values to display
forceAspectRatio can be 'x', 'y' or None.
If 'x', the boundsX will be modified to enforce conservation of aspect ratio
If 'y', the boundsY will be modified to enforce conservation of aspect ratio
If None, aspect ratio is not adjusted by the window
See GLUIWindow for other parameters.
"""
super(WindowWithControlPoints,self).__init__(parent,x,y,width,height, minWidth, minHeight)
self._controlPoints = []
self._controlPointHeld = None
self._holdPos = (-1,-1)
self._boundsX = boundsX
self._boundsY = boundsY
self._width = float(boundsX[1] - boundsX[0])
self._height = float(boundsY[1] - boundsY[0])
if forceAspectRatio is not None:
if forceAspectRatio == 'x' :
self._width = self._height * float(minWidth) / float(minHeight)
midX = (boundsX[0] + boundsX[1])/2.0
self._boundsX = (midX - self._width/2.0, midX + self._width/2.0)
elif forceAspectRatio == 'y' :
self._height = width * float(minHeight) / float(minWidth)
midY = (boundsY[0] + boundsY[1])/2.0
self._boundsY = (midY - self._height/2.0, midY + self._height/2.0)
else :
raise ValueError( "forceAspectRation must be 'x', 'y' or None" )
def draw(self):
"""Draws the content of the window by calling self.drawContent(), then the control points."""
# Save projection matrix and sets it to a simple orthogonal projection
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
glOrtho(self._boundsX[0], self._boundsX[1], self._boundsY[0], self._boundsY[1],-1,1)
self.drawContent()
# Draw control points
try:
glPointSize( 8.0 )
glColor3d(1,1,0)
glBegin( GL_POINTS );
for controlPoint in self._controlPoints:
controlPoint.draw()
glEnd()
except Exception as e:
glEnd()
print "Exception while drawing WindowWithControlPoints interface: " + str(e)
traceback.print_exc(file=sys.stdout)
# Restore projection to pixel mode
glMatrixMode(GL_PROJECTION)
glPopMatrix()
def deleteAllControlPoints(self):
"""Delete all the control points."""
self._controlPoints = []
def addControlPoint(self, controlPoint):
"""Adds a control point to the window."""
self._controlPoints.append( controlPoint )
def onLeftDown(self, mouseEvent):
"""Left mouse button pressed."""
x, y = mouseEvent.x, mouseEvent.y
self._captureControlPoint( self._findClosestControlPoint(x,y), x, y )
return True
def onLeftUp( self, mouseEvent ):
self._checkReleaseCapture(mouseEvent)
return True;
def _posToPixel(self, x, y):
size = self.getSize()
return int((x-self._boundsX[0])*size.width/self._width), \
size.height-int((y-self._boundsY[0])*size.height/self._height)
def _pixelToPos(self, x, y):
size = self.getSize()
return self._boundsX[0] + x*self._width/float(size.width), \
self._boundsY[0] - (y - size.height)*self._height/float(size.height)
def _findClosestControlPoint(self, x,y):
for controlPoint in self._controlPoints:
distX, distY = self._posToPixel( *controlPoint.getPos() )
distX -= x
distY -= y
if distX*distX + distY*distY < 25 :
return controlPoint;
return None;
def _captureControlPoint( self, controlPoint, x, y ):
if self.hasCapture(): return
self._controlPointHeld = controlPoint
if controlPoint is None : return
posX, posY = self._pixelToPos( x, y )
controlPoint.setPreviousMousePos( (posX, posY) )
self._holdPos = (x,y)
self.captureMouse()
def _checkReleaseCapture( self, mouseEvent ):
if not self.hasCapture(): return
if mouseEvent.leftDown or mouseEvent.rightDown : return
self.releaseMouse()
if self._controlPointHeld is not None :
self._controlPointHeld.unsetPreviousMousePos()
self._controlPointHeld = None
self._holdPos = (-1,-1)
def onMotion( self, mouseEvent ):
if not mouseEvent.leftDown and not mouseEvent.rightDown: return True
if not self.hasCapture(): return True
if self._controlPointHeld is None : return True
posX, posY = self._pixelToPos( mouseEvent.x, mouseEvent.y )
self._controlPointHeld.moveToPos( (posX, posY) )
return True
| Python |
from CurveEditorCollection import CurveEditorCollection
from WindowWithControlPoints import WindowWithControlPoints, ControlPoint | Python |
'''
Created on 2009-08-24
This module contains the main OpenGL application window that is used by all SNM applications
@author: beaudoin
'''
import wx
import UI
class MainWindow(wx.Frame):
"""The class for the main window."""
MIN_TOOLPANEL_WIDTH = 200
MIN_CONSOLE_HEIGHT = 100
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE,
name='frame', fps=30, glCanvasSize=wx.DefaultSize,
showConsole=True,
consoleEnvironment={} ):
# Check if a fixed glWindow was asked
fixedGlWindow = glCanvasSize != wx.DefaultSize
self._glCanvasSize = glCanvasSize
#
# Forcing a specific style on the window.
# Should this include styles passed?
style |= wx.NO_FULL_REPAINT_ON_RESIZE
# Not resizable if GL canvas is fixed size
if fixedGlWindow :
style &= ~wx.RESIZE_BORDER & ~wx.MAXIMIZE_BOX
super(MainWindow, self).__init__(parent, id, title, pos, size, style, name)
#
# Create the menu
self._menuBar = wx.MenuBar()
self._fileMenu = wx.Menu()
self._fileMenu.Append( wx.ID_OPEN, "&Open" )
self._fileMenu.Append( wx.ID_SAVE, "&Save" )
self._fileMenu.AppendSeparator()
self._fileMenu.Append( wx.ID_EXIT, "&Quit" )
self._menuBar.Append(self._fileMenu, "&File" )
self._helpMenu = wx.Menu()
self._helpMenu.Append( wx.ID_ABOUT, "&About" )
self._menuBar.Append(self._helpMenu, "&Help" )
self.SetMenuBar( self._menuBar )
#
# Create the GL canvas
attribList = (wx.glcanvas.WX_GL_RGBA, # RGBA
wx.glcanvas.WX_GL_DOUBLEBUFFER, # Double Buffered
wx.glcanvas.WX_GL_DEPTH_SIZE, 24, # 24 bit depth
wx.glcanvas.WX_GL_STENCIL_SIZE, 8 ) # 8 bit stencil
self._glCanvas = UI.GLPanel(self, fps = fps, size = glCanvasSize, attribList = attribList)
# Create the right window (sashed) where the tool panel will be
self._rightWindow = wx.SashLayoutWindow(self)
self._rightWindow.SetDefaultSize((MainWindow.MIN_TOOLPANEL_WIDTH * 1.3,-1))
self._rightWindow.SetMinimumSizeX(MainWindow.MIN_TOOLPANEL_WIDTH)
self._rightWindow.SetOrientation( wx.LAYOUT_VERTICAL )
self._rightWindow.SetAlignment( wx.LAYOUT_RIGHT )
if not fixedGlWindow:
self._rightWindow.SetSashVisible( wx.SASH_LEFT, True )
self._rightWindow.Bind( wx.EVT_SASH_DRAGGED, self.onSashDragRightWindow )
#
# Create the tool panel
self._toolPanel = UI.ToolPanel(self._rightWindow)
# Create the bottom window (sashed) where the console will be
self._bottomWindow = wx.SashLayoutWindow(self)
self._bottomWindow.SetDefaultSize((-1,MainWindow.MIN_CONSOLE_HEIGHT*2))
self._bottomWindow.SetMinimumSizeY(MainWindow.MIN_CONSOLE_HEIGHT)
self._bottomWindow.SetOrientation( wx.LAYOUT_HORIZONTAL )
self._bottomWindow.SetAlignment( wx.LAYOUT_BOTTOM )
if not fixedGlWindow:
self._bottomWindow.SetSashVisible( wx.SASH_TOP, True )
self._bottomWindow.Bind( wx.EVT_SASH_DRAGGED, self.onSashDragBottomWindow )
#
# Create the console window
self._console = UI.PythonConsole(self._bottomWindow, size=(-1,220), consoleEnvironment = consoleEnvironment )
if not showConsole:
self._bottomWindow.Hide()
self.Bind( wx.EVT_SIZE, self.onSize )
#
# Private methods
def _layoutFrame(self):
"""Private. Perform frame layout"""
wx.LayoutAlgorithm().LayoutFrame(self, self._glCanvas)
#
# Event handlers
def onSize(self, event):
self._layoutFrame()
if self._glCanvasSize != wx.DefaultSize :
currGlCanvasSize = self._glCanvas.GetSize()
diff = ( currGlCanvasSize[0] - self._glCanvasSize[0], currGlCanvasSize[1] - self._glCanvasSize[1] )
if diff == (0,0) :
return
currentSize = event.GetSize()
newSize= ( currentSize[0] - diff[0], currentSize[1] - diff[1] )
if newSize == currentSize :
return
self.SetSize( newSize )
self.SendSizeEvent()
def onSashDragRightWindow(self, event):
if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
return
self._rightWindow.SetDefaultSize((event.GetDragRect().width,-1))
self._layoutFrame()
def onSashDragBottomWindow(self, event):
if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
return
self._bottomWindow.SetDefaultSize((-1,event.GetDragRect().height))
self._layoutFrame()
#
# Accessors
def getGLCanvas(self):
"""Return the associated GL canvas."""
return self._glCanvas
def getToolPanel(self):
"""Return the associated tool panel."""
return self._toolPanel
def getFps(self):
"""Return the desired frame per second for this window."""
return self._glCanvas.getFps()
| Python |
'''
Created on 2009-09-24
@author: beaudoin
'''
import Utils, wx
import PyUtils
class MemberDisplay(Utils.Observer):
"""
This class wraps an element and displays its content in a table with a grid sizer
"""
def __init__(self, table, sizer):
super(MemberDisplay,self).__init__()
self._table = table
self._sizer = sizer
self._contentControls = None
self._object = None
def __del__(self):
try: self.deleteObserver()
except AttributeError: pass
def deleteObserver(self):
try: self._object.deleteObserver(self)
except AttributeError: pass
def attachObject(self, object):
self.deleteObserver()
self._object = object
try:
self._proxy = PyUtils.wrap( object, recursive = False )
except AttributeError:
self._proxy = None
try: object.addObserver(self)
except AttributeError: pass
self.createControls()
def createControls(self):
"""Creates all the controls to display the attached object's content"""
self._table.Freeze()
self._table.DestroyChildren()
self._contentControls = []
if self._proxy is None :
self._table.SetVirtualSize((0,0))
self._table.Thaw()
return
for i in range( self._proxy.getMemberCount() ) :
( value, info ) = self._proxy.getValueAndInfo(i)
if info.isObject : continue
value = info.format(value)
labelControl = wx.StaticText(self._table, label=info.fancyName)
if info.editable :
contentControl = self.createControlForMember( self._table, info, value)
else :
contentControl = wx.StaticText(self._table, label=str(value))
self._sizer.Add( labelControl, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.TOP , 2)
self._sizer.Add( contentControl, 0, wx.EXPAND | wx.TOP | wx.RIGHT, 2)
self._contentControls.append( contentControl )
self._table.FitInside()
self._table.Thaw()
def createControlForMember( self, parent, info, value ):
"""Creates a control for the member specified in info."""
from App.Proxys import Member
if isinstance(info, Member.Enum) :
result = wx.ComboBox( parent, value=value, style = wx.CB_READONLY, choices = info.enum.choices() )
result.Bind( wx.EVT_COMBOBOX, lambda event: self.changeValue(info.name, result.GetValue()) )
elif info.type == bool :
result = wx.CheckBox( parent )
result.SetValue(value)
result.Bind( wx.EVT_CHECKBOX, lambda event: self.changeValue(info.name, result.GetValue()) )
else:
result = wx.TextCtrl(parent, value=str(value))
result.Bind( wx.EVT_KILL_FOCUS, lambda event: self.changeValue(info.name, result.GetValue()) )
return result
def changeValue(self, memberName, value):
"""The value of the control specified in info has changed."""
try: self._proxy.setValueAndUpdateObject( memberName, value, self._object )
except: self.update()
def update(self, data = None):
"""Called whenever the observer is updated."""
self._proxy.extractFromObject( self._object, recursive = False )
j = 0
for i in range( self._proxy.getMemberCount() ) :
( value, info ) = self._proxy.getValueAndInfo(i)
if info.isObject : continue
value = info.format(value)
if not info.type is bool : value = str(value)
control = self._contentControls[j]
try: self._contentControls[j].SetValue(value) # Try to set the value
except AttributeError: self._contentControls[j].SetLabel(value) # Otherwise SetLabel will do
j += 1
| Python |
'''
Created on 2009-10-08
@author: beaudoin
'''
import wx
class ToggleBitmapButton(wx.BitmapButton):
def __init__(self, parent, id=wx.ID_ANY, bitmap=wx.NullBitmap, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.BU_AUTODRAW, validator=wx.DefaultValidator, name=wx.ButtonNameStr, selected=False):
"""Creates a bitmap button that can be toggled on and off."""
super(ToggleBitmapButton,self).__init__( parent, id, bitmap, pos, size, style, validator, name)
self._selected = selected
self._lookIsSelected = False
self.Bind( wx.EVT_BUTTON, self.OnClick )
#
# Callbacks
#
def OnClick(self, event):
"""Flips the state if possible."""
self._selected = not self._selected
self._updateLook()
event.Skip()
#
# Public methods
#
def SetBitmapSelected(self, bitmap):
"""Sets the bitmap for the selected (depressed) button appearance."""
super(ToggleBitmapButton,self).SetBitmapSelected(bitmap)
self._updateLook()
def SetSelected(self, selected = True):
"""Indicates whether this toggle button should be selected or not."""
self._selected = selected
self._updateLook()
def IsSelected(self):
"""Returns true if the toggle button is currently in its selected state, false otherwise."""
return self._selected
#
# Private methods
#
def _updateLook(self):
"""Make sure the look matches the selected state."""
if self._selected == self._lookIsSelected : return
# Toggle looks
other = self.GetBitmapSelected()
if not other.IsOk(): return
current = self.GetBitmapLabel()
self.SetBitmapLabel( other )
super(ToggleBitmapButton,self).SetBitmapSelected( current )
self._lookIsSelected = self._selected
| Python |
from ToggleBitmapButton import ToggleBitmapButton | Python |
import ToolSets
import GLUITools
import Ext
from InfoTree import InfoTreeBasic, InfoTree
from GLPanel import GLPanel
from PythonConsole import PythonConsole
from ToolPanel import ToolPanel
from MainWindow import MainWindow
| Python |
'''
Created on 2009-09-14
@author: beaudoin
'''
import wx
import Utils
from MemberDisplay import MemberDisplay
# Unique list for all the images
_iconList = None
_iconDict = {}
_unknownIcon = '../data/ui/unknownIcon.png'
def _getIconList():
global _iconList
if _iconList is None :
_iconList = wx.ImageList(16,16, False)
return _iconList
def _addIcon( pngFilename ):
"""Private, adds an icon to the list of icon and the dictionnary."""
global _iconDict, _unknownIcon
iconList = _getIconList()
if pngFilename == None: pngFilename = _unknownIcon
bitmap = wx.Bitmap(pngFilename, wx.BITMAP_TYPE_PNG)
if not bitmap.Ok() :
if pngFilename == _unknownIcon :
raise IOError("Icon file '%s' not found" % _unknownIcon)
return _addIcon(None)
index = iconList.Add(bitmap)
_iconDict[pngFilename] = index
return index
def getIconIndex( pngFilename ):
"""Returns the index of the icon for the pngFilename.
Use this to set node images in the info tree."""
global _iconDict
try: return _iconDict[pngFilename]
except KeyError: return _addIcon( pngFilename )
class InfoTreeBasic(wx.TreeCtrl):
"""A class that display a tree structure containing all the information of a given wrappable and observable object."""
def __init__(self, parent, object = None, rootName = "Root", autoVisible = False, onUpdate = None, id = wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style= wx.TR_HAS_BUTTONS | wx.TR_HIDE_ROOT | wx.TR_LINES_AT_ROOT,
validator = wx.DefaultValidator, name='InfoTreeBasic'):
"""Initializes a tree that listens to the object."""
super(InfoTreeBasic, self).__init__(parent, id, pos, size, style, validator, name)
# Configure empty tree
self.SetImageList( _getIconList() )
self.AddRoot( "" )
# Set a reasonable minimum width
self.SetMinSize( (-1,80) )
self._rootName = rootName
self._autoVisible = autoVisible
self._onUpdate = onUpdate
self._updateLocks = 0
# Create an observer that need to be alive for as long as the tree is alive
# so store it in a member
self.attachToObject( object )
def isAutoVisible(self):
"""True if the tree should make new nodes visible when they are added."""
return self._autoVisible
def attachToObject(self, object):
"""Attach this tree to a specific object."""
from App.Proxys.NodeData import NodeData
if object is not None:
self._root = NodeData( self._rootName, object, self, self.GetRootItem() )
#
# Callbacks
#
def updateLock(self):
"""Called whenever something in the tree is updated. Call that to set a lock. The update
will take place once all the locks are released."""
self._updateLocks += 1
def updateUnlock(self):
"""Called whenever something in the tree is updated. Call that to release a lock. The update
will take place once all the locks are released."""
assert self._updateLocks > 0, "Update unlocked, but no lock set!"
self._updateLocks -= 1
if self._updateLocks == 0 :
self.update()
def update(self, data = None):
"""Called whenever something in the tree is updated."""
try: self._onUpdate(data)
except TypeError: pass
class InfoTree(wx.Panel):
"""A complete tree attached to an info box."""
def __init__(self, parent, object = None, rootName = "Root", autoVisible = False, onUpdate = None, id = wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style= wx.TAB_TRAVERSAL, name='InfoTree'):
super(InfoTree, self).__init__(parent, id, pos, size, style, name)
self._infoTreeBasic = InfoTreeBasic( self, object, rootName, autoVisible, onUpdate )
self._sashWindow = wx.SashWindow( self )
self._sashWindow.SetSashVisible( wx.SASH_TOP, True )
self._infoTable = wx.ScrolledWindow(self._sashWindow, style = wx.VSCROLL )
self._infoTable.SetBackgroundColour( (255,255,255) )
self._infoTable.SetScrollRate(0,10)
self._infoTable.SetMinSize( (-1,70) )
self._infoTableSizer = wx.FlexGridSizer(0,2,0,8)
self._infoTableSizer.AddGrowableCol(1)
self._infoTable.SetSizer( self._infoTableSizer )
self._vBoxSashWindow = wx.BoxSizer(wx.VERTICAL)
self._vBoxSashWindow.Add( self._infoTable, 1, wx.EXPAND )
self._vBoxSashWindow.SetMinSize( (-1,100) )
self._sashWindow.SetSizer( self._vBoxSashWindow )
self._sashWindow.Bind( wx.EVT_SASH_DRAGGED, self.sashWindowResize )
self._vBox = wx.BoxSizer(wx.VERTICAL)
self._vBox.Add( self._infoTreeBasic, 1, wx.EXPAND )
self._vBox.Add( self._sashWindow, 0, wx.EXPAND )
self.SetSizerAndFit( self._vBox )
self._memberDisplay = MemberDisplay(self._infoTable, self._infoTableSizer)
self._infoTreeBasic.Bind( wx.EVT_TREE_SEL_CHANGED, self.selectionChanged )
self.Bind( wx.EVT_PAINT, self.onPaint )
#
# Private methods
#
def _adjustSashSize(self):
"""Private. Make sure sash size is not too large."""
height = self._vBoxSashWindow.GetMinSize()[1]
maxHeight = self.GetSize()[1] - 80
if height > maxHeight :
if maxHeight <= 0 : maxHeight = -1
currMaxHeight = self._vBoxSashWindow.GetMinSize().height
if currMaxHeight == maxHeight : return
self._vBoxSashWindow.SetMinSize( (-1,maxHeight) )
self._refreshAll()
def _refreshAll(self):
"""Private. Make sure everything is laid-out correctly."""
self.Fit()
self.GetParent().Layout()
def _displayInfo(self, object):
"""Display info on the passed object."""
self._memberDisplay.attachObject(object)
#
# Public methods
#
def attachToObject(self, object):
self._infoTreeBasic.attachToObject(object)
def getTree(self):
return self._infoTreeBasic
#
# Callbacks
#
def onPaint(self, event):
self._adjustSashSize()
event.Skip()
def sashWindowResize(self, event):
"""Called whenever the sash window is resized"""
if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE :
return
self._vBoxSashWindow.SetMinSize( (-1,event.GetDragRect().height) )
self._adjustSashSize()
self._refreshAll()
def selectionChanged(self, event):
nodeData = self._infoTreeBasic.GetItemPyData(event.GetItem())
try: object = nodeData.getObject()
except (AttributeError, TypeError): object = nodeData
self._displayInfo( object )
event.Skip()
| Python |
'''
Created on 2009-08-30
@author: beaudoin
This file contains a class that can be used as a python interpreter console
'''
import wx
import sys
class PythonConsole(wx.Panel):
"""A console to output python and a command line interprete.
You should only have one of this as it seize the standard output.
"""
def __init__(self, parent, id = wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.TAB_TRAVERSAL,
name='', consoleEnvironment={} ):
"""Initialize a console. You can pass other dictionnaries as globals and locals."""
super(PythonConsole, self).__init__(parent, id, pos, size, style, name)
#
# Create the console components
self._console = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH2 | wx.TE_CHARWRAP )
self._console.SetDefaultStyle( wx.TextAttr(wx.BLACK, wx.WHITE, wx.Font(8, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) ) )
self._commandLine = wx.TextCtrl(self, size=(-1,20), style = wx.TE_PROCESS_ENTER | wx.TE_RICH2 )
self._commandLine.SetDefaultStyle( wx.TextAttr(wx.BLUE, wx.WHITE, wx.Font(8, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) ) )
#
# Create the sizer
self._vBox = wx.BoxSizer(wx.VERTICAL)
self._vBox.Add( self._console, 1, wx.EXPAND )
self._vBox.Add( self._commandLine, 0, wx.EXPAND )
self.SetSizer( self._vBox )
#
# Do bindings
self._commandLine.Bind( wx.EVT_KEY_DOWN, self.processKeyDown )
self._commandLine.Bind( wx.EVT_TEXT_ENTER, self.processUserCommand )
#
# Initialize
self._history = []
self._historyIndex = 0
self._currentCommand = u""
self._commandDepth = 0
self._runningCommand = u""
self._globals = consoleEnvironment
self._locals = consoleEnvironment
sys.stdout = self
#
# write function for stdout and stderr
def write(self, text, color = None):
# Freeze the window then scroll it as many lines as needed
self._console.Freeze()
before = self._console.GetLastPosition()
self._console.AppendText( text )
after = self._console.GetLastPosition()
if color is not None :
self._console.SetStyle (before, after, wx.TextAttr(color))
self._console.ScrollLines( text.count('\n') + 1 )
self._console.ShowPosition( self._console.GetLastPosition() )
self._console.Thaw()
#
# wxPython Window Handlers
def processKeyDown(self, event):
"""Called whenever the user presses a key in the command line.
Used to catch the UP arrow and DOWN arrow and navigate through history.
"""
keyCode = event.GetKeyCode()
if keyCode == wx.WXK_UP:
if self._historyIndex != 0:
if self._historyIndex == len( self._history ):
self._currentCommand = self._commandLine.GetValue()
self._historyIndex -= 1
self._commandLine.SetValue( self._history[self._historyIndex] )
self._commandLine.SetInsertionPointEnd()
elif keyCode == wx.WXK_DOWN:
if self._historyIndex != len( self._history ):
self._historyIndex += 1
if self._historyIndex == len( self._history ):
self._commandLine.SetValue( self._currentCommand )
else:
self._commandLine.SetValue( self._history[self._historyIndex] )
self._commandLine.SetInsertionPointEnd()
else:
# Assume text was entered
self._historyIndex = len( self._history )
event.Skip()
def processUserCommand(self, event):
"""Called when the user press enter to validate a new command line."""
commandLine = self._commandLine.GetValue().strip()
if len(commandLine) > 0:
self._history.append( commandLine )
self._historyIndex = len(self._history)
self._currentCommand = u""
if len(commandLine) == 0 and self._commandDepth > 0:
self._commandDepth -= 1
if self._commandDepth > 0:
self.write( "... " + " " * self._commandDepth + "<<<<\n", wx.BLUE )
else:
self.write( "<<<\n", wx.BLUE )
else:
if self._commandDepth == 0:
self.write( ">>> ", wx.BLUE )
else:
self.write( "... ", wx.BLUE )
commandLine = " " * self._commandDepth + commandLine
self._runningCommand += commandLine + "\n"
self.write( commandLine + "\n", wx.BLUE )
if commandLine.endswith(':'):
self._commandDepth += 1
if self._commandDepth == 0:
# First assume it is an expression
try:
x = eval( self._runningCommand, self._globals, self._locals )
if x is not None:
self._globals["_"] = x
print x
# If it fails, execute it as a statement
except:
try:
exec self._runningCommand in self._globals, self._locals
except NameError as exception:
self.write( "Symbol not found: " + str(exception) + "\n", wx.RED );
except SyntaxError as exception:
if exception.text is not None:
self.write( "Syntax error: " + "\n", wx.RED );
self.write( " " + exception.text + "\n", wx.RED );
self.write( " " + " " * exception.offset + "^" + "\n", wx.RED );
else:
self.write( "Syntax error: " + str(exception) + "\n", wx.RED );
except EnvironmentError as exception:
self.write( "IO error (" + str(exception.errno) + "): " + exception.strerror + "\n", wx.RED );
except ArithmeticError as exception:
self.write( "Arithmetic error: " + str(exception) + "\n", wx.RED );
except ImportError as exception:
self.write( "Import error: " + str(exception) + "\n", wx.RED );
except AssertionError as exception:
self.write( "Assertion failed: " + str(exception) + "\n", wx.RED );
except AttributeError as exception:
self.write( "Attribute not found: " + str(exception) + "\n", wx.RED );
except TypeError as exception:
self.write( "Invalid type: " + str(exception) + "\n", wx.RED );
except ValueError as exception:
self.write( "Invalid value: " + str(exception) + "\n", wx.RED );
except IndexError as exception:
self.write( "Index out of range: " + str(exception) + "\n", wx.RED );
except KeyError as exception:
self.write( "Key does not exist: " + str(exception) + "\n", wx.RED );
except SystemError as exception:
self.write( "Internal error: " + str(exception) + "\n", wx.RED );
except MemoryError as exception:
self.write( "Out of memory error: " + str(exception) + "\n", wx.RED );
except SystemExit:
wx.GetApp().GetTopWindow().Close()
except:
self.write( "Unknown error, exception raised: ", sys.exc_info()[0] + "\n", wx.RED );
finally:
self._runningCommand = u""
self._commandLine.SetValue(u"")
| Python |
'''
Created on 2009-08-30
@author: beaudoin
'''
try:
import wx
from wx import glcanvas
except ImportError:
raise ImportError, "Required dependency wx.glcanvas not present"
try:
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
except ImportError:
raise ImportError, "Required dependency OpenGL not present"
import time
import math
import GLUtils
from MathLib import Vector3d, Point3d, TransformationMatrix
class GLUITopLevelWindow( GLUtils.GLUITopLevelWindow ):
def __init__(self, width, height, window):
super(GLUITopLevelWindow,self).__init__(width,height)
self._window = window
def startMouseCapture(self):
self._window.CaptureMouse()
def stopMouseCapture(self):
self._window.ReleaseMouse()
class GLPanel(glcanvas.GLCanvas):
def __init__(self, parent, id = wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0,
name='glpane', attribList=(), fps=30):
super(GLPanel, self).__init__(parent, id, pos, size, style, name, attribList)
self._glInitialized = False
width, height = self.GetSizeTuple()
self._gluiTopLevelWindow = GLUITopLevelWindow( width, height, self )
self._gluiSizer = GLUtils.GLUIBoxSizer( GLUtils.GLUI_VERTICAL )
self._gluiTopLevelWindow.setSizer( self._gluiSizer )
#
# Set the event handlers.
self.Bind(wx.EVT_ERASE_BACKGROUND, self.processEraseBackgroundEvent)
self.Bind(wx.EVT_SIZE, self.processSizeEvent)
self.Bind(wx.EVT_PAINT, self.processPaintEvent)
self.Bind(wx.EVT_LEFT_DOWN, self.processMouseDown)
self.Bind(wx.EVT_LEFT_UP, self.processMouseUp)
self.Bind(wx.EVT_MIDDLE_DOWN, self.processMouseDown)
self.Bind(wx.EVT_MIDDLE_UP, self.processMouseUp)
self.Bind(wx.EVT_RIGHT_DOWN, self.processMouseDown)
self.Bind(wx.EVT_RIGHT_UP, self.processMouseUp)
self.Bind(wx.EVT_MOTION, self.processMouseMotion)
self.Bind(wx.EVT_LEFT_DOWN, lambda event: self.processGLUIMouseEvent(event, self._gluiTopLevelWindow.onLeftDown) )
self.Bind(wx.EVT_LEFT_UP, lambda event: self.processGLUIMouseEvent(event, self._gluiTopLevelWindow.onLeftUp) )
self.Bind(wx.EVT_LEFT_DCLICK, lambda event: self.processGLUIMouseEvent(event, self._gluiTopLevelWindow.onLeftDClick) )
self.Bind(wx.EVT_MIDDLE_DOWN, lambda event: self.processGLUIMouseEvent(event, self._gluiTopLevelWindow.onMiddleDown) )
self.Bind(wx.EVT_MIDDLE_UP, lambda event: self.processGLUIMouseEvent(event, self._gluiTopLevelWindow.onMiddleUp) )
self.Bind(wx.EVT_MIDDLE_DCLICK, lambda event: self.processGLUIMouseEvent(event, self._gluiTopLevelWindow.onMiddleDClick) )
self.Bind(wx.EVT_RIGHT_DOWN, lambda event: self.processGLUIMouseEvent(event, self._gluiTopLevelWindow.onRightDown) )
self.Bind(wx.EVT_RIGHT_UP, lambda event: self.processGLUIMouseEvent(event, self._gluiTopLevelWindow.onRightUp) )
self.Bind(wx.EVT_RIGHT_DCLICK, lambda event: self.processGLUIMouseEvent(event, self._gluiTopLevelWindow.onRightDClick) )
self.Bind(wx.EVT_MOTION, lambda event: self.processGLUIMouseEvent(event, self._gluiTopLevelWindow.onMotion) )
self.Bind(wx.EVT_MOUSEWHEEL, lambda event: self.processGLUIMouseEvent(event, self._gluiTopLevelWindow.onMouseWheel) )
self.Bind(wx.EVT_IDLE, self.processIdle)
# Set-up starting state
self._drawAxes = False
self._printLoad = False
self._drawGround = True
self._groundTexture = None
self._cameraControl = True
self._fps = fps
self._load = 0
self._loadWindow = []
self._loadWindowSize = math.ceil(fps)
self._oldX = -1
self._oldY = -1
self._drawCallbacks = []
self._postDrawCallbacks = []
self._oncePerFrameCallbacks = []
self._timeOfNextFrame = 0
# Set-up initial camera
self._camera = GLUtils.GLCamera()
self._camera.setTarget( Point3d(0,1,0) )
self._camera.modifyRotations( Vector3d( -0.18, -3.141592/2.0, 0 ) )
self._cameraTargetFunction = None
#
# wxPython Window Handlers
def processEraseBackgroundEvent(self, event):
"""Process the erase background event."""
pass # Do nothing, to avoid flashing on MSWin
def processSizeEvent(self, event):
"""Process the resize event."""
if self.IsShown() and self.GetContext():
# Make sure the frame is shown before calling SetCurrent.
self.Show()
self.SetCurrent()
size = self.GetClientSize()
self.onReshape(size.width, size.height)
event.Skip()
def processPaintEvent(self, event):
"""Process the drawing event."""
self.SetCurrent()
# This is a 'perfect' time to initialize OpenGL ... only if we need to
if not self._glInitialized:
self.onInitGL()
self._glInitialized = True
if self._cameraTargetFunction is not None:
newTarget = self._cameraTargetFunction( self._camera.getTarget() )
try:
self._camera.setTarget( newTarget )
except:
pass
self.onDraw()
event.Skip()
def processGLUIMouseEvent(self, mouseEvent, gluiMethod ):
"""Sends a mouse event to GLUI. Will skip if GLUI did not process the event."""
# If the mouse is captured, but not by GLUI, skip
if self.HasCapture() and not self._gluiTopLevelWindow.mouseIsCaptured() :
mouseEvent.Skip()
return
gluiMouseEvent = _createGLUIMouseEvent(mouseEvent)
gluiMethod( gluiMouseEvent )
if gluiMouseEvent.skip : mouseEvent.Skip()
def processMouseDown(self, event):
"""
Process a mouse left down event on any button.
Captures the mouse events
"""
if self._cameraControl and not self.HasCapture():
self.CaptureMouse()
event.Skip()
def processMouseUp(self, event):
"""Process a mouse up event on any button.
Releases the mouse events if all button are released
"""
self.potentiallyReleaseCapture(event)
event.Skip()
def potentiallyReleaseCapture(self, event):
"""Releases mouse capture if no button is pressed"""
if self.HasCapture() and not ( event.LeftIsDown() or event.MiddleIsDown() or event.RightIsDown() ):
self.ReleaseMouse()
def processMouseMotion(self, event):
"""Process mouse motion within the window"""
x = event.GetX()
y = event.GetY()
if self._cameraControl and self.HasCapture() and (self._oldX >= 0 or self._oldY >= 0) :
if event.LeftIsDown():
self._camera.modifyRotations( Vector3d( (self._oldY-y)/100.0, (self._oldX-x)/100.0, 0 ) )
if event.MiddleIsDown():
self._camera.translateCamDistance( (self._oldY - y)/200.0 )
if event.RightIsDown():
v = Vector3d( (self._oldX - x)/200.0, -(self._oldY - y)/200.0, 0 )
camToWorld = TransformationMatrix()
camToWorld.setToInverseCoordFrameTransformationOf(self._camera.getWorldToCam());
v = camToWorld * v;
self._camera.translateTarget(v)
self._oldX = x
self._oldY = y
event.Skip()
def processIdle(self, event):
"""Process the idle loop, calls every function that wants to be called once per frame."""
currentTime = time.clock()
timeLeft = self._timeOfNextFrame - currentTime
secondPerFrame = 1.0/self._fps
if timeLeft > 0 :
# Not enough elapsed time
time.sleep( min(timeLeft, 0.001) )
else :
# Enough time elapsed perform simulation loop and render
self._timeOfNextFrame = currentTime + secondPerFrame
# Call everything that should happen once per frame
for callback in self._oncePerFrameCallbacks:
callback()
# Redraw the screen
self.Refresh(False)
# Compute the load, that is, the percentage of the allotted time spend doing this
# load = (secondPerFrame - (self._timeOfNextFrame - time.clock())) / secondPerFrame
load = 1 - (self._timeOfNextFrame - time.clock()) * self._fps
self._loadWindow.append(load)
if len(self._loadWindow) >= self._loadWindowSize :
self._load = sum(self._loadWindow) / float(len(self._loadWindow))
self._loadWindow = []
event.RequestMore()
#
# GLFrame OpenGL Event Handlers
def onInitGL(self):
"""Initialize OpenGL for use in the window."""
glClearColor(0.0, 0.0, 0.0, 1)
glShadeModel(GL_SMOOTH)
glEnable(GL_DEPTH_TEST)
glEnable(GL_TEXTURE_2D)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
glEnable(GL_BLEND)
glEnable(GL_POINT_SMOOTH)
glEnable(GL_LINE_SMOOTH)
glEnable(GL_POLYGON_SMOOTH)
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST)
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST)
glBlendFunc(GL_SRC_ALPHA ,GL_ONE_MINUS_SRC_ALPHA)
glClearColor(0.0, 0.0, 0.0, 1)
ambient = [0.3, 0.3, 0.3, 1.0]
diffuse0 = [0.9, 0.9, 0.9, 1.0]
diffuse = [0.6, 0.6, 0.6, 1.0]
specular = [0.0, 0.0, 0.0, 0.0]
glLightfv(GL_LIGHT0, GL_AMBIENT, ambient)
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse0)
glLightfv(GL_LIGHT0, GL_SPECULAR, specular)
glLightfv(GL_LIGHT1, GL_AMBIENT, ambient)
glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse)
glLightfv(GL_LIGHT1, GL_SPECULAR, specular)
glLightfv(GL_LIGHT2, GL_AMBIENT, ambient)
glLightfv(GL_LIGHT2, GL_DIFFUSE, diffuse)
glLightfv(GL_LIGHT2, GL_SPECULAR, specular)
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular)
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50.0)
glEnable(GL_LIGHTING)
light0_position = [ 50.0, 10.0, 200.0, 0.0 ]
light1_position = [200.0, 10.0, -200.0, 0.0 ]
light2_position = [-200.0, 10.0, -200.0, 0.0 ]
glLightfv(GL_LIGHT0, GL_POSITION, light0_position)
glLightfv(GL_LIGHT1, GL_POSITION, light1_position)
glLightfv(GL_LIGHT2, GL_POSITION, light2_position)
glEnable(GL_LIGHT0)
glEnable(GL_LIGHT1)
glEnable(GL_LIGHT2)
def onReshape(self, width, height):
"""Reshape the OpenGL viewport based on the dimensions of the window."""
glViewport(0, 0, width, height)
self._gluiTopLevelWindow.setSize( width, height )
def onDraw(self, *args, **kwargs):
"""Draw the window."""
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)
size = self.GetClientSize()
# Setup the 3D projection matrix
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45.0, size.width/float(size.height),0.1,150.0);
# Apply the camera
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
self._camera.applyCameraTransformations();
if self._drawGround:
GLUtils.GLUtils_drawGround(50, 5, 98)
# Call all 3D drawing callbacks
for callback in self._drawCallbacks:
callback()
if self._drawAxes:
self.drawAxes()
if self._printLoad:
self.printLoad()
# Draw the GLUI
self._gluiTopLevelWindow.refresh()
self.SwapBuffers()
# Call all 3D post drawing callbacks
for callback in self._postDrawCallbacks:
callback()
#
# Private methods
def drawAxes(self):
glPushMatrix()
glLoadIdentity()
glTranslated(-3,-2.0,-6.0)
rot = self._camera.getRotations()
glRotated(-180/math.pi * rot.x,1.0,0.0,0.0)
glRotated(-180/math.pi * rot.y,0.0,1.0,0.0)
glRotated(-180/math.pi * rot.z,0.0,0.0,1.0)
glDisable(GL_DEPTH_TEST)
GLUtils.GLUtils_drawAxes(0.5)
glEnable(GL_DEPTH_TEST)
glPopMatrix()
def printLoad(self):
loadString = "FPS: %d Load: %6.2f%%" % (self._fps, (self._load*100))
size = self.GetClientSize()
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
glOrtho(size.width,0,size.height,0,-1,1)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()
glDisable(GL_DEPTH_TEST)
glColor4f(0,0,0,1)
glRasterPos2f(200, 15)
for c in loadString:
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, ord(c));
glEnable(GL_DEPTH_TEST)
glPopMatrix()
glMatrixMode(GL_PROJECTION)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
#
# Accessors
def setDrawAxes(self, drawAxes):
"""Controls whether the axes should be drawn or not."""
self._drawAxes = drawAxes
def getDrawAxes(self):
"""Indicates whether the application draws the axes or not."""
return self._drawAxes
def setPrintLoad(self, printLoad):
"""Controls whether the load should be printed or not."""
self._printLoad = printLoad
def getPrintLoad(self):
"""Indicates whether the load should be printed or not."""
return self._printLoad
def setDrawGround(self, drawGround):
"""Controls whether the ground should be drawn or not."""
self._drawGround = drawGround
def getDrawGround(self):
"""Indicates whether the application draws the ground or not."""
return self._drawGround
def setCameraControl(self, cameraControl):
"""Controls whether the camera can be controlled with the mouse."""
self._cameraControl = cameraControl
def getCameraControl(self):
"""Indicates whether the camera can be controlled with the mouse or not."""
return self._cameraControl
def getFps(self):
"""Return the desired frame per second for this window."""
return self._fps
def getLoad(self):
"""Return the load during the previous frame (in % of desired FPS)."""
return self._load
def setCameraTargetFunction(self, cameraTargetFunction):
"""Specifies a function that can be called to identify which point the panel should be looking at.
This function must take one Point3d parameter that indicates the current camera target.
This function must return a Point3d or None if the camera shouldn't change its current target.
You can set the CameraTargetFunction to None to disable the feature."""
self._cameraTargetFunction = cameraTargetFunction
def setCameraAutoOrbit(self, autoOrbit):
"""Indicates whether the camera should automatically orbit or not"""
self._camera.setAutoOrbit(autoOrbit)
def doesCameraAutoOrbit(self):
"""Checks if the camera is currently automatically orbiting."""
return self._camera.doesAutoOrbit()
#
# Public methods
def addGLUITool(self, gluiToolClass, *args, **kwargs):
"""Adds a GLUI tool to the list of available tools. The parameter passed should be a non-instanciated
GLUIWindow derived class for which the constructor accept a parent window.
Returns the newly created GLUIWindow of the tool.
Any extra parameter provided are passed to the tool's constructor."""
gluiTool = gluiToolClass(self._gluiTopLevelWindow, *args, **kwargs)
self._gluiSizer.add(gluiTool)
self._gluiSizer.layout()
return gluiTool
def addDrawCallback(self, callback):
"""Adds a method that should be called when the system is drawing 3D meshes
The order in which the registered callbacks are called is not guaranteed
"""
self._drawCallbacks.append( callback )
def addPostDrawCallback(self, callback):
"""Adds a method that should be called whenever the system has finished drawing the OpenGL window
The order in which the registered callbacks are called is not guaranteed
"""
self._postDrawCallbacks.append( callback )
def addOncePerFrameCallback(self, callback):
"""Adds a method that should be called exactly once per frame
The order in which the registered callbacks are called is not guaranteed
"""
self._oncePerFrameCallbacks.append( callback )
def removeDrawCallback(self, callback):
"""Removes a previously added draw callback"""
self._drawCallbacks.remove( callback )
def removeDrawInterfaceCallback(self, callback):
"""Removes a previously added draw interface callback"""
self._drawCallbacks.remove( callback )
def removeOncePerFrameCallback(self, callback):
"""Removes a previously added once-per-frame callback"""
self._oncePerFrameCallbacks.remove( callback )
def beginShadows(self):
"""This method should be called before drawing shadows
After calling this method, the application should draw any mesh for which
it wants a shadow. Make sure you do not call glColor when drawing the meshes.
Call endShadows() when complete
"""
# Setup constants
n = Vector3d(0,1,0) # Ground normal
d = Vector3d(-150,200,200) # Light direction
# Draw a 1 on the stencil buffer everywhere on the ground
glClear(GL_STENCIL_BUFFER_BIT);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, 1, 0xffffffff);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
GLUtils.GLUtils_drawGround(50,5,98);
# Setup the stencil to write only on the ground
glStencilFunc(GL_LESS, 0, 0xffffffff);
glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
# Offset the shadow polygons
glPolygonOffset(-2.0, -2.0);
glEnable(GL_POLYGON_OFFSET_FILL);
# Draw semitransparent black shadows
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(0.0, 0.0, 0.0, 0.5);
# Setup the ModelView matrix to a skewed & flattening projection
glPushMatrix();
dot = n.dotProductWith(d);
mat = [ dot - n.x*d.x, -n.x * d.y, -n.x * d.z, 0,
-n.y * d.x, dot - n.y * d.y, -n.y * d.z, 0,
-n.z * d.x, - n.z * d.y, dot - n.z * d.z, 0,
0, 0, 0, dot ]
glMultMatrixd(mat);
def endShadows(self):
"""This method should be called after shadows have been drawn.
It should always be called to close a call to beginShadows()"""
glPopMatrix();
glDisable(GL_POLYGON_OFFSET_FILL);
glDisable(GL_STENCIL_TEST);
def saveScreenshot(self, filename):
size = self.GetClientSize()
GLUtils.GLUtils_saveScreenShot( filename, 0, 0, size.width, size.height)
def _createGLUIMouseEvent( mouseEvent ):
"""Converts a wx mouse event to a GLUIMouseEvent."""
result = GLUtils.GLUIMouseEvent()
result.altDown = mouseEvent.m_altDown
result.controlDown = mouseEvent.m_controlDown
result.leftDown = mouseEvent.m_leftDown
result.middleDown = mouseEvent.m_middleDown
result.rightDown = mouseEvent.m_rightDown
result.metaDown = mouseEvent.m_metaDown
result.shiftDown = mouseEvent.m_shiftDown
result.x = mouseEvent.m_x
result.y = mouseEvent.m_y
result.wheelRotation = mouseEvent.m_wheelRotation
result.wheelDelta = mouseEvent.m_wheelDelta
result.linesPerAction = mouseEvent.m_linesPerAction
result.moving = mouseEvent.Moving()
result.dragging = mouseEvent.Dragging()
return result
| Python |
'''
Created on 2009-08-25
Basic controller editor
@author: beaudoin
'''
import sys
sys.path += ['.']
import wx, App, math
movieResolution = (1280,720)
movieSetup = False # True if we want a movie
glMovie = False # True if we're only interested in recording the GL canvas
# False if we want a "screen cast"
glCanvasSize = wx.DefaultSize
size = wx.DefaultSize
showConsole = True
if movieSetup:
if glMovie:
glCanvasSize = movieResolution
else:
size = movieResolution
showConsole = False
app = App.SNMApp("Style Editor", size = size, glCanvasSize=glCanvasSize, showConsole = showConsole)
import UI, Utils, GLUtils, Physics, Core, MathLib, PyUtils
from App import InstantChar, KeyframeEditor
# Create the desired tool sets
toolPanel = app.getToolPanel()
animationToolSet = UI.ToolSets.Animation(toolPanel)
if not movieSetup:
optionsToolSet = UI.ToolSets.Options(toolPanel)
optionsToolSet._toolSet.setOpen(False)
cameraToolSet = UI.ToolSets.Camera(toolPanel)
cameraToolSet._toolSet.setOpen(False)
instantChar = InstantChar.Model()
if not movieSetup:
controllerSnapshotToolSet = UI.ToolSets.SnapshotTree(toolPanel)
controllerSnapshotToolSet._toolSet.setOpen(False)
controllerTreeToolSet = UI.ToolSets.ControllerTree(toolPanel)
controllerTreeToolSet._toolSet.setOpen(False)
glCanvas = app.getGLCanvas()
glCanvas.addGLUITool( UI.GLUITools.CurveEditorCollection )
#from Data.Frameworks import DefaultFramework
#from Data.Frameworks import DanceFramework
#from Data.Frameworks import WalkFramework
#####################
## BEGIN Custom for Instant Character
character = instantChar.create()
#controller = PyUtils.load( "Characters.BipV3.Controllers.CartoonySneak", character )
#controller = PyUtils.load( "Characters.BipV3.Controllers.ZeroWalk", character )
#controller = PyUtils.load( "Characters.BipV3.Controllers.VeryFastWalk_5-43_0-4", character )
#controller = PyUtils.load( "Characters.BipV3.Controllers.jog_8-76_0-33", character )
#controller = PyUtils.load( "Characters.BipV3.Controllers.run_21-57_0-38_0-10", character )
#controller = PyUtils.load( "Characters.BipV3.Controllers.FastWalk_3-7_0-53", character )
controller = PyUtils.load( "Characters.BipV3.Controllers.EditableWalking", character )
#controller = PyUtils.load( "Temp.Cartoony", character )
#controller = PyUtils.load( "Temp.TipToe", character )
controller.setStance( Core.LEFT_STANCE );
instantChar.connectController(False)
#character.loadReducedStateFromFile( "Data/Characters/BipV3/Controllers/runState.rs" )
keyframeEditor = KeyframeEditor.Model()
## END
#####################
######################
## BEGIN DUMMY STUFF
#staircase = App.Scenario.Staircase( position=(0,0,5), rightRampHeight = 1, stepCount = 22, leftRampHeight = 1, angle = math.pi/4.0 )
#staircase.load()
#PyUtils.convertController("../../scoros5/data/controllers/bipV3/fWalk_3.sbc")
#ctrl2 = PyUtils.copy( app.getController(0), char )
## END DUMMY STUFF
######################
# Initial snapshot
app.takeSnapshot()
app.MainLoop()
app.Destroy()
| Python |
'''
Created on 2009-08-28
@author: beaudoin
'''
from App.Proxys import *
data = RigidBody(
name = "ground",
locked = True,
cdps = [ BoxCDP( (-50,-1,-50), (50,0,50) ),
PlaneCDP( (0,1,0), (0,-1,0) ) ],
frictionCoeff = 2.5,
restitutionCoeff = 0.35 ) | Python |
'''
Created on 2009-08-28
@author: beaudoin
'''
from App.Proxys import *
data = RigidBody(
name = "ground",
locked = True,
cdps = [ PlaneCDP( (0,1,0), (0,0,0) ) ],
frictionCoeff = 2.5,
restitutionCoeff = 0.35 )
| Python |
'''
Created on 2009-08-28
@author: beaudoin
'''
from App.Proxys import *
data = RigidBody(
name = "dodgeBall",
meshes = [ ("../data/models/sphere.obj",(0.8,0,0,1)) ],
mass = 2.0,
moi = ( 0.2,0.2,0.2 ),
cdps = [ SphereCDP( (0,0,0), 0.1 ) ],
pos = (1000, 1000, 0.2),
frictionCoeff = 1.8,
restitutionCoeff = 0.35 ) | Python |
'''
Created on 2009-08-28
@author: beaudoin
'''
from os import path
meshDir = path.join( path.dirname(__file__), "Meshes" )
colourDark = ( 0.5, 0.5, 0.5, 1 )
colourLight = ( 0.8, 0.8, 0.8, 1 )
from App.Proxys import *
data = Character(
name = "Bip",
root = ArticulatedRigidBody(
name = "pelvis",
meshes = [ (path.join(meshDir, "pelvis_2_b.obj"), colourDark),
(path.join(meshDir, "pelvis_2_s.obj"), colourLight) ],
mass = 12.9,
moi = (0.0705, 0.11, 0.13),
cdps = [ SphereCDP((0,-0.075,0), 0.12) ],
pos = (0, 1.035, 0.2),
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
arbs = [
ArticulatedRigidBody(
name = "torso",
meshes = [ (path.join(meshDir, "torso_2_b.obj"), colourDark),
(path.join(meshDir, "torso_2_s_v2.obj"), colourLight) ],
mass = 22.5,
moi = (0.34, 0.21, 0.46),
cdps = [ SphereCDP((0,0,0.01), 0.11) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "head",
meshes = [ (path.join(meshDir, "head_b.obj"), colourDark),
(path.join(meshDir, "head_s.obj"), colourLight) ],
mass = 5.2,
moi = (0.04, 0.02, 0.042),
cdps = [ SphereCDP((0,0.04,0), 0.11) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lUpperArm",
meshes = [ (path.join(meshDir, "lUpperArm.obj"), colourDark) ],
mass = 2.2,
moi = (0.005, 0.02, 0.02),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lLowerArm",
meshes = [ (path.join(meshDir, "lLowerArm.obj"), colourDark) ],
mass = 1.7,
moi = (0.0024, 0.025, 0.025),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rUpperArm",
meshes = [ (path.join(meshDir, "rUpperArm.obj"), colourDark) ],
mass = 2.2,
moi = (0.005, 0.02, 0.02),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rLowerArm",
meshes = [ (path.join(meshDir, "rLowerArm.obj"), colourDark) ],
mass = 1.7,
moi = (0.0024, 0.025, 0.025),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lUpperLeg",
meshes = [ (path.join(meshDir, "lUpperLeg.obj"), colourDark) ],
mass = 6.6,
moi = (0.15, 0.022, 0.15),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.26, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lLowerLeg",
meshes = [ (path.join(meshDir, "lLowerLeg.obj"), colourDark) ],
mass = 3.2,
moi = (0.055, 0.007, 0.055),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.2, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rUpperLeg",
meshes = [ (path.join(meshDir, "rUpperLeg.obj"), colourDark) ],
mass = 6.6,
moi = (0.15, 0.022, 0.15),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.26, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rLowerLeg",
meshes = [ (path.join(meshDir, "rLowerLeg.obj"), colourDark) ],
mass = 3.2,
moi = (0.055, 0.007, 0.055),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.2, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lFoot",
meshes = [ (path.join(meshDir, "lFoot.obj"), colourDark) ],
mass = 1.0,
moi = (0.007, 0.008, 0.002),
cdps = [ BoxCDP((-0.025, -0.033, -0.09), (0.025, 0.005, 0.055)) ],
# CDP_Sphere 0.025 -0.025 -0.08 0.01
# CDP_Sphere -0.025 -0.025 -0.08 0.01
# CDP_Sphere 0.02 -0.025 0.045 0.01
# CDP_Sphere -0.02 -0.025 0.045 0.01
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) ),
ArticulatedRigidBody(
name = "rFoot",
meshes = [ (path.join(meshDir, "rFoot.obj"), colourDark) ],
mass = 1.0,
moi = (0.007, 0.008, 0.002),
cdps = [ BoxCDP((-0.025, -0.033, -0.09), (0.025, 0.005, 0.055)) ],
# CDP_Sphere 0.025 -0.025 -0.08 0.01
# CDP_Sphere -0.025 -0.025 -0.08 0.01
# CDP_Sphere 0.02 -0.025 0.045 0.01
# CDP_Sphere -0.02 -0.025 0.045 0.01
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) ),
ArticulatedRigidBody(
name = "lToes",
meshes = [ (path.join(meshDir, "lToes.obj"), colourDark) ],
mass = 0.2,
moi = (0.002, 0.002, 0.0005),
cdps = [ SphereCDP((0.0, -0.005, 0.025), 0.01) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) ),
ArticulatedRigidBody(
name = "rToes",
meshes = [ (path.join(meshDir, "rToes.obj"), colourDark) ],
mass = 0.2,
moi = (0.002, 0.002, 0.0005),
cdps = [ SphereCDP((0.0, -0.005, 0.025), 0.01) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) )
],
joints = [
BallInSocketJoint(
name = "pelvis_torso",
parent = "pelvis",
child = "torso",
posInParent = (0, 0.17, -0.035),
posInChild = (0, -0.23, -0.01),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "torso_head",
parent = "torso",
child = "head",
posInParent = (0, 0.1, -0.00),
posInChild = (0, -0.16, -0.025),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "lShoulder",
parent = "torso",
child = "lUpperArm",
posInParent = (0.20, 0.07, 0.02),
posInChild = (-0.17, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = ( 1, 0, 0),
limits = (-1.7, 1.7, -1.5, 1.5, -1.5, 1.5) ),
BallInSocketJoint(
name = "rShoulder",
parent = "torso",
child = "rUpperArm",
posInParent = (-0.20, 0.07, 0.02),
posInChild = (0.17, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = ( 1, 0, 0),
limits = (-1.7, 1.7, -1.5, 1.5, -1.5, 1.5) ),
HingeJoint(
name = "lElbow",
parent = "lUpperArm",
child = "lLowerArm",
posInParent = (0.175, 0, 0.006),
posInChild = (-0.215, 0, 0),
axis = ( 0, 1, 0 ),
limits = (-2.7, 0) ),
HingeJoint(
name = "rElbow",
parent = "rUpperArm",
child = "rLowerArm",
posInParent = (-0.175, 0, 0.006),
posInChild = (0.215, 0, 0),
axis = ( 0, -1, 0 ),
limits = (-2.7, 0) ),
BallInSocketJoint(
name = "lHip",
parent = "pelvis",
child = "lUpperLeg",
posInParent = (0.1, -0.05, 0.0),
posInChild = (0, 0.21, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-1.3, 1.9, -1, 1, -0.25, 1) ),
BallInSocketJoint(
name = "rHip",
parent = "pelvis",
child = "rUpperLeg",
posInParent = (-0.1, -0.05, 0.0),
posInChild = (0, 0.21, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-1.3, 1.9, -1, 1, -1, 0.25) ),
HingeJoint(
name = "lKnee",
parent = "lUpperLeg",
child = "lLowerLeg",
posInParent = (0, -0.26, 0),
posInChild = (0, 0.21, 0),
axis = ( 1, 0, 0 ),
limits = (0, 2.5) ),
HingeJoint(
name = "rKnee",
parent = "rUpperLeg",
child = "rLowerLeg",
posInParent = (0, -0.26, 0),
posInChild = (0, 0.21, 0),
axis = ( 1, 0, 0 ),
limits = (0, 2.5) ),
UniversalJoint(
name = "lAnkle",
parent = "lLowerLeg",
child = "lFoot",
posInParent = (0, -0.25, 0.01),
posInChild = (0.0, 0.02, -0.04),
parentAxis = (1, 0, 0),
childAxis = (0, 0, 1),
limits = (-0.75, 0.75, -0.75, 0.75) ),
UniversalJoint(
name = "rAnkle",
parent = "rLowerLeg",
child = "rFoot",
posInParent = (0, -0.25, 0.01),
posInChild = (0.0, 0.02, -0.04),
parentAxis = (1, 0, 0),
childAxis = (0, 0, -1),
limits = (-0.75, 0.75, -0.75, 0.75) ),
HingeJoint(
name = "lToeJoint",
parent = "lFoot",
child = "lToes",
posInParent = (0, -0.02, 0.05),
posInChild = (0, 0, -0.025),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.02) ),
HingeJoint(
name = "rToeJoint",
parent = "rFoot",
child = "rToes",
posInParent = (0, -0.02, 0.05),
posInChild = (0, 0, -0.025),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.02) )
]
)
| Python |
from App.Proxys import *
data = SimBiController(
name = 'Turning',
controlParamsList = [
ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'pelvis_torso', kp = 200.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 200.0, kd = 20.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 20.0, kd = 5.0, tauMax = 10000.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 20.0, kd = 5.0, tauMax = 10000.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 75.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 75.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 10.0, kd = 0.5, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 10.0, kd = 0.5, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 1,
duration = 0.7,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [ ( 0.319408095177, 59.9547123615 ) ],
forceY = [ ( 0.0, 0.0 ) ],
forceZ = [ ( 0.693332994276, -5.26775796183 ), ( 0.693342994276, 54.4334989389 ) ],
torqueX = [ ],
torqueY = [
( 0.0236475679619, 14.3936675448 ),
( 0.38629006461, 50.9613634694 ),
( 0.841129806169, -34.6226057158 ) ],
torqueZ = [ ] ) ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.020067, 0.0713 ), ( 0.538462, 0.0713 ), ( 0.966555, 0.0713 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.006689, 0.037422 ), ( 0.491639, -0.030618 ), ( 0.993311, 0.034506 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, -0.015813 ), ( 0.354515, 0.024849 ), ( 0.508361, 0.196533 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = -0.3, cv = -0.3 ),
baseTrajectory = [
( 0.023411, -0.091589 ),
( 0.230769, -0.476365 ),
( 0.521739, -0.218055 ),
( 0.70903, -0.035635 ),
( 0.842809, -0.002125 ),
( 0.986622, -0.000708 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1.0, 0.0, 0.0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.73913, -0.058739 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.016722, 0.887089 ),
( 0.250836, 0.800963 ),
( 0.428094, 0.659216 ),
( 0.555184, 0.47829 ),
( 0.632107, 0.142159 ),
( 0.77592, -0.027983 ),
( 0.993311, -0.03162 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.046823, 0.39623 ), ( 0.207358, 0.134641 ), ( 0.662207, -0.011162 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0.0, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.5804 ), ( 0.22408, 0.862791 ), ( 0.431438, -0.048689 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = 0.2, cv = 0.2 ),
baseTrajectory = [ ( 0.016722, -0.203606 ), ( 0.551839, -0.217268 ), ( 1.0, 0.030252 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.57 ), ( 1.0, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.036789, 0.087916 ), ( 0.665552, -0.282452 ), ( 0.989967, -0.224412 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 1.57 ), ( 1.0, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.003344, 0.03002 ),
( 0.180602, 0.002729 ),
( 0.494983, -0.011906 ),
( 0.802676, 0.068758 ),
( 0.986622, 0.078197 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.033445, 0.310933 ), ( 0.521739, 0.419418 ), ( 0.939799, 0.310933 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.003344, -0.036889 ), ( 0.608696, -0.391027 ), ( 1.0, -0.3 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0170029671656, 0.546257090497 ), ( 0.640214956672, 0.168866831761 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.117057, -0.001063 ), ( 0.511706, 0.024454 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.280602, 0.015874 ), ( 0.99, 0.0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.0 ), ( 0.508361, 0.05 ), ( 0.986622, 0.0 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] )
]
),
SimBiConState(
name = 'State 1',
nextStateIndex = 1,
duration = 0.7,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [ ( 0.0, 0.0 ) ],
forceY = [ ( 0.0, 0.0 ) ],
forceZ = [ ( 0.0, 0.0 ) ],
torqueX = [ ],
torqueY = [ ],
torqueZ = [ ] ) ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.020067, 0.0713 ), ( 0.538462, 0.0713 ), ( 0.966555, 0.0713 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.006689, 0.037422 ), ( 0.491639, -0.030618 ), ( 0.993311, 0.034506 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, -0.015813 ), ( 0.354515, 0.024849 ), ( 0.508361, 0.196533 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = -0.3, cv = -0.3 ),
baseTrajectory = [
( 0.023411, -0.091589 ),
( 0.230769, -0.476365 ),
( 0.521739, -0.218055 ),
( 0.70903, -0.035635 ),
( 0.842809, -0.002125 ),
( 0.986622, -0.000708 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1.0, 0.0, 0.0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.73913, -0.058739 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.016722, 0.887089 ),
( 0.250836, 0.800963 ),
( 0.428094, 0.659216 ),
( 0.555184, 0.47829 ),
( 0.632107, 0.142159 ),
( 0.77592, -0.027983 ),
( 0.993311, -0.03162 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.046823, 0.39623 ), ( 0.207358, 0.134641 ), ( 0.662207, -0.011162 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0.0, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 1.5804 ),
( 0.22408, 0.862791 ),
( 0.431438, -0.048689 ),
( 0.688963, -0.71086 ),
( 0.986622, -0.782532 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = 0.2, cv = 0.2 ),
baseTrajectory = [ ( 0.016722, -0.203606 ), ( 0.551839, -0.217268 ), ( 1.0, 0.030252 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.57 ), ( 1.0, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.036789, 0.087916 ), ( 0.665552, -0.282452 ), ( 0.989967, -0.224412 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 1.57 ), ( 1.0, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.003344, 0.03002 ),
( 0.180602, 0.002729 ),
( 0.494983, -0.011906 ),
( 0.802676, 0.068758 ),
( 0.986622, 0.078197 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.033445, 0.310933 ), ( 0.521739, 0.419418 ), ( 0.939799, 0.310933 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.003344, -0.036889 ), ( 0.608696, -0.391027 ), ( 1.0, -0.3 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.00034 ), ( 0.505017, -0.100323 ), ( 0.986622, -0.001158 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.117057, -0.001063 ), ( 0.511706, 0.024454 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.280602, 0.015874 ), ( 0.99, 0.0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.0 ), ( 0.508361, 0.05 ), ( 0.986622, 0.0 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] )
]
)
]
) | Python |
from App.Proxys import *
data = SimBiController(
name = 'Jumping',
controlParamsList = [
ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'pelvis_torso', kp = 1000.0, kd = 100.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 200.0, kd = 20.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rAnkle', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lToeJoint', kp = 50.0, kd = 5.0, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 50.0, kd = 5.0, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State0',
nextStateIndex = 1,
transitionOn = 'TIME_UP',
duration = 2.0,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [ ( 0.0, 0.0 ) ],
forceY = [
( 0.220257139643, -0.297893823029 ),
( 0.269866998824, 4009.37843155 ),
( 0.323865606442, -0.297893823029 ) ],
forceZ = [
( 0.22457639404, 0.230547728033 ),
( 0.312787202786, 1969.12899193 ),
( 0.340594719742, 0.281229318864 ) ],
torqueX = [
( 0.336683417085, 0.026145829397 ),
( 0.388500473607, -54.4526060901 ),
( 0.448698407471, -3.77495360492 ),
( 0.677040782713, -1.51348004883 ),
( 0.878199541855, -0.759655530132 ),
( 1.03586451524, -30.912636278 ) ],
torqueY = [
( 0.361809045226, -0.0251256281407 ),
( 0.429548422996, -8.20440959163 ),
( 0.474930850007, -0.0223053848099 ) ],
torqueZ = [
( 0.336683417085, 0.0753768844221 ),
( 0.416682339801, -13.6502244593 ),
( 0.462311557789, 0.0251256281407 ) ] ) ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.488294, 0.113631 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.197367186158, -0.311997836151 ),
( 0.29648241206, -2.0351758794 ),
( 0.557788944724, -1.03015075377 ),
( 0.663316582915, -0.929648241206 ),
( 1.06507609055, 0.082112161635 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.06 ), ( 0.5, -0.06 ), ( 1.0, -0.06 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Hip',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.195969899497, -1.08040201005 ),
( 0.195979899497, 0.0251256281407 ),
( 0.43216080402, 0.0753768844221 ),
( 0.984924623116, -1.08040201005 ) ] ),
TrajectoryComponent( rotationAxis = ( 0.0, 0.0, 1.0 ), reverseOnStance = 'LEFT', baseTrajectory = [ ( 0.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.336683417085, 1.4824120603 ), ( 0.552763819095, 0.175879396985 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.16105827842, 0.873209081588 ),
( 0.224457449363, 0.0138604616125 ),
( 0.43216080402, 0.0753768844221 ),
( 0.723618090452, 1.93467336683 ),
( 0.989949748744, 0.879396984925 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.020067, 0.809573 ),
( 0.197324, -0.510418 ),
( 0.27135678392, -0.326633165829 ),
( 0.658291457286, 0.376884422111 ),
( 0.994974874372, 0.527638190955 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.211055276382, -0.326633165829 ), ( 0.261306532663, 0.577889447236 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.327759, 1.733668 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0301, -0.005792 ), ( 0.41806, -0.277104 ), ( 0.973244, -0.017375 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.006689, -0.025126 ), ( 0.505017, -0.138526 ), ( 0.996656, -0.025126 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.110368, 1.884422 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.023411, 0.003989 ), ( 0.471572, 0.243329 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.013378, 0.005066 ), ( 0.448161, 0.321392 ), ( 0.993311, 0.025126 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ( 0.307692, 2.135678 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.307692, 2.573897 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ( 0.364548, 2.98995 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.013378, -2.665055 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.598662, 0.138959 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.685619, 0.026046 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.692308, 0.025126 ), ( 0.856187, -1.532663 ) ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.38796, 0.014868 ), ( 0.826087, -0.431185 ) ] ) ] )
]
),
SimBiConState(
name = 'State1',
nextStateIndex = 1,
transitionOn = 'TIME_UP',
duration = 0.4,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [ ( 0.0, 0.0 ) ],
forceY = [ ( 0.0, 0.0 ) ],
forceZ = [ ( 0.0, 0.0 ) ],
torqueX = [ ],
torqueY = [ ],
torqueZ = [ ] ) ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.488294, 0.113631 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = -0.55, cv = -0.3 ),
baseTrajectory = [ ( 0.541806, -0.438308 ), ( 0.692308, -0.362199 ), ( 0.859532, -0.160317 ), ( 0.996656, 0.200194 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1.0, 0.0, 0.0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.0, -0.06 ), ( 0.5, -0.06 ), ( 1.0, -0.06 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.528428, 1.658482 ), ( 0.80602, 1.006429 ), ( 0.983278, 0.354748 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.147157, 0.130628 ),
( 0.394649, 0.318731 ),
( 0.61204, 0.29114 ),
( 0.832776, 0.236208 ),
( 0.989967, 0.576787 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.020067, 0.809573 ),
( 0.197324, -0.510418 ),
( 0.488294, -0.518456 ),
( 0.75, -0.5 ),
( 0.751, -0.15 ),
( 1.0, -0.15 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.354515, -0.354772 ), ( 0.625418, 0.764028 ), ( 0.749164, 1.163781 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.327759, 1.733668 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0301, -0.005792 ), ( 0.41806, -0.277104 ), ( 0.973244, -0.017375 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.006689, -0.025126 ), ( 0.505017, -0.138526 ), ( 0.996656, -0.025126 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.110368, 1.884422 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.023411, 0.003989 ), ( 0.471572, 0.243329 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.013378, 0.005066 ), ( 0.448161, 0.321392 ), ( 0.993311, 0.025126 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ( 0.307692, 2.135678 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.307692, 2.573897 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ( 0.364548, 2.98995 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.013378, -2.665055 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.598662, 0.138959 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.685619, 0.026046 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.692308, 0.025126 ), ( 0.856187, -1.532663 ) ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.38796, 0.014868 ), ( 0.826087, -0.431185 ) ] ) ] )
]
)
]
) | Python |
'''
Created on 2009-09-09
@author: beaudoin
'''
from App.Proxys import *
data = SimBiController(
name = 'Walking',
startingState = 0,
controlParamsList = [
ControlParams( joint = 'root', kp = 3000, kd = 300, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'pelvis_torso', kp = 200, kd = 30, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'lHip', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.66, 1 ) ),
ControlParams( joint = 'rHip', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.66, 1 ) ),
ControlParams( joint = 'torso_head', kp = 200, kd = 20, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'lShoulder', kp = 20, kd = 5, tauMax = 10000, scale = ( 0.5, 1, 1 ) ),
ControlParams( joint = 'rShoulder', kp = 20, kd = 5, tauMax = 10000, scale = ( 0.3, 1, 1 ) ),
ControlParams( joint = 'lKnee', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'rKnee', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'lElbow', kp = 5, kd = 1, tauMax = 10000, scale = ( 0.2, 1, 1 ) ),
ControlParams( joint = 'rElbow', kp = 5, kd = 1, tauMax = 10000, scale = ( 0.2, 1, 1 ) ),
ControlParams( joint = 'lAnkle', kp = 75, kd = 10, tauMax = 10000, scale = ( 1, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 75, kd = 10, tauMax = 10000, scale = ( 1, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 10, kd = 0.5, tauMax = 10000, scale = ( 1, 1, 1 ) ),
ControlParams( joint = 'rToeJoint', kp = 10, kd = 0.5, tauMax = 10000, scale = ( 1, 1, 1 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
transitionOn = 'FOOT_CONTACT',
stance = 'REVERSE',
duration = 0.7,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [(0,0)],
forceY = [(0,0)],
forceZ = [(0,0)] )
],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ( 0, 1 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [ ( 0.020067, 0.0713 ), ( 0.538462, 0.0713 ), ( 0.966555, 0.0713 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.006689, 0.037422 ), ( 0.491639, -0.030618 ), ( 0.993311, 0.034506 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ( 0, 1 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, -0.015813 ), ( 0.354515, 0.024849 ), ( 0.508361, 0.196533 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
feedback = LinearBalanceFeedback( axis = ( 0, 0, 1 ), cd = -0.3, cv = -0.3 ),
baseTrajectory = [
( 0.023411, -0.091589 ),
( 0.230769, -0.476365 ),
( 0.521739, -0.218055 ),
( 0.70903, -0.035635 ),
( 0.842809, -0.002125 ),
( 0.986622, -0.000708 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1, 0, 0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.73913, -0.058739 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [
( 0.016722, 0.887089 ),
( 0.250836, 0.800963 ),
( 0.428094, 0.659216 ),
( 0.555184, 0.47829 ),
( 0.632107, 0.142159 ),
( 0.77592, -0.027983 ),
( 0.993311, -0.03162 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [ ( 0.046823, 0.39623 ), ( 0.207358, 0.134641 ), ( 0.662207, -0.011162 ), ( 1, 0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0, 1 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [
( 0, 1.5804 ),
( 0.22408, 0.862791 ),
( 0.431438, -0.048689 ),
( 0.688963, -0.71086 ),
( 0.986622, -0.782532 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
feedback = LinearBalanceFeedback( axis = ( 0, 0, 1 ), cd = 0.2, cv = 0.2 ),
baseTrajectory = [ ( 0.016722, -0.203606 ), ( 0.551839, -0.217268 ), ( 1, 0.030252 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0, 1.57 ), ( 1, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [ ( 0.036789, 0.087916 ), ( 0.665552, -0.282452 ), ( 0.989967, -0.224412 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0, 1.57 ), ( 1, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [
( 0.003344, 0.03002 ),
( 0.180602, 0.002729 ),
( 0.494983, -0.011906 ),
( 0.802676, 0.068758 ),
( 0.986622, 0.078197 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.033445, 0.310933 ), ( 0.521739, 0.419418 ), ( 0.939799, 0.310933 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.003344, -0.036889 ), ( 0.608696, -0.391027 ), ( 1, -0.3 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.00034 ), ( 0.505017, -0.100323 ), ( 0.986622, -0.001158 ) ] ),
TrajectoryComponent( rotationAxis = ( 1, 0, 0 ), baseTrajectory = [ ( 0.117057, -0.001063 ), ( 0.511706, 0.024454 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0, 0 ), ( 0.280602, 0.015874 ), ( 0.99, 0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0 ), ( 0.508361, 0.05 ), ( 0.986622, 0 ) ] ),
TrajectoryComponent( rotationAxis = ( 1, 0, 0 ) ) ] )
]
)
]
)
| Python |
from App.Proxys import *
data = SimBiController(
name = 'Walking',
controlParamsList = [
ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'pelvis_torso', kp = 200.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 200.0, kd = 20.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 20.0, kd = 5.0, tauMax = 10000.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 20.0, kd = 5.0, tauMax = 10000.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 75.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 75.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 10.0, kd = 0.5, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 10.0, kd = 0.5, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.7,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [ ( 0.0, 0.0 ) ],
forceY = [
( 0.228828884494, -481.092195147 ),
( 0.620017798112, 825.542462415 ),
( 0.876735522675, -793.791087555 ) ],
forceZ = [ ( 0.496870702609, 26.2427270763 ) ],
torqueX = [ ],
torqueY = [ ],
torqueZ = [ ] ) ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.020067, 0.0713 ), ( 0.538462, 0.0713 ), ( 0.966555, 0.0713 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.006689, 0.037422 ), ( 0.491639, -0.030618 ), ( 0.993311, 0.034506 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, -0.015813 ), ( 0.354515, 0.024849 ), ( 0.508361, 0.196533 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = -0.3, cv = -0.3 ),
baseTrajectory = [
( 0.023411, -0.091589 ),
( 0.230769, -0.476365 ),
( 0.521739, -0.218055 ),
( 0.70903, -0.035635 ),
( 0.842809, -0.002125 ),
( 0.986622, -0.000708 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1.0, 0.0, 0.0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.73913, -0.058739 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.016722, 0.887089 ),
( 0.250836, 0.800963 ),
( 0.428094, 0.659216 ),
( 0.555184, 0.47829 ),
( 0.632107, 0.142159 ),
( 0.77592, -0.027983 ),
( 0.993311, -0.03162 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.046823, 0.39623 ), ( 0.207358, 0.134641 ), ( 0.662207, -0.011162 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0.0, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 1.5804 ),
( 0.22408, 0.862791 ),
( 0.431438, -0.048689 ),
( 0.688963, -0.71086 ),
( 0.986622, -0.782532 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = 0.2, cv = 0.2 ),
baseTrajectory = [ ( 0.016722, -0.203606 ), ( 0.551839, -0.217268 ), ( 1.0, 0.030252 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.57 ), ( 1.0, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.036789, 0.087916 ), ( 0.665552, -0.282452 ), ( 0.989967, -0.224412 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 1.57 ), ( 1.0, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.003344, 0.03002 ),
( 0.180602, 0.002729 ),
( 0.494983, -0.011906 ),
( 0.802676, 0.068758 ),
( 0.986622, 0.078197 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.033445, 0.310933 ), ( 0.521739, 0.419418 ), ( 0.939799, 0.310933 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.003344, -0.036889 ), ( 0.608696, -0.391027 ), ( 1.0, -0.3 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.00034 ), ( 0.505017, -0.100323 ), ( 0.986622, -0.001158 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.117057, -0.001063 ), ( 0.511706, 0.024454 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.280602, 0.015874 ), ( 0.99, 0.0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.0 ), ( 0.508361, 0.05 ), ( 0.986622, 0.0 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] )
]
)
]
) | Python |
'''
Created on 2009-09-09
@author: beaudoin
'''
from App.Proxys import *
data = SimBiController(
name = 'Running',
startingState = 0,
controlParamsList = [
ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'pelvis_torso', kp = 1000.0, kd = 100.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 200.0, kd = 20.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rAnkle', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lToeJoint', kp = 50.0, kd = 5.0, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 50.0, kd = 5.0, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
transitionOn = 'TIME_UP',
stance = 'REVERSE',
duration = 0.4,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [(0,0)],
forceY = [(0,0)],
forceZ = [(0,0)] )
],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.488294, 0.113631 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = -0.55, cv = -0.3 ),
baseTrajectory = [ ( 0.541806, -0.438308 ), ( 0.692308, -0.362199 ), ( 0.859532, -0.160317 ), ( 0.996656, 0.200194 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1.0, 0.0, 0.0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.0, -0.06 ), ( 0.5, -0.06 ), ( 1.0, -0.06 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.528428, 1.658482 ), ( 0.80602, 1.006429 ), ( 0.983278, 0.354748 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.147157, 0.130628 ),
( 0.394649, 0.318731 ),
( 0.61204, 0.29114 ),
( 0.832776, 0.236208 ),
( 0.989967, 0.576787 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.020067, 0.809573 ),
( 0.197324, -0.510418 ),
( 0.488294, -0.518456 ),
( 0.75, -0.5 ),
( 0.751, -0.15 ),
( 1.0, -0.15 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.354515, -0.354772 ), ( 0.625418, 0.764028 ), ( 0.749164, 1.163781 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.327759, 1.733668 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0301, -0.005792 ), ( 0.41806, -0.277104 ), ( 0.973244, -0.017375 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.006689, -0.025126 ), ( 0.505017, -0.138526 ), ( 0.996656, -0.025126 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.110368, 1.884422 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.023411, 0.003989 ), ( 0.471572, 0.243329 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.013378, 0.005066 ), ( 0.448161, 0.321392 ), ( 0.993311, 0.025126 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ( 0.307692, 2.135678 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.307692, 2.573897 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ( 0.364548, 2.98995 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.013378, -2.665055 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.598662, 0.138959 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.685619, 0.026046 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.692308, 0.025126 ), ( 0.856187, -1.532663 ) ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.38796, 0.014868 ), ( 0.826087, -0.431185 ) ] ) ] )
]
)
]
)
| Python |
from App.Proxys import *
data = SimBiController(
name = 'Running',
controlParamsList = [
ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'pelvis_torso', kp = 1000.0, kd = 100.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 200.0, kd = 20.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rAnkle', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lToeJoint', kp = 50.0, kd = 5.0, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 50.0, kd = 5.0, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'Default state in the walking controller',
nextStateIndex = 0,
transitionOn = 'TIME_UP',
duration = 0.4,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [ ( 0.463986797381, 88.822109274 ) ],
forceY = [ ( 0.0, 0.0 ) ],
forceZ = [ ( 0.543945213314, -43.3990089807 ) ],
torqueX = [ ],
torqueY = [ ( 0.532200954731, 7.14704129206 ) ],
torqueZ = [ ] ) ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.488294, 0.113631 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = -0.55, cv = -0.3 ),
baseTrajectory = [
( 0.511418617829, -0.473413246148 ),
( 0.692308, -0.362199 ),
( 0.859532, -0.160317 ),
( 0.996656, 0.200194 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1.0, 0.0, 0.0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.0, -0.06 ), ( 0.5, -0.06 ), ( 1.0, -0.06 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.528428, 1.658482 ), ( 0.80602, 1.006429 ), ( 0.983278, 0.354748 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.147157, 0.130628 ),
( 0.394649, 0.318731 ),
( 0.61204, 0.29114 ),
( 0.832776, 0.236208 ),
( 0.989967, 0.576787 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.020067, 0.809573 ),
( 0.197324, -0.510418 ),
( 0.488294, -0.518456 ),
( 0.75, -0.5 ),
( 0.751, -0.15 ),
( 1.0, -0.15 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.354515, -0.354772 ), ( 0.625418, 0.764028 ), ( 0.749164, 1.163781 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.327759, 1.733668 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0301, -0.005792 ), ( 0.41806, -0.277104 ), ( 0.973244, -0.017375 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.006689, -0.025126 ), ( 0.505017, -0.138526 ), ( 0.996656, -0.025126 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.110368, 1.884422 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.023411, 0.003989 ), ( 0.471572, 0.243329 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.013378, 0.005066 ), ( 0.448161, 0.321392 ), ( 0.993311, 0.025126 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ( 0.307692, 2.135678 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.307692, 2.573897 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ( 0.364548, 2.98995 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.013378, -2.665055 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
components = [
TrajectoryComponent( rotationAxis = ( 0.0, 1.0, 0.0 ), baseTrajectory = [ ( 0.211055276382, -0.226130653266 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.598662, 0.138959 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.685619, 0.026046 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.692308, 0.025126 ), ( 0.856187, -1.532663 ) ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.38796, 0.014868 ), ( 0.826087, -0.431185 ) ] ) ] )
]
)
]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 300.0, kd = 100.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 10.0, kd = 3.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.003344, 0.204846 ), ( 0.959866, 0.070153 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.3 ), ( 0.3, 0.3 ), ( 0.4, 0.0 ), ( 1.0, -0.3 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [
( -0.5, 2.0 ),
( -0.1, 1.0 ),
( 0.0, 0.0 ),
( 0.1, 1.0 ),
( 0.5, 2.5 ),
( 1.0, 6.0 ),
( 1.1, 7.0 ),
( 1.5, 3.0 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ( 0.3, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.3, 0.0 ), ( 0.8, 0.0 ), ( 1.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.1, 0.5 ), ( 0.0, 0.0 ), ( 0.2, 0.2 ), ( 0.5, 0.2 ), ( 1.0, 2.5 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.57 ), ( 0.752508, -1.473995 ), ( 0.979933, -1.308908 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cv = 0.1, vLimits = ( -0.6, 0.6 ) ),
baseTrajectory = [ ( 0.0, 0.143195 ), ( 0.558653, 0.193845 ), ( 0.813333, 0.16319 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.57 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cv = -0.1, vLimits = ( -0.6, 0.6 ) ),
baseTrajectory = [ ( 0.0, -0.2 ), ( 0.842809, -0.176382 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.006689, -0.1 ), ( 0.568562, -0.2 ), ( 0.989967, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 0.8, 0.15 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.0 ), ( 0.8, 1.0 ) ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.508361, -0.2 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.1 ), ( 0.5, 0.5 ), ( 1.0, 1.0 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.3, 0.0 ), ( 0.75, 0.2 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.0 ), ( 0.8, 1.0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
]
) | Python |
'''
Created on 2009-09-09
@author: beaudoin
'''
from App.Proxys import *
data = SimBiController(
name = 'Walking',
startingState = 0,
controlParamsList = [
ControlParams( joint = 'root', kp = 3000, kd = 300, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'pelvis_torso', kp = 200, kd = 30, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'lHip', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.66, 1 ) ),
ControlParams( joint = 'rHip', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.66, 1 ) ),
ControlParams( joint = 'torso_neck', kp = 200, kd = 20, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'lShoulder', kp = 20, kd = 5, tauMax = 10000, scale = ( 0.5, 1, 1 ) ),
ControlParams( joint = 'rShoulder', kp = 20, kd = 5, tauMax = 10000, scale = ( 0.3, 1, 1 ) ),
ControlParams( joint = 'lWrist', kp = 10, kd = 2.5, tauMax = 10000, scale = ( 1, 0.2, 0.2 ) ),
ControlParams( joint = 'rWrist', kp = 10, kd = 2.5, tauMax = 10000, scale = ( 1, 0.2, 0.2 ) ),
ControlParams( joint = 'lKnee', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'rKnee', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'lElbow', kp = 5, kd = 1, tauMax = 10000, scale = ( 0.2, 1, 1 ) ),
ControlParams( joint = 'rElbow', kp = 5, kd = 1, tauMax = 10000, scale = ( 0.2, 1, 1 ) ),
ControlParams( joint = 'lAnkle', kp = 75, kd = 10, tauMax = 10000, scale = ( 1, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 75, kd = 10, tauMax = 10000, scale = ( 1, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 10, kd = 0.5, tauMax = 10000, scale = ( 1, 1, 1 ) ),
ControlParams( joint = 'rToeJoint', kp = 10, kd = 0.5, tauMax = 10000, scale = ( 1, 1, 1 ) )
],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
transitionOn = 'FOOT_CONTACT',
stance = 'REVERSE',
duration = 0.7,
trajectories = [
Trajectory(
joint = 'root',
strength = [ ( 0, 1 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [ ( 0.020067, 0.0713 ), ( 0.538462, 0.0713 ), ( 0.966555, 0.0713 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.006689, 0.037422 ), ( 0.491639, -0.030618 ), ( 0.993311, 0.034506 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ( 0, 1 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, -0.015813 ), ( 0.354515, 0.024849 ), ( 0.508361, 0.196533 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
feedback = LinearBalanceFeedback( axis = ( 0, 0, 1 ), cd = -0.3, cv = -0.3 ),
baseTrajectory = [
( 0.023411, -0.091589 ),
( 0.230769, -0.476365 ),
( 0.521739, -0.218055 ),
( 0.70903, -0.035635 ),
( 0.842809, -0.002125 ),
( 0.986622, -0.000708 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1, 0, 0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.73913, -0.058739 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [
( 0.016722, 0.887089 ),
( 0.250836, 0.800963 ),
( 0.428094, 0.659216 ),
( 0.555184, 0.47829 ),
( 0.632107, 0.142159 ),
( 0.77592, -0.027983 ),
( 0.993311, -0.03162 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [ ( 0.046823, 0.39623 ), ( 0.207358, 0.134641 ), ( 0.662207, -0.011162 ), ( 1, 0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0, 1 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [
( 0, 1.5804 ),
( 0.22408, 0.862791 ),
( 0.431438, -0.048689 ),
( 0.688963, -0.71086 ),
( 0.986622, -0.782532 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
feedback = LinearBalanceFeedback( axis = ( 0, 0, 1 ), cd = 0.2, cv = 0.2 ),
baseTrajectory = [ ( 0.016722, -0.203606 ), ( 0.551839, -0.217268 ), ( 1, 0.030252 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0, 1.57 ), ( 1, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [ ( 0.036789, 0.087916 ), ( 0.665552, -0.282452 ), ( 0.989967, -0.224412 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0, 1.57 ), ( 1, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [
( 0.003344, 0.03002 ),
( 0.180602, 0.002729 ),
( 0.494983, -0.011906 ),
( 0.802676, 0.068758 ),
( 0.986622, 0.078197 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.033445, 0.310933 ), ( 0.521739, 0.419418 ), ( 0.939799, 0.310933 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.003344, -0.036889 ), ( 0.608696, -0.391027 ), ( 1, -0.3 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.00034 ), ( 0.505017, -0.100323 ), ( 0.986622, -0.001158 ) ] ),
TrajectoryComponent( rotationAxis = ( 1, 0, 0 ), baseTrajectory = [ ( 0.117057, -0.001063 ), ( 0.511706, 0.024454 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0, 0 ), ( 0.280602, 0.015874 ), ( 0.99, 0 ) ] ) ] ),
Trajectory(
joint = 'torso_neck',
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0 ), ( 0.508361, 0.05 ), ( 0.986622, 0 ) ] ),
TrajectoryComponent( rotationAxis = ( 1, 0, 0 ) ) ] )
]
)
]
)
| Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.71,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.5675 ), ( 0.5, 0.7775 ), ( 1.0, 0.5675 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 0.5, 0.395005787037 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 0.5, 0.234994212963 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.5, -1.5 ), ( 1.0, 0.0352692469298 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.25 ), ( 0.5, 0.292441001978 ), ( 1.0, -1.90266501957 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.0352692469298 ), ( 0.5, 1.5 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -1.90266501957 ), ( 0.5, -0.306916761712 ), ( 1.0, -0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ), ( 0.5, 0.1 ), ( 1.0, 2.36557411429 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -2.36557411429 ), ( 0.5, -0.1 ), ( 1.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.25605985176 ), ( 0.5, 0.0 ), ( 1.0, 0.25605985176 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.0353280996748 ), ( 0.5, 0.20780840116 ), ( 1.0, -0.0353280996748 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.431240696418 ), ( 0.5, 0.0 ), ( 1.0, -0.431240696418 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0408453732455 ), ( 0.5, 0.407477192474 ), ( 1.0, 0.0408453732455 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.713153999991 ), ( 0.5, 0.0 ), ( 1.0, -0.713153999991 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.430555555556 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.01875 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = WalkController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 500.0, kd = 50.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 10.0, kd = 3.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.140703517588, 0.929648241206 ), ( 0.643216080402, 0.175879396985 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.3 ), ( 0.3, 0.3 ), ( 0.4, 0.0 ), ( 1.0, -0.3 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [
( -0.5, 2.0 ),
( -0.1, 1.0 ),
( 0.0, 0.0 ),
( 0.1, 1.0 ),
( 0.5, 2.5 ),
( 1.0, 6.0 ),
( 1.1, 7.0 ),
( 1.5, 3.0 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ( 0.3, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.3, 0.0 ), ( 0.8, 0.0 ), ( 1.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.1, 0.5 ), ( 0.0, 0.0 ), ( 0.2, 0.2 ), ( 0.5, 0.2 ), ( 1.0, 2.5 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.57 ), ( 0.752508, -1.473995 ), ( 0.979933, -1.308908 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cv = 0.1, vLimits = ( -0.6, 0.6 ) ),
baseTrajectory = [ ( 0.0, 0.143195 ), ( 0.366834170854, 0.326633165829 ), ( 0.813333, 0.16319 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.57 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cv = -0.1, vLimits = ( -0.6, 0.6 ) ),
baseTrajectory = [ ( 0.0, -0.2 ), ( 0.532663316583, -0.979899497487 ), ( 0.842809, -0.176382 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.006689, -0.1 ), ( 0.568562, -0.2 ), ( 0.989967, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 0.8, 0.15 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.0 ), ( 0.8, 1.0 ) ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.508361, -0.2 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.1 ), ( 0.5, 0.5 ), ( 1.0, 1.0 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.185929648241, -0.376884422111 ), ( 0.743718592965, 0.778894472362 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.0 ), ( 0.8, 1.0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 10.0, kd = 3.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.200 ), ( 1.0, 0.0700 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
referenceFrame = 'CHARACTER_RELATIVE',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.25 ), ( 1.0, -0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
referenceFrame = 'CHARACTER_RELATIVE',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.25 ), ( 1.0, 0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 10.0, kd = 3.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.2 ), ( 0.5, 0.2 ), ( 1.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.5, -1.14602051247 ), ( 1.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -3.14 ), ( 0.5, -1.35766712772 ), ( 1.0, -3.14 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ), ( 0.5, 1.06088629112 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -3.14 ), ( 0.5, -1.97544780802 ), ( 1.0, -3.14 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ), ( 0.5, 1.82220932323 ), ( 1.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.5, -1.98237428543 ), ( 1.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.506029102038 ), ( 0.5, 0.0 ), ( 1.0, -0.506029102038 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -1.14083040404 ), ( 0.5, 1.06099591765 ), ( 1.0, -1.14083040404 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.496075995362 ), ( 0.5, -1.38777878078e-17 ), ( 1.0, 0.496075995362 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.893777070901 ), ( 0.5, -0.863756831077 ), ( 1.0, 0.893777070901 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 10.0, kd = 3.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.200 ), ( 1.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
referenceFrame = 'CHARACTER_RELATIVE',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
referenceFrame = 'CHARACTER_RELATIVE',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.145 ), ( 0.5, 0.62 ), ( 1.0, 1.145 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.612760773201 ), ( 0.5, 0.4 ), ( 1.0, -0.60767396515 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.96228502799 ), ( 0.5, 1.17208006251 ), ( 1.0, -2.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.59144454428 ), ( 0.5, 1.96164897246 ), ( 1.0, 1.60692503929 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.60767396515 ), ( 0.5, 0.4 ), ( 1.0, -0.612760773201 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 2.0 ), ( 0.5, -1.16088017237 ), ( 1.0, 1.96228502799 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.60692503929 ), ( 0.5, 1.9892369757 ), ( 1.0, 1.59144454428 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 2.43705921824 ), ( 0.5, 2.04112770189 ), ( 1.0, 2.39675689772 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -2.39675689772 ), ( 0.5, -2.11858188981 ), ( 1.0, -2.43705921824 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.652537431571 ), ( 0.5, 0.362026574602 ), ( 1.0, 0.652537431571 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.679034314188 ), ( 0.5, 0.242455663357 ), ( 1.0, 0.679034314188 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.443539037361 ), ( 0.5, 0.0 ), ( 1.0, 0.443539037361 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.10625 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.09375 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.72,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.515 ), ( 0.5, 0.2 ), ( 1.0, 0.515 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.221383627068 ), ( 0.5, -0.117036102433 ), ( 1.0, -0.0126885777983 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.25 ), ( 0.5, 0.0 ), ( 1.0, 0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0126885777983 ), ( 0.5, 0.117036102433 ), ( 1.0, 0.221383627068 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.25 ), ( 0.5, 0.0 ), ( 1.0, -0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ), ( 0.5, 0.1 ), ( 1.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.5, -0.1 ), ( 1.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.322732761288 ), ( 0.5, -6.93889390391e-18 ), ( 1.0, 0.322732761288 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.171880490998 ), ( 0.5, 0.0 ), ( 1.0, 0.171880490998 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.107003153544 ), ( 0.5, 0.0 ), ( 1.0, 0.107003153544 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.164284842328 ), ( 0.5, 0.0 ), ( 1.0, 0.164284842328 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.0625 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.04375 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.59,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.38875 ), ( 0.5, 0.91375 ), ( 1.0, 0.38875 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.833665018614 ), ( 0.5, -1.72418658712 ), ( 1.0, -1.25418278399 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.887063295345 ), ( 0.5, 1.12111014855 ), ( 1.0, 0.963554856376 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.25418278399 ), ( 0.5, 1.71966054144 ), ( 1.0, 0.833665018614 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.963554856376 ), ( 0.5, -0.882514042565 ), ( 1.0, -0.887063295345 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.407448864947 ), ( 0.5, 0.351509516585 ), ( 1.0, 1.56625370414 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.56625370414 ), ( 0.5, -0.405009398611 ), ( 1.0, -0.407448864947 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.0389657021399 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.563973711862 ), ( 0.5, 0.591760708973 ), ( 1.0, 0.563973711862 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.231730813046 ), ( 0.5, 0.0 ), ( 1.0, 0.231730813046 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.319155072529 ), ( 0.5, 0.254737775857 ), ( 1.0, 0.319155072529 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.282965672936 ), ( 0.5, 0.262222770702 ), ( 1.0, 0.282965672936 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.075 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.06875 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.62,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.1 ), ( 1.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.09190687384 ), ( 1.0, 2.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -2.63817581809 ), ( 1.0, 0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -2.0 ), ( 1.0, 1.09190687384 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.25 ), ( 1.0, -2.63817581809 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.00402694999565 ), ( 1.0, 1.42770774061 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.42770774061 ), ( 1.0, -0.00402694999565 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.375744188714 ), ( 1.0, 0.375744188714 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.2 ), ( 1.0, 1.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.64363902446 ), ( 1.0, -0.64363902446 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.16725218285 ), ( 1.0, 1.16725218285 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -1.2 ), ( 1.0, 1.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.464482553944 ), ( 1.0, 0.464482553944 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.56,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.06625 ), ( 0.5, 2.01125 ), ( 1.0, 1.06625 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 0.5, 0.315 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 0.5, 0.315 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.5, -1.41439098346 ), ( 1.0, -1.32878196693 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.476043280795 ), ( 0.5, -0.208794224374 ), ( 1.0, 0.488385048199 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.32878196693 ), ( 0.5, 1.41439098346 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.488385048199 ), ( 0.5, -0.560286000046 ), ( 1.0, 0.476043280795 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.953853151322 ), ( 0.5, 0.257563366311 ), ( 1.0, 0.704587743289 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.704587743289 ), ( 0.5, -0.157456703138 ), ( 1.0, -0.953853151322 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0820512424596 ), ( 0.5, -1.73472347598e-18 ), ( 1.0, -0.0820512424596 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.245782640643 ), ( 0.5, 0.245782640643 ), ( 1.0, 0.245782640643 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0806602092784 ), ( 0.5, 0.0 ), ( 1.0, -0.0806602092784 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.246192476802 ), ( 0.5, 0.246192476802 ), ( 1.0, 0.246192476802 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.0125723271947 ), ( 0.5, 0.0 ), ( 1.0, 0.0125723271947 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.1125 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.09375 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.08125 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.78,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.725 ), ( 0.5, 0.725 ), ( 1.0, 0.725 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.5, -1.5 ), ( 1.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.96138465184 ), ( 0.5, -0.856486612376 ), ( 1.0, -0.809332292173 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ), ( 0.5, 1.5 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.809332292173 ), ( 0.5, 0.913031361175 ), ( 1.0, -0.96138465184 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ), ( 0.5, 1.56222904526 ), ( 1.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.5, -2.49302076492 ), ( 1.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.190389583533 ), ( 0.5, 0.0 ), ( 1.0, 0.190389583533 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.00160097650778 ), ( 0.5, -0.53515635646 ), ( 1.0, -0.00160097650778 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.214836466015 ), ( 0.5, 0.0 ), ( 1.0, 0.214836466015 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0953519033856 ), ( 0.5, -0.741172382825 ), ( 1.0, 0.0953519033856 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.13125 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.24375 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.61,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.145 ), ( 0.5, 0.96125 ), ( 1.0, 1.145 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.5, -1.5 ), ( 1.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.25 ), ( 0.5, 0.177270637465 ), ( 1.0, 0.604541274931 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ), ( 0.5, 1.5 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.604541274931 ), ( 0.5, 0.177270637465 ), ( 1.0, -0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ), ( 0.5, -0.529892784046 ), ( 1.0, -1.15978556809 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.15978556809 ), ( 0.5, 0.529892784046 ), ( 1.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.11172679807 ), ( 0.5, -1.45783077227 ), ( 1.0, 1.11172679807 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.825721085275 ), ( 0.5, 0.453946311569 ), ( 1.0, -0.825721085275 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 10.0, kd = 3.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.003344, 0.204846 ), ( 0.959866, 0.070153 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.3 ), ( 0.3, 0.3 ), ( 0.4, 0.0 ), ( 1.0, -0.3 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [
( -0.5, 2.0 ),
( -0.1, 1.0 ),
( 0.0, 0.0 ),
( 0.1, 1.0 ),
( 0.5, 2.5 ),
( 1.0, 6.0 ),
( 1.1, 7.0 ),
( 1.5, 3.0 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ( 0.3, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.3, 0.0 ), ( 0.8, 0.0 ), ( 1.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.1, 0.5 ), ( 0.0, 0.0 ), ( 0.2, 0.2 ), ( 0.5, 0.2 ), ( 1.0, 2.5 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.57 ), ( 0.752508, -1.473995 ), ( 0.979933, -1.308908 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cv = 0.1, vLimits = ( -0.6, 0.6 ) ),
baseTrajectory = [ ( 0.0, 0.143195 ), ( 0.558653, 0.193845 ), ( 0.813333, 0.16319 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.57 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cv = -0.1, vLimits = ( -0.6, 0.6 ) ),
baseTrajectory = [ ( 0.0, -0.2 ), ( 0.842809, -0.176382 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.006689, -0.1 ), ( 0.568562, -0.2 ), ( 0.989967, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 0.8, 0.15 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.0 ), ( 0.8, 1.0 ) ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.508361, -0.2 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.1 ), ( 0.5, 0.5 ), ( 1.0, 1.0 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.3, 0.0 ), ( 0.75, 0.2 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.0 ), ( 0.8, 1.0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.9875 ), ( 0.5, 0.725 ), ( 1.0, 0.9875 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.507078011239 ), ( 0.5, -2.0 ), ( 1.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.25 ), ( 0.5, 0.0 ), ( 1.0, 0.103941218655 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ), ( 0.5, 2.0 ), ( 1.0, -0.507078011239 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.103941218655 ), ( 0.5, -1.01407070469 ), ( 1.0, -0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 2.8 ), ( 0.5, 1.08110877003 ), ( 1.0, 1.96798697012 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.96798697012 ), ( 0.5, -0.1 ), ( 1.0, -2.8 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.958534192796 ), ( 0.5, 0.797093037412 ), ( 1.0, 0.958534192796 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -1.2 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.792321805397 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.2 ), ( 0.5, 0.0 ), ( 1.0, 1.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.01875 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.2875 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.21875 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.84,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.2 ), ( 0.25, 0.2 ), ( 0.5, 0.9875 ), ( 0.75, 0.2 ), ( 1.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 0.25, 0.8071875 ), ( 0.5, 0.315 ), ( 0.75, -0.15326171875 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 0.25, -0.1771875 ), ( 0.5, 0.315 ), ( 0.75, 0.78326171875 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 0.75, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.25, -0.856849024564 ), ( 0.5, -1.5 ), ( 0.75, -1.5 ), ( 1.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.25 ), ( 0.25, -0.140625 ), ( 0.5, 0.0 ), ( 0.75, 0.1337890625 ), ( 1.0, 0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 0.75, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ), ( 0.25, 1.5 ), ( 0.5, 1.5 ), ( 0.75, 0.841261506347 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.25 ), ( 0.25, 0.140625 ), ( 0.5, 0.0 ), ( 0.75, -0.1337890625 ), ( 1.0, -0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ), ( 0.25, 0.1 ), ( 0.5, 0.1 ), ( 0.75, 0.1 ), ( 1.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.25, -0.1 ), ( 0.5, -0.1 ), ( 0.75, -0.1 ), ( 1.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, -0.338245685756 ), ( 0.5, 0.0 ), ( 0.75, 0.392858393573 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 0.562673316863 ),
( 0.25, -0.0266145330645 ),
( 0.5, -0.387208283918 ),
( 0.75, 0.00346308709372 ),
( 1.0, 0.562673316863 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, -0.339825553389 ), ( 0.5, 0.0 ), ( 0.75, 0.356935318054 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 0.61823324355 ),
( 0.25, -0.0516524962421 ),
( 0.5, -0.462717152977 ),
( 0.75, -0.0178491409028 ),
( 1.0, 0.61823324355 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.59625 ), ( 0.25, 0.12625 ), ( 0.5, 1.6684375 ), ( 0.75, 0.87875 ), ( 1.0, 1.59625 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 0.75, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, -1.34490238197 ),
( 0.25, -1.37382525821 ),
( 0.5, -1.39238772339 ),
( 0.75, -1.3957393067 ),
( 1.0, -1.30297512805 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, -1.20181038542 ),
( 0.25, -0.160088376855 ),
( 0.5, 0.376943118099 ),
( 0.75, 0.847681649056 ),
( 1.0, 1.35905994564 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 0.75, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, 1.30297512805 ),
( 0.25, 1.3872971337 ),
( 0.5, 1.39369185442 ),
( 0.75, 1.38458588639 ),
( 1.0, 1.34490238197 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 1.35905994564 ),
( 0.25, 0.199536413777 ),
( 0.5, -0.28034056213 ),
( 0.75, -0.680447461984 ),
( 1.0, -1.20181038542 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.33527695073 ), ( 0.25, 0.1 ), ( 0.5, 1.37279519058 ), ( 0.75, 2.8 ), ( 1.0, 2.8 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, -2.8 ),
( 0.25, -0.1 ),
( 0.5, -0.286758983578 ),
( 0.75, -0.869268965331 ),
( 1.0, -1.33527695073 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 0.210319987649 ),
( 0.25, 0.0 ),
( 0.5, 0.0525799969121 ),
( 0.75, 0.140213325099 ),
( 1.0, 0.210319987649 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.08125 ), ( 0.5, 0.0609375 ), ( 0.75, 0.0270833333333 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.175 ), ( 0.5, 0.13125 ), ( 0.75, 0.0583333333333 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.77,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.7775 ), ( 0.25, 0.80375 ), ( 0.5, 1.01375 ), ( 1.0, 0.7775 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.25, -1.5 ), ( 0.5, -1.5 ), ( 1.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, -0.936327835916 ),
( 0.25, -0.058116628439 ),
( 0.5, -0.00533624569115 ),
( 1.0, -0.865882528352 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ), ( 0.25, 1.5 ), ( 0.5, 1.5 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, -0.865882528352 ),
( 0.25, -0.799151333694 ),
( 0.5, -0.641187304081 ),
( 1.0, -0.936327835916 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.76437203967 ), ( 0.25, 1.84072933733 ), ( 0.5, 2.38782151456 ), ( 1.0, 1.40210704392 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.40210704392 ), ( 0.25, -2.29167684138 ), ( 0.5, -2.09410431324 ), ( 1.0, -1.76437203967 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.159484126975 ), ( 0.25, -0.158674699251 ), ( 0.5, 0.0 ), ( 1.0, 0.159484126975 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.494230489065 ), ( 0.25, 0.57453066062 ), ( 0.5, 0.5693434543 ), ( 1.0, -0.494230489065 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.167319769534 ), ( 0.25, -0.0971231314315 ), ( 0.5, 0.0 ), ( 1.0, 0.167319769534 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.529286239128 ), ( 0.25, 1.11799105329 ), ( 0.5, 1.2 ), ( 1.0, -0.529286239128 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.112816611208 ), ( 0.5, 0.200562864369 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.08125 ), ( 0.5, 0.28125 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.04375 ), ( 0.5, 0.175 ), ( 1.0, 0.0 ) ]
) | Python |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.59,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.5675 ), ( 0.25, 0.5675 ), ( 0.5, 0.5675 ), ( 0.75, 0.5675 ), ( 1.0, 0.5675 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 1.19 ),
( 0.25, 0.83453125 ),
( 0.5, 0.340065104167 ),
( 0.75, -0.159971064815 ),
( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, -0.56 ),
( 0.25, -0.20453125 ),
( 0.5, 0.289934895833 ),
( 0.75, 0.789971064815 ),
( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 0.75, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, -1.5 ),
( 0.25, -1.37826048129 ),
( 0.5, -1.20891768923 ),
( 0.75, -1.03766729788 ),
( 1.0, -0.900666984803 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, -0.651047012036 ),
( 0.25, -0.311105917294 ),
( 0.5, 0.16176086193 ),
( 0.75, 0.639954353465 ),
( 1.0, 1.02250914669 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 0.75, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, 0.900666984803 ),
( 0.25, 1.02240650351 ),
( 0.5, 1.19174929557 ),
( 0.75, 1.36299968692 ),
( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 1.02250914669 ),
( 0.25, 0.682568051951 ),
( 0.5, 0.209701272727 ),
( 0.75, -0.268492218808 ),
( 1.0, -0.651047012036 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, 1.47145472144 ),
( 0.25, 1.44865469994 ),
( 0.5, 1.41693928543 ),
( 0.75, 1.38486660562 ),
( 1.0, 1.35920846178 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, -1.35920846178 ),
( 0.25, -1.38200848327 ),
( 0.5, -1.41372389778 ),
( 0.75, -1.44579657759 ),
( 1.0, -1.47145472144 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [
( 0.0, -0.155403232618 ),
( 0.25, -0.092270669367 ),
( 0.5, -0.00445165510104 ),
( 0.75, 0.0843566158541 ),
( 1.0, 0.155403232618 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, -0.0353280996748 ),
( 0.25, -0.0353280996748 ),
( 0.5, -0.0353280996748 ),
( 0.75, -0.0353280996748 ),
( 1.0, -0.0353280996748 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [
( 0.0, -0.220856401634 ),
( 0.25, -0.13113348847 ),
( 0.5, -0.00632661567182 ),
( 0.75, 0.119886171721 ),
( 1.0, 0.220856401634 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 0.0408453732455 ),
( 0.25, 0.0408453732455 ),
( 0.5, 0.0408453732455 ),
( 0.75, 0.0408453732455 ),
( 1.0, 0.0408453732455 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [
( 0.0, -0.133448913926 ),
( 0.25, -0.0792352926433 ),
( 0.5, -0.00382275534683 ),
( 0.75, 0.0724392831378 ),
( 1.0, 0.133448913926 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, -0.1375 ), ( 0.5, -0.248046875 ), ( 0.75, 0.0854166666667 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.25, -0.03125 ), ( 0.5, 0.00078125 ), ( 0.75, 0.177083333333 ), ( 1.0, 0.0 ) ]
) | Python |
'''
Created on 2009-08-28
@author: beaudoin
'''
from os import path
meshDir = path.join( path.dirname(__file__), "Meshes" )
blue = ( 0.5, 0.6, 0.8, 1 )
green = ( 0.5, 0.8, 0.6, 1 )
red = ( 0.892, 0.716, 0.602, 1 )
gray = ( 0.5, 0.5, 0.5, 1 )
from App.Proxys import *
data = Character(
name = "BipV3",
root = ArticulatedRigidBody(
name = "pelvis",
meshes = [ (path.join(meshDir, "pelvis.obj"), blue) ],
mass = 12.9,
moi = (0.0705, 0.11, 0.13),
cdps = [ CapsuleCDP((-0.05, -0.025, 0), (0.05, -0.025, 0), 0.07) ],
pos = (0, 1.035, 0),
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
arbs = [
ArticulatedRigidBody(
name = "lowerBack",
meshes = [ (path.join(meshDir, "lowerBack.obj"), green) ],
mass = 7.0,
moi = (0.1, 0.08, 0.15),
cdps = [ CapsuleCDP((0,-0.05,0), (0, 0.015, 0), 0.08) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "torso",
meshes = [ (path.join(meshDir, "torso.obj"), green) ],
mass = 15.5,
moi = (0.21, 0.14, 0.31),
cdps = [ CapsuleCDP((0, -0.05, 0.03), (0, 0.07, 0.03), 0.12) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "head",
meshes = [ (path.join(meshDir, "head.obj"), red) ],
mass = 5.2,
moi = (0.04, 0.02, 0.042),
cdps = [ CapsuleCDP((0,0.05,0), (0,0.1,0), 0.09) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lUpperArm",
meshes = [ (path.join(meshDir, "lUpperArm.obj"), green) ],
mass = 2.2,
moi = (0.005, 0.02, 0.02),
cdps = [ CapsuleCDP((-0.13,0,0), (0.08,0,0), 0.04) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lLowerArm",
meshes = [ (path.join(meshDir, "lLowerArm.obj"), red) ],
mass = 1.7,
moi = (0.0024, 0.025, 0.025),
cdps = [ CapsuleCDP((-0.2,0,0), (0.07,0,0), 0.04) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rUpperArm",
meshes = [ (path.join(meshDir, "rUpperArm.obj"), green) ],
mass = 2.2,
moi = (0.005, 0.02, 0.02),
cdps = [ CapsuleCDP((0.13,0,0), (-0.08,0,0), 0.04) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rLowerArm",
meshes = [ (path.join(meshDir, "rLowerArm.obj"), red) ],
mass = 1.7,
moi = (0.0024, 0.025, 0.025),
cdps = [ CapsuleCDP((-0.07,0,0), (0.2,0,0), 0.04) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lUpperLeg",
meshes = [ (path.join(meshDir, "lUpperLeg.obj"), blue) ],
mass = 6.6,
moi = (0.15, 0.022, 0.15),
cdps = [ CapsuleCDP((0, 0.15, 0), (0, -0.19, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lLowerLeg",
meshes = [ (path.join(meshDir, "lLowerLeg.obj"), blue) ],
mass = 3.2,
moi = (0.055, 0.007, 0.055),
cdps = [ CapsuleCDP((0, 0.17, 0), (0, -0.22, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rUpperLeg",
meshes = [ (path.join(meshDir, "rUpperLeg.obj"), blue) ],
mass = 6.6,
moi = (0.15, 0.022, 0.15),
cdps = [ CapsuleCDP((0, 0.15, 0), (0, -0.19, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rLowerLeg",
meshes = [ (path.join(meshDir, "rLowerLeg.obj"), blue) ],
mass = 3.2,
moi = (0.055, 0.007, 0.055),
cdps = [ CapsuleCDP((0, 0.17, 0), (0, -0.22, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lFoot",
meshes = [ (path.join(meshDir, "lFoot.obj"), gray) ],
mass = 1.0,
moi = (0.007, 0.008, 0.002),
cdps = [ BoxCDP((-0.05, -0.04, -0.09), (0.05, 0.005, 0.065)) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0005, 0.2) ),
ArticulatedRigidBody(
name = "rFoot",
meshes = [ (path.join(meshDir, "rFoot.obj"), gray) ],
mass = 1.0,
moi = (0.007, 0.008, 0.002),
cdps = [ BoxCDP((-0.05, -0.04, -0.09), (0.05, 0.005, 0.065)) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0005, 0.2) ),
ArticulatedRigidBody(
name = "lToes",
meshes = [ (path.join(meshDir, "lToes.obj"), gray) ],
mass = 0.2,
moi = (0.002, 0.002, 0.0005),
cdps = [ BoxCDP((-0.03, 0.015, -0.035), (0.03, -0.017, 0.02)) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0005, 0.2) ),
ArticulatedRigidBody(
name = "rToes",
meshes = [ (path.join(meshDir, "rToes.obj"), gray) ],
mass = 0.2,
moi = (0.002, 0.002, 0.0005),
cdps = [ BoxCDP((-0.03, 0.015, -0.035), (0.03, -0.017, 0.02)) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0005, 0.2) )
],
joints = [
BallInSocketJoint(
name = "pelvis_lowerback",
parent = "pelvis",
child = "lowerBack",
posInParent = (0, 0.07, -0.015),
posInChild = (0, -0.09, -0.015),
swingAxis1 = (1, 0, 0),
twistAxis = (0, 0, 1),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "lowerback_torso",
parent = "lowerBack",
child = "torso",
posInParent = (0, 0.05, -0.015),
posInChild = (0, -0.138, 0.012),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 0, 1),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "torso_head",
parent = "torso",
child = "head",
posInParent = (0, 0.16, 0.00),
posInChild = (0, -0.08, -0.03),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 0, 1),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "lShoulder",
parent = "torso",
child = "lUpperArm",
posInParent = (0.16, 0.095, 0.02),
posInChild = (-0.13, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = ( 1, 0, 0),
limits = (-100, 100, -1.5, 1.5, -100, 100) ),
BallInSocketJoint(
name = "rShoulder",
parent = "torso",
child = "rUpperArm",
posInParent = (-0.16, 0.095, 0.02),
posInChild = (0.13, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = ( 1, 0, 0),
limits = (-100, 100, -1.5, 1.5, -100, 100) ),
HingeJoint(
name = "lElbow",
parent = "lUpperArm",
child = "lLowerArm",
posInParent = (0.11, 0, 0),
posInChild = (-0.24, 0, 0),
axis = ( 0, 1, 0 ),
limits = (-2.7, 0) ),
HingeJoint(
name = "rElbow",
parent = "rUpperArm",
child = "rLowerArm",
posInParent = (-0.11, 0, 0),
posInChild = (0.24, 0, 0),
axis = ( 0, -1, 0 ),
limits = (-2.7, 0) ),
BallInSocketJoint(
name = "lHip",
parent = "pelvis",
child = "lUpperLeg",
posInParent = (0.08, -0.03, -0.01),
posInChild = (0, 0.17, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 0, 1),
limits = (-1.3, 1.9, -1, 1, -1, 1) ),
BallInSocketJoint(
name = "rHip",
parent = "pelvis",
child = "rUpperLeg",
posInParent = (-0.08, -0.03, -0.01),
posInChild = (0, 0.17, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 0, 1),
limits = (-1.3, 1.9, -1, 1, -1, 1) ),
HingeJoint(
name = "lKnee",
parent = "lUpperLeg",
child = "lLowerLeg",
posInParent = (0, -0.23, 0),
posInChild = (0, 0.22, 0),
axis = ( 1, 0, 0 ),
limits = (0, 2.5) ),
HingeJoint(
name = "rKnee",
parent = "rUpperLeg",
child = "rLowerLeg",
posInParent = (0, -0.23, 0),
posInChild = (0, 0.22, 0),
axis = ( 1, 0, 0 ),
limits = (0, 2.5) ),
UniversalJoint(
name = "lAnkle",
parent = "lLowerLeg",
child = "lFoot",
posInParent = (0.01, -0.24, 0.00),
posInChild = (0.0, 0.02, -0.03),
parentAxis = (0, 0, 1),
childAxis = (1, 0, 0),
limits = (-0.75, 0.75, -0.75, 0.75) ),
UniversalJoint(
name = "rAnkle",
parent = "rLowerLeg",
child = "rFoot",
posInParent = (-0.01, -0.24, 0.00),
posInChild = (0.0, 0.02, -0.03),
parentAxis = (0, 0, -1),
childAxis = (1, 0, 0),
limits = (-0.75, 0.75, -0.75, 0.75) ),
HingeJoint(
name = "lToeJoint",
parent = "lFoot",
child = "lToes",
posInParent = (0, -0.02, 0.055),
posInChild = (0, 0, -0.045),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.1) ),
HingeJoint(
name = "rToeJoint",
parent = "rFoot",
child = "rToes",
posInParent = (0, -0.02, 0.055),
posInChild = (0, 0, -0.045),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.1) )
]
)
| Python |
'''
Created on 2009-08-28
@author: beaudoin
'''
import PyUtils
import Core, wx
File = "Jumping"
#File = "Running"
#File = "SideRunning"
#File = "JumpWalk"
#File = "Walking"
#File = "Turning"
#PyUtils.load( "RigidBodies.FlatGround" )
PyUtils.load( "RigidBodies.FiniteFlatGround" )
PyUtils.loadMany( "RigidBodies.DodgeBall", 5 )
character = PyUtils.load( "Characters.Bip" )
character.loadReducedStateFromFile( "Data/Characters/Bip/Controllers/%sState.rs" % File );
controller = PyUtils.load( "Characters.Bip.Controllers.%s" % File, character )
controller.setStance( Core.LEFT_STANCE );
| Python |
'''
Created on 2009-11-26
@author: beaudoin
'''
import PyUtils
import Core, wx
import Controllers
PyUtils.load( "RigidBodies.FiniteFlatGround" )
PyUtils.loadMany( "RigidBodies.DodgeBall", 5 )
character = PyUtils.load( "Characters.BipV3" )
character.computeMass();
controller = Controllers.DanceController(character)
controller.loadFromFile("../data/controllers/bipV3/fWalk_4.sbc")
#controller.loadFromFile("../data/controllers/bipV3/fWalk_3.sbc")
Core.cvar.SimGlobals_stanceKnee = 0.00
Core.cvar.SimGlobals_rootSagittal = 0.3
Core.cvar.SimGlobals_stepHeight = 0.25
Core.cvar.SimGlobals_duckWalk = 0.2
Core.cvar.SimGlobals_VDelSagittal = 2.0
Core.cvar.SimGlobals_stepTime = 0.2
#Core.cvar.SimGlobals_upperBodyTwist = 0.2
controller.initialSetup()
| Python |
'''
Created on 2009-08-28
@author: beaudoin
This file is just a proxy to indicate which one is the desire framework for typical applications
'''
import BipFramework | Python |
'''
Created on 2009-11-23
@author: beaudoin
'''
import PyUtils
PyUtils.load( "RigidBodies.FiniteFlatGround" ) | Python |
'''
Created on 2009-11-26
@author: beaudoin
'''
import PyUtils
import Core, wx
import Controllers
PyUtils.load( "RigidBodies.FiniteFlatGround" )
PyUtils.loadMany( "RigidBodies.DodgeBall", 5 )
character = PyUtils.load( "Characters.BipV3" )
character.loadReducedStateFromFile( "Data/Characters/BipV3/Controllers/WalkingState.rs" );
character.computeMass();
#controller = PyUtils.load( "Characters.BipV3.Controllers.StylizedWalking", character )
controller = PyUtils.load( "Characters.BipV3.Controllers.EditableWalking", character )
controller.setStance( Core.LEFT_STANCE );
app = wx.GetApp()
worldOracle = app.getWorldOracle()
behaviour = Core.TurnController(character, controller, worldOracle)
behaviour.initializeDefaultParameters()
controller.setBehaviour(behaviour)
behaviour.requestHeading(0);
behaviour.conTransitionPlan();
| Python |
from App.UtilFuncs import fancify
print fancify(
"""Character(
root = ArticulatedRigidBody(
name = "pelvis",
meshes = [ (path.join(meshDir, "pelvis_2_b.obj"), colourDark),
(path.join(meshDir, "pelvis_2_s.obj"), colourLight) ],
mass = 12.9,
moi = (0.0705, 0.11, 0.13),
cdps = [ SphereCDP((0,-0.075,0), 0.12) ],
pos = (0, 1.035, 0.2),
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
arbs = [
ArticulatedRigidBody(
name = "torso",
meshes = [ (path.join(meshDir, "torso_2_b.obj"), colourDark),
(path.join(meshDir, "torso_2_s_v2.obj"), colourLight) ],
mass = 22.5,
moi = (0.34, 0.21, 0.46),
cdps = [ SphereCDP((0,0,0.01), 0.11) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "head",
meshes = [ (path.join(meshDir, "head_b.obj"), colourDark),
(path.join(meshDir, "head_s.obj"), colourLight) ],
mass = 5.2,
moi = (0.04, 0.02, 0.042),
cdps = [ SphereCDP((0,0.04,0), 0.11) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lUpperArm",
meshes = [ (path.join(meshDir, "lUpperArm.obj"), colourDark) ],
mass = 2.2,
moi = (0.005, 0.02, 0.02),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lLowerArm",
meshes = [ (path.join(meshDir, "lLowerArm.obj"), colourDark) ],
mass = 1.7,
moi = (0.0024, 0.025, 0.025),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rUpperArm",
meshes = [ (path.join(meshDir, "rUpperArm.obj"), colourDark) ],
mass = 2.2,
moi = (0.005, 0.02, 0.02),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rLowerArm",
meshes = [ (path.join(meshDir, "rLowerArm.obj"), colourDark) ],
mass = 1.7,
moi = (0.0024, 0.025, 0.025),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lUpperLeg",
meshes = [ (path.join(meshDir, "lUpperLeg.obj"), colourDark) ],
mass = 6.6,
moi = (0.15, 0.022, 0.15),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.26, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lLowerLeg",
meshes = [ (path.join(meshDir, "lLowerLeg.obj"), colourDark) ],
mass = 3.2,
moi = (0.055, 0.007, 0.055),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.2, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rUpperLeg",
meshes = [ (path.join(meshDir, "rUpperLeg.obj"), colourDark) ],
mass = 6.6,
moi = (0.15, 0.022, 0.15),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.26, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rLowerLeg",
meshes = [ (path.join(meshDir, "rLowerLeg.obj"), colourDark) ],
mass = 3.2,
moi = (0.055, 0.007, 0.055),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.2, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lFoot",
meshes = [ (path.join(meshDir, "lFoot.obj"), colourDark) ],
mass = 1.0,
moi = (0.007, 0.008, 0.002),
cdps = [ BoxCDP((-0.025, -0.033, -0.09), (0.025, 0.005, 0.055)) ],
# CDP_Sphere 0.025 -0.025 -0.08 0.01
# CDP_Sphere -0.025 -0.025 -0.08 0.01
# CDP_Sphere 0.02 -0.025 0.045 0.01
# CDP_Sphere -0.02 -0.025 0.045 0.01
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) ),
ArticulatedRigidBody(
name = "rFoot",
meshes = [ (path.join(meshDir, "rFoot.obj"), colourDark) ],
mass = 1.0,
moi = (0.007, 0.008, 0.002),
cdps = [ BoxCDP((-0.025, -0.033, -0.09), (0.025, 0.005, 0.055)) ],
# CDP_Sphere 0.025 -0.025 -0.08 0.01
# CDP_Sphere -0.025 -0.025 -0.08 0.01
# CDP_Sphere 0.02 -0.025 0.045 0.01
# CDP_Sphere -0.02 -0.025 0.045 0.01
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) ),
ArticulatedRigidBody(
name = "lToes",
meshes = [ (path.join(meshDir, "lToes.obj"), colourDark) ],
mass = 0.2,
moi = (0.002, 0.002, 0.0005),
cdps = [ SphereCDP((0.0, -0.005, 0.025), 0.01) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) ),
ArticulatedRigidBody(
name = "rToes",
meshes = [ (path.join(meshDir, "rToes.obj"), colourDark) ],
mass = 0.2,
moi = (0.002, 0.002, 0.0005),
cdps = [ SphereCDP((0.0, -0.005, 0.025), 0.01) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) )
],
joints = [
BallInSocketJoint(
name = "pelvis_torso",
parent = "pelvis",
child = "torso",
posInParent = (0, 0.17, -0.035),
posInChild = (0, -0.23, -0.01),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "torso_head",
parent = "torso",
child = "head",
posInParent = (0, 0.1, -0.00),
posInChild = (0, -0.16, -0.025),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "lShoulder",
parent = "torso",
child = "lUpperArm",
posInParent = (0.20, 0.07, 0.02),
posInChild = (-0.17, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = ( 1, 0, 0),
limits = (-1.7, 1.7, -1.5, 1.5, -1.5, 1.5) ),
BallInSocketJoint(
name = "rShoulder",
parent = "torso",
child = "rUpperArm",
posInParent = (-0.20, 0.07, 0.02),
posInChild = (0.17, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = ( 1, 0, 0),
limits = (-1.7, 1.7, -1.5, 1.5, -1.5, 1.5) ),
HingeJoint(
name = "lElbow",
parent = "lUpperArm",
child = "lLowerArm",
posInParent = (0.175, 0, 0.006),
posInChild = (-0.215, 0, 0),
axis = ( 0, 1, 0 ),
limits = (-2.7, 0) ),
HingeJoint(
name = "rElbow",
parent = "rUpperArm",
child = "rLowerArm",
posInParent = (-0.175, 0, 0.006),
posInChild = (0.215, 0, 0),
axis = ( 0, -1, 0 ),
limits = (-2.7, 0) ),
BallInSocketJoint(
name = "lHip",
parent = "pelvis",
child = "lUpperLeg",
posInParent = (0.1, -0.05, 0.0),
posInChild = (0, 0.21, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-1.3, 1.9, -1, 1, -0.25, 1) ),
BallInSocketJoint(
name = "rHip",
parent = "pelvis",
child = "rUpperLeg",
posInParent = (-0.1, -0.05, 0.0),
posInChild = (0, 0.21, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-1.3, 1.9, -1, 1, -1, 0.25) ),
HingeJoint(
name = "lKnee",
parent = "lUpperLeg",
child = "lLowerLeg",
posInParent = (0, -0.26, 0),
posInChild = (0, 0.21, 0),
axis = ( 1, 0, 0 ),
limits = (0, 2.5) ),
HingeJoint(
name = "rKnee",
parent = "rUpperLeg",
child = "rLowerLeg",
posInParent = (0, -0.26, 0),
posInChild = (0, 0.21, 0),
axis = ( 1, 0, 0 ),
limits = (0, 2.5) ),
UniversalJoint(
name = "lAnkle",
parent = "lLowerLeg",
child = "lFoot",
posInParent = (0, -0.25, 0.01),
posInChild = (0.0, 0.02, -0.04),
parentAxis = (1, 0, 0),
childAxis = (0, 0, 1),
limits = (-0.75, 0.75, -0.75, 0.75) ),
UniversalJoint(
name = "rAnkle",
parent = "rLowerLeg",
child = "rFoot",
posInParent = (0, -0.25, 0.01),
posInChild = (0.0, 0.02, -0.04),
parentAxis = (1, 0, 0),
childAxis = (0, 0, -1),
limits = (-0.75, 0.75, -0.75, 0.75) ),
HingeJoint(
name = "lToeJoint",
parent = "lFoot",
child = "lToes",
posInParent = (0, -0.02, 0.05),
posInChild = (0, 0, -0.025),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.02) ),
HingeJoint(
name = "rToeJoint",
parent = "rFoot",
child = "rToes",
posInParent = (0, -0.02, 0.05),
posInChild = (0, 0, -0.025),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.02) )
]
)""")
| Python |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| Python |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| Python |
#!/usr/bin/env python
import time
t = time.time()
u = time.gmtime(t)
s = time.strftime('%a, %e %b %Y %T GMT', u)
print 'Content-Type: text/javascript'
print 'Cache-Control: no-cache'
print 'Date: ' + s
print 'Expires: ' + s
print ''
print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
| Python |
#!/usr/bin/env python
import math
import sys
try:
verilogfilename = sys.argv[1]
verilog = open(verilogfilename,'r')
PADS_PER_SIDE=int(sys.argv[2])
except:
print >> sys.stderr, "USAGE: %s mapped/design.v pads_per_side"%sys.argv[0]
sys.exit(2)
TOTALPADS=4*PADS_PER_SIDE
# Gather up all the pads to allocate
padtypes={}
names=[]
types = ['PADVDD','PADGND','PADOUT','PADINC','PADINOUT']
for l in verilog:
l = l.strip()
l = l.split(' ',2)
prefix=l[0]
if prefix in types:
typ,name,junk = l
if name in padtypes:
print >> stderr, 'Duplicate pad %s'%name
sys.exit(1)
names.append(name)
padtypes[name] = prefix
REALPADS=len(names)
# Build a map of padpoints
orients = ['N','S','E','W']
padorients=[]
for o in orients:
padorients += [o]*PADS_PER_SIDE
padspots=TOTALPADS*[None]
# Start assigning to pads
assignments={}
# Generate an ordering to try to equally space the pins around the edge
def skipdist(idx):
return idx%int(TOTALPADS/REALPADS)
skipbest = sorted(range(TOTALPADS),key=skipdist)
# Chop down to the number of actual pads so that we don't assign to any others
placeablepads = skipbest[:REALPADS]
# Start allocating VDD and GND by biasing towards the center
def centerdistance(idx):
local = idx % PADS_PER_SIDE
return abs(local - PADS_PER_SIDE/2)
# Locate all VDD and GND pins
pwrpins = [name for name,prefix in padtypes.iteritems() if prefix in ['PADVDD','PADGND']]
# Best spots, in order
centerbest = sorted(placeablepads,key=centerdistance)
for n in pwrpins:
# Find the best unoccupied spot
for i in centerbest:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> stderr, 'Failed to assign pad %s of type %s'%(n,padtypes[n])
# OK, now just start assigning pads to spots
# O(n^2) FTW!
err=False
for n in names:
# Don't try assigning if it's already assigned!
if n in assignments:
continue
for i in placeablepads:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> sys.stderr, 'ERROR: Failed to assign pad %s of type %s. No pads available.'%(n,padtypes[n])
err = True
if err:
print >> sys.stderr
print >> sys.stderr, "Not all pads could be assigned."
print >> sys.stderr, "You probably didn't specify enough pads per side."
mpps = int(math.ceil(float(len(padtypes))/4))
print >> sys.stderr, "You should probably try at least %d pads per side."%mpps
sys.exit(3)
print """
# encounter.io file, autogenerated by scripts/pads
Version: 2
Orient: R0
Pad: c01 NW PADFC
Orient: R270
Pad: c02 NE PADFC
Orient: R180
Pad: c03 SE PADFC
Orient: R90
Pad: c04 SW PADFC
"""
# Generator for extra "trash" pads
def trashpadgen():
i=100
while True:
name='X%d'%i
while name in names:
i += 1
name='X%d'%i
names.append(name)
yield name
trashpads = trashpadgen()
# Print out in order of pads
for i in range(len(padspots)):
name = padspots[i]
orientation = padorients[i]
if name is None:
name = trashpads.next()
typ = 'PADNC'
else:
typ = ''
print 'Pad: %4s %s %s'%(name,orientation,typ)
if ((i+1)%PADS_PER_SIDE) == 0:
print
| Python |
#!/usr/bin/env python
for i in range(32):
print "PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );"%(i+3,i,i,i)
| Python |
#!/usr/bin/env python
import math
import sys
try:
verilogfilename = sys.argv[1]
verilog = open(verilogfilename,'r')
PADS_PER_SIDE=int(sys.argv[2])
except:
print >> sys.stderr, "USAGE: %s mapped/design.v pads_per_side"%sys.argv[0]
sys.exit(2)
TOTALPADS=4*PADS_PER_SIDE
# Gather up all the pads to allocate
padtypes={}
names=[]
types = ['PADVDD','PADGND','PADOUT','PADINC','PADINOUT']
for l in verilog:
l = l.strip()
l = l.split(' ',2)
prefix=l[0]
if prefix in types:
typ,name,junk = l
if name in padtypes:
print >> stderr, 'Duplicate pad %s'%name
sys.exit(1)
names.append(name)
padtypes[name] = prefix
REALPADS=len(names)
# Build a map of padpoints
orients = ['N','S','E','W']
padorients=[]
for o in orients:
padorients += [o]*PADS_PER_SIDE
padspots=TOTALPADS*[None]
# Start assigning to pads
assignments={}
# Generate an ordering to try to equally space the pins around the edge
def skipdist(idx):
return idx%int(TOTALPADS/REALPADS)
skipbest = sorted(range(TOTALPADS),key=skipdist)
# Chop down to the number of actual pads so that we don't assign to any others
placeablepads = skipbest[:REALPADS]
# Start allocating VDD and GND by biasing towards the center
def centerdistance(idx):
local = idx % PADS_PER_SIDE
return abs(local - PADS_PER_SIDE/2)
# Locate all VDD and GND pins
pwrpins = [name for name,prefix in padtypes.iteritems() if prefix in ['PADVDD','PADGND']]
# Best spots, in order
centerbest = sorted(placeablepads,key=centerdistance)
for n in pwrpins:
# Find the best unoccupied spot
for i in centerbest:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> stderr, 'Failed to assign pad %s of type %s'%(n,padtypes[n])
# OK, now just start assigning pads to spots
# O(n^2) FTW!
err=False
for n in names:
# Don't try assigning if it's already assigned!
if n in assignments:
continue
for i in placeablepads:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> sys.stderr, 'ERROR: Failed to assign pad %s of type %s. No pads available.'%(n,padtypes[n])
err = True
if err:
print >> sys.stderr
print >> sys.stderr, "Not all pads could be assigned."
print >> sys.stderr, "You probably didn't specify enough pads per side."
mpps = int(math.ceil(float(len(padtypes))/4))
print >> sys.stderr, "You should probably try at least %d pads per side."%mpps
sys.exit(3)
print """
# encounter.io file, autogenerated by scripts/pads
Version: 2
Orient: R0
Pad: c01 NW PADFC
Orient: R270
Pad: c02 NE PADFC
Orient: R180
Pad: c03 SE PADFC
Orient: R90
Pad: c04 SW PADFC
"""
# Generator for extra "trash" pads
def trashpadgen():
i=100
while True:
name='X%d'%i
while name in names:
i += 1
name='X%d'%i
names.append(name)
yield name
trashpads = trashpadgen()
# Print out in order of pads
for i in range(len(padspots)):
name = padspots[i]
orientation = padorients[i]
if name is None:
name = trashpads.next()
typ = 'PADNC'
else:
typ = ''
print 'Pad: %4s %s %s'%(name,orientation,typ)
if ((i+1)%PADS_PER_SIDE) == 0:
print
| Python |
#!/usr/bin/env python
for i in range(32):
print "PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );"%(i+3,i,i,i)
| Python |
#!/usr/bin/env python
import math
import sys
try:
verilogfilename = sys.argv[1]
verilog = open(verilogfilename,'r')
PADS_PER_SIDE=int(sys.argv[2])
except:
print >> sys.stderr, "USAGE: %s mapped/design.v pads_per_side"%sys.argv[0]
sys.exit(2)
TOTALPADS=4*PADS_PER_SIDE
# Gather up all the pads to allocate
padtypes={}
names=[]
types = ['PADVDD','PADGND','PADOUT','PADINC','PADINOUT']
for l in verilog:
l = l.strip()
l = l.split(' ',2)
prefix=l[0]
if prefix in types:
typ,name,junk = l
if name in padtypes:
print >> stderr, 'Duplicate pad %s'%name
sys.exit(1)
names.append(name)
padtypes[name] = prefix
REALPADS=len(names)
# Build a map of padpoints
orients = ['N','S','E','W']
padorients=[]
for o in orients:
padorients += [o]*PADS_PER_SIDE
padspots=TOTALPADS*[None]
# Start assigning to pads
assignments={}
# Generate an ordering to try to equally space the pins around the edge
def skipdist(idx):
return idx%int(TOTALPADS/REALPADS)
skipbest = sorted(range(TOTALPADS),key=skipdist)
# Chop down to the number of actual pads so that we don't assign to any others
placeablepads = skipbest[:REALPADS]
# Start allocating VDD and GND by biasing towards the center
def centerdistance(idx):
local = idx % PADS_PER_SIDE
return abs(local - PADS_PER_SIDE/2)
# Locate all VDD and GND pins
pwrpins = [name for name,prefix in padtypes.iteritems() if prefix in ['PADVDD','PADGND']]
# Best spots, in order
centerbest = sorted(placeablepads,key=centerdistance)
for n in pwrpins:
# Find the best unoccupied spot
for i in centerbest:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> stderr, 'Failed to assign pad %s of type %s'%(n,padtypes[n])
# OK, now just start assigning pads to spots
# O(n^2) FTW!
err=False
for n in names:
# Don't try assigning if it's already assigned!
if n in assignments:
continue
for i in placeablepads:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> sys.stderr, 'ERROR: Failed to assign pad %s of type %s. No pads available.'%(n,padtypes[n])
err = True
if err:
print >> sys.stderr
print >> sys.stderr, "Not all pads could be assigned."
print >> sys.stderr, "You probably didn't specify enough pads per side."
mpps = int(math.ceil(float(len(padtypes))/4))
print >> sys.stderr, "You should probably try at least %d pads per side."%mpps
sys.exit(3)
print """
# encounter.io file, autogenerated by scripts/pads
Version: 2
Orient: R0
Pad: c01 NW PADFC
Orient: R270
Pad: c02 NE PADFC
Orient: R180
Pad: c03 SE PADFC
Orient: R90
Pad: c04 SW PADFC
"""
# Generator for extra "trash" pads
def trashpadgen():
i=100
while True:
name='X%d'%i
while name in names:
i += 1
name='X%d'%i
names.append(name)
yield name
trashpads = trashpadgen()
# Print out in order of pads
for i in range(len(padspots)):
name = padspots[i]
orientation = padorients[i]
if name is None:
name = trashpads.next()
typ = 'PADNC'
else:
typ = ''
print 'Pad: %4s %s %s'%(name,orientation,typ)
if ((i+1)%PADS_PER_SIDE) == 0:
print
| Python |
#!/usr/bin/env python
for i in range(32):
print "PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );"%(i+3,i,i,i)
| Python |
#!/usr/bin/env python
import math
import sys
try:
verilogfilename = sys.argv[1]
verilog = open(verilogfilename,'r')
PADS_PER_SIDE=int(sys.argv[2])
except:
print >> sys.stderr, "USAGE: %s mapped/design.v pads_per_side"%sys.argv[0]
sys.exit(2)
TOTALPADS=4*PADS_PER_SIDE
# Gather up all the pads to allocate
padtypes={}
names=[]
types = ['PADVDD','PADGND','PADOUT','PADINC','PADINOUT']
for l in verilog:
l = l.strip()
l = l.split(' ',2)
prefix=l[0]
if prefix in types:
typ,name,junk = l
if name in padtypes:
print >> stderr, 'Duplicate pad %s'%name
sys.exit(1)
names.append(name)
padtypes[name] = prefix
REALPADS=len(names)
# Build a map of padpoints
orients = ['N','S','E','W']
padorients=[]
for o in orients:
padorients += [o]*PADS_PER_SIDE
padspots=TOTALPADS*[None]
# Start assigning to pads
assignments={}
# Generate an ordering to try to equally space the pins around the edge
def skipdist(idx):
return idx%int(TOTALPADS/REALPADS)
skipbest = sorted(range(TOTALPADS),key=skipdist)
# Chop down to the number of actual pads so that we don't assign to any others
placeablepads = skipbest[:REALPADS]
# Start allocating VDD and GND by biasing towards the center
def centerdistance(idx):
local = idx % PADS_PER_SIDE
return abs(local - PADS_PER_SIDE/2)
# Locate all VDD and GND pins
pwrpins = [name for name,prefix in padtypes.iteritems() if prefix in ['PADVDD','PADGND']]
# Best spots, in order
centerbest = sorted(placeablepads,key=centerdistance)
for n in pwrpins:
# Find the best unoccupied spot
for i in centerbest:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> stderr, 'Failed to assign pad %s of type %s'%(n,padtypes[n])
# OK, now just start assigning pads to spots
# O(n^2) FTW!
err=False
for n in names:
# Don't try assigning if it's already assigned!
if n in assignments:
continue
for i in placeablepads:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> sys.stderr, 'ERROR: Failed to assign pad %s of type %s. No pads available.'%(n,padtypes[n])
err = True
if err:
print >> sys.stderr
print >> sys.stderr, "Not all pads could be assigned."
print >> sys.stderr, "You probably didn't specify enough pads per side."
mpps = int(math.ceil(float(len(padtypes))/4))
print >> sys.stderr, "You should probably try at least %d pads per side."%mpps
sys.exit(3)
print """
# encounter.io file, autogenerated by scripts/pads
Version: 2
Orient: R0
Pad: c01 NW PADFC
Orient: R270
Pad: c02 NE PADFC
Orient: R180
Pad: c03 SE PADFC
Orient: R90
Pad: c04 SW PADFC
"""
# Generator for extra "trash" pads
def trashpadgen():
i=100
while True:
name='X%d'%i
while name in names:
i += 1
name='X%d'%i
names.append(name)
yield name
trashpads = trashpadgen()
# Print out in order of pads
for i in range(len(padspots)):
name = padspots[i]
orientation = padorients[i]
if name is None:
name = trashpads.next()
typ = 'PADNC'
else:
typ = ''
print 'Pad: %4s %s %s'%(name,orientation,typ)
if ((i+1)%PADS_PER_SIDE) == 0:
print
| Python |
#!/usr/bin/env python
for i in range(32):
print "PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );"%(i+3,i,i,i)
| Python |
import pbkdf2
def hx(s):
return s.encode('hex').upper()
vectors=pbkdf2.PBKDF2_tests
for i in range(len(vectors)):
args, res = vectors[i]
print
print '******************************************************************'
print 'UNIT %d'%i
wu = list(pbkdf2.workunits(*args))
if len(wu) != 1:
print 'Skipping unit %d due to multiple work units'%i
continue
KO,U1,c = wu[0]
c = pbkdf2.i2bytes(c)
print 'KO =',hx(KO)
print 'U1 =',hx(U1)
print ' c =',hx(c)
wub = KO+U1+c
print 'Complete work unit:'
open('work%02d'%i,'wb').write(wub)
print hx(wub)
result = pbkdf2.PBKDF2(*args)
print 'Expected result:'
assert(result == res.decode('hex'))
print hx(result)
out = 'vector%02d.asm'%i
print 'Generating ASM file:',out
out = open(out,'w')
words = [hx(wub[i:i+4]) for i in range(0,len(wub),4)]
words.reverse()
out.write('org 0x0000\n')
for w in words:
out.write("cfw 0x%s\n" % w)
out.write('\n')
out.write('org 0x0160\n')
for i in range(7):
out.write('cfw 0x00000000\n')
out.write('\n')
out.write('org 0x0200\n')
for w in reversed([res[i:i+8] for i in range(0,len(res),8)]):
out.write('cfw 0x%s\n'%w)
| Python |
# Generate a couple of 672-bit test vectors to feed through the HashBlock
from hashlib import sha1
import random
random.seed(12345)
datalen_bits=672
datalen=datalen_bits/8
def mkhdata():
return ''.join([chr(random.randint(0,255)) for x in range(datalen)])
def hx(s):
return s.encode('hex')
def cenc(s):
accum=[]
for c in s:
accum.append('0x%s'%c.encode('hex'))
return '{'+','.join(accum)+'}'
vectors=[mkhdata() for x in range(10)]
print 'sha1test tests[%d] = {'%len(vectors)
for i in range(len(vectors)):
idd = i+1
v = vectors[i]
h = sha1(v).digest()
print '// Test case #%d'%idd
assert(len(v)*8 == 672)
assert(len(h) == 20)
prefix = v[:64]
postfix = v[64:]
assert(len(prefix) == 64)
assert(len(postfix) == 20)
print '{{%s},'%cenc(prefix)
print '{%s},'%cenc(postfix)
print '{%s}},'%cenc(h)
print
print '};'
| Python |
import hashlib
import math
import os
B = 64 # SHA-1 block size, bytes
hLen = 20 # SHA-1 hash output length, bytes.
def sha1(d):
return hashlib.sha1(d).digest()
def mkKo(P):
if len(P) == B:
return P
if len(P) > B:
return sha1(P)+chr(0)*(B-hLen)
if len(P) < B:
return P+chr(0)*(B - len(P))
assert(False)
def xor(a,b):
return ''.join([chr(ord(x)^ord(y)) for x,y in zip(a,b)])
def i2bytes(i):
bytes=[]
while i:
bytes.append(chr(i % 256))
i = i / 256
while len(bytes) < 4:
bytes.append(chr(0))
bytes.reverse() # big-endian!
return ''.join(bytes)
ipad = chr(0x36)*B
opad = chr(0x5c)*B
def HMAC_SHA1(K,text):
Ko = mkKo(K)
assert(len(Ko) == B)
return sha1( xor(Ko, opad) +
sha1( xor(Ko,ipad) + text ) )
def PRF(K, data):
return HMAC_SHA1(K,data)
def innerF(Ko,U1,c):
c = i2bytes(c)
assert(len(Ko) == B)
assert(len(U1) == hLen)
assert(len(c) == 4)
print 'Calling innerF with:'
print 'Ko =',Ko.encode('hex')
print 'U1 =',U1.encode('hex')
print ' c =', c.encode('hex')
FN = "work"
q=open(FN,"wb")
q.write(Ko+U1+c)
q.close()
retval = os.system("./innerfssl %s"%FN)
assert(retval == 0)
OUT=FN+".output"
data=open(OUT,"rb").read()
assert(len(data) == hLen)
print 'innerF result:',data.encode('hex')
return data
def innerPRF(Ko,data):
assert(len(Ko) == B)
assert(len(data) == hLen)
step4 = xor(Ko,ipad)
step5 = step4 + data
assert(len(step5) == B+hLen)
step6 = sha1(step5)
step7 = xor(Ko, opad)
step8 = step7+step6
assert(len(step8) == B+hLen)
step9 = sha1(step8)
assert(step9 == HMAC_SHA1(Ko,data))
return step9
def innerF_host(Ko,U1,c):
assert(len(Ko) == B)
assert(len(U1) == hLen)
Ui = U1
acc = U1
#print 1
#print 'Ui: %s'%Ui.encode("hex")
#print 'acc: %s'%acc.encode("hex")
for i in range(2,c+1):
Ui = innerPRF(Ko, Ui)
acc = xor(acc, Ui)
#print i
#print 'Ui: %s'%Ui.encode("hex")
#print 'acc: %s'%acc.encode("hex")
return acc
def workunits(P,S, c, dkLen):
l = int(math.ceil(float(dkLen)/hLen))
r = dkLen - (l-1) * hLen
# Pregenerate the Ko vector
Ko = mkKo(P)
assert(len(Ko) == B)
# Resultant keyblocks
for i in range(l):
# Calculate first U iteration
U1 = PRF(P,S + i2bytes(i+1))
yield (Ko,U1,c)
def PBKDF2(P, S, c, dkLen):
l = int(math.ceil(float(dkLen)/hLen))
r = dkLen - (l-1) * hLen
T = [innerF(*workunit) for workunit in workunits(P,S,c, dkLen)]
# Assemble the results into a dkLen-length array and return them
result=[]
for i in range(l-1):
result.append(T[i])
result.append(T[l-1][:r])
return ''.join(result)
HMAC_tests = [
("Sample #1",
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
"4f4ca3d5d68ba7cc0a1208c9c61e9c5da0403c0a"),
("Sample #2",
"303132333435363738393a3b3c3d3e3f40414243",
"0922d3405faa3d194f82a45830737d5cc6c75d24"),
("Sample #4",
"707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0",
"9ea886efe268dbecce420c7524df32e0751a2a26")
]
def test_HMAC():
for text, key, result in HMAC_tests:
key,result = [z.decode("hex") for z in key,result]
if HMAC_SHA1(key,text) == result:
print text,'passed'
else:
print text,'failed'
PBKDF2_tests = [
(("password","salt",1,20), "0c60c80f961f0e71f3a9b524af6012062fe037a6"),
(("password","salt",2,20), "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"),
(("password","salt",4096,20), "4b007901b765489abead49d926f721d065a429c1"),
(("password","salt",16777216,20),"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"),
(("passwordPASSWORDpassword","saltSALTsaltSALTsaltSALTsaltSALTsalt",4096,25),"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"),
(("pass\x00word","sa\x00lt",4096,16),"56fa6aa75548099dcc37d7f03425e0c3")
]
def test_PBKDF2():
for i in range(len(PBKDF2_tests)):
params, result = PBKDF2_tests[i]
myres = PBKDF2(*params).encode("hex")
if myres == result:
print 'Test %d passed'%i
else:
print 'Test %d FAILED'%i
return
print
PBKDF2_vectors = [
("password", "salt", 16, 20)
]
if __name__ == "__main__":
test_PBKDF2()
print '-----------------------------------------------------------'
print 'Additional test vectors:'
for params in PBKDF2_vectors:
PBKDF2(*params)
print
| Python |
'''
Created on 21-03-2011
@author: maciek
'''
def formatString(format, **kwargs):
'''
'''
if not format: return ''
for arg in kwargs.keys():
format = format.replace("{" + arg + "}", "##" + arg + "##")
format = format.replace ("{", "{{")
format = format.replace("}", "}}")
for arg in kwargs.keys():
format = format.replace("##" + arg + "##", "{" + arg + "}")
res = format.format(**kwargs)
res = res.replace("{{", "{")
res = res.replace("}}", "}")
return res | Python |
'''
Created on 21-03-2011
@author: maciek
'''
from IndexGenerator import IndexGenerator
from optparse import OptionParser
import os
import tempfile
import shutil
import logging
logging.basicConfig(level = logging.DEBUG)
parser = OptionParser()
parser.add_option('-n', '--app-name', action='store', dest='appName', help='aplication name')
parser.add_option('-u', '--release-urls', action='store', dest='releaseUrls', help='URLs of download files - as coma separated list of entrires')
parser.add_option('-d', '--destination-directory', action='store', dest='otaAppDir', help='Directory where OTA files are created')
parser.add_option('-v', '--version', action='store', dest='version', help='Version of the application')
parser.add_option('-r', '--releases', action='store', dest='releases', help='Release names of the application')
parser.add_option('-R', '--release-notes', action='store', dest='releaseNotes', help='Release notes of the application (in txt2tags format)')
parser.add_option('-D', '--description', action='store', dest='description', help='Description of the application (in txt2tags format)')
(options, args) = parser.parse_args()
if options.appName == None:
parser.error("Please specify the appName.")
elif options.releaseUrls == None:
parser.error("Please specify releaseUrls")
elif options.otaAppDir == None:
parser.error("Please specify destination directory")
elif options.version == None:
parser.error("Please specify version")
elif options.releases == None:
parser.error("Please specify releases")
elif options.releaseNotes == None:
parser.error("Please specify releaseNotes")
elif options.description == None:
parser.error("Please specify description")
appName = options.appName
releaseUrls = options.releaseUrls
otaAppDir = options.otaAppDir
version = options.version
releases = options.releases
releaseNotes = options.releaseNotes
description = options.description
def findIconFilename():
iconPath = "res/drawable-hdpi/icon.png"
if not os.path.exists(iconPath):
iconPath = "res/drawable-mdpi/icon.png"
if not os.path.exists(iconPath):
iconPath = "res/drawable-ldpi/icon.png"
if not os.path.exists(iconPath):
iconPath = "res/drawable/icon.png"
logging.debug("IconPath: "+iconPath)
return iconPath
def createOTApackage():
'''
crates all needed files in tmp dir
'''
releaseNotesContent = open(releaseNotes).read()
descriptionContent = open(description).read()
indexGenerator = IndexGenerator(appName, releaseUrls, releaseNotesContent, descriptionContent, version, releases)
index = indexGenerator.get();
tempIndexFile = tempfile.TemporaryFile()
tempIndexFile.write(index)
tempIndexFile.flush()
tempIndexFile.seek(0)
return tempIndexFile
tempIndexFile = createOTApackage()
if not os.path.isdir(otaAppDir):
logging.debug("creating dir: "+otaAppDir)
os.mkdir(otaAppDir)
else:
logging.warning("dir: "+otaAppDir+" exists")
indexFile = open(os.path.join(otaAppDir,"index.html"),'w')
shutil.copyfileobj(tempIndexFile, indexFile)
srcIconFileName = findIconFilename()
disIconFileName = os.path.join(otaAppDir,"Icon.png")
shutil.copy(srcIconFileName,disIconFileName)
| Python |
'''
Created on 21-03-2011
@author: maciek
'''
from formater import formatString
import os
class IndexGenerator(object):
'''
Generates Index.html for iOS app OTA distribution
'''
basePath = os.path.dirname(__file__)
templateFile = os.path.join(basePath,"templates/index.tmpl")
releaseUrls = ""
appName = ""
changeLog = ""
description = ""
version = ""
release = ""
def __init__(self,appName, releaseUrls, changeLog, description, version, releases):
'''
Constructor
'''
self.appName = appName
self.releaseUrls = releaseUrls
self.changeLog = changeLog
self.description = description
self.version = version
self.releases = releases
def get(self):
'''
returns index.html source code from template file
'''
urlList = self.releaseUrls.split(",")
releaseList = self.releases.split(",")
generatedHtml=""
count=0;
for release in releaseList:
generatedHtml += " <li>\n"
generatedHtml += " <h3><a href=\"javascript:load('" + urlList[count] + "')\">" + release + "</a></h3>\n"
generatedHtml += " </li>\n"
count += 1
template = open(self.templateFile).read()
index = formatString(template, downloads=generatedHtml,
changeLog=self.changeLog,
appName=self.appName,
description=self.description,
version = self.version);
return index | Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '1.0'
__author__ = 'Liao Xuefeng (askxuefeng@gmail.com)'
'''
Python client SDK for sina weibo API using OAuth 1.0
'''
try:
import json
except ImportError:
import simplejson as json
import time
import hmac
import uuid
import base64
import urllib
import urllib2
import hashlib
import logging
_OAUTH_SIGN_METHOD = 'HMAC-SHA1'
_OAUTH_VERSION = '1.0'
class OAuthToken(object):
def __init__(self, oauth_token, oauth_token_secret, oauth_verifier=None, **kw):
self.oauth_token = oauth_token
self.oauth_token_secret = oauth_token_secret
self.oauth_verifier = oauth_verifier
for k, v in kw.iteritems():
setattr(self, k, v)
def __str__(self):
attrs = [s for s in dir(self) if not s.startswith('__')]
kvs = ['%s = %s' % (k, getattr(self, k)) for k in attrs]
return ', '.join(kvs)
__repr__ = __str__
class APIClient(object):
def __init__(self, app_key, app_secret, token=None, callback=None, domain='api.t.sina.com.cn'):
self.app_key = str(app_key)
self.app_secret = str(app_secret)
if token:
if isinstance(token, OAuthToken):
if token.oauth_token:
self.oauth_token = token.oauth_token
if token.oauth_token_secret:
self.oauth_token_secret = token.oauth_token_secret
if token.oauth_verifier:
self.oauth_verifier = token.oauth_verifier
else:
raise TypeError('token parameter must be instance of OAuthToken.')
self.callback = callback
self.api_url = 'http://%s' % domain
self.get = HttpObject(self, _HTTP_GET)
self.post = HttpObject(self, _HTTP_POST)
def _oauth_request(self, method, url, **kw):
params = dict( \
oauth_consumer_key=self.app_key, \
oauth_nonce=_generate_nonce(), \
oauth_signature_method=_OAUTH_SIGN_METHOD, \
oauth_timestamp=str(int(time.time())), \
oauth_version=_OAUTH_VERSION, \
oauth_token=self.oauth_token)
params.update(kw)
m = 'GET' if method==_HTTP_GET else 'POST'
bs = _generate_base_string(m, url, **params)
key = '%s&%s' % (self.app_secret, self.oauth_token_secret)
oauth_signature = _generate_signature(key, bs)
print 'params:', params
print 'base string:', bs
print 'key:', key, 'sign:', oauth_signature
print 'url:', url
r = _http_call(url, method, self.__build_oauth_header(params, oauth_signature=oauth_signature), **kw)
return r
def get_request_token(self):
'''
Step 1: request oauth token.
Returns:
OAuthToken object contains oauth_token and oauth_token_secret
'''
params = dict(oauth_callback=self.callback, \
oauth_consumer_key=self.app_key, \
oauth_nonce=_generate_nonce(), \
oauth_signature_method=_OAUTH_SIGN_METHOD, \
oauth_timestamp=str(int(time.time())), \
oauth_version=_OAUTH_VERSION)
url = '%s/oauth/request_token' % self.api_url
bs = _generate_base_string('GET', url, **params)
params['oauth_signature'] = base64.b64encode(hmac.new('%s&' % self.app_secret, bs, hashlib.sha1).digest())
r = _http_call(url, _HTTP_GET, return_json=False, **params)
kw = _parse_params(r, False)
return OAuthToken(**kw)
def get_authorize_url(self, oauth_token):
'''
Step 2: get authorize url and redirect to it.
Args:
oauth_token: oauth_token str that returned from request_token:
oauth_token = client.request_token().oauth_token
Returns:
redirect url, e.g. "http://api.t.sina.com.cn/oauth/authorize?oauth_token=ABCD1234XYZ"
'''
return '%s/oauth/authorize?oauth_token=%s' % (self.api_url, oauth_token)
def get_access_token(self):
'''
get access token from request token:
request_token = OAuthToken(oauth_token, oauth_secret, oauth_verifier)
client = APIClient(appkey, appsecret, request_token)
access_token = client.get_access_token()
'''
params = {
'oauth_consumer_key': self.app_key,
'oauth_timestamp': str(int(time.time())),
'oauth_nonce': _generate_nonce(),
'oauth_version': _OAUTH_VERSION,
'oauth_signature_method': _OAUTH_SIGN_METHOD,
'oauth_token': self.oauth_token,
'oauth_verifier': self.oauth_verifier,
}
url = '%s/oauth/access_token' % self.api_url
bs = _generate_base_string('GET', url, **params)
key = '%s&%s' % (self.app_secret, self.oauth_token_secret)
oauth_signature = _generate_signature(key, bs)
authorization = self.__build_oauth_header(params, oauth_signature=oauth_signature)
r = _http_call(url, _HTTP_GET, authorization, return_json=False)
kw = _parse_params(r, False)
return OAuthToken(**kw)
def __build_oauth_header(self, params, **kw):
'''
build oauth header like: Authorization: OAuth oauth_token="xxx", oauth_nonce="123"
Args:
params: parameter dict.
**kw: any additional key-value parameters.
'''
d = dict(**kw)
d.update(params)
L = [r'%s="%s"' % (k, v) for k, v in d.iteritems() if k.startswith('oauth_')]
return 'OAuth %s' % ', '.join(L)
def __getattr__(self, attr):
' a shortcut for client.get.funcall() to client.funcall() '
return getattr(self.get, attr)
def _obj_hook(pairs):
'''
convert json object to python object.
'''
o = JsonObject()
for k, v in pairs.iteritems():
o[str(k)] = v
return o
class APIError(StandardError):
'''
raise APIError if got failed json message.
'''
def __init__(self, error_code, error, request):
self.error_code = error_code
self.error = error
self.request = request
StandardError.__init__(self, error)
def __str__(self):
return 'APIError: %s: %s, request: %s' % (self.error_code, self.error, self.request)
class JsonObject(dict):
'''
general json object that can bind any fields but also act as a dict.
'''
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
def _encode_multipart(**kw):
'''
Build a multipart/form-data body with generated random boundary.
'''
boundary = '----------%s' % hex(int(time.time() * 1000))
data = []
for k, v in kw.iteritems():
data.append('--%s' % boundary)
if hasattr(v, 'read'):
# file-like object:
ext = ''
filename = getattr(v, 'name', '')
n = filename.rfind('.')
if n != (-1):
ext = filename[n:].lower()
content = v.read()
data.append('Content-Disposition: form-data; name="%s"; filename="hidden"' % k)
data.append('Content-Length: %d' % len(content))
data.append('Content-Type: %s\r\n' % _guess_content_type(ext))
data.append(content)
else:
data.append('Content-Disposition: form-data; name="%s"\r\n' % k)
data.append(v.encode('utf-8') if isinstance(v, unicode) else v)
data.append('--%s--\r\n' % boundary)
return '\r\n'.join(data), boundary
_CONTENT_TYPES = { '.png': 'image/png', '.gif': 'image/gif', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.jpe': 'image/jpeg' }
def _guess_content_type(ext):
return _CONTENT_TYPES.get(ext, 'application/octet-stream')
_HTTP_GET = 0
_HTTP_POST = 1
_HTTP_UPLOAD = 2
def _http_call(url, method, authorization=None, return_json=True, **kw):
'''
send an http request and return headers and body if no error.
'''
params = None
boundary = None
if method==_HTTP_UPLOAD:
params, boundary = _encode_multipart(**kw)
else:
params = _encode_params(**kw)
http_url = '%s?%s' % (url, params) if method==_HTTP_GET and params else url
http_body = None if method==_HTTP_GET else params
req = urllib2.Request(http_url, data=http_body)
if authorization:
print 'Authorization:', authorization
req.add_header('Authorization', authorization)
if boundary:
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
print method, http_url, 'BODY:', http_body
resp = urllib2.urlopen(req)
body = resp.read()
if return_json:
r = json.loads(body, object_hook=_obj_hook)
if hasattr(r, 'error_code'):
raise APIError(r.error_code, getattr(r, 'error', ''), getattr(r, 'request', ''))
return r
return body
class HttpObject(object):
def __init__(self, client, method):
self.client = client
self.method = method
def __getattr__(self, attr):
def wrap(**kw):
return self.client._oauth_request(self.method, '%s/%s.json' % (self.client.api_url, attr.replace('__', '/')), **kw)
return wrap
################################################################################
# utility functions
################################################################################
def _parse_params(params_str, unicode_value=True):
'''
parse a query string as JsonObject (also a dict)
Args:
params_str: query string as str.
unicode_value: return unicode value if True, otherwise str value. default true.
Returns:
JsonObject (inherited from dict)
>>> s = _parse_params('a=123&b=X%26Y&c=%E4%B8%AD%E6%96%87')
>>> s.a
u'123'
>>> s.b
u'X&Y'
>>> s.c==u'\u4e2d\u6587'
True
>>> s = _parse_params('a=123&b=X%26Y&c=%E4%B8%AD%E6%96%87', False)
>>> s.a
'123'
>>> s.b
'X&Y'
>>> s.c=='\xe4\xb8\xad\xe6\x96\x87'
True
>>> s.d #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
KeyError:
'''
d = dict()
for s in params_str.split('&'):
n = s.find('=')
if n>0:
key = s[:n]
value = urllib.unquote(s[n+1:])
d[key] = value.decode('utf-8') if unicode_value else value
return JsonObject(**d)
def _encode_params(**kw):
'''
Encode parameters.
'''
if kw:
args = []
for k, v in kw.iteritems():
qv = v.encode('utf-8') if isinstance(v, unicode) else str(v)
args.append('%s=%s' % (k, _quote(qv)))
return '&'.join(args)
return ''
def _quote(s):
'''
quote everything including /
>>> _quote(123)
'123'
>>> _quote(u'\u4e2d\u6587')
'%E4%B8%AD%E6%96%87'
>>> _quote('/?abc=def& _+%')
'%2F%3Fabc%3Ddef%26%20_%2B%25'
'''
if isinstance(s, unicode):
s = s.encode('utf-8')
return urllib.quote(str(s), safe='')
def _generate_nonce():
' generate random uuid as oauth_nonce '
return uuid.uuid4().hex
def _generate_signature(key, base_string):
'''
generate url-encoded oauth_signature with HMAC-SHA1
'''
return _quote(base64.b64encode(hmac.new(key, base_string, hashlib.sha1).digest()))
def _generate_base_string(method, url, **params):
'''
generate base string for signature
>>> method = 'GET'
>>> url = 'http://www.sina.com.cn/news'
>>> params = dict(a=1, b='A&B')
>>> _generate_base_string(method, url, **params)
'GET&http%3A%2F%2Fwww.sina.com.cn%2Fnews&a%3D1%26b%3DA%2526B'
'''
plist = [(_quote(k), _quote(v)) for k, v in params.iteritems()]
plist.sort()
return '%s&%s&%s' % (method, _quote(url), _quote('&'.join(['%s=%s' % (k, v) for k, v in plist])))
if __name__=='__main__':
import doctest
doctest.testmod()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '1.04'
__author__ = 'Liao Xuefeng (askxuefeng@gmail.com)'
'''
Python client SDK for sina weibo API using OAuth 2.
'''
try:
import json
except ImportError:
import simplejson as json
import time
import urllib
import urllib2
import logging
def _obj_hook(pairs):
'''
convert json object to python object.
'''
o = JsonObject()
for k, v in pairs.iteritems():
o[str(k)] = v
return o
class APIError(StandardError):
'''
raise APIError if got failed json message.
'''
def __init__(self, error_code, error, request):
self.error_code = error_code
self.error = error
self.request = request
StandardError.__init__(self, error)
def __str__(self):
return 'APIError: %s: %s, request: %s' % (self.error_code, self.error, self.request)
class JsonObject(dict):
'''
general json object that can bind any fields but also act as a dict.
'''
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
def _encode_params(**kw):
'''
Encode parameters.
'''
args = []
for k, v in kw.iteritems():
qv = v.encode('utf-8') if isinstance(v, unicode) else str(v)
args.append('%s=%s' % (k, urllib.quote(qv)))
return '&'.join(args)
def _encode_multipart(**kw):
'''
Build a multipart/form-data body with generated random boundary.
'''
boundary = '----------%s' % hex(int(time.time() * 1000))
data = []
for k, v in kw.iteritems():
data.append('--%s' % boundary)
if hasattr(v, 'read'):
# file-like object:
ext = ''
filename = getattr(v, 'name', '')
n = filename.rfind('.')
if n != (-1):
ext = filename[n:].lower()
content = v.read()
data.append('Content-Disposition: form-data; name="%s"; filename="hidden"' % k)
data.append('Content-Length: %d' % len(content))
data.append('Content-Type: %s\r\n' % _guess_content_type(ext))
data.append(content)
else:
data.append('Content-Disposition: form-data; name="%s"\r\n' % k)
data.append(v.encode('utf-8') if isinstance(v, unicode) else v)
data.append('--%s--\r\n' % boundary)
return '\r\n'.join(data), boundary
_CONTENT_TYPES = { '.png': 'image/png', '.gif': 'image/gif', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.jpe': 'image/jpeg' }
def _guess_content_type(ext):
return _CONTENT_TYPES.get(ext, 'application/octet-stream')
_HTTP_GET = 0
_HTTP_POST = 1
_HTTP_UPLOAD = 2
def _http_get(url, authorization=None, **kw):
logging.info('GET %s' % url)
return _http_call(url, _HTTP_GET, authorization, **kw)
def _http_post(url, authorization=None, **kw):
logging.info('POST %s' % url)
return _http_call(url, _HTTP_POST, authorization, **kw)
def _http_upload(url, authorization=None, **kw):
logging.info('MULTIPART POST %s' % url)
return _http_call(url, _HTTP_UPLOAD, authorization, **kw)
def _http_call(url, method, authorization, **kw):
'''
send an http request and expect to return a json object if no error.
'''
params = None
boundary = None
if method==_HTTP_UPLOAD:
params, boundary = _encode_multipart(**kw)
else:
params = _encode_params(**kw)
http_url = '%s?%s' % (url, params) if method==_HTTP_GET else url
http_body = None if method==_HTTP_GET else params
req = urllib2.Request(http_url, data=http_body)
if authorization:
req.add_header('Authorization', 'OAuth2 %s' % authorization)
if boundary:
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
resp = urllib2.urlopen(req)
body = resp.read()
r = json.loads(body, object_hook=_obj_hook)
if hasattr(r, 'error_code'):
raise APIError(r.error_code, getattr(r, 'error', ''), getattr(r, 'request', ''))
return r
class HttpObject(object):
def __init__(self, client, method):
self.client = client
self.method = method
def __getattr__(self, attr):
def wrap(**kw):
if self.client.is_expires():
raise APIError('21327', 'expired_token', attr)
return _http_call('%s%s.json' % (self.client.api_url, attr.replace('__', '/')), self.method, self.client.access_token, **kw)
return wrap
class APIClient(object):
'''
API client using synchronized invocation.
'''
def __init__(self, app_key, app_secret, redirect_uri=None, response_type='code', domain='api.weibo.com', version='2'):
self.client_id = app_key
self.client_secret = app_secret
self.redirect_uri = redirect_uri
self.response_type = response_type
self.auth_url = 'https://%s/oauth2/' % domain
self.api_url = 'https://%s/%s/' % (domain, version)
self.access_token = None
self.expires = 0.0
self.get = HttpObject(self, _HTTP_GET)
self.post = HttpObject(self, _HTTP_POST)
self.upload = HttpObject(self, _HTTP_UPLOAD)
def set_access_token(self, access_token, expires_in):
self.access_token = str(access_token)
self.expires = float(expires_in)
def get_authorize_url(self, redirect_uri=None, display='default'):
'''
return the authroize url that should be redirect.
'''
redirect = redirect_uri if redirect_uri else self.redirect_uri
if not redirect:
raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
return '%s%s?%s' % (self.auth_url, 'authorize', \
_encode_params(client_id = self.client_id, \
response_type = 'code', \
display = display, \
redirect_uri = redirect))
def request_access_token(self, code, redirect_uri=None):
'''
return access token as object: {"access_token":"your-access-token","expires_in":12345678}, expires_in is standard unix-epoch-time
'''
redirect = redirect_uri if redirect_uri else self.redirect_uri
if not redirect:
raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
r = _http_post('%s%s' % (self.auth_url, 'access_token'), \
client_id = self.client_id, \
client_secret = self.client_secret, \
redirect_uri = redirect, \
code = code, grant_type = 'authorization_code')
r.expires_in += int(time.time())
return r
def is_expires(self):
return not self.access_token or time.time() > self.expires
def __getattr__(self, attr):
return getattr(self.get, attr)
| Python |
#!/usr/bin/env python
"""
client module for memcached (memory cache daemon)
Overview
========
See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.
Usage summary
=============
This should give you a feel for how this module operates::
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
mc.set("some_key", "Some value")
value = mc.get("some_key")
mc.set("another_key", 3)
mc.delete("another_key")
mc.set("key", "1") # note that the key used for incr/decr must be a string.
mc.incr("key")
mc.decr("key")
The standard way to use memcache with a database is like this::
key = derive_key(obj)
obj = mc.get(key)
if not obj:
obj = backend_api.get(...)
mc.set(key, obj)
# we now have obj, and future passes through this code
# will use the object from the cache.
Detailed Documentation
======================
More detailed documentation is available in the L{Client} class.
"""
import sys
import socket
import time
import os
import re
try:
import cPickle as pickle
except ImportError:
import pickle
from binascii import crc32 # zlib version is not cross-platform
def cmemcache_hash(key):
return((((crc32(key) & 0xffffffff) >> 16) & 0x7fff) or 1)
serverHashFunction = cmemcache_hash
def useOldServerHashFunction():
"""Use the old python-memcache server hash function."""
global serverHashFunction
serverHashFunction = crc32
try:
from zlib import compress, decompress
_supports_compress = True
except ImportError:
_supports_compress = False
# quickly define a decompress just in case we recv compressed data.
def decompress(val):
raise _Error("received compressed data but I don't support compression (import error)")
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
# Original author: Evan Martin of Danga Interactive
__author__ = "Sean Reifschneider <jafo-memcached@tummy.com>"
__version__ = "1.48"
__copyright__ = "Copyright (C) 2003 Danga Interactive"
# http://en.wikipedia.org/wiki/Python_Software_Foundation_License
__license__ = "Python Software Foundation License"
SERVER_MAX_KEY_LENGTH = 250
# Storing values larger than 1MB requires recompiling memcached. If you do,
# this value can be changed by doing "memcache.SERVER_MAX_VALUE_LENGTH = N"
# after importing this module.
SERVER_MAX_VALUE_LENGTH = 1024*1024
class _Error(Exception):
pass
class _ConnectionDeadError(Exception):
pass
try:
# Only exists in Python 2.4+
from threading import local
except ImportError:
# TODO: add the pure-python local implementation
class local(object):
pass
_DEAD_RETRY = 30 # number of seconds before retrying a dead server.
_SOCKET_TIMEOUT = 3 # number of seconds before sockets timeout.
class Client(local):
"""
Object representing a pool of memcache servers.
See L{memcache} for an overview.
In all cases where a key is used, the key can be either:
1. A simple hashable type (string, integer, etc.).
2. A tuple of C{(hashvalue, key)}. This is useful if you want to avoid
making this module calculate a hash value. You may prefer, for
example, to keep all of a given user's objects on the same memcache
server, so you could use the user's unique id as the hash value.
@group Setup: __init__, set_servers, forget_dead_hosts, disconnect_all, debuglog
@group Insertion: set, add, replace, set_multi
@group Retrieval: get, get_multi
@group Integers: incr, decr
@group Removal: delete, delete_multi
@sort: __init__, set_servers, forget_dead_hosts, disconnect_all, debuglog,\
set, set_multi, add, replace, get, get_multi, incr, decr, delete, delete_multi
"""
_FLAG_PICKLE = 1<<0
_FLAG_INTEGER = 1<<1
_FLAG_LONG = 1<<2
_FLAG_COMPRESSED = 1<<3
_SERVER_RETRIES = 10 # how many times to try finding a free server.
# exceptions for Client
class MemcachedKeyError(Exception):
pass
class MemcachedKeyLengthError(MemcachedKeyError):
pass
class MemcachedKeyCharacterError(MemcachedKeyError):
pass
class MemcachedKeyNoneError(MemcachedKeyError):
pass
class MemcachedKeyTypeError(MemcachedKeyError):
pass
class MemcachedStringEncodingError(Exception):
pass
def __init__(self, servers, debug=0, pickleProtocol=0,
pickler=pickle.Pickler, unpickler=pickle.Unpickler,
pload=None, pid=None,
server_max_key_length=SERVER_MAX_KEY_LENGTH,
server_max_value_length=SERVER_MAX_VALUE_LENGTH,
dead_retry=_DEAD_RETRY, socket_timeout=_SOCKET_TIMEOUT,
cache_cas = False):
"""
Create a new Client object with the given list of servers.
@param servers: C{servers} is passed to L{set_servers}.
@param debug: whether to display error messages when a server can't be
contacted.
@param pickleProtocol: number to mandate protocol used by (c)Pickle.
@param pickler: optional override of default Pickler to allow subclassing.
@param unpickler: optional override of default Unpickler to allow subclassing.
@param pload: optional persistent_load function to call on pickle loading.
Useful for cPickle since subclassing isn't allowed.
@param pid: optional persistent_id function to call on pickle storing.
Useful for cPickle since subclassing isn't allowed.
@param dead_retry: number of seconds before retrying a blacklisted
server. Default to 30 s.
@param socket_timeout: timeout in seconds for all calls to a server. Defaults
to 3 seconds.
@param cache_cas: (default False) If true, cas operations will be
cached. WARNING: This cache is not expired internally, if you have
a long-running process you will need to expire it manually via
"client.reset_cas(), or the cache can grow unlimited.
@param server_max_key_length: (default SERVER_MAX_KEY_LENGTH)
Data that is larger than this will not be sent to the server.
@param server_max_value_length: (default SERVER_MAX_VALUE_LENGTH)
Data that is larger than this will not be sent to the server.
"""
local.__init__(self)
self.debug = debug
self.dead_retry = dead_retry
self.socket_timeout = socket_timeout
self.set_servers(servers)
self.stats = {}
self.cache_cas = cache_cas
self.reset_cas()
# Allow users to modify pickling/unpickling behavior
self.pickleProtocol = pickleProtocol
self.pickler = pickler
self.unpickler = unpickler
self.persistent_load = pload
self.persistent_id = pid
self.server_max_key_length = server_max_key_length
self.server_max_value_length = server_max_value_length
# figure out the pickler style
file = StringIO()
try:
pickler = self.pickler(file, protocol = self.pickleProtocol)
self.picklerIsKeyword = True
except TypeError:
self.picklerIsKeyword = False
def reset_cas(self):
"""
Reset the cas cache. This is only used if the Client() object
was created with "cache_cas=True". If used, this cache does not
expire internally, so it can grow unbounded if you do not clear it
yourself.
"""
self.cas_ids = {}
def set_servers(self, servers):
"""
Set the pool of servers used by this client.
@param servers: an array of servers.
Servers can be passed in two forms:
1. Strings of the form C{"host:port"}, which implies a default weight of 1.
2. Tuples of the form C{("host:port", weight)}, where C{weight} is
an integer weight value.
"""
self.servers = [_Host(s, self.debug, dead_retry=self.dead_retry,
socket_timeout=self.socket_timeout)
for s in servers]
self._init_buckets()
def get_stats(self, stat_args = None):
'''Get statistics from each of the servers.
@param stat_args: Additional arguments to pass to the memcache
"stats" command.
@return: A list of tuples ( server_identifier, stats_dictionary ).
The dictionary contains a number of name/value pairs specifying
the name of the status field and the string value associated with
it. The values are not converted from strings.
'''
data = []
for s in self.servers:
if not s.connect(): continue
if s.family == socket.AF_INET:
name = '%s:%s (%s)' % ( s.ip, s.port, s.weight )
else:
name = 'unix:%s (%s)' % ( s.address, s.weight )
if not stat_args:
s.send_cmd('stats')
else:
s.send_cmd('stats ' + stat_args)
serverData = {}
data.append(( name, serverData ))
readline = s.readline
while 1:
line = readline()
if not line or line.strip() == 'END': break
stats = line.split(' ', 2)
serverData[stats[1]] = stats[2]
return(data)
def get_slabs(self):
data = []
for s in self.servers:
if not s.connect(): continue
if s.family == socket.AF_INET:
name = '%s:%s (%s)' % ( s.ip, s.port, s.weight )
else:
name = 'unix:%s (%s)' % ( s.address, s.weight )
serverData = {}
data.append(( name, serverData ))
s.send_cmd('stats items')
readline = s.readline
while 1:
line = readline()
if not line or line.strip() == 'END': break
item = line.split(' ', 2)
#0 = STAT, 1 = ITEM, 2 = Value
slab = item[1].split(':', 2)
#0 = items, 1 = Slab #, 2 = Name
if slab[1] not in serverData:
serverData[slab[1]] = {}
serverData[slab[1]][slab[2]] = item[2]
return data
def flush_all(self):
'Expire all data currently in the memcache servers.'
for s in self.servers:
if not s.connect(): continue
s.send_cmd('flush_all')
s.expect("OK")
def debuglog(self, str):
if self.debug:
sys.stderr.write("MemCached: %s\n" % str)
def _statlog(self, func):
if func not in self.stats:
self.stats[func] = 1
else:
self.stats[func] += 1
def forget_dead_hosts(self):
"""
Reset every host in the pool to an "alive" state.
"""
for s in self.servers:
s.deaduntil = 0
def _init_buckets(self):
self.buckets = []
for server in self.servers:
for i in range(server.weight):
self.buckets.append(server)
def _get_server(self, key):
if isinstance(key, tuple):
serverhash, key = key
else:
serverhash = serverHashFunction(key)
for i in range(Client._SERVER_RETRIES):
server = self.buckets[serverhash % len(self.buckets)]
if server.connect():
#print "(using server %s)" % server,
return server, key
serverhash = serverHashFunction(str(serverhash) + str(i))
return None, None
def disconnect_all(self):
for s in self.servers:
s.close_socket()
def delete_multi(self, keys, time=0, key_prefix=''):
'''
Delete multiple keys in the memcache doing just one query.
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1
>>> mc.delete_multi(['key1', 'key2'])
1
>>> mc.get_multi(['key1', 'key2']) == {}
1
This method is recommended over iterated regular L{delete}s as it reduces total latency, since
your app doesn't have to wait for each round-trip of L{delete} before sending
the next one.
@param keys: An iterable of keys to clear
@param time: number of seconds any subsequent set / update commands should fail. Defaults to 0 for no delay.
@param key_prefix: Optional string to prepend to each key when sending to memcache.
See docs for L{get_multi} and L{set_multi}.
@return: 1 if no failure in communication with any memcacheds.
@rtype: int
'''
self._statlog('delete_multi')
server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(keys, key_prefix)
# send out all requests on each server before reading anything
dead_servers = []
rc = 1
for server in server_keys.iterkeys():
bigcmd = []
write = bigcmd.append
if time != None:
for key in server_keys[server]: # These are mangled keys
write("delete %s %d\r\n" % (key, time))
else:
for key in server_keys[server]: # These are mangled keys
write("delete %s\r\n" % key)
try:
server.send_cmds(''.join(bigcmd))
except socket.error, msg:
rc = 0
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
dead_servers.append(server)
# if any servers died on the way, don't expect them to respond.
for server in dead_servers:
del server_keys[server]
for server, keys in server_keys.iteritems():
try:
for key in keys:
server.expect("DELETED")
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
rc = 0
return rc
def delete(self, key, time=0):
'''Deletes a key from the memcache.
@return: Nonzero on success.
@param time: number of seconds any subsequent set / update commands
should fail. Defaults to None for no delay.
@rtype: int
'''
self.check_key(key)
server, key = self._get_server(key)
if not server:
return 0
self._statlog('delete')
if time != None and time != 0:
cmd = "delete %s %d" % (key, time)
else:
cmd = "delete %s" % key
try:
server.send_cmd(cmd)
line = server.readline()
if line and line.strip() in ['DELETED', 'NOT_FOUND']: return 1
self.debuglog('Delete expected DELETED or NOT_FOUND, got: %s'
% repr(line))
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return 0
def incr(self, key, delta=1):
"""
Sends a command to the server to atomically increment the value
for C{key} by C{delta}, or by 1 if C{delta} is unspecified.
Returns None if C{key} doesn't exist on server, otherwise it
returns the new value after incrementing.
Note that the value for C{key} must already exist in the memcache,
and it must be the string representation of an integer.
>>> mc.set("counter", "20") # returns 1, indicating success
1
>>> mc.incr("counter")
21
>>> mc.incr("counter")
22
Overflow on server is not checked. Be aware of values approaching
2**32. See L{decr}.
@param delta: Integer amount to increment by (should be zero or greater).
@return: New value after incrementing.
@rtype: int
"""
return self._incrdecr("incr", key, delta)
def decr(self, key, delta=1):
"""
Like L{incr}, but decrements. Unlike L{incr}, underflow is checked and
new values are capped at 0. If server value is 1, a decrement of 2
returns 0, not -1.
@param delta: Integer amount to decrement by (should be zero or greater).
@return: New value after decrementing.
@rtype: int
"""
return self._incrdecr("decr", key, delta)
def _incrdecr(self, cmd, key, delta):
self.check_key(key)
server, key = self._get_server(key)
if not server:
return 0
self._statlog(cmd)
cmd = "%s %s %d" % (cmd, key, delta)
try:
server.send_cmd(cmd)
line = server.readline()
if line == None or line.strip() =='NOT_FOUND': return None
return int(line)
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return None
def add(self, key, val, time = 0, min_compress_len = 0):
'''
Add new key with value.
Like L{set}, but only stores in memcache if the key doesn't already exist.
@return: Nonzero on success.
@rtype: int
'''
return self._set("add", key, val, time, min_compress_len)
def append(self, key, val, time=0, min_compress_len=0):
'''Append the value to the end of the existing key's value.
Only stores in memcache if key already exists.
Also see L{prepend}.
@return: Nonzero on success.
@rtype: int
'''
return self._set("append", key, val, time, min_compress_len)
def prepend(self, key, val, time=0, min_compress_len=0):
'''Prepend the value to the beginning of the existing key's value.
Only stores in memcache if key already exists.
Also see L{append}.
@return: Nonzero on success.
@rtype: int
'''
return self._set("prepend", key, val, time, min_compress_len)
def replace(self, key, val, time=0, min_compress_len=0):
'''Replace existing key with value.
Like L{set}, but only stores in memcache if the key already exists.
The opposite of L{add}.
@return: Nonzero on success.
@rtype: int
'''
return self._set("replace", key, val, time, min_compress_len)
def set(self, key, val, time=0, min_compress_len=0):
'''Unconditionally sets a key to a given value in the memcache.
The C{key} can optionally be an tuple, with the first element
being the server hash value and the second being the key.
If you want to avoid making this module calculate a hash value.
You may prefer, for example, to keep all of a given user's objects
on the same memcache server, so you could use the user's unique
id as the hash value.
@return: Nonzero on success.
@rtype: int
@param time: Tells memcached the time which this value should expire, either
as a delta number of seconds, or an absolute unix time-since-the-epoch
value. See the memcached protocol docs section "Storage Commands"
for more info on <exptime>. We default to 0 == cache forever.
@param min_compress_len: The threshold length to kick in auto-compression
of the value using the zlib.compress() routine. If the value being cached is
a string, then the length of the string is measured, else if the value is an
object, then the length of the pickle result is measured. If the resulting
attempt at compression yeilds a larger string than the input, then it is
discarded. For backwards compatability, this parameter defaults to 0,
indicating don't ever try to compress.
'''
return self._set("set", key, val, time, min_compress_len)
def cas(self, key, val, time=0, min_compress_len=0):
'''Sets a key to a given value in the memcache if it hasn't been
altered since last fetched. (See L{gets}).
The C{key} can optionally be an tuple, with the first element
being the server hash value and the second being the key.
If you want to avoid making this module calculate a hash value.
You may prefer, for example, to keep all of a given user's objects
on the same memcache server, so you could use the user's unique
id as the hash value.
@return: Nonzero on success.
@rtype: int
@param time: Tells memcached the time which this value should expire,
either as a delta number of seconds, or an absolute unix
time-since-the-epoch value. See the memcached protocol docs section
"Storage Commands" for more info on <exptime>. We default to
0 == cache forever.
@param min_compress_len: The threshold length to kick in
auto-compression of the value using the zlib.compress() routine. If
the value being cached is a string, then the length of the string is
measured, else if the value is an object, then the length of the
pickle result is measured. If the resulting attempt at compression
yeilds a larger string than the input, then it is discarded. For
backwards compatability, this parameter defaults to 0, indicating
don't ever try to compress.
'''
return self._set("cas", key, val, time, min_compress_len)
def _map_and_prefix_keys(self, key_iterable, key_prefix):
"""Compute the mapping of server (_Host instance) -> list of keys to stuff onto that server, as well as the mapping of
prefixed key -> original key.
"""
# Check it just once ...
key_extra_len=len(key_prefix)
if key_prefix:
self.check_key(key_prefix)
# server (_Host) -> list of unprefixed server keys in mapping
server_keys = {}
prefixed_to_orig_key = {}
# build up a list for each server of all the keys we want.
for orig_key in key_iterable:
if isinstance(orig_key, tuple):
# Tuple of hashvalue, key ala _get_server(). Caller is essentially telling us what server to stuff this on.
# Ensure call to _get_server gets a Tuple as well.
str_orig_key = str(orig_key[1])
server, key = self._get_server((orig_key[0], key_prefix + str_orig_key)) # Gotta pre-mangle key before hashing to a server. Returns the mangled key.
else:
str_orig_key = str(orig_key) # set_multi supports int / long keys.
server, key = self._get_server(key_prefix + str_orig_key)
# Now check to make sure key length is proper ...
self.check_key(str_orig_key, key_extra_len=key_extra_len)
if not server:
continue
if server not in server_keys:
server_keys[server] = []
server_keys[server].append(key)
prefixed_to_orig_key[key] = orig_key
return (server_keys, prefixed_to_orig_key)
def set_multi(self, mapping, time=0, key_prefix='', min_compress_len=0):
'''
Sets multiple keys in the memcache doing just one query.
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1
This method is recommended over regular L{set} as it lowers the number of
total packets flying around your network, reducing total latency, since
your app doesn't have to wait for each round-trip of L{set} before sending
the next one.
@param mapping: A dict of key/value pairs to set.
@param time: Tells memcached the time which this value should expire, either
as a delta number of seconds, or an absolute unix time-since-the-epoch
value. See the memcached protocol docs section "Storage Commands"
for more info on <exptime>. We default to 0 == cache forever.
@param key_prefix: Optional string to prepend to each key when sending to memcache. Allows you to efficiently stuff these keys into a pseudo-namespace in memcache:
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}, key_prefix='subspace_')
>>> len(notset_keys) == 0
True
>>> mc.get_multi(['subspace_key1', 'subspace_key2']) == {'subspace_key1' : 'val1', 'subspace_key2' : 'val2'}
True
Causes key 'subspace_key1' and 'subspace_key2' to be set. Useful in conjunction with a higher-level layer which applies namespaces to data in memcache.
In this case, the return result would be the list of notset original keys, prefix not applied.
@param min_compress_len: The threshold length to kick in auto-compression
of the value using the zlib.compress() routine. If the value being cached is
a string, then the length of the string is measured, else if the value is an
object, then the length of the pickle result is measured. If the resulting
attempt at compression yeilds a larger string than the input, then it is
discarded. For backwards compatability, this parameter defaults to 0,
indicating don't ever try to compress.
@return: List of keys which failed to be stored [ memcache out of memory, etc. ].
@rtype: list
'''
self._statlog('set_multi')
server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(mapping.iterkeys(), key_prefix)
# send out all requests on each server before reading anything
dead_servers = []
notstored = [] # original keys.
for server in server_keys.iterkeys():
bigcmd = []
write = bigcmd.append
try:
for key in server_keys[server]: # These are mangled keys
store_info = self._val_to_store_info(
mapping[prefixed_to_orig_key[key]],
min_compress_len)
if store_info:
write("set %s %d %d %d\r\n%s\r\n" % (key, store_info[0],
time, store_info[1], store_info[2]))
else:
notstored.append(prefixed_to_orig_key[key])
server.send_cmds(''.join(bigcmd))
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
dead_servers.append(server)
# if any servers died on the way, don't expect them to respond.
for server in dead_servers:
del server_keys[server]
# short-circuit if there are no servers, just return all keys
if not server_keys: return(mapping.keys())
for server, keys in server_keys.iteritems():
try:
for key in keys:
line = server.readline()
if line == 'STORED':
continue
else:
notstored.append(prefixed_to_orig_key[key]) #un-mangle.
except (_Error, socket.error), msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return notstored
def _val_to_store_info(self, val, min_compress_len):
"""
Transform val to a storable representation, returning a tuple of the flags, the length of the new value, and the new value itself.
"""
flags = 0
if isinstance(val, str):
pass
elif isinstance(val, int):
flags |= Client._FLAG_INTEGER
val = "%d" % val
# force no attempt to compress this silly string.
min_compress_len = 0
elif isinstance(val, long):
flags |= Client._FLAG_LONG
val = "%d" % val
# force no attempt to compress this silly string.
min_compress_len = 0
else:
flags |= Client._FLAG_PICKLE
file = StringIO()
if self.picklerIsKeyword:
pickler = self.pickler(file, protocol = self.pickleProtocol)
else:
pickler = self.pickler(file, self.pickleProtocol)
if self.persistent_id:
pickler.persistent_id = self.persistent_id
pickler.dump(val)
val = file.getvalue()
lv = len(val)
# We should try to compress if min_compress_len > 0 and we could
# import zlib and this string is longer than our min threshold.
if min_compress_len and _supports_compress and lv > min_compress_len:
comp_val = compress(val)
# Only retain the result if the compression result is smaller
# than the original.
if len(comp_val) < lv:
flags |= Client._FLAG_COMPRESSED
val = comp_val
# silently do not store if value length exceeds maximum
if self.server_max_value_length != 0 and \
len(val) > self.server_max_value_length: return(0)
return (flags, len(val), val)
def _set(self, cmd, key, val, time, min_compress_len = 0):
self.check_key(key)
server, key = self._get_server(key)
if not server:
return 0
def _unsafe_set():
self._statlog(cmd)
store_info = self._val_to_store_info(val, min_compress_len)
if not store_info: return(0)
if cmd == 'cas':
if key not in self.cas_ids:
return self._set('set', key, val, time, min_compress_len)
fullcmd = "%s %s %d %d %d %d\r\n%s" % (
cmd, key, store_info[0], time, store_info[1],
self.cas_ids[key], store_info[2])
else:
fullcmd = "%s %s %d %d %d\r\n%s" % (
cmd, key, store_info[0], time, store_info[1], store_info[2])
try:
server.send_cmd(fullcmd)
return(server.expect("STORED") == "STORED")
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return 0
try:
return _unsafe_set()
except _ConnectionDeadError:
# retry once
try:
server._get_socket()
return _unsafe_set()
except (_ConnectionDeadError, socket.error), msg:
server.mark_dead(msg)
return 0
def _get(self, cmd, key):
self.check_key(key)
server, key = self._get_server(key)
if not server:
return None
def _unsafe_get():
self._statlog(cmd)
try:
server.send_cmd("%s %s" % (cmd, key))
rkey = flags = rlen = cas_id = None
if cmd == 'gets':
rkey, flags, rlen, cas_id, = self._expect_cas_value(server)
if rkey and self.cache_cas:
self.cas_ids[rkey] = cas_id
else:
rkey, flags, rlen, = self._expectvalue(server)
if not rkey:
return None
try:
value = self._recv_value(server, flags, rlen)
finally:
server.expect("END")
except (_Error, socket.error), msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return None
return value
try:
return _unsafe_get()
except _ConnectionDeadError:
# retry once
try:
if server.connect():
return _unsafe_get()
return None
except (_ConnectionDeadError, socket.error), msg:
server.mark_dead(msg)
return None
def get(self, key):
'''Retrieves a key from the memcache.
@return: The value or None.
'''
return self._get('get', key)
def gets(self, key):
'''Retrieves a key from the memcache. Used in conjunction with 'cas'.
@return: The value or None.
'''
return self._get('gets', key)
def get_multi(self, keys, key_prefix=''):
'''
Retrieves multiple keys from the memcache doing just one query.
>>> success = mc.set("foo", "bar")
>>> success = mc.set("baz", 42)
>>> mc.get_multi(["foo", "baz", "foobar"]) == {"foo": "bar", "baz": 42}
1
>>> mc.set_multi({'k1' : 1, 'k2' : 2}, key_prefix='pfx_') == []
1
This looks up keys 'pfx_k1', 'pfx_k2', ... . Returned dict will just have unprefixed keys 'k1', 'k2'.
>>> mc.get_multi(['k1', 'k2', 'nonexist'], key_prefix='pfx_') == {'k1' : 1, 'k2' : 2}
1
get_mult [ and L{set_multi} ] can take str()-ables like ints / longs as keys too. Such as your db pri key fields.
They're rotored through str() before being passed off to memcache, with or without the use of a key_prefix.
In this mode, the key_prefix could be a table name, and the key itself a db primary key number.
>>> mc.set_multi({42: 'douglass adams', 46 : 'and 2 just ahead of me'}, key_prefix='numkeys_') == []
1
>>> mc.get_multi([46, 42], key_prefix='numkeys_') == {42: 'douglass adams', 46 : 'and 2 just ahead of me'}
1
This method is recommended over regular L{get} as it lowers the number of
total packets flying around your network, reducing total latency, since
your app doesn't have to wait for each round-trip of L{get} before sending
the next one.
See also L{set_multi}.
@param keys: An array of keys.
@param key_prefix: A string to prefix each key when we communicate with memcache.
Facilitates pseudo-namespaces within memcache. Returned dictionary keys will not have this prefix.
@return: A dictionary of key/value pairs that were available. If key_prefix was provided, the keys in the retured dictionary will not have it present.
'''
self._statlog('get_multi')
server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(keys, key_prefix)
# send out all requests on each server before reading anything
dead_servers = []
for server in server_keys.iterkeys():
try:
server.send_cmd("get %s" % " ".join(server_keys[server]))
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
dead_servers.append(server)
# if any servers died on the way, don't expect them to respond.
for server in dead_servers:
del server_keys[server]
retvals = {}
for server in server_keys.iterkeys():
try:
line = server.readline()
while line and line != 'END':
rkey, flags, rlen = self._expectvalue(server, line)
# Bo Yang reports that this can sometimes be None
if rkey is not None:
val = self._recv_value(server, flags, rlen)
retvals[prefixed_to_orig_key[rkey]] = val # un-prefix returned key.
line = server.readline()
except (_Error, socket.error), msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return retvals
def _expect_cas_value(self, server, line=None):
if not line:
line = server.readline()
if line and line[:5] == 'VALUE':
resp, rkey, flags, len, cas_id = line.split()
return (rkey, int(flags), int(len), int(cas_id))
else:
return (None, None, None, None)
def _expectvalue(self, server, line=None):
if not line:
line = server.readline()
if line and line[:5] == 'VALUE':
resp, rkey, flags, len = line.split()
flags = int(flags)
rlen = int(len)
return (rkey, flags, rlen)
else:
return (None, None, None)
def _recv_value(self, server, flags, rlen):
rlen += 2 # include \r\n
buf = server.recv(rlen)
if len(buf) != rlen:
raise _Error("received %d bytes when expecting %d"
% (len(buf), rlen))
if len(buf) == rlen:
buf = buf[:-2] # strip \r\n
if flags & Client._FLAG_COMPRESSED:
buf = decompress(buf)
if flags == 0 or flags == Client._FLAG_COMPRESSED:
# Either a bare string or a compressed string now decompressed...
val = buf
elif flags & Client._FLAG_INTEGER:
val = int(buf)
elif flags & Client._FLAG_LONG:
val = long(buf)
elif flags & Client._FLAG_PICKLE:
try:
file = StringIO(buf)
unpickler = self.unpickler(file)
if self.persistent_load:
unpickler.persistent_load = self.persistent_load
val = unpickler.load()
except Exception, e:
self.debuglog('Pickle error: %s\n' % e)
return None
else:
self.debuglog("unknown flags on get: %x\n" % flags)
return val
def check_key(self, key, key_extra_len=0):
"""Checks sanity of key. Fails if:
Key length is > SERVER_MAX_KEY_LENGTH (Raises MemcachedKeyLength).
Contains control characters (Raises MemcachedKeyCharacterError).
Is not a string (Raises MemcachedStringEncodingError)
Is an unicode string (Raises MemcachedStringEncodingError)
Is not a string (Raises MemcachedKeyError)
Is None (Raises MemcachedKeyError)
"""
if isinstance(key, tuple): key = key[1]
if not key:
raise Client.MemcachedKeyNoneError("Key is None")
if isinstance(key, unicode):
raise Client.MemcachedStringEncodingError(
"Keys must be str()'s, not unicode. Convert your unicode "
"strings using mystring.encode(charset)!")
if not isinstance(key, str):
raise Client.MemcachedKeyTypeError("Key must be str()'s")
if isinstance(key, basestring):
if self.server_max_key_length != 0 and \
len(key) + key_extra_len > self.server_max_key_length:
raise Client.MemcachedKeyLengthError("Key length is > %s"
% self.server_max_key_length)
for char in key:
if ord(char) < 33 or ord(char) == 127:
raise Client.MemcachedKeyCharacterError(
"Control characters not allowed")
class _Host(object):
def __init__(self, host, debug=0, dead_retry=_DEAD_RETRY,
socket_timeout=_SOCKET_TIMEOUT):
self.dead_retry = dead_retry
self.socket_timeout = socket_timeout
self.debug = debug
if isinstance(host, tuple):
host, self.weight = host
else:
self.weight = 1
# parse the connection string
m = re.match(r'^(?P<proto>unix):(?P<path>.*)$', host)
if not m:
m = re.match(r'^(?P<proto>inet):'
r'(?P<host>[^:]+)(:(?P<port>[0-9]+))?$', host)
if not m: m = re.match(r'^(?P<host>[^:]+)(:(?P<port>[0-9]+))?$', host)
if not m:
raise ValueError('Unable to parse connection string: "%s"' % host)
hostData = m.groupdict()
if hostData.get('proto') == 'unix':
self.family = socket.AF_UNIX
self.address = hostData['path']
else:
self.family = socket.AF_INET
self.ip = hostData['host']
self.port = int(hostData.get('port', 11211))
self.address = ( self.ip, self.port )
self.deaduntil = 0
self.socket = None
self.buffer = ''
def debuglog(self, str):
if self.debug:
sys.stderr.write("MemCached: %s\n" % str)
def _check_dead(self):
if self.deaduntil and self.deaduntil > time.time():
return 1
self.deaduntil = 0
return 0
def connect(self):
if self._get_socket():
return 1
return 0
def mark_dead(self, reason):
self.debuglog("MemCache: %s: %s. Marking dead." % (self, reason))
self.deaduntil = time.time() + self.dead_retry
self.close_socket()
def _get_socket(self):
if self._check_dead():
return None
if self.socket:
return self.socket
s = socket.socket(self.family, socket.SOCK_STREAM)
if hasattr(s, 'settimeout'): s.settimeout(self.socket_timeout)
try:
s.connect(self.address)
except socket.timeout, msg:
self.mark_dead("connect: %s" % msg)
return None
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
self.mark_dead("connect: %s" % msg[1])
return None
self.socket = s
self.buffer = ''
return s
def close_socket(self):
if self.socket:
self.socket.close()
self.socket = None
def send_cmd(self, cmd):
self.socket.sendall(cmd + '\r\n')
def send_cmds(self, cmds):
""" cmds already has trailing \r\n's applied """
self.socket.sendall(cmds)
def readline(self):
buf = self.buffer
recv = self.socket.recv
while True:
index = buf.find('\r\n')
if index >= 0:
break
data = recv(4096)
if not data:
# connection close, let's kill it and raise
self.close_socket()
raise _ConnectionDeadError()
buf += data
self.buffer = buf[index+2:]
return buf[:index]
def expect(self, text):
line = self.readline()
if line != text:
self.debuglog("while expecting '%s', got unexpected response '%s'"
% (text, line))
return line
def recv(self, rlen):
self_socket_recv = self.socket.recv
buf = self.buffer
while len(buf) < rlen:
foo = self_socket_recv(max(rlen - len(buf), 4096))
buf += foo
if not foo:
raise _Error( 'Read %d bytes, expecting %d, '
'read returned 0 length bytes' % ( len(buf), rlen ))
self.buffer = buf[rlen:]
return buf[:rlen]
def __str__(self):
d = ''
if self.deaduntil:
d = " (dead until %d)" % self.deaduntil
if self.family == socket.AF_INET:
return "inet:%s:%d%s" % (self.address[0], self.address[1], d)
else:
return "unix:%s%s" % (self.address, d)
def _doctest():
import doctest, memcache
servers = ["127.0.0.1:11211"]
mc = Client(servers, debug=1)
globs = {"mc": mc}
return doctest.testmod(memcache, globs=globs)
if __name__ == "__main__":
failures = 0
print "Testing docstrings..."
_doctest()
print "Running tests:"
print
serverList = [["127.0.0.1:11211"]]
if '--do-unix' in sys.argv:
serverList.append([os.path.join(os.getcwd(), 'memcached.socket')])
for servers in serverList:
mc = Client(servers, debug=1)
def to_s(val):
if not isinstance(val, basestring):
return "%s (%s)" % (val, type(val))
return "%s" % val
def test_setget(key, val):
global failures
print "Testing set/get {'%s': %s} ..." % (to_s(key), to_s(val)),
mc.set(key, val)
newval = mc.get(key)
if newval == val:
print "OK"
return 1
else:
print "FAIL"; failures = failures + 1
return 0
class FooStruct(object):
def __init__(self):
self.bar = "baz"
def __str__(self):
return "A FooStruct"
def __eq__(self, other):
if isinstance(other, FooStruct):
return self.bar == other.bar
return 0
test_setget("a_string", "some random string")
test_setget("an_integer", 42)
if test_setget("long", long(1<<30)):
print "Testing delete ...",
if mc.delete("long"):
print "OK"
else:
print "FAIL"; failures = failures + 1
print "Checking results of delete ..."
if mc.get("long") == None:
print "OK"
else:
print "FAIL"; failures = failures + 1
print "Testing get_multi ...",
print mc.get_multi(["a_string", "an_integer"])
# removed from the protocol
#if test_setget("timed_delete", 'foo'):
# print "Testing timed delete ...",
# if mc.delete("timed_delete", 1):
# print "OK"
# else:
# print "FAIL"; failures = failures + 1
# print "Checking results of timed delete ..."
# if mc.get("timed_delete") == None:
# print "OK"
# else:
# print "FAIL"; failures = failures + 1
print "Testing get(unknown value) ...",
print to_s(mc.get("unknown_value"))
f = FooStruct()
test_setget("foostruct", f)
print "Testing incr ...",
x = mc.incr("an_integer", 1)
if x == 43:
print "OK"
else:
print "FAIL"; failures = failures + 1
print "Testing decr ...",
x = mc.decr("an_integer", 1)
if x == 42:
print "OK"
else:
print "FAIL"; failures = failures + 1
sys.stdout.flush()
# sanity tests
print "Testing sending spaces...",
sys.stdout.flush()
try:
x = mc.set("this has spaces", 1)
except Client.MemcachedKeyCharacterError, msg:
print "OK"
else:
print "FAIL"; failures = failures + 1
print "Testing sending control characters...",
try:
x = mc.set("this\x10has\x11control characters\x02", 1)
except Client.MemcachedKeyCharacterError, msg:
print "OK"
else:
print "FAIL"; failures = failures + 1
print "Testing using insanely long key...",
try:
x = mc.set('a'*SERVER_MAX_KEY_LENGTH, 1)
except Client.MemcachedKeyLengthError, msg:
print "FAIL"; failures = failures + 1
else:
print "OK"
try:
x = mc.set('a'*SERVER_MAX_KEY_LENGTH + 'a', 1)
except Client.MemcachedKeyLengthError, msg:
print "OK"
else:
print "FAIL"; failures = failures + 1
print "Testing sending a unicode-string key...",
try:
x = mc.set(u'keyhere', 1)
except Client.MemcachedStringEncodingError, msg:
print "OK",
else:
print "FAIL",; failures = failures + 1
try:
x = mc.set((u'a'*SERVER_MAX_KEY_LENGTH).encode('utf-8'), 1)
except:
print "FAIL",; failures = failures + 1
else:
print "OK",
import pickle
s = pickle.loads('V\\u4f1a\np0\n.')
try:
x = mc.set((s*SERVER_MAX_KEY_LENGTH).encode('utf-8'), 1)
except Client.MemcachedKeyLengthError:
print "OK"
else:
print "FAIL"; failures = failures + 1
print "Testing using a value larger than the memcached value limit...",
x = mc.set('keyhere', 'a'*SERVER_MAX_VALUE_LENGTH)
if mc.get('keyhere') == None:
print "OK",
else:
print "FAIL",; failures = failures + 1
x = mc.set('keyhere', 'a'*SERVER_MAX_VALUE_LENGTH + 'aaa')
if mc.get('keyhere') == None:
print "OK"
else:
print "FAIL"; failures = failures + 1
print "Testing set_multi() with no memcacheds running",
mc.disconnect_all()
errors = mc.set_multi({'keyhere' : 'a', 'keythere' : 'b'})
if errors != []:
print "FAIL"; failures = failures + 1
else:
print "OK"
print "Testing delete_multi() with no memcacheds running",
mc.disconnect_all()
ret = mc.delete_multi({'keyhere' : 'a', 'keythere' : 'b'})
if ret != 1:
print "FAIL"; failures = failures + 1
else:
print "OK"
if failures > 0:
print '*** THERE WERE FAILED TESTS'
sys.exit(1)
sys.exit(0)
# vim: ts=4 sw=4 et :
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import web
from framework import WebError
import urls
__author__ = 'Michael Liao'
class PageHandler(object):
def __init__(self):
self.mapping = {}
for s in dir(urls):
f = getattr(urls, s)
if callable(f) and getattr(f, 'handler', False):
self.mapping[getattr(f, '__name__', '')] = f
def GET(self, path):
logging.info('GET /%s' % path)
if path=='':
path = 'index'
return self._handle(path)
def POST(self, path):
logging.info('POST /%s' % path)
return self._handle(path)
def _handle(self, path):
f = self.mapping.get(path, None)
if f is None:
raise web.notfound()
web.header('Content-Type', 'text/html;charset=utf-8')
try:
return f()
except WebError, e:
return e.message
except BaseException, e:
raise
app = web.application(('/(.*)', 'PageHandler'), globals())
if __name__ == "__main__":
app.run()
else:
import sae
application = sae.create_wsgi_app(app.wsgifunc())
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '1.04'
__author__ = 'Liao Xuefeng (askxuefeng@gmail.com)'
'''
Python client SDK for sina weibo API using OAuth 2.
'''
try:
import json
except ImportError:
import simplejson as json
import time
import urllib
import urllib2
import logging
def _obj_hook(pairs):
'''
convert json object to python object.
'''
o = JsonObject()
for k, v in pairs.iteritems():
o[str(k)] = v
return o
class APIError(StandardError):
'''
raise APIError if got failed json message.
'''
def __init__(self, error_code, error, request):
self.error_code = error_code
self.error = error
self.request = request
StandardError.__init__(self, error)
def __str__(self):
return 'APIError: %s: %s, request: %s' % (self.error_code, self.error, self.request)
class JsonObject(dict):
'''
general json object that can bind any fields but also act as a dict.
'''
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
def _encode_params(**kw):
'''
Encode parameters.
'''
args = []
for k, v in kw.iteritems():
qv = v.encode('utf-8') if isinstance(v, unicode) else str(v)
args.append('%s=%s' % (k, urllib.quote(qv)))
return '&'.join(args)
def _encode_multipart(**kw):
'''
Build a multipart/form-data body with generated random boundary.
'''
boundary = '----------%s' % hex(int(time.time() * 1000))
data = []
for k, v in kw.iteritems():
data.append('--%s' % boundary)
if hasattr(v, 'read'):
# file-like object:
ext = ''
filename = getattr(v, 'name', '')
n = filename.rfind('.')
if n != (-1):
ext = filename[n:].lower()
content = v.read()
data.append('Content-Disposition: form-data; name="%s"; filename="hidden"' % k)
data.append('Content-Length: %d' % len(content))
data.append('Content-Type: %s\r\n' % _guess_content_type(ext))
data.append(content)
else:
data.append('Content-Disposition: form-data; name="%s"\r\n' % k)
data.append(v.encode('utf-8') if isinstance(v, unicode) else v)
data.append('--%s--\r\n' % boundary)
return '\r\n'.join(data), boundary
_CONTENT_TYPES = { '.png': 'image/png', '.gif': 'image/gif', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.jpe': 'image/jpeg' }
def _guess_content_type(ext):
return _CONTENT_TYPES.get(ext, 'application/octet-stream')
_HTTP_GET = 0
_HTTP_POST = 1
_HTTP_UPLOAD = 2
def _http_get(url, authorization=None, **kw):
logging.info('GET %s' % url)
return _http_call(url, _HTTP_GET, authorization, **kw)
def _http_post(url, authorization=None, **kw):
logging.info('POST %s' % url)
return _http_call(url, _HTTP_POST, authorization, **kw)
def _http_upload(url, authorization=None, **kw):
logging.info('MULTIPART POST %s' % url)
return _http_call(url, _HTTP_UPLOAD, authorization, **kw)
def _http_call(url, method, authorization, **kw):
'''
send an http request and expect to return a json object if no error.
'''
params = None
boundary = None
if method==_HTTP_UPLOAD:
params, boundary = _encode_multipart(**kw)
else:
params = _encode_params(**kw)
http_url = '%s?%s' % (url, params) if method==_HTTP_GET else url
http_body = None if method==_HTTP_GET else params
req = urllib2.Request(http_url, data=http_body)
if authorization:
req.add_header('Authorization', 'OAuth2 %s' % authorization)
if boundary:
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
resp = urllib2.urlopen(req)
body = resp.read()
r = json.loads(body, object_hook=_obj_hook)
if hasattr(r, 'error_code'):
raise APIError(r.error_code, getattr(r, 'error', ''), getattr(r, 'request', ''))
return r
class HttpObject(object):
def __init__(self, client, method):
self.client = client
self.method = method
def __getattr__(self, attr):
def wrap(**kw):
if self.client.is_expires():
raise APIError('21327', 'expired_token', attr)
return _http_call('%s%s.json' % (self.client.api_url, attr.replace('__', '/')), self.method, self.client.access_token, **kw)
return wrap
class APIClient(object):
'''
API client using synchronized invocation.
'''
def __init__(self, app_key, app_secret, redirect_uri=None, response_type='code', domain='api.weibo.com', version='2'):
self.client_id = app_key
self.client_secret = app_secret
self.redirect_uri = redirect_uri
self.response_type = response_type
self.auth_url = 'https://%s/oauth2/' % domain
self.api_url = 'https://%s/%s/' % (domain, version)
self.access_token = None
self.expires = 0.0
self.get = HttpObject(self, _HTTP_GET)
self.post = HttpObject(self, _HTTP_POST)
self.upload = HttpObject(self, _HTTP_UPLOAD)
def set_access_token(self, access_token, expires_in):
self.access_token = str(access_token)
self.expires = float(expires_in)
def get_authorize_url(self, redirect_uri=None, display='default'):
'''
return the authroize url that should be redirect.
'''
redirect = redirect_uri if redirect_uri else self.redirect_uri
if not redirect:
raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
return '%s%s?%s' % (self.auth_url, 'authorize', \
_encode_params(client_id = self.client_id, \
response_type = 'code', \
display = display, \
redirect_uri = redirect))
def request_access_token(self, code, redirect_uri=None):
'''
return access token as object: {"access_token":"your-access-token","expires_in":12345678}, expires_in is standard unix-epoch-time
'''
redirect = redirect_uri if redirect_uri else self.redirect_uri
if not redirect:
raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
r = _http_post('%s%s' % (self.auth_url, 'access_token'), \
client_id = self.client_id, \
client_secret = self.client_secret, \
redirect_uri = redirect, \
code = code, grant_type = 'authorization_code')
r.expires_in += int(time.time())
return r
def is_expires(self):
return not self.access_token or time.time() > self.expires
def __getattr__(self, attr):
return getattr(self.get, attr)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import web
from framework import WebError
import urls
__author__ = 'Michael Liao'
class PageHandler(object):
def __init__(self):
self.mapping = {}
for s in dir(urls):
f = getattr(urls, s)
if callable(f) and getattr(f, 'handler', False):
self.mapping[getattr(f, '__name__', '')] = f
def GET(self, path):
logging.info('GET /%s' % path)
if path=='':
path = 'index'
return self._handle(path)
def POST(self, path):
logging.info('POST /%s' % path)
return self._handle(path)
def _handle(self, path):
f = self.mapping.get(path, None)
if f is None:
raise web.notfound()
web.header('Content-Type', 'text/html;charset=utf-8')
try:
return f()
except WebError, e:
return e.message
except BaseException, e:
raise
app = web.application(('/(.*)', 'PageHandler'), globals())
if __name__ == "__main__":
app.run()
else:
import sae
application = sae.create_wsgi_app(app.wsgifunc())
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao'
import json
import time
from datetime import date
from datetime import datetime
from datetime import timedelta
import urllib2
import hashlib
import logging
import web
from weibo import APIClient
from framework import handler
from framework import odict
from framework import cache
from framework import db
try:
from configdemo import APP_KEY, APP_SECRET
except ImportError:
from config import APP_KEY, APP_SECRET
_CALLBACK_URL = 'http://sinaweibopy.sinaapp.com/callback'
_DAYS = [u'星期一', u'星期二', u'星期三', u'星期四', u'星期五', u'星期六', u'星期日']
_DEFAULT_CITY = u'2151330'
# key: english name, value: [yahoo weather code, chinese name, weibo picture name]
_WEATHER_CODES = {
u'tornado' : [0, u'龙卷风', u'[龙卷风]'],
u'tropical storm' : [1, u'热带风暴', u''],
u'hurricane' : [2, u'飓风', u''],
u'severe thunderstorms' : [3, u'风暴', u''],
u'thunderstorms' : [4, u'雷雨', u'[闪电]'],
u'mixed rain and snow' : [5, u'雨夹雪', u'[雪]'],
u'mixed rain and sleet' : [6, u'雨夹冰雹', u'[冰雹]'],
u'mixed snow and sleet' : [7, u'雪夹冰雹', u'[冰雹]'],
u'freezing drizzle' : [8, u'冰毛毛雨', u'[下雨]'],
u'drizzle' : [9, u'毛毛雨', u'[下雨]'],
u'freezing rain' : [10, u'冰雨', u'[下雨]'],
u'showers' : [11, u'阵雨', u'[下雨]'],
u'showers' : [12, u'阵雨', u'[下雨]'],
u'snow flurries' : [13, u'小雪', u'[雪]'],
u'light snow showers' : [14, u'小雨雪', u'[雪]'],
u'blowing snow' : [15, u'风雪', u'[雪]'],
u'snow' : [16, u'下雪', u'[雪]'],
u'hail' : [17, u'冰雹', u'[冰雹]'],
u'sleet' : [18, u'雨夹雪', u'[雪]'],
u'dust' : [19, u'尘土', u'[沙尘暴]'],
u'foggy' : [20, u'雾', u'[雾]'],
u'haze' : [21, u'霾', u'[雾]'],
u'smoky' : [22, u'烟雾', u'[雾]'],
u'blustery' : [23, u'狂风', u'[风]'],
u'windy' : [24, u'大风', u'[风]'],
u'cold' : [25, u'寒冷', u''],
u'cloudy' : [26, u'多云', u'[阴天]'],
u'mostly cloudy (night)' : [27, u'多云', u'[阴天]'],
u'mostly cloudy (day)' : [28, u'多云', u'[阴天]'],
u'mostly cloudy' : [28, u'多云', u'[阴天]'],
u'partly cloudy (night)' : [29, u'局部多云', u'[阴天]'],
u'partly cloudy (day)' : [30, u'局部多云', u'[阴天]'],
u'partly cloudy' : [30, u'局部多云', u'[阴天]'],
u'clear (night)' : [31, u'晴朗', u'[阳光]'],
u'clear' : [31, u'晴朗', u'[阳光]'],
u'sunny' : [32, u'晴', u'[阳光]'],
u'fair (night)' : [33, u'晴朗', u'[阳光]'],
u'fair (day)' : [34, u'晴朗', u'[阳光]'],
u'fair' : [34, u'晴朗', u'[阳光]'],
u'mixed rain and hail' : [35, u'雨夹冰雹', u'[冰雹]'],
u'hot' : [36, u'炎热', u'[阳光]'],
u'isolated thunderstorms' : [37, u'局部雷雨', u'[闪电]'],
u'scattered thunderstorms' : [38, u'零星雷雨', u'[闪电]'],
u'scattered thunderstorms' : [39, u'零星雷雨', u'[闪电]'],
u'scattered showers' : [40, u'零星阵雨', u'[下雨]'],
u'heavy snow' : [41, u'大雪', u'[雪]'],
u'scattered snow showers' : [42, u'零星雨夹雪', '[雪]'],
u'heavy snow' : [43, u'大雪', u'[雪]'],
# u'partly cloudy' : [44, u'局部多云', u''],
u'thundershowers' : [45, u'雷阵雨', u'[闪电]'],
u'snow showers' : [46, u'小雪', u'[雪]'],
u'isolated thundershowers' : [47, u'局部雷雨', u'[闪电]'],
u'not available' : [3200, u'暂无数据', u'']
}
def _get_day(d):
return [u'%s-%s-%s' % (d.year, d.month, d.day), _DAYS[d.weekday()]]
def _get_today():
return _get_day(date.today())
def _get_tomorrow():
return _get_day(date.today() + timedelta(days=1))
def _get_cities():
L = list(db.select('city', order='alias'))
city_list = []
w_dict = dict()
y_dict = dict()
for c in L:
oc = odict(name=c.name, alias=c.alias, yahoo_code=c.yahoo_code, weibo_code=c.weibo_code)
city_list.append(oc)
w_dict[oc.weibo_code] = oc.yahoo_code
y_dict[oc.yahoo_code] = oc.weibo_code
return (city_list, w_dict, y_dict)
def _make_cookie(uid, access_token):
s = u'%s:%s' % (uid, access_token)
return '%s:%s' % (uid, hashlib.md5(str(s)).hexdigest())
def _extract_cookie(cookie_str):
if cookie_str:
ss = cookie_str.split(u':')
if len(ss)==2:
return ss[0], ss[1]
return None, None
def _get_user_from_cookie():
uid, hash = _extract_cookie(web.cookies().get('weibouser'))
if not uid:
logging.info('no cookie found.')
return None
users = list(db.select('user', where='uid=$uid', vars=dict(uid=uid)))
if not users:
logging.info('no such user: %s' % uid)
return None
u = users[0]
if hashlib.md5(str(u'%s:%s' % (uid, u.access_token))).hexdigest()!=hash:
logging.info('user found, but hash not match.')
return None
return u
@handler('GET')
def index():
user = _get_user_from_cookie()
city = web.input().get('city', None)
logging.info('get city from url: %s' % city)
cities, wdict, ydict = _get_cities()
if city not in ydict:
city = None
logging.info('invalid city from url.')
if user and not city:
# guess city:
pcode = u'001%03d' % int(user.province_code)
ycode = wdict.get(pcode, None)
if not ycode:
pcode = u'001%03d%03d' % (int(user.province_code), int(user.city_code))
ycode = wdict.get(pcode, None)
if ycode:
city = ycode
logging.info('locate user to city: %s' % city)
if not city:
city = _DEFAULT_CITY
logging.info('set to default city.')
return dict(user=user, city=city, cities=cities, today=_get_today(), tomorrow=_get_tomorrow())
@handler('GET')
def login():
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET)
raise web.found(client.get_authorize_url(_CALLBACK_URL))
@handler('GET')
def logout():
web.setcookie('weibouser', 'x', expires=-1)
raise web.found('/index')
@handler('GET')
def callback():
i = web.input()
code = i.get('code', None)
if code:
# /callback?code=xxx
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET)
token = client.request_access_token(code, _CALLBACK_URL)
logging.info('got access token: %s' % str(token))
uid = token.uid
kw = dict(access_token=token.access_token, expires_in=token.expires_in)
# check for update:
if 0==db.update('user', where='uid=$uid', vars=dict(uid=uid), **kw):
# create user:
client.set_access_token(token.access_token, token.expires_in)
user = client.get.users__show(uid=uid)
kw['uid'] = uid
kw['name'] = user.screen_name
kw['gender'] = user.gender
kw['province_code'] = user.province
kw['city_code'] = user.city
kw['image_url'] = user.profile_image_url
db.insert('user', **kw)
# make a cookie:
web.setcookie('weibouser', _make_cookie(uid, token.access_token), int(token.expires_in - time.time()))
raise web.found('/index')
def _get_weather_code(eng_code):
key = eng_code.lower()
while True:
value = _WEATHER_CODES.get(key, None)
if value:
return value
if key.startswith(u'mostly '):
key = key[7:]
elif key.startswith(u'pm '):
key = key[3:]
else:
return [3200, eng_code, u'']
def _get_weather(city):
if not city:
return r'{"code":"500","Message":"Missing Input: city"}'
data = cache.get('city-%s' % city)
if data:
logging.info('got data from cache')
web.header('X-Cache', 'Hit from cache')
return data
# check city:
cities = list(db.select('city', where='yahoo_code=$code', vars=dict(code=city)))
if not cities:
return r'{"code":"500","Message":"Invalid Input: city"}'
c = cities[0]
w = c.yahoo_code
logging.info('fetch from yahoo weather...')
url = 'http://weather.yahooapis.com/forecastjson?w=%s&u=c' % w
resp = urllib2.urlopen(url)
if resp.code==200:
logging.info('begin fetch...')
data = json.loads(resp.read())
data['city'] = c.name
cond = data['forecast'][0]['condition']
codes = _get_weather_code(cond)
data['forecast'][0]['code'] = codes[0]
data['forecast'][0]['condition'] = codes[1]
data['forecast'][0]['image'] = codes[2]
cond = data['forecast'][1]['condition']
codes = _get_weather_code(cond)
data['forecast'][1]['code'] = codes[0]
data['forecast'][1]['condition'] = codes[1]
data['forecast'][1]['image'] = codes[2]
# cache it, but first calculate expires time:
now = datetime.now()
t = datetime(now.year, now.month, now.day)
delta = now - t
exp = 86400 - delta.seconds # makes it expires in midnight (24:00)
if exp > 3600:
exp = 3600
logging.info('fetched and cache for %d seconds.' % exp)
json_data = json.dumps(data)
cache.set('city-%s' % city, json_data, exp)
web.header('X-Cache', 'Miss from cache')
return json_data
return None
@handler('GET', False)
def weather():
i = web.input()
web.header('Content-Type', 'application/json')
city = str(i.get('city', ''))
data = _get_weather(city)
if not data:
logging.info('fetch failed.')
return r'{"code":"500","Message":"Fetch failed"}'
return data
@handler('GET', False)
def share():
user = _get_user_from_cookie()
if not user:
return ur'出错啦!'
i = web.input()
city = str(i.get('city', ''))
data = _get_weather(city)
if not data:
return ur'出错啦!'
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET)
client.set_access_token(user.access_token, user.expires_in)
obj_data = json.loads(data)
fcast = obj_data['forecast'][0]
s = u'%s %s今日%s%s,%d ~ %d度。来自城市天气预报 http://t.cn/SxvH12' % (_get_today()[0], obj_data['city'], fcast['condition'], fcast['image'], int(fcast['low_temperature']), int(fcast['high_temperature']))
client.post.statuses__update(status=s)
return u'''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>城市天气预报分享成功!</title>
<script type="text/javascript">
function jump() { location.assign('http://weibo.com/u/%s'); }
setTimeout('jump()', 3000);
</script>
</head>
<body>
<p>分享成功!3秒后跳转至您的微博首页!<a href="javascript:void(0)" onclick="jump()">立刻跳转</a></p>
</body>
</html>
''' % user.uid
#@handler('GET')
def list_city():
cities = list(db.select('city'))
return dict(cities=cities)
#@handler('POST')
def add_city():
i = web.input()
db.insert('city', name=i.name, alias=i.alias, yahoo_code=i.yahoo_code, weibo_code=i.weibo_code)
raise web.found('/list_city')
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
APP_KEY = 'hidden'
APP_SECRET = 'hidden'
| Python |
# mako/runtime.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""provides runtime services for templates, including Context,
Namespace, and various helper functions."""
from mako import exceptions, util
import __builtin__, inspect, sys
class Context(object):
"""Provides runtime namespace, output buffer, and various
callstacks for templates.
See :ref:`runtime_toplevel` for detail on the usage of
:class:`.Context`.
"""
def __init__(self, buffer, **data):
self._buffer_stack = [buffer]
self._data = data
self._kwargs = data.copy()
self._with_template = None
self._outputting_as_unicode = None
self.namespaces = {}
# "capture" function which proxies to the
# generic "capture" function
self._data['capture'] = util.partial(capture, self)
# "caller" stack used by def calls with content
self.caller_stack = self._data['caller'] = CallerStack()
@property
def lookup(self):
"""Return the :class:`.TemplateLookup` associated
with this :class:`.Context`.
"""
return self._with_template.lookup
@property
def kwargs(self):
"""Return the dictionary of keyword argments associated with this
:class:`.Context`.
"""
return self._kwargs.copy()
def push_caller(self, caller):
"""Pushes a 'caller' callable onto the callstack for
this :class:`.Context`."""
self.caller_stack.append(caller)
def pop_caller(self):
"""Pops a 'caller' callable onto the callstack for this
:class:`.Context`."""
del self.caller_stack[-1]
def keys(self):
"""Return a list of all names established in this :class:`.Context`."""
return self._data.keys()
def __getitem__(self, key):
if key in self._data:
return self._data[key]
else:
return __builtin__.__dict__[key]
def _push_writer(self):
"""push a capturing buffer onto this Context and return
the new writer function."""
buf = util.FastEncodingBuffer()
self._buffer_stack.append(buf)
return buf.write
def _pop_buffer_and_writer(self):
"""pop the most recent capturing buffer from this Context
and return the current writer after the pop.
"""
buf = self._buffer_stack.pop()
return buf, self._buffer_stack[-1].write
def _push_buffer(self):
"""push a capturing buffer onto this Context."""
self._push_writer()
def _pop_buffer(self):
"""pop the most recent capturing buffer from this Context."""
return self._buffer_stack.pop()
def get(self, key, default=None):
"""Return a value from this :class:`.Context`."""
return self._data.get(key,
__builtin__.__dict__.get(key, default)
)
def write(self, string):
"""Write a string to this :class:`.Context` object's
underlying output buffer."""
self._buffer_stack[-1].write(string)
def writer(self):
"""Return the current writer function"""
return self._buffer_stack[-1].write
def _copy(self):
c = Context.__new__(Context)
c._buffer_stack = self._buffer_stack
c._data = self._data.copy()
c._kwargs = self._kwargs
c._with_template = self._with_template
c._outputting_as_unicode = self._outputting_as_unicode
c.namespaces = self.namespaces
c.caller_stack = self.caller_stack
return c
def locals_(self, d):
"""create a new :class:`.Context` with a copy of this
:class:`Context`'s current state, updated with the given dictionary."""
if len(d) == 0:
return self
c = self._copy()
c._data.update(d)
return c
def _clean_inheritance_tokens(self):
"""create a new copy of this :class:`.Context`. with
tokens related to inheritance state removed."""
c = self._copy()
x = c._data
x.pop('self', None)
x.pop('parent', None)
x.pop('next', None)
return c
class CallerStack(list):
def __init__(self):
self.nextcaller = None
def __nonzero__(self):
return self._get_caller() and True or False
def _get_caller(self):
return self[-1]
def __getattr__(self, key):
return getattr(self._get_caller(), key)
def _push_frame(self):
self.append(self.nextcaller or None)
self.nextcaller = None
def _pop_frame(self):
self.nextcaller = self.pop()
class Undefined(object):
"""Represents an undefined value in a template.
All template modules have a constant value
``UNDEFINED`` present which is an instance of this
object.
"""
def __str__(self):
raise NameError("Undefined")
def __nonzero__(self):
return False
UNDEFINED = Undefined()
class _NSAttr(object):
def __init__(self, parent):
self.__parent = parent
def __getattr__(self, key):
ns = self.__parent
while ns:
if hasattr(ns.module, key):
return getattr(ns.module, key)
else:
ns = ns.inherits
raise AttributeError(key)
class Namespace(object):
"""Provides access to collections of rendering methods, which
can be local, from other templates, or from imported modules.
To access a particular rendering method referenced by a
:class:`.Namespace`, use plain attribute access::
${some_namespace.foo(x, y, z)}
:class:`.Namespace` also contains several built-in attributes
described here.
"""
def __init__(self, name, context,
callables=None, inherits=None,
populate_self=True, calling_uri=None):
self.name = name
self.context = context
self.inherits = inherits
if callables is not None:
self.callables = dict([(c.func_name, c) for c in callables])
callables = ()
module = None
"""The Python module referenced by this Namespace.
If the namespace references a :class:`.Template`, then
this module is the equivalent of ``template.module``,
i.e. the generated module for the template.
"""
template = None
"""The :class:`.Template` object referenced by this
:class:`.Namespace`, if any.
"""
context = None
"""The :class:`.Context` object for this namespace.
Namespaces are often created with copies of contexts that
contain slightly different data, particularly in inheritance
scenarios. Using the :class:`.Context` off of a :class:`.Namespace` one
can traverse an entire chain of templates that inherit from
one-another.
"""
filename = None
"""The path of the filesystem file used for this
Namespace's module or template.
If this is a pure module-based
Namespace, this evaluates to ``module.__file__``. If a
template-based namespace, it evaluates to the original
template file location.
"""
uri = None
"""The uri for this Namespace's template.
I.e. whatever was sent to :meth:`.TemplateLookup.get_template()`.
This is the equivalent of :attr:`Template.uri`.
"""
_templateuri = None
@util.memoized_property
def attr(self):
"""Access module level attributes by name.
This accessor allows templates to supply "scalar"
attributes which are particularly handy in inheritance
relationships. See the example in
:ref:`inheritance_toplevel`.
"""
return _NSAttr(self)
def get_namespace(self, uri):
"""Return a :class:`.Namespace` corresponding to the given uri.
If the given uri is a relative uri (i.e. it does not
contain ia leading slash ``/``), the uri is adjusted to
be relative to the uri of the namespace itself. This
method is therefore mostly useful off of the built-in
``local`` namespace, described in :ref:`namespace_local`
In
most cases, a template wouldn't need this function, and
should instead use the ``<%namespace>`` tag to load
namespaces. However, since all ``<%namespace>`` tags are
evaulated before the body of a template ever runs,
this method can be used to locate namespaces using
expressions that were generated within the body code of
the template, or to conditionally use a particular
namespace.
"""
key = (self, uri)
if key in self.context.namespaces:
return self.context.namespaces[key]
else:
ns = TemplateNamespace(uri, self.context._copy(),
templateuri=uri,
calling_uri=self._templateuri)
self.context.namespaces[key] = ns
return ns
def get_template(self, uri):
"""Return a :class:`.Template` from the given uri.
The uri resolution is relative to the uri of this :class:`.Namespace`
object's :class:`.Template`.
"""
return _lookup_template(self.context, uri, self._templateuri)
def get_cached(self, key, **kwargs):
"""Return a value from the :class:`.Cache` referenced by this
:class:`.Namespace` object's :class:`.Template`.
The advantage to this method versus direct access to the
:class:`.Cache` is that the configuration parameters
declared in ``<%page>`` take effect here, thereby calling
up the same configured backend as that configured
by ``<%page>``.
"""
if self.template:
if not self.template.cache_enabled:
createfunc = kwargs.get('createfunc', None)
if createfunc:
return createfunc()
else:
return None
if self.template.cache_dir:
kwargs.setdefault('data_dir', self.template.cache_dir)
if self.template.cache_type:
kwargs.setdefault('type', self.template.cache_type)
if self.template.cache_url:
kwargs.setdefault('url', self.template.cache_url)
return self.cache.get(key, **kwargs)
@property
def cache(self):
"""Return the :class:`.Cache` object referenced
by this :class:`.Namespace` object's
:class:`.Template`.
"""
return self.template.cache
def include_file(self, uri, **kwargs):
"""Include a file at the given uri"""
_include_file(self.context, uri, self._templateuri, **kwargs)
def _populate(self, d, l):
for ident in l:
if ident == '*':
for (k, v) in self._get_star():
d[k] = v
else:
d[ident] = getattr(self, ident)
def _get_star(self):
if self.callables:
for key in self.callables:
yield (key, self.callables[key])
def __getattr__(self, key):
if key in self.callables:
val = self.callables[key]
elif self.inherits:
val = getattr(self.inherits, key)
else:
raise AttributeError(
"Namespace '%s' has no member '%s'" %
(self.name, key))
setattr(self, key, val)
return val
class TemplateNamespace(Namespace):
"""A :class:`.Namespace` specific to a :class:`.Template` instance."""
def __init__(self, name, context, template=None, templateuri=None,
callables=None, inherits=None,
populate_self=True, calling_uri=None):
self.name = name
self.context = context
self.inherits = inherits
if callables is not None:
self.callables = dict([(c.func_name, c) for c in callables])
if templateuri is not None:
self.template = _lookup_template(context, templateuri,
calling_uri)
self._templateuri = self.template.module._template_uri
elif template is not None:
self.template = template
self._templateuri = template.module._template_uri
else:
raise TypeError("'template' argument is required.")
if populate_self:
lclcallable, lclcontext = \
_populate_self_namespace(context, self.template,
self_ns=self)
@property
def module(self):
"""The Python module referenced by this Namespace.
If the namespace references a :class:`.Template`, then
this module is the equivalent of ``template.module``,
i.e. the generated module for the template.
"""
return self.template.module
@property
def filename(self):
"""The path of the filesystem file used for this
Namespace's module or template.
"""
return self.template.filename
@property
def uri(self):
"""The uri for this Namespace's template.
I.e. whatever was sent to :meth:`.TemplateLookup.get_template()`.
This is the equivalent of :attr:`Template.uri`.
"""
return self.template.uri
def _get_star(self):
if self.callables:
for key in self.callables:
yield (key, self.callables[key])
def get(key):
callable_ = self.template._get_def_callable(key)
return util.partial(callable_, self.context)
for k in self.template.module._exports:
yield (k, get(k))
def __getattr__(self, key):
if key in self.callables:
val = self.callables[key]
elif self.template.has_def(key):
callable_ = self.template._get_def_callable(key)
val = util.partial(callable_, self.context)
elif self.inherits:
val = getattr(self.inherits, key)
else:
raise AttributeError(
"Namespace '%s' has no member '%s'" %
(self.name, key))
setattr(self, key, val)
return val
class ModuleNamespace(Namespace):
"""A :class:`.Namespace` specific to a Python module instance."""
def __init__(self, name, context, module,
callables=None, inherits=None,
populate_self=True, calling_uri=None):
self.name = name
self.context = context
self.inherits = inherits
if callables is not None:
self.callables = dict([(c.func_name, c) for c in callables])
mod = __import__(module)
for token in module.split('.')[1:]:
mod = getattr(mod, token)
self.module = mod
@property
def filename(self):
"""The path of the filesystem file used for this
Namespace's module or template.
"""
return self.module.__file__
def _get_star(self):
if self.callables:
for key in self.callables:
yield (key, self.callables[key])
def get(key):
callable_ = getattr(self.module, key)
return util.partial(callable_, self.context)
for k in dir(self.module):
if k[0] != '_':
yield (k, get(k))
def __getattr__(self, key):
if key in self.callables:
val = self.callables[key]
elif hasattr(self.module, key):
callable_ = getattr(self.module, key)
val = util.partial(callable_, self.context)
elif self.inherits:
val = getattr(self.inherits, key)
else:
raise AttributeError(
"Namespace '%s' has no member '%s'" %
(self.name, key))
setattr(self, key, val)
return val
def supports_caller(func):
"""Apply a caller_stack compatibility decorator to a plain
Python function.
See the example in :ref:`namespaces_python_modules`.
"""
def wrap_stackframe(context, *args, **kwargs):
context.caller_stack._push_frame()
try:
return func(context, *args, **kwargs)
finally:
context.caller_stack._pop_frame()
return wrap_stackframe
def capture(context, callable_, *args, **kwargs):
"""Execute the given template def, capturing the output into
a buffer.
See the example in :ref:`namespaces_python_modules`.
"""
if not callable(callable_):
raise exceptions.RuntimeException(
"capture() function expects a callable as "
"its argument (i.e. capture(func, *args, **kwargs))"
)
context._push_buffer()
try:
callable_(*args, **kwargs)
finally:
buf = context._pop_buffer()
return buf.getvalue()
def _decorate_toplevel(fn):
def decorate_render(render_fn):
def go(context, *args, **kw):
def y(*args, **kw):
return render_fn(context, *args, **kw)
try:
y.__name__ = render_fn.__name__[7:]
except TypeError:
# < Python 2.4
pass
return fn(y)(context, *args, **kw)
return go
return decorate_render
def _decorate_inline(context, fn):
def decorate_render(render_fn):
dec = fn(render_fn)
def go(*args, **kw):
return dec(context, *args, **kw)
return go
return decorate_render
def _include_file(context, uri, calling_uri, **kwargs):
"""locate the template from the given uri and include it in
the current output."""
template = _lookup_template(context, uri, calling_uri)
(callable_, ctx) = _populate_self_namespace(
context._clean_inheritance_tokens(),
template)
callable_(ctx, **_kwargs_for_include(callable_, context._data, **kwargs))
def _inherit_from(context, uri, calling_uri):
"""called by the _inherit method in template modules to set
up the inheritance chain at the start of a template's
execution."""
if uri is None:
return None
template = _lookup_template(context, uri, calling_uri)
self_ns = context['self']
ih = self_ns
while ih.inherits is not None:
ih = ih.inherits
lclcontext = context.locals_({'next':ih})
ih.inherits = TemplateNamespace("self:%s" % template.uri,
lclcontext,
template = template,
populate_self=False)
context._data['parent'] = lclcontext._data['local'] = ih.inherits
callable_ = getattr(template.module, '_mako_inherit', None)
if callable_ is not None:
ret = callable_(template, lclcontext)
if ret:
return ret
gen_ns = getattr(template.module, '_mako_generate_namespaces', None)
if gen_ns is not None:
gen_ns(context)
return (template.callable_, lclcontext)
def _lookup_template(context, uri, relativeto):
lookup = context._with_template.lookup
if lookup is None:
raise exceptions.TemplateLookupException(
"Template '%s' has no TemplateLookup associated" %
context._with_template.uri)
uri = lookup.adjust_uri(uri, relativeto)
try:
return lookup.get_template(uri)
except exceptions.TopLevelLookupException, e:
raise exceptions.TemplateLookupException(str(e))
def _populate_self_namespace(context, template, self_ns=None):
if self_ns is None:
self_ns = TemplateNamespace('self:%s' % template.uri,
context, template=template,
populate_self=False)
context._data['self'] = context._data['local'] = self_ns
if hasattr(template.module, '_mako_inherit'):
ret = template.module._mako_inherit(template, context)
if ret:
return ret
return (template.callable_, context)
def _render(template, callable_, args, data, as_unicode=False):
"""create a Context and return the string
output of the given template and template callable."""
if as_unicode:
buf = util.FastEncodingBuffer(unicode=True)
elif template.bytestring_passthrough:
buf = util.StringIO()
else:
buf = util.FastEncodingBuffer(
unicode=as_unicode,
encoding=template.output_encoding,
errors=template.encoding_errors)
context = Context(buf, **data)
context._outputting_as_unicode = as_unicode
context._with_template = template
_render_context(template, callable_, context, *args,
**_kwargs_for_callable(callable_, data))
return context._pop_buffer().getvalue()
def _kwargs_for_callable(callable_, data):
argspec = util.inspect_func_args(callable_)
# for normal pages, **pageargs is usually present
if argspec[2]:
return data
# for rendering defs from the top level, figure out the args
namedargs = argspec[0] + [v for v in argspec[1:3] if v is not None]
kwargs = {}
for arg in namedargs:
if arg != 'context' and arg in data and arg not in kwargs:
kwargs[arg] = data[arg]
return kwargs
def _kwargs_for_include(callable_, data, **kwargs):
argspec = util.inspect_func_args(callable_)
namedargs = argspec[0] + [v for v in argspec[1:3] if v is not None]
for arg in namedargs:
if arg != 'context' and arg in data and arg not in kwargs:
kwargs[arg] = data[arg]
return kwargs
def _render_context(tmpl, callable_, context, *args, **kwargs):
import mako.template as template
# create polymorphic 'self' namespace for this
# template with possibly updated context
if not isinstance(tmpl, template.DefTemplate):
# if main render method, call from the base of the inheritance stack
(inherit, lclcontext) = _populate_self_namespace(context, tmpl)
_exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
else:
# otherwise, call the actual rendering method specified
(inherit, lclcontext) = _populate_self_namespace(context, tmpl.parent)
_exec_template(callable_, context, args=args, kwargs=kwargs)
def _exec_template(callable_, context, args=None, kwargs=None):
"""execute a rendering callable given the callable, a
Context, and optional explicit arguments
the contextual Template will be located if it exists, and
the error handling options specified on that Template will
be interpreted here.
"""
template = context._with_template
if template is not None and \
(template.format_exceptions or template.error_handler):
error = None
try:
callable_(context, *args, **kwargs)
except Exception, e:
_render_error(template, context, e)
except:
e = sys.exc_info()[0]
_render_error(template, context, e)
else:
callable_(context, *args, **kwargs)
def _render_error(template, context, error):
if template.error_handler:
result = template.error_handler(context, error)
if not result:
raise error
else:
error_template = exceptions.html_error_template()
if context._outputting_as_unicode:
context._buffer_stack[:] = [util.FastEncodingBuffer(unicode=True)]
else:
context._buffer_stack[:] = [util.FastEncodingBuffer(
error_template.output_encoding,
error_template.encoding_errors)]
context._with_template = error_template
error_template.render_context(context, error=error)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.