Ejemplo n.º 1
0
 def __updateCanvasZpos(self,Zpos):
     newZ=clampScalar(Zpos, .0, self.canvasLen-self.frameHeight+.015)
     self.canvas.setZ(newZ)
     thumbZ=-newZ*self.canvasRatio
     self.vertSliderThumb.setZ(thumbZ)
     self.pageUpRegion['frameSize']=(-.015,.015,thumbZ-.01,-.01)
     self.pageDnRegion['frameSize']=(-.015,.015,-self.frameHeight+.01,thumbZ+self.vertSliderThumb['frameSize'][2])
Ejemplo n.º 2
0
 def __prevItem(self):
     if self.numItems:
         self.sel = clampScalar(0, self.numItems - 1,
                                (self.sel -
                                 1) if self.sel > -1 else self.numItems - 1)
         self.__putPointerAtItem()
         self.selByKey = True
Ejemplo n.º 3
0
 def cameraZoom(
     self,
     zoomFactor,
 ):
     """Scale and clamp zoom level, then set distance by it."""
     self.zoomLvl = clampScalar(self.zoomLvl * zoomFactor, *self.zoomClamp)
     self.setDist(self.zoomLvl)
    def dartTask(self, task):
        for dart in self.dartList:
            desiredPos = dart.getDefaultPos()
            (newPos, theta) = self.clampSpherePtToHorizon(desiredPos)
            framePos = self._transSphereToFramePt(newPos)
            if -1.1000000000000001 < framePos[0]:
                pass
            framePos[0] < 1.1000000000000001
            if 1:
                if -1.1000000000000001 < framePos[1]:
                    pass
                framePos[1] < 1.1000000000000001
                if 1:
                    dart.setEdgeMode(False)
                    dart.setPos(newPos)
                    if theta:
                        theta = clampScalar(0, math.pi / 4, theta)
                        dart.setScale(-2 * theta / math.pi + 1)
                    else:
                        dart.setScale(1)
            dart.setPos(newPos)
            angle = math.atan2(-framePos[0], -framePos[1])
            angle = angle * 180 / math.pi
            dart.setEdgeMode(True)
            dart.edgeModeNode.setR(angle)
            absFramePos = (abs(framePos[0]), abs(framePos[1]))
            markerFramePos = framePos / max(absFramePos)
            dart.edgeModeNode.setPos(markerFramePos[0], 0, markerFramePos[1])

        return task.cont
Ejemplo n.º 5
0
    def dartTask(self, task):
        for dart in self.dartList:
            desiredPos = dart.getDefaultPos()
            newPos, theta = self.clampSpherePtToHorizon(desiredPos)
            framePos = self._transSphereToFramePt(newPos)
            if -1.1 < framePos[0] < 1.1:
                if -1.1 < framePos[1] < 1.1:
                    dart.setEdgeMode(False)
                    dart.setPos(newPos)
                    theta = theta and clampScalar(0, math.pi / 4, theta)
                    dart.setScale(-2 * theta / math.pi + 1)
                else:
                    dart.setScale(1)
            else:
                dart.setPos(newPos)
                angle = math.atan2(-framePos[0], -framePos[1])
                angle = angle * 180 / math.pi
                dart.setEdgeMode(True)
                dart.edgeModeNode.setR(angle)
                absFramePos = (abs(framePos[0]), abs(framePos[1]))
                markerFramePos = framePos / max(absFramePos)
                dart.edgeModeNode.setPos(markerFramePos[0], 0,
                                         markerFramePos[1])

        return task.cont
 def _mouseUpdateTask(self, task):
     if OrbitCamera._mouseUpdateTask(self, task) == task.cont or self.mouseDelta[0] or self.mouseDelta[1]:
         sensitivity = 0.5
         self.setRotation(self.getRotation() - self.mouseDelta[0] * sensitivity)
         self.setEscapement(clampScalar(self.escapement + self.mouseDelta[1] * sensitivity * 0.59999999999999998, self._minEsc, self._maxEsc))
     
     return task.cont
 def __updateNonlocalVehicle(self, task = None):
     self.curSpeed = self.smoother.getSmoothForwardVelocity()
     rotSpeed = -1 * self.smoother.getSmoothRotationalVelocity()
     self.leanAmount = self.curSpeed * rotSpeed / 500.0
     self.leanAmount = clampScalar(self.leanAmount, -10, 10)
     self.__animate()
     return Task.cont
Ejemplo n.º 8
0
 def __animate(self):
     speed = self.curSpeed
     self.spinWheels(speed / 10)
     enginePitch = clampScalar(speed / 120.0, 0.5, 15)
     self.kartLoopSfx.setPlayRate(enginePitch)
     if not self.localVehicle:
         dist = (self.getPos() - localAvatar.getPos()).length()
     if self.localVehicle:
         if self.lifter.isOnGround():
             if self.offGround > 10:
                 kart = self.geom[0].find('**/main*')
                 bumpDown1 = kart.posInterval(0.1, Vec3(0, 0, -1))
                 bumpUp1 = kart.posInterval(0.15, Vec3(0, 0, 0))
                 bumpDown2 = kart.posInterval(0.5, Vec3(0, 0, -.4))
                 bumpUp2 = kart.posInterval(0.7, Vec3(0, 0, 0))
                 bumpSeq = Sequence(bumpDown1, bumpUp1, bumpDown2, bumpUp2)
                 bumpSeq.start()
             self.offGround = 0
         else:
             self.offGround += 1
     if self.offGround == 0:
         modifier = self.surfaceModifiers[self.groundType]['shake'] * (speed / 50.0)
     else:
         modifier = 1
     roll = self.leanAmount * 1.5
     roll += (random.random() * 2 - 1) * modifier
     pitch = self.acceleration * -.005
     pitch += (random.random() * 2 - 1) * modifier
     self.rollSuspension(roll)
     self.pitchSuspension(pitch)
     return Task.cont
 def __animate(self):
     speed = self.curSpeed
     self.spinWheels(speed / 10)
     enginePitch = clampScalar(speed / 120.0, 0.5, 15)
     self.kartLoopSfx.setPlayRate(enginePitch)
     if not self.localVehicle:
         dist = (self.getPos() - localAvatar.getPos()).length()
     if self.localVehicle:
         if self.lifter.isOnGround():
             if self.offGround > 10:
                 kart = self.geom[0].find('**/main*')
                 bumpDown1 = kart.posInterval(0.1, Vec3(0, 0, -1))
                 bumpUp1 = kart.posInterval(0.15, Vec3(0, 0, 0))
                 bumpDown2 = kart.posInterval(0.5, Vec3(0, 0, -.4))
                 bumpUp2 = kart.posInterval(0.7, Vec3(0, 0, 0))
                 bumpSeq = Sequence(bumpDown1, bumpUp1, bumpDown2, bumpUp2)
                 bumpSeq.start()
             self.offGround = 0
         else:
             self.offGround += 1
     if self.offGround == 0:
         modifier = self.surfaceModifiers[self.groundType]['shake'] * (speed / 50.0)
     else:
         modifier = 1
     roll = self.leanAmount * 1.5
     roll += (random.random() * 2 - 1) * modifier
     pitch = self.acceleration * -.005
     pitch += (random.random() * 2 - 1) * modifier
     self.rollSuspension(roll)
     self.pitchSuspension(pitch)
     return Task.cont
 def doDrift(curValue, timeToMedian, dt=float(dt)):
     # mood = mood + secs/((hrs/2*(mood/2))*(secs/hr))
     """ use this to make sure that the numbers are even moving
     print curValue - (curValue + dt/(timeToMedian*7200))
     """
     newValue = curValue + dt / (timeToMedian * 7200)  #3600)#60*60)
     return clampScalar(newValue, 0., 1.)
Ejemplo n.º 11
0
 def getExtremeness(self, traitValue):
     percent = self._getTraitPercent(traitValue)
     if percent < 0.5:
         howExtreme = (0.5 - percent) * 2.0
     else:
         howExtreme = (percent - 0.5) * 2.0
     return clampScalar(howExtreme, 0.0, 1.0)
Ejemplo n.º 12
0
 def applyIdealDistance(self):
     if self.isActive():
         self.idealDistance = clampScalar(self.idealDistance,
                                          self._minDistance,
                                          self._maxDistance)
         if self._practicalDistance is None:
             self._zoomToDistance(self.idealDistance)
Ejemplo n.º 13
0
 def getExtremeness(self, traitValue):
     percent = self._getTraitPercent(traitValue)
     if percent < 0.5:
         howExtreme = (0.5 - percent) * 2.0
     else:
         howExtreme = (percent - 0.5) * 2.0
     return clampScalar(howExtreme, 0.0, 1.0)
Ejemplo n.º 14
0
 def addToMood(self, component, delta):
     # delta is in [-1..1]
     # delta will be added to component, and result is clamped to [0..1]
     assert -1. <= delta <= 1.
     value = self.mood.getComponent(component)
     value += delta
     self.setMoodComponent(component, clampScalar(value, 0., 1.))
Ejemplo n.º 15
0
 def __updateNonlocalVehicle(self, task = None):
     self.curSpeed = self.smoother.getSmoothForwardVelocity()
     rotSpeed = -1 * self.smoother.getSmoothRotationalVelocity()
     self.leanAmount = self.curSpeed * rotSpeed / 500.0
     self.leanAmount = clampScalar(self.leanAmount, -10, 10)
     self.__animate()
     return Task.cont
 def clampSpherePtToHorizon(self, pt):
     camRaySpherePt = self.findCamRaySpherePt(pt)
     if camRaySpherePt and not pt.almostEqual(camRaySpherePt, 0.0001):
         camToSphere = self.cam.getTransform(self._rNode)
         OC = camToSphere.getMat().xformPoint(Vec3(0, 0, 0))
         theta = math.acos(clampScalar(-1.0, 1.0, self._radius / OC.length()))
         axis = OC.cross(pt)
         axis.normalize()
         q = Quat(math.cos(theta / 2), axis * math.sin(theta / 2))
         ts = TransformState.makeQuat(q)
         OC.normalize()
         OC *= self._radius
         newPt = ts.getMat().xformPoint(OC)
         dTheta = math.acos(clampScalar(-1.0, 1.0, pt.dot(newPt)))
         return (newPt, dTheta)
     else:
         return (pt, 0)
Ejemplo n.º 17
0
 def getExtremeness(self, traitValue):
     # returns 'extremeness' value in [0..1] for a particular trait value
     percent = self._getTraitPercent(traitValue)
     if percent < .5:
         howExtreme = (.5 - percent) * 2.
     else:
         howExtreme = (percent - .5) * 2.
     return clampScalar(howExtreme, 0., 1.)
