Ejemplo n.º 1
0
 def handleKeyboardEvent(self, task):
     keys = self.keys
     
     dt = globalClock.getDt()
     impulse = Vec3(0, 0, 0)
     increment = self._impulseIncrement * dt
     
     above_limit = self.is_above_limit
     
     for key, vec in (("left", Vec3.left()),
                      ("right", Vec3.right()),
                      ("up", Vec3.forward()),
                      ("down", Vec3.back())):
         if keys[key] and (not above_limit or self.is_braking(vec)):
             impulse += vec * increment
     
     self.addImpulse(impulse)
     
     # If Equismo was not hit by an enemy look at the movement direction.
     # Otherwise look at the enemy until Equismo turns around.
     if not self._hit:
         self.face(self.velocity)
     
     elif ((impulse.length() > 0) and
           (self.velocity.length() > 0.5) and
           (not self.is_braking(impulse))):
                 self._hit = False
     
     self.doWalkAnimation(impulse)
     
     return task.cont
 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()
Ejemplo n.º 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
Ejemplo n.º 4
0
    def update(self, task=None):
        """
        Updates position of sounds in the 3D audio system. Will be called automatically
        in a task.
        """
        # Update the positions of all sounds based on the objects
        # to which they are attached

        # The audio manager is not active so do nothing
        if hasattr(self.audio_manager, "getActive"):
            if self.audio_manager.getActive()==0:
                return Task.cont

        for known_object in self.sound_dict.keys():
            tracked_sound = 0
            while tracked_sound < len(self.sound_dict[known_object]):
                sound = self.sound_dict[known_object][tracked_sound]
                pos = known_object.getPos(self.root)
                vel = self.getSoundVelocity(sound)
                sound.set3dAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2])
                tracked_sound += 1

        # Update the position of the listener based on the object
        # to which it is attached
        if self.listener_target:
            pos = self.listener_target.getPos(self.root)
            forward = self.root.getRelativeVector(self.listener_target, Vec3.forward())
            up = self.root.getRelativeVector(self.listener_target, Vec3.up())
            vel = self.getListenerVelocity()
            self.audio_manager.audio3dSetListenerAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0], forward[1], forward[2], up[0], up[1], up[2])
        else:
            self.audio_manager.audio3dSetListenerAttributes(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1)
        return Task.cont
    def step(self, task):
        distance = ClockObject.getGlobalClock().getDt() * self.speed

        rotMat = Mat3.rotateMatNormaxis(self.avatar.getH(), Vec3.up())
        step = Vec3(rotMat.xform(Vec3.forward() * distance))
        self.avatar.setFluidPos(Point3(self.avatar.getPos() + step))

        return Task.cont
Ejemplo n.º 6
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
    def matchPose(self, pose_rig):
        for node, parent in pose_rig.exposed_joints:
            if node.getName() not in joints_config:
                continue

            joint_config = joints_config[node.getName()]
            if 'joints' not in joint_config:
                continue

            joints = joint_config['joints']
            if len(joints) == 0:
                continue

            box_np = self.root.find(node.getName())

            if len(joints) > 1:
                pos = node.getPos(pose_rig.actor)
                hpr = node.getHpr(pose_rig.actor)
                box_np.setPosHpr(self.root, pos, hpr)
            else:
                joint = joints.keys()[0]
                child_node, child_parent = next((child_node, child_parent) for child_node, child_parent in pose_rig.exposed_joints if child_node.getName() == joint)
                box_np.setPos(child_parent, child_node.getPos(child_parent) / 2.0)

                quat = Quat()
                lookAt(quat, child_node.getPos(child_parent), Vec3.up())
                box_np.setQuat(child_parent, quat)

            box_np.node().clearForces()
Ejemplo n.º 8
0
    def ik_leg(self):
        floor_pos = self.get_floor_spot()
        target_pos = self._get_target_pos()
        hip_pos = self.hip_bone.get_pos(self.foot_ref)

        if floor_pos and target_pos.y < floor_pos.y:
            floor_pos.x = target_pos.x
            target_vector = hip_pos - floor_pos
            self.is_on_ground = True
        else:
            target_vector = hip_pos - target_pos
            self.is_on_ground = False

        #turn off the ground for debugging
        #target_vector = hip_pos - target_pos

        pt_length = target_vector.length()
        if .01 < pt_length < (TOP_LEG_LENGTH + BOTTOM_LEG_LENGTH +.1):
            tt_angle_cos = (math.pow(TOP_LEG_LENGTH, 2) + math.pow(pt_length, 2) - math.pow(BOTTOM_LEG_LENGTH,2))/(2*TOP_LEG_LENGTH*pt_length)
            try:
                target_top_angle = rad2Deg(math.acos(tt_angle_cos))
            except ValueError:
                return
            target_vector.normalize()
            self.hip_bone.get_relative_vector(self.foot_ref, target_vector)
            delta = target_vector.get_xy().signed_angle_deg(Vec3.unitY().get_xy())
            self.top_bone.set_p(90 - target_top_angle + delta)

            tb_angle_cos = ((math.pow(TOP_LEG_LENGTH, 2) + math.pow(BOTTOM_LEG_LENGTH, 2) - math.pow(pt_length,2))/(2*TOP_LEG_LENGTH*BOTTOM_LEG_LENGTH))
            target_bottom_angle = rad2Deg(math.acos(tb_angle_cos))
            self.bottom_bone.set_p((180 - target_bottom_angle) * -1)
        else:
            return
 def __estimateSize__(self):
   minp = LPoint3.zero()
   maxp = LPoint3.zero()
   size = Vec3.zero()
   if self.calcTightBounds(minp,maxp):
     size = maxp - minp
     
   return size 
def create_colliders(root, pose_rig, joints_config):
    for node, parent in pose_rig.exposed_joints:
        if node.getName() not in joints_config:
            continue

        joint_config = joints_config[node.getName()]
        if "joints" not in joint_config:
            continue

        joints = joint_config["joints"]
        if len(joints) == 0:
            continue

        mass = joint_config["mass"] if "mass" in joint_config else 1

        box_rb = BulletRigidBodyNode(node.getName())
        box_rb.setMass(1.0)
        # box_rb.setLinearDamping(0.2)
        # box_rb.setAngularDamping(0.9)
        # box_rb.setFriction(1.0)
        # box_rb.setAnisotropicFriction(1.0)
        # box_rb.setRestitution(0.0)

        for joint in joints:
            child_node, child_parent = next(
                (child_node, child_parent)
                for child_node, child_parent in pose_rig.exposed_joints
                if child_node.getName() == joint
            )

            pos = child_node.getPos(child_parent)
            width = pos.length() / 2.0
            scale = Vec3(3, width, 3)

            shape = BulletBoxShape(scale)

            quat = Quat()
            lookAt(quat, child_node.getPos(child_parent), Vec3.up())
            if len(joints) > 1:
                transform = TransformState.makePosHpr(child_node.getPos(child_parent) / 2.0, quat.getHpr())
            else:
                transform = TransformState.makeHpr(quat.getHpr())

            box_rb.addShape(shape, transform)

        box_np = root.attachNewNode(box_rb)

        if len(joints) > 1:
            pos = node.getPos(pose_rig.actor)
            hpr = node.getHpr(pose_rig.actor)
            box_np.setPosHpr(root, pos, hpr)
        else:
            box_np.setPos(child_parent, child_node.getPos(child_parent) / 2.0)
            box_np.lookAt(child_parent, child_node.getPos(child_parent))

        yield box_np
Ejemplo n.º 11
0
 def get_normal(self):
     seen = set()
     points = [p for p in self.points if p not in seen and not seen.add(p)]
     if len(points) >= 3:
         v1 = points[0] - points[1]
         v2 = points[1] - points[2]
         normal = v1.cross(v2)
         normal.normalize()
     else:
         normal = Vec3.up()
     return normal
Ejemplo n.º 12
0
 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    
Ejemplo n.º 13
0
 def guide_missile(self, task):
     try:
         quat = Quat()
         lookAt(quat, self.target.np.getPos() - self.missile.anp.getPos(), Vec3.up())
         self.missile.anp.setQuat(quat)
         fwd = quat.getForward()
         fwd.normalize()
         mvel = self.missile.anpo.getVelocity().length()
         self.missile.anpo.setVelocity(fwd*mvel)
     except:
         return task.done
     return task.cont
  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
Ejemplo n.º 15
0
    def update(self, task=None):
        """
        Updates position of sounds in the 3D audio system. Will be called automatically
        in a task.
        """
        # Update the positions of all sounds based on the objects
        # to which they are attached

        # The audio manager is not active so do nothing
        if hasattr(self.audio_manager, "getActive"):
            if self.audio_manager.getActive()==0:
                return Task.cont

        for known_object, sounds in list(self.sound_dict.items()):
            node_path = known_object.getNodePath()
            if not node_path:
                # The node has been deleted.
                del self.sound_dict[known_object]
                continue

            pos = node_path.getPos(self.root)

            for sound in sounds:
                vel = self.getSoundVelocity(sound)
                sound.set3dAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2])

        # Update the position of the listener based on the object
        # to which it is attached
        if self.listener_target:
            pos = self.listener_target.getPos(self.root)
            forward = self.root.getRelativeVector(self.listener_target, Vec3.forward())
            up = self.root.getRelativeVector(self.listener_target, Vec3.up())
            vel = self.getListenerVelocity()
            self.audio_manager.audio3dSetListenerAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0], forward[1], forward[2], up[0], up[1], up[2])
        else:
            self.audio_manager.audio3dSetListenerAttributes(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1)
        return Task.cont
 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()
Ejemplo n.º 17
0
 def __init__(self, parent, model):
     PhysicalNode.__init__(self, parent, model, "equismo")
     
     self.mass = 500.0
     
     self.addCollisionSphere(1.2)
     
     self._impulseIncrement = 4.0
     self._speedLimit = 5.0
     self._turningSpeed = 0.2
     
     self._hit = False
     self._currentDirection = Vec3.forward()
     self._currentAngle = 0
     
     self.setScale(0.8)
     
     # Little "hack" to fix orientation
     # Seems that the model has its eyes in the back?!
     self.actor.setH(180)
     
     #-----------------------------------------------------------------------
     # KeyboardEventHandler initialization
     #-----------------------------------------------------------------------
     self.keys = dict.fromkeys("left right up down".split(), 0)
     set_key = self.keys.__setitem__
     self.bindings = (
         ("w", set_key, ["up", 1]),
         ("a", set_key, ["left", 1]),
         ("s", set_key, ["down", 1]),
         ("d", set_key, ["right", 1]),
         
         ("w-up", set_key, ["up", 0]),
         ("a-up", set_key, ["left", 0]),
         ("s-up", set_key, ["down", 0]),
         ("d-up", set_key, ["right", 0]),
         
         ("arrow_up", set_key, ["up", 1]),
         ("arrow_left", set_key, ["left", 1]),
         ("arrow_down", set_key, ["down", 1]),
         ("arrow_right", set_key, ["right", 1]),
         
         ("arrow_up-up", set_key, ["up", 0]),
         ("arrow_left-up", set_key, ["left", 0]),
         ("arrow_down-up", set_key, ["down", 0]),
         ("arrow_right-up", set_key, ["right", 0]),
     )
  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)
Ejemplo n.º 19
0
 def __applyLinearVelocity(self):
     globalVel = self.movementParent.getQuat(render).xform(self.__linearVelocity) * self.__timeStep
     
     if self.predictFutureSpace and not self.__checkFutureSpace(globalVel):
         return
     
     if self.__footContact is not None and self.minSlopeDot and self.movementState != "flying":
         normalVel = Vec3(globalVel)
         normalVel.normalize()
         
         floorNormal = self.__footContact[2]
         absSlopeDot = round(floorNormal.dot(Vec3.up()), 2)
         
         def applyGravity():
             self.__currentPos -= Vec3(floorNormal.x, floorNormal.y, 0.0) * self.gravity * self.__timeStep * 0.1
         
         if absSlopeDot <= self.minSlopeDot:
             applyGravity()
             
             if globalVel != Vec3():
                 globalVelDir = Vec3(globalVel)
                 globalVelDir.normalize()
                 
                 fn = Vec3(floorNormal.x, floorNormal.y, 0.0)
                 fn.normalize()
                 
                 velDot = 1.0 - globalVelDir.angleDeg(fn) / 180.0
                 if velDot < 0.5:
                     self.__currentPos -= Vec3(fn.x * globalVel.x, fn.y * globalVel.y, 0.0) * velDot
                 
                 globalVel *= velDot
         
         elif self.__slopeAffectsSpeed and globalVel != Vec3():
             applyGravity()
     
     self.__currentPos += globalVel
 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())
class DistributedBattleTrolley(DistributedObject):
    notify = directNotify.newCategory('DistributedBattleTrolley')
    STAND_POSITIONS = [
     Point3(-4.75, -5, 1.4),
     Point3(-4.75, -1.6, 1.4),
     Point3(-4.75, 1.6, 1.4),
     Point3(-4.75, 5, 1.4),
     Point3(-4.75, -5, 1.4),
     Point3(-4.75, -1.6, 1.4),
     Point3(-4.75, 1.6, 1.4),
     Point3(-4.75, 5, 1.4)]
    TROLLEY_NEUTRAL_POS = Point3(15, 14, -1)
    TROLLEY_GONE_POS = Point3(50, 14.1588, -0.984615)
    TROLLEY_ARRIVING_START_POS = Point3(-20, 14.1588, -0.984615)
    CAM_POS = Point3(-35, 0, 8)
    CAM_HPR = Vec3(-90, 0, 0)

    def __init__(self, cr):
        DistributedObject.__init__(self, cr)
        self.fsm = ClassicFSM.ClassicFSM('DistributedBattleTrolley', [State.State('off', self.enterOff, self.exitOff),
         State.State('wait', self.enterWait, self.exitWait),
         State.State('waitCountdown', self.enterWaitCountdown, self.exitWaitCountdown),
         State.State('leaving', self.enterLeaving, self.exitLeaving),
         State.State('arriving', self.enterArriving, self.exitArriving)], 'off', 'off')
        self.fsm.enterInitialState()
        self.trolleyStation = None
        self.trolleyCar = None
        self.trolleyKey = None
        self.countdownText = None
        self.trolleyAwaySfx = base.loadSfx('phase_4/audio/sfx/SZ_trolley_away.ogg')
        if self.cr.holidayManager.getHoliday() == HolidayType.CHRISTMAS:
            self.trolleyAwaySfx = base.loadSfx('winter/audio/sfx/SZ_trolley_away.ogg')
        self.trolleyBellSfx = base.loadSfx('phase_4/audio/sfx/SZ_trolley_bell.ogg')
        self.hoodIndex = 0
        self.localAvOnTrolley = False
        self.trolleyEnterTrack = None
        self.trolleyExitTrack = None
        return

    def headOff(self, zoneId):
        hoodId = self.cr.playGame.hood.hoodId
        if hoodId == CIGlobals.ToontownCentral:
            hoodId = CIGlobals.BattleTTC
        requestStatus = {'zoneId': zoneId, 'hoodId': hoodId, 'where': 'playground', 
           'avId': base.localAvatar.doId, 
           'loader': 'safeZoneLoader', 
           'shardId': None, 
           'wantLaffMeter': 1, 
           'how': 'teleportIn'}
        self.cr.playGame.getPlace().doneStatus = requestStatus
        messenger.send(self.cr.playGame.getPlace().doneEvent)
        base.localAvatar.reparentTo(render)
        base.localAvatar.setPos(0, 0, 0)
        base.localAvatar.setHpr(0, 0, 0)
        base.localAvatar.walkControls.setCollisionsActive(1)
        self.localAvOnTrolley = False
        return

    def setHoodIndex(self, zone):
        self.hoodIndex = zone

    def getToZone(self):
        return self.toZone

    def enterOff(self, ts=0):
        pass

    def exitOff(self):
        pass

    def enterWait(self, ts=0):
        self.trolleyCar.setPos(self.TROLLEY_NEUTRAL_POS)
        self.acceptOnce('entertrolley_sphere', self.__handleTrolleyTrigger)

    def exitWait(self):
        self.ignore('entertrolley_sphere')

    def enterWaitCountdown(self, ts=0):
        self.trolleyCar.setPos(self.TROLLEY_NEUTRAL_POS)
        self.acceptOnce('entertrolley_sphere', self.__handleTrolleyTrigger)
        if self.countdownText:
            self.countdownTrack = Sequence()
            for i in range(10):
                self.countdownTrack.append(Func(self.countdownText.node().setText, str(10 - i)))
                self.countdownTrack.append(Wait(1.0))

            self.countdownTrack.start()

    def exitWaitCountdown(self):
        self.ignore('entertrolley_sphere')
        if hasattr(self, 'countdownTrack'):
            self.countdownTrack.finish()
            del self.countdownTrack
        if self.countdownText:
            self.countdownText.node().setText('')
        self.disableExitButton()

    def enterArriving(self, ts=0):
        self.trolleyEnterTrack.start(ts)

    def exitArriving(self):
        if self.trolleyEnterTrack:
            self.trolleyEnterTrack.finish()

    def enterLeaving(self, ts=0):
        camera.posHprInterval(3, (0, 18.55, 3.75), (-180, 0, 0), blendType='easeInOut').start()
        base.playSfx(self.trolleyBellSfx, node=self.trolleyCar)
        if self.localAvOnTrolley == True:
            self.trolleyExitTrack.append(Sequence(Wait(4.0), Func(base.transitions.fadeOut)))
        self.trolleyExitTrack.start(ts)
        self.ignore('entertrolley_sphere')

    def exitLeaving(self):
        if self.trolleyExitTrack:
            self.trolleyExitTrack.finish()

    def setState(self, stateName, timestamp):
        ts = globalClockDelta.localElapsedTime(timestamp)
        self.fsm.request(stateName, [ts])

    def __handleTrolleyTrigger(self, entry):
        self.cr.playGame.getPlace().fsm.request('stop')
        base.localAvatar.disableGags()
        self.notify.info('Waiting for response from server to enter trolley')
        self.sendUpdate('requestBoard')
        base.localAvatar.walkControls.setCollisionsActive(0)

    def rejectBoard(self):
        self.cr.playGame.getPlace().fsm.request('walk')

    def fillSlot(self, index, avId):
        toon = self.cr.doId2do.get(avId)
        toon.stopSmooth()
        if toon:
            toon.wrtReparentTo(self.trolleyCar)
            if index <= 3:
                slotPos = Point3(-5, -4.5 + index * 3, 1.4)
                sitStartDuration = toon.getDuration('start-sit')
                toon.headsUp(slotPos)
                track = Sequence(Func(toon.setAnimState, 'run'), LerpPosInterval(toon, 0.75, Point3(-5, -4.5 + index * 3, 1.4)), LerpHprInterval(toon, 0.25, Point3(90, 0, 0)), Parallel(ActorInterval(toon, 'start-sit'), Sequence(Wait(sitStartDuration * 0.25), LerpPosInterval(toon, sitStartDuration * 0.25, Point3(-3.9, -4.5 + index * 3, 3.0)))), Func(toon.loop, 'sit'))
            else:
                slotPos = self.STAND_POSITIONS[index]
                toon.headsUp(slotPos)
                track = Sequence(Func(toon.setAnimState, 'run'), LerpPosInterval(toon, duration=1.0, pos=slotPos, startPos=toon.getPos()), Func(toon.setAnimState, 'neutral'), Func(toon.setHpr, 90, 0, 0))
            track.start()
        if avId == base.localAvatar.doId:
            self.localAvOnTrolley = True
            base.localAvatar.stopSmartCamera()
            base.camera.wrtReparentTo(self.trolleyCar)
            camTrack = Sequence(Parallel(LerpPosInterval(base.camera, duration=1.5, pos=self.CAM_POS, startPos=base.camera.getPos(), blendType='easeOut'), LerpQuatInterval(base.camera, duration=1.5, hpr=self.CAM_HPR, startHpr=base.camera.getHpr(), blendType='easeOut')), Func(self.enableExitButton))
            camTrack.start()

    def enableExitButton(self):
        if self.fsm.getCurrentState().getName() != 'leaving':
            gui = loader.loadModel('phase_3.5/models/gui/inventory_gui.bam')
            up = gui.find('**/InventoryButtonUp')
            down = gui.find('**/InventoryButtonDown')
            rlvr = gui.find('**/InventoryButtonRollover')
            self.exitButton = DirectButton(image=(up, down, rlvr), relief=None, text='Exit', text_fg=(1,
                                                                                                      1,
                                                                                                      0.65,
                                                                                                      1), text_pos=(0,
                                                                                                                    -0.23), text_scale=0.8, image_scale=(11,
                                                                                                                                                         1,
                                                                                                                                                         11), pos=(0,
                                                                                                                                                                   0,
                                                                                                                                                                   -0.8), scale=0.15, command=self.__handleExitButton, image_color=(1,
                                                                                                                                                                                                                                    0,
                                                                                                                                                                                                                                    0,
                                                                                                                                                                                                                                    1))
        return

    def __handleExitButton(self):
        if self.fsm.getCurrentState().getName() == 'waitCountdown' and self.localAvOnTrolley == True:
            self.disableExitButton()
            self.sendUpdate('requestHopOff')

    def disableExitButton(self):
        if hasattr(self, 'exitButton'):
            self.exitButton.destroy()
            del self.exitButton

    def emptySlot(self, index, avId):
        toon = self.cr.doId2do.get(avId)
        toon.stopSmooth()
        currToonPos = toon.getPos(render)
        toon.wrtReparentTo(render)
        slotPos = self.STAND_POSITIONS[index]
        endPos = (-20, slotPos.getY(), 1.4)
        toon.setPos(self.trolleyCar, endPos)
        endPosWrtRender = toon.getPos(render)
        toon.setPos(currToonPos)
        toon.headsUp(self.trolleyCar, endPos)
        if index <= 3:
            track = Sequence(Parallel(ActorInterval(toon, 'start-sit', startTime=1, endTime=0.0), Sequence(Wait(0.5), LerpPosInterval(toon, 0.25, Point3(-5, -4.5 + index * 3, 1.4), other=self.trolleyCar))), Func(toon.setAnimState, 'run'), LerpPosInterval(toon, 1, Point3(21 - index * 3, -5, 0.02), other=self.trolleyStation), Func(toon.setAnimState, 'neutral'), Func(toon.startSmooth), name=toon.uniqueName('emptyTrolley'), autoPause=1)
        else:
            track = Sequence(Func(toon.setAnimState, 'run'), LerpPosInterval(toon, duration=1.0, pos=endPosWrtRender, startPos=currToonPos), Func(toon.setAnimState, 'neutral'), Func(toon.startSmooth))
        if avId == base.localAvatar.doId:
            self.localAvOnTrolley = False
            track.append(Func(self.__hoppedOffTrolley))
        track.start()

    def __hoppedOffTrolley(self):
        self.acceptOnce('entertrolley_sphere', self.__handleTrolleyTrigger)
        base.localAvatar.walkControls.setCollisionsActive(1)
        self.cr.playGame.getPlace().fsm.request('walk')

    def generate(self):
        DistributedObject.announceGenerate(self)
        self.trolleyStation = self.cr.playGame.hood.loader.geom.find('**/prop_trolley_station_DNARoot')
        self.trolleyCar = self.trolleyStation.find('**/trolley_car')
        self.trolleyKey = self.trolleyStation.find('**/key')
        exitFog = Fog('TrolleyExitFog')
        exitFog.setColor(0.0, 0.0, 0.0)
        exitFog.setLinearOnsetPoint(30.0, 14.0, 0.0)
        exitFog.setLinearOpaquePoint(37.0, 14.0, 0.0)
        exitFog.setLinearFallback(70.0, 999.0, 1000.0)
        self.trolleyExitFog = self.trolleyStation.attachNewNode(exitFog)
        self.trolleyExitFogNode = exitFog
        enterFog = Fog('TrolleyEnterFog')
        enterFog.setColor(0.0, 0.0, 0.0)
        enterFog.setLinearOnsetPoint(0.0, 14.0, 0.0)
        enterFog.setLinearOpaquePoint(-7.0, 14.0, 0.0)
        enterFog.setLinearFallback(70.0, 999.0, 1000.0)
        self.trolleyEnterFog = self.trolleyStation.attachNewNode(enterFog)
        self.trolleyEnterFogNode = enterFog
        self.trolleyCar.setFogOff()
        tn = TextNode('trolleycountdowntext')
        tn.setFont(CIGlobals.getMickeyFont())
        tn.setTextColor(1, 0, 0, 1)
        tn.setAlign(TextNode.ACenter)
        self.keys = self.trolleyCar.findAllMatches('**/key')
        self.numKeys = self.keys.getNumPaths()
        self.keyInit = []
        self.keyRef = []
        for i in range(self.numKeys):
            key = self.keys[i]
            key.setTwoSided(1)
            ref = self.trolleyCar.attachNewNode('key' + `i` + 'ref')
            ref.iPosHpr(key)
            self.keyRef.append(ref)
            self.keyInit.append(key.getTransform())

        self.frontWheels = self.trolleyCar.findAllMatches('**/front_wheels')
        self.numFrontWheels = self.frontWheels.getNumPaths()
        self.frontWheelInit = []
        self.frontWheelRef = []
        for i in range(self.numFrontWheels):
            wheel = self.frontWheels[i]
            ref = self.trolleyCar.attachNewNode('frontWheel' + `i` + 'ref')
            ref.iPosHpr(wheel)
            self.frontWheelRef.append(ref)
            self.frontWheelInit.append(wheel.getTransform())

        self.backWheels = self.trolleyCar.findAllMatches('**/back_wheels')
        self.numBackWheels = self.backWheels.getNumPaths()
        self.backWheelInit = []
        self.backWheelRef = []
        for i in range(self.numBackWheels):
            wheel = self.backWheels[i]
            ref = self.trolleyCar.attachNewNode('backWheel' + `i` + 'ref')
            ref.iPosHpr(wheel)
            self.backWheelRef.append(ref)
            self.backWheelInit.append(wheel.getTransform())

        trolleyAnimationReset = Func(self.resetAnimation)
        trolleyEnterStartPos = Point3(-20, 14, -1)
        trolleyEnterEndPos = Point3(15, 14, -1)
        trolleyEnterPos = Sequence(name='TrolleyEnterPos')
        trolleyEnterPos.append(Func(self.trolleyCar.setFog, self.trolleyEnterFogNode))
        trolleyEnterPos.append(self.trolleyCar.posInterval(TROLLEY_ENTER_TIME, trolleyEnterEndPos, startPos=trolleyEnterStartPos, blendType='easeOut'))
        trolleyEnterPos.append(Func(self.trolleyCar.setFogOff))
        trolleyEnterTrack = Sequence(trolleyAnimationReset, trolleyEnterPos, name='trolleyEnter')
        keyAngle = round(TROLLEY_ENTER_TIME) * 360
        dist = Vec3(trolleyEnterEndPos - trolleyEnterStartPos).length()
        wheelAngle = dist / (2.0 * math.pi * 0.95) * 360
        trolleyEnterAnimateInterval = LerpFunctionInterval(self.animateTrolley, duration=TROLLEY_ENTER_TIME, blendType='easeOut', extraArgs=[keyAngle, wheelAngle], name='TrolleyAnimate')
        trolleyEnterSoundTrack = SoundInterval(self.trolleyAwaySfx, node=self.trolleyCar)
        self.trolleyEnterTrack = Parallel(trolleyEnterTrack, trolleyEnterAnimateInterval, trolleyEnterSoundTrack)
        trolleyExitStartPos = Point3(15, 14, -1)
        trolleyExitEndPos = Point3(50, 14, -1)
        trolleyExitPos = Sequence(name='TrolleyExitPos')
        trolleyExitPos.append(Func(self.trolleyCar.setFog, self.trolleyExitFogNode))
        trolleyExitPos.append(self.trolleyCar.posInterval(TROLLEY_EXIT_TIME, trolleyExitEndPos, startPos=trolleyExitStartPos, blendType='easeIn'))
        trolleyExitPos.append(Func(self.trolleyCar.setFogOff))
        trolleyExitStartPos = Point3(15, 14, -1)
        trolleyExitEndPos = Point3(50, 14, -1)
        trolleyExitBellInterval = SoundInterval(self.trolleyBellSfx, node=self.trolleyCar)
        trolleyExitAwayInterval = SoundInterval(self.trolleyAwaySfx, node=self.trolleyCar)
        keyAngle = round(TROLLEY_EXIT_TIME) * 360
        dist = Vec3(trolleyExitEndPos - trolleyExitStartPos).length()
        wheelAngle = dist / (2.0 * math.pi * 0.95) * 360
        trolleyExitAnimateInterval = LerpFunctionInterval(self.animateTrolley, duration=TROLLEY_EXIT_TIME, blendType='easeIn', extraArgs=[keyAngle, wheelAngle], name='TrolleyAnimate')
        self.trolleyExitTrack = Parallel(trolleyExitPos, trolleyExitBellInterval, trolleyExitAwayInterval, trolleyExitAnimateInterval, name=self.uniqueName('trolleyExit'))
        self.countdownText = self.trolleyStation.attachNewNode(tn)
        self.countdownText.setScale(3.0)
        self.countdownText.setPos(14.58, 10.77, 11.17)
        self.acceptOnce('entertrolley_sphere', self.__handleTrolleyTrigger)

    def resetAnimation(self):
        if self.keys:
            for i in range(self.numKeys):
                self.keys[i].setTransform(self.keyInit[i])

            for i in range(self.numFrontWheels):
                self.frontWheels[i].setTransform(self.frontWheelInit[i])

            for i in range(self.numBackWheels):
                self.backWheels[i].setTransform(self.backWheelInit[i])

    def animateTrolley(self, t, keyAngle, wheelAngle):
        if self.keys:
            for i in range(self.numKeys):
                key = self.keys[i]
                ref = self.keyRef[i]
                key.setH(ref, t * keyAngle)

            for i in range(self.numFrontWheels):
                frontWheel = self.frontWheels[i]
                ref = self.frontWheelRef[i]
                frontWheel.setH(ref, t * wheelAngle)

            for i in range(self.numBackWheels):
                backWheel = self.backWheels[i]
                ref = self.backWheelRef[i]
                backWheel.setH(ref, t * wheelAngle)

    def delete(self):
        self.trolleyStation = None
        self.trolleyKey = None
        self.soundMoving = None
        self.soundBell = None
        self.troleyCar = None
        self.backWheelInit = None
        self.backWheelRef = None
        self.backWheels = None
        self.frontWheelInit = None
        self.frontWheelRef = None
        self.frontWheels = None
        self.keyInit = None
        self.keyRef = None
        self.keys = None
        self.trolleyEnterTrack = None
        self.trolleyExitTrack = None
        self.trolleyExitFog = None
        self.trolleyExitFogNode = None
        self.trolleyEnterFogNode = None
        self.trolleyEnterFog = None
        self.ignore('entertrolley_sphere')
        DistributedObject.delete(self)
        return
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
    def create(self,
               generator,
               mins,
               maxs,
               material,
               roundDecimals,
               temp=False):
        solids = []

        numSides = self.numSides.getValue()
        if numSides < 3:
            return solids
        wallWidth = self.wallWidth.getValue()
        if wallWidth < 1:
            return solids
        arc = self.arc.getValue()
        if arc < 1:
            return solids
        startAngle = self.startAngle.getValue()
        if startAngle < 0 or startAngle > 359:
            return solids
        addHeight = self.addHeight.getValue()
        curvedRamp = self.curvedRamp.getValue()
        tiltAngle = self.tiltAngle.getValue()
        if abs(tiltAngle % 180) == 90:
            return solids
        tiltInterp = curvedRamp and self.tiltInterp.getValue()

        # Very similar to the pipe brush, except with options for start angle, arc, height, and tilt.
        width = maxs.x - mins.x
        length = maxs.y - mins.y
        height = maxs.z - mins.z

        majorOut = width / 2
        majorIn = majorOut - wallWidth
        minorOut = length / 2
        minorIn = minorOut - wallWidth

        start = deg2Rad(startAngle)
        tilt = deg2Rad(tiltAngle)
        angle = deg2Rad(arc) / numSides

        center = (mins + maxs) / 2

        # Calculate the coordinates of the inner and outer ellipses' points.
        outer = []
        inner = []
        for i in range(numSides + 1):
            a = start + i * angle
            h = i * addHeight
            interp = 1
            if tiltInterp:
                interp = math.cos(math.pi / numSides * (i - numSides / 2))
            tiltHeight = wallWidth / 2 * interp * math.tan(tilt)

            xval = center.x + majorOut * math.cos(a)
            yval = center.y + minorOut * math.sin(a)
            zval = mins.z
            if curvedRamp:
                zval += h + tiltHeight
            outer.append(
                LEUtils.roundVector(Point3(xval, yval, zval), roundDecimals))

            xval = center.x + majorIn * math.cos(a)
            yval = center.y + minorIn * math.sin(a)
            zval = mins.z
            if curvedRamp:
                zval += h - tiltHeight
            inner.append(
                LEUtils.roundVector(Point3(xval, yval, zval), roundDecimals))

        color = LEUtils.getRandomSolidColor()

        # create the solids
        z = LEUtils.roundVector(Point3(0, 0, height), roundDecimals)
        for i in range(numSides):
            faces = []

            # Since we are triangulating/splitting each arch segment, we need to generate 2 brushes per side
            if curvedRamp:
                # The splitting orientation depends on the curving direction of the arch
                if addHeight >= 0:
                    faces.append([
                        outer[i], outer[i] + z, outer[i + 1] + z, outer[i + 1]
                    ])
                    faces.append([
                        outer[i + 1], outer[i + 1] + z, inner[i] + z, inner[i]
                    ])
                    faces.append(
                        [inner[i], inner[i] + z, outer[i] + z, outer[i]])
                    faces.append(
                        [outer[i] + z, inner[i] + z, outer[i + 1] + z])
                    faces.append([outer[i + 1], inner[i], outer[i]])
                else:
                    faces.append([
                        inner[i + 1], inner[i + 1] + z, inner[i] + z, inner[i]
                    ])
                    faces.append([
                        outer[i], outer[i] + z, inner[i + 1] + z, inner[i + 1]
                    ])
                    faces.append(
                        [inner[i], inner[i] + z, outer[i] + z, outer[i]])
                    faces.append(
                        [inner[i + 1] + z, outer[i] + z, inner[i] + z])
                    faces.append([inner[i], outer[i], inner[i + 1]])
                solids.append(
                    self.makeSolid(generator, faces, material, temp, color))

                faces.clear()

                if addHeight >= 0:
                    faces.append([
                        inner[i + 1], inner[i + 1] + z, inner[i] + z, inner[i]
                    ])
                    faces.append([
                        inner[i], inner[i] + z, outer[i + 1] + z, outer[i + 1]
                    ])
                    faces.append([
                        outer[i + 1], outer[i + 1] + z, inner[i + 1] + z,
                        inner[i + 1]
                    ])
                    faces.append(
                        [inner[i + 1] + z, outer[i + 1] + z, inner[i] + z])
                    faces.append([inner[i], outer[i + 1], inner[i + 1]])
                else:
                    faces.append([
                        outer[i], outer[i] + z, outer[i + 1] + z, outer[i + 1]
                    ])
                    faces.append([
                        inner[i + 1], inner[i + 1] + z, outer[i] + z, outer[i]
                    ])
                    faces.append([
                        outer[i + 1], outer[i + 1] + z, inner[i + 1] + z,
                        inner[i + 1]
                    ])
                    faces.append(
                        [outer[i] + z, inner[i + 1] + z, outer[i + 1] + z])
                    faces.append([outer[i + 1], inner[i + 1], outer[i]])

                solids.append(
                    self.makeSolid(generator, faces, material, temp, color))
            else:
                h = Vec3.unitZ() * i * addHeight
                faces.append([
                    outer[i] + h, outer[i] + z + h, outer[i + 1] + z + h,
                    outer[i + 1] + h
                ])
                faces.append([
                    inner[i + 1] + h, inner[i + 1] + z + h, inner[i] + z + h,
                    inner[i] + h
                ])
                faces.append([
                    outer[i + 1] + h, outer[i + 1] + z + h,
                    inner[i + 1] + z + h, inner[i + 1] + h
                ])
                faces.append([
                    inner[i] + h, inner[i] + z + h, outer[i] + z + h,
                    outer[i] + h
                ])
                faces.append([
                    inner[i + 1] + z + h, outer[i + 1] + z + h,
                    outer[i] + z + h, inner[i] + z + h
                ])
                faces.append([
                    inner[i] + h, outer[i] + h, outer[i + 1] + h,
                    inner[i + 1] + h
                ])
                solids.append(
                    self.makeSolid(generator, faces, material, temp, color))

        return solids
Ejemplo n.º 24
0
 def bounds(self):
     return Vec3(
         self.model_bounds[0] * self.scale_x,
         self.model_bounds[1] * self.scale_y,
         self.model_bounds[2] * self.scale_z
         )
Ejemplo n.º 25
0
    def camTask(self, task):
        # query the mouse
        mouse_dx = 0
        mouse_dy = 0

        # if we have a mouse and the right button is depressed
        if base.mouseWatcherNode.hasMouse():
            if self.keyMap["mouse3"] != 0:
                self.mouse_accum.update()
            else:
                self.mouse_accum.reset()

        mouse_dx = self.mouse_accum.dx
        mouse_dy = self.mouse_accum.dy

        self.rXSpeed = fabs(self.mouse_accum.dx) * (self.cam_speed + 1) * max(5 * 1000 / self.xres, 3)
        self.rYSpeed = fabs(self.mouse_accum.dy) * (self.cam_speed + 1) * max(3 * 1000 / self.yres, 1)

        if self.keyMap["cam-left"] != 0 or mouse_dx < 0:
            if self.rSpeed < 160:
                self.rSpeed += 80 * globalClock.getDt()

            if mouse_dx != 0:
                self.camHeading += self.rXSpeed * globalClock.getDt()
            else:
                self.camHeading += self.rSpeed * globalClock.getDt()

            if self.camHeading > 360.0:
                self.camHeading = self.camHeading - 360.0
        elif self.keyMap["cam-right"] != 0 or mouse_dx > 0:
            if self.rSpeed < 160:
                self.rSpeed += 80 * globalClock.getDt()

            if mouse_dx != 0:
                self.camHeading -= self.rXSpeed * globalClock.getDt()
            else:
                self.camHeading -= self.rSpeed * globalClock.getDt()

            if self.camHeading < 0.0:
                self.camHeading = self.camHeading + 360.0
        else:
            self.rSpeed = 80

        if mouse_dy > 0:
            self.camPitch += self.rYSpeed * globalClock.getDt()
        elif mouse_dy < 0:
            self.camPitch -= self.rYSpeed * globalClock.getDt()

        # set camera heading and pitch
        base.camera.setHpr(self.camHeading, self.camPitch, 0)

        # viewer position (camera) movement control
        v = render.getRelativeVector(base.camera, Vec3.forward())
        if not self.flyMode:
            v.setZ(0.0)

        move_speed = self.cam_speeds[self.cam_speed]
        if self.keyMap["forward"] == 1:
            self.campos += v * move_speed * globalClock.getDt()
        if self.keyMap["backward"] == 1:
            self.campos -= v * move_speed * globalClock.getDt()

        # actually move the camera
        lastPos = base.camera.getPos()
        base.camera.setPos(self.campos)
        # self.plnp.setPos(self.campos)      # move the point light with the viewer position

        # WALKMODE: simple collision detection
        # we simply check a ray from slightly below the "eye point" straight down
        # for geometry collisions and if there are any we detect the point of collision
        # and adjust the camera's Z accordingly
        if self.flyMode == 0:
            # move the camera to where it would be if it made the move
            # the colliderNode moves with it
            # base.camera.setPos(self.campos)
            # check for collissons
            self.cTrav.traverse(render)
            entries = []
            for i in range(self.camGroundHandler.getNumEntries()):
                entry = self.camGroundHandler.getEntry(i)
                entries.append(entry)
                # print 'collision'
            entries.sort(lambda x, y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ()))

            if len(entries) > 0:  # and (entries[0].getIntoNode().getName() == "terrain"):
                # print len(entries)
                self.campos.setZ(entries[0].getSurfacePoint(render).getZ() + self.eyeHeight)
            else:
                self.campos = lastPos
                base.camera.setPos(self.campos)

            # if (base.camera.getZ() < self.player.getZ() + 2.0):
            #    base.camera.setZ(self.player.getZ() + 2.0)

        # update loc and hpr display
        pos = base.camera.getPos()
        hpr = base.camera.getHpr()
        self.inst2.setText("Loc: %.2f, %.2f, %.2f" % (pos.getX(), pos.getY(), pos.getZ()))
        self.inst3.setText("Hdg: %.2f, %.2f, %.2f" % (hpr.getX(), hpr.getY(), hpr.getZ()))
        return task.cont
Ejemplo n.º 26
0
    def __setattr__(self, name, value):

        if name == 'enabled':
            try:
                # try calling on_enable() on classes inheriting from Entity
                if value == True:
                    self.on_enable()
                else:
                    self.on_disable()
            except:
                pass

            if value == True:
                if not self.is_singleton():
                    self.unstash()
            else:
                if not self.is_singleton():
                    self.stash()


        if name == 'eternal':
            for c in self.children:
                c.eternal = value


        if name == 'world_parent':
            self.reparent_to(value)

        if name == 'model':
            if value is None:
                if hasattr(self, 'model') and self.model:
                    self.model.removeNode()
                    # print('removed model')
                object.__setattr__(self, name, value)
                return None

            if isinstance(value, NodePath): # pass procedural model
                if self.model is not None and value != self.model:
                    self.model.removeNode()
                object.__setattr__(self, name, value)

            elif isinstance(value, str): # pass model asset name
                m = load_model(value, application.asset_folder)
                if not m:
                    m = load_model(value, application.internal_models_folder)
                if m:
                    if self.model is not None:
                        self.model.removeNode()
                    object.__setattr__(self, name, m)
                    if isinstance(m, Mesh):
                        m.recipe = value
                    # print('loaded model successively')
                else:
                    print('missing model:', value)
                    return

            if self.model:
                self.model.reparentTo(self)
                self.model.setTransparency(TransparencyAttrib.M_dual)
                setattr(self, 'color', self.color) # reapply color after changing model
                setattr(self, 'texture', self.texture) # reapply texture after changing model
                self._vert_cache = None
                if isinstance(value, Mesh):
                    if hasattr(value, 'on_assign'):
                        value.on_assign(assigned_to=self)
                return

        if name == 'color' and value is not None:
            if not isinstance(value, Vec4):
                value = Vec4(value[0], value[1], value[2], value[3])

            if self.model:
                self.model.setColorScale(value)
                object.__setattr__(self, name, value)


        if name == 'texture_scale':
            if self.model and self.texture:
                self.model.setTexScale(TextureStage.getDefault(), value[0], value[1])

        if name == 'texture_offset':
            if self.model and self.texture:
                self.model.setTexOffset(TextureStage.getDefault(), value[0], value[1])
                self.texture = self.texture

        if name == 'position':
            # automatically add position instead of extending the tuple
            new_value = Vec3()

            if len(value) % 2 == 0:
                for i in range(0, len(value), 2):
                    new_value.add_x(value[i])
                    new_value.add_y(value[i+1])
                new_value.add_z(self.getY())

            if len(value) % 3 == 0:
                for i in range(0, len(value), 3):
                    new_value.add_x(value[i])
                    new_value.add_y(value[i+1])
                    new_value.add_z(value[i+2])

            try:
                self.setPos(new_value[0], new_value[2], new_value[1])
            except:
                pass    # can't set position

        if name == 'x': self.setX(value)
        if name == 'y': self.setZ(value)
        if name == 'z': self.setY(value)

        if name == 'origin' and self.model:
            new_value = Vec3()

            if len(value) % 2 == 0:
                for i in range(0, len(value), 2):
                    new_value.add_x(value[i])
                    new_value.add_y(value[i+1])
                new_value.add_z(self.model.getY())

            if len(value) % 3 == 0:
                for i in range(0, len(value), 3):
                    new_value.add_x(value[i])
                    new_value.add_y(value[i+1])
                    new_value.add_z(value[i+2])

            self.model.setPos(-new_value[0], -new_value[2], -new_value[1])
            object.__setattr__(self, name, new_value)
            return

        if name == 'rotation':
            new_value = Vec3()

            if len(value) % 2 == 0:
                for i in range(0, len(value), 2):
                    new_value.add_x(value[i])
                    new_value.add_y(value[i+1])
                new_value.add_z(self.getR())

            if len(value) % 3 == 0:
                for i in range(0, len(value), 3):
                    new_value.add_x(value[i])
                    new_value.add_y(value[i+1])
                    new_value.add_z(value[i+2])

            self.setHpr(Vec3(-new_value[1], -new_value[0], new_value[2]))

        if name == 'rotation_x': self.setP(-value)
        if name == 'rotation_y': self.setH(-value)
        if name == 'rotation_z': self.setR(value)

        if name == 'scale':
            if isinstance(value, (int, float, complex)):
                value = (value, value, value)

            new_value = Vec3()

            if len(value) % 2 == 0:
                for i in range(0, len(value), 2):
                    new_value.add_x(value[i])
                    new_value.add_y(value[i+1])
                new_value.add_z(self.getSy())

            if len(value) % 3 == 0:
                for i in range(0, len(value), 3):
                    new_value.add_x(value[i])
                    new_value.add_y(value[i+1])
                    new_value.add_z(value[i+2])

            for e in new_value:
                if e == 0:
                    e = .001

            self.setScale(new_value[0], new_value[2], new_value[1])

        if name == 'scale_x':
            self.set_scale(value, self.scale_z, self.scale_y)

        if name == 'scale_y':
            self.set_scale(self.scale_x, self.scale_z, value)

        if name == 'scale_z':
            self.set_scale(self.scale_x, value, self.scale_y)


        if name == 'collision' and hasattr(self, 'collider') and self.collider:
            if value:
                self.collider.node_path.unstash()
            else:
                self.collider.node_path.stash()

            object.__setattr__(self, name, value)
            return


        if name == 'render_queue':
            if self.model:
                self.model.setBin('fixed', value)

        if name == 'double_sided':
            self.setTwoSided(value)

        try:
            super().__setattr__(name, value)
        except:
            pass
Ejemplo n.º 27
0
 def getClickBox(self):
     return [Vec3(-1), Vec3(1)]
Ejemplo n.º 28
0
Archivo: Game.py Proyecto: dea398/DS4A
    def __init__(self):
        ShowBase.__init__(self)
        self.disableMouse()
        properties = WindowProperties()
        properties.setSize(1000, 750)
        self.win.requestProperties(properties)
        
        mainLight = DirectionalLight("main light")
        self.mainLightNodePath = render.attachNewNode(mainLight)
        self.mainLightNodePath.setHpr(45, -45, 0)
        
        render.setLight(self.mainLightNodePath)
        ambientLight = AmbientLight("ambient light")
        ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1))
        self.ambientLightNodePath = render.attachNewNode(ambientLight)
        render.setLight(self.ambientLightNodePath)
        render.setShaderAuto()

        self.environment = loader.loadModel("Models/Misc/environment")
        self.environment.reparentTo(render)

        self.camera.setPos(0, 0, 32)
        self.camera.setP(-90)

        self.keyMap = {
            "up" : False,
            "down" : False,
            "left" : False,
            "right" : False,
            "shoot" : False
        }

        self.accept("w", self.updateKeyMap, ["up", True])
        self.accept("w-up", self.updateKeyMap, ["up", False])
        self.accept("s", self.updateKeyMap, ["down", True])
        self.accept("s-up", self.updateKeyMap, ["down", False])
        self.accept("a", self.updateKeyMap, ["left", True])
        self.accept("a-up", self.updateKeyMap, ["left", False])
        self.accept("d", self.updateKeyMap, ["right", True])
        self.accept("d-up", self.updateKeyMap, ["right", False])
        self.accept("mouse1", self.updateKeyMap, ["shoot", True])
        self.accept("mouse1-up", self.updateKeyMap, ["shoot", False])

        self.pusher = CollisionHandlerPusher()
        self.cTrav = CollisionTraverser()
        self.pusher.setHorizontal(True)

        wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2)
        wallNode = CollisionNode("wall")
        wallNode.addSolid(wallSolid)
        wall = render.attachNewNode(wallNode)
        wall.setY(8.0)

        wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2)
        wallNode = CollisionNode("wall")
        wallNode.addSolid(wallSolid)
        wall = render.attachNewNode(wallNode)
        wall.setY(-8.0)

        wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2)
        wallNode = CollisionNode("wall")
        wallNode.addSolid(wallSolid)
        wall = render.attachNewNode(wallNode)
        wall.setX(8.0)

        wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2)
        wallNode = CollisionNode("wall")
        wallNode.addSolid(wallSolid)
        wall = render.attachNewNode(wallNode)
        wall.setX(-8.0)

        self.updateTask = taskMgr.add(self.update, "update")

        self.player = Player(Vec3(0, 0, 0),
                            "Models/PandaChan/act_p3d_chan",
                              {
                                  "stand" : "Models/PandaChan/a_p3d_chan_idle",
                                  "walk" : "Models/PandaChan/a_p3d_chan_run"
                              },
                            5,
                            10,
                            "player")

        self.tempEnemy = WalkingEnemy(Vec3(5, 0, 0))
Ejemplo n.º 29
0
    def __init__(self):
        self.login = "******"
        base.setFrameRateMeter(True)
        #input states
        inputState.watchWithModifiers('forward', 'w')
        inputState.watchWithModifiers('left', 'a')
        inputState.watchWithModifiers('brake', 's')
        inputState.watchWithModifiers('right', 'd')
        inputState.watchWithModifiers('turnLeft', 'q')
        inputState.watchWithModifiers('turnRight', 'e')

        self.keyMap = {
            "hello": 0,
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "cam-left": 0,
            "cam-right": 0,
            "chat0": 0,
            "powerup": 0,
            "reset": 0
        }
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        # Network Setup
        self.cManager = ConnectionManager(self)
        self.startConnection()
        #self.cManager.sendRequest(Constants.CMSG_LOGIN, ["username", "password"])
        # chat box
        # self.chatbox = Chat(self.cManager, self)

        # Set up the environment
        #
        self.initializeBulletWorld(False)

        #self.createEnvironment()
        Track(self.bulletWorld)

        # Create the main character, Ralph

        self.mainCharRef = Vehicle(self.bulletWorld, (100, 10, 5, 0, 0, 0),
                                   self.login)
        #self.mainCharRef = Character(self, self.bulletWorld, 0, "Me")
        self.mainChar = self.mainCharRef.chassisNP
        #self.mainChar.setPos(0, 25, 16)

        #         self.characters.append(self.mainCharRef)

        #         self.TestChar = Character(self, self.bulletWorld, 0, "test")
        #         self.TestChar.actor.setPos(0, 0, 0)

        self.previousPos = self.mainChar.getPos()
        taskMgr.doMethodLater(.1, self.updateMove, 'updateMove')

        # Set Dashboard
        self.dashboard = Dashboard(self.mainCharRef, taskMgr)

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation
        self.accept("escape", self.doExit)
        self.accept("a", self.setKey, ["left", 1])
        self.accept("d", self.setKey, ["right", 1])
        self.accept("w", self.setKey, ["forward", 1])
        self.accept("s", self.setKey, ["backward", 1])
        self.accept("arrow_left", self.setKey, ["cam-left", 1])
        self.accept("arrow_right", self.setKey, ["cam-right", 1])
        self.accept("a-up", self.setKey, ["left", 0])
        self.accept("d-up", self.setKey, ["right", 0])
        self.accept("w-up", self.setKey, ["forward", 0])
        self.accept("s-up", self.setKey, ["backward", 0])
        self.accept("arrow_left-up", self.setKey, ["cam-left", 0])
        self.accept("arrow_right-up", self.setKey, ["cam-right", 0])
        self.accept("h", self.setKey, ["hello", 1])
        self.accept("h-up", self.setKey, ["hello", 0])
        self.accept("0", self.setKey, ["chat0", 1])
        self.accept("0-up", self.setKey, ["chat0", 0])
        self.accept("1", self.setKey, ["powerup", 1])
        self.accept("1-up", self.setKey, ["powerup", 0])
        self.accept("2", self.setKey, ["powerup", 2])
        self.accept("2-up", self.setKey, ["powerup", 0])
        self.accept("3", self.setKey, ["powerup", 3])
        self.accept("3-up", self.setKey, ["powerup", 0])
        self.accept("r", self.doReset)
        self.accept("p", self.setTime)

        #taskMgr.add(self.move, "moveTask")

        # Game state variables
        self.isMoving = False

        # Sky Dome
        self.sky = SkyDome()

        # Set up the camera
        self.camera = Camera(self.mainChar)
        #base.disableMouse()
        #base.camera.setPos(self.mainChar.getX(), self.mainChar.getY() + 10, self.mainChar.getZ() + 2)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        directionalLight2 = DirectionalLight("directionalLight2")
        directionalLight2.setDirection(Vec3(5, 5, -5))
        directionalLight2.setColor(Vec4(1, 1, 1, 1))
        directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
        render.setLight(render.attachNewNode(directionalLight2))

        # Game initialisation
        self.gameState = self.gameStateDict["Login"]
        self.responseValue = -1

        self.cManager.sendRequest(Constants.CMSG_LOGIN, [self.login, "1234"])
        taskMgr.add(self.enterGame, "EnterGame")

        # Create Powerups
        self.createPowerups()
        taskMgr.add(self.powerups.checkPowerPickup, "checkPowerupTask")
        taskMgr.add(self.usePowerup, "usePowerUp")
Ejemplo n.º 30
0
    def __init__(self):
        ShowBase.__init__(self)

        self.grid = np.loadtxt("input/maze.txt")
        f = open("input/start_point.txt", "r")
        self.start_pos = eval(f.read())

        if FULLSCREEN:
            wp = WindowProperties()
            wp.setFullscreen(True)
            base.win.requestProperties(wp)

        self.disableMouse()
        self.accept("escape", sys.exit)
        self.camera.setPosHpr(self.start_pos[0], self.start_pos[1],
                              CAMERA_SCALE, 0, -90, 0)

        # maze wall
        offset = 0.05  # expand collision boundaries for the walls
        for i in range(-1, len(self.grid) + 1):
            for j in range(-1, len(self.grid[0]) + 1):
                if i == -1 or j == -1 or i == len(self.grid) or j == len(
                        self.grid[0]) or self.grid[i][j]:
                    #box-1_-1 is not a valid name so we change it to boxa_b
                    texti = i
                    textj = j
                    if i == -1:
                        texti = 'a'
                    if j == -1:
                        textj = 'b'
                    suffix = str(texti) + "_" + str(textj)
                    # model
                    exec("self.box" + suffix +
                         " = self.loader.loadModel('models/cube')")
                    exec("self.box" + suffix + ".reparentTo(self.render)")
                    exec("self.box" + suffix + ".setPos(" + str(i) + ", " +
                         str(j) + ", 1)")
                    # collision node
                    exec("self.boxCollider" + suffix + " = self.box" + suffix +
                         ".attachNewNode(CollisionNode('wall_collide'))")
                    exec(
                        "self.boxCollider" + suffix +
                        ".node().addSolid(CollisionBox(Point3(0-offset,0-offset,0-offset),Point3(1+offset,1+offset,1+offset)))"
                    )
                    exec("self.boxCollider" + suffix +
                         ".node().setIntoCollideMask(BitMask32.bit(0))")
                    #exec("self.boxCollider" + suffix + ".show()")

        # maze ground model
        self.maze = loader.loadModel("models/cube")
        self.maze.setScale(len(self.grid), len(self.grid[0]), 1)
        self.maze.reparentTo(self.render)

        # maze ground collision node
        self.walls = self.maze.attachNewNode(CollisionNode('wall_collide'))
        self.walls.node().addSolid(
            CollisionBox(Point3(0, 0, 0), Point3(1, 1, 1)))
        self.walls.node().setIntoCollideMask(BitMask32.bit(1))

        # maze ground plane collision node
        self.mazeGround = self.maze.attachNewNode(
            CollisionNode('ground_collide'))
        self.mazeGround.node().addSolid(
            CollisionPlane(Plane(Vec3(0, 0, 1), Point3(2, 2, 1))))
        self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1))

        # ball model
        self.ballRoot = render.attachNewNode("ballRoot")
        self.ball = loader.loadModel("models/ball")
        self.ball.reparentTo(self.ballRoot)

        # ball material
        m = Material()
        m.setSpecular((1, 1, 1, 1))
        m.setShininess(96)
        self.ball.setMaterial(m, 1)

        # ball collision node
        self.ballSphere = self.ball.find("**/ball")
        self.ballSphere.node().setFromCollideMask(BitMask32.bit(0))
        self.ballSphere.node().setIntoCollideMask(BitMask32.allOff())

        # collision ray
        self.ballGroundRay = CollisionRay()
        self.ballGroundRay.setOrigin(0, 0, 10)
        self.ballGroundRay.setDirection(0, 0, -1)

        # ray collision node
        self.ballGroundCol = CollisionNode('groundRay')
        self.ballGroundCol.addSolid(self.ballGroundRay)
        self.ballGroundCol.setFromCollideMask(BitMask32.bit(1))
        self.ballGroundCol.setIntoCollideMask(BitMask32.allOff())

        # ray
        self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol)

        # collision traverser and handler queue
        self.cHandler = CollisionHandlerQueue()
        self.cTrav = CollisionTraverser()
        self.cTrav.addCollider(self.ballSphere, self.cHandler)
        self.cTrav.addCollider(self.ballGroundColNp, self.cHandler)

        # visual effects
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.55, .55, .55, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(LVector3(0, 0, -1))
        directionalLight.setColor((0.375, 0.375, 0.375, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        self.ballRoot.setLight(render.attachNewNode(ambientLight))
        self.ballRoot.setLight(render.attachNewNode(directionalLight))

        self.start()
Ejemplo n.º 31
0
 def explosionSequence(self):
     self.exploding = True
     self.explosionModel.setPosHpr( Vec3(self.player.getX(),self.player.getY(), \
                            self.player.getZ()), Vec3( self.player.getH(),0,0))
     self.player.hide()
     taskMgr.add(self.expandExplosion, 'expandExplosion')
Ejemplo n.º 32
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
Ejemplo n.º 33
0
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
Ejemplo n.º 34
0
 def world_position(self, value):
     value = Vec3(value[0], value[2], value[1])
     self.setPos(render, value)
Ejemplo n.º 35
0
class Position:
    value: Vec3 = field(default_factory=lambda: Vec3(0, 0, 0))
Ejemplo n.º 36
0
 def position(self):
     return Vec3(self.getX(), self.getZ(), self.getY())
Ejemplo n.º 37
0
 def getUpdatedProperties(self, obj, inst):
     transform = inst.getTransform(obj.np.getParent())
     return {
         "origin": Point3(transform.getPos()),
         "angles": Vec3(transform.getHpr())
     }
Ejemplo n.º 38
0
 def world_rotation(self):
     rotation = self.getHpr(base.render)
     return Vec3(-rotation[1], -rotation[0], rotation[2])
 def add_warning(self, msg):
     """ Adds a new warning message """
     self.add_text(msg, Vec3(1, 1, 0.2))
Ejemplo n.º 40
0
 def rotation(self):
     rotation = self.getHpr()
     return Vec3(-rotation[1], -rotation[0], rotation[2])
Ejemplo n.º 41
0
 def getClickBox(self):
     return [Vec3(-1, -0.2, -1), Vec3(1, 0.2, 1)]
Ejemplo n.º 42
0
 def onTransformDone(self):
     self.toolVisRoot.setHpr(Vec3(0))
     self.setBoxToSelection()
    def generate(self):
        DistributedObject.announceGenerate(self)
        self.trolleyStation = self.cr.playGame.hood.loader.geom.find('**/prop_trolley_station_DNARoot')
        self.trolleyCar = self.trolleyStation.find('**/trolley_car')
        self.trolleyKey = self.trolleyStation.find('**/key')
        exitFog = Fog('TrolleyExitFog')
        exitFog.setColor(0.0, 0.0, 0.0)
        exitFog.setLinearOnsetPoint(30.0, 14.0, 0.0)
        exitFog.setLinearOpaquePoint(37.0, 14.0, 0.0)
        exitFog.setLinearFallback(70.0, 999.0, 1000.0)
        self.trolleyExitFog = self.trolleyStation.attachNewNode(exitFog)
        self.trolleyExitFogNode = exitFog
        enterFog = Fog('TrolleyEnterFog')
        enterFog.setColor(0.0, 0.0, 0.0)
        enterFog.setLinearOnsetPoint(0.0, 14.0, 0.0)
        enterFog.setLinearOpaquePoint(-7.0, 14.0, 0.0)
        enterFog.setLinearFallback(70.0, 999.0, 1000.0)
        self.trolleyEnterFog = self.trolleyStation.attachNewNode(enterFog)
        self.trolleyEnterFogNode = enterFog
        self.trolleyCar.setFogOff()
        tn = TextNode('trolleycountdowntext')
        tn.setFont(CIGlobals.getMickeyFont())
        tn.setTextColor(1, 0, 0, 1)
        tn.setAlign(TextNode.ACenter)
        self.keys = self.trolleyCar.findAllMatches('**/key')
        self.numKeys = self.keys.getNumPaths()
        self.keyInit = []
        self.keyRef = []
        for i in range(self.numKeys):
            key = self.keys[i]
            key.setTwoSided(1)
            ref = self.trolleyCar.attachNewNode('key' + `i` + 'ref')
            ref.iPosHpr(key)
            self.keyRef.append(ref)
            self.keyInit.append(key.getTransform())

        self.frontWheels = self.trolleyCar.findAllMatches('**/front_wheels')
        self.numFrontWheels = self.frontWheels.getNumPaths()
        self.frontWheelInit = []
        self.frontWheelRef = []
        for i in range(self.numFrontWheels):
            wheel = self.frontWheels[i]
            ref = self.trolleyCar.attachNewNode('frontWheel' + `i` + 'ref')
            ref.iPosHpr(wheel)
            self.frontWheelRef.append(ref)
            self.frontWheelInit.append(wheel.getTransform())

        self.backWheels = self.trolleyCar.findAllMatches('**/back_wheels')
        self.numBackWheels = self.backWheels.getNumPaths()
        self.backWheelInit = []
        self.backWheelRef = []
        for i in range(self.numBackWheels):
            wheel = self.backWheels[i]
            ref = self.trolleyCar.attachNewNode('backWheel' + `i` + 'ref')
            ref.iPosHpr(wheel)
            self.backWheelRef.append(ref)
            self.backWheelInit.append(wheel.getTransform())

        trolleyAnimationReset = Func(self.resetAnimation)
        trolleyEnterStartPos = Point3(-20, 14, -1)
        trolleyEnterEndPos = Point3(15, 14, -1)
        trolleyEnterPos = Sequence(name='TrolleyEnterPos')
        trolleyEnterPos.append(Func(self.trolleyCar.setFog, self.trolleyEnterFogNode))
        trolleyEnterPos.append(self.trolleyCar.posInterval(TROLLEY_ENTER_TIME, trolleyEnterEndPos, startPos=trolleyEnterStartPos, blendType='easeOut'))
        trolleyEnterPos.append(Func(self.trolleyCar.setFogOff))
        trolleyEnterTrack = Sequence(trolleyAnimationReset, trolleyEnterPos, name='trolleyEnter')
        keyAngle = round(TROLLEY_ENTER_TIME) * 360
        dist = Vec3(trolleyEnterEndPos - trolleyEnterStartPos).length()
        wheelAngle = dist / (2.0 * math.pi * 0.95) * 360
        trolleyEnterAnimateInterval = LerpFunctionInterval(self.animateTrolley, duration=TROLLEY_ENTER_TIME, blendType='easeOut', extraArgs=[keyAngle, wheelAngle], name='TrolleyAnimate')
        trolleyEnterSoundTrack = SoundInterval(self.trolleyAwaySfx, node=self.trolleyCar)
        self.trolleyEnterTrack = Parallel(trolleyEnterTrack, trolleyEnterAnimateInterval, trolleyEnterSoundTrack)
        trolleyExitStartPos = Point3(15, 14, -1)
        trolleyExitEndPos = Point3(50, 14, -1)
        trolleyExitPos = Sequence(name='TrolleyExitPos')
        trolleyExitPos.append(Func(self.trolleyCar.setFog, self.trolleyExitFogNode))
        trolleyExitPos.append(self.trolleyCar.posInterval(TROLLEY_EXIT_TIME, trolleyExitEndPos, startPos=trolleyExitStartPos, blendType='easeIn'))
        trolleyExitPos.append(Func(self.trolleyCar.setFogOff))
        trolleyExitStartPos = Point3(15, 14, -1)
        trolleyExitEndPos = Point3(50, 14, -1)
        trolleyExitBellInterval = SoundInterval(self.trolleyBellSfx, node=self.trolleyCar)
        trolleyExitAwayInterval = SoundInterval(self.trolleyAwaySfx, node=self.trolleyCar)
        keyAngle = round(TROLLEY_EXIT_TIME) * 360
        dist = Vec3(trolleyExitEndPos - trolleyExitStartPos).length()
        wheelAngle = dist / (2.0 * math.pi * 0.95) * 360
        trolleyExitAnimateInterval = LerpFunctionInterval(self.animateTrolley, duration=TROLLEY_EXIT_TIME, blendType='easeIn', extraArgs=[keyAngle, wheelAngle], name='TrolleyAnimate')
        self.trolleyExitTrack = Parallel(trolleyExitPos, trolleyExitBellInterval, trolleyExitAwayInterval, trolleyExitAnimateInterval, name=self.uniqueName('trolleyExit'))
        self.countdownText = self.trolleyStation.attachNewNode(tn)
        self.countdownText.setScale(3.0)
        self.countdownText.setPos(14.58, 10.77, 11.17)
        self.acceptOnce('entertrolley_sphere', self.__handleTrolleyTrigger)
Ejemplo n.º 44
0
    def world_scale(self, value):
        if isinstance(value, (int, float, complex)):
            value = (value, value, value)

        self.setScale(base.render, Vec3(value[0], value[2], value[1]))
Ejemplo n.º 45
0
 def exitNormal(self):
     self.setAnimState('off', 1.0)
     if self.isLocal:
         self.activity.orthoWalk.stop()
     self.toon.lerpLookAt(Vec3.forward(), time=0.2, blink=0)
Ejemplo n.º 46
0
 def enterNormal(self):
     self.notify.debug('enterNormal')
     self.setAnimState('Catching', 1.0)
     if self.isLocal:
         self.activity.orthoWalk.start()
     self.toon.lerpLookAt(Vec3.forward() + Vec3.up(), time=0.2, blink=0)
Ejemplo n.º 47
0
 def update(self):
     self.velocity = self.velocity + self.acceleration
     self.location = self.location + self.velocity
     self.acceleration = Vec3.zero()
Ejemplo n.º 48
0
 def setDestination(self, destination):
     self.destination = Vec3(destination[0], destination[1], 0)
     self.destinationNode.setPos(self.destination)
Ejemplo n.º 49
0
 def construct(self, size):
     self.size = size
     node = BulletRigidBodyNode()
     shape = BulletBoxShape(Vec3(*size))
     node.addShape(shape)
     return node
Ejemplo n.º 50
0
 def right(self):
     vec =  render.getRelativeVector(self, (1, 0, 0))
     return Vec3(vec[0], vec[2], vec[1])
 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())
Ejemplo n.º 52
0
 def up(self):
     vec = render.getRelativeVector(self, (0, 0, 1))
     return Vec3(vec[0], vec[2], vec[1])
Ejemplo n.º 53
0
 def world_scale_z(self, value):
     self.setScale(base.render, Vec3(self.world_scale_x, value, self.world_scale_y))
Ejemplo n.º 54
0
    def load_vehicle(self, pos=(0.0, -20.0, -0.6), quat=None):
        # Chassis
        self._mass = self.params['mass']
        #chassis_shape = self.params['chassis_shape']
        shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5))
        ts = TransformState.makePos(Point3(0, 0, 0.5))

        self.vehicle_pointer = self.worldNP.attachNewNode(
            BulletRigidBodyNode('Vehicle'))
        self.vehicle_node = self.vehicle_pointer.node()
        self.vehicle_node.addShape(shape, ts)
        self.previous_pos = pos
        self.vehicle_pointer.setPos(pos[0], pos[1], pos[2])
        if quat is not None:
            self.vehicle_pointer.setQuat(quat)
        self.previous_quat = self.vehicle_pointer.getQuat()
        self.vehicle_node.setMass(self._mass)
        self.vehicle_node.setDeactivationEnabled(False)

        #        first_person = self.params['first_person']
        self.camera_sensor = Panda3dCameraSensor(base,
                                                 color=True,
                                                 depth=True,
                                                 size=(160, 90))

        self.camera_node = self.camera_sensor.cam
        #        if first_person:
        #            self.camera_node.setPos(0.0, 1.0, 1.0)
        #            self.camera_node.lookAt(0.0, 6.0, 0.0)
        #        else:
        #            self.camera_node.setPos(0.0, -10.0, 5.0)
        #            self.camera_node.lookAt(0.0, 5.0, 0.0)

        self.camera_node.reparentTo(self.vehicle_pointer)
        self.camera_node.setPos(0.0, 1.0, 1.0)
        self.camera_node.lookAt(0.0, 6.0, 0.0)

        self.back_camera_sensor = Panda3dCameraSensor(base,
                                                      color=True,
                                                      depth=True,
                                                      size=(160, 90))

        self.back_camera_node = self.back_camera_sensor.cam
        #        if first_person:
        #            self.camera_node.setPos(0.0, 1.0, 1.0)
        #            self.camera_node.lookAt(0.0, 6.0, 0.0)
        #        else:
        #            self.camera_node.setPos(0.0, -10.0, 5.0)
        #            self.camera_node.lookAt(0.0, 5.0, 0.0)

        self.back_camera_node.reparentTo(self.vehicle_pointer)
        self.back_camera_node.setPos(0.0, -1.0, 1.0)
        self.back_camera_node.lookAt(0.0, -6.0, 0.0)

        self.world.attachRigidBody(self.vehicle_node)

        self.vehicle_node.setCcdSweptSphereRadius(1.0)
        self.vehicle_node.setCcdMotionThreshold(1e-7)

        # Vehicle
        self.vehicle = BulletVehicle(self.world, self.vehicle_node)
        self.vehicle.setCoordinateSystem(ZUp)
        self.world.attachVehicle(self.vehicle)

        self.yugoNP = loader.loadModel('../models/yugo/yugo.egg')
        self.yugoNP.reparentTo(self.vehicle_pointer)

        self._wheels = []
        # Right front wheel
        np = loader.loadModel('../models/yugo/yugotireR.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(0.70, 1.05, 0.3), True, np)
        # Left front wheel
        np = loader.loadModel('../models/yugo/yugotireL.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(-0.70, 1.05, 0.3), True, np)
        # Right rear wheel
        np = loader.loadModel('../models/yugo/yugotireR.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(0.70, -1.05, 0.3), False, np)
        # Left rear wheel
        np = loader.loadModel('../models/yugo/yugotireL.egg')
        np.reparentTo(self.worldNP)
        self.addWheel(Point3(-0.70, -1.05, 0.3), False, np)
Ejemplo n.º 55
0
 def scale(self):
     scale = self.getScale()
     return Vec3(scale[0], scale[2], scale[1])
Ejemplo n.º 56
0
 def forward(self):
     vec =  render.getRelativeVector(self, (0, 1, 0))
     return Vec3(vec[0], vec[2], vec[1])
Ejemplo n.º 57
0
 def world_scale(self):
     scale = self.getScale(base.render)
     return Vec3(scale[0], scale[2], scale[1])
Ejemplo n.º 58
0
 def attachRing(self, showbase):
     self.ringNode = showbase.loader.loadModel('models/ring')
     self.ringNode.setPos(-Vec3(0, 0, 1.25))
     self.ringNode.reparentTo(self.head)