def startNextIdleAnim(self):
		self.notify.debug(
			'startNextAnim self.okToStartNextAnim=%s' %
			self.okToStartNextAnim)
		if not hasattr(self, 'node') or not self.node:
			self.notify.warning(
				"startNextIdleAnim returning hasattr(self,'node')=%s" %
				hasattr(
					self, 'node'))
			return
		self.curIval = None
		if self.okToStartNextAnim:
			self.notify.debug('got pass okToStartNextAnim')
			whichAnim = self.chooseIdleAnimToRun()
			if self.visId == localAvatar.zoneId:
				self.notify.debug('whichAnim=%s' % whichAnim)
				if __dev__:
					self.notify.info(
						'whichAnim=%s %s' %
						(whichAnim, self.getOrigIdleAnimName(whichAnim)))
			self.lastPlayingAnimPhase = whichAnim
			self.curIval = self.createIdleAnimSequence(whichAnim)
			self.notify.debug(
				'starting curIval of length %s' %
				self.curIval.getDuration())
			self.curIval.start()
		else:
			self.curIval = Wait(10)
			self.notify.debug(
				'false self.okToStartNextAnim=%s' %
				self.okToStartNextAnim)
		return
    def startNextIdleAnim(self):
        if not hasattr(self, 'node') or not self.node:
            self.notify.warning("startNextIdleAnim returning hasattr(self,'node')=%s" % hasattr(self, 'node'))
            return

        self.curIval = None

        if self.okToStartNextAnim:
            self.notify.debug('got pass okToStartNextAnim')
            whichAnim = self.chooseIdleAnimToRun()
            self.lastPlayingAnimPhase = whichAnim
            self.curIval = self.createIdleAnimSequence(whichAnim)
            self.notify.debug('starting curIval of length %s' % self.curIval.getDuration())
            self.curIval.start()
        else:
            self.curIval = Wait(3)
            self.notify.debug('false self.okToStartNextAnim=%s' % self.okToStartNextAnim)
 def initFlash(self):
     model = CogdoUtil.loadFlyingModel('gatherableFlash_card')
     texName = Globals.Level.GatherableType2TextureName[self.type]
     tex = model.findTexture(texName)
     tex.setWrapU(Texture.WMRepeat)
     tex.setWrapV(Texture.WMRepeat)
     del model
     self.ts = TextureStage('ts')
     self.ts.setMode(TextureStage.MCombine)
     self.ts.setSort(1)
     self.ts.setCombineRgb(TextureStage.CMInterpolate, TextureStage.CSPrevious, TextureStage.COSrcColor, TextureStage.CSTexture, TextureStage.COSrcColor, TextureStage.CSConstant, TextureStage.COSrcColor)
     self.ts.setCombineAlpha(TextureStage.CMInterpolate, TextureStage.CSPrevious, TextureStage.COSrcAlpha, TextureStage.CSTexture, TextureStage.COSrcAlpha, TextureStage.CSConstant, TextureStage.COSrcAlpha)
     self._model.setTexture(self.ts, tex)
     dur = Globals.Gameplay.GatherableFlashTime
     self.flashLoop = Sequence(LerpFunctionInterval(self.setTextureAlphaFunc, fromData=1.0, toData=0.25, duration=dur / 2.0, blendType='easeInOut'), LerpFunctionInterval(self.setTextureAlphaFunc, fromData=0.25, toData=1.0, duration=dur / 2.0, blendType='easeInOut'), Wait(1.0), name='%s.flashLoop-%s' % (self.__class__.__name__, self.serialNum))
Пример #4
0
    def animToToon(self, timeStamp):
        self.stopTransition()
        if self.mode != 'suit':
            self.setToSuit()
        self.loadAnimToToonSfx()
        suitSoundPlayed = 0
        toonSoundPlayed = 0
        bldgNodes = self.getNodePaths()
        tracks = Parallel()
        for i in bldgNodes:
            name = i.getName()
            if name[0] == 's':
                hideTrack = Sequence(name = self.taskName('ToToonSuitFlatsTrack'))
                landmark = name.find('_landmark_') != -1
                if not suitSoundPlayed:
                    hideTrack.append(Func(base.playSfx, self.cogWeakenSound, 0, 1, None, 0.0))
                hideTrack.append(self.createBounceTrack(i, 3, 1.2, TO_TOON_BLDG_TIME * 0.05, slowInitBounce = 0.0))
                hideTrack.append(self.createBounceTrack(i, 5, 0.8, TO_TOON_BLDG_TIME * 0.1, slowInitBounce = 0.0))
                hideTrack.append(self.createBounceTrack(i, 7, 1.2, TO_TOON_BLDG_TIME * 0.17, slowInitBounce = 0.0))
                hideTrack.append(self.createBounceTrack(i, 9, 1.2, TO_TOON_BLDG_TIME * 0.18, slowInitBounce = 0.0))
                realScale = i.getScale()
                hideTrack.append(LerpScaleInterval(i, TO_TOON_BLDG_TIME * 0.1, Vec3(realScale[0], realScale[1], 0.01)))
                if landmark:
                    hideTrack.append(Func(i.removeNode))
                else:
                    hideTrack.append(Func(i.stash))
                    hideTrack.append(Func(i.setScale, Vec3(1)))
                if not suitSoundPlayed:
                    suitSoundPlayed = 1
                tracks.append(hideTrack)
            elif name[0] == 't':
                hideTrack = Sequence(name = self.taskName('ToToonFlatsTrack'))
                hideTrack.append(Wait(TO_TOON_BLDG_TIME * 0.5))
                if not toonSoundPlayed:
                    hideTrack.append(Func(base.playSfx, self.toonGrowSound, 0, 1, None, 0.0))
                hideTrack.append(Func(i.unstash))
                hideTrack.append(Func(i.setScale, Vec3(1, 1, 0.01)))
                if not toonSoundPlayed:
                    hideTrack.append(Func(base.playSfx, self.toonSettleSound, 0, 1, None, 0.0))
                hideTrack.append(self.createBounceTrack(i, 11, 1.2, TO_TOON_BLDG_TIME * 0.5, slowInitBounce=4.0))
                tracks.append(hideTrack)
                if not toonSoundPlayed:
                    toonSoundPlayed = 1

        self.stopTransition()
        bldgMTrack = tracks
        localToonIsVictor = self.localToonIsVictor()
        if localToonIsVictor:
            base.localAvatar.loop('neutral')
            camTrack = self.walkOutCameraTrack()
        victoryRunTrack, delayDeletes = self.getVictoryRunTrack()
        trackName = self.taskName('toToonTrack')
        self._deleteTransitionTrack()
        if localToonIsVictor:
            freedomTrack1 = Func(self.cr.playGame.getPlace().fsm.request, 'walk')
            freedomTrack2 = Func(base.localAvatar.d_setParent, CIGlobals.SPRender)
            self.transitionTrack = Parallel(camTrack, Sequence(victoryRunTrack, bldgMTrack, freedomTrack1, freedomTrack2), name = trackName)
        else:
            self.transitionTrack = Sequence(victoryRunTrack, bldgMTrack, name = trackName)
        self.transitionTrack.delayDeletes = delayDeletes
        if localToonIsVictor:
            self.transitionTrack.start(0)
        else:
            self.transitionTrack.start(timeStamp)
 def startTutorial(self):
     self.t.fadeOut(1)
     Sequence(Wait(1.2), Func(self.playVideo)).start()