Ejemplo n.º 18
0
 def clampSpherePtToHorizon(self, pt):
     camRaySpherePt = self.findCamRaySpherePt(pt)
     if camRaySpherePt and not pt.almostEqual(camRaySpherePt, 0.0001):
         camToSphere = self.cam.getTransform(self._rNode)
         OC = camToSphere.getMat().xformPoint(Vec3(0, 0, 0))
         theta = math.acos(
             clampScalar(-1.0, 1.0, self._radius / OC.length()))
         axis = OC.cross(pt)
         axis.normalize()
         q = Quat(math.cos(theta / 2), axis * math.sin(theta / 2))
         ts = TransformState.makeQuat(q)
         OC.normalize()
         OC *= self._radius
         newPt = ts.getMat().xformPoint(OC)
         dTheta = math.acos(clampScalar(-1.0, 1.0, pt.dot(newPt)))
         return (newPt, dTheta)
     else:
         return (pt, 0)
 def __init__(self, name, worldMap, maxTilt=math.pi / 4, mapSize=2.0, *args, **kwargs):
     ArcBall.__init__(self, name, *args, **kwargs)
     self.worldMap = worldMap
     maxTilt = clampScalar(0, math.pi / 4.0, maxTilt)
     _maxDist = math.tan(maxTilt * 2)
     self.tsMat = Mat3(TransformState.makeScale2d(Vec2(_maxDist / mapSize / 2.0)).getMat3())
     self.tsMatInv = invert(self.tsMat)
     self._mapOrigin = self.mapPosToSpherePt(Point2(0))
     self._worldNorth = Point3(0, 1, 0)
     self._loadModels()
Ejemplo n.º 20
0
 def __init__(self, name, worldMap, maxTilt = math.pi / 4, mapSize = 2.0, *args, **kwargs):
     ArcBall.__init__(self, name, *args, **args)
     self.worldMap = worldMap
     maxTilt = clampScalar(0, math.pi / 4.0, maxTilt)
     _maxDist = math.tan(maxTilt * 2)
     self.tsMat = Mat3(TransformState.makeScale2d(Vec2(_maxDist / mapSize / 2.0)).getMat3())
     self.tsMatInv = invert(self.tsMat)
     self._mapOrigin = self.mapPosToSpherePt(Point2(0))
     self._worldNorth = Point3(0, 1, 0)
     self._loadModels()
 def _lerpEscapement(self, escapement, duration = None):
     curEsc = self.getEscapement()
     escapement = clampScalar(escapement, self._minEsc, self._maxEsc)
     if duration is None:
         diff = abs(curEsc - escapement)
         speed = (max(curEsc, self._maxEsc) - min(curEsc, self._minEsc)) * 0.025000000000000001
         duration = diff / speed
     
     self._stopEscapementLerp()
     self._escLerpIval = LerpFunctionInterval(self.setEscapement, fromData = curEsc, toData = escapement, duration = duration, blendType = 'easeOut', name = 'OrbitCamera.escapementLerp')
     self._escLerpIval.start()
 def setTrickAptitude(self, trickId, aptitude, send = 1):
     aptitude = clampScalar(aptitude, 0.0, 1.0)
     aptitudes = self.trickAptitudes
     while len(aptitudes) - 1 < trickId:
         aptitudes.append(0.0)
     if aptitudes[trickId] != aptitude:
         aptitudes[trickId] = aptitude
         if send:
             self.b_setTrickAptitudes(aptitudes)
         else:
             self.setTrickAptitudes(aptitudes, local = 1)
 def _getRotateAboutAxisQuat(self, axis, p0, p1, factor = 1.0):
     axis = axis / axis.length()
     dot0 = axis.dot(p0)
     proj0 = p0 - axis * dot0
     dot1 = axis.dot(p1)
     proj1 = p1 - axis * dot1
     axis = proj0.cross(proj1)
     area = axis.length()
     axis.normalize()
     theta = math.acos(clampScalar(-1, 1, proj0.dot(proj1) / proj0.length() * proj1.length()))
     return (Quat(math.cos(theta / 2.0), axis * math.sin(theta / 2.0)), area)
    def stickCarToGround(self):
        posList = []
        nWheels = len(self.wheelData)
        for nWheel in range(nWheels):
            cQueue = self.cQueue[nWheel]
            cQueue.sortEntries()
            if cQueue.getNumEntries() == 0:
                return
            entry = cQueue.getEntry(0)
            self.shakeWheel(nWheel, entry.getIntoNodePath())
            pos = entry.getSurfacePoint(render)
            wheelPos = self.wheelBases[nWheel].getPos(render)
            pos = wheelPos - pos
            posList.append(pos)
            cQueue.clearEntries()

        rf = posList[0].getZ()
        lf = posList[1].getZ()
        rr = posList[2].getZ()
        lr = posList[3].getZ()
        right = (rf + rr) / 2
        left = (lf + lr) / 2
        rollVal = right - left
        rollVal = clampScalar(rollVal, -1, 1)
        curRoll = self.getR()
        newRoll = curRoll + rollVal * 2.0
        self.setR(newRoll)
        if not self.stopped:
            camera.setR(-newRoll)
        front = (rf + lf) / 2
        rear = (rr + lr) / 2
        center = (front + rear) / 2
        pitchVal = front - rear
        pitchVal = clampScalar(pitchVal, -1, 1)
        curPitch = self.getP()
        newPitch = curPitch - pitchVal * 2.0
        self.setP((newPitch + curPitch) / 2.0)
        if self.proRacer:
            self.cameraNode.setP(-newPitch)
        elif not self.stopped:
            self.cameraNode.setP(-newPitch)
Ejemplo n.º 25
0
    def stickCarToGround(self):
        posList = []
        nWheels = len(self.wheelData)
        for nWheel in range(nWheels):
            cQueue = self.cQueue[nWheel]
            cQueue.sortEntries()
            if cQueue.getNumEntries() == 0:
                return
            entry = cQueue.getEntry(0)
            self.shakeWheel(nWheel, entry.getIntoNodePath())
            pos = entry.getSurfacePoint(render)
            wheelPos = self.wheelBases[nWheel].getPos(render)
            pos = wheelPos - pos
            posList.append(pos)
            cQueue.clearEntries()

        rf = posList[0].getZ()
        lf = posList[1].getZ()
        rr = posList[2].getZ()
        lr = posList[3].getZ()
        right = (rf + rr) / 2
        left = (lf + lr) / 2
        rollVal = right - left
        rollVal = clampScalar(rollVal, -1, 1)
        curRoll = self.getR()
        newRoll = curRoll + rollVal * 2.0
        self.setR(newRoll)
        if not self.stopped:
            camera.setR(-newRoll)
        front = (rf + lf) / 2
        rear = (rr + lr) / 2
        center = (front + rear) / 2
        pitchVal = front - rear
        pitchVal = clampScalar(pitchVal, -1, 1)
        curPitch = self.getP()
        newPitch = curPitch - pitchVal * 2.0
        self.setP((newPitch + curPitch) / 2.0)
        if self.proRacer:
            self.cameraNode.setP(-newPitch)
        elif not self.stopped:
            self.cameraNode.setP(-newPitch)
Ejemplo n.º 26
0
    def getOrthTiltLimitQuat(self, thetaLimit=10):
        X = Vec3.unitX()
        Y = Vec3.unitY()
        Z = Vec3.unitZ()
        upSpaceNodePath = self
        rNodeNorth = Z
        arcballNorth = -Y
        baseQuat = self._rNode.getQuat(upSpaceNodePath)
        quatX = Quat.identQuat()
        quatY = Quat.identQuat()
        rNodeToUpSpace = TransformState.makeQuat(baseQuat)
        northPole = rNodeToUpSpace.getMat().xformPoint(rNodeNorth)
        dot = northPole.dot(X)
        proj = northPole - X * dot
        theta = math.acos(
            clampScalar(-1.0, 1.0,
                        proj.dot(arcballNorth) / proj.length()))
        if theta > thetaLimit:
            theta -= thetaLimit
            if northPole.dot(Z) < 0.0:
                theta *= -1

            quatX = Quat(math.cos(theta / 2.0), X * math.sin(theta / 2.0))
            baseQuat *= quatX
            rNodeToUpSpace = TransformState.makeQuat(baseQuat)
            northPole = rNodeToUpSpace.getMat().xformPoint(rNodeNorth)

        dot = northPole.dot(Z)
        proj = northPole - Z * dot
        theta = math.acos(
            clampScalar(-1.0, 1.0,
                        proj.dot(arcballNorth) / proj.length()))
        if theta > thetaLimit:
            theta -= thetaLimit
            if northPole.dot(X) >= 0.0:
                theta *= -1

            quatY = Quat(math.cos(theta / 2.0), Z * math.sin(theta / 2.0))
            baseQuat *= quatY

        return quatX * quatY
    def setTrickAptitude(self, trickId, aptitude, send=1):
        aptitude = clampScalar(aptitude, 0.0, 1.0)
        aptitudes = self.trickAptitudes
        while len(aptitudes) - 1 < trickId:
            aptitudes.append(0.0)

        if aptitudes[trickId] != aptitude:
            aptitudes[trickId] = aptitude
            if send:
                self.b_setTrickAptitudes(aptitudes)
            else:
                self.setTrickAptitudes(aptitudes, local=1)
 def _getPtToPtQuat(self, p0, p1, factor = 1.0):
     p0.normalize()
     p1.normalize()
     theta = math.acos(clampScalar(-1, 1, p0.dot(p1)))
     axis = p0.cross(p1)
     axis.normalize()
     if factor == 1.0:
         return Quat(math.cos(theta / 2.0), axis * math.sin(theta / 2.0))
     elif 0.0 < factor:
         pass
     elif factor == 1.0:
         q = nLerp(Quat.identQuat(), Quat(math.cos(theta / 2.0), axis * math.sin(theta / 2.0)), factor)
         return q
Ejemplo n.º 29
0
 def _mouseUpdateTask(self, task):
     if OrbitCamera._mouseUpdateTask(
             self, task
     ) == task.cont and self.mouseDelta[0] or self.mouseDelta[1]:
         sensitivity = 0.5
         self.camTimer = -1.0
         self.setRotation(self.getRotation() -
                          self.mouseDelta[0] * sensitivity)
         self.setEscapement(
             clampScalar(
                 self.escapement + self.mouseDelta[1] * sensitivity * 0.6,
                 self._minEsc, self._maxEsc))
     return task.cont
