def update(self, object):
        """Adjusts the node's _subTreeItemIds list so that it matches an input object list.
        TreeItemId s will be deleted or inserted into _subTreeItemIds based on its current content and
        that of the input object list."""

        count = self._member.getCount(object)
        for i in range(count):
            inObject = self._member.getObject(object,i)
            try: 
                outObject = self.getObject(i)
                areSameObject = PyUtils.sameObject(inObject, outObject)
            except IndexError: 
                outObject = None
                areSameObject = False        
            if not areSameObject:
                # Need to delete or insert
                # First, check how many objects we should delete
                delete = 1 
                try: 
                    while not PyUtils.sameObject( inObject, self.getObject(i+delete) ) :
                        delete += 1
                except IndexError:
                    delete = 0
            
                if delete > 0 :
                    # Delete the specified objects
                    self.removeChildren(i,i+delete)
                else :
                    # Insert the specified object                                                        
                    self.insertChild(i, inObject)
        
        # Delete any remaining objects
        self.removeChildren(count)
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 create(self):
        """Creates the instant character based on the available description. Attach a reasonable controller, if available."""       
        app = wx.GetApp()
        
        try:
            wrappedController = PyUtils.wrapCopy( app.getController(0) )
        except IndexError:
            wrappedController = None
                
        try:
            character = app.getCharacter(0)
            previousMass = character.getMass()
        except IndexError:
            previousMass = None
        
        
        app.deleteAllObjects()
        PyUtils.load( "RigidBodies.FlatGround" )
        character = self._characterDescription.createCharacter()
        character.computeMass()
        app.addCharacter(character)

        if wrappedController is not None:
            controller = wrappedController.createAndFillObject(None, character)
            if previousMass is not None:
                massRatio = character.getMass() / previousMass
                controller.scaleGains( massRatio )
            app.addController(controller)
            controller.setStance( Core.LEFT_STANCE )
            self.connectController()
        
        return character
 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()
 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) )
 def load(self):
     assert not self._loaded, "Cannot load scenario twice!"
     
     self._loaded = True
     
     # Create the rigid bodies for the main staircase        
     orientation = PyUtils.angleAxisToQuaternion( (self._angle,(0,1,0)) )
     size = MathLib.Vector3d( self._staircaseWidth, self._riserHeight, self._threadDepth )
     pos = PyUtils.toPoint3d( self._position ) + MathLib.Vector3d( 0, -self._riserHeight/2.0, 0 )
     delta = MathLib.Vector3d(size)
     delta.x = 0
     delta = orientation.rotate( delta )
     for i in range(self._stepCount):
         box = PyUtils.RigidBody.createBox( size, pos = pos + delta * (i+1), locked = True, orientation=orientation )
         Physics.world().addRigidBody(box)
     
     # Create the rigid bodies for both ramps
     rampHeights = ( self._leftRampHeight, self._rightRampHeight )
     
     deltaRamp = MathLib.Vector3d(self._staircaseWidth/2.0,0,0)
     deltaRamp = orientation.rotate( deltaRamp )
     deltaRamps = (deltaRamp, deltaRamp * -1)
     for deltaRamp, rampHeight in zip( deltaRamps, rampHeights ):
         if rampHeight is None: continue
         deltaRamp.y = rampHeight/2.0
         box = PyUtils.RigidBody.createBox( (0.02,rampHeight,0.02), pos = pos + deltaRamp + delta , locked = True, orientation=orientation )
         Physics.world().addRigidBody(box)
         box = PyUtils.RigidBody.createBox( (0.02,rampHeight,0.02), pos = pos + deltaRamp + (delta * self._stepCount) , locked = True, orientation=orientation )
         Physics.world().addRigidBody(box)
         deltaRamp.y = rampHeight
         rampOrientation = orientation * PyUtils.angleAxisToQuaternion( (math.atan2(self._riserHeight, self._threadDepth), (-1,0,0)) )
         rampLen = self._stepCount * math.sqrt( self._riserHeight*self._riserHeight + self._threadDepth*self._threadDepth )
         box = PyUtils.RigidBody.createBox( (0.04,0.02,rampLen), pos = pos + deltaRamp + (delta * ((self._stepCount+1) * 0.5)) , locked = True, orientation=rampOrientation )
         Physics.world().addRigidBody(box)
    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 _addIndirectVar(self, varName, initialValue):
     """Add an indirect variable with the given name, as well as its getter and setter."""
     if isinstance(initialValue, _Symmetric) :
         self.__setattr__( PyUtils.getterName(varName), lambda side: self.getIndirectVarSymmetric(varName, side) )
     else:
         self.__setattr__( PyUtils.getterName(varName), lambda: self.getIndirectVar(varName) )
     self._indirectVarsAreValid = None
     self.__setattr__(varName, initialValue)