class InteractiveAnimatedProp(
		GenericAnimatedProp.GenericAnimatedProp,
		FSM.FSM):
	ZoneToIdles = {}
	ZoneToIdleIntoFightAnims = {}
	ZoneToFightAnims = {}
	ZoneToVictoryAnims = {}
	ZoneToSadAnims = {}
	IdlePauseTime = config.GetFloat('prop-idle-pause-time', 0.0)
	HpTextGenerator = TextNode('HpTextGenerator')
	BattleCheerText = '+'

	def __init__(self, node, holidayId=-1):
		FSM.FSM.__init__(self, 'InteractiveProp-%s' % str(node))
		self.holidayId = holidayId
		self.numIdles = 0
		self.numFightAnims = 0
		self.idleInterval = None
		self.battleCheerInterval = None
		self.sadInterval = None
		self.victoryInterval = None
		self.lastIdleAnimName = ''
		self.lastIdleTime = 0
		self.curIval = None
		self.okToStartNextAnim = False
		cellIndexStr = node.getTag('DNACellIndex')
		self.cellIndex = ord(cellIndexStr)
		self.origAnimNameToSound = {}
		self.lastPlayingAnimPhase = 0
		self.buildingsMakingMeSad = set()
		GenericAnimatedProp.GenericAnimatedProp.__init__(self, node)
		return

	def delete(self):
		self.exit()
		GenericAnimatedProp.GenericAnimatedProp.delete(self)
		self.idleInterval = None
		self.battleCheerInterval = None
		self.sadInterval = None
		self.victoryInterval = None
		return

	def getCellIndex(self):
		return self.cellIndex

	def playBattleCheerAnim(self):
		self.node.loop('battleCheer')

	def setupActor(self, node):
		if self.hoodId in self.ZoneToIdles:
			self.numIdles = len(self.ZoneToIdles[self.hoodId])
		if self.hoodId in self.ZoneToFightAnims:
			self.numFightAnims = len(self.ZoneToFightAnims[self.hoodId])
		self.idleInterval = None
		anim = node.getTag('DNAAnim')
		self.trashcan = Actor.Actor(node, copy=0)
		self.trashcan.reparentTo(node)
		animDict = {'anim': '%s/%s' % (self.path, anim)}
		for i in xrange(self.numIdles):
			baseAnim = self.ZoneToIdles[self.hoodId][i]
			if isinstance(baseAnim, tuple):
				baseAnim = baseAnim[0]
			animStr = self.path + '/' + baseAnim
			animKey = 'idle%d' % i
			animDict[animKey] = animStr
			settleName = self.getSettleName(i)
			if settleName:
				settleStr = self.path + '/' + settleName
				settleKey = 'settle%d' % i
				animDict[settleKey] = settleStr

		for i in xrange(self.numFightAnims):
			animStr = self.path + '/' + self.ZoneToFightAnims[self.hoodId][i]
			animKey = 'fight%d' % i
			animDict[animKey] = animStr

		if self.hoodId in self.ZoneToIdleIntoFightAnims:
			animStr = self.path + '/' + \
				self.ZoneToIdleIntoFightAnims[self.hoodId]
			animKey = 'idleIntoFight'
			animDict[animKey] = animStr
		if self.hoodId in self.ZoneToIdleIntoFightAnims:
			animStr = self.path + '/' + self.ZoneToVictoryAnims[self.hoodId]
			animKey = 'victory'
			animDict[animKey] = animStr
		if self.hoodId in self.ZoneToSadAnims:
			animStr = self.path + '/' + self.ZoneToSadAnims[self.hoodId]
			animKey = 'sad'
			animDict[animKey] = animStr
		self.trashcan.loadAnims(animDict)
		self.trashcan.pose('anim', 0)
		self.node = self.trashcan
		self.idleInterval = self.createIdleInterval()
		self.battleCheerInterval = self.createBattleCheerInterval()
		self.victoryInterval = self.createVictoryInterval()
		self.sadInterval = self.createSadInterval()
		return

	def createIdleInterval(self):
		result = Sequence()
		if self.numIdles >= 3:
			numberOfAnimsAbove2 = self.numIdles - 2
			for rareIdle in xrange(2, self.numIdles):
				for i in xrange(2):
					result.append(ActorInterval(self.node, 'idle0'))
					result.append(Wait(self.IdlePauseTime))
					result.append(ActorInterval(self.node, 'idle1'))
					result.append(Wait(self.IdlePauseTime))

				result.append(ActorInterval(self.node, 'idle%d' % rareIdle))
				result.append(Wait(self.IdlePauseTime))

		else:
			for i in xrange(self.numIdles):
				result.append(ActorInterval(self.node, 'idle%d' % i))

		self.notify.debug('idle interval=%s' % result)
		return result

	def createBattleCheerText(self):
		self.HpTextGenerator.setFont(ToontownGlobals.getSignFont())
		self.HpTextGenerator.setText(self.BattleCheerText)
		self.HpTextGenerator.clearShadow()
		self.HpTextGenerator.setAlign(TextNode.ACenter)
		r = 0
		g = 0
		b = 1
		a = 1
		self.HpTextGenerator.setTextColor(r, g, b, a)
		self.hpTextNode = self.HpTextGenerator.generate()
		self.hpText = self.node.attachNewNode(self.hpTextNode)
		self.hpText.setScale(1)
		self.hpText.setBillboardPointEye()
		self.hpText.setBin('fixed', 100)
		self.hpText.setPos(0, 0, 4)
		self.hpText.hide()

	def createBattleCheerInterval(self):
		result = Sequence()
		for i in xrange(self.numFightAnims):
			animKey = 'fight%d' % i
			animAndSoundIval = self.createAnimAndSoundIval(animKey)
			origAnimName = self.node.getAnimFilename(animKey).split('/')[-1]
			if self.hasOverrideIval(origAnimName):
				result.append(self.getOverrideIval(origAnimName))
			elif self.hasSpecialIval(origAnimName):
				result.append(
					Parallel(
						animAndSoundIval,
						self.getSpecialIval(origAnimName)))
			else:
				result.append(animAndSoundIval)

		self.createBattleCheerText()
		battleCheerTextIval = Sequence(
			Func(
				self.hpText.show), self.hpText.posInterval(
				duration=4.0, pos=Vec3(
					0, 0, 7), startPos=(
					0, 0, 3)), Func(
						self.hpText.hide))
		ivalWithText = Parallel(battleCheerTextIval, result)
		return ivalWithText

	def createSadInterval(self):
		result = Sequence()
		if self.hoodId in self.ZoneToSadAnims:
			result = self.createAnimAndSoundIval('sad')
		return result

	def hasSpecialIval(self, origAnimName):
		return False

	def getSpecialIval(self, origAnimName):
		return Sequence()

	def hasOverrideIval(self, origAnimName):
		return False

	def getOverrideIval(self, origAnimName):
		return Sequence()

	def createVictoryInterval(self):
		result = Sequence()
		if self.hoodId in self.ZoneToVictoryAnims:
			animAndSoundIval = self.createAnimAndSoundIval('victory')
			result.append(animAndSoundIval)
		return result

	def enter(self):
		GenericAnimatedProp.GenericAnimatedProp.enter(self)
		self.notify.debug('props buff battles is true')
		self.notify.debug('holiday is running, doing idle interval')
		self.node.stop()
		self.node.pose('idle0', 0)
		self.requestIdleOrSad()


	def exit(self):
		self.okToStartNextAnim = False
		self.notify.debug(
			'%s %d okToStartNextAnim=%s' %
			(self, self.visId, self.okToStartNextAnim))
		GenericAnimatedProp.GenericAnimatedProp.exit(self)
		self.request('Off')

	def requestIdleOrSad(self):
		if not hasattr(self, 'node') or not self.node:
			self.notify.warning(
				"requestIdleOrSad  returning hasattr(self,'node')=%s" %
				hasattr(
					self, 'node'))
			return
		if self.buildingsMakingMeSad:
			self.request('Sad')
		else:
			self.request('DoIdleAnim')

	def enterDoIdleAnim(self):
		self.notify.debug('enterDoIdleAnim numIdels=%d' % self.numIdles)
		self.okToStartNextAnim = True
		self.notify.debug(
			'%s %d okToStartNextAnim=%s' %
			(self, self.visId, self.okToStartNextAnim))
		self.startNextIdleAnim()

	def exitDoIdleAnim(self):
		self.notify.debug('exitDoIdlesAnim numIdles=%d' % self.numIdles)
		self.okToStartNextAnim = False
		self.notify.debug(
			'%s %d okToStartNextAnim=%s' %
			(self, self.visId, self.okToStartNextAnim))
		self.calcLastIdleFrame()
		self.clearCurIval()

	def calcLastIdleFrame(self):
		if self.curIval and self.curIval.ivals:
			firstIval = self.curIval.ivals[0]
			if isinstance(firstIval, ActorInterval):
				self.lastIdleFrame = firstIval.getCurrentFrame()
				self.lastIdleAnimName = firstIval.animName
			elif isinstance(firstIval, Parallel):
				for testIval in firstIval.ivals:
					if isinstance(firstIval, ActorInterval):
						self.lastIdleTime = testIval.getT()
						self.lastIdleAnimName = testIval.animName
						break

	def chooseIdleAnimToRun(self):
		result = self.numIdles - 1
		if config.GetBool('randomize-interactive-idles', True):
			pairs = []
			for i in xrange(self.numIdles):
				reversedChance = self.numIdles - i - 1
				pairs.append((math.pow(2, reversedChance), i))

			sum = math.pow(2, self.numIdles) - 1
			result = weightedChoice(pairs, sum=sum)
			self.notify.debug(
				'chooseAnimToRun numIdles=%s pairs=%s result=%s' %
				(self.numIdles, pairs, result))
		else:
			result = self.lastPlayingAnimPhase + 1
			if result >= len(self.ZoneToIdles[self.hoodId]):
				result = 0
		return result

	def startNextIdleAnim(self):
		self.notify.debug(
			'startNextAnim self.okToStartNextAnim=%s' %
			self.okToStartNextAnim)
		if not hasattr(self, 'node') or not self.node:
			self.notify.warning(
				"startNextIdleAnim returning hasattr(self,'node')=%s" %
				hasattr(
					self, 'node'))
			return
		self.curIval = None
		if self.okToStartNextAnim:
			self.notify.debug('got pass okToStartNextAnim')
			whichAnim = self.chooseIdleAnimToRun()
			if self.visId == localAvatar.zoneId:
				self.notify.debug('whichAnim=%s' % whichAnim)
				if __dev__:
					self.notify.info(
						'whichAnim=%s %s' %
						(whichAnim, self.getOrigIdleAnimName(whichAnim)))
			self.lastPlayingAnimPhase = whichAnim
			self.curIval = self.createIdleAnimSequence(whichAnim)
			self.notify.debug(
				'starting curIval of length %s' %
				self.curIval.getDuration())
			self.curIval.start()
		else:
			self.curIval = Wait(10)
			self.notify.debug(
				'false self.okToStartNextAnim=%s' %
				self.okToStartNextAnim)
		return

	def createIdleAnimAndSoundInterval(self, whichIdleAnim, startingTime=0):
		animIval = self.node.actorInterval(
			'idle%d' %
			whichIdleAnim,
			startTime=startingTime)
		animIvalDuration = animIval.getDuration()
		origAnimName = self.ZoneToIdles[self.hoodId][whichIdleAnim]
		if isinstance(origAnimName, tuple):
			origAnimName = origAnimName[0]
		soundIval = self.createSoundInterval(origAnimName, animIvalDuration)
		soundIvalDuration = soundIval.getDuration()
		if self.hasSpecialIval(origAnimName):
			specialIval = self.getSpecialIval(origAnimName)
			idleAnimAndSound = Parallel(animIval, soundIval, specialIval)
		else:
			idleAnimAndSound = Parallel(animIval, soundIval)
		return idleAnimAndSound

	def createIdleAnimSequence(self, whichIdleAnim):
		dummyResult = Sequence(Wait(self.IdlePauseTime))
		if not hasattr(self, 'node') or not self.node:
			self.notify.warning(
				"createIdleAnimSequence returning dummyResult hasattr(self,'node')=%s" %
				hasattr(
					self, 'node'))
			return dummyResult
		idleAnimAndSound = self.createIdleAnimAndSoundInterval(whichIdleAnim)
		result = Sequence(
			idleAnimAndSound, Wait(
				self.IdlePauseTime), Func(
				self.startNextIdleAnim))
		if isinstance(
			self.ZoneToIdles[
				self.hoodId][whichIdleAnim],
			tuple) and len(
			self.ZoneToIdles[
				self.hoodId][whichIdleAnim]) > 2:
			info = self.ZoneToIdles[self.hoodId][whichIdleAnim]
			origAnimName = info[0]
			minLoop = info[1]
			maxLoop = info[2]
			settleAnim = info[3]
			minPauseTime = info[4]
			maxPauseTime = info[5]
			numberOfLoops = random.randrange(minLoop, maxLoop + 1)
			pauseTime = random.randrange(minPauseTime, maxPauseTime + 1)
			result = Sequence()
			for i in xrange(numberOfLoops):
				result.append(idleAnimAndSound)

			if self.getSettleName(whichIdleAnim):
				result.append(
					self.node.actorInterval(
						'settle%d' %
						whichIdleAnim))
			result.append(Wait(pauseTime))
			result.append(Func(self.startNextIdleAnim))
		return result

	def gotoFaceoff(self):
		self.notify.debugStateCall(self)
		if base.cr.newsManager.isHolidayRunning(self.holidayId):
			self.request('Faceoff')
		else:
			self.notify.debug(
				'not going to faceoff because holiday %d is not running' %
				self.holidayId)

	def gotoBattleCheer(self):
		self.notify.debugStateCall(self)
		if base.cr.newsManager.isHolidayRunning(self.holidayId):
			self.request('BattleCheer')
		else:
			self.notify.debug(
				'not going to battleCheer because holiday %d is not running' %
				self.holidayId)

	def gotoIdle(self):
		self.notify.debugStateCall(self)
		if base.cr.newsManager.isHolidayRunning(self.holidayId):
			self.request('DoIdleAnim')
		else:
			self.notify.debug(
				'not going to idle because holiday %d is not running' %
				self.holidayId)

	def gotoVictory(self):
		self.notify.debugStateCall(self)
		if base.cr.newsManager.isHolidayRunning(self.holidayId):
			self.request('Victory')
		else:
			self.notify.debug(
				'not going to victory because holiday %d is not running' %
				self.holidayId)

	def gotoSad(self, buildingDoId):
		self.notify.debugStateCall(self)
		self.buildingsMakingMeSad.add(buildingDoId)
		if base.cr.newsManager.isHolidayRunning(self.holidayId):
			self.request('Sad')
		else:
			self.notify.debug(
				'not going to sad because holiday %d is not running' %
				self.holidayId)

	def buildingLiberated(self, buildingDoId):
		self.buildingsMakingMeSad.discard(buildingDoId)
		if not self.buildingsMakingMeSad:
			self.gotoIdle()

	def enterFaceoff(self):
		self.notify.debugStateCall(self)
		self.curIval = self.createFaceoffInterval()
		self.curIval.start()

	def exitFaceoff(self):
		self.notify.debugStateCall(self)
		self.curIval.pause()
		self.curIval = None
		return

	def calcWhichIdleAnim(self, animName):
		result = 0
		info = self.ZoneToIdles[self.hoodId]
		for index, curInfo in enumerate(info):
			if isinstance(curInfo, tuple):
				if curInfo[0] == animName:
					result = index
					break
			elif isinstance(curInfo, str):
				if curInfo == animName:
					result = index
					breal

		return result

	def createFaceoffInterval(self):
		result = Sequence()
		if self.lastIdleAnimName:
			whichIdleAnim = self.calcWhichIdleAnim(self.lastIdleAnimName)
			animAndSound = self.createIdleAnimAndSoundInterval(
				whichIdleAnim, self.lastIdleTime)
			result.append(animAndSound)
		idleIntoFightIval = self.createAnimAndSoundIval('idleIntoFight')
		result.append(idleIntoFightIval)
		result.append(Func(self.gotoBattleCheer))
		return result

	def enterBattleCheer(self):
		self.notify.debugStateCall(self)
		self.curIval = self.battleCheerInterval
		if self.curIval:
			self.curIval.loop()

	def exitBattleCheer(self):
		self.notify.debugStateCall(self)
		if self.curIval:
			self.curIval.finish()
			self.curIval = None
		return

	def enterVictory(self):
		self.notify.debugStateCall(self)
		self.curIval = self.victoryInterval
		if self.curIval:
			self.curIval.loop()

	def exitVictory(self):
		self.notify.debugStateCall(self)
		if self.curIval:
			self.curIval.finish()
			self.curIval = None
		return

	def enterSad(self):
		self.notify.debugStateCall(self)
		self.curIval = self.sadInterval
		if self.curIval:
			self.curIval.loop()

	def exitSad(self):
		self.notify.debugStateCall(self)
		if self.curIval:
			self.curIval.finish()
			self.curIval = None
		return

	def getSettleName(self, whichIdleAnim):
		result = None
		if isinstance(
			self.ZoneToIdles[
				self.hoodId][whichIdleAnim],
			tuple) and len(
			self.ZoneToIdles[
				self.hoodId][whichIdleAnim]) > 3:
			result = self.ZoneToIdles[self.hoodId][whichIdleAnim][3]
		return result

	def getOrigIdleAnimName(self, whichIdleAnim):
		result = None
		if isinstance(self.ZoneToIdles[self.hoodId][whichIdleAnim], tuple):
			result = self.ZoneToIdles[self.hoodId][whichIdleAnim][0]
		else:
			result = self.ZoneToIdles[self.hoodId][whichIdleAnim]
		return result

	def createAnimAndSoundIval(self, animKey):
		animIval = self.node.actorInterval(animKey)
		animIvalDuration = animIval.getDuration()
		origAnimName = self.node.getAnimFilename(animKey)
		soundIval = self.createSoundInterval(origAnimName, animIvalDuration)
		soundIvalDuration = soundIval.getDuration()
		printFunc = Func(self.printAnimIfClose, animKey)
		if self.hasSpecialIval(origAnimName):
			specialIval = self.getSpecialIval(origAnimName)
			idleAnimAndSound = Parallel(animIval, soundIval, specialIval)
			if config.GetBool('interactive-prop-info', False):
				idleAnimAndSound.append(printFunc)
		else:
			idleAnimAndSound = Parallel(animIval, soundIval)
			if config.GetBool('interactive-prop-info', False):
				idleAnimAndSound.append(printFunc)
		return idleAnimAndSound

	def printAnimIfClose(self, animKey):
		if config.GetBool('interactive-prop-info', False):
			try:
				animName = self.node.getAnimFilename(animKey)
				baseAnimName = animName.split('/')[-1]
				if localAvatar.zoneId == self.visId:
					self.notify.info('playing %s' % baseAnimName)
			except Exception as e:
				self.notify.warning(
					'Unknown error in printAnimIfClose, giving up:\n%s' %
					str(e))

	def clearCurIval(self):
		if self.curIval:
			self.curIval.finish()
		clearPythonIvals(self.curIval)
		self.curIval = None
		return