Ejemplo n.º 30
0
 def _getPtToPtQuat(self, p0, p1, factor=1.0):
     p0.normalize()
     p1.normalize()
     theta = math.acos(clampScalar(-1, 1, p0.dot(p1)))
     axis = p0.cross(p1)
     axis.normalize()
     if factor == 1.0:
         return Quat(math.cos(theta / 2.0), axis * math.sin(theta / 2.0))
     elif 0.0 < factor < 1.0:
         q = nLerp(
             Quat.identQuat(),
             Quat(math.cos(theta / 2.0), axis * math.sin(theta / 2.0)),
             factor)
         return q
Ejemplo n.º 31
0
 def _getRotateAboutAxisQuat(self, axis, p0, p1, factor=1.0):
     axis = axis / axis.length()
     dot0 = axis.dot(p0)
     proj0 = p0 - axis * dot0
     dot1 = axis.dot(p1)
     proj1 = p1 - axis * dot1
     axis = proj0.cross(proj1)
     area = axis.length()
     axis.normalize()
     theta = math.acos(
         clampScalar(-1, 1,
                     proj0.dot(proj1) / proj0.length() * proj1.length()))
     return (Quat(math.cos(theta / 2.0),
                  axis * math.sin(theta / 2.0)), area)
Ejemplo n.º 32
0
 def rotateCam(self, arc):
     """Setup a lerp interval to rotate the camera about the target."""
     newP = clampScalar(self.target.getP() - arc.getY(),
                        *self.clampP)  #Clamped.
     newH = self.target.getH() + arc.getX()  #Not clamped, just added.
     LERP.LerpHprInterval(
         self.target,
         self.speed,  #Setup the interval\
         P.Vec3(
             newH,
             newP,
             self.target.getR(),
         ),
     ).start()  #and start it.
    def getOrthTiltLimitQuat(self, thetaLimit = 10):
        X = Vec3.unitX()
        Y = Vec3.unitY()
        Z = Vec3.unitZ()
        upSpaceNodePath = self
        rNodeNorth = Z
        arcballNorth = -Y
        baseQuat = self._rNode.getQuat(upSpaceNodePath)
        quatX = Quat.identQuat()
        quatY = Quat.identQuat()
        rNodeToUpSpace = TransformState.makeQuat(baseQuat)
        northPole = rNodeToUpSpace.getMat().xformPoint(rNodeNorth)
        dot = northPole.dot(X)
        proj = northPole - X * dot
        theta = math.acos(clampScalar(-1.0, 1.0, proj.dot(arcballNorth) / proj.length()))
        if theta > thetaLimit:
            theta -= thetaLimit
            if northPole.dot(Z) < 0.0:
                theta *= -1

            quatX = Quat(math.cos(theta / 2.0), X * math.sin(theta / 2.0))
            baseQuat *= quatX
            rNodeToUpSpace = TransformState.makeQuat(baseQuat)
            northPole = rNodeToUpSpace.getMat().xformPoint(rNodeNorth)

        dot = northPole.dot(Z)
        proj = northPole - Z * dot
        theta = math.acos(clampScalar(-1.0, 1.0, proj.dot(arcballNorth) / proj.length()))
        if theta > thetaLimit:
            theta -= thetaLimit
            if northPole.dot(X) >= 0.0:
                theta *= -1

            quatY = Quat(math.cos(theta / 2.0), Z * math.sin(theta / 2.0))
            baseQuat *= quatY

        return quatX * quatY
Ejemplo n.º 34
0
    def zoom(self, amount):
        if self.game.isChatting:
            return

        self.targetY = clampScalar(self.targetY + amount, -2, -15)

        if self.interval is not None:
            self.interval.pause()
        self.interval = LerpPosInterval(
            base.camera,
            duration=0.6,
            pos=Vec3(base.camera.getX(), self.targetY, base.camera.getZ()),
            blendType="easeOut",
            name="Camera.zoom",
        )
        self.interval.start()
 def getTiltLimitQuat(self, thetaLimit):
     Y = Vec3.unitY()
     Z = Vec3.unitZ()
     upSpaceNodePath = self
     rNodeNorth = Z
     arcballNorth = -Y
     rNodeToUpSpace = TransformState.makeHpr(self._rNode.getHpr(upSpaceNodePath))
     northPole = rNodeToUpSpace.getMat().xformPoint(rNodeNorth)
     dot = northPole.dot(arcballNorth)
     theta = math.acos(clampScalar(-1, 1, dot))
     if theta < thetaLimit:
         return Quat.identQuat()
     else:
         axis = northPole.cross(arcballNorth)
         axis.normalize()
         theta -= thetaLimit
         return Quat(math.cos(theta / 2.0), axis * math.sin(theta / 2.0))
Ejemplo n.º 36
0
 def getTiltLimitQuat(self, thetaLimit):
     Y = Vec3.unitY()
     Z = Vec3.unitZ()
     upSpaceNodePath = self
     rNodeNorth = Z
     arcballNorth = -Y
     rNodeToUpSpace = TransformState.makeHpr(
         self._rNode.getHpr(upSpaceNodePath))
     northPole = rNodeToUpSpace.getMat().xformPoint(rNodeNorth)
     dot = northPole.dot(arcballNorth)
     theta = math.acos(clampScalar(-1, 1, dot))
     if theta < thetaLimit:
         return Quat.identQuat()
     else:
         axis = northPole.cross(arcballNorth)
         axis.normalize()
         theta -= thetaLimit
         return Quat(math.cos(theta / 2.0), axis * math.sin(theta / 2.0))
Ejemplo n.º 37
0
    def _lerpEscapement(self, escapement, duration=None):
        curEsc = self.getEscapement()
        escapement = clampScalar(escapement, self._minEsc, self._maxEsc)
        if duration is None:
            diff = abs(curEsc - escapement)
            speed = (max(curEsc, self._maxEsc) -
                     min(curEsc, self._minEsc)) * 0.025000000000000001
            duration = diff / speed

        self._stopEscapementLerp()
        self._escLerpIval = LerpFunctionInterval(
            self.setEscapement,
            fromData=curEsc,
            toData=escapement,
            duration=duration,
            blendType='easeOut',
            name='OrbitCamera.escapementLerp')
        self._escLerpIval.start()
    def getUprightCorrectionQuat(self, pt):
        Y = Vec3.unitY()
        Z = Vec3.unitZ()
        rNodeNorth = self._north
        upSpaceNodePath = self
        axis = pt / pt.length()
        up = Z
        rNodeToUpSpace = TransformState.makeHpr(self._rNode.getHpr(upSpaceNodePath))
        northPole = rNodeToUpSpace.getMat().xformPoint(rNodeNorth)
        right = up.cross(axis)
        final = axis.cross(right)
        dot = northPole.dot(axis)
        proj = northPole - axis * dot
        theta = math.acos(clampScalar(-1.0, 1.0, proj.dot(final) / proj.length() * final.length()))
        if northPole.dot(right) < 0.0:
            theta *= -1

        return Quat(math.cos(theta / 2.0), Vec3(axis) * math.sin(theta / 2.0))
Ejemplo n.º 39
0
 def getUprightCorrectionQuat(self, pt):
     Y = Vec3.unitY()
     Z = Vec3.unitZ()
     rNodeNorth = self._north
     upSpaceNodePath = self
     axis = pt / pt.length()
     up = Z
     rNodeToUpSpace = TransformState.makeHpr(
         self._rNode.getHpr(upSpaceNodePath))
     northPole = rNodeToUpSpace.getMat().xformPoint(rNodeNorth)
     right = up.cross(axis)
     final = axis.cross(right)
     dot = northPole.dot(axis)
     proj = northPole - axis * dot
     theta = math.acos(
         clampScalar(-1.0, 1.0,
                     proj.dot(final) / (proj.length() * final.length())))
     if northPole.dot(right) < 0.0:
         theta *= -1
     return Quat(math.cos(theta / 2.0), Vec3(axis) * math.sin(theta / 2.0))
Ejemplo n.º 40
0
 def setTrickAptitude(self, trickId, aptitude, send=1):
     # use this func to set aptitudes individually; you can prevent
     # a message from being sent out by setting send=0, but don't forget
     # to then call one of the above functions to distribute the new
     # values to clients when you're done
     assert trickId != PetTricks.Tricks.BALK
     aptitude = clampScalar(aptitude, 0., 1.)
     aptitudes = self.trickAptitudes
     # This while loop produces the old behavior: the array will be only
     # as long as it needs to be. So a pet with no aptitude on any trick
     # will have an empty aptitude array instead of a populated array of
     # zeroes (i.e. [0, 0, 0, 0, 0, 0, 0]), and a pet with aptitude only
     # for trick 3 will have an array like [0, 0, 0, 1] instead of the
     # full array, i.e. [0, 0, 0, 1, 0, 0, 0].  This 'sparse' array has
     # caused confusion. See the changes above that fill out the entire
     # array.
     while ((len(aptitudes)-1) < trickId):
         aptitudes.append(0.)
     if aptitudes[trickId] != aptitude:
         aptitudes[trickId] = aptitude
         if send:
             self.b_setTrickAptitudes(aptitudes)
         else:
             self.setTrickAptitudes(aptitudes, local=1)