Exemplo n.º 9
0
def DownloadPDBs(PDB_list_file):
    PDB_list = open(os.getcwd()+'/'+PDB_list_file,'r').readlines()
    for i in range(len(PDB_list)):
        PDBid = PDB_list[i].strip()
        PyUtils.create_folder(os.getcwd()+"/"+PDBid)
        os.chdir(PDBid)
        cmd = ["~/../scripts/pdbUtil/getPdb.pl"+" -id "+PDBid]
        subprocess.call(cmd,shell=True)
        os.chdir("..")
 def _addNativeVar(self, varName, initialValue):
     """Add a variable with he given name, as well as its getter and setter."""
     if isinstance(initialValue, _Symmetric) :
         self.__setattr__( PyUtils.getterName(varName), lambda side: self.getNativeVarSymmetric(varName, side) )
         self.__setattr__( PyUtils.setterName(varName), lambda side, value: self.setNativeVarSymmetric(varName, side, value) )
     else :
         self.__setattr__( PyUtils.getterName(varName), lambda: self.getNativeVar(varName) )
         self.__setattr__( PyUtils.setterName(varName), lambda value: self.setNativeVar(varName, value) )
     self.__setattr__( varName, initialValue )
Exemplo n.º 11
0
 def __init__(self, rec, lig, cov, cov_index, HG, tart=False):
     self.tart = bool(tart)
     self.rec = rec
     self.lig = lig
     self.folder = os.path.dirname(os.path.abspath(rec)) + "/"
     self.fixed_rec = self.folder + "rec.pdb"
     self.fixed_lig = self.folder + "xtal-lig.pdb"
     self.cov = cov
     self.cov_index = cov_index
     self.hg = HG
     PyUtils.initPythonVs()
Exemplo n.º 12
0
    def __init__(self, rec, lig, cov, cov_index, HG):
        self.rec = rec
        self.lig = lig
	#self.folder = os.getcwd() + "/"
        self.folder = os.path.dirname(os.path.abspath(rec)) + "/"
        self.fixed_rec = self.folder + "rec.pdb"
        self.fixed_lig = self.folder + "xtal-lig.pdb"
        self.cov = cov
        self.cov_index = cov_index
        self.hg = HG
        PyUtils.initPythonVs()
Exemplo n.º 13
0
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
Exemplo n.º 14
0
    def __init__(self, folder_name, compound, library = False):
	self.folder = os.getcwd() + "/"
        self.name = self.folder + folder_name + "/"
        #self.compound = os.path.abspath(compound)[5:]
        self.compound = compound
        self.library = library
        PyUtils.create_folder(self.name)
        self.copyIndock()
        self.softlink()
        os.chdir(self.name)
        self.dock_command = Paths.DOCKBASE + "docking/DOCK/src/i386/dock64"
        self.DOCK()
Exemplo n.º 15
0
 def poses2pdb(self):
     PyUtils.create_folder('recs')
     os.chdir('poses')
     for k in range(1, len(os.listdir(os.getcwd())) + 1):
         i = str(k) + '.mol2'
         surface = PYMOLUtils.get_surface_area(i)
         with open(i, 'r') as f_mol:
             for line in f_mol:
                 if 'SMILES' in line:
                     smile_line = line.split()[2]
                 if 'heavy atom count' in line:
                     heavy_atoms = int(line.split()[-1])
                     break
         if surface < 200 or surface / heavy_atoms < 14.5:
             self.counters.append(0)
             continue
         if '[N+](=O)[O-]' in smile_line or smile_line.count('N') + smile_line.count('O') + smile_line.count('n') + smile_line.count('o') > 4:
             self.counters.append(0)
             continue
         pdb_pose = '../recs/' + i[:-4] + 'pdb'
         subprocess.call(['convert.py', i, pdb_pose])
         hetatm = []
         with open(pdb_pose, 'r') as f_pdb:
             for line in f_pdb:
                 if 'HETATM' in line:
                     hetatm.append(line[:23] + ' -1' + line[26:])
         rec_pose = '../recs/rec_' + i[:-4] + 'pdb'
         with open(rec_pose, 'w') as f_rec:
             for line in hetatm:
                 f_rec.write(line)
             for line in self.rec_lines:
                 f_rec.write(line)
         sub_command = []
         for res_l in self.res_list:
             sub_command.append('-seed_residue')
             sub_command.append(str(res_l))
         subprocess.call(['python', Paths.SCRIPTS + 'HBonanza.py', '-trajectory_filename', rec_pose, '-hydrogen_bond_distance_cutoff', '3.0', '-hydrogen_bond_angle_cutoff', '30', '-seed_residue', '-1'] + sub_command + ['-just_immediate_connections', 'true'], stdout=open(os.devnull, 'w'))
         os.remove(rec_pose + '.average_hbonds')
         os.remove(rec_pose + '.frame_by_frame_hbonds.csv')
         if os.path.isfile(rec_pose + '.hbond_averages_in_occupancy_column.pdb'):
             os.remove(rec_pose + '.hbond_averages_in_occupancy_column.pdb')
             counter = self.countHbonds(rec_pose + '.HBonds')
         else:
             counter = 0
         self.counters.append(counter)
         os.remove(rec_pose)
     os.chdir('../')
     shutil.rmtree('recs')
     shutil.rmtree('poses')
    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 )        
    def __init__(self, memberName, object, tree, treeItemId, container = None, index = None):
        """Subclasses must calls this constructor.
        Pass a string giving the member name for this node (member should be either App.Proxys.Member.Object or App.Proxys.Member.ObjectList.          
        Pass the object to observe, the member information for this object (from App.Proxys.Member).
        Also pass the tree and the treeItemId where this object is found.
        In container, pass the object that contains this node (in an HAS_A or HAS_MANY relationship)
        In index, pass the index of this node within its container (in an HAS_MANY relationship)        
        """
        super( NodeData, self ).__init__()
        self._memberName = memberName
        self._object = object
        self._tree = tree
        self._treeItemId = treeItemId
        self._container = container
        self._index = index
        if object is None :
            self._proxyClass = None
            iconIndex = getIconIndex( '../data/ui/noneIcon.png' )
        else:
            object.addObserver( self )
            self._proxyClass = PyUtils.getProxyClass(object)
            iconIndex = getIconIndex( self._proxyClass.getIcon() )
        self._tree.SetItemImage( self._treeItemId, iconIndex )

        self._subMemberNodes = []
        if self._proxyClass is not None :
            for subMember in self._proxyClass.getObjectMembers():
                self._subMemberNodes.append( _createSubMemberNode(subMember, self._tree, self._treeItemId, object) )

        tree.SetItemPyData( treeItemId, self )
        
        # Initial update
        self.update()
Exemplo n.º 18
0
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 add(self, object):
     """Adds an object to the list, notify observers."""
     if PyUtils.sameObjectInList(object, self._objects) :
         raise KeyError ('Cannot add the same object twice to application.')
     self._objects.append( object )
     self.notifyObservers()
     return object
    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()
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 update(self, object):
     """Updates the node so that it contains the specified object."""
     subObject = self._member.getObject(object)
     try:
         currentObject = self.getObject() 
         if PyUtils.sameObject(currentObject, subObject) : return
     except AttributeError: pass
     nodeData = NodeData( self._member.name, subObject, self._tree, self._treeItemId, self._container )
 def __init__(self, type, name, default, editable = False, fancyName = None, isObject = False ):
     self.name = name
     self.default = default
     self.editable = editable
     self.isObject = isObject
     self.type = type
     self.fancyName = fancyName
     if fancyName == None:
         self.fancyName = PyUtils.unCamelCase(name)
 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 setValueAndUpdateObject(self, memberName, value, object, container = None):
     """
     Sets the specified value of the specified member and updates the object.
     As a container, specify the object (not proxy object) to which this object is attached with an HAS_A or HAS_MANY relationship.
     """
     info = self._memberDict[memberName]
     newValue = info.interpret(value)
     if PyUtils.safeEqual( newValue, self.__getattribute__(memberName) ) : return
     self.__setattr__(memberName, newValue)
     info.set(object, newValue, container )
 def addCharacter(self, character):
     """Adds a character to the application and the world"""
     import Physics
     if PyUtils.sameObjectInList(character, self._characters) :
         raise KeyError ('Cannot add the same character twice to application.')
     Physics.world().addArticulatedFigure( character )
     self._characters.append( character )
     if self._followedCharacter is None :
         self._followedCharacter = character
         self._cameraFollowCharacter = True
         self._cameraObservable.notifyObservers()
     self._characterObservable.notifyObservers()
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 __repr__(self) :
     """
     Creates a representation of this proxy object. This can be evaluated provided the following includes:
       from App.Proxys.All import *
     """
     outMembers = []
     for member in self._members:
         value = self.__getattribute__(member.name)
         if self._verbose and PyUtils.safeEqual(value, member.default) : continue 
         outMember = repr( member.format(value) )
         if self._verbose: outMember = member.name + " = " + outMember
         outMembers.append( outMember )
     return type(self).__name__ + "(" + ','.join(outMembers) + ")"
Exemplo n.º 29
0
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
Exemplo n.º 30
0
def toList(m):
    '''
    Convert a PyMEL Matrix or [4][4] list into a flat 16-element list
    '''

    if isinstance(m, pm.datatypes.Matrix):
        m = [m.a00, m.a01, m.a02, m.a03,
                m.a10, m.a11, m.a12, m.a13,
                m.a20, m.a21, m.a22, m.a23,
                m.a30, m.a31, m.a32, m.a33]
    elif PyUtils.isIterable(m[0]):
        m = [m[0][0], m[0][1], m[0][2], m[0][3],
                m[1][0], m[1][1], m[1][2], m[1][3],
                m[2][0], m[2][1], m[2][2], m[2][3],
                m[3][0], m[3][1], m[3][2], m[3][3]]
    return m
Exemplo n.º 31
0
    def __init__(self):
        """Creates a new model for a character description, including the required UI."""

        app = wx.GetApp()
        glCanvas = app.getGLCanvas()

        self._container = glCanvas.addGLUITool(GLUtils.GLUIContainer)
        self._container.setVisible(False)

        self._optionsObservable = PyUtils.Observable()

        self._sizer = GLUtils.GLUIBoxSizer(GLUtils.GLUI_HORIZONTAL)
        self._container.setSizer(self._sizer)
        self.reset()

        self._toolSet = ToolSet(app.getToolPanel(), self)
Exemplo n.º 32
0
    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)
Exemplo n.º 33
0
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 )
Exemplo n.º 34
0
    def __init__(self,
                 memberName,
                 object,
                 tree,
                 treeItemId,
                 container=None,
                 index=None):
        """Subclasses must calls this constructor.
        Pass a string giving the member name for this node (member should be either App.Proxys.Member.Object or App.Proxys.Member.ObjectList.          
        Pass the object to observe, the member information for this object (from App.Proxys.Member).
        Also pass the tree and the treeItemId where this object is found.
        In container, pass the object that contains this node (in an HAS_A or HAS_MANY relationship)
        In index, pass the index of this node within its container (in an HAS_MANY relationship)        
        """
        super(NodeData, self).__init__()
        self._memberName = memberName
        self._object = object
        self._tree = tree
        self._treeItemId = treeItemId
        self._container = container
        self._index = index
        if object is None:
            self._proxyClass = None
            iconIndex = getIconIndex('../data/ui/noneIcon.png')
        else:
            object.addObserver(self)
            self._proxyClass = PyUtils.getProxyClass(object)
            iconIndex = getIconIndex(self._proxyClass.getIcon())
        self._tree.SetItemImage(self._treeItemId, iconIndex)

        self._subMemberNodes = []
        if self._proxyClass is not None:
            for subMember in self._proxyClass.getObjectMembers():
                self._subMemberNodes.append(
                    _createSubMemberNode(subMember, self._tree,
                                         self._treeItemId, object))

        tree.SetItemPyData(treeItemId, self)

        # Initial update
        self.update()
Exemplo n.º 35
0
    def __init__(self, parentBranch):
        """Takes a shot of a world, add it to the specified branch."""
        super(Snapshot, self).__init__()

        self._time = time.localtime()

        # Save the world
        world = Physics.world()
        self._worldState = Utils.DynamicArrayDouble()
        world.getState(self._worldState)

        # Save the controllers
        app = wx.GetApp()
        self._controllers = []
        for i in range(app.getControllerCount()):
            controller = app.getController(i)
            controllerState = Core.SimBiControllerState()
            controller.getControllerState(controllerState)
            self._controllers.append(
                (controllerState, PyUtils.wrapCopy(controller)))

        self._parentBranch = parentBranch
        self._childBranches = []
        self._activeIndex = -1
'''
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();
Exemplo n.º 37
0
 def runDirSingle(self, dirname, command):
     PyUtils.create_folder(dirname[:-1])
     curr = os.getcwd()
     os.chdir(dirname[:-1])
     self.runSingle(command)
     os.chdir(curr)
Exemplo n.º 38
0
 def get(self, object):
     result = []
     for i in range(self.getCount(object)):
         result.append(PyUtils.wrap(self.getObject(object, i)))
     return result
Exemplo n.º 39
0
 def set(self, object, valueProxyList, container=None):
     if valueProxyList is None: return
     PyUtils.callOnObjectOrListAndEnumerate(
         valueProxyList,
         lambda i, valueProxy: self._set(object, i, valueProxy, container))
Exemplo n.º 40
0
    def __init__(self,
                 appTitle="Simbicon Application",
                 fps=30.0,
                 dt=1 / 2000.0,
                 glCanvasSize=wx.DefaultSize,
                 size=wx.DefaultSize,
                 redirect=False,
                 filename=None,
                 useBestVisual=False,
                 clearSigInt=True,
                 showConsole=True):
        """
        appTitle is the window title
        fps is the desired number of frames per seconds
        dt is the desired simulation timestep
        :see: wx.BasicApp.__init__`
        """

        wx.App.__init__(self, redirect, filename, useBestVisual, clearSigInt)

        # No annoying error logging window
        wx.Log.SetActiveTarget(wx.LogStderr())

        import UI

        # Setup the main window style
        style = wx.DEFAULT_FRAME_STYLE
        if size == wx.DefaultSize:
            size = wx.GetDisplaySize()
            size.height *= 0.75
            size.width *= 0.75
            if glCanvasSize == wx.DefaultSize:
                style |= wx.MAXIMIZE

        # Setup the environment for the python interactive console
        consoleEnvironment = {"wx": wx, "Physics": Physics, "Utils": Utils}
        exec "from MathLib import *\n" + \
             "app = wx.GetApp()\n" + \
             "from PyUtils import load" in consoleEnvironment, consoleEnvironment

        # Create the main window
        self._frame = UI.MainWindow(None,
                                    -1,
                                    appTitle,
                                    size=size,
                                    style=style,
                                    fps=fps,
                                    glCanvasSize=glCanvasSize,
                                    showConsole=showConsole,
                                    consoleEnvironment=consoleEnvironment)

        # Define GL callbacks
        self._glCanvas = self._frame.getGLCanvas()
        self._glCanvas.addDrawCallback(self.draw)
        self._glCanvas.addPostDrawCallback(self.postDraw)
        self._glCanvas.addOncePerFrameCallback(self.advanceAnimation)
        self._glCanvas.setDrawAxes(False)
        self._glCanvas.setPrintLoad(True)
        self._glCanvas.setCameraTargetFunction(self.cameraTargetFunction)

        self._glCanvas.setDrawGround(False)

        # Get the tool panel
        self._toolPanel = self._frame.getToolPanel()

        # Show the application
        self._frame.Show()

        # Set-up starting state
        self._dt = dt
        self._drawShadows = True
        self._simulationSecondsPerSecond = 1  # 1 = real time, 2 = twice real time, 1/2 = half real time
        self._animationRunning = False
        self._cameraFollowCharacter = False
        self._drawCollisionVolumes = False
        self._followedCharacter = None  # Pointer to focused character
        self._captureScreenShots = False
        self._printStepReport = True
        self._screenShotNumber = 0
        self._worldOracle = Core.WorldOracle()
        self._worldOracle.initializeWorld(Physics.world())
        self._kinematicMotion = False

        # Set-up starting list of characters and controllers
        self._characters = []

        # Define the observables
        self._controllerList = ObservableList()
        self._characterObservable = PyUtils.Observable()
        self._animationObservable = PyUtils.Observable()
        self._cameraObservable = PyUtils.Observable()
        self._optionsObservable = PyUtils.Observable()

        self._COMObservable = PyUtils.Observable()

        self._curveList = ObservableList()
        self._snapshotTree = SnapshotBranch()

        self._showAbstractView = False
        self._showAbstractViewSkeleton = False
        self._showBodyFrame = False
        self._showCDPrimitives = False
        self._showColors = False
        self._showFrictionParticles = False
        self._showJoints = False
        self._showMesh = True
        self._showMinBDGSphere = False
        self._showCenterOfMass = True

        self._COMErrorScale = 0.01

        params = [
            3.75162180e-04, 1.70361201e+00, -7.30441228e-01, -6.22795336e-01,
            3.05330848e-01
        ]
        fps = 100

        # params = [0, 0, 0, 0, 0]

        # fps = 100.0
        # model_order = (50, 50)
        # params = [0.00019815056771797725, 1.9687785869242351, -0.9709165752219967, -0.565841931234043, 0.3226849680645409]

        self._armaX = ArmaProcess(params[0], params[1:3], params[3:5], fps)
        self._armaY = ArmaProcess(params[0], params[1:3], params[3:5], fps)
        self._armaZ = ArmaProcess(params[0], params[1:3], params[3:5], fps)
Exemplo n.º 41
0
 def poses2pdb(self):
     PyUtils.create_folder('recs')
     os.chdir('poses')
     for k in range(1, len(os.listdir(os.getcwd())) + 1):
         i = str(k) + '.mol2'
         surface = PYMOLUtils.get_surface_area(i)
         with open(i, 'r') as f_mol:
             for line in f_mol:
                 if 'SMILES' in line:
                     smile_line = line.split()[2]
                 if 'heavy atom count' in line:
                     heavy_atoms = int(line.split()[-1])
                     break
         #if surface < 200 or surface / heavy_atoms < 14.5:
         #    self.counters.append(0)
         #    continue
         #if '[N+](=O)[O-]' in smile_line or smile_line.count('N') + smile_line.count('O') + smile_line.count('n') + smile_line.count('o') > 4:
         #    self.counters.append(0)
         #    continue
         #Remove comment to filter for phosphates
         #if 'P' in smile_line:
         #    self.counters.append(0)
         #    continue
         pdb_pose = '../recs/' + i[:-4] + 'pdb'
         subprocess.call(
             ['python', Paths.SCRIPTS + 'ChemChem/convert.py', i, pdb_pose])
         hetatm = []
         with open(pdb_pose, 'r') as f_pdb:
             for line in f_pdb:
                 #if 'HETATM' in line:
                 if 'ATOM' in line:
                     hetatm.append(line[:23] + ' -1' + line[26:])
         rec_pose = '../recs/rec_' + i[:-4] + 'pdb'
         with open(rec_pose, 'w') as f_rec:
             for line in hetatm:
                 f_rec.write(line)
             for line in self.rec_lines:
                 f_rec.write(line)
         sub_command = []
         for res_l in self.res_list:
             sub_command.append('-seed_residue')
             sub_command.append(str(res_l))
         subprocess.call([
             'python', Paths.SCRIPTS + 'HBonanza.py',
             '-trajectory_filename', rec_pose,
             '-hydrogen_bond_distance_cutoff', '3.0',
             '-hydrogen_bond_angle_cutoff', '30', '-seed_residue', '-1'
         ] + sub_command + ['-just_immediate_connections', 'true'],
                         stdout=open(os.devnull, 'w'))
         os.remove(rec_pose + '.average_hbonds')
         os.remove(rec_pose + '.frame_by_frame_hbonds.csv')
         if os.path.isfile(rec_pose +
                           '.hbond_averages_in_occupancy_column.pdb'):
             os.remove(rec_pose + '.hbond_averages_in_occupancy_column.pdb')
             counter = self.countHbonds(rec_pose + '.HBonds')
         else:
             counter = 0
         self.counters.append(counter)
         os.remove(rec_pose)
     os.chdir('../')
     #shutil.rmtree('recs')
     shutil.rmtree('poses')
Exemplo n.º 42
0
 def format(self, value):
     return PyUtils.angleAxisFromQuaternion(value)
Exemplo n.º 43
0
    def __init__(self,
                 appTitle="Simbicon Application",
                 fps=30.0,
                 dt=1 / 2000.0,
                 glCanvasSize=wx.DefaultSize,
                 size=wx.DefaultSize,
                 redirect=False,
                 filename=None,
                 useBestVisual=False,
                 clearSigInt=True,
                 showConsole=True):
        """
        appTitle is the window title
        fps is the desired number of frames per seconds
        dt is the desired simulation timestep
        :see: wx.BasicApp.__init__`
        """

        wx.App.__init__(self, redirect, filename, useBestVisual, clearSigInt)

        # No annoying error logging window
        wx.Log.SetActiveTarget(wx.LogStderr())

        import UI

        # Setup the main window style
        style = wx.DEFAULT_FRAME_STYLE
        if size == wx.DefaultSize:
            size = wx.GetDisplaySize()
            size.height *= 0.75
            size.width *= 0.75
            if glCanvasSize == wx.DefaultSize:
                style |= wx.MAXIMIZE

        # Setup the environment for the python interactive console
        consoleEnvironment = {"wx": wx, "Physics": Physics, "Utils": Utils}
        exec "from MathLib import *\n" + \
             "app = wx.GetApp()\n" + \
             "from PyUtils import load" in consoleEnvironment, consoleEnvironment

        # Create the main window
        self._frame = UI.MainWindow(None,
                                    -1,
                                    appTitle,
                                    size=size,
                                    style=style,
                                    fps=fps,
                                    glCanvasSize=glCanvasSize,
                                    showConsole=showConsole,
                                    consoleEnvironment=consoleEnvironment)

        # Define GL callbacks
        self._glCanvas = self._frame.getGLCanvas()
        self._glCanvas.addDrawCallback(self.draw)
        self._glCanvas.addPostDrawCallback(self.postDraw)
        self._glCanvas.addOncePerFrameCallback(self.advanceAnimation)
        self._glCanvas.setDrawAxes(False)
        self._glCanvas.setPrintLoad(True)
        self._glCanvas.setCameraTargetFunction(self.cameraTargetFunction)

        # Get the tool panel
        self._toolPanel = self._frame.getToolPanel()

        # Show the application
        self._frame.Show()

        # Set-up starting state
        self._dt = dt
        self._drawShadows = True
        self._simulationSecondsPerSecond = 1  # 1 = real time, 2 = twice real time, 1/2 = half real time
        self._animationRunning = False
        self._cameraFollowCharacter = False
        self._drawCollisionVolumes = False
        self._followedCharacter = None  # Pointer to focused character
        self._captureScreenShots = False
        self._printStepReport = True
        self._screenShotNumber = 0
        self._worldOracle = Core.WorldOracle()
        self._worldOracle.initializeWorld(Physics.world())
        self._kinematicMotion = False

        # Set-up starting list of characters and controllers
        self._characters = []

        # Define the observables
        self._controllerList = ObservableList()
        self._characterObservable = PyUtils.Observable()
        self._animationObservable = PyUtils.Observable()
        self._cameraObservable = PyUtils.Observable()
        self._optionsObservable = PyUtils.Observable()
        self._curveList = ObservableList()
        self._snapshotTree = SnapshotBranch()
Exemplo n.º 44
0
'''
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 );
Exemplo n.º 45
0
#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
Exemplo n.º 46
0
 def interpret(self, value):
     value = self.basicInterpret(value)
     if isinstance(value, MathLib.Point3d): return value
     else: return PyUtils.toPoint3d(value)
Exemplo n.º 47
0
 def format(self, value):
     return PyUtils.fromVector3d(value)
Exemplo n.º 48
0
'''
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()
Exemplo n.º 49
0
 def runDirSingle(self, dirname, command):
     PyUtils.create_folder(dirname[:-1])
     os.chdir(dirname[:-1])
     self.runSingle(command)
     os.chdir('../')
Exemplo n.º 50
0
 def interpret(self, value):
     value = self.basicInterpret(value)
     if isinstance(value, MathLib.Trajectory1d): return value
     else: return PyUtils.toTrajectory1d(value)
Exemplo n.º 51
0
'''
Created on 2009-11-23

@author: beaudoin
'''

import PyUtils

PyUtils.load( "RigidBodies.FiniteFlatGround" )
Exemplo n.º 52
0
 def format(self, value):
     return PyUtils.fromTrajectory1d(value)
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 )

# This shows off the balance controller well
controller = PyUtils.load("Characters.BipV3.Controllers.jerome2", character)

#controller = PyUtils.load( "Characters.BipV3.Controllers.emps", 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
Exemplo n.º 54
0
 def get(self, object):
     return PyUtils.wrap(self.getObject(object))
Exemplo n.º 55
0
 def format(self, value):
     return PyUtils.fromPoint3d(value)
Exemplo n.º 56
0
    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()            
Exemplo n.º 57
0
 def interpret(self, value):
     value = self.basicInterpret(value)
     if isinstance(value, MathLib.Quaternion): return value
     else: return PyUtils.angleAxisToQuaternion(value)
Exemplo n.º 58
0
 def softlink(self):
     files = "dockfiles"
     PyUtils.create_softlink(self.folder + files, self.name + files)