Пример #7
0
    def enterDie(self, ts=0):
        self.show()
        self.clearStunnedIval()
        self.generateCog(isLose=1)
        self.nametag.clearChatText()
        self.deleteNameTag()
        self.deathSound = base.audio3d.loadSfx(
            "phase_3.5/audio/sfx/Cog_Death_Full.ogg")
        base.audio3d.attachSoundToObject(self.deathSound, self)
        trackName = self.uniqueName('enterDie')

        smallGears = ParticleLoader.loadParticleEffect(
            'phase_3.5/etc/gearExplosionSmall.ptf')
        #smallGears.getParticlesNamed('particles-1').setPoolSize(30)

        singleGear = ParticleLoader.loadParticleEffect(
            'phase_3.5/etc/gearExplosion.ptf')
        singleGear.getParticlesNamed('particles-1').setPoolSize(1)

        smallGearExplosion = ParticleLoader.loadParticleEffect(
            'phase_3.5/etc/gearExplosion.ptf')
        smallGearExplosion.getParticlesNamed('particles-1').setPoolSize(10)

        bigGearExplosion = ParticleLoader.loadParticleEffect(
            'phase_3.5/etc/gearExplosionBig.ptf')
        bigGearExplosion.getParticlesNamed('particles-1').setPoolSize(30)

        smallGears.setDepthWrite(False)
        singleGear.setDepthWrite(False)
        smallGearExplosion.setDepthWrite(False)
        bigGearExplosion.setDepthWrite(False)

        gearPoint = self.getPos(render) + (0, 0, self.getHeight() - 0.2)

        self.smallGears = smallGears
        self.smallGears.setPos(gearPoint)
        self.singleGear = singleGear
        self.singleGear.setPos(gearPoint)
        self.smallGearExp = smallGearExplosion
        self.smallGearExp.setPos(gearPoint)
        self.bigGearExp = bigGearExplosion
        self.bigGearExp.setPos(gearPoint)

        gearTrack = Sequence(Wait(0.7), Func(self.doSingleGear), Wait(1.5),
                             Func(self.doSmallGears), Wait(3.0),
                             Func(self.doBigExp))
        self.suitTrack = Parallel(
            Sequence(Wait(0.8), SoundInterval(self.deathSound, duration=4.28)),
            Sequence(Wait(0.7), Func(self.doSingleGear), Wait(4.5),
                     Func(self.suitExplode), Wait(1.0),
                     Func(self.disableBodyCollisions)),
            gearTrack,
            Sequence(ActorInterval(self, 'lose', duration=6),
                     Func(self.getGeomNode().hide)),
            name=trackName)
        self.suitTrack.setDoneEvent(self.suitTrack.getName())
        self.acceptOnce(self.suitTrack.getName(), self.exitDie)
        if self.isDistributed():
            self.suitTrack.delayDelete = DelayDelete.DelayDelete(
                self, trackName)
        self.suitTrack.start(ts)
Пример #8
0
    def showResults(self):
        if not self.gameIsEnding:
            self.gameIsEnding = True
            for barrel in self.barrels:
                barrel.wrtReparentTo(render)

            for key in self.cogInfo:
                thief = self.cogInfo[key]['suit']
                thief.suit.setPos(100, 0, 0)
                thief.suit.hide()

            self._DistributedCogThiefGame__killRewardCountdown()
            self.stopGameWalk()
            numBarrelsSaved = len(self.barrels) - len(self.stolenBarrels)
            resultStr = ''
            if numBarrelsSaved == len(self.barrels):
                resultStr = TTLocalizer.CogThiefPerfect
            elif numBarrelsSaved > 1:
                resultStr = TTLocalizer.CogThiefBarrelsSaved % {
                    'num': numBarrelsSaved
                }
            elif numBarrelsSaved == 1:
                resultStr = TTLocalizer.CogThiefBarrelSaved % {
                    'num': numBarrelsSaved
                }
            else:
                resultStr = TTLocalizer.CogThiefNoBarrelsSaved
            perfectTextSubnode = hidden.attachNewNode(
                self._DistributedCogThiefGame__genText(resultStr))
            perfectText = hidden.attachNewNode('perfectText')
            perfectTextSubnode.reparentTo(perfectText)
            frame = self._DistributedCogThiefGame__textGen.getCardActual()
            offsetY = -abs(frame[2] + frame[3]) / 2.0
            perfectTextSubnode.setPos(0, 0, offsetY)
            perfectText.setColor(1, 0.10000000000000001, 0.10000000000000001,
                                 1)

            def fadeFunc(t, text=perfectText):
                text.setColorScale(1, 1, 1, t)

            def destroyText(text=perfectText):
                text.removeNode()

            def safeGameOver(self=self):
                if not self.frameworkFSM.isInternalStateInFlux():
                    self.gameOver()

            textTrack = Sequence(
                Func(perfectText.reparentTo, aspect2d),
                Parallel(
                    LerpScaleInterval(perfectText,
                                      duration=0.5,
                                      scale=0.29999999999999999,
                                      startScale=0.0),
                    LerpFunctionInterval(fadeFunc,
                                         fromData=0.0,
                                         toData=1.0,
                                         duration=0.5)), Wait(2.0),
                Parallel(
                    LerpScaleInterval(perfectText, duration=0.5, scale=1.0),
                    LerpFunctionInterval(fadeFunc,
                                         fromData=1.0,
                                         toData=0.0,
                                         duration=0.5,
                                         blendType='easeIn')),
                Func(destroyText), WaitInterval(0.5), Func(safeGameOver))
            if numBarrelsSaved == len(self.barrels):
                soundTrack = SoundInterval(self.sndPerfect)
            else:
                soundTrack = Sequence()
            self.resultIval = Parallel(textTrack, soundTrack)
            self.resultIval.start()
Пример #9
0
 def handleCollisions(self, avId, wait = 0):
     # May be overridden if needed.
     if base.localAvatar.doId == avId:
         Sequence(Wait(wait), Func(self.sendUpdate, 'collectedObject', [])).start()
Пример #10
0
 def handleToonExited(self, toonId):
     DistributedPartyTeamActivity.handleToonExited(self, toonId)
     if toonId == base.localAvatar.doId:
         self.cameraMoveIval.pause()
         if toonId not in self.fallenToons:
             if toonId in self.toonIdsToAnimIntervals and self.toonIdsToAnimIntervals[toonId] is not None:
                 self.toonIdsToAnimIntervals[toonId].finish()
             toon = self.getAvatar(toonId)
             targetH = fitDestAngle2Src(toon.getH(self.root), 180.0)
             targetPos = self.hopOffPositions[self.getTeam(toonId)][self.getIndex(toonId, self.getTeam(toonId))]
             hopOffAnim = Sequence(Func(toon.startPosHprBroadcast, 0.1), toon.hprInterval(0.2, VBase3(targetH, 0.0, 0.0), other=self.root), Func(toon.b_setAnimState, 'jump', 1.0), Wait(0.4), PartyUtils.arcPosInterval(0.75, toon, targetPos, 5.0, self.root), Func(toon.stopPosHprBroadcast), Func(toon.sendCurrentPosition), Func(self.hopOffFinished, toonId))
             self.toonIdsToAnimIntervals[toonId] = hopOffAnim
             self._hopOffFinishedSV.set(False)
             self.toonIdsToAnimIntervals[toonId].start()
         else:
             self._hopOffFinishedSV.set(True)
             del self.toonIdsToAnimIntervals[toonId]
     return
Пример #11
0
 def __handleGameOverAck(self):
     self.fsm.requestFinalState()
     Sequence(Func(base.transitions.irisOut, 1.0), Wait(1.2),
             Func(self.d_leaving), Func(self.headBackToMinigameArea)).start()
 def startProjInterval(self, startX, startY, startZ, endX, endY, endZ, duration, gravityMult, ts=0):
     if isinstance(ts, int) and ts != 0:
         ts = globalClockDelta.localElapsedTime(ts)
     self.disableRay()
     self.stopMoveInterval()
     startPos = Point3(startX, startY, startZ)
     endPos = Point3(endX, endY, endZ)
     oldHpr = self.getHpr(render)
     self.headsUp(endPos)
     newHpr = self.getHpr(render)
     self.setHpr(oldHpr)
     self.moveIval = Parallel(LerpHprInterval(self, duration=0.5, hpr=newHpr, startHpr=oldHpr, blendType='easeInOut'), Sequence(Func(self.animFSM.request, 'flyAway', [ts]), Wait(3.5), Func(self.animFSM.request, 'flyDown', [1.0])), Sequence(Wait(2.0), Func(self.headsUp, endPos), ProjectileInterval(self, startPos=startPos, endPos=endPos, gravityMult=gravityMult, duration=duration)))
     self.moveIval.start(ts)
Пример #13
0
 def loser(self):
     self.loseSfx.play()
     self.localAv.b_setAnimState("neutral")
     Sequence(Wait(3.5), Func(self.displayGameOver, "loser")).start()
Пример #14
0
 def showPrize(self, amt):
     self.winSfx.play()
     self.localAv.b_setAnimState("happy")
     Sequence(Wait(3.5), Func(self.displayGameOver, "showPrize", amt)).start()