Ejemplo n.º 41
0
    def update(self, time):
        placeSorter = []
        placeCount = 0

        # begin updates for all racers
        for key in self.racerDict.keys():
            racer = self.racerDict[key]
            curvetime = racer.curvetime
            face = racer.face
            mapspot = racer.mapspot
            maxlaphit = racer.maxlaphit

            if (not racer.finished and racer.enabled):
                placeSorter.append((curvetime, key))
            if (racer.finished or racer.enabled):
                placeCount += 1

            pt = Vec3(0, 0, 0)

            mapT = (
                (curvetime % 1 + self.race.startT / self.race.curve.getMaxT())
                % 1) * self.race.curve.getMaxT()

            self.race.curve.getPoint(mapT, pt)
            self.race.curve.getPoint((mapT % self.race.curve.getMaxT()), pt)

            lapT = clampScalar(curvetime / self.race.lapCount, 0.0, 1.0)

            faceX = self.faceStartPos[0] * (1 -
                                            lapT) + self.faceEndPos[0] * lapT
            racer.update(faceX=faceX, mapspotPt=pt)

            # subtract out previous lap times
            t = time - self.race.baseTime - self.raceTimeDelta

            # begin updates for self only
            if (key == localAvatar.doId):
                if (self.race.laps > maxlaphit):
                    racer.update(maxlaphit=self.race.laps)
                    self.maxLapHit = racer.maxlaphit

                    if (self.maxLapHit < self.race.lapCount):
                        for y in self.timeLabels[self.maxLapHit - 1]:
                            y.configure(
                                text_font=ToontownGlobals.getSignFont())
                        for y in self.timeLabels[self.maxLapHit]:
                            y.show()
                        for y in self.timeLabels[self.maxLapHit]:
                            y.configure(
                                text_font=ToontownGlobals.getSignFont())

                        self.raceTimeDelta = globalClock.getFrameTime(
                        ) - self.race.baseTime

                        lapNotice = DirectLabel()
                        lapNotice.setScale(.1)
                        if (self.maxLapHit == self.race.lapCount - 1):
                            lapNotice[
                                'text'] = TTLocalizer.KartRace_FinalLapText
                        else:
                            lapNotice[
                                'text'] = TTLocalizer.KartRace_LapText % str(
                                    self.maxLapHit + 1)
                        taskMgr.doMethodLater(2,
                                              lapNotice.remove,
                                              "removeIt",
                                              extraArgs=[])

                self.lapLabel['text'] = str(
                    clampScalar(self.maxLapHit + 1, 1,
                                self.race.lapCount)) + '/' + str(
                                    self.race.lapCount)

        suffix = {
            1: TTLocalizer.KartRace_FirstSuffix,
            2: TTLocalizer.KartRace_SecondSuffix,
            3: TTLocalizer.KartRace_ThirdSuffix,
            4: TTLocalizer.KartRace_FourthSuffix,
        }
        placeSorter.sort()
        for x, p in zip(placeSorter, xrange(len(placeSorter), 0, -1)):
            self.racerDict[x[1]].update(place=(p + placeCount -
                                               len(placeSorter)))

        # if we are close to the finish line, and so is someone else,
        # declare a 'photo finish'
        localRacer = self.racerDict[localAvatar.doId]
        (nearDiff, farDiff) = RaceGlobals.TrackDict[self.race.trackId][8]
        if (not localRacer.finished) and (
                self.faceEndPos[0] - localRacer.face.getX() < nearDiff):
            for racerId in self.racerDict.keys():
                racer = self.racerDict[racerId]
                if (not racer.enabled or (racerId == localAvatar.doId)
                        or (racer.face.getX() >= self.faceEndPos[0])):
                    continue

                if (self.faceEndPos[0] - racer.face.getX()) < farDiff:
                    self.photoFinish = True

        if self.photoFinish:
            self.photoFinishLabel.show()
            self.placeLabelNum['text'] = ""
            self.placeLabelStr['text'] = ""
        else:
            self.photoFinishLabel.hide()
            self.placeLabelNum['text'] = str(
                self.racerDict[localAvatar.doId].place)
            self.placeLabelStr['text'] = suffix[self.racerDict[
                localAvatar.doId].place]

        # convert the time into a label displayable string
        minutes = int(t / 60)
        t -= minutes * 60
        seconds = int(t)
        # quick python ternary operator
        padding = (seconds < 10 and ['0'] or [''])[0]
        t -= seconds
        fraction = str(t)[2:4]
        fraction = fraction + '0' * (2 - len(fraction))
        if (self.timerEnabled and self.maxLapHit < self.race.lapCount):
            self.timeLabels[self.maxLapHit][0]['text'] = '%d\'' % (minutes)
            self.timeLabels[self.maxLapHit][1]['text'] = '%s%d\'\'' % (padding,
                                                                       seconds)
            self.timeLabels[self.maxLapHit][2]['text'] = '%s' % (fraction)

        if (self.race.wrongWay and not self.wrongWaySeq.isPlaying()):
            self.wrongWaySeq.loop()
        elif (not self.race.wrongWay and self.wrongWaySeq.isPlaying()):
            self.wrongWaySeq.finish()
Ejemplo n.º 42
0
    def update(self, time):
        placeSorter = []
        placeCount = 0
        for key in self.racerDict.keys():
            racer = self.racerDict[key]
            curvetime = racer.curvetime
            face = racer.face
            mapspot = racer.mapspot
            maxlaphit = racer.maxlaphit
            if not racer.finished and racer.enabled:
                placeSorter.append((curvetime, key))
            if racer.finished or racer.enabled:
                placeCount += 1
            pt = Vec3(0, 0, 0)
            mapT = (curvetime % 1 + self.race.startT / self.race.curve.getMaxT()) % 1 * self.race.curve.getMaxT()
            self.race.curve.getPoint(mapT, pt)
            self.race.curve.getPoint(mapT % self.race.curve.getMaxT(), pt)
            lapT = clampScalar(curvetime / self.race.lapCount, 0.0, 1.0)
            faceX = self.faceStartPos[0] * (1 - lapT) + self.faceEndPos[0] * lapT
            racer.update(faceX=faceX, mapspotPt=pt)
            t = time - self.race.baseTime - self.raceTimeDelta
            if key == localAvatar.doId:
                if self.race.laps > maxlaphit:
                    racer.update(maxlaphit=self.race.laps)
                    self.maxLapHit = racer.maxlaphit
                    if self.maxLapHit < self.race.lapCount:
                        for y in self.timeLabels[self.maxLapHit - 1]:
                            y.configure(text_font=ToontownGlobals.getSignFont())

                        for y in self.timeLabels[self.maxLapHit]:
                            y.show()

                        for y in self.timeLabels[self.maxLapHit]:
                            y.configure(text_font=ToontownGlobals.getSignFont())

                        self.raceTimeDelta = globalClock.getFrameTime() - self.race.baseTime
                        lapNotice = DirectLabel()
                        lapNotice.setScale(0.1)
                        if self.maxLapHit == self.race.lapCount - 1:
                            lapNotice['text'] = TTLocalizer.KartRace_FinalLapText
                        else:
                            lapNotice['text'] = TTLocalizer.KartRace_LapText % str(self.maxLapHit + 1)
                        taskMgr.doMethodLater(2, lapNotice.remove, 'removeIt', extraArgs=[])
                self.lapLabel['text'] = str(clampScalar(self.maxLapHit + 1, 1, self.race.lapCount)) + '/' + str(self.race.lapCount)

        suffix = {1: TTLocalizer.KartRace_FirstSuffix,
         2: TTLocalizer.KartRace_SecondSuffix,
         3: TTLocalizer.KartRace_ThirdSuffix,
         4: TTLocalizer.KartRace_FourthSuffix}
        placeSorter.sort()
        for x, p in zip(placeSorter, xrange(len(placeSorter), 0, -1)):
            self.racerDict[x[1]].update(place=p + placeCount - len(placeSorter))

        localRacer = self.racerDict[localAvatar.doId]
        nearDiff, farDiff = RaceGlobals.TrackDict[self.race.trackId][8]
        if not localRacer.finished and self.faceEndPos[0] - localRacer.face.getX() < nearDiff:
            for racerId in self.racerDict.keys():
                racer = self.racerDict[racerId]
                if not racer.enabled or racerId == localAvatar.doId or racer.face.getX() >= self.faceEndPos[0]:
                    continue
                if self.faceEndPos[0] - racer.face.getX() < farDiff:
                    self.photoFinish = True

        if self.photoFinish:
            self.photoFinishLabel.show()
            self.placeLabelNum['text'] = ''
            self.placeLabelStr['text'] = ''
        else:
            self.photoFinishLabel.hide()
            self.placeLabelNum['text'] = str(self.racerDict[localAvatar.doId].place)
            self.placeLabelStr['text'] = suffix[self.racerDict[localAvatar.doId].place]
        minutes = int(t / 60)
        t -= minutes * 60
        seconds = int(t)
        padding = (seconds < 10 and ['0'] or [''])[0]
        t -= seconds
        fraction = str(t)[2:4]
        fraction = fraction + '0' * (2 - len(fraction))
        if self.timerEnabled and self.maxLapHit < self.race.lapCount:
            self.timeLabels[self.maxLapHit][0]['text'] = "%d'" % minutes
            self.timeLabels[self.maxLapHit][1]['text'] = "%s%d''" % (padding, seconds)
            self.timeLabels[self.maxLapHit][2]['text'] = '%s' % fraction
        if self.race.wrongWay and not self.wrongWaySeq.isPlaying():
            self.wrongWaySeq.loop()
        elif not self.race.wrongWay and self.wrongWaySeq.isPlaying():
            self.wrongWaySeq.finish()
    def __watchControls(self, task):
        dt = globalClock.getDt()
        curVelocity = self.actorNode.getPhysicsObject().getVelocity()
        curSpeed = curVelocity.length()
        fvec = self.forward.getPos(render) - self.getPos(render)
        fvec.normalize()
        dotProduct = curVelocity.dot(fvec)
        goingBack = -1
        if dotProduct < 0:
            goingBack = 1
        if self.proRacer:
            self.__computeTurnRatio(curSpeed)
            self.__updateWheelPos(dt, curSpeed)
        newHForTurning = self.getH()
        if self.proRacer or not self.stopped and self.arrowHorz and curSpeed > 1:
            if self.proRacer:
                turnHelp = 0
                if self.hittingWall or goingBack == 1:
                    turnHelp = self.arrowHorz
                effectiveSpeed = curSpeed
                if effectiveSpeed > self.speedMinTurn:
                    effectiveSpeed = self.speedMinTurn
                rotation = -goingBack * (self.wheelPosition * dt * self.turnRatio * -1.8 * curSpeed / 100 + turnHelp * dt * self.turnRatio * -1.2)
                self.outPutCounter += 1
                if self.outPutCounter > 5:
                    self.outPutCounter = 0
            else:
                rotation = self.arrowHorz * dt * self.turnRatio * -1.2
            oldH = self.getH()
            newH = (oldH + rotation) % 360
            self.setH(newH)
            newHForTurning = newH
            if self.groundType == 'ice':
                newHForTurning = (oldH + rotation * iceTurnFactor) % 360
        pitch = -self.getP() + 5
        accelBase = self.accelerationBase
        pitch += accelBase
        pitch = clampScalar(pitch, accelBase - 5, accelBase + 5)
        self.accelerationMult = pitch * 2
        if self.groundType == 'ice':
            self.accelerationMult *= iceAccelFactor
        if self.stopped:
            self.acceleration = 0
        else:
            self.acceleration = self.arrowVert * self.accelerationMult * self.cheatFactor
            if self.proRacer:
                if self.skidding:
                    self.acceleration = self.arrowVert * self.accelerationMult * self.cheatFactor * 0.5
            if self.turbo:
                self.acceleration += self.accelerationMult * 1.5
        self.engine.setVector(Vec3(0, self.acceleration, 0))
        if self.groundType == 'ice':
            rotMat = Mat3.rotateMatNormaxis(newHForTurning, Vec3.up())
        else:
            rotMat = Mat3.rotateMatNormaxis(self.getH(), Vec3.up())
        curHeading = rotMat.xform(Vec3.forward())
        push = (3 - self.getP()) * 0.02
        curHeading.setZ(curHeading.getZ() - min(0.2, max(-.2, push)))
        onScreenDebug.append('vehicle curHeading = %s\n' % curHeading.pPrintValues())
        onScreenDebug.append('vehicle H = %s  newHForTurning=%f\n' % (self.getH(), newHForTurning))
        windResistance = self.surfaceModifiers[self.groundType]['windResistance']
        self.windResistance.setCoef(windResistance)
        physicsFrame = int((globalClock.getFrameTime() - self.physicsEpoch) * self.physicsCalculationsPerSecond)
        numFrames = min(physicsFrame - self.lastPhysicsFrame, self.maxPhysicsFrames)
        self.lastPhysicsFrame = physicsFrame
        leanIncrement = self.arrowHorz * self.physicsDt * self.turnRatio
        if self.stopped:
            leanIncrement = 0
        driftMin = self.surfaceModifiers[self.groundType]['driftMin']
        if self.proRacer:
            driftMin = self.surfaceModifiers[self.groundType]['driftMin'] * 0.2
            if self.skidding:
                driftMin = self.surfaceModifiers[self.groundType]['driftMin']
        for i in range(numFrames):
            self.physicsMgr.doPhysics(self.physicsDt)
            curVelocity = self.actorNode.getPhysicsObject().getVelocity()
            idealVelocity = curHeading * curSpeed
            curVelocity *= self.imHitMult
            driftVal = abs(self.leanAmount) * 16 / self.cheatFactor + 15 / self.cheatFactor
            curVelocity = Vec3((curVelocity * driftVal + idealVelocity) / (driftVal + 1))
            curSpeed = curVelocity.length()
            curVelocity.normalize()
            curVelocity *= min(curSpeed, 600)
            self.actorNode.getPhysicsObject().setVelocity(curVelocity)
            curSpeed = curVelocity.length()
            speedFactor = min(curSpeed, 150) / 162.0
            self.leanAmount = (self.leanAmount + leanIncrement) * speedFactor
            self.leanAmount = clampScalar(self.leanAmount, -10, 10)

        self.cWallTrav.traverse(render)
        self.curSpeed = curSpeed
        if self.proRacer:
            self.turnWheels(self.wheelPosition * -45)
        else:
            self.turnWheels(self.arrowHorz * -10)
        self.__animate()
        if self.proRacer:
            speedProporation = 1.0
            if curSpeed < self.speedMaxTurn:
                speedProporation = 0.0
            else:
                speedProporation = (curSpeed - self.speedMaxTurn) / self.speedMinTurn
            cameraDist = self.cameraArmBase + self.cameraArmExtend * speedProporation
            cameraOffset = Point3(0, -cameraDist, 0)
            self.cameraNode.setPos(cameraOffset)
            behindPos = render.getRelativePoint(self, Point3(0, -30, 0))
            self.proCameraDummyNode.setPos(render, behindPos)
            self.proCameraDummyNode.lookAt(self)
            self.cameraNode.lookAt(self)
            dir1 = self.proCameraDummyNode.getH()
            dir2 = self.proCameraHeading
            if dir1 > 180:
                dir1 -= 360
            elif dir1 < -180:
                dir1 += 360
            if dir2 > 180:
                dir2 -= 360
            elif dir2 < -180:
                dir2 += 360
            self.proCameraHeading = dir2
            dif = dir1 - dir2
            if dif > 180:
                dif -= 360
            elif dif < -180:
                dif += 360
            speedDif = abs(dif)
            if speedDif > 90:
                speedDif = 90
            cameraTightener = 1.0
            if curSpeed > self.speedMinTurn:
                cameraTightener = self.cameraTightener
            else:
                cameraTightener = 1.0 + curSpeed / self.speedMinTurn * (self.cameraTightener - 1.0)
            swingSpeedRatio = speedDif / 90
            swingSpeed = self.armSwingSpeedPerp * swingSpeedRatio + self.armSwingSpeedPara * (1 - swingSpeedRatio)
            self.proCameraHeading += dif * cameraTightener * (dt / swingSpeed)
            self.cameraArmNode.setH(self.proCameraHeading - self.getH())
        elif not self.stopped:
            self.cameraNode.setH(self.leanAmount)
        self.updateParticles(self.leanAmount)
        if (self.leanAmount > 8 or self.leanAmount < -8) and self.offGround <= 0:
            self.startSkid()
        else:
            self.stopSkid()
        if self.speedometer:
            self.speedometer['text'] = str(int(curSpeed / 3))
            self.speedGauge.setR(min(110, max(0, curSpeed / 3 / 120 * 110)))
        if not self.stopped:
            self.stickCarToGround()
        if self.__clampPosition():
            self.notify.debug('did a clampPosition on %d' % self.doId)
        return Task.cont
    def createCurvedArrow(self, axis, p0, p1, width, numPanels = 10):
        N = numPanels
        self.tail_geom_node.removeAllGeoms()
        self.head_geom_node.removeAllGeoms()
        axis = axis / axis.length()
        dot0 = axis.dot(p0)
        proj0 = p0 - axis * dot0
        dot1 = axis.dot(p1)
        proj1 = p1 - axis * dot1
        theta = math.acos(clampScalar(-1, 1, proj0.dot(proj1) / proj0.length() * proj1.length()))
        if not proj0.almostEqual(proj1, 0.0001) and theta != 0:
            if proj0.lengthSquared() >= proj1.lengthSquared():
                A = proj0
                C = proj1
            else:
                A = proj1
                C = proj0
            a = A.length()
            aUnit = A / a
            x = A.dot(C) / a
            yy = C.lengthSquared() - x * x
            bUnit = A.cross(C).cross(A)
            bUnit.normalize()
            b = math.sqrt(max(0.0, yy / (1 - x * x / a * a)))
            t = math.atan2(a, b / math.tan(theta))
            aUnit *= a
            bUnit *= b
            pts = [ aUnit * math.cos(x * t / N) + bUnit * math.sin(x * t / N) for x in range(N + 1) ]
            pts = [ pt + axis * math.sqrt(self._radius * self._radius - pt.lengthSquared()) for pt in pts ]
            if A != proj0:
                pts.reverse()

            format = GeomVertexFormat.getV3c4t2()
            vertex_data = GeomVertexData('arc_ball', format, Geom.UHStatic)
            vertex_writer = GeomVertexWriter(vertex_data, 'vertex')
            color_writer = GeomVertexWriter(vertex_data, 'color')
            texture_writer = GeomVertexWriter(vertex_data, 'texcoord')
            triStrip = GeomTristrips(Geom.UHStatic)
            cross = pts[0].cross(pts[1] - pts[0])
            cross.normalize()
            cross *= width / 2.0
            pt = pts[0]
            vertex_writer.addData3f(pt[0] + cross[0], pt[1] + cross[1], pt[2] + cross[2])
            vertex_writer.addData3f(pt[0] - cross[0], pt[1] - cross[1], pt[2] - cross[2])
            color_writer.addData4f(0, 1, 0, 1)
            color_writer.addData4f(0, 1, 0, 1)
            texture_writer.addData2f(0, 1)
            texture_writer.addData2f(1, 1)
            diffA = pts[1] - pts[0]
            diffB = pts[2] - pts[1]
            cross = pts[1].cross((diffB + diffA) / 2.0)
            cross.normalize()
            cross *= width / 2.0
            pt = pts[1]
            vertex_writer.addData3f(pt[0] + cross[0], pt[1] + cross[1], pt[2] + cross[2])
            vertex_writer.addData3f(pt[0] - cross[0], pt[1] - cross[1], pt[2] - cross[2])
            color_writer.addData4f(0, 1, 0, 1)
            color_writer.addData4f(0, 1, 0, 1)
            texture_writer.addData2f(0, 0)
            texture_writer.addData2f(1, 0)
            triStrip.addNextVertices(4)
            geometry = Geom(vertex_data)
            geometry.addPrimitive(triStrip)
            self.head_geom_node.addGeom(geometry)
            format = GeomVertexFormat.getV3c4t2()
            vertex_data = GeomVertexData('arc_ball', format, Geom.UHStatic)
            vertex_writer = GeomVertexWriter(vertex_data, 'vertex')
            color_writer = GeomVertexWriter(vertex_data, 'color')
            texture_writer = GeomVertexWriter(vertex_data, 'texcoord')
            triStrip = GeomTristrips(Geom.UHStatic)
            for x in range(len(pts[1:-1])):
                cross = pts[x + 1].cross(pts[x + 2] - pts[x])
                cross.normalize()
                cross *= width / 2.0
                pt = pts[x + 1]
                vertex_writer.addData3f(pt[0] + cross[0], pt[1] + cross[1], pt[2] + cross[2])
                vertex_writer.addData3f(pt[0] - cross[0], pt[1] - cross[1], pt[2] - cross[2])
                color_writer.addData4f(0, 1, 0, 1)
                color_writer.addData4f(0, 1, 0, 1)
                if x % 2:
                    texture_writer.addData2f(0, 1)
                    texture_writer.addData2f(1, 1)
                else:
                    texture_writer.addData2f(0, 0)
                    texture_writer.addData2f(1, 0)
                triStrip.addNextVertices(2)

            cross = pts[-1].cross(pts[-1] - pts[-2])
            cross.normalize()
            cross *= width / 2.0
            pt = pts[-1]
            vertex_writer.addData3f(pt[0] + cross[0], pt[1] + cross[1], pt[2] + cross[2])
            vertex_writer.addData3f(pt[0] - cross[0], pt[1] - cross[1], pt[2] - cross[2])
            color_writer.addData4f(0, 1, 0, 1)
            color_writer.addData4f(0, 1, 0, 1)
            if N % 2:
                texture_writer.addData2f(0, 0)
                texture_writer.addData2f(1, 0)
            else:
                texture_writer.addData2f(0, 1)
                texture_writer.addData2f(1, 1)
            triStrip.addNextVertices(2)
            geometry = Geom(vertex_data)
            geometry.addPrimitive(triStrip)
            self.tail_geom_node.addGeom(geometry)
Ejemplo n.º 45
0
    def __watchControls(self, task):
        dt = globalClock.getDt()
        curVelocity = self.actorNode.getPhysicsObject().getVelocity()
        curSpeed = curVelocity.length()
        fvec = self.forward.getPos(render) - self.getPos(render)
        fvec.normalize()
        dotProduct = curVelocity.dot(fvec)
        goingBack = -1
        if dotProduct < 0:
            goingBack = 1
        if self.proRacer:
            self.__computeTurnRatio(curSpeed)
            self.__updateWheelPos(dt, curSpeed)
        newHForTurning = self.getH()
        if self.proRacer or not self.stopped and self.arrowHorz and curSpeed > 1:
            if self.proRacer:
                turnHelp = 0
                if self.hittingWall or goingBack == 1:
                    turnHelp = self.arrowHorz
                effectiveSpeed = curSpeed
                if effectiveSpeed > self.speedMinTurn:
                    effectiveSpeed = self.speedMinTurn
                rotation = -goingBack * (self.wheelPosition * dt * self.turnRatio * -1.8 * curSpeed / 100 + turnHelp * dt * self.turnRatio * -1.2)
                self.outPutCounter += 1
                if self.outPutCounter > 5:
                    self.outPutCounter = 0
            else:
                rotation = self.arrowHorz * dt * self.turnRatio * -1.2
            oldH = self.getH()
            newH = (oldH + rotation) % 360
            self.setH(newH)
            newHForTurning = newH
            if self.groundType == 'ice':
                newHForTurning = (oldH + rotation * iceTurnFactor) % 360
        pitch = -self.getP() + 5
        accelBase = self.accelerationBase
        pitch += accelBase
        pitch = clampScalar(pitch, accelBase - 5, accelBase + 5)
        self.accelerationMult = pitch * 2
        if self.groundType == 'ice':
            self.accelerationMult *= iceAccelFactor
        if self.stopped:
            self.acceleration = 0
        else:
            self.acceleration = self.arrowVert * self.accelerationMult * self.cheatFactor
            if self.proRacer:
                if self.skidding:
                    self.acceleration = self.arrowVert * self.accelerationMult * self.cheatFactor * 0.5
            if self.turbo:
                self.acceleration += self.accelerationMult * 1.5
        self.engine.setVector(Vec3(0, self.acceleration, 0))
        if self.groundType == 'ice':
            rotMat = Mat3.rotateMatNormaxis(newHForTurning, Vec3.up())
        else:
            rotMat = Mat3.rotateMatNormaxis(self.getH(), Vec3.up())
        curHeading = rotMat.xform(Vec3.forward())
        push = (3 - self.getP()) * 0.02
        curHeading.setZ(curHeading.getZ() - min(0.2, max(-.2, push)))
        onScreenDebug.append('vehicle curHeading = %s\n' % curHeading.pPrintValues())
        onScreenDebug.append('vehicle H = %s  newHForTurning=%f\n' % (self.getH(), newHForTurning))
        windResistance = self.surfaceModifiers[self.groundType]['windResistance']
        self.windResistance.setCoef(windResistance)
        physicsFrame = int((globalClock.getFrameTime() - self.physicsEpoch) * self.physicsCalculationsPerSecond)
        numFrames = min(physicsFrame - self.lastPhysicsFrame, self.maxPhysicsFrames)
        self.lastPhysicsFrame = physicsFrame
        leanIncrement = self.arrowHorz * self.physicsDt * self.turnRatio
        if self.stopped:
            leanIncrement = 0
        driftMin = self.surfaceModifiers[self.groundType]['driftMin']
        if self.proRacer:
            driftMin = self.surfaceModifiers[self.groundType]['driftMin'] * 0.2
            if self.skidding:
                driftMin = self.surfaceModifiers[self.groundType]['driftMin']
        for i in range(int(numFrames)):
            self.physicsMgr.doPhysics(self.physicsDt)
            curVelocity = self.actorNode.getPhysicsObject().getVelocity()
            idealVelocity = curHeading * curSpeed
            curVelocity *= self.imHitMult
            driftVal = abs(self.leanAmount) * 16 / self.cheatFactor + 15 / self.cheatFactor
            curVelocity = Vec3((curVelocity * driftVal + idealVelocity) / (driftVal + 1))
            curSpeed = curVelocity.length()
            curVelocity.normalize()
            curVelocity *= min(curSpeed, 600)
            self.actorNode.getPhysicsObject().setVelocity(curVelocity)
            curSpeed = curVelocity.length()
            speedFactor = min(curSpeed, 150) / 162.0
            self.leanAmount = (self.leanAmount + leanIncrement) * speedFactor
            self.leanAmount = clampScalar(self.leanAmount, -10, 10)

        self.cWallTrav.traverse(render)
        self.curSpeed = curSpeed
        if self.proRacer:
            self.turnWheels(self.wheelPosition * -45)
        else:
            self.turnWheels(self.arrowHorz * -10)
        self.__animate()
        if self.proRacer:
            speedProporation = 1.0
            if curSpeed < self.speedMaxTurn:
                speedProporation = 0.0
            else:
                speedProporation = (curSpeed - self.speedMaxTurn) / self.speedMinTurn
            cameraDist = self.cameraArmBase + self.cameraArmExtend * speedProporation
            cameraOffset = Point3(0, -cameraDist, 0)
            self.cameraNode.setPos(cameraOffset)
            behindPos = render.getRelativePoint(self, Point3(0, -30, 0))
            self.proCameraDummyNode.setPos(render, behindPos)
            self.proCameraDummyNode.lookAt(self)
            self.cameraNode.lookAt(self)
            dir1 = self.proCameraDummyNode.getH()
            dir2 = self.proCameraHeading
            if dir1 > 180:
                dir1 -= 360
            elif dir1 < -180:
                dir1 += 360
            if dir2 > 180:
                dir2 -= 360
            elif dir2 < -180:
                dir2 += 360
            self.proCameraHeading = dir2
            dif = dir1 - dir2
            if dif > 180:
                dif -= 360
            elif dif < -180:
                dif += 360
            speedDif = abs(dif)
            if speedDif > 90:
                speedDif = 90
            cameraTightener = 1.0
            if curSpeed > self.speedMinTurn:
                cameraTightener = self.cameraTightener
            else:
                cameraTightener = 1.0 + curSpeed / self.speedMinTurn * (self.cameraTightener - 1.0)
            swingSpeedRatio = speedDif / 90
            swingSpeed = self.armSwingSpeedPerp * swingSpeedRatio + self.armSwingSpeedPara * (1 - swingSpeedRatio)
            self.proCameraHeading += dif * cameraTightener * (dt / swingSpeed)
            self.cameraArmNode.setH(self.proCameraHeading - self.getH())
        elif not self.stopped:
            self.cameraNode.setH(self.leanAmount)
        self.updateParticles(self.leanAmount)
        if (self.leanAmount > 8 or self.leanAmount < -8) and self.offGround <= 0:
            self.startSkid()
        else:
            self.stopSkid()
        if self.speedometer:
            self.speedometer['text'] = str(int(curSpeed / 3))
            self.speedGauge.setR(min(110, max(0, curSpeed / 3 / 120 * 110)))
        if not self.stopped:
            self.stickCarToGround()
        if self.__clampPosition():
            self.notify.debug('did a clampPosition on %d' % self.doId)
        return Task.cont
    def createStraightArrow(self, p0, p1, width):
        p0.normalize()
        p1.normalize()
        dot = p0.dot(p1)
        cross = p0.cross(p1)
        arcLen = math.acos(clampScalar(-1, 1, dot))
        self.tail_geom_node.removeAllGeoms()
        self.head_geom_node.removeAllGeoms()
        if arcLen > 0.0:
            cross.normalize()
            cross *= width / 2.0
            theta = 2 * math.asin(width / 2.0)
            div = arcLen / theta
            steps = int(div)
            remainder = div - steps
            pts = []
            for n in range(steps + 1):
                pts.append(sLerp(p1, p0, n / div, arcLen) * self._radius)

            format = GeomVertexFormat.getV3c4t2()
            vertex_data = GeomVertexData('arc_ball', format, Geom.UHStatic)
            vertex_writer = GeomVertexWriter(vertex_data, 'vertex')
            color_writer = GeomVertexWriter(vertex_data, 'color')
            texture_writer = GeomVertexWriter(vertex_data, 'texcoord')
            triStrip = GeomTristrips(Geom.UHStatic)
            if len(pts) == 1:
                vertex_writer.addData3f(p1[0] - cross[0], p1[1] - cross[1], p1[2] - cross[2])
                vertex_writer.addData3f(p1[0] + cross[0], p1[1] + cross[1], p1[2] + cross[2])
                color_writer.addData4f(0, 1, 0, 1)
                color_writer.addData4f(0, 1, 0, 1)
                texture_writer.addData2f(1, 1)
                texture_writer.addData2f(0, 1)
                vertex_writer.addData3f(p0[0] - cross[0], p0[1] - cross[1], p0[2] - cross[2])
                vertex_writer.addData3f(p0[0] + cross[0], p0[1] + cross[1], p0[2] + cross[2])
                color_writer.addData4f(0, 1, 0, 1)
                color_writer.addData4f(0, 1, 0, 1)
                texture_writer.addData2f(1, 1 - remainder)
                texture_writer.addData2f(0, 1 - remainder)
                triStrip.addNextVertices(4)
            else:
                for pt in pts[:2]:
                    vertex_writer.addData3f(pt[0] - cross[0], pt[1] - cross[1], pt[2] - cross[2])
                    vertex_writer.addData3f(pt[0] + cross[0], pt[1] + cross[1], pt[2] + cross[2])
                    color_writer.addData4f(0, 1, 0, 1)
                    color_writer.addData4f(0, 1, 0, 1)

                texture_writer.addData2f(1, 1)
                texture_writer.addData2f(0, 1)
                texture_writer.addData2f(1, 0)
                texture_writer.addData2f(0, 0)
                triStrip.addNextVertices(4)
            geometry = Geom(vertex_data)
            geometry.addPrimitive(triStrip)
            self.head_geom_node.addGeom(geometry)
            format = GeomVertexFormat.getV3c4t2()
            vertex_data = GeomVertexData('arc_ball', format, Geom.UHStatic)
            vertex_writer = GeomVertexWriter(vertex_data, 'vertex')
            color_writer = GeomVertexWriter(vertex_data, 'color')
            texture_writer = GeomVertexWriter(vertex_data, 'texcoord')
            triStrip = GeomTristrips(Geom.UHStatic)
            for pt in pts[1:]:
                vertex_writer.addData3f(pt[0] - cross[0], pt[1] - cross[1], pt[2] - cross[2])
                vertex_writer.addData3f(pt[0] + cross[0], pt[1] + cross[1], pt[2] + cross[2])
                color_writer.addData4f(0, 1, 0, 1)
                color_writer.addData4f(0, 1, 0, 1)

            numPts = len(pts[1:])
            for x in range(numPts / 2):
                texture_writer.addData2f(1, 1)
                texture_writer.addData2f(0, 1)
                texture_writer.addData2f(1, 0)
                texture_writer.addData2f(0, 0)

            if numPts % 2:
                texture_writer.addData2f(1, 1)
                texture_writer.addData2f(0, 1)

            vertex_writer.addData3f(p0[0] - cross[0], p0[1] - cross[1], p0[2] - cross[2])
            vertex_writer.addData3f(p0[0] + cross[0], p0[1] + cross[1], p0[2] + cross[2])
            color_writer.addData4f(0, 1, 0, 1)
            color_writer.addData4f(0, 1, 0, 1)
            if numPts % 2:
                texture_writer.addData2f(1, 1 - remainder)
                texture_writer.addData2f(0, 1 - remainder)
            else:
                texture_writer.addData2f(1, remainder)
                texture_writer.addData2f(0, remainder)
            triStrip.addNextVertices(numPts * 2 + 2)
            geometry = Geom(vertex_data)
            geometry.addPrimitive(triStrip)
            self.tail_geom_node.addGeom(geometry)
    def updatePlayer(self, task):
        if self.pause:
            return task.cont
        
        if self.can_move == False:
            return task.cont
        

        if getTile( self.node.getPos() ) == self.parent.level.finish_tile:
            self.parent.gameWin()
        
        #monsters only think once per second so we need to keep gunshots remembered for at least 2 seconds
        if self.gunshot_at:
            if time.time() - self.gunshot_at[1] > GUNSHOT_TIMEOUT:
                self.gunshot_at = None
            
        self.cooldown( globalClock.getDt() )
        
        if self.parent.type == 'FPS':
            md = base.win.getPointer(0)
            x = md.getX()
            y = md.getY()
    
            if self.mouse_owner and base.win.movePointer(0, self.centerx, self.centery):
                h, p, r = self.node.getHpr()
                h += (x - self.centerx) * -0.2
                p += (y - self.centery) * -0.2
                p = clampScalar(p, -80.0, 80.0)
                self.node.setHpr(h, p, 0)
    
            speed1 = 0
            speed2 = 0
            
            if self.keys['sprint']:
                player_speed = self.sprint_speed
            else:
                player_speed = self.speed
                
            if self.keys['forward']:
                speed1 = player_speed * globalClock.getDt()
            if self.keys['back']:
                speed1 =  -player_speed * globalClock.getDt()
            if self.keys['strafe_left']:
                speed2 = -player_speed * globalClock.getDt()
            if self.keys['strafe_right']:
                speed2 = player_speed * globalClock.getDt()
    
            if speed1 or speed2:
                if self.keys['sprint']:
                    self.sprint = True
                else:
                    self.sprint = False
                self.moving = True
            else:
                self.moving = False
                self.sprint = False
    
            self.node.setFluidZ(TILE_SIZE*ASPECT/1.5)
            self.node.setFluidPos(self.node, speed2, speed1, 0)
        
        elif self.parent.type == 'DEBUG':
            speed1 = 0
            speed2 = 0
            if self.keys['forward']:
                speed1 = self.speed * globalClock.getDt()
            if self.keys['back']:
                speed1 =  -self.speed * globalClock.getDt()
            if self.keys['strafe_left']:
                speed2 = -self.speed * globalClock.getDt()
            if self.keys['strafe_right']:
                speed2 = self.speed * globalClock.getDt()
    
            if speed1 or speed2:
                self.moving = True
            else:
                self.moving = False
                
            self.node.setFluidZ(TILE_SIZE*ASPECT/1.5)
            self.node.setFluidPos(self.node, speed2, speed1, 0)
        return task.cont
Ejemplo n.º 48
0
    def createCurvedArrow(self, axis, p0, p1, width, numPanels=10):
        N = numPanels
        self.tail_geom_node.removeAllGeoms()
        self.head_geom_node.removeAllGeoms()
        axis = axis / axis.length()
        dot0 = axis.dot(p0)
        proj0 = p0 - axis * dot0
        dot1 = axis.dot(p1)
        proj1 = p1 - axis * dot1
        theta = math.acos(
            clampScalar(-1, 1,
                        proj0.dot(proj1) / proj0.length() * proj1.length()))
        if not proj0.almostEqual(proj1, 0.0001) and theta != 0:
            if proj0.lengthSquared() >= proj1.lengthSquared():
                A = proj0
                C = proj1
            else:
                A = proj1
                C = proj0
            a = A.length()
            aUnit = A / a
            x = A.dot(C) / a
            yy = C.lengthSquared() - x * x
            bUnit = A.cross(C).cross(A)
            bUnit.normalize()
            b = math.sqrt(max(0.0, yy / (1 - x * x / a * a)))
            t = math.atan2(a, b / math.tan(theta))
            aUnit *= a
            bUnit *= b
            pts = [
                aUnit * math.cos(x * t / N) + bUnit * math.sin(x * t / N)
                for x in range(N + 1)
            ]
            pts = [
                pt + axis *
                math.sqrt(self._radius * self._radius - pt.lengthSquared())
                for pt in pts
            ]
            if A != proj0:
                pts.reverse()

            format = GeomVertexFormat.getV3c4t2()
            vertex_data = GeomVertexData('arc_ball', format, Geom.UHStatic)
            vertex_writer = GeomVertexWriter(vertex_data, 'vertex')
            color_writer = GeomVertexWriter(vertex_data, 'color')
            texture_writer = GeomVertexWriter(vertex_data, 'texcoord')
            triStrip = GeomTristrips(Geom.UHStatic)
            cross = pts[0].cross(pts[1] - pts[0])
            cross.normalize()
            cross *= width / 2.0
            pt = pts[0]
            vertex_writer.addData3f(pt[0] + cross[0], pt[1] + cross[1],
                                    pt[2] + cross[2])
            vertex_writer.addData3f(pt[0] - cross[0], pt[1] - cross[1],
                                    pt[2] - cross[2])
            color_writer.addData4f(0, 1, 0, 1)
            color_writer.addData4f(0, 1, 0, 1)
            texture_writer.addData2f(0, 1)
            texture_writer.addData2f(1, 1)
            diffA = pts[1] - pts[0]
            diffB = pts[2] - pts[1]
            cross = pts[1].cross((diffB + diffA) / 2.0)
            cross.normalize()
            cross *= width / 2.0
            pt = pts[1]
            vertex_writer.addData3f(pt[0] + cross[0], pt[1] + cross[1],
                                    pt[2] + cross[2])
            vertex_writer.addData3f(pt[0] - cross[0], pt[1] - cross[1],
                                    pt[2] - cross[2])
            color_writer.addData4f(0, 1, 0, 1)
            color_writer.addData4f(0, 1, 0, 1)
            texture_writer.addData2f(0, 0)
            texture_writer.addData2f(1, 0)
            triStrip.addNextVertices(4)
            geometry = Geom(vertex_data)
            geometry.addPrimitive(triStrip)
            self.head_geom_node.addGeom(geometry)
            format = GeomVertexFormat.getV3c4t2()
            vertex_data = GeomVertexData('arc_ball', format, Geom.UHStatic)
            vertex_writer = GeomVertexWriter(vertex_data, 'vertex')
            color_writer = GeomVertexWriter(vertex_data, 'color')
            texture_writer = GeomVertexWriter(vertex_data, 'texcoord')
            triStrip = GeomTristrips(Geom.UHStatic)
            for x in range(len(pts[1:-1])):
                cross = pts[x + 1].cross(pts[x + 2] - pts[x])
                cross.normalize()
                cross *= width / 2.0
                pt = pts[x + 1]
                vertex_writer.addData3f(pt[0] + cross[0], pt[1] + cross[1],
                                        pt[2] + cross[2])
                vertex_writer.addData3f(pt[0] - cross[0], pt[1] - cross[1],
                                        pt[2] - cross[2])
                color_writer.addData4f(0, 1, 0, 1)
                color_writer.addData4f(0, 1, 0, 1)
                if x % 2:
                    texture_writer.addData2f(0, 1)
                    texture_writer.addData2f(1, 1)
                else:
                    texture_writer.addData2f(0, 0)
                    texture_writer.addData2f(1, 0)
                triStrip.addNextVertices(2)

            cross = pts[-1].cross(pts[-1] - pts[-2])
            cross.normalize()
            cross *= width / 2.0
            pt = pts[-1]
            vertex_writer.addData3f(pt[0] + cross[0], pt[1] + cross[1],
                                    pt[2] + cross[2])
            vertex_writer.addData3f(pt[0] - cross[0], pt[1] - cross[1],
                                    pt[2] - cross[2])
            color_writer.addData4f(0, 1, 0, 1)
            color_writer.addData4f(0, 1, 0, 1)
            if N % 2:
                texture_writer.addData2f(0, 0)
                texture_writer.addData2f(1, 0)
            else:
                texture_writer.addData2f(0, 1)
                texture_writer.addData2f(1, 1)
            triStrip.addNextVertices(2)
            geometry = Geom(vertex_data)
            geometry.addPrimitive(triStrip)
            self.tail_geom_node.addGeom(geometry)
Ejemplo n.º 49
0
 def cameraZoom(self,zoomFactor,):
   """Scale and clamp zoom level, then set distance by it."""
   self.zoomLvl=clampScalar(self.zoomLvl*zoomFactor,*self.zoomClamp)
   self.setDist(self.zoomLvl)
Ejemplo n.º 50
0
    def createStraightArrow(self, p0, p1, width):
        p0.normalize()
        p1.normalize()
        dot = p0.dot(p1)
        cross = p0.cross(p1)
        arcLen = math.acos(clampScalar(-1, 1, dot))
        self.tail_geom_node.removeAllGeoms()
        self.head_geom_node.removeAllGeoms()
        if arcLen > 0.0:
            cross.normalize()
            cross *= width / 2.0
            theta = 2 * math.asin(width / 2.0)
            div = arcLen / theta
            steps = int(div)
            remainder = div - steps
            pts = []
            for n in range(steps + 1):
                pts.append(sLerp(p1, p0, n / div, arcLen) * self._radius)

            format = GeomVertexFormat.getV3c4t2()
            vertex_data = GeomVertexData('arc_ball', format, Geom.UHStatic)
            vertex_writer = GeomVertexWriter(vertex_data, 'vertex')
            color_writer = GeomVertexWriter(vertex_data, 'color')
            texture_writer = GeomVertexWriter(vertex_data, 'texcoord')
            triStrip = GeomTristrips(Geom.UHStatic)
            if len(pts) == 1:
                vertex_writer.addData3f(p1[0] - cross[0], p1[1] - cross[1],
                                        p1[2] - cross[2])
                vertex_writer.addData3f(p1[0] + cross[0], p1[1] + cross[1],
                                        p1[2] + cross[2])
                color_writer.addData4f(0, 1, 0, 1)
                color_writer.addData4f(0, 1, 0, 1)
                texture_writer.addData2f(1, 1)
                texture_writer.addData2f(0, 1)
                vertex_writer.addData3f(p0[0] - cross[0], p0[1] - cross[1],
                                        p0[2] - cross[2])
                vertex_writer.addData3f(p0[0] + cross[0], p0[1] + cross[1],
                                        p0[2] + cross[2])
                color_writer.addData4f(0, 1, 0, 1)
                color_writer.addData4f(0, 1, 0, 1)
                texture_writer.addData2f(1, 1 - remainder)
                texture_writer.addData2f(0, 1 - remainder)
                triStrip.addNextVertices(4)
            else:
                for pt in pts[:2]:
                    vertex_writer.addData3f(pt[0] - cross[0], pt[1] - cross[1],
                                            pt[2] - cross[2])
                    vertex_writer.addData3f(pt[0] + cross[0], pt[1] + cross[1],
                                            pt[2] + cross[2])
                    color_writer.addData4f(0, 1, 0, 1)
                    color_writer.addData4f(0, 1, 0, 1)

                texture_writer.addData2f(1, 1)
                texture_writer.addData2f(0, 1)
                texture_writer.addData2f(1, 0)
                texture_writer.addData2f(0, 0)
                triStrip.addNextVertices(4)
            geometry = Geom(vertex_data)
            geometry.addPrimitive(triStrip)
            self.head_geom_node.addGeom(geometry)
            format = GeomVertexFormat.getV3c4t2()
            vertex_data = GeomVertexData('arc_ball', format, Geom.UHStatic)
            vertex_writer = GeomVertexWriter(vertex_data, 'vertex')
            color_writer = GeomVertexWriter(vertex_data, 'color')
            texture_writer = GeomVertexWriter(vertex_data, 'texcoord')
            triStrip = GeomTristrips(Geom.UHStatic)
            for pt in pts[1:]:
                vertex_writer.addData3f(pt[0] - cross[0], pt[1] - cross[1],
                                        pt[2] - cross[2])
                vertex_writer.addData3f(pt[0] + cross[0], pt[1] + cross[1],
                                        pt[2] + cross[2])
                color_writer.addData4f(0, 1, 0, 1)
                color_writer.addData4f(0, 1, 0, 1)

            numPts = len(pts[1:])
            for x in range(numPts / 2):
                texture_writer.addData2f(1, 1)
                texture_writer.addData2f(0, 1)
                texture_writer.addData2f(1, 0)
                texture_writer.addData2f(0, 0)

            if numPts % 2:
                texture_writer.addData2f(1, 1)
                texture_writer.addData2f(0, 1)

            vertex_writer.addData3f(p0[0] - cross[0], p0[1] - cross[1],
                                    p0[2] - cross[2])
            vertex_writer.addData3f(p0[0] + cross[0], p0[1] + cross[1],
                                    p0[2] + cross[2])
            color_writer.addData4f(0, 1, 0, 1)
            color_writer.addData4f(0, 1, 0, 1)
            if numPts % 2:
                texture_writer.addData2f(1, 1 - remainder)
                texture_writer.addData2f(0, 1 - remainder)
            else:
                texture_writer.addData2f(1, remainder)
                texture_writer.addData2f(0, remainder)
            triStrip.addNextVertices(numPts * 2 + 2)
            geometry = Geom(vertex_data)
            geometry.addPrimitive(triStrip)
            self.tail_geom_node.addGeom(geometry)
Ejemplo n.º 51
0
 def rotateCam(self,arc):
   """Setup a lerp interval to rotate the camera about the target."""
   newP=clampScalar(self.target.getP()-arc.getY(),*self.clampP)#Clamped.
   newH=self.target.getH()+arc.getX()#Not clamped, just added.
   LERP.LerpHprInterval(self.target, self.speed,#Setup the interval\
     P.Vec3(newH,newP,self.target.getR(), ), ).start()#and start it.
    def update(self, time):
        placeSorter = []
        placeCount = 0
        for key in self.racerDict.keys():
            racer = self.racerDict[key]
            curvetime = racer.curvetime
            face = racer.face
            mapspot = racer.mapspot
            maxlaphit = racer.maxlaphit
            if not racer.finished and racer.enabled:
                placeSorter.append((curvetime, key))
            if racer.finished or racer.enabled:
                placeCount += 1
            pt = Vec3(0, 0, 0)
            mapT = (curvetime % 1 + self.race.startT /
                    self.race.curve.getMaxT()) % 1 * self.race.curve.getMaxT()
            self.race.curve.getPoint(mapT, pt)
            self.race.curve.getPoint(mapT % self.race.curve.getMaxT(), pt)
            lapT = clampScalar(curvetime / self.race.lapCount, 0.0, 1.0)
            faceX = self.faceStartPos[0] * (1 -
                                            lapT) + self.faceEndPos[0] * lapT
            racer.update(faceX=faceX, mapspotPt=pt)
            t = time - self.race.baseTime - self.raceTimeDelta
            if key == localAvatar.doId:
                if self.race.laps > maxlaphit:
                    racer.update(maxlaphit=self.race.laps)
                    self.maxLapHit = racer.maxlaphit
                    if self.maxLapHit < self.race.lapCount:
                        for y in self.timeLabels[self.maxLapHit - 1]:
                            y.configure(
                                text_font=ToontownGlobals.getSignFont())

                        for y in self.timeLabels[self.maxLapHit]:
                            y.show()

                        for y in self.timeLabels[self.maxLapHit]:
                            y.configure(
                                text_font=ToontownGlobals.getSignFont())

                        self.raceTimeDelta = globalClock.getFrameTime(
                        ) - self.race.baseTime
                        lapNotice = DirectLabel()
                        lapNotice.setScale(0.1)
                        if self.maxLapHit == self.race.lapCount - 1:
                            lapNotice[
                                'text'] = TTLocalizer.KartRace_FinalLapText
                        else:
                            lapNotice[
                                'text'] = TTLocalizer.KartRace_LapText % str(
                                    self.maxLapHit + 1)
                        taskMgr.doMethodLater(2,
                                              lapNotice.remove,
                                              'removeIt',
                                              extraArgs=[])
                self.lapLabel['text'] = str(
                    clampScalar(self.maxLapHit + 1, 1,
                                self.race.lapCount)) + '/' + str(
                                    self.race.lapCount)

        suffix = {
            1: TTLocalizer.KartRace_FirstSuffix,
            2: TTLocalizer.KartRace_SecondSuffix,
            3: TTLocalizer.KartRace_ThirdSuffix,
            4: TTLocalizer.KartRace_FourthSuffix
        }
        placeSorter.sort()
        for x, p in zip(placeSorter, xrange(len(placeSorter), 0, -1)):
            self.racerDict[x[1]].update(place=p + placeCount -
                                        len(placeSorter))

        localRacer = self.racerDict[localAvatar.doId]
        nearDiff, farDiff = RaceGlobals.TrackDict[self.race.trackId][8]
        if not localRacer.finished and self.faceEndPos[
                0] - localRacer.face.getX() < nearDiff:
            for racerId in self.racerDict.keys():
                racer = self.racerDict[racerId]
                if not racer.enabled or racerId == localAvatar.doId or racer.face.getX(
                ) >= self.faceEndPos[0]:
                    continue
                if self.faceEndPos[0] - racer.face.getX() < farDiff:
                    self.photoFinish = True

        if self.photoFinish:
            self.photoFinishLabel.show()
            self.placeLabelNum['text'] = ''
            self.placeLabelStr['text'] = ''
        else:
            self.photoFinishLabel.hide()
            self.placeLabelNum['text'] = str(
                self.racerDict[localAvatar.doId].place)
            self.placeLabelStr['text'] = suffix[self.racerDict[
                localAvatar.doId].place]
        minutes = int(t / 60)
        t -= minutes * 60
        seconds = int(t)
        padding = (seconds < 10 and ['0'] or [''])[0]
        t -= seconds
        fraction = str(t)[2:4]
        fraction = fraction + '0' * (2 - len(fraction))
        if self.timerEnabled and self.maxLapHit < self.race.lapCount:
            self.timeLabels[self.maxLapHit][0]['text'] = "%d'" % minutes
            self.timeLabels[self.maxLapHit][1]['text'] = "%s%d''" % (padding,
                                                                     seconds)
            self.timeLabels[self.maxLapHit][2]['text'] = '%s' % fraction
        if self.race.wrongWay and not self.wrongWaySeq.isPlaying():
            self.wrongWaySeq.loop()
        elif not self.race.wrongWay and self.wrongWaySeq.isPlaying():
            self.wrongWaySeq.finish()
 def applyIdealDistance(self):
     if self.isActive():
         self.idealDistance = clampScalar(self.idealDistance, self._minDistance, self._maxDistance)
         if self._practicalDistance is None:
             self._zoomToDistance(self.idealDistance)
 def addToMood(self, component, delta):
     value = self.mood.getComponent(component)
     value += delta
     self.setMoodComponent(component, clampScalar(value, 0.0, 1.0))
 def doDrift(curValue, timeToMedian, dt = float(dt)):
     newValue = curValue + dt / (timeToMedian * 7200)
     return clampScalar(newValue, 0.0, 1.0)
 def setZoom(self, zoom):
     self._zoom = clampScalar(0.0, 0.75, zoom)
     self.buffer.camera.setY(lerp(self.camY[0], self.camY[1], self._zoom))
     self.mapBall._setTiltLimit(lerp(self.tiltLimit[0], self.tiltLimit[1], self._zoom))
     self.mapBall.updateTextZoom(self._zoom)
Ejemplo n.º 57
0
 def addToMood(self, component, delta):
     value = self.mood.getComponent(component)
     value += delta
     self.setMoodComponent(component, clampScalar(value, 0.0, 1.0))