Example #1
0
    def load(self):
        DistributedPartyFireworksActivity.notify.debug('load')
        DistributedPartyActivity.load(self)
        self.eventId = PartyGlobals.FireworkShows.Summer
        self.launchPadModel = loader.loadModel('phase_13/models/parties/launchPad')
        self.launchPadModel.setH(90.0)
        self.launchPadModel.setPos(0.0, -18.0, 0.0)
        self.launchPadModel.reparentTo(self.root)
        railingsCollection = self.launchPadModel.findAllMatches('**/launchPad_mesh/*railing*')
        for i in xrange(railingsCollection.getNumPaths()):
            railingsCollection[i].setAttrib(AlphaTestAttrib.make(RenderAttrib.MGreater, 0.75))

        leverLocator = self.launchPadModel.find('**/RocketLever_locator')
        self.lever.setPosHpr(Vec3.zero(), Vec3.zero())
        self.lever.reparentTo(leverLocator)
        self.toonPullingLeverInterval = None
        self.sign.reparentTo(self.launchPadModel.find('**/launchPad_sign_locator'))
        self.rocketActor = Actor('phase_13/models/parties/rocket_model', {'launch': 'phase_13/models/parties/rocket_launch'})
        rocketLocator = self.launchPadModel.find('**/rocket_locator')
        self.rocketActor.reparentTo(rocketLocator)
        self.rocketActor.node().setBound(OmniBoundingVolume())
        self.rocketActor.node().setFinal(True)
        effectsLocator = self.rocketActor.find('**/joint1')
        self.rocketExplosionEffect = RocketExplosion(effectsLocator, rocketLocator)
        self.rocketParticleSeq = None
        self.launchSound = base.loader.loadSfx('phase_13/audio/sfx/rocket_launch.ogg')
        self.activityFSM = FireworksActivityFSM(self)
        self.activityFSM.request('Idle')
        return
 def setup(self):
   
   # setting up sector entry plane
   self.detection_plane_ = self.attachNewNode(BulletRigidBodyNode(self.getName() + 'entry-plane'))
   
   box_shape =  BulletBoxShape(SECTOR_PLANE_SIZE/2)
   box_shape.setMargin(SECTOR_COLLISION_MARGIN)    
   self.detection_plane_.node().addShape(box_shape)
   self.detection_plane_.node().setMass(0)
   self.detection_plane_.setPos(self,SECTOR_PLANE_POS)
   self.detection_plane_.node().setIntoCollideMask(SECTOR_ENTERED_BITMASK)
   self.physics_world_.attach(self.detection_plane_.node())    
   self.detection_plane_.node().clearBounds()
   self.detection_plane_.reparentTo(self.getParent())
   
   # sector constraint plane
   self.constraint_plane_ = self.attachNewNode(BulletRigidBodyNode(self.getName()+ 'constraint-plane'))
   self.constraint_plane_.node().addShape(BulletPlaneShape(Vec3(0,1,0),0))
   self.constraint_plane_.node().setMass(0)
   self.constraint_plane_.setPos(Vec3.zero())
   self.constraint_plane_.setHpr(Vec3.zero())
   self.constraint_plane_.node().setIntoCollideMask(BitMask32.allOff())
   self.physics_world_.attach(self.constraint_plane_.node())
   self.constraint_plane_.reparentTo(self.getParent())
       
   # setting up objects
   self.setupBoxes()
   self.setupPlatforms()
Example #3
0
 def face(self, direction):
     """Makes Equismo look at a given the direction.
     This method makes only heading rotations.
     
     `direction': vector
     """
     
     direction = Vec3(direction.x, direction.y, 0)
     
     if direction != Vec3.zero():
         direction.normalize()
         
         currentDirection = self._currentDirection
         
         headingAngle = direction.signedAngleDeg(currentDirection, 
                                                 Vec3.down())
         headingAngle += self._currentAngle
         
         if abs(headingAngle) > 1:
             interval = self.model.hprInterval(self._turningSpeed,
                                               Point3(headingAngle, 0, 0))
             interval.start()
             
             self._currentDirection = direction
             self._currentAngle = headingAngle
Example #4
0
 def _constrain_axis(self, body):
     """ Apply existing axis constraints to a body."""
     # Set displacements.
     for axis, (f, d) in enumerate(zip(self.axis_constraint_fac,
                                       self.axis_constraint_disp)):
         if not f and not isnan(d):
             nodep = NodePath(body)
             pos = nodep.getPos()
             pos[axis] = d
             nodep.setPos(pos)
     try:
         # Linear and angular factors of 0 mean forces in the
         # corresponding axis are scaled to 0.
         body.setLinearFactor(self.axis_constraint_fac)
         # Angular factors restrict rotation about an axis, so the
         # following logic selects the appropriate axes to
         # constrain.
         s = sum(self.axis_constraint_fac)
         if s == 3.:
             v = self.axis_constraint_fac
         elif s == 2.:
             v = -self.axis_constraint_fac + 1
         else:
             v = Vec3.zero()
         body.setAngularFactor(v)
     except AttributeError:
         # The body was not a rigid body (it didn't have
         # setLinearFactor method).
         pass
Example #5
0
    def checkTarget(self):
        """
        Gets and stores data and conditions pertaining to the current target.
        Returns true if the target LKP was updated.
        """

        updatedLKP = False
        self.clearConditions(COND_TARGET_FACING_ME)

        if not self.isPlayerVisible(self.target.entity, False, False):
            assert not self.hasConditions(COND_SEE_TARGET), "COND_SEE_TARGET is set, but target is not visible."
            self.setConditions(COND_TARGET_OCCLUDED)
        else:
            self.clearConditions(COND_TARGET_OCCLUDED)

        isDead = True
        try:
            isDead = self.target.entity.getHealth() <= 0
        except: pass

        if isDead:
            self.setConditions(COND_TARGET_DEAD)
            self.clearConditions(COND_SEE_TARGET | COND_TARGET_OCCLUDED)
            self.clearTarget()
            return False

        targetPos = self.target.entity.getPos(render)
        distToTarget = (targetPos - self.getPos(render)).lengthSquared()

        if self.hasConditions(COND_SEE_TARGET):
            self.target.lastKnownPosition = targetPos
            updatedLKP = True

            # Alright, we can see the player, but can the player see us?
            if self.isPlayerInVisionCone_FromPlayer(self.target.entity):
                self.setConditions(COND_TARGET_FACING_ME)
            else:
                self.clearConditions(COND_TARGET_FACING_ME)

            if self.target.entity.movementDelta != Vec3.zero():
                # trail the enemy a bit
                self.target.lastKnownPosition = (
                    self.target.lastKnownPosition - self.target.entity.movementDelta * random.uniform(-0.05, 0)
                )
        elif not self.hasConditions(COND_TARGET_OCCLUDED|COND_SEE_TARGET) and distToTarget <= 256:
            # if the target is not occluded, and unseen, that means it is behind or beside us
            # let us know where the target is
            updatedLKP = True
            self.target.lastKnownPosition = targetPos

        if distToTarget >= self.MAX_VISION_DISTANCE_SQR:
            # Target is very far from us
            self.setConditions(COND_TARGET_TOOFAR)
        else:
            self.clearConditions(COND_TARGET_TOOFAR)

        if self.canCheckAttacks():
            self.checkAttacks(distToTarget)

        return updatedLKP
Example #6
0
    def face(self, direction):
        """Makes Equismo look at a given the direction.
        This method makes only heading rotations.
        
        `direction': vector
        """

        direction = Vec3(direction.x, direction.y, 0)

        if direction != Vec3.zero():
            direction.normalize()

            currentDirection = self._currentDirection

            headingAngle = direction.signedAngleDeg(currentDirection,
                                                    Vec3.down())
            headingAngle += self._currentAngle

            if abs(headingAngle) > 1:
                interval = self.model.hprInterval(self._turningSpeed,
                                                  Point3(headingAngle, 0, 0))
                interval.start()

                self._currentDirection = direction
                self._currentAngle = headingAngle
 def __estimateSize__(self):
   minp = LPoint3.zero()
   maxp = LPoint3.zero()
   size = Vec3.zero()
   if self.calcTightBounds(minp,maxp):
     size = maxp - minp
     
   return size 
 def addLedge(self,ledge, pos = Vec3.zero()):
   
   if type(ledge) is not Ledge:
     logging.error("Object is not a Ledge instance")
     return False
   
   ledge.reparentTo(self)
   ledge.setPos(pos)
   self.ledges_.append(ledge)
   
   return True    
  def addBox(self,name,size,pos,visual):

    # Box (dynamic)
    box = NodePath(BulletRigidBodyNode(name))
    box.node().setMass(1.0)
    box.node().addShape(BulletBoxShape(size))
    box.setCollideMask(GAME_OBJECT_BITMASK)
    #box.node().setLinearFactor((1,0,1))
    #box.node().setAngularFactor((0,1,0))
    visual.instanceTo(box)
    box.reparentTo(self.getParent())    
    box.setPos(self,pos)
    box.setHpr(self,Vec3.zero())

    self.physics_world_.attachRigidBody(box.node())
    self.object_nodes_.append(box)
    
    # adding constraint
    motion2d_constraint = BulletGenericConstraint(self.constraint_plane_.node(),box.node(),
                                        TransformState.makeIdentity(),
                                        TransformState.makeIdentity(),
                                        False)
    
    rot_constraint = BulletGenericConstraint(self.constraint_plane_.node(),box.node(),
                                        TransformState.makeIdentity(),
                                        TransformState.makeIdentity(),
                                        False)
    

 
    motion2d_constraint.setLinearLimit(0,-sys.float_info.max,sys.float_info.max)
    motion2d_constraint.setLinearLimit(1,0,0)
    motion2d_constraint.setLinearLimit(2,-sys.float_info.max,sys.float_info.max)
    
    # All angular constraints must be either locked or released for the simulation to be stable
    #motion2d_constraint.setAngularLimit(0,-0.1,0.1) 
    #motion2d_constraint.setAngularLimit(1,-100,100)
    #motion2d_constraint.setAngularLimit(2,-0.1,0.1)
    
    #motion2d_constraint.setBreakingThreshold(1000)
    motion2d_constraint.setDebugDrawSize(0)
    
#     for axis in range(0,6):
#       motion2d_constraint.setParam(BulletGenericConstraint.CP_cfm,0,axis)
#       motion2d_constraint.setParam(BulletGenericConstraint.CP_erp,0.4,axis)
    
    self.physics_world_.attach(motion2d_constraint)
    self.box_contraints_.append(motion2d_constraint)
    
    return box
Example #10
0
    def keybControl(self, dt):
        move = self.spd_forward * dt
        vel = Vec3(0, 0, 0)

        if self.keys['up']: vel += self.up(move)
        if self.keys['down']: vel += self.down(move)
        if self.keys['right']: vel += self.right(move)
        if self.keys['left']: vel += self.left(move)

        ###self.avatar.setPos(self.avatar.getPos()+vel)
        self.avatar.setFluidPos(self.avatar.getPos() + vel)
        if self.lockY != None: self.avatar.setY(self.lockY)
        if (vel != Vec3.zero()): self.walk(dt, vel)
        if self.keys['jump']: self.jump(dt)
 def __init__(self,camera_np, name = "CameraController"):
   NodePath.__init__(self,name)
   
   self.target_np_ = None    
   self.camera_np_ = camera_np
   self.target_tracker_np_ = self.attachNewNode("TargetTrackerNode") 
   self.enabled_ = True  
   self.smoothing_ = False
   self.target_ref_np_ = None
   
   # position tracking
   self.target_locked_ = True
   
   # rotation tracking
   self.rot_pr_target_ = Vec3.zero()
   self.rot_interpolation_sequence_ = Sequence()
  def addPlatform(self,topleft,size,name,visual):

    # Box (static)
    platform = self.getParent().attachNewNode(BulletRigidBodyNode(name))   
    platform.node().setMass(0)
    platform.node().addShape(BulletBoxShape(size/2))
    platform.setPos(self,Vec3(topleft[0] + 0.5*size.getX(),0,topleft[1]-0.5*size.getZ()))
    platform.setHpr(self,Vec3.zero())
    platform.setCollideMask(GAME_OBJECT_BITMASK)
    local_visual = visual.instanceUnderNode(platform,name + '_visual')
    local_visual.reparentTo(platform)
    
    # Visual scaling
    bounds = local_visual.getTightBounds()
    extents = Vec3(bounds[1] - bounds[0])
    scale_factor = 1/max([extents.getX(),extents.getY(),extents.getZ()])
    local_visual.setScale(size.getX()*scale_factor,size.getY()*scale_factor,size.getZ()*scale_factor)    

    self.physics_world_.attachRigidBody(platform.node())
    self.object_nodes_.append(platform)
Example #13
0
    def getResizedBoxCoordinates(self, vp):
        if self.state.action != BoxAction.Resizing and self.state.action != BoxAction.Drawing:
            return [self.state.boxStart, self.state.boxEnd]
        now = base.snapToGrid(vp.viewportToWorld(vp.getMouse()))
        cstart = vp.flatten(self.state.boxStart)
        cend = vp.flatten(self.state.boxEnd)

        # Proportional scaling
        ostart = vp.flatten(self.state.preTransformBoxStart if self.state.
                            preTransformBoxStart else Vec3.zero())
        oend = vp.flatten(self.state.preTransformBoxEnd if self.state.
                          preTransformBoxEnd else Vec3.zero())
        owidth = oend.x - ostart.x
        oheight = oend.z - ostart.z
        proportional = vp.mouseWatcher.isButtonDown(KeyboardButton.control()) and \
            self.state.action == BoxAction.Resizing and owidth != 0 and oheight != 0

        if self.state.handle == ResizeHandle.TopLeft:
            cstart.x = now.x
            cend.z = now.z
        elif self.state.handle == ResizeHandle.Top:
            cend.z = now.z
        elif self.state.handle == ResizeHandle.TopRight:
            cend.x = now.x
            cend.z = now.z
        elif self.state.handle == ResizeHandle.Left:
            cstart.x = now.x
        elif self.state.handle == ResizeHandle.Center:
            cdiff = cend - cstart
            distance = self.getResizeDistance(vp)
            if not distance:
                cstart = vp.flatten(self.state.preTransformBoxStart) + now \
                    - base.snapToGrid(self.state.moveStart)
            else:
                cstart = vp.flatten(self.state.preTransformBoxStart) + distance
            cend = cstart + cdiff
        elif self.state.handle == ResizeHandle.Right:
            cend.x = now.x
        elif self.state.handle == ResizeHandle.BottomLeft:
            cstart.x = now.x
            cstart.z = now.z
        elif self.state.handle == ResizeHandle.Bottom:
            cstart.z = now.z
        elif self.state.handle == ResizeHandle.BottomRight:
            cend.x = now.x
            cstart.z = now.z

        if proportional:
            nwidth = cend.x - cstart.x
            nheight = cend.z - cstart.z
            mult = max(nwidth / owidth, nheight / oheight)
            pwidth = owidth * mult
            pheight = oheight * mult
            wdiff = pwidth - nwidth
            hdiff = pheight - nheight
            if self.state.handle == ResizeHandle.TopLeft:
                cstart.x -= wdiff
                cend.z += hdiff
            elif self.state.handle == ResizeHandle.TopRight:
                cend.x += wdiff
                cend.z += hdiff
            elif self.state.handle == ResizeHandle.BottomLeft:
                cstart.x -= wdiff
                cstart.z -= hdiff
            elif self.state.handle == ResizeHandle.BottomRight:
                cend.x += wdiff
                cstart.z -= hdiff

        cstart = vp.expand(cstart) + vp.getUnusedCoordinate(
            self.state.boxStart)
        cend = vp.expand(cend) + vp.getUnusedCoordinate(self.state.boxEnd)
        return [cstart, cend]
Example #14
0
 def getViewPunch(self):
     """
     Return the angles of the view "punch" that is applied to the camera when this
     attack is used by the local avatar.
     """
     return Vec3.zero()
 def __init__(self,name,size,right_side_ledge = True, left_side_ledge = True):
   '''
   Creates a box shaped platform
   SimplePlatform(String name, Vec3 size, Bool right_side_ledge, Bool left_side_ledge)
   '''
   
   # creating a static box
   collision_shape = BulletBoxShape(size/2) 
   collision_shape.setMargin(GameObject.DEFAULT_COLLISION_MARGIN)
   bt_node = BulletRigidBodyNode(name)
   bt_node.addShape(collision_shape)
   bt_node.setMass(0)
   
   # calling super constructor
   super(SimplePlatform,self).__init__(bt_node)
   self.size_ = size
   self.setCollideMask(CollisionMasks.PLATFORM_RIGID_BODY)
   visual_np = GameObject.createSimpleBoxVisualNode(self,self.size_, self.getName() + '-visual')
   visual_np.setTexture(SimplePlatform.__DEFAULT_TEXTURE__,1) 
   
   # addding ledges
   ledge_size = Vec3(SimplePlatform.__LEDGE_BOX_SIDE_LENGHT__,self.getSize().getY(),SimplePlatform.__LEDGE_BOX_SIDE_LENGHT__)
   self.left_ledge_ = Ledge(name + 'left-ledge',False,ledge_size) if left_side_ledge else None
   self.right_ledge_ = Ledge(name + 'right-ledge',True,ledge_size) if right_side_ledge else None
   self.ledges_ = [] 
   
   # ledge placement
   half_width = 0.5*size.getX()
   half_height = 0.5*size.getZ()
   half_depth = 0.5*size.getY()
   
   if left_side_ledge:
     self.left_ledge_.reparentTo(self)
     self.left_ledge_.setPos(Vec3(-half_width ,0,half_height))
     self.ledges_.append(self.left_ledge_)
     
   if right_side_ledge:
     self.right_ledge_.reparentTo(self)
     self.right_ledge_.setPos(Vec3(half_width ,0,half_height))
     self.ledges_.append(self.right_ledge_)
     
   # creating platform floor node
   thickness = SimplePlatform.__PERIMETER_THICKNESS__
   self.floor_ghost_np_ = self.attachNewNode(BulletGhostNode(name + 'floor'))    
   self.floor_ghost_np_.node().addShape(BulletBoxShape(Vec3((size.getX()-2*thickness)*0.5,size.getY()*0.5 ,thickness*0.5) ))
   #self.floor_ghost_np_.node().getShape(0).setMargin(GameObject.DEFAULT_COLLISION_MARGIN)
   self.floor_ghost_np_.setPosHpr(self,Vec3(0,0,(size.getZ() - thickness)*0.5),Vec3.zero())
   self.floor_ghost_np_.node().setIntoCollideMask(CollisionMasks.SURFACE)
   
   # creating platform right wall node
   self.rightwall_ghost_np_ = self.attachNewNode(BulletGhostNode(name + 'right-wall'))
   self.rightwall_ghost_np_.node().addShape(BulletBoxShape(Vec3(thickness*0.5,size.getY()*0.5,size.getZ()*0.5 )))
   #self.rightwall_ghost_np_.node().getShape(0).setMargin(GameObject.DEFAULT_COLLISION_MARGIN)
   self.rightwall_ghost_np_.setPosHpr(self,Vec3((size.getX() - thickness)*0.5,0,0),Vec3.zero())
   self.rightwall_ghost_np_.node().setIntoCollideMask(CollisionMasks.WALL)
   
   # creating platform left wall node
   self.leftwall_ghost_np_ = self.attachNewNode(BulletGhostNode(name + 'left-wall'))
   self.leftwall_ghost_np_.node().addShape(BulletBoxShape(Vec3(thickness*0.5,size.getY()*0.5,size.getZ()*0.5 )))
   #self.leftwall_ghost_np_.node().getShape(0).setMargin(GameObject.DEFAULT_COLLISION_MARGIN)
   self.leftwall_ghost_np_.setPosHpr(self,Vec3(-(size.getX() - thickness)*0.5,0,0),Vec3.zero())
   self.leftwall_ghost_np_.node().setIntoCollideMask(CollisionMasks.WALL)
   
   # storing all ghost nodes in subclass list
   self.bt_children_nodes_ = [self.leftwall_ghost_np_, self.rightwall_ghost_np_, self.floor_ghost_np_]
   
   # setting id 
   self.setObjectID(self.getName())
Example #16
0
    def handleAvatarControls(self, task):
        """
        Check on the arrow keys and update the avatar.
        """
        # get the button states:
        run = inputState.isSet("run")
        forward = inputState.isSet("forward")
        reverse = inputState.isSet("reverse")
        turnLeft = inputState.isSet("turnLeft")
        turnRight = inputState.isSet("turnRight")
        slideLeft = inputState.isSet("slideLeft")
        slideRight = inputState.isSet("slideRight")
        jump = inputState.isSet("jump")

        avatarControlForwardSpeed = 0
        avatarControlReverseSpeed = 0
        avatarControlSLeftSpeed = 0
        avatarControlSRightSpeed = 0

        if forward:
            if not self.hasSetForwardInitTime:
                self.forwardInitTime = globalClock.getFrameTime()
                self.hasSetForwardInitTime = True
                self.isAtZeroForward = False
                self.hasSetForwardStopTime = False
            timeSinceForwardSet = globalClock.getFrameTime() - self.forwardInitTime
            if timeSinceForwardSet == 0:
                avatarControlForwardSpeed = 0.0
            else:
                avatarControlForwardSpeed = min((timeSinceForwardSet / self.avatarControlForwardSpeed) * 750,
                                            self.avatarControlForwardSpeed)
        else:
            if self.hasSetForwardInitTime:
                self.hasSetForwardInitTime = False
            if not self.hasSetForwardStopTime:
                self.forwardStopTime = globalClock.getFrameTime()
                self.hasSetForwardStopTime = True
            timeSinceForwardStop = globalClock.getFrameTime() - self.forwardStopTime
            if timeSinceForwardStop == 0:
                avatarControlForwardSpeed = 16.0
            elif not self.isAtZeroForward:
                avatarControlForwardSpeed = self.avatarControlForwardSpeed - (timeSinceForwardStop * 50)
                if avatarControlForwardSpeed <= 0.5:
                    avatarControlForwardSpeed = 0.0
                    self.isAtZeroForward = True
                    self.hasSetForwardStopTime = False

        if reverse:
            if not self.hasSetReverseInitTime:
                self.reverseInitTime = globalClock.getFrameTime()
                self.hasSetReverseInitTime = True
                self.isAtZeroReverse = False
                self.hasSetReverseStopTime = False
            timeSinceReverseSet = globalClock.getFrameTime() - self.reverseInitTime
            if timeSinceReverseSet == 0:
                avatarControlReverseSpeed = 0.0
            else:
                avatarControlReverseSpeed = min((timeSinceReverseSet / self.avatarControlReverseSpeed) * 400,
                                            self.avatarControlReverseSpeed)
        else:
            if self.hasSetReverseInitTime:
                self.hasSetReverseInitTime = False
            if not self.hasSetReverseStopTime:
                self.reverseStopTime = globalClock.getFrameTime()
                self.hasSetReverseStopTime = True
            timeSinceReverseStop = globalClock.getFrameTime() - self.reverseStopTime
            if timeSinceReverseStop == 0:
                avatarControlReverseSpeed = 16.0
            elif not self.isAtZeroReverse:
                avatarControlReverseSpeed = self.avatarControlReverseSpeed - (timeSinceReverseStop * 20)
                if avatarControlReverseSpeed <= 0.5:
                    avatarControlReverseSpeed = 0.0
                    self.isAtZeroReverse = True
                    self.hasSetReverseStopTime = False

        if slideLeft:
            if not self.hasSetSLeftInitTime:
                self.sLeftInitTime = globalClock.getFrameTime()
                self.hasSetSLeftInitTime = True
                self.isAtZeroSLeft = False
                self.hasSetSLeftStopTime = False
            timeSinceSLeftSet = globalClock.getFrameTime() - self.sLeftInitTime
            if timeSinceSLeftSet == 0:
                avatarControlSLeftSpeed = 0.0
            else:
                avatarControlSLeftSpeed = min((timeSinceSLeftSet / self.avatarControlForwardSpeed) * 750,
                                            self.avatarControlForwardSpeed)
        else:
            if self.hasSetSLeftInitTime:
                self.hasSetSLeftInitTime = False
            if not self.hasSetSLeftStopTime:
                self.sLeftStopTime = globalClock.getFrameTime()
                self.hasSetSLeftStopTime = True
            timeSinceSLeftStop = globalClock.getFrameTime() - self.sLeftStopTime
            if timeSinceSLeftStop == 0:
                avatarControlSLeftSpeed = 16.0
            elif not self.isAtZeroSLeft:
                avatarControlSLeftSpeed = self.avatarControlForwardSpeed - (timeSinceSLeftStop * 50)
                if avatarControlSLeftSpeed <= 0.5:
                    avatarControlSLeftSpeed = 0.0
                    self.isAtZeroSLeft = True
                    self.hasSetSLeftStopTime = False

        if slideRight:
            if not self.hasSetSRightInitTime:
                self.sRightInitTime = globalClock.getFrameTime()
                self.hasSetSRightInitTime = True
                self.isAtZeroSRight = False
                self.hasSetSRightStopTime = False
            timeSinceSRightSet = globalClock.getFrameTime() - self.sRightInitTime
            if timeSinceSRightSet == 0:
                avatarControlSRightSpeed = 0.0
            else:
                avatarControlSRightSpeed = min((timeSinceSRightSet / self.avatarControlForwardSpeed) * 750,
                                            self.avatarControlForwardSpeed)
        else:
            if self.hasSetSRightInitTime:
                self.hasSetSRightInitTime = False
            if not self.hasSetSRightStopTime:
                self.sRightStopTime = globalClock.getFrameTime()
                self.hasSetSRightStopTime = True
            timeSinceSRightStop = globalClock.getFrameTime() - self.sRightStopTime
            if timeSinceSRightStop == 0:
                avatarControlSRightSpeed = 16.0
            elif not self.isAtZeroSRight:
                avatarControlSRightSpeed = self.avatarControlForwardSpeed - (timeSinceSRightStop * 50)
                if avatarControlSRightSpeed <= 0.5:
                    avatarControlSRightSpeed = 0.0
                    self.isAtZeroSRight = True
                    self.hasSetSRightStopTime = False

        # Check for Auto-Run
        #if 'localAvatar' in __builtins__:
        #    if base.localAvatar and base.localAvatar.getAutoRun():
        #        forward = 1
        #        reverse = 0

        # Determine what the speeds are based on the buttons:
        self.speed=(avatarControlForwardSpeed or
                    -avatarControlReverseSpeed)
        # Slide speed is a scaled down version of forward speed
        # Note: you can multiply a factor in here if you want slide to
        # be slower than normal walk/run. Let's try full speed.
        #self.slideSpeed=(slideLeft and -self.avatarControlForwardSpeed*0.75 or
        #                 slideRight and self.avatarControlForwardSpeed*0.75)
        self.slideSpeed=(-avatarControlSLeftSpeed or
                        avatarControlSRightSpeed)
        self.rotationSpeed=not (slideLeft or slideRight) and (
                (turnLeft and self.avatarControlRotateSpeed) or
                (turnRight and -self.avatarControlRotateSpeed))

        if self.speed and self.slideSpeed:
            self.speed *= GravityWalker.DiagonalFactor
            self.slideSpeed *= GravityWalker.DiagonalFactor

        debugRunning = inputState.isSet("debugRunning")
        if(debugRunning):
            self.speed*=base.debugRunningMultiplier
            self.slideSpeed*=base.debugRunningMultiplier
            self.rotationSpeed*=1.25

        if self.needToDeltaPos:
            self.setPriorParentVector()
            self.needToDeltaPos = 0
        if self.wantDebugIndicator:
            self.displayDebugInfo()
        if self.lifter.isOnGround():
            if self.isAirborne:
                self.isAirborne = 0
                assert self.debugPrint("isAirborne 0 due to isOnGround() true")
                impact = self.lifter.getImpactVelocity()
                if impact < -30.0:
                    messenger.send("jumpHardLand")
                    self.startJumpDelay(0.3)
                else:
                    messenger.send("jumpLand")
                    if impact < -5.0:
                        self.startJumpDelay(0.2)
                    # else, ignore the little potholes.
            assert self.isAirborne == 0
            self.priorParent = Vec3.zero()
            if jump and self.mayJump:
                # The jump button is down and we're close
                # enough to the ground to jump.
                self.lifter.addVelocity(self.avatarControlJumpForce)
                messenger.send("jumpStart")
                self.isAirborne = 1
                assert self.debugPrint("isAirborne 1 due to jump")
        else:
            if self.isAirborne == 0:
                assert self.debugPrint("isAirborne 1 due to isOnGround() false")
            self.isAirborne = 1

        self.__oldPosDelta = self.avatarNodePath.getPosDelta(render)
        # How far did we move based on the amount of time elapsed?
        self.__oldDt = ClockObject.getGlobalClock().getDt()
        dt=self.__oldDt

        # Check to see if we're moving at all:
        self.moving = self.speed or self.slideSpeed or self.rotationSpeed or (self.priorParent!=Vec3.zero())
        if self.moving:
            distance = dt * self.speed
            slideDistance = dt * self.slideSpeed
            rotation = dt * self.rotationSpeed

            # Take a step in the direction of our previous heading.
            if distance or slideDistance or self.priorParent != Vec3.zero():
                # rotMat is the rotation matrix corresponding to
                # our previous heading.
                rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
                if self.isAirborne:
                    forward = Vec3.forward()
                else:
                    contact = self.lifter.getContactNormal()
                    forward = contact.cross(Vec3.right())
                    # Consider commenting out this normalize.  If you do so
                    # then going up and down slops is a touch slower and
                    # steeper terrain can cut the movement in half.  Without
                    # the normalize the movement is slowed by the cosine of
                    # the slope (i.e. it is multiplied by the sign as a
                    # side effect of the cross product above).
                    forward.normalize()
                self.vel=Vec3(forward * distance)
                if slideDistance:
                    if self.isAirborne:
                        right = Vec3.right()
                    else:
                        right = forward.cross(contact)
                        # See note above for forward.normalize()
                        right.normalize()
                    self.vel=Vec3(self.vel + (right * slideDistance))
                self.vel=Vec3(rotMat.xform(self.vel))
                step=self.vel + (self.priorParent * dt)
                self.avatarNodePath.setFluidPos(Point3(
                        self.avatarNodePath.getPos()+step))
            self.avatarNodePath.setH(self.avatarNodePath.getH()+rotation)
        else:
            self.vel.set(0.0, 0.0, 0.0)
        if self.moving or jump:
            messenger.send("avatarMoving")
        return Task.cont
Example #17
0
        def repel_context(world):
            """ Sets up a repel context. Gets the bodies, turns off
            gravity, rescales the masses, sets up the collision
            notification callback. """

            def change_contact_thresh(bodies, thresh=0.001):
                """ Adjust the contact processing threshold. This is
                used to make the objects not trigger collisions when
                just barely touching."""
                if isinstance(thresh, Iterable):
                    it = izip(bodies, thresh)
                else:
                    it = ((body, thresh) for body in bodies)
                thresh0 = []
                for body, th in it:
                    thresh0.append(body.getContactProcessingThreshold())
                    body.setContactProcessingThreshold(th)
                return thresh0

            def rescale_masses(bodies):
                """ Rescale the masses so they are proportional to the
                volume."""
                masses, inertias = zip(*[(body.getMass(), body.getInertia())
                                         for body in bodies])
                volumefac = 1.
                for body, mass, inertia in zip(bodies, masses, inertias):
                    # Compute the mass-normalized diagonal elements of the
                    # inertia tensor.
                    if mass > 0.:
                        it = inertia / mass * 12
                        # Calculate volume from the mass-normalized
                        # inertia tensor (from wikipedia).
                        h = sqrt((it[0] - it[1] + it[2]) / 2)
                        w = sqrt(it[2] - h ** 2)
                        d = sqrt(it[1] - w ** 2)
                        volume = h * w * d
                        # Change the mass.
                        body.setMass(volume * volumefac)
                return masses

            # Get the bodies.
            bodies = world.getRigidBodies()
            # Turn gravity off.
            gravity = world.getGravity()
            world.setGravity(Vec3.zero())
            # Tighten the contact processing threshold slightly.
            delta = -0.001
            cp_thresh = change_contact_thresh(bodies, thresh=delta)
            # Adjust masses.
            masses = rescale_masses(bodies)
            # Adjust sleep thresholds.
            deactivations = [b.isDeactivationEnabled() for b in bodies]
            for body in bodies:
                body.setDeactivationEnabled(False)
            # Zero out velocities.
            self.attenuate_velocities(bodies)
            # Collisions monitor.
            collisions = CollisionMonitor(world)
            collisions.push_notifiers(bodies)
            ## Finish __enter__.
            yield bodies, collisions
            ## Start __exit__.
            collisions.pop_notifiers()
            # Zero out velocities.
            self.attenuate_velocities(bodies)
            # Restore the contact processing threshold.
            change_contact_thresh(bodies, thresh=cp_thresh)
            # Set masses back.
            for body, mass in zip(bodies, masses):
                body.setMass(mass)
                # Turn gravity back on.
                world.setGravity(gravity)
            for body, d in zip(bodies, deactivations):
                body.setDeactivationEnabled(d)
 def  __init__(self,info):
   
   # animation base setup
   self.character_info_ = info   
   size = Vec3(info.width, AnimationActor.DEFAULT_WIDTH , info.height)
   AnimatableObject.__init__(self,info.name,size,info.mass)    
   self.animation_root_np_.setPos(Vec3(0,0,0))
   
       # constraints
   self.left_constraint_ = None
   self.right_constraint_ = None
   self.selected_constraint_ = None
   
   # removing default shapes from rigid body
   shapes = self.node().getShapes()
   for shape in shapes:
     self.node().removeShape(shape)
   
   # adding capsule shape
   radius = 0.5*size.getX()
   height = size.getZ() - 2.0*radius  # height of cylindrical part only
   height = height if height >= 0 else 0.0
   bullet_shape = BulletCapsuleShape(radius, height, ZUp)
   bullet_shape.setMargin(GameObject.DEFAULT_COLLISION_MARGIN)
   self.node().addShape(bullet_shape,TransformState.makePos(Vec3(0,0,0.5*size.getZ()))) # box bottom center coincident with the origin
   self.node().setMass(self.character_info_.mass)
   self.node().setLinearFactor((1,1,1)) 
   self.node().setAngularFactor((0,0,0)) 
   self.setCollideMask(CollisionMasks.NO_COLLISION)    
   
   #  setting bounding volume
   min = LPoint3(-0.5*size.getX(),-0.5*size.getY(),0)
   max = LPoint3(0.5*size.getX(),0.5*size.getY(),size.getZ())
   self.node().setBoundsType(BoundingVolume.BT_box)    
   self.node().setBounds(BoundingBox(min,max))
   
   # setting origin ghost nodes
   rel_pos = Vec3(-GameObject.ORIGIN_XOFFSET,0,info.height/2)
   self.left_origin_gn_ = self.attachNewNode(BulletGhostNode(self.getName() + '-left-origin'))
   self.left_origin_gn_.node().addShape(BulletSphereShape(GameObject.ORIGIN_SPHERE_RADIUS),TransformState.makePosHpr(rel_pos,Vec3.zero()))
   self.left_origin_gn_.node().setIntoCollideMask(CollisionMasks.ACTION_TRIGGER_0 if not self.isFacingRight() else CollisionMasks.NO_COLLISION)
   
   rel_pos = Vec3(GameObject.ORIGIN_XOFFSET,0,info.height/2)
   self.right_origin_gn_ = self.attachNewNode(BulletGhostNode(self.getName() + '-right-origin'))
   self.right_origin_gn_.node().addShape(BulletSphereShape(GameObject.ORIGIN_SPHERE_RADIUS),TransformState.makePosHpr(rel_pos,Vec3.zero()))
   self.right_origin_gn_.node().setIntoCollideMask(CollisionMasks.ACTION_TRIGGER_0 if self.isFacingRight() else CollisionMasks.NO_COLLISION)
   
   # character status
   self.state_data_ = CharacterStateData()
   
   # state machine
   self.sm_ = StateMachine()     
   
   # motion commander
   self.motion_commander_ = MotionCommander(self)
   
   # set id
   self.setObjectID(self.getName())
def getRotationTo(src, dest, fallbackAxis=Vec3_ZERO):
    # Quaternion q;
    # Vector3 v0 = *this;
    # Vector3 v1 = dest;
    # v0.normalise();
    # v1.normalise();
    q = Quat()
    v0 = Vec3(src)
    v1 = Vec3(dest)
    v0.normalize()
    v1.normalize()

    # Real d = v0.dotProduct(v1);
    d = v0.dot(v1)

    # if (d >= 1.0f)
    # {
    # return Quaternion::IDENTITY;
    # }
    if d >= 1.0:
        return Quat(1, 0, 0, 0)

    # if (d < (1e-6f - 1.0f))
    if d < (1.0e-6 - 1.0):
        # if (fallbackAxis != Vector3::ZERO)
        # {
        # // rotate 180 degrees about the fallback axis
        # q.FromAngleAxis(Radian(Math::PI), fallbackAxis);
        # }
        if fallbackAxis != Vec3_ZERO:
            q.setFromAxisAngleRad(pi, fallbackAxis)
        # else
        # {
        # // Generate an axis
        # Vector3 axis = Vector3::UNIT_X.crossProduct(*this);
        # if (axis.isZeroLength()) // pick another if colinear
        # axis = Vector3::UNIT_Y.crossProduct(*this);
        # axis.normalise();
        # q.FromAngleAxis(Radian(Math::PI), axis);
        # }
        else:
            axis = Vec3(1, 0, 0).cross(src)
            if axis.almostEqual(Vec3.zero()):
                axis = Vec3(0, 1, 0).cross(src)
            axis.normalize()
            q.setFromAxisAngleRad(pi, axis)
        # else
        # {
        # Real s = Math::Sqrt( (1+d)*2 );
        # Real invs = 1 / s;

        # Vector3 c = v0.crossProduct(v1);

        # q.x = c.x * invs;
        # q.y = c.y * invs;
        # q.z = c.z * invs;
        # q.w = s * 0.5f;
        # q.normalise();
    # }
    else:
        s = sqrt((1 + d) * 2)
        invs = 1 / s
        c = v0.cross(v1)
        q.setI(c.x * invs)
        q.setJ(c.y * invs)
        q.setK(c.z * invs)
        q.setR(s * .5)
        q.normalize()
    return q
Example #20
0
 def __init__(self, mass=1, location = Point3.zero(), velocity=Vec3.zero(), acceleration=Vec3.zero()):
     # instance variables
     self.mass = mass
     self.location = location
     self.velocity = velocity
     self.acceleration = acceleration
Example #21
0
 def update(self):
     self.velocity = self.velocity + self.acceleration
     self.location = self.location + self.velocity
     self.acceleration = Vec3.zero()