Пример #15
0
 def winner(self):
     self.winSfx.play()
     self.localAv.b_setAnimState("happy")
     Sequence(Wait(3.5), Func(self.displayGameOver, "winner")).start()
 def initIntervals(self):
     dur = Globals.LegalEagle.LiftOffTime
     nestPos = self.nest.getPos(render)
     airPos = nestPos + Vec3(0.0, 0.0, Globals.LegalEagle.LiftOffHeight)
     self.takeOffSeq = Sequence(Parallel(
         Sequence(
             Wait(dur * 0.6),
             LerpPosInterval(self.suit,
                             dur * 0.4,
                             startPos=nestPos,
                             pos=airPos,
                             blendType='easeInOut'))),
                                Wait(1.5),
                                Func(self.request, 'next'),
                                name='%s.takeOffSeq-%i' %
                                (self.__class__.__name__, self.index))
     self.landOnNestPosLerp = LerpPosInterval(self.suit,
                                              1.0,
                                              startPos=airPos,
                                              pos=nestPos,
                                              blendType='easeInOut')
     self.landingSeq = Sequence(Func(self.updateLandOnNestPosLerp),
                                Parallel(self.landOnNestPosLerp),
                                Func(self.request, 'next'),
                                name='%s.landingSeq-%i' %
                                (self.__class__.__name__, self.index))
     dur = Globals.LegalEagle.ChargeUpTime
     self.chargeUpPosLerp = LerpFunc(
         self.moveAlongChargeUpMopathFunc,
         fromData=0.0,
         toData=self.chargeUpMotionPath.getMaxT(),
         duration=dur,
         blendType='easeInOut')
     self.chargeUpAttackSeq = Sequence(
         Func(self.updateChargeUpPosLerp),
         self.chargeUpPosLerp,
         Func(self.request, 'next'),
         name='%s.chargeUpAttackSeq-%i' %
         (self.__class__.__name__, self.index))
     dur = Globals.LegalEagle.RetreatToNestTime
     self.retreatToNestPosLerp = LerpPosInterval(self.suit,
                                                 dur,
                                                 startPos=Vec3(0, 0, 0),
                                                 pos=airPos,
                                                 blendType='easeInOut')
     self.retreatToNestSeq = Sequence(Func(self.updateRetreatToNestPosLerp),
                                      self.retreatToNestPosLerp,
                                      Func(self.request, 'next'),
                                      name='%s.retreatToNestSeq-%i' %
                                      (self.__class__.__name__, self.index))
     dur = Globals.LegalEagle.RetreatToSkyTime
     self.retreatToSkyPosLerp = LerpFunc(
         self.moveAlongRetreatMopathFunc,
         fromData=0.0,
         toData=self.retreatToSkyMotionPath.getMaxT(),
         duration=dur,
         blendType='easeOut')
     self.retreatToSkySeq = Sequence(Func(self.updateRetreatToSkyPosLerp),
                                     self.retreatToSkyPosLerp,
                                     Func(self.request, 'next'),
                                     name='%s.retreatToSkySeq-%i' %
                                     (self.__class__.__name__, self.index))
     dur = Globals.LegalEagle.PreAttackTime
     self.preAttackLerpXY = LerpFunc(self.updateAttackXY,
                                     fromData=0.0,
                                     toData=1.0,
                                     duration=dur)
     self.preAttackLerpZ = LerpFunc(self.updateAttackZ,
                                    fromData=0.0,
                                    toData=1.0,
                                    duration=dur,
                                    blendType='easeOut')
     dur = Globals.LegalEagle.PostAttackTime
     self.postAttackPosLerp = LerpPosInterval(self.suit,
                                              dur,
                                              startPos=Vec3(0, 0, 0),
                                              pos=Vec3(0, 0, 0))
     self.attackSeq = Sequence(
         Parallel(self.preAttackLerpXY, self.preAttackLerpZ),
         Func(self.updatePostAttackPosLerp),
         self.postAttackPosLerp,
         Func(self.request, 'next'),
         name='%s.attackSeq-%i' % (self.__class__.__name__, self.index))
     dur = Globals.LegalEagle.CooldownTime
     self.cooldownSeq = Sequence(Wait(dur),
                                 Func(self.request, 'next'),
                                 name='%s.cooldownSeq-%i' %
                                 (self.__class__.__name__, self.index))
     self.propTrack = Sequence(
         ActorInterval(self.prop, 'propeller', startFrame=0, endFrame=14))
     self.hoverOverNestSeq = Sequence(
         ActorInterval(self.suit,
                       'landing',
                       startFrame=10,
                       endFrame=20,
                       playRate=0.5),
         ActorInterval(self.suit,
                       'landing',
                       startFrame=20,
                       endFrame=10,
                       playRate=0.5))
Пример #17
0
 def enterThrow(self):
     self.ival = Parallel(
         Sequence(Wait(0.4), Func(self.mySnowball.b_throw)),
         Sequence(ActorInterval(self.vModel, "throw"),
                  Func(self.fsm.request, 'off')))
     self.ival.start()
Пример #18
0
 def doActivity(self):
     return Sequence(Func(self.avatar.animFSM.request, 'flyDown'), Wait(9.0))
Пример #19
0
 def enterCatch(self):
     self.ival = Parallel(
         Sequence(Wait(0.2), Func(self.__tryToCatchOrGrab)),
         Sequence(ActorInterval(self.vModel, "catch"),
                  Func(self.__maybeHold)))
     self.ival.start()
Пример #20
0
    def __init__(self):
        DirectObject.__init__(self)
        base.cr.DMENU_SCREEN = self
        self.seq = None
        self.isSeqPlaying = False # .isPlaying() doesnt want to work
        base.cr.avChoice = None

        fadeSequence = Sequence(
            Func(base.transitions.fadeOut, .001),
            Wait(.5),
            Func(base.transitions.fadeIn, .5),
            base.camera.posHprInterval(1, Point3(MAIN_POS), VBase3(MAIN_HPR), blendType = 'easeInOut')).start()
        if base.showDisclaimer:
            FeatureComingSoonDialog.FeatureComingSoonDialog(text = '\1textShadow\1Disclaimer:\2\nThis is an ALPHA build of Project Altis! Expect the server to restart a lot, and expect crashes and other bugs. Please report bugs to the team. Thanks, and enjoy Project Altis!')
        self.background2d = OnscreenImage(image = 'phase_3.5/maps/loading/toon.jpg', parent = aspect2d)
        self.background2d.setScale(2, 1, 1)
        self.background2d.setBin('background', 1)
        self.background2d.setTransparency(1)
        self.background2d.setColorScale(1, 1, 1, .2)
        self.background = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
        self.background.reparentTo(render)
        self.background.setPosHpr(-25, 0, 8.1, -95, 0, 0)
        ropes = loader.loadModel('phase_4/models/modules/tt_m_ara_int_ropes')
        ropes.reparentTo(self.background)
        self.sillyMeter = Actor.Actor('phase_4/models/props/tt_a_ara_ttc_sillyMeter_default', {'arrowTube': 'phase_4/models/props/tt_a_ara_ttc_sillyMeter_arrowFluid',
            'phaseOne': 'phase_4/models/props/tt_a_ara_ttc_sillyMeter_phaseOne',
            'phaseTwo': 'phase_4/models/props/tt_a_ara_ttc_sillyMeter_phaseTwo',
            'phaseThree': 'phase_4/models/props/tt_a_ara_ttc_sillyMeter_phaseThree',
            'phaseFour': 'phase_4/models/props/tt_a_ara_ttc_sillyMeter_phaseFour',
            'phaseFourToFive': 'phase_4/models/props/tt_a_ara_ttc_sillyMeter_phaseFourToFive',
            'phaseFive': 'phase_4/models/props/tt_a_ara_ttc_sillyMeter_phaseFive'})

        self.sillyMeter.reparentTo(self.background)
        self.sillyMeter.makeSubpart('arrow', ['uvj_progressBar*', 'def_springA'])
        self.sillyMeter.makeSubpart('meter', ['def_pivot'], ['uvj_progressBar*', 'def_springA'])
        self.audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0], camera)

        self.phase3Sfx = self.audio3d.loadSfx('phase_4/audio/sfx/tt_s_prp_sillyMeterPhaseThree.ogg')
        self.phase3Sfx.setLoop(True)
        self.arrowSfx = self.audio3d.loadSfx('phase_4/audio/sfx/tt_s_prp_sillyMeterArrow.ogg')
        self.arrowSfx.setLoop(False)
        self.phase3Sfx.setVolume(0.2)
        self.arrowSfx.setVolume(0.2)

        self.animSeq = Sequence(Sequence(ActorInterval(self.sillyMeter, 'arrowTube', partName = 'arrow', constrainedLoop = 0, startFrame = 236, endFrame = 247), Func(self.arrowSfx.play)), Parallel(ActorInterval(self.sillyMeter, 'arrowTube', partName = 'arrow', duration = 604800, constrainedLoop = 1, startFrame = 247, endFrame = 276), Sequence(Func(self.phase3Sfx.play), Func(self.audio3d.attachSoundToObject, self.phase3Sfx, self.sillyMeter))))
        self.animSeq.start()
        self.smPhase1 = self.sillyMeter.find('**/stage1')
        self.smPhase1.show()
        self.smPhase2 = self.sillyMeter.find('**/stage2')
        self.smPhase2.hide()
        self.smPhase3 = self.sillyMeter.find('**/stage3')
        self.smPhase3.hide()
        self.smPhase4 = self.sillyMeter.find('**/stage4')
        self.smPhase4.hide()

        thermometerLocator = self.sillyMeter.findAllMatches('**/uvj_progressBar')[1]
        thermometerMesh = self.sillyMeter.find('**/tube')
        thermometerMesh.setTexProjector(thermometerMesh.findTextureStage('default'), thermometerLocator, self.sillyMeter)

        self.sillyMeter.loop('phaseOne', partName = 'meter')
        self.sillyMeter.setBlend(frameBlend = base.wantSmoothAnims)

        self.surlee = Toon.Toon()
        self.surlee.setName('Doctor Surlee')
        self.surlee.setPickable(0)
        self.surlee.setPlayerType(CCNonPlayer)
        dna = ToonDNA.ToonDNA()
        dna.newToonFromProperties('pls', 'ls', 'l', 'm', 9, 0, 9, 9, 98, 27, 86, 27, 38, 27)
        self.surlee.setDNA(dna)
        self.surlee.loop('scientistGame')
        self.surlee.reparentTo(self.background)
        self.surlee.setPosHpr(13, 24, 0.025, -180, 0, 0)

        self.dimm = Toon.Toon()
        self.dimm.setName('Doctor Dimm')
        self.dimm.setPickable(0)
        self.dimm.setPlayerType(CCNonPlayer)
        dna = ToonDNA.ToonDNA()
        dna.newToonFromProperties('fll', 'ss', 's', 'm', 15, 0, 15, 15, 99, 27, 86, 27, 39, 27)
        self.dimm.setDNA(dna)
        self.dimm.loop('scientistGame')
        self.dimm.reparentTo(self.background)
        self.dimm.setPosHpr(16, 24, 0.025, -180, 0, 0)

        surleeHand = self.surlee.find('**/def_joint_right_hold')
        clipBoard = loader.loadModel('phase_4/models/props/tt_m_prp_acs_clipboard')
        surleeHandNode = surleeHand.attachNewNode('ClipBoard')
        clipBoard.instanceTo(surleeHandNode)
        surleeHandNode.setH(180)
        surleeHandNode.setScale(render, 1.0)
        surleeHandNode.setPos(0, 0, 0.1)

        dimmHand = self.dimm.find('**/def_joint_right_hold')
        sillyReader = loader.loadModel('phase_4/models/props/tt_m_prp_acs_sillyReader')
        dimHandNode = dimmHand.attachNewNode('SillyReader')
        sillyReader.instanceTo(dimHandNode)
        dimHandNode.setH(180)
        dimHandNode.setScale(render, 1.0)
        dimHandNode.setPos(0, 0, 0.1)

        self.banana = self.background.find('**/gagBanana')

        self.bananaClicker = CollisionTraverser()
        # self.bananaClicker.showCollisions(render)
        self.collHandlerQueue = CollisionHandlerQueue()

        self.bananaRayNode = CollisionNode('bananaMouseRay')
        self.bananaRayNP = base.camera.attachNewNode(self.bananaRayNode)
        self.bananaRayNode.setIntoCollideMask(BitMask32.bit(0))
        self.bananaRayNode.setFromCollideMask(BitMask32.bit(1))
        self.banana.setCollideMask(BitMask32.bit(1))
        self.ray = CollisionRay()
        self.bananaRayNode.addSolid(self.ray)
        self.bananaClicker.addCollider(self.bananaRayNP, self.collHandlerQueue)
        self.accept('mouse1', self.slipAndSlideOnThisBananaPeelHaHaHa)

        for frame in render.findAllMatches('*/doorFrame*'):
            frame.removeNode()

        self.sky = loader.loadModel('phase_3.5/models/props/TT_sky')
        SkyUtil.startCloudSky(self)
        base.camera.setPosHpr(MAIN_POS, MAIN_HPR)

        self.logo = OnscreenImage(image = GameLogo, scale = (.5, .5, .25))
        self.logo.reparentTo(aspect2d)
        self.logo.setTransparency(TransparencyAttrib.MAlpha)
        scale = self.logo.getScale()
        self.logo.setPos(0, 0, .5)
        self.logo.setColorScale(Vec4(0, 0, 0, 0))
        fadeInLogo = (LerpColorScaleInterval(self.logo, 1, Vec4(1, 1, 1, 1), Vec4(1, 1, 1, 0))).start()

        self.createButtons()

        self.fadeOut = None
        self.optionsMgr = PickAToonOptions.NewPickAToonOptions()
        self.quitConfirmation = DMenuQuit.DMenuQuit()
        self.accept('doQuitGame', self.doQuitFunc)
        self.accept('doCancelQuitGame', self.doCancelQuitFunc)
        self.patNode = None

        if DMENU_GAME == 'Toontown':
            # TT: We need these to run the Pick A Toon screen
            self.patAvList = base.cr.PAT_AVLIST
            self.patFSM = base.cr.PAT_LOGINFSM
            self.patDoneEvent = base.cr.PAT_DONEEVENT
Пример #21
0
    def fillSlot(self, index, avId, wantBoardingShow = 0):
        """Put someone in the kart, as dictated by the AI."""
        self.notify.debug("%s.fillSlot(%s, %s, ... %s)" % (self.doId, index, avId, globalClock.getRealTime()))
        request = self.toonRequests.get(index)
        if request:
            self.cr.relatedObjectMgr.abortRequest(request)
            del self.toonRequests[index]

        if avId == 0:
            # This means that the slot is now empty, and no action should
            # be taken.
            pass

        elif avId not in self.cr.doId2do:
            # It's someone who hasn't been generated yet.
            func = PythonUtil.Functor(
                self.gotToon, index, avId)

            assert index not in self.toonRequests
            self.toonRequests[index] = self.cr.relatedObjectMgr.requestObjects(
                [avId], allCallback = func)

        elif not self.isSetup:
            # We haven't set up the elevator yet.
            self.deferredSlots.append((index, avId, wantBoardingShow))

        else:
            # If localToon is boarding, he needs to change state
            if avId == base.localAvatar.getDoId():
                place = base.cr.playGame.getPlace()
                if not place:
                    return
                elevator = self.getPlaceElevator()
                if elevator == None:
                    place.fsm.request('elevator')
                    elevator = self.getPlaceElevator()
                if not elevator:
                    return

                self.localToonOnBoard = 1

                if hasattr(localAvatar, "boardingParty") and localAvatar.boardingParty:
                    localAvatar.boardingParty.forceCleanupInviteePanel()
                    localAvatar.boardingParty.forceCleanupInviterPanels()

                # Cleanup any leftover elevator messages before boarding the elevator.
                if hasattr(base.localAvatar, "elevatorNotifier"):
                    base.localAvatar.elevatorNotifier.cleanup()

                cameraTrack = Sequence()
                # Move the camera towards and face the elevator.
                cameraTrack.append(Func(elevator.fsm.request, "boarding", [self.getElevatorModel()]))
                # Enable the Hop off button.
                cameraTrack.append(Func(elevator.fsm.request, "boarded"))

            toon = self.cr.doId2do[avId]
            # Parent it to the elevator
            toon.stopSmooth()
            toon.wrtReparentTo(self.golfKart)

            sitStartDuration = toon.getDuration("sit-start")
            jumpTrack = self.generateToonJumpTrack(toon, index)

            track = Sequence(
				jumpTrack,
                Func(toon.setAnimState, "Sit", 1.0),
                Func(self.clearToonTrack, avId),
                name = toon.uniqueName("fillElevator"),
                autoPause = 1)

            if wantBoardingShow:
                boardingTrack, boardingTrackType = self.getBoardingTrack(toon, index, True)
                track = Sequence(boardingTrack, track)

                if avId == base.localAvatar.getDoId():
                    cameraWaitTime = 2.5
                    if (boardingTrackType == BoardingGroupShow.TRACK_TYPE_RUN):
                        cameraWaitTime = 0.5
                    cameraTrack = Sequence(Wait(cameraWaitTime), cameraTrack)

            if self.canHideBoardingQuitBtn(avId):
                track = Sequence(Func(localAvatar.boardingParty.groupPanel.disableQuitButton),
                                 track)

            # Start the camera track in parallel here
            if avId == base.localAvatar.getDoId():
                track = Parallel(cameraTrack, track)

            track.delayDelete = DelayDelete.DelayDelete(toon, 'CogKart.fillSlot')
            self.storeToonTrack(avId, track)
            track.start()

            self.fillSlotTrack = track

            assert avId not in self.boardedAvIds
            self.boardedAvIds[avId] = None
Пример #22
0
 def doMolePop(self, startTime, timeToMoveUp, timeToStayUp, timeToMoveDown, moleType):
     if self.hillType == MoleFieldBase.HILL_WHACKED or self.hillType == MoleFieldBase.HILL_COGWHACKED:
         return
     if self.popIval:
         self.popIval.pause()
     if self.downIval:
         self.downIval.pause()
         self.downIval = None
     moleColor = None
     self.switchUp()
     self.popupNum += 1
     if self.hillType == MoleFieldBase.HILL_BOMB:
         self.popIval = Sequence(Func(self.setHillType, moleType), Func(self.moleColNodePath.unstash), LerpPosInterval(self.mole, timeToMoveUp, Point3(0, 0, 0.0)), Wait(timeToStayUp), LerpPosInterval(self.mole, timeToMoveDown, Point3(0, 0, -2.5)), Func(self.stashMoleCollision), Func(self.switchDown))
     else:
         self.popIval = Sequence(Func(self.setHillType, moleType), LerpPosInterval(self.mole, timeToMoveUp, Point3(0, 0, 0.0)), Func(self.moleColNodePath.unstash), Wait(timeToStayUp), Func(self.stashMoleCollision), LerpPosInterval(self.mole, timeToMoveDown, Point3(0, 0, -2.5)), Func(self.switchDown))
     self.popIval.start()
     return
Пример #23
0
    def generateToonJumpTrack(self, av, seatIndex):
        """Return an interval of the toon jumping into the golf kart."""
        av.pose('sit', 47)
        hipOffset = av.getHipsParts()[2].getPos(av)

        def getToonJumpTrack( av, seatIndex ):
            # using a local func allows the ProjectileInterval to
            # calculate this pos at run-time
            def getJumpDest(av = av, node = self.golfKart):
                dest = Point3(0,0,0)
                if hasattr(self, 'golfKart') and self.golfKart:
                    dest = Vec3(self.golfKart.getPos(av.getParent()))
                    seatNode = self.golfKart.find("**/seat" + str(seatIndex + 1))
                    dest += seatNode.getPos(self.golfKart)
                    dna = av.getStyle()
                    dest -= hipOffset
                    if(seatIndex < 2):
                        dest.setY( dest.getY() + 2 * hipOffset.getY())
                    dest.setZ(dest.getZ() + 0.1)
                else:
                    self.notify.warning('getJumpDestinvalid golfKart, returning (0,0,0)')
                return dest

            def getJumpHpr(av = av, node = self.golfKart):
                hpr = Point3(0,0,0)
                if hasattr(self, 'golfKart') and self.golfKart:
                    hpr = self.golfKart.getHpr(av.getParent())
                    if(seatIndex < 2):
                        hpr.setX( hpr.getX() + 180)
                    else:
                        hpr.setX( hpr.getX() )
                    angle = PythonUtil.fitDestAngle2Src(av.getH(), hpr.getX())
                    hpr.setX(angle)
                else:
                    self.notify.warning('getJumpHpr invalid golfKart, returning (0,0,0)')
                return hpr

            toonJumpTrack = Parallel(ActorInterval( av, 'jump' ),
                                     Sequence(Wait( 0.43 ),
                                              Parallel(LerpHprInterval(av,
                                                                       hpr = getJumpHpr,
                                                                       duration = .9 ),
                                                       ProjectileInterval(av,
                                                                          endPos = getJumpDest,
                                                                          duration = .9 ),
                                                      ),
                                             ),
                                    )
            return toonJumpTrack

        def getToonSitTrack( av ):
            toonSitTrack = Sequence(

                ActorInterval( av, 'sit-start' ),
                Func( av.loop, 'sit' )
                )
            return toonSitTrack

        toonJumpTrack = getToonJumpTrack( av, seatIndex )
        toonSitTrack = getToonSitTrack( av )

        jumpTrack = Sequence(
            Parallel(
                toonJumpTrack,
                Sequence( Wait(1),
                          toonSitTrack,
                          ),
                ),
##            Func( av.wrtReparentTo, self.golfKart ),
            )

        return jumpTrack
Пример #24
0
    def showToonHitBySuit(self, avId, timestamp):
        toon = self.getAvatar(avId)
        if toon == None:
            return None

        rng = self.toonRNGs[self.avIdList.index(avId)]
        curPos = toon.getPos(render)
        oldTrack = self.toonHitTracks[avId]
        if oldTrack.isPlaying():
            oldTrack.finish()

        toon.setPos(curPos)
        toon.setZ(self.TOON_Z)
        parentNode = render.attachNewNode('mazeFlyToonParent-' + ` avId `)
        parentNode.setPos(toon.getPos())
        toon.reparentTo(parentNode)
        toon.setPos(0, 0, 0)
        startPos = parentNode.getPos()
        dropShadow = toon.dropShadow.copyTo(parentNode)
        dropShadow.setScale(toon.dropShadow.getScale(render))
        trajectory = Trajectory.Trajectory(0,
                                           Point3(0, 0, 0),
                                           Point3(0, 0, 50),
                                           gravMult=1.0)
        oldFlyDur = trajectory.calcTimeOfImpactOnPlane(0.0)
        trajectory = Trajectory.Trajectory(0,
                                           Point3(0, 0, 0),
                                           Point3(0, 0, 50),
                                           gravMult=0.55000000000000004)
        flyDur = trajectory.calcTimeOfImpactOnPlane(0.0)
        avIndex = self.avIdList.index(avId)
        endPos = CTGG.ToonStartingPositions[avIndex]

        def flyFunc(t,
                    trajectory,
                    startPos=startPos,
                    endPos=endPos,
                    dur=flyDur,
                    moveNode=parentNode,
                    flyNode=toon):
            u = t / dur
            moveNode.setX(startPos[0] + u * (endPos[0] - startPos[0]))
            moveNode.setY(startPos[1] + u * (endPos[1] - startPos[1]))
            flyNode.setPos(trajectory.getPos(t))

        flyTrack = Sequence(LerpFunctionInterval(flyFunc,
                                                 fromData=0.0,
                                                 toData=flyDur,
                                                 duration=flyDur,
                                                 extraArgs=[trajectory]),
                            name=toon.uniqueName('hitBySuit-fly'))
        geomNode = toon.getGeomNode()
        startHpr = geomNode.getHpr()
        destHpr = Point3(startHpr)
        hRot = rng.randrange(1, 8)
        if rng.choice([0, 1]):
            hRot = -hRot

        destHpr.setX(destHpr[0] + hRot * 360)
        spinHTrack = Sequence(LerpHprInterval(geomNode,
                                              flyDur,
                                              destHpr,
                                              startHpr=startHpr),
                              Func(geomNode.setHpr, startHpr),
                              name=toon.uniqueName('hitBySuit-spinH'))
        parent = geomNode.getParent()
        rotNode = parent.attachNewNode('rotNode')
        geomNode.reparentTo(rotNode)
        rotNode.setZ(toon.getHeight() / 2.0)
        oldGeomNodeZ = geomNode.getZ()
        geomNode.setZ(-toon.getHeight() / 2.0)
        startHpr = rotNode.getHpr()
        destHpr = Point3(startHpr)
        pRot = rng.randrange(1, 3)
        if rng.choice([0, 1]):
            pRot = -pRot

        destHpr.setY(destHpr[1] + pRot * 360)
        spinPTrack = Sequence(LerpHprInterval(rotNode,
                                              flyDur,
                                              destHpr,
                                              startHpr=startHpr),
                              Func(rotNode.setHpr, startHpr),
                              name=toon.uniqueName('hitBySuit-spinP'))
        i = self.avIdList.index(avId)
        soundTrack = Sequence(Func(base.playSfx,
                                   self.sndTable['hitBySuit'][i]),
                              Wait(flyDur * (2.0 / 3.0)),
                              SoundInterval(self.sndTable['falling'][i],
                                            duration=flyDur * (1.0 / 3.0)),
                              name=toon.uniqueName('hitBySuit-soundTrack'))

        def preFunc(self=self, avId=avId, toon=toon, dropShadow=dropShadow):
            forwardSpeed = toon.forwardSpeed
            rotateSpeed = toon.rotateSpeed
            if avId == self.localAvId:
                self.stopGameWalk()
            else:
                toon.stopSmooth()
            if forwardSpeed or rotateSpeed:
                toon.setSpeed(forwardSpeed, rotateSpeed)

            toon.dropShadow.hide()

        def postFunc(self=self,
                     avId=avId,
                     oldGeomNodeZ=oldGeomNodeZ,
                     dropShadow=dropShadow,
                     parentNode=parentNode):
            if avId == self.localAvId:
                base.localAvatar.setPos(endPos)
                if hasattr(self, 'gameWalk'):
                    toon = base.localAvatar
                    toon.setSpeed(0, 0)
                    self.startGameWalk()

            dropShadow.removeNode()
            del dropShadow
            toon = self.getAvatar(avId)
            if toon:
                toon.dropShadow.show()
                geomNode = toon.getGeomNode()
                rotNode = geomNode.getParent()
                baseNode = rotNode.getParent()
                geomNode.reparentTo(baseNode)
                rotNode.removeNode()
                del rotNode
                geomNode.setZ(oldGeomNodeZ)

            if toon:
                toon.reparentTo(render)
                toon.setPos(endPos)

            parentNode.removeNode()
            del parentNode
            if avId != self.localAvId:
                if toon:
                    toon.startSmooth()

        preFunc()
        slipBack = Parallel(
            Sequence(ActorInterval(toon, 'slip-backward', endFrame=24),
                     Wait(CTGG.LyingDownDuration - flyDur - oldFlyDur),
                     ActorInterval(toon, 'slip-backward', startFrame=24)))
        if toon.doId == self.localAvId:
            slipBack.append(SoundInterval(self.sndOof))

        hitTrack = Sequence(Parallel(flyTrack, spinHTrack, spinPTrack,
                                     soundTrack),
                            slipBack,
                            Func(postFunc),
                            name=toon.uniqueName('hitBySuit'))
        self.notify.debug('hitTrack duration = %s' % hitTrack.getDuration())
        self.toonHitTracks[avId] = hitTrack
        hitTrack.start(globalClockDelta.localElapsedTime(timestamp))
 def makeToonGrabInterval(self, toon):
     toon.pose('leverNeutral', 0)
     toon.update()
     rightHandPos = toon.rightHand.getPos(toon)
     self.toonPitcherPosition = Point3(self.handPos[0] - rightHandPos[0], self.handPos[1] - rightHandPos[1], 0)
     destZScale = rightHandPos[2] / self.handPos[2]
     grabIval = Sequence(Func(toon.wrtReparentTo, self.waterPitcherNode), Func(toon.loop, 'neutral'), Parallel(ActorInterval(toon, 'jump'), Sequence(Wait(0.43), Parallel(ProjectileInterval(toon, duration=0.9, startPos=toon.getPos(self.waterPitcherNode), endPos=self.toonPitcherPosition), LerpHprInterval(toon, 0.9, Point3(0, 0, 0)), LerpScaleInterval(self.waterPitcherModel, 0.9, Point3(1, 1, destZScale))))), Func(toon.setPos, self.toonPitcherPosition), Func(toon.loop, 'leverNeutral'))
     return grabIval
 def stopVideo(self):
     self.movieSound.stop()
     self.card.removeNode()
     self.t.fadeOut(0)
     self.pickAToon.createGui(1)
     Sequence(Wait(0.2), Func(self.t.fadeIn, 1)).start()
class InteractiveAnimatedProp(GenericAnimatedProp.GenericAnimatedProp, FSM.FSM):
    ZoneToIdles = {}
    ZoneToIdleIntoFightAnims = {}
    ZoneToFightAnims = {}
    ZoneToVictoryAnims = {}
    ZoneToSadAnims = {}
    IdlePauseTime = base.config.GetFloat('prop-idle-pause-time', 0.0)
    HpTextGenerator = TextNode('HpTextGenerator')
    BattleCheerText = '+'

    def __init__(self, node):
        FSM.FSM.__init__(self, 'InteractiveProp-%s' % str(node))
        self.numIdles = 0
        self.numFightAnims = 0
        self.idleInterval = None
        self.battleCheerInterval = None
        self.sadInterval = None
        self.victoryInterval = None
        self.lastIdleAnimName = ''
        self.lastIdleTime = 0
        self.curIval = None
        self.okToStartNextAnim = False
        cellIndexStr = node.getTag('DNACellIndex')
        self.cellIndex = ord(cellIndexStr)
        self.origAnimNameToSound = {}
        self.lastPlayingAnimPhase = 0
        self.buildingsMakingMeSad = set()
        GenericAnimatedProp.GenericAnimatedProp.__init__(self, node)

    def delete(self):
        self.exit()
        GenericAnimatedProp.GenericAnimatedProp.delete(self)
        self.idleInterval = None
        self.battleCheerInterval = None
        self.sadInterval = None
        self.victoryInterval = None

    def getCellIndex(self):
        return self.cellIndex

    def playBattleCheerAnim(self):
        self.node.loop('battleCheer')

    def setupActor(self, node):
        if self.hoodId in self.ZoneToIdles:
            self.numIdles = len(self.ZoneToIdles[self.hoodId])
        if self.hoodId in self.ZoneToFightAnims:
            self.numFightAnims = len(self.ZoneToFightAnims[self.hoodId])

        self.idleInterval = None
        anim = node.getTag('DNAAnim')
        self.trashcan = Actor.Actor(node, copy=0)
        self.trashcan.reparentTo(node)
        animDict = {}
        animDict['anim'] = '%s/%s' % (self.path, anim)

        for i in xrange(self.numIdles):
            baseAnim = self.ZoneToIdles[self.hoodId][i]

            if isinstance(baseAnim, tuple):
                baseAnim = baseAnim[0]

            animStr = self.path + '/' + baseAnim
            animKey = 'idle%d' % i
            animDict[animKey] = animStr
            settleName = self.getSettleName(i)

            if settleName:
                settleStr = self.path + '/' + settleName
                settleKey = 'settle%d' % i
                animDict[settleKey] = settleStr

        for i in xrange(self.numFightAnims):
            animStr = self.path + '/' + self.ZoneToFightAnims[self.hoodId][i]
            animKey = 'fight%d' % i
            animDict[animKey] = animStr

        if self.hoodId in self.ZoneToIdleIntoFightAnims:
            animStr = self.path + '/' + self.ZoneToIdleIntoFightAnims[self.hoodId]
            animKey = 'idleIntoFight'
            animDict[animKey] = animStr

        if self.hoodId in self.ZoneToIdleIntoFightAnims:
            animStr = self.path + '/' + self.ZoneToVictoryAnims[self.hoodId]
            animKey = 'victory'
            animDict[animKey] = animStr

        if self.hoodId in self.ZoneToSadAnims:
            animStr = self.path + '/' + self.ZoneToSadAnims[self.hoodId]
            animKey = 'sad'
            animDict[animKey] = animStr

        self.trashcan.loadAnims(animDict)
        self.trashcan.pose('anim', 0)
        self.node = self.trashcan
        self.idleInterval = self.createIdleInterval()
        self.battleCheerInterval = self.createBattleCheerInterval()
        self.victoryInterval = self.createVictoryInterval()
        self.sadInterval = self.createSadInterval()

    def createIdleInterval(self):
        result = Sequence()

        if self.numIdles >= 3:
            numberOfAnimsAbove2 = self.numIdles - 2
            for rareIdle in xrange(2, self.numIdles):
                for i in xrange(2):
                    result.append(ActorInterval(self.node, 'idle0'))
                    result.append(Wait(self.IdlePauseTime))
                    result.append(ActorInterval(self.node, 'idle1'))
                    result.append(Wait(self.IdlePauseTime))

                result.append(ActorInterval(self.node, 'idle%d' % rareIdle))
                result.append(Wait(self.IdlePauseTime))

        else:
            for i in xrange(self.numIdles):
                result.append(ActorInterval(self.node, 'idle%d' % i))

        self.notify.debug('idle interval=%s' % result)
        return result

    def createBattleCheerText(self):
        self.HpTextGenerator.setFont(ToontownGlobals.getSignFont())
        self.HpTextGenerator.setText(self.BattleCheerText)
        self.HpTextGenerator.clearShadow()
        self.HpTextGenerator.setAlign(TextNode.ACenter)
        r = 0
        g = 0
        b = 1
        a = 1
        self.HpTextGenerator.setTextColor(r, g, b, a)
        self.hpTextNode = self.HpTextGenerator.generate()
        self.hpText = self.node.attachNewNode(self.hpTextNode)
        self.hpText.setScale(1)
        self.hpText.setBillboardPointEye()
        self.hpText.setBin('fixed', 100)
        self.hpText.setPos(0, 0, 4)
        self.hpText.hide()

    def createBattleCheerInterval(self):
        result = Sequence()

        for i in xrange(self.numFightAnims):
            animKey = 'fight%d' % i
            animAndSoundIval = self.createAnimAndSoundIval(animKey)
            origAnimName = self.node.getAnimFilename(animKey).split('/')[-1]
            if self.hasOverrideIval(origAnimName):
                result.append(self.getOverrideIval(origAnimName))
            elif self.hasSpecialIval(origAnimName):
                result.append(Parallel(animAndSoundIval, self.getSpecialIval(origAnimName)))
            else:
                result.append(animAndSoundIval)

        self.createBattleCheerText()
        battleCheerTextIval = Sequence(Func(self.hpText.show), self.hpText.posInterval(duration=4.0, pos=Vec3(0, 0, 7), startPos=(0, 0, 3)), Func(self.hpText.hide))
        ivalWithText = Parallel(battleCheerTextIval, result)

        return ivalWithText

    def createSadInterval(self):
        result = Sequence()
        if self.hoodId in self.ZoneToSadAnims:
            result = self.createAnimAndSoundIval('sad')
        return result

    def hasSpecialIval(self, origAnimName):
        return False

    def getSpecialIval(self, origAnimName):
        return Sequence()

    def hasOverrideIval(self, origAnimName):
        return False

    def getOverrideIval(self, origAnimName):
        return Sequence()

    def createVictoryInterval(self):
        result = Sequence()

        if self.hoodId in self.ZoneToVictoryAnims:
            animAndSoundIval = self.createAnimAndSoundIval('victory')
            result.append(animAndSoundIval)

        return result

    def enter(self):
        GenericAnimatedProp.GenericAnimatedProp.enter(self)

        if base.config.GetBool('props-buff-battles', True):
            self.notify.debug('props buff battles is true')
            self.node.stop()
            self.node.pose('idle0', 0)
            self.requestIdleOrSad()
        else:
            self.notify.debug('props do not buff battles')
            self.node.stop()
            self.node.pose('idle0', 0)

    def exit(self):
        self.okToStartNextAnim = False
        self.notify.debug('%s %d okToStartNextAnim=%s' % (self, self.visId, self.okToStartNextAnim))
        GenericAnimatedProp.GenericAnimatedProp.exit(self)
        self.request('Off')

    def requestIdleOrSad(self):
        if not hasattr(self, 'node') or not self.node:
            self.notify.warning("requestIdleOrSad  returning hasattr(self,'node')=%s" % hasattr(self, 'node'))
            return

        if self.buildingsMakingMeSad:
            self.request('Sad')
        else:
            self.request('DoIdleAnim')

    def enterDoIdleAnim(self):
        self.notify.debug('enterDoIdleAnim numIdels=%d' % self.numIdles)
        self.okToStartNextAnim = True
        self.notify.debug('%s %d okToStartNextAnim=%s' % (self, self.visId, self.okToStartNextAnim))
        self.startNextIdleAnim()

    def exitDoIdleAnim(self):
        self.notify.debug('exitDoIdlesAnim numIdles=%d' % self.numIdles)
        self.okToStartNextAnim = False
        self.notify.debug('%s %d okToStartNextAnim=%s' % (self, self.visId, self.okToStartNextAnim))
        self.calcLastIdleFrame()
        self.clearCurIval()

    def calcLastIdleFrame(self):
        if self.curIval and self.curIval.ivals:
            firstIval = self.curIval.ivals[0]
            if isinstance(firstIval, ActorInterval):
                self.lastIdleFrame = firstIval.getCurrentFrame()
                self.lastIdleAnimName = firstIval.animName
            elif isinstance(firstIval, Parallel):
                for testIval in firstIval.ivals:
                    if isinstance(firstIval, ActorInterval):
                        self.lastIdleTime = testIval.getT()
                        self.lastIdleAnimName = testIval.animName
                        break

    def chooseIdleAnimToRun(self):
        result = self.numIdles - 1

        if base.config.GetBool('randomize-interactive-idles', True):
            pairs = []
            for i in xrange(self.numIdles):
                reversedChance = self.numIdles - i - 1
                pairs.append((math.pow(2, reversedChance), i))

            sum = math.pow(2, self.numIdles) - 1
            result = weightedChoice(pairs, sum=sum)
            self.notify.debug('chooseAnimToRun numIdles=%s pairs=%s result=%s' % (self.numIdles, pairs, result))
        else:
            result = self.lastPlayingAnimPhase + 1
            if result >= len(self.ZoneToIdles[self.hoodId]):
                result = 0

        return result

    def startNextIdleAnim(self):
        if not hasattr(self, 'node') or not self.node:
            self.notify.warning("startNextIdleAnim returning hasattr(self,'node')=%s" % hasattr(self, 'node'))
            return

        self.curIval = None

        if self.okToStartNextAnim:
            self.notify.debug('got pass okToStartNextAnim')
            whichAnim = self.chooseIdleAnimToRun()
            self.lastPlayingAnimPhase = whichAnim
            self.curIval = self.createIdleAnimSequence(whichAnim)
            self.notify.debug('starting curIval of length %s' % self.curIval.getDuration())
            self.curIval.start()
        else:
            self.curIval = Wait(3)
            self.notify.debug('false self.okToStartNextAnim=%s' % self.okToStartNextAnim)

    def createIdleAnimAndSoundInterval(self, whichIdleAnim, startingTime = 0):
        animIval = self.node.actorInterval('idle%d' % whichIdleAnim, startTime=startingTime)
        animIvalDuration = animIval.getDuration()
        origAnimName = self.ZoneToIdles[self.hoodId][whichIdleAnim]

        if isinstance(origAnimName, tuple):
            origAnimName = origAnimName[0]

        soundIval = self.createSoundInterval(origAnimName, animIvalDuration)
        soundIvalDuration = soundIval.getDuration()

        if self.hasSpecialIval(origAnimName):
            specialIval = self.getSpecialIval(origAnimName)
            return Parallel(animIval, soundIval, specialIval)
        else:
            return Parallel(animIval, soundIval)

    def createIdleAnimSequence(self, whichIdleAnim):
        dummyResult = Sequence(Wait(self.IdlePauseTime))

        if not hasattr(self, 'node') or not self.node:
            self.notify.warning("createIdleAnimSequence returning dummyResult hasattr(self,'node')=%s" % hasattr(self, 'node'))
            return dummyResult

        idleAnimAndSound = self.createIdleAnimAndSoundInterval(whichIdleAnim)
        result = Sequence(idleAnimAndSound, Wait(self.IdlePauseTime), Func(self.startNextIdleAnim))

        if isinstance(self.ZoneToIdles[self.hoodId][whichIdleAnim], tuple) and len(self.ZoneToIdles[self.hoodId][whichIdleAnim]) > 2:
            info = self.ZoneToIdles[self.hoodId][whichIdleAnim]
            origAnimName = info[0]
            minLoop = info[1]
            maxLoop = info[2]
            settleAnim = info[3]
            minPauseTime = info[4]
            maxPauseTime = info[5]
            numberOfLoops = random.randrange(minLoop, maxLoop + 1)
            pauseTime = random.randrange(minPauseTime, maxPauseTime + 1)
            result = Sequence()
            for i in xrange(numberOfLoops):
                result.append(idleAnimAndSound)

            if self.getSettleName(whichIdleAnim):
                result.append(self.node.actorInterval('settle%d' % whichIdleAnim))
            result.append(Wait(pauseTime))
            result.append(Func(self.startNextIdleAnim))

        return result

    def gotoBattleCheer(self):
        self.notify.debugStateCall(self)
        self.request('BattleCheer')

    def gotoIdle(self):
        self.notify.debugStateCall(self)
        self.request('DoIdleAnim')

    def gotoVictory(self):
        self.notify.debugStateCall(self)
        self.request('Victory')

    def gotoSad(self, buildingDoId):
        self.notify.debugStateCall(self)
        self.buildingsMakingMeSad.add(buildingDoId)
        self.request('Sad')

    def buildingLiberated(self, buildingDoId):
        self.buildingsMakingMeSad.discard(buildingDoId)

        if not self.buildingsMakingMeSad:
            self.gotoIdle()

    def calcWhichIdleAnim(self, animName):
        result = 0
        info = self.ZoneToIdles[self.hoodId]

        for index, curInfo in enumerate(info):
            if isinstance(curInfo, tuple):
                if curInfo[0] == animName:
                    result = index
                    break
            elif isinstance(curInfo, str):
                if curInfo == animName:
                    result = index
                    breal

        return result

    def enterBattleCheer(self):
        self.notify.debugStateCall(self)
        self.curIval = self.battleCheerInterval

        if self.curIval:
            self.curIval.loop()

    def exitBattleCheer(self):
        self.notify.debugStateCall(self)

        if self.curIval:
            self.curIval.finish()
            self.curIval = None

    def enterVictory(self):
        self.notify.debugStateCall(self)
        self.curIval = self.victoryInterval

        if self.curIval:
            self.curIval.loop()

    def exitVictory(self):
        self.notify.debugStateCall(self)

        if self.curIval:
            self.curIval.finish()
            self.curIval = None

    def enterSad(self):
        self.notify.debugStateCall(self)
        self.curIval = self.sadInterval

        if self.curIval:
            self.curIval.loop()

    def exitSad(self):
        self.notify.debugStateCall(self)

        if self.curIval:
            self.curIval.finish()
            self.curIval = None

    def getSettleName(self, whichIdleAnim):
        if isinstance(self.ZoneToIdles[self.hoodId][whichIdleAnim], tuple) and len(self.ZoneToIdles[self.hoodId][whichIdleAnim]) > 3:
            return self.ZoneToIdles[self.hoodId][whichIdleAnim][3]
        return None

    def getOrigIdleAnimName(self, whichIdleAnim):
        anim = self.ZoneToIdles[self.hoodId][whichIdleAnim]

        return anim[0] if isinstance(anim, tuple) else anim

    def createAnimAndSoundIval(self, animKey):
        animIval = self.node.actorInterval(animKey)
        animIvalDuration = animIval.getDuration()
        origAnimName = self.node.getAnimFilename(animKey)
        soundIval = self.createSoundInterval(origAnimName, animIvalDuration)
        soundIvalDuration = soundIval.getDuration()

        if self.hasSpecialIval(origAnimName):
            specialIval = self.getSpecialIval(origAnimName)
            return Parallel(animIval, soundIval, specialIval)
        else:
            return Parallel(animIval, soundIval)

    def clearCurIval(self):
        if self.curIval:
            self.curIval.finish()

        clearPythonIvals(self.curIval)
        self.curIval = None
    def doDeathTrack(self):
        def removeDeathSuit(suit, deathSuit):
            if not deathSuit.isEmpty():
                deathSuit.detachNode()
                suit.cleanupLoseActor()

        self.deathSuit.reparentTo(self.suit.getParent())
        self.deathSuit.setScale(self.suit.getScale())
        self.deathSuit.setPos(render, self.suit.getPos(render))
        self.deathSuit.setHpr(render, self.suit.getHpr(render))
        self.suit.hide()
        self.collNodePath.reparentTo(self.deathSuit)
        gearPoint = Point3(0, 0, self.suit.height / 2.0 + 2.0)
        smallGears = BattleParticles.createParticleEffect(
            file='gearExplosionSmall')
        singleGear = BattleParticles.createParticleEffect('GearExplosion',
                                                          numParticles=1)
        smallGearExplosion = BattleParticles.createParticleEffect(
            'GearExplosion', numParticles=10)
        bigGearExplosion = BattleParticles.createParticleEffect(
            'BigGearExplosion', numParticles=30)
        smallGears.setPos(gearPoint)
        singleGear.setPos(gearPoint)
        smallGearExplosion.setPos(gearPoint)
        bigGearExplosion.setPos(gearPoint)
        smallGears.setDepthWrite(False)
        singleGear.setDepthWrite(False)
        smallGearExplosion.setDepthWrite(False)
        bigGearExplosion.setDepthWrite(False)
        suitTrack = Sequence(
            Func(self.collNodePath.stash),
            ActorInterval(self.deathSuit, 'lose', startFrame=80, endFrame=140),
            Func(removeDeathSuit,
                 self.suit,
                 self.deathSuit,
                 name='remove-death-suit'))
        explosionTrack = Sequence(
            Wait(1.5),
            MovieUtil.createKapowExplosionTrack(self.deathSuit,
                                                explosionPoint=gearPoint))
        gears1Track = Sequence(ParticleInterval(smallGears,
                                                self.deathSuit,
                                                worldRelative=0,
                                                duration=4.3,
                                                cleanup=True),
                               name='gears1Track')
        gears2MTrack = Track((0.0, explosionTrack),
                             (0.7,
                              ParticleInterval(singleGear,
                                               self.deathSuit,
                                               worldRelative=0,
                                               duration=5.7,
                                               cleanup=True)),
                             (5.2,
                              ParticleInterval(smallGearExplosion,
                                               self.deathSuit,
                                               worldRelative=0,
                                               duration=1.2,
                                               cleanup=True)),
                             (5.4,
                              ParticleInterval(bigGearExplosion,
                                               self.deathSuit,
                                               worldRelative=0,
                                               duration=1.0,
                                               cleanup=True)),
                             name='gears2MTrack')

        def removeParticle(particle):
            if particle and hasattr(particle, 'renderParent'):
                particle.cleanup()
                del particle

        removeParticles = Sequence(Func(removeParticle, smallGears),
                                   Func(removeParticle, singleGear),
                                   Func(removeParticle, smallGearExplosion),
                                   Func(removeParticle, bigGearExplosion))
        self.deathTrack = Sequence(
            Parallel(suitTrack, gears2MTrack, gears1Track,
                     self._deathSoundIval), removeParticles)
        self.deathTrack.start()
Пример #29
0
def makeExplosion(pos=(0, 0, 0),
                  scale=1,
                  sound=True,
                  shakeCam=True,
                  duration=1.0,
                  soundVol=1.0):
    explosion = loader.loadModel('phase_3.5/models/props/explosion.bam')
    explosion.setScale(scale)
    explosion.reparentTo(render)
    explosion.setBillboardPointEye()
    explosion.setLightOff(1)
    explosion.hide(ShadowCameraBitmask)
    explosion.setPos(pos)

    frames = 10.0
    fps = 24.0
    duration = frames / fps
    explosion.find("**/+SequenceNode").node().play()

    from src.coginvasion.toon import ParticleLoader
    smoke = ParticleLoader.loadParticleEffect(
        "phase_14/etc/explosion_smoke.ptf")
    smoke.setDepthWrite(False, 1)
    smoke.setScale(scale)
    smoke.setPos(pos)
    smoke.start(render, getParticleRender())

    track = Parallel()

    if sound:
        import random

        hlsounds = base.config.GetBool('explosion-hlsounds', False)
        if hlsounds:
            hldir = "phase_14/audio/sfx/"
            snd = base.audio3d.loadSfx(hldir + random.choice(
                ['explode3_hl2', 'explode4_hl2', 'explode5_hl2']) + ".ogg")
        else:
            snd = base.audio3d.loadSfx(
                "phase_3.5/audio/sfx/ENC_cogfall_apart.ogg")

        base.audio3d.attachSoundToObject(snd, explosion)

        # explosion aftermaths
        debChoice = random.randint(1, 4)
        if debChoice <= 3:
            debris = base.audio3d.loadSfx(
                "phase_14/audio/sfx/debris{0}.ogg".format(debChoice))
        else:
            debris = base.audio3d.loadSfx(
                "phase_4/audio/sfx/MG_crash_whizz.ogg")
        base.audio3d.attachSoundToObject(debris, explosion)

        track.append(SoundInterval(snd, volume=soundVol))
        wait = 0.0791 if not hlsounds else 0.0
        track.append(
            Sequence(Wait(wait), SoundInterval(debris, volume=soundVol)))

    if shakeCam:
        dist = camera.getDistance(explosion)
        maxDist = 100.0 * scale
        maxIntense = 1.4 * scale
        if dist <= maxDist:
            base.doCamShake(maxIntense - (maxIntense * (dist / maxDist)),
                            duration)

    track.append(Sequence(Wait(duration), Func(explosion.removeNode)))
    track.append(Sequence(Wait(duration), Func(smoke.softStop)))
    track.start()
    def makeToonReleaseInterval(self, toon):
        temp1 = self.waterPitcherNode.attachNewNode('temp1')
        temp1.setPos(self.toonPitcherPosition)
        temp2 = self.waterPitcherNode.attachNewNode('temp2')
        temp2.setPos(0, -10, -self.waterPitcherNode.getZ())
        startPos = temp1.getPos(render)
        endPos = temp2.getPos(render)
        temp1.removeNode()
        temp2.removeNode()

        def getSlideToPos(toon = toon):
            return render.getRelativePoint(toon, Point3(0, -10, 0))

        if self.gotHitByBoss:
            self.notify.debug('creating zap interval instead')
            grabIval = Sequence(Func(toon.loop, 'neutral'), Func(toon.wrtReparentTo, render), Parallel(ActorInterval(toon, 'slip-backward'), toon.posInterval(0.5, getSlideToPos, fluid=1)))
        else:
            grabIval = Sequence(Func(toon.loop, 'neutral'), Func(toon.wrtReparentTo, render), Parallel(ActorInterval(toon, 'jump'), Sequence(Wait(0.43), ProjectileInterval(toon, duration=0.9, startPos=startPos, endPos=endPos))))
        return grabIval
Пример #31
0
 def addNewAttacker(self, suitId, length=5):
     if not suitId in self.attackers:
         self.attackers.append(suitId)
         Sequence(Wait(length), Func(self.removeAttacker, suitId)).start()
 def fillSlot(self, index, avId, wantBoardingShow=0):
     self.notify.debug('%s.fillSlot(%s, %s, ... %s)' %
                       (self.doId, index, avId, globalClock.getRealTime()))
     request = self.toonRequests.get(index)
     if request:
         self.cr.relatedObjectMgr.abortRequest(request)
         del self.toonRequests[index]
     if avId == 0:
         pass
     elif not self.cr.doId2do.has_key(avId):
         func = PythonUtil.Functor(self.gotToon, index, avId)
         self.toonRequests[index] = self.cr.relatedObjectMgr.requestObjects(
             [avId], allCallback=func)
     elif not self.isSetup:
         self.deferredSlots.append((index, avId, wantBoardingShow))
     else:
         if avId == base.localAvatar.getDoId():
             place = base.cr.playGame.getPlace()
             if not place:
                 return
             elevator = self.getPlaceElevator()
             if elevator == None:
                 place.fsm.request('elevator')
                 elevator = self.getPlaceElevator()
             if not elevator:
                 return
             self.localToonOnBoard = 1
             if hasattr(localAvatar,
                        'boardingParty') and localAvatar.boardingParty:
                 localAvatar.boardingParty.forceCleanupInviteePanel()
                 localAvatar.boardingParty.forceCleanupInviterPanels()
             if hasattr(base.localAvatar, 'elevatorNotifier'):
                 base.localAvatar.elevatorNotifier.cleanup()
             cameraTrack = Sequence()
             cameraTrack.append(
                 Func(elevator.fsm.request, 'boarding',
                      [self.getElevatorModel()]))
             cameraTrack.append(Func(elevator.fsm.request, 'boarded'))
         toon = self.cr.doId2do[avId]
         toon.stopSmooth()
         toon.wrtReparentTo(self.golfKart)
         sitStartDuration = toon.getDuration('sit-start')
         jumpTrack = self.generateToonJumpTrack(toon, index)
         track = Sequence(jumpTrack,
                          Func(toon.setAnimState, 'Sit', 1.0),
                          Func(self.clearToonTrack, avId),
                          name=toon.uniqueName('fillElevator'),
                          autoPause=1)
         if wantBoardingShow:
             boardingTrack, boardingTrackType = self.getBoardingTrack(
                 toon, index, True)
             track = Sequence(boardingTrack, track)
             if avId == base.localAvatar.getDoId():
                 cameraWaitTime = 2.5
                 if boardingTrackType == BoardingGroupShow.TRACK_TYPE_RUN:
                     cameraWaitTime = 0.5
                 cameraTrack = Sequence(Wait(cameraWaitTime), cameraTrack)
         if self.canHideBoardingQuitBtn(avId):
             track = Sequence(
                 Func(localAvatar.boardingParty.groupPanel.disableQuitButton
                      ), track)
         if avId == base.localAvatar.getDoId():
             track = Parallel(cameraTrack, track)
         track.delayDelete = DelayDelete.DelayDelete(
             toon, 'CogKart.fillSlot')
         self.storeToonTrack(avId, track)
         track.start()
         self.fillSlotTrack = track
         self.boardedAvIds[avId] = None
     return
Пример #33
0
    def __showToonHitBySuit(self, avId, timestamp):
        toon = self.getAvatar(avId)
        if toon == None:
            return
        rng = self.toonRNGs[self.avIdList.index(avId)]
        curPos = toon.getPos(render)
        oldTrack = self.toonHitTracks[avId]
        if oldTrack.isPlaying():
            oldTrack.finish()
        toon.setPos(curPos)
        toon.setZ(self.TOON_Z)
        parentNode = render.attachNewNode("mazeFlyToonParent-" + repr(avId))
        parentNode.setPos(toon.getPos())
        toon.reparentTo(parentNode)
        toon.setPos(0, 0, 0)
        startPos = parentNode.getPos()
        dropShadow = toon.dropShadow.copyTo(parentNode)
        dropShadow.setScale(toon.dropShadow.getScale(render))
        trajectory = Trajectory.Trajectory(0,
                                           Point3(0, 0, 0),
                                           Point3(0, 0, 50),
                                           gravMult=1.0)
        flyDur = trajectory.calcTimeOfImpactOnPlane(0.0)
        while 1:
            endTile = [
                rng.randint(2, self.maze.width - 1),
                rng.randint(2, self.maze.height - 1),
            ]
            if self.maze.isWalkable(endTile[0], endTile[1]):
                break
        endWorldCoords = self.maze.tile2world(endTile[0], endTile[1])
        endPos = Point3(endWorldCoords[0], endWorldCoords[1], startPos[2])

        def flyFunc(
            t,
            trajectory,
            startPos=startPos,
            endPos=endPos,
            dur=flyDur,
            moveNode=parentNode,
            flyNode=toon,
        ):
            u = t / dur
            moveNode.setX(startPos[0] + u * (endPos[0] - startPos[0]))
            moveNode.setY(startPos[1] + u * (endPos[1] - startPos[1]))
            flyNode.setPos(trajectory.getPos(t))

        flyTrack = Sequence(
            LerpFunctionInterval(
                flyFunc,
                fromData=0.0,
                toData=flyDur,
                duration=flyDur,
                extraArgs=[trajectory],
            ),
            name=toon.uniqueName("hitBySuit-fly"),
        )
        if avId != self.localAvId:
            cameraTrack = Sequence()
        else:
            self.camParent.reparentTo(parentNode)
            startCamPos = camera.getPos()
            destCamPos = camera.getPos()
            zenith = trajectory.getPos(flyDur / 2.0)[2]
            destCamPos.setZ(zenith * 1.3)
            destCamPos.setY(destCamPos[1] * 0.3)

            def camTask(
                task,
                zenith=zenith,
                flyNode=toon,
                startCamPos=startCamPos,
                camOffset=destCamPos - startCamPos,
            ):
                u = flyNode.getZ() / zenith
                camera.setPos(startCamPos + camOffset * u)
                camera.lookAt(toon)
                return Task.cont

            camTaskName = "mazeToonFlyCam-" + repr(avId)
            taskMgr.add(camTask, camTaskName, priority=20)

            def cleanupCamTask(self=self,
                               toon=toon,
                               camTaskName=camTaskName,
                               startCamPos=startCamPos):
                taskMgr.remove(camTaskName)
                self.camParent.reparentTo(toon)
                camera.setPos(startCamPos)
                camera.lookAt(toon)

            cameraTrack = Sequence(Wait(flyDur),
                                   Func(cleanupCamTask),
                                   name="hitBySuit-cameraLerp")

        geomNode = toon.getGeomNode()
        startHpr = geomNode.getHpr()
        destHpr = Point3(startHpr)
        hRot = rng.randrange(1, 8)
        if rng.choice([0, 1]):
            hRot = -hRot
        destHpr.setX(destHpr[0] + hRot * 360)
        spinHTrack = Sequence(
            LerpHprInterval(geomNode, flyDur, destHpr, startHpr=startHpr),
            Func(geomNode.setHpr, startHpr),
            name=toon.uniqueName("hitBySuit-spinH"),
        )
        parent = geomNode.getParent()
        rotNode = parent.attachNewNode("rotNode")
        geomNode.reparentTo(rotNode)
        rotNode.setZ(toon.getHeight() / 2.0)
        oldGeomNodeZ = geomNode.getZ()
        geomNode.setZ(-toon.getHeight() / 2.0)
        startHpr = rotNode.getHpr()
        destHpr = Point3(startHpr)
        pRot = rng.randrange(1, 3)
        if rng.choice([0, 1]):
            pRot = -pRot
        destHpr.setY(destHpr[1] + pRot * 360)
        spinPTrack = Sequence(
            LerpHprInterval(rotNode, flyDur, destHpr, startHpr=startHpr),
            Func(rotNode.setHpr, startHpr),
            name=toon.uniqueName("hitBySuit-spinP"),
        )
        i = self.avIdList.index(avId)
        soundTrack = Sequence(
            Func(base.playSfx, self.sndTable["hitBySuit"][i]),
            Wait(flyDur * (2.0 / 3.0)),
            SoundInterval(self.sndTable["falling"][i],
                          duration=flyDur * (1.0 / 3.0)),
            name=toon.uniqueName("hitBySuit-soundTrack"),
        )

        def preFunc(self=self, avId=avId, toon=toon, dropShadow=dropShadow):
            forwardSpeed = toon.forwardSpeed
            rotateSpeed = toon.rotateSpeed
            if avId == self.localAvId:
                self.orthoWalk.stop()
            else:
                toon.stopSmooth()
            if forwardSpeed or rotateSpeed:
                toon.setSpeed(forwardSpeed, rotateSpeed)
            toon.dropShadow.hide()

        def postFunc(
            self=self,
            avId=avId,
            oldGeomNodeZ=oldGeomNodeZ,
            dropShadow=dropShadow,
            parentNode=parentNode,
        ):
            if avId == self.localAvId:
                base.localAvatar.setPos(endPos)
                if hasattr(self, "orthoWalk"):
                    if self.gameFSM.getCurrentState().getName() == "play":
                        self.orthoWalk.start()
            dropShadow.removeNode()
            del dropShadow
            toon.dropShadow.show()
            geomNode = toon.getGeomNode()
            rotNode = geomNode.getParent()
            baseNode = rotNode.getParent()
            geomNode.reparentTo(baseNode)
            rotNode.removeNode()
            del rotNode
            geomNode.setZ(oldGeomNodeZ)
            toon.reparentTo(render)
            toon.setPos(endPos)
            parentNode.removeNode()
            del parentNode
            if avId != self.localAvId:
                toon.startSmooth()

        preFunc()

        hitTrack = Sequence(
            Parallel(flyTrack, cameraTrack, spinHTrack, spinPTrack,
                     soundTrack),
            Func(postFunc),
            name=toon.uniqueName("hitBySuit"),
        )

        self.toonHitTracks[avId] = hitTrack

        hitTrack.start(globalClockDelta.localElapsedTime(timestamp))