Best Python code snippet using slash
odebase.py
Source:odebase.py
1import sys, random, time2from math import degrees, sin, cos, pi, sqrt, pow, atan3from direct.showbase import PythonUtil as PU4#import ode as ode5#import direct.directbase.DirectStart6from pandac.PandaModules import PerspectiveLens7from pandac.PandaModules import TransparencyAttrib,GeomVertexReader,GeomVertexFormat,GeomVertexData,Geom,GeomVertexWriter,GeomTriangles,GeomNode8from pandac.PandaModules import Vec3,Vec4,Point39from pandac.PandaModules import OdeWorld, OdeSimpleSpace, OdeJointGroup, OdeSpace, OdeBallJoint, OdeHinge2Joint, OdeQuadTreeSpace, OdeHashSpace10from pandac.PandaModules import OdeBody, OdeMass, OdeSphereGeom, OdeBoxGeom, OdePlaneGeom, OdeCylinderGeom, OdeCappedCylinderGeom, OdeTriMeshGeom, OdeTriMeshData11from pandac.PandaModules import BitMask32, Quat, Mat412from pandac.PandaModules import PandaSystem1314#from random import randint, random15import random1617def getLength(v1,v2):18 return sqrt(pow(v1[0]-v2[0],2)+pow(v1[1]-v2[1],2)+pow(v1[2]-v2[2],2))19def getCenter(v1,v2):20 return [ (v1[0]+v2[0])/2, (v1[1]+v2[1])/2, (v1[2]+v2[2])/2]2122class ODEBallJoint(OdeBallJoint):23 def __init__(self, world, model=None, renderparent=None, scale=None):24 OdeBallJoint.__init__(self, world)25 if model != None:26 self.np = model.copyTo(renderparent)27 self.np.setP(90)28 self.np.flattenStrong()29 self.scale = scale30 else:31 self.np = None32 self.bodies = 03334 def destroy(self):35 self.detach()36 OdeBallJoint.destroy(self)37 if self.np != None:38 self.np.removeNode()3940 def attach(self, b1, b2):41 OdeBallJoint.attach(self, b1,b2)42 self.body1 = b143 if b2 == None:44 self.bodies = 145 else:46 self.bodies = 247 self.body2 = b24849 def Render(self):50 if self.np==None or self.bodies == 0:51 return52 #v = self.getAnchor()53 if self.bodies == 1:54 v = self.getAnchor2()55 else:56 #v = self.getBody(1).getPosition()57 v = self.body2.getPosition()58 #vb = self.getBody(0).getPosition()59 vb = self.body1.getPosition()60 #if self.bodies == 2:61 # print v, vb62 v = Vec3(v[0],v[1],v[2])63 vb = Vec3(vb[0],vb[1],vb[2])64 c = (vb+v) / 265 vd = vb-v66 l = vd.length()67 #self.np.setScale(self.scale[0], self.scale[1], self.scale[2] * l)68 self.np.setScale(self.scale[0], self.scale[1] *l, self.scale[0])69 self.np.setPos(c[0],c[1],c[2])70 self.np.lookAt(vb[0],vb[1],vb[2])717273##class ODEBallJointOld(OdeBallJoint):74## def __init__(self, world, model=None, renderparent=None, scale=None):75## OdeBallJoint.__init__(self, world)76## if model != None:77## self.np = renderparent.attachNewNode("dummy")78## np = model.copyTo(self.np)79## np.setP(90)80## self.np2 = np81##82## self.scale = scale83## else:84## self.np = None85##86## def destroy(self):87## self.detach()88## OdeBallJoint.destroy(self)89## if self.np != None:90## self.np.removeNode()91##92## def Render(self):93## if self.np==None:94## return95## #v = self.getAnchor()96## v = self.getAnchor2()97## vb = self.getBody(0).getPosition()98## v = Vec3(v[0],v[1],v[2])99## vb = Vec3(vb[0],vb[1],vb[2])100## c = (vb+v) / 2101## vd = vb-v102## l = vd.length()103## #self.np.setScale(self.scale[0], self.scale[1], self.scale[2] * l)104## #self.np.setScale(self.scale[0], self.scale[1] *l, self.scale[2])105## self.np2.setScale(self.scale[0], self.scale[1], self.scale[2] * l)106## self.np.setPos(c[0],c[1],c[2])107## self.np.lookAt(vb[0],vb[1],vb[2])108109110class ODEobjbase:111 def storeProps(self, realObj, mass, surfaceId, collideBits, categoryBits):112 self.realObj=realObj113 self.mass=mass114 self.surfaceId = surfaceId115 self.geom.getSpace().setSurfaceType(self.geom, surfaceId)116 self.geom.setCollideBits(BitMask32(collideBits))117 self.geom.setCategoryBits(BitMask32(categoryBits))118119 def isDynamic(self):120 return hasattr(self,'body')121122 def delRealobj(self):123 if self.realObj != None:124 self.realObj.removeNode()125 self.realObj = None126127 def destroy(self):128 if hasattr(self,'body'):129 #self.body.destroy()130 del self.body131 self.geom.getSpace().remove(self.geom)132133 del self.geom134 if hasattr(self,'visualizer'):135 self.visualizer.removeNode()136 self.delRealobj()137138139 def getOBB(self,collObj):140 ''' get the Oriented Bounding Box '''141 # save object's parent and transformation142 parent=collObj.getParent()143 trans=collObj.getTransform()144 # ODE need everything in world's coordinate space,145 # so bring the object directly under render, but keep the transformation146 collObj.wrtReparentTo(render)147 # get the tight bounds before any rotation148 collObj.setHpr(0,0,0)149 bounds=collObj.getTightBounds()150 offset=collObj.getBounds().getCenter()-collObj.getPos()151 # bring object to it's parent and restore it's transformation152 collObj.reparentTo(parent)153 collObj.setTransform(trans)154 # (max - min) bounds155 box=bounds[1]-bounds[0]156# print bounds[0], bounds[1]157 return [box[0],box[1],box[2]], [offset[0],offset[1],offset[2]]158159class ODEbox(ODEobjbase):160 def __init__(self, world, space, realObj=None, collObj=None,161 density=0, surfaceId=0, collideBits=0, categoryBits=0):162 if realObj==None:163 obj=collObj164 else:165 obj=realObj166 if collObj==None:167 collObj=realObj168169 boundingBox, offset=self.getOBB(collObj)170 #print boundingBox, offset171172## if offset==Vec3(0):173## fCentered=True174## else:175## realGeom= OdeBoxGeom(None, lengths=boundingBox)176## self.geom = Ode.GeomTransform(space)177## self.geom.setGeom(realGeom)178## realGeom.setPosition(offset)179## nonCenteredO=1180## print 'NON-CENTERED ORIGIN'181##182## if density: # create body if the object is dynamic, otherwise don't183## self.body = ode.Body(world)184## M = ode.Mass()185## M.setBox(density, *boundingBox)186## if nonCenteredO:187## M.translate(offset)188189 self.geom = OdeBoxGeom(space, *boundingBox)190191 if density > 0: # create body if the object is dynamic, otherwise don't192 self.body = OdeBody(world)193 M = OdeMass()194 M.setBox(density, *boundingBox)195 self.body.setMass(M)196 self.geom.setBody(self.body)197 #self.geom.setOffsetPosition(*offset)198 #print offset199 mass = M.getMagnitude()200 else:201 mass = 0202 # synchronize ODE geom's transformation according to the real object's203 self.geom.setPosition(obj.getPos(render))204 self.geom.setQuaternion(obj.getQuat(render))205 # store object's properties206 self.storeProps(realObj, mass, surfaceId, collideBits, categoryBits)207208class ODEcylinder(ODEobjbase):209 def __init__(self, world, space, realObj=None, collObj=None,210 density=0, direction=3, radius=1, length=1, surfaceId=0, collideBits=0, categoryBits=0):211 if realObj==None:212 obj=collObj213 else:214 obj=realObj215 if collObj==None:216 collObj=realObj217218 self.geom = OdeCylinderGeom(space, radius, length)219220 if density > 0: # create body if the object is dynamic, otherwise don't221 self.body = OdeBody(world)222 M = OdeMass()223 M.setCylinder(density, direction, radius, length)224 self.body.setMass(M)225 self.geom.setBody(self.body)226 #self.geom.setOffsetPosition(*offset)227 #print offset228 mass = M.getMagnitude()229 else:230 mass = 0231 # synchronize ODE geom's transformation according to the real object's232 self.geom.setPosition(obj.getPos(render))233 self.geom.setQuaternion(obj.getQuat(render))234 # store object's properties235 self.storeProps(realObj, mass, surfaceId, collideBits, categoryBits)236237class ODEcylinder2(ODEobjbase):238 def __init__(self, world, space, realObj=None, collObj=None,239 density=0, direction=3, radius=1, length=1, surfaceId=0, collideBits=0, categoryBits=0):240 if realObj==None:241 obj=collObj242 else:243 obj=realObj244 if collObj==None:245 collObj=realObj246247 self.geom = OdeSphereGeom(space, radius)248249 if density > 0: # create body if the object is dynamic, otherwise don't250 self.body = OdeBody(world)251 M = OdeMass()252 M.setCylinder(density, direction, radius, length)253 self.body.setMass(M)254 self.geom.setBody(self.body)255 #self.geom.setOffsetPosition(*offset)256 #print offset257 mass = M.getMagnitude()258 else:259 mass = 0260 # synchronize ODE geom's transformation according to the real object's261 self.geom.setPosition(obj.getPos(render))262 self.geom.setQuaternion(obj.getQuat(render))263 # store object's properties264 self.storeProps(realObj, mass, surfaceId, collideBits, categoryBits)265266267class ODECappedCylinder(ODEobjbase):268 def __init__(self, world, space, realObj=None, collObj=None,269 density=0, direction=3,radius=1, length=1, surfaceId=0, collideBits=0, categoryBits=0):270 if realObj==None:271 obj=collObj272 else:273 obj=realObj274 if collObj==None:275 collObj=realObj276277 self.geom = OdeCappedCylinderGeom(space, radius, length)278279 if density > 0: # create body if the object is dynamic, otherwise don't280 self.body = OdeBody(world)281 M = OdeMass()282 M.setCapsule(density, direction, radius, length)283 self.body.setMass(M)284 self.geom.setBody(self.body)285 #self.geom.setOffsetPosition(*offset)286 #print offset287 mass = M.getMagnitude()288 else:289 mass = 0290 # synchronize ODE geom's transformation according to the real object's291 self.geom.setPosition(obj.getPos(render))292 self.geom.setQuaternion(obj.getQuat(render))293 # store object's properties294 self.storeProps(realObj, mass, surfaceId, collideBits, categoryBits)295296297class ODEsphere(ODEobjbase):298 def __init__(self, world, space, realObj=None, collObj=None,299 density=0, surfaceId=0, collideBits=0, categoryBits=0):300 if realObj==None:301 obj=collObj302 else:303 obj=realObj304 if collObj==None:305 collObj=realObj306307 boundingBox, offset=self.getOBB(collObj)308 r = boundingBox[0]/2309 self.geom = OdeSphereGeom(space, r)310 if density > 0: # create body if the object is dynamic, otherwise don't311 self.body = OdeBody(world)312 M = OdeMass()313 M.setSphere(density, r)314 self.body.setMass(M)315 self.geom.setBody(self.body)316 mass = M.getMagnitude()317 else:318 mass = 0319 # synchronize ODE geom's transformation according to the real object's320 self.geom.setPosition(obj.getPos(render))321 self.geom.setQuaternion(obj.getQuat(render))322 # store object's properties323 self.storeProps(realObj, mass, surfaceId, collideBits, categoryBits)324325326327class ODEtrimesh(ODEobjbase):328 def __init__(self, world, space, realObj=None, collObj=None,329 mass=0, surfaceId=0, collideBits=0, categoryBits=0):330 if realObj==None:331 obj=collObj332 else:333 obj=realObj334 if collObj==None:335 collObj=realObj336337338 modelTrimesh = OdeTriMeshData(obj, True)339 self.geom = OdeTriMeshGeom(space, modelTrimesh)340 if mass > 0: # create body if the object is dynamic, otherwise don't341 self.body = OdeBody(world)342 M = OdeMass()343 boundingBox, offset=self.getOBB(collObj)344 #print boundingBox345 size = max(0.01,max(boundingBox[0],boundingBox[1],boundingBox[2])/2)346 M.setSphereTotal(mass, size)347 self.body.setMass(M)348 #self.body.setGravityMode(1)349 #print M350 self.geom.setBody(self.body)351 # synchronize ODE geom's transformation according to the real object's352 self.geom.setPosition(obj.getPos(render))353 self.geom.setQuaternion(obj.getQuat(render))354 # store object's properties355 self.storeProps(realObj, mass, surfaceId, collideBits, categoryBits)356357358# make a rectangular room using boxes359def MakeRoomBoxes(minpos, maxpos, thickness):360 # six pieces361 xmid = (maxpos[0] + minpos[0]) / 2362 ymid = (maxpos[1] + minpos[1]) / 2363 zmid = (maxpos[2] + minpos[2]) / 2364 xl = (maxpos[0] - minpos[0])365 yl = (maxpos[1] - minpos[1])366 zl = (maxpos[2] - minpos[2])367 return [368 [maxpos[0]+thickness/2,ymid,zmid,thickness,yl,zl],369 [minpos[0]-thickness/2,ymid,zmid,thickness,yl,zl],370 [xmid, ymid, maxpos[2]+thickness/2, xl, yl, thickness],371 [xmid, ymid, minpos[2]-thickness/2, xl, yl, thickness],372 [xmid, maxpos[1]+thickness/2, zmid, xl, thickness, zl],373 [xmid, minpos[1]-thickness/2, zmid, xl, thickness, zl],374 ]375376def MakeRoom(node,box,odeworld,collideBits,categoryBits,minpos,maxpos,thickness,sides=6):377 boxes = MakeRoomBoxes(minpos,maxpos,thickness)378 room = node.attachNewNode("roomwalls")379 objlist=[]380 for i in range(sides):381 b = boxes[i]382 x,y,z,sx,sy,sz = b383 bNP = box.copyTo(room)384 bNP.setPos(x,y,z)385 bNP.setScale(sx,sy,sz)386 b_ode = ODEbox(odeworld.world,odeworld.space,bNP, None, 0, 0, collideBits,categoryBits)387 b_ode.delRealobj()388 odeworld.AddObject(b_ode)389 objlist.append(b_ode)390 return room,objlist391392class ODEWorld_Simple():393 SIMPLESPACE = 1394 HASHSPACE = 2395 def __init__(self, spacetype=SIMPLESPACE):396 major = PandaSystem.getMajorVersion()397 minor = PandaSystem.getMinorVersion()398 self.supportEvent = (major == 1 and minor > 5) or (major > 2)399 if self.supportEvent:400 self.collisionMap = {}401 self.InitODE(spacetype)402 self.listener = set()403404 # debugging405 #if self.supportEvent:406 # self.space.setCollisionEvent("ode-collision")407 # base.accept("ode-collision", self.onCollision)408 self.count = 0409 self.totaltime1 = 0.0410 self.totaltime2 = 0.0411412 #################################################413 # this functions are obsoleted, only for 1.5.4414 def setNotifier(self, object):415 self.listener.add(object)416417 def removeNotifier(self, object):418 self.listener.remove(object)419420 def notify(self, collisions):421 for obj in self.listener:422 obj.odeEvent(collisions)423 # this function are obsoleted, only for 1.5.4424 #################################################425426 # this function is for 1.6427 def setCollisionNotifier(self, odeobject, func):428 if self.supportEvent:429 if len(self.collisionMap) == 0:430 self.space.setCollisionEvent("ode-collision")431 base.accept("ode-collision", self.onCollision)432 id = int(str(odeobject.geom).split(" ")[-1].rstrip(")"), 16)433 #print id434 self.collisionMap[id] = (odeobject, func)435436 def EnableODETask(self, task=2):437 if task == 2:438 #taskMgr.doMethodLater(0.5, simulationTask, "Physics Simulation", extraArgs=[self], appendTask=True)439 taskMgr.doMethodLater(0.5, self.simulationTask2, "ODESimulation")440 elif task == 3:441 taskMgr.doMethodLater(0.5, self.simulationTask3, "ODESimulation")442 elif task == 4: # debug443 #self.stepSize = 1.0 / 40.0444 taskMgr.doMethodLater(0.5, self.simulationTask4, "ODESimulation")445 elif task == 5: # debug446 taskMgr.doMethodLater(0.5, self.simulationTask5, "ODESimulation")447 else:448 taskMgr.remove("ODESimulation")449450451 def InitODE(self, spacetype):452 world = OdeWorld()453 self.world = world454455 # Create a space and add a contactgroup to it to add the contact joints456 if spacetype == self.SIMPLESPACE:457 space = OdeSimpleSpace()458 elif spacetype == self.HASHSPACE:459 space = OdeHashSpace()460 self.InitODEwithSpace(space)461462 def InitODEwithSpace(self, space):463 space.setAutoCollideWorld(self.world)464 contactgroup = OdeJointGroup()465 space.setAutoCollideJointGroup(contactgroup)466467 self.space = space468 self.contactgroup = contactgroup469 #self.objectlist = {}470 self.objectlist = set()471472 # Create an accumulator to track the time since the sim473 # has been running474 # This stepSize makes the simulation run at 90 frames per second475 self.deltaTimeAccumulator = 0.0476 #self.stepSize = 1.0 / 200.0477 #self.stepSize = 1.0 / 90.0478 self.stepSize = 1.0 / 50.0479 #s = self.world.getQuickStepNumIterations()480 #self.world.setQuickStepNumIterations(1000)481 #print s482483 def AddObject(self, odeobject):484 #self.objectlist[odeobject] = odeobject485 self.objectlist.add(odeobject)486487 def RemoveObject(self, odeobject):488 #del self.objectlist[odeobject]489 if self.supportEvent:490 if hasattr(odeobject, "geom") and odeobject.geom in self.collisionMap:491 del self.collisionMap[odeobject.geom]492 if len(self.collisionMap) == 0:493 self.space.setCollisionEvent("")494 self.objectlist.remove(odeobject)495496 def DestroyAllObjects(self):497 if self.supportEvent:498 self.collisionMap.clear()499 self.space.setCollisionEvent("")500 for odeobject in self.objectlist:501 odeobject.destroy()502 self.objectlist.clear()503504 # The task for our simulation505 def simulationTask1(self, task):506 #self.space.autoCollide() # Setup the contact joints507 # Step the simulation and set the new positions508 self.world.quickStep(globalClock.getDt())509 cc = self.space.autoCollide() # Setup the contact joints510 if not self.supportEvent:511 # this is obsoleted, only for 1.5.4512 collisions = []513 if cc > 0:514 for i in range(cc):515 p = Vec3(self.space.getContactData(i*3+0),self.space.getContactData(i*3+1),self.space.getContactData(i*3+2))516 collisions.append(p)517518 #for b_ode in room.balls:519 for b_ode in self.objectlist:520 if isinstance(b_ode, ODEobjbase):521 if b_ode.isDynamic():522 np = b_ode.realObj523 if np != None:524 #body = b_ode.body525 body = b_ode.geom526 np.setPosQuat(render, body.getPosition(), Quat(body.getQuaternion()))527 self.contactgroup.empty() # Clear the contact joints528 if not self.supportEvent:529 self.notify(collisions)530 return task.cont531532533 # The task for our simulation534 def simulationTask2(self, task):535 # Set the force on the body to push it off the ridge536 # Add the deltaTime for the task to the accumulator537 self.deltaTimeAccumulator +=globalClock.getDt()538 if self.deltaTimeAccumulator < self.stepSize:539 return task.cont540541 self.space.autoCollide() # Setup the contact joints542 collisions=[]543 while self.deltaTimeAccumulator > self.stepSize:544 # Remove a stepSize from the accumulator until545 # the accumulated time is less than the stepsize546 self.deltaTimeAccumulator -= self.stepSize547 # Step the simulation548 self.world.quickStep(self.stepSize)549 cc=self.space.autoCollide() # Setup the contact joints550 if not self.supportEvent:551 # this is obsoleted, only for 1.5.4552 if cc > 0:553 for i in range(cc):554 p = Vec3(self.space.getContactData(i*3+0),self.space.getContactData(i*3+1),self.space.getContactData(i*3+2))555 collisions.append(p)556 break557 #cc = self.space.autoCollide() # Setup the contact joints558 for b_ode in self.objectlist:559 if isinstance(b_ode, ODEobjbase):560 if b_ode.isDynamic():561 np = b_ode.realObj562 if np != None:563 #body = b_ode.body564 body = b_ode.geom565 np.setPosQuat(body.getPosition(), Quat(body.getQuaternion()))566 if b_ode.mass > 0 and hasattr(b_ode, "motionfriction"):567 v = b_ode.body.getLinearVel()568 ma = -b_ode.motionfriction * b_ode.mass569 b_ode.body.addForce(ma*v[0],ma*v[1],ma*v[2])570 v = b_ode.body.getAngularVel()571 ma = (1-b_ode.angularfriction)572 b_ode.body.setAngularVel(ma*v[0],ma*v[1],ma*v[2])573 else:574 # a joint ?575 b_ode.Render()576 #for contact in self.contactgroup:577 # print contact578 self.contactgroup.empty() # Clear the contact joints579 if not self.supportEvent:580 self.notify(collisions)581 return task.cont582583584 # The task for our simulation585 def simulationTask2Save(self, task):586 # Set the force on the body to push it off the ridge587 # Add the deltaTime for the task to the accumulator588 self.deltaTimeAccumulator +=globalClock.getDt()589 if self.deltaTimeAccumulator < self.stepSize:590 return task.cont591592 self.space.autoCollide() # Setup the contact joints593 collisions=[]594 while self.deltaTimeAccumulator > self.stepSize:595 # Remove a stepSize from the accumulator until596 # the accumulated time is less than the stepsize597 self.deltaTimeAccumulator -= self.stepSize598 # Step the simulation599 self.world.quickStep(self.stepSize)600 cc=self.space.autoCollide() # Setup the contact joints601 if not self.supportEvent:602 # this is obsoleted, only for 1.5.4603 if cc > 0:604 for i in range(cc):605 p = Vec3(self.space.getContactData(i*3+0),self.space.getContactData(i*3+1),self.space.getContactData(i*3+2))606 collisions.append(p)607608 #cc = self.space.autoCollide() # Setup the contact joints609 for b_ode in self.objectlist:610 if isinstance(b_ode, ODEobjbase):611 if b_ode.isDynamic():612 np = b_ode.realObj613 if np != None:614 #body = b_ode.body615 body = b_ode.geom616 np.setPosQuat(render, body.getPosition(), Quat(body.getQuaternion()))617 if b_ode.mass > 0 and hasattr(b_ode, "motionfriction"):618 v = b_ode.body.getLinearVel()619 ma = -b_ode.motionfriction * b_ode.mass620 b_ode.body.addForce(ma*v[0],ma*v[1],ma*v[2])621 v = b_ode.body.getAngularVel()622 ma = (1-b_ode.angularfriction)623 b_ode.body.setAngularVel(ma*v[0],ma*v[1],ma*v[2])624 else:625 # a joint ?626 b_ode.Render()627 #for contact in self.contactgroup:628 # print contact629 self.contactgroup.empty() # Clear the contact joints630 if not self.supportEvent:631 self.notify(collisions)632 return task.cont633634 def simulationTask3(self,task):635 iterations = 5636 #We limit the maximum time not to receive explosion of physic system if application stuck637 dt=globalClock.getDt()638 if dt>0.02: dt=0.02639 dt=dt / iterations * 3640641 #Some iterations for the more stable simulation642 for i in xrange(iterations):643 self.world.quickStep(dt)644 cc=self.space.autoCollide()645 #Sync the box with the bodies646 for b_ode in self.objectlist:647 if isinstance(b_ode, ODEobjbase):648 if b_ode.isDynamic():649 np = b_ode.realObj650 if np != None:651 #body = b_ode.body652 body = b_ode.geom653 np.setPosQuat(render, body.getPosition(), Quat(body.getQuaternion()))654 if b_ode.mass > 0 and hasattr(b_ode, "motionfriction"):655 v = b_ode.body.getLinearVel()656 ma = -b_ode.motionfriction * b_ode.mass657 b_ode.body.addForce(ma*v[0],ma*v[1],ma*v[2])658 v = b_ode.body.getAngularVel()659 ma = (1-b_ode.angularfriction)660 b_ode.body.setAngularVel(ma*v[0],ma*v[1],ma*v[2])661 else:662 # a joint ?663 b_ode.Render()664 self.contactgroup.empty()665 return task.cont666667668 # Setup collision event669 def onCollision(self, entry):670 geom1 = entry.getGeom1()671 geom2 = entry.getGeom2()672 id1 = int(str(geom1).split(" ")[-1].rstrip(")"), 16)673 id2 = int(str(geom2).split(" ")[-1].rstrip(")"), 16)674 if id1 in self.collisionMap:675 id = id1676 geomn = geom2677 elif id2 in self.collisionMap:678 id = id2679 geomn = geom1680 else:681 return682 odeobject, func = self.collisionMap[id]683 func(odeobject, geomn, entry)684 #points = entry.getContactPoints()685 #body1 = entry.getBody1()686 #body2 = entry.getBody2()687688689 # The debug task for performance test690 def simulationTask4(self, task):691 # Set the force on the body to push it off the ridge692 # Add the deltaTime for the task to the accumulator693 self.deltaTimeAccumulator +=globalClock.getDt()694 if self.deltaTimeAccumulator < self.stepSize:695 return task.cont696697 #self.space.autoCollide() # Setup the contact joints698 collisions=[]699 while self.deltaTimeAccumulator > self.stepSize:700 # Remove a stepSize from the accumulator until701 # the accumulated time is less than the stepsize702 self.deltaTimeAccumulator -= self.stepSize703 # Step the simulation704 t1 = time.time()705 #for i in range(100):706 self.world.quickStep(self.stepSize)707 t12 = time.time()708 t2 = time.time()709 cc = self.space.autoCollide() # Setup the contact joints710 t22 = time.time()711 self.count += 1712 self.totaltime1 += t12 - t1713 self.totaltime2 += t22 - t2714 #print t2,t1715 #cc=self.space.autoCollide() # Setup the contact joints716 if self.count > 200:717 print "quickStep %f %0.3f" % (self.totaltime1, self.totaltime1 * 1000 / self.count)718 print "autocollide %f %0.3f" % (self.totaltime2, self.totaltime2 * 1000 / self.count)719 #print "cc %0.1f" % (self.totaltime2 / self.count)720 self.count = 0721 self.totaltime1 = 0.0722 self.totaltime2 = 0.0723 #if not self.supportEvent:724 # this is obsoleted, only for 1.5.4725 # if cc > 0:726 # for i in range(cc):727 # p = Vec3(self.space.getContactData(i*3+0),self.space.getContactData(i*3+1),self.space.getContactData(i*3+2))728 # collisions.append(p)729730 #cc = self.space.autoCollide() # Setup the contact joints731 if True:732 for b_ode in self.objectlist:733 if isinstance(b_ode, ODEobjbase):734 if b_ode.isDynamic():735 np = b_ode.realObj736 if np != None:737 #body = b_ode.body738 body = b_ode.geom739 #np.setPosQuat(render, body.getPosition(), Quat(body.getQuaternion()))740 np.setPosQuat(body.getPosition(), Quat(body.getQuaternion()))741 if False and b_ode.mass > 0 and hasattr(b_ode, "motionfriction"):742 v = b_ode.body.getLinearVel()743 ma = -b_ode.motionfriction * b_ode.mass744 b_ode.body.addForce(ma*v[0],ma*v[1],ma*v[2])745 v = b_ode.body.getAngularVel()746 ma = (1-b_ode.angularfriction)747 b_ode.body.setAngularVel(ma*v[0],ma*v[1],ma*v[2])748 else:749 # a joint ?750 b_ode.Render()751 #for contact in self.contactgroup:752 # print contact753 self.contactgroup.empty() # Clear the contact joints754 if not self.supportEvent:755 self.notify(collisions)756 return task.cont757758 # The task for our simulation759 def simulationTask5(self, task):760 # Set the force on the body to push it off the ridge761 # Add the deltaTime for the task to the accumulator762 self.deltaTimeAccumulator +=globalClock.getDt()763 if self.deltaTimeAccumulator < self.stepSize:764 return task.cont765766 collisions=[]767 while self.deltaTimeAccumulator > self.stepSize:768 # Remove a stepSize from the accumulator until769 # the accumulated time is less than the stepsize770 self.deltaTimeAccumulator -= self.stepSize771 # Step the simulation772 self.space.autoCollide() # Setup the contact joints773 self.world.quickStep(self.stepSize)774775 for b_ode in self.objectlist:776 if isinstance(b_ode, ODEobjbase):777 if b_ode.isDynamic():778 np = b_ode.realObj779 if np != None:780 #body = b_ode.body781 body = b_ode.geom782 np.setPosQuat(body.getPosition(), Quat(body.getQuaternion()))783 #if b_ode.mass > 0 and hasattr(b_ode, "motionfriction"):784 # v = b_ode.body.getLinearVel()785 # ma = -b_ode.motionfriction * b_ode.mass786 # b_ode.body.addForce(ma*v[0],ma*v[1],ma*v[2])787 # v = b_ode.body.getAngularVel()788 # ma = (1-b_ode.angularfriction)789 # b_ode.body.setAngularVel(ma*v[0],ma*v[1],ma*v[2])790 else:791 # a joint ?792 b_ode.Render()793 #for contact in self.contactgroup:794 # print contact795 self.contactgroup.empty() # Clear the contact joints796 if not self.supportEvent:797 self.notify(collisions)798 return task.cont799800801class ODEWorld_AutoHash(ODEWorld_Simple):802 def __init__(self):803 ODEWorld_Simple.__init__(self, ODEWorld_Simple.HASHSPACE)
...
AutoCharacter.py
Source:AutoCharacter.py
1import bpy2from AutoFactory import BL_Properties#AMProperties3from .RIG_Tool import *4class AutoLatticeShape(bpy.types.Operator):5 bl_idname = "am.autolatticeshape"6 bl_label = "AutoLatticeShape"7 bl_description = "éæ©å¤ä¸ªç©ä½ï¼å
¶ä¸æ´»å¨ç©ä½ä¸ºæ¶æ ¼ä½ï¼å
¶ä»ç为ç½æ ¼(å¨ç¼è¾æ¨¡å¼Né®å·¥å
·-é项ä¸å
³ééå)" 8 bl_options = {'REGISTER', 'UNDO'}9 def execute(self, context):10 amProperty = context.scene.amProperties11 sel = bpy.context.selected_objects12 Latticename=bpy.context.object.name13 ObjL_vertex_group=amProperty.LeftBodyGroupSTR#'LeftBody'#ç»äºå个ä¸å¿è¾¹ç¼ç¹50%æéï¼ä¸ä¸è¦æ¼é14 ObjR_vertex_group=amProperty.RightBodyGroupSTR#'RightBody'#ç»äºå个ä¸å¿è¾¹ç¼ç¹50%æéï¼ä¸ä¸è¦æ¼é15 vertex_group=amProperty.VertexGroupSTR16 17 ObjsName=[]18 sel.remove(bpy.context.active_object)19 for ob in sel:20 #if (ob.name!=ObjName) and (ob.type=='LATTICE'):21 ObjsName.append(ob.name)22 #ObjName=ob.name#'Human'23 Lattice=bpy.data.objects[Latticename]24 Lattice.data.name=Latticename25 LatticeData=bpy.data.lattices[Latticename]26 for ObjName in ObjsName:27 ObjShapeKeyList=[]28 29 RealObj=bpy.data.objects[ObjName]30 RealObjData=bpy.data.objects[ObjName].data31 #delete all shape key for duplicate32 bpy.context.view_layer.objects.active = RealObj33 RealObj.select_set(True)34 bpy.ops.object.shape_key_add(from_mix=False)35 bpy.ops.object.shape_key_remove(all=True)36 for shapekey in bpy.data.shape_keys:37 if shapekey.user == LatticeData:38 print(ObjName)39 print(shapekey.name)40 print(LatticeData.name)41 for key in shapekey.key_blocks:#bpy.data.shape_keys["Key.002"].key_blocks["Hand"].name = "Hand"42 key.value = 043 44 for key in shapekey.key_blocks:45 key.value = 100#make it max! 46 bpy.ops.object.select_all(action='DESELECT')47 bpy.context.view_layer.objects.active = RealObj48 RealObj.select_set(True)49 50 51 bpy.ops.object.duplicate_move(OBJECT_OT_duplicate={"linked":False, "mode":'TRANSLATION'}, TRANSFORM_OT_translate={"value":(0, 0, 0), "orient_type":'GLOBAL', "orient_matrix":((1, 0, 0), (0, 1, 0), (0, 0, 1)), "orient_matrix_type":'GLOBAL', "constraint_axis":(False, False, False), "mirror":True, "use_proportional_edit":False, "proportional_edit_falloff":'SMOOTH', "proportional_size":14.7843, "use_proportional_connected":False, "use_proportional_projected":False, "snap":False, "snap_target":'CLOSEST', "snap_point":(0, 0, 0), "snap_align":False, "snap_normal":(0, 0, 0), "gpencil_strokes":False, "cursor_transform":False, "texture_space":False, "remove_on_cancel":False, "release_confirm":False, "use_accurate":False, "use_automerge_and_split":False})52 RealObj.select_set(False)53 54 if RealObj.name.split('.')[0] in bpy.context.object.name:55 bpy.ops.object.apply_all_modifiers()56 57 bpy.context.object.name=bpy.context.object.name.split('.')[0]+'_'+key.name#è¥å
å«ä¸å线ä¼å»æãã58 key.value = 059 ObjShapeKeyList.append(bpy.context.object.name)60 61 bpy.ops.object.select_all(action='DESELECT')62 bpy.context.view_layer.objects.active = RealObj63 RealObj.select_set(True)64 bpy.ops.object.shape_key_add(from_mix=False)#add a Basis shapekey65 #RealObj.active_shape_key_index=066 print(ObjShapeKeyList)67 #å¦ææ¯æ¶æ ¼ä½å
å´å
¨èº«ééåçï¼68 if amProperty.LatticeMirrorBool==False:69 RealObj.active_shape_key_index=070 for shapekey in bpy.data.shape_keys:71 if shapekey.user == RealObjData:72 for ObjShapeName in ObjShapeKeyList:73 74 bpy.context.view_layer.objects.active = RealObj75 RealObj.select_set(True)76 77 bpy.data.objects[ObjShapeName].select_set(True)78 bpy.ops.object.join_shapes()79 bpy.data.objects[ObjShapeName].select_set(False)80 bpy.ops.object.select_all(action='DESELECT')81 for key in shapekey.key_blocks:82 key.value = 083 RealObj.active_shape_key_index=084 85 #for key in shapekey.key_blocks:86 for i in range(len(ObjShapeKeyList)):87 #int(next(ShapeCount))88 89 RealObj.active_shape_key_index+=190 91 shapename=RealObj.active_shape_key.name.split('_')[1]92 RealObj.active_shape_key.value=093 RealObj.active_shape_key.slider_min = -194 RealObj.active_shape_key.name=shapename95 RealObj.active_shape_key.vertex_group = vertex_group96 #å¦åæ§è¡ä»¥ä¸ ä¿®æ¹å¨ä¹éè¦åå²å·¦å³é¡¶ç¹ç» å¨ç¼è¾æ¨¡å¼ä¸å
³ééå!97 else:98 RealObj.active_shape_key_index=099 for shapekey in bpy.data.shape_keys:100 if shapekey.user == RealObjData:101 for ObjShapeName in ObjShapeKeyList:102 103 bpy.context.view_layer.objects.active = RealObj104 RealObj.select_set(True)105 106 bpy.data.objects[ObjShapeName].select_set(True)107 bpy.ops.object.join_shapes()108 bpy.ops.object.join_shapes()109 bpy.data.objects[ObjShapeName].select_set(False)110 bpy.ops.object.select_all(action='DESELECT')111 for key in shapekey.key_blocks:112 key.value = 0113 114 RealObj.active_shape_key_index=0115 116 #for key in shapekey.key_blocks:117 for i in range(len(ObjShapeKeyList)):118 #int(next(ShapeCount))119 120 RealObj.active_shape_key_index+=1121 shapename=RealObj.active_shape_key.name.split('_')[1]122 RealObj.active_shape_key.value=100123 RealObj.active_shape_key.slider_min = -1124 RealObj.active_shape_key.vertex_group = ObjL_vertex_group125 RealObj.active_shape_key_index+=1#MirrorShapekey126 RealObj.active_shape_key.value=100127 RealObj.active_shape_key.slider_min = -1128 RealObj.active_shape_key.vertex_group = ObjR_vertex_group129 shapeindex=RealObj.active_shape_key_index130 bpy.ops.object.shape_key_mirror(use_topology=False)131 132 bpy.ops.object.shape_key_add(from_mix=True)133 RealObj.active_shape_key.name=shapename134 RealObj.active_shape_key.slider_min = -1135 RealObj.active_shape_key_index=shapeindex#len(shapekey.key_blocks)136 bpy.ops.object.shape_key_remove(all=False)137 bpy.ops.object.shape_key_remove(all=False)138 if amProperty.DeleteShapeObjBool==True:139 bpy.ops.object.select_all(action='DESELECT')140 #å é¤å½¢ç¶é®ç½æ ¼ä½141 for ObjShapeName in ObjShapeKeyList:142 removeObj=bpy.data.objects[ObjShapeName]143 bpy.context.view_layer.objects.active = removeObj144 removeObj.select_set(True)145 bpy.ops.object.delete(use_global=False)146 self.report({'INFO'}, "Done")147 return {'FINISHED'}148class DefaultShapekey(bpy.types.Operator):149 bl_idname = "am.defaultshapekey"150 bl_label = "DefaultShapekey"151 bl_description = "å°æéç©ä½æ¥æçææå½¢ç¶é®è®¾ä¸º0" 152 bl_options = {'REGISTER', 'UNDO'}153 def execute(self, context):154 #obj=bpy.context.object155 RealObj=bpy.context.object156 RealObjData=RealObj.data157 for shapekey in bpy.data.shape_keys:158 if shapekey.user == RealObjData:159 for key in shapekey.key_blocks:#bpy.data.shape_keys["Key.002"].key_blocks["Hand"].name = "Hand"160 key.value = 0161 self.report({'INFO'}, "Done")162 return {'FINISHED'}163class ShapekeyDriver(bpy.types.Operator):164 bl_idname = "am.shapekeydriver"165 bl_label = "ShapekeyDriver"166 bl_description = "éæ©è³å°ä¸¤ä¸ªç©ä½ï¼åæ¥æéç©ä½è³æ´»å¨ç©ä½çéåå½¢ç¶é®" 167 bl_options = {'REGISTER', 'UNDO'}168 def execute(self, context):169 #Driver170 #obj=bpy.context.object171 #åè¿ ç´æ¥æ¿æ¥ç¨äºhttps://blender.stackexchange.com/questions/86757/python-how-to-connect-shapekeys-via-drivers172 selected_obj = bpy.context.selected_objects173 active_obj = bpy.context.active_object174 shapekey_list_string = str(active_obj.data.shape_keys.key_blocks.keys())175 for obj in selected_obj:176 if not obj == active_obj:177 for key in obj.data.shape_keys.key_blocks:178 if key.name.lstrip(obj.name) in shapekey_list_string:179 if not key.name == "Basis":180 skey_driver = key.driver_add('value')181 skey_driver.driver.type = 'AVERAGE'182 # skey_driver.driver.show_debug_info = True183 newVar = skey_driver.driver.variables.new()184 newVar.name = "var"185 newVar.type = 'SINGLE_PROP'186 newVar.targets[0].id_type = 'KEY'187 newVar.targets[0].id = active_obj.data.shape_keys188 newVar.targets[0].data_path = 'key_blocks["' + key.name.lstrip(obj.name)+ '"].value' 189 # litlle change was made here by deleting the active object name for the path190 #add_driver(SourceType,Source,SourceDataPath,SourceIndex,expType,exp,TargetNum,FuncName,FuncType,TargetType,targetName,TargetDataPath,transform_type,transform_space,rotation_mode)191 #add_driver('OBJECT',RealObj.name,0,SourceIndex,expType,exp,TargetNum,FuncName,FuncType,TargetType,targetName,TargetDataPath,transform_type,transform_space,rotation_mode)192 self.report({'INFO'}, "Done")193 return {'FINISHED'}194class TransferAllKey(bpy.types.Operator):195 bl_idname = "am.transferallkey"196 bl_label = "TransferAllKey"197 bl_description = "éæ©ä¸¤ä¸ªç©ä½ï¼ä¼ éææå½¢æé®å°æ´»å¨ç©ä½(éç¨äºåæ¶æ ¼ä½æä¸è¯å«çéåç©ä½)" 198 bl_options = {'REGISTER', 'UNDO'}199 def execute(self, context):200 sel = bpy.context.selected_objects201 amProperty = context.scene.amProperties202 ActObj=bpy.context.active_object203 vertex_group=amProperty.VertexGroupSTR204 bpy.context.active_object205 sel.remove(bpy.context.active_object)206 for ob in sel:207 if (ob.name!=bpy.context.active_object) and (ob.type=='MESH'):208 selObj=ob209 selObj.active_shape_key_index = 0210 #bpy.context.active_object.data.shape_keys211 #selObj.active_shape_key212 for i in range(len(selObj.data.shape_keys.key_blocks)):213 selObj.active_shape_key_index=i214 bpy.ops.object.shape_key_transfer()215 ActObj.active_shape_key.vertex_group = selObj.active_shape_key.vertex_group216 #bpy.data.shape_keys["Key.015"].key_blocks["TriangleUP"].slider_min = -1217 ActObj.active_shape_key.slider_min = -1218 #bpy.context.object.active_shape_key_index = 0219 bpy.context.object.show_only_shape_key = False220 221 self.report({'INFO'}, "Done")222 return {'FINISHED'}223class BlendKey(bpy.types.Operator):224 bl_idname = "am.blendkey"225 bl_label = "BlendKey"226 bl_description = "å°æ´»å¨ç©ä½ç¸ä¼¼å称ä¸ç¸åæåºå½¢æé®å并(éç¨äºåæ¶æ ¼ä½æä¸è¯å«çéåç©ä½)" 227 bl_options = {'REGISTER', 'UNDO'}228 def execute(self, context):229 ActObj=bpy.context.active_object230 ActObj.active_shape_key_index = 0231 #ActObj.active_shape_key.name232 maxmirror=len(ActObj.data.shape_keys.key_blocks)233 for i in range(int(maxmirror/2)):234 #if '_blend' not in ActObj.active_shape_key.name:235 ActObj.active_shape_key_index = i236 onekey=ActObj.active_shape_key237 onekey.value=100238 onekey.slider_min = -1239 oneName=ActObj.active_shape_key.name240 ActObj.active_shape_key_index = i+int(maxmirror/2)241 twokey=ActObj.active_shape_key242 twokey.value=100243 twokey.slider_min = -1244 bpy.ops.object.shape_key_add(from_mix=True)245 ActObj.active_shape_key.name=oneName+'_blend'246 ActObj.active_shape_key.slider_min = -1247 onekey.value=0248 twokey.value=0249 '''250 for key in ActObj.data.shape_keys.key_blocks:#è¿äºå°æ¹æé®é¢251 if (oneName in key.name) and(oneName != key.name):252 twokey=key253 twokey.value=100254 bpy.ops.object.shape_key_add(from_mix=True)255 ActObj.active_shape_key.name=oneName+'_blend'256 onekey.value=0257 if twokey.name in ActObj.data.shape_keys.key_blocks:258 twokey.value=0259 '''260 bpy.context.object.active_shape_key_index = maxmirror-1261 #ActObj.active_shape_key_index=maxmirror262 for i in range(maxmirror):263 bpy.ops.object.shape_key_remove(all=False)264 for key in ActObj.data.shape_keys.key_blocks:265 key.name=key.name.split('_')[0]266 self.report({'INFO'}, "Done")267 return {'FINISHED'}268class Bonelayered(bpy.types.Operator):269 bl_idname = "am.bonelayered"270 bl_label = "Bonelayered"271 bl_description = "åæ¢å½¢å,å°å称ææé骨骼ååééè¿å¼å
³å½¢åçæ¹å¼è¿è¡éª¨éª¼åå±åæ¢ï¼æå©äºæ´æ¢èº«ä½é¨ä½ï¼ä¾å¦å¤´ä¸èº«ä½çå离ï¼éæ¶æ¿æ¢ä¿®æ¹å¯¼åº"#å¼å
³å½¢åä¸å¤ªçæ³"åæ¢å½¢åï¼ä¾å¦ï¼è¾å
¥æ°å'22,23'为åæ¢22ï¼23å±å½¢åï¼è¾å
¥éª¨éª¼å称Faceåå°åæ¢å®ä¸åéçå½¢å"# #ï¼å¯¹äºå¸¦å½¢ç¶é®çç©ä½æ æ³åºç¨ä¿®æ¹å¨ããï¼272 bl_options = {'REGISTER', 'UNDO'}273 def execute(self, context):274 amProperty = context.scene.amProperties275 #bpy.ops.object.mode_set(mode='OBJECT')276 bpy.ops.object.mode_set(mode='EDIT')277 if amProperty.BoneSTR.isdigit() :278 bpy.context.object.data.edit_bones.active=None279 bpy.ops.armature.select_all(action='DESELECT')280 for i in range(31):281 bpy.context.object.data.layers[i] = False282 #MakeSureSelectOneLayer(int(amProperty.BoneSTR))283 bpy.context.object.data.layers[int(amProperty.BoneSTR)]=True284 bpy.ops.armature.select_all(action='SELECT')285 for bone in bpy.context.selected_bones:286 #if bone.layer[int(amProperty.BoneSTR)] == True:287 bpy.context.object.data.edit_bones.active=bone288 if bone.use_deform == False:289 bone.use_deform = True290 else:291 bone.use_deform = False292 bpy.context.object.data.layers[int(amProperty.BoneSTR)]=False293 elif ',' in amProperty.BoneSTR:294 bpy.context.object.data.edit_bones.active=None295 bpy.ops.armature.select_all(action='DESELECT')296 Boneslayer=amProperty.BoneSTR.split(',')297 for bonelayer in Boneslayer:298 for i in range(31):299 bpy.context.object.data.layers[i] = False300 bpy.context.object.data.layers[int(bonelayer)]=True301 bpy.ops.armature.select_all(action='SELECT')302 for bone in bpy.context.selected_bones:303 bpy.context.object.data.edit_bones.active=bone304 if bone.use_deform == False:305 bone.use_deform = True306 else:307 bone.use_deform = False308 bpy.context.object.data.layers[int(bonelayer)]=False309 elif amProperty.BoneSTR!='':310 SelectBone(amProperty.BoneSTR)311 parentbone=bpy.context.active_bone312 parentbonename=bpy.context.active_bone.name313 #éæ©face314 #alt ç¹å» å½¢åï¼315 bpy.ops.armature.select_similar(type='CHILDREN')316 if parentbone.use_deform == True:#bpy.context.object.data.edit_bones[parentbonename]317 for bone in bpy.context.selected_bones:318 #if bone.use_deform == True:319 bone.use_deform = False320 #else:321 else:322 for bone in bpy.context.selected_bones:323 bone.use_deform = True324 bpy.ops.armature.select_all(action='DESELECT')325 SelectBone(parentbonename)326 bpy.context.object.data.edit_bones[parentbonename]327 bpy.ops.object.mode_set(mode='OBJECT')328 329 self.report({'INFO'}, "Done")...
capturepython.py
Source:capturepython.py
1""" Generic front end module to all forms of Python interception"""2import sys, os, logging, inspect, types3from distutils.sysconfig import get_python_lib4from . import pythonclient, config5class CallStackChecker:6 def __init__(self, rcHandler):7 # Always ignore our own command-line capture module8 # TODO - ignore_callers list should be able to vary between different calls9 self.ignoreModuleCalls = set([ "capturecommand" ] + rcHandler.getList("ignore_callers", [ "python" ]))10 self.excludeLevel = 011 self.inCallback = False12 self.logger = logging.getLogger("Call Stack Checker")13 self.stdlibDirs = self.findStandardLibDirs()14 self.logger.debug("Found stdlib directories at " + repr(self.stdlibDirs))15 self.logger.debug("Ignoring calls from " + repr(self.ignoreModuleCalls))16 def callNoInterception(self, callback, method, *args, **kw):17 delta = -1 if callback else 118 self.excludeLevel += delta19 if callback:20 self.inCallback = True21 try:22 return method(*args, **kw)23 finally:24 self.excludeLevel -= delta25 if callback:26 self.inCallback = False27 28 def findStandardLibDirs(self):29 dirs = [ get_python_lib(standard_lib=True, prefix=sys.prefix) ]30 if hasattr(sys, "real_prefix"): # virtualenv31 dirs.append(get_python_lib(standard_lib=True, prefix=sys.real_prefix))32 return [ os.path.normcase(os.path.realpath(d)) for d in dirs ]33 34 def callerExcluded(self, stackDistance=1, callback=False):35 if (callback and self.excludeLevel < 0) or (not callback and self.excludeLevel > 0):36 # If we get called recursively, must call the real thing to avoid infinite loop...37 return True38 # Don't intercept if we've been called from within the standard library39 self.excludeLevel += 140 41 framerecord = inspect.stack()[stackDistance]42 fileName = framerecord[1]43 dirName = self.getDirectory(fileName)44 moduleName = self.getModuleName(fileName)45 moduleNames = set([ moduleName, os.path.basename(dirName) ])46 self.logger.debug("Checking call from " + dirName + ", modules " + repr(moduleNames))47 self.excludeLevel -= 148 return dirName in self.stdlibDirs or len(moduleNames.intersection(self.ignoreModuleCalls)) > 049 def getModuleName(self, fileName):50 given = inspect.getmodulename(fileName)51 if given == "__init__":52 return os.path.basename(os.path.dirname(fileName))53 else:54 return given55 def getDirectory(self, fileName):56 dirName, local = os.path.split(os.path.normcase(os.path.realpath(fileName)))57 if local.startswith("__init__"):58 return self.getDirectory(dirName)59 else:60 return dirName61 def moduleExcluded(self, modName, mod):62 if not hasattr(mod, "__file__") or mod.__file__ is None:63 return False64 65 modFile = os.path.normcase(os.path.realpath(mod.__file__))66 return any((modFile.startswith(stdlibDir) for stdlibDir in self.stdlibDirs)) or \67 modName.split(".")[0] in self.ignoreModuleCalls68 69class ImportHandler:70 def __init__(self, moduleNames, callStackChecker, trafficHandler):71 self.moduleNames = moduleNames72 self.interceptedNames = set()73 self.callStackChecker = callStackChecker74 self.trafficHandler = trafficHandler75 self.handleImportedModules()76 def handleImportedModules(self):77 for modName in self.moduleNames:78 if modName in sys.modules:79 # Fix global imports in other modules80 oldModule = sys.modules.get(modName)81 for currModName in [ modName ] + self.findSubModules(modName, oldModule):82 loadingMods = self.modulesLoading(currModName, modName)83 if loadingMods:84 newModule = pythonclient.ModuleProxy(currModName, self.trafficHandler, sys.modules.get)85 sys.modules[currModName] = newModule86 for attrName, otherMod in loadingMods:87 varName = otherMod.__name__ + "." + attrName88 print("WARNING: having to reset the variable '" + varName + "'.\n" + \89 "This implies you are intercepting the module '" + modName + "'" + \90 " after importing it.\nWhile this might work, it may well be very slow and " + \91 "is not recommended.\n")92 setattr(otherMod, attrName, newModule)93 else:94 del sys.modules[currModName]95 def findSubModules(self, modName, oldModule):96 subModNames = []97 if not hasattr(oldModule, "__file__"):98 return subModNames99 dirName = os.path.dirname(self.getModuleFile(oldModule))100 for subModName, subMod in sys.modules.items():101 if subModName.startswith(modName + ".") and hasattr(subMod, "__file__") and \102 self.getModuleFile(subMod).startswith(dirName):103 subModNames.append(subModName)104 return subModNames105 106 def getModuleFile(self, mod):107 if hasattr(mod, "captureMockTarget"):108 return mod.captureMockTarget.__file__109 else:110 return mod.__file__111 def modulesLoading(self, modName, interceptModName):112 modules = []113 oldModule = sys.modules.get(modName)114 for otherName, otherMod in sys.modules.items():115 if not otherName.startswith("capturemock") and \116 not otherName.startswith(interceptModName + ".") and \117 not isinstance(otherMod, pythonclient.ModuleProxy) and \118 not self.callStackChecker.moduleExcluded(otherName, otherMod):119 modAttrName = self.findAttribute(otherMod, oldModule)120 if modAttrName:121 modules.append((modAttrName, otherMod))122 return modules123 def findAttribute(self, module, attr):124 # Can't assume the attribute will have the same name of the module,125 # because of "import x as y" construct126 for currAttrName in dir(module):127 if getattr(module, currAttrName, None) is attr:128 return currAttrName129 def shouldIntercept(self, name):130 # Never try to intercept anything if it's blocked for some reason131 if self.callStackChecker.excludeLevel:132 return False133 if name in self.moduleNames:134 return True135 elif "." in name:136 for modName in self.moduleNames:137 if name.startswith(modName + "."):138 return True139 return False140 141 def find_module(self, name, *args):142 if self.shouldIntercept(name):143 return self144 def load_module(self, name):145 self.interceptedNames.add(name)146 return sys.modules.setdefault(name, self.createProxy(name))147 def createProxy(self, name):148 return pythonclient.ModuleProxy(name, self.trafficHandler, self.loadRealModule)149 150 def loadRealModule(self, name):151 oldMod = None152 if name in sys.modules:153 oldMod = sys.modules.get(name)154 del sys.modules[name]155 sys.meta_path.remove(self)156 try:157 # This is a bit weird, but it's apparently necessary in python 3...158 # See http://bugs.python.org/issue6862159 cmd = "import " + name + " as _realModule"160 d = {}161 exec(cmd, d)162 _realModule = d["_realModule"]163 finally:164 sys.meta_path.insert(0, self)165 if name in sys.modules:166 if oldMod is not None:167 sys.modules[name] = oldMod168 else:169 del sys.modules[name]170 self.interceptImportedPackageSubmodules(name, _realModule)171 return _realModule172 def reset(self):173 for modName in self.interceptedNames:174 if modName in sys.modules:175 del sys.modules[modName]176 sys.meta_path.remove(self)177 def interceptImportedPackageSubmodules(self, name, realModule):178 """ Handle the situation where intercepted package A is preloaded, and intercepted module B imports submodules of A """179 for submodule in self.getImportedPackageSubmodules(name, realModule):180 proxy = pythonclient.ModuleProxy(submodule, self.trafficHandler, sys.modules.get)181 sys.modules[submodule] = proxy182 self.interceptedNames.add(submodule)183 parts = submodule.rsplit(".", 1)184 parentModule = sys.modules.get(parts[0])185 if parentModule is not None:186 setattr(parentModule, parts[1], proxy)187 188 def getImportedPackageSubmodules(self, name, realModule):189 submodules = []190 for other in self.interceptedNames:191 if other == name or not name.startswith(other):192 otherModule = realModule if other == name else sys.modules.get(other)193 for subModName in self.findSubModules(other, otherModule):194 if not isinstance(sys.modules.get(subModName), pythonclient.ModuleProxy):195 submodules.append(subModName)196 return submodules197def interceptPython(*args, **kw):198 handler = InterceptHandler(*args, **kw)199 handler.makeIntercepts()200 return handler201# Workaround for stuff where we can't do setattr202class TransparentProxy:203 def __init__(self, obj):204 self.obj = obj205 def __call__(self, *args, **kw):206 return self.obj(*args, **kw)207 208 def __getattr__(self, name):209 return getattr(self.obj, name)210class InterceptHandler:211 def __init__(self, mode, recordFile, replayFile, rcFiles, pythonAttrs):212 self.attributesIntercepted = []213 self.rcHandler = config.RcFileHandler(rcFiles)214 # Has too many side effects, because our log configuration file may conflict with the application's logging set up. Need to find another way.215 #self.rcHandler.setUpLogging()216 from . import replayinfo217 self.replayInfo = replayinfo.ReplayInfo(mode, replayFile, self.rcHandler)218 self.recordFile = recordFile219 self.allAttrNames = self.findAttributeNames(mode, pythonAttrs)220 def findAttributeNames(self, mode, pythonAttrs):221 rcAttrs = self.rcHandler.getIntercepts("python")222 if mode == config.REPLAY:223 return pythonAttrs + [attr for attr in rcAttrs if attr in self.replayInfo.replayItems]224 else:225 return pythonAttrs + rcAttrs226 def classifyIntercepts(self):227 fullIntercepts = []228 partialIntercepts = {}229 for attrName in self.allAttrNames:230 if "." in attrName:231 moduleName, subAttrName = self.splitByModule(attrName)232 if moduleName:233 if subAttrName:234 partialIntercepts.setdefault(moduleName, []).append(subAttrName)235 else:236 del sys.modules[attrName] # We imported the real version, get rid of it again...237 fullIntercepts.append(attrName)238 else:239 fullIntercepts.append(attrName)240 return fullIntercepts, partialIntercepts241 def makeIntercepts(self):242 fullIntercepts, partialIntercepts = self.classifyIntercepts()243 if len(fullIntercepts) == 0 and len(partialIntercepts) == 0:244 # Don't construct PythonTrafficHandler, which will delete any existing files245 return246 callStackChecker = CallStackChecker(self.rcHandler)247 from .pythontraffic import PythonTrafficHandler248 trafficHandler = PythonTrafficHandler(self.replayInfo, self.recordFile, self.rcHandler,249 callStackChecker, self.allAttrNames)250 if len(fullIntercepts):251 import_handler = ImportHandler(fullIntercepts, callStackChecker, trafficHandler)252 if import_handler not in sys.meta_path:253 sys.meta_path.insert(0, import_handler)254 for moduleName, attributes in partialIntercepts.items():255 self.interceptAttributes(moduleName, attributes, trafficHandler)256 def splitByModule(self, attrName):257 if self.canImport(attrName):258 return attrName, ""259 elif "." in attrName:260 parentName, localName = attrName.rsplit(".", 1)261 parentModule, parentAttr = self.splitByModule(parentName)262 if parentAttr:263 localName = parentAttr + "." + localName264 return parentModule, localName265 else:266 return "", "" # Cannot import any parent, so don't do anything267 def canImport(self, moduleName):268 try:269 exec("import " + moduleName)270 return True271 except ImportError:272 return False273 def interceptAttributes(self, moduleName, attrNames, trafficHandler):274 for attrName in attrNames:275 self.interceptAttribute(moduleName, trafficHandler,276 sys.modules.get(moduleName), attrName)277 278 def interceptAttribute(self, proxyName, trafficHandler, realObj, attrName):279 parts = attrName.split(".", 1)280 currAttrName = parts[0]281 if not hasattr(realObj, currAttrName):282 return # If the real object doesn't have it, assume the fake one doesn't either...283 if len(parts) == 1:284 if type(realObj) == types.ModuleType:285 proxy = pythonclient.ModuleProxy(proxyName, trafficHandler, sys.modules.get, realObj)286 else:287 proxy = pythonclient.PythonProxy(proxyName, trafficHandler, realObj, sys.modules)288 self.performAttributeInterception(realObj, currAttrName, getattr(proxy, currAttrName))289 else:290 currRealAttr = getattr(realObj, currAttrName)291 newProxyName = proxyName + "." + parts[0]292 try:293 self.interceptAttribute(newProxyName, trafficHandler, currRealAttr, parts[1])294 except TypeError: # it's a builtin (assume setattr threw), so we hack around...295 realAttrProxy = TransparentProxy(currRealAttr)296 self.interceptAttribute(newProxyName, trafficHandler, realAttrProxy, parts[1])297 self.performAttributeInterception(realObj, currAttrName, realAttrProxy)298 def performAttributeInterception(self, realObj, attrName, proxy):299 origValue = getattr(realObj, attrName)300 setattr(realObj, attrName, proxy)301 self.attributesIntercepted.append((realObj, attrName, origValue))302 def resetIntercepts(self):303 for item in sys.meta_path:304 if isinstance(item, ImportHandler):305 item.reset()306 for realObj, attrName, origValue in self.attributesIntercepted:...
test_context.py
Source:test_context.py
...72def contextobj(loaded_context, realobj):73 setattr(loaded_context, "obj", realobj)74 return ContextAttributeProxy("obj")75@pytest.fixture76def realobj():77 class Object(object):78 __attr__ = object()79 attr = object()80 return Object()81@pytest.fixture82def loaded_context():83 returned = Context()84 context.push(returned)85 return returned86@pytest.fixture(autouse=True, scope="function")87def pop_all(request):88 @request.addfinalizer89 def cleanup(): # pylint: disable=unused-variable90 while len(context._stack) > 1: # pylint: disable=protected-access...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!