def createGui(self): self.deleteGui() phase = 'phase_3.5/maps/' posGroup = self.threeSlotsPos self.inventoryFrame = DirectFrame(parent=base.a2dRightCenter, pos=(-0.2, 0, 0)) if self.defaultSlots == 4: posGroup = self.fourSlotPos for slot in range(len(posGroup) + 1): if slot == 3: posGroup = self.fourSlotPos slotIdle = loader.loadTexture(phase + 'slot_%s_idle.png' % str(slot + 1)) slotObj = Slot(slot + 1, posGroup[slot], self.inventoryFrame) slotOutline = OnscreenImage(image=slotIdle, color=(1, 1, 1, 0.5), parent=slotObj) slotOutline.setTransparency(TransparencyAttrib.MAlpha) slotObj.setOutline(slotOutline) self.slots.append(slotObj) if slot == 3: slotObj.hide() self.ammoLabel = DirectLabel(text='Ammo: 0', text_fg=(1, 1, 1, 1), relief=None, text_shadow=(0, 0, 0, 1), text_scale=0.08, pos=(0.2, 0, 0.35), parent=base.a2dBottomLeft) self.ammoLabel.hide() self.enableWeaponSwitch() self.resetScroll() self.update() return
def getCrosshair(scale=0.04, color=(1, 1, 1, 1), hidden=True): crosshair = OnscreenImage(image="phase_4/maps/crosshair.png", scale=scale, color=color) crosshair.setTransparency(True) if hidden: crosshair.hide() return crosshair
def getLogoImage(parent = None, size = 1, pos = (0, 0, 0)): from direct.gui.DirectGui import OnscreenImage if not parent: parent = aspect2d logo = loader.loadTexture("phase_3/maps/CogInvasion_Logo.png") logoNode = parent.attachNewNode('logoNode') logoNode.setScale(size) logoNode.setPos(pos) factor = 0.315 logoImg = OnscreenImage(image = logo, scale = (1.920 * factor, 0, 1.080 * factor), parent = logoNode) logoImg.setTransparency(1) return [logoNode, logoImg]
def __init__(self, viewport): DocObject.__init__(self, viewport.doc) self.viewport = viewport self.enabled = False self.mouseSensitivity = 0.3 self.cameraSpeed = 500 / 16.0 self.timeToSpeed = 0.5 # seconds self.moveStart = 0.0 self.cameraRotateSpeed = 75.0 self.cameraSmooth = 0.7 self.slideFactor = 0.75 self.maxPitch = 90 self.minPitch = -90 self.diagonalFactor = math.sqrt(2.0) / 2.0 self.lastSpeeds = Vec3(0) self.moving = False self.cursor = QtGui.QCursor() self.cursor.setShape(QtCore.Qt.BlankCursor) tex = base.loader.loadTexture('icons/editor-crosshair.png') tex.setMinfilter(SamplerState.FTLinear) tex.setMagfilter(SamplerState.FTLinear) crosshair = OnscreenImage(tex) crosshair.setTransparency(True) crosshair.setScale(0.04) crosshair.reparentTo(NodePath()) self.crosshair = crosshair self.inputState = {} self.addInput("forward", KeyBind.Forward3DView) self.addInput("reverse", KeyBind.Back3DView) self.addInput("slideLeft", KeyBind.Left3DView) self.addInput("slideRight", KeyBind.Right3DView) self.addInput("floatDown", KeyBind.Down3DView) self.addInput("floatUp", KeyBind.Up3DView) self.addInput("lookUp", KeyBind.LookUp3DView) self.addInput("lookDown", KeyBind.LookDown3DView) self.addInput("lookRight", KeyBind.LookRight3DView) self.addInput("lookLeft", KeyBind.LookLeft3DView) self.accept(KeyBinds.getPandaShortcut(KeyBind.FlyCam), self.handleZ) self.doc.taskMgr.add(self.__flyCamTask, 'flyCam')
def goto_home(self): self.soft_destroy() LerpPosHprInterval(base.camera, 0.35, Point3(0, 0, 0), Point3(0, 0, 0)).start() logo = OnscreenImage(image=loader.loadTexture('mainmenu/logo.png'), pos=(0, 0, 0.625), scale=(1, 1, 0.4)) logo.setTransparency(TransparencyAttrib.MAlpha) exit_button = DirectButton( geom=(self.sprites.find('**/mm-exit-ready'), self.sprites.find('**/mm-exit-click'), self.sprites.find('**/mm-exit-hover'), self.sprites.find('**/mm-exit-disabled')), relief=None, geom_scale=(0.666, 0, 0.25), geom_pos=(0, 0, -0.75), command=self.level_holder.exit_game) settings_button = DirectButton( geom=(self.sprites.find('**/mm-settings-ready'), self.sprites.find('**/mm-settings-click'), self.sprites.find('**/mm-settings-hover'), self.sprites.find('**/mm-settings-disabled')), relief=None, geom_scale=(0.666, 0, 0.25), geom_pos=(0, 0, -0.4), command=self.goto_settings) play_button = DirectButton( geom=(self.sprites.find('**/mm-play-ready'), self.sprites.find('**/mm-play-click'), self.sprites.find('**/mm-play-hover'), self.sprites.find('**/mm-play-disabled')), relief=None, geom_scale=(1, 0, 0.3), geom_pos=(0, 0, 0.1), command=self.goto_play) if not self.level_holder.check_connection(): play_button["state"] = DGG.DISABLED self.images["img_logo"] = logo self.gui["btn_exit"] = exit_button self.gui["btn_settings"] = settings_button self.gui["btn_play"] = play_button
def createEnviroment(self): # Fog to hide performance tweak: colour = (0.5, 0.5, 0.5) expfog = Fog("scene-wide-fog") expfog.setColor(*colour) expfog.setExpDensity(0.002) self.render.setFog(expfog) base.setBackgroundColor(*colour) # Our sky skydome = self.loader.loadModel('blue-sky-sphere') skydome.setEffect(CompassEffect.make(self.render)) skydome.setScale(0.08) # bit less than "far" # NOT render - you`ll fly through the sky!: skydome.reparentTo(self.camera) # Our lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.6, .6, .6, 1)) render.setLight(render.attachNewNode(ambientLight)) directionalLight = DirectionalLight("directionalLight") directionalLight.setColor(Vec4(0.8, 0.8, 0.5, 1)) dlnp = self.render.attachNewNode(directionalLight) dlnp.setPos(0, 0, 260) dlnp.lookAt(self.player) self.render.setLight(dlnp) self.render2d = render2d # image scale of 1 fills screen, position defaults to central Scale = 1.0 / 2.5 # decimal point is VITAL self.radar = OnscreenImage(image='radar.png', scale=Scale, \ parent=self.render2d, pos=(-0.95,0,-0.95)) self.radar.setTransparency(TransparencyAttrib.MAlpha) # note the image itself and how it is centered hud = OnscreenImage(image='hud1.png', scale=1, \ parent=self.render2d, pos=(0,0,0)) hud.setTransparency(TransparencyAttrib.MAlpha) self.dots = list() self.playerobj = OnscreenImage(image='playerdot.png', \ scale=1.0/20.0,parent=self.radar) self.playerobj.setTransparency(TransparencyAttrib.MAlpha)
def goto_settings(self): self.soft_destroy() LerpPosHprInterval(base.camera, 0.35, Point3(1, 12, 0), Point3(-7, 0, 0)).start() settings_image = OnscreenImage(image='mainmenu/mm-settings-ready.png', pos=(0, 0, 0.7), scale=(0.5, 1, 0.2)) settings_image.setTransparency(TransparencyAttrib.MAlpha) back_button = DirectButton( geom=(self.sprites.find('**/mm-back-ready'), self.sprites.find('**/mm-back-click'), self.sprites.find('**/mm-back-hover'), self.sprites.find('**/mm-back-disabled')), relief=None, geom_scale=(0.666, 0, 0.25), geom_pos=(0, 0, -0.75), command=self.goto_home) self.gui["btn_settings_back"] = back_button self.images["img_settings"] = settings_image
def updateGUI(self, boundingBox): boundingBox = boundingBox * 2 offsetX = 0.0 offsetZ = 0.0 # would be fine for minimap self.playerobj.setX(self.player.getX() / boundingBox) self.playerobj.setZ(self.player.getY() / boundingBox) # player center if (self.playerobj.getX() > 0.5): offsetX = -(self.playerobj.getX() - 0.5) elif (self.playerobj.getX() < 0.5): offsetX = 0.5 - self.playerobj.getX() # else stays zero if (self.playerobj.getZ() > 0.5): offsetZ = -(self.playerobj.getZ() - 0.5) elif (self.playerobj.getZ() < 0.5): offsetZ = 0.5 - self.playerobj.getZ() self.playerobj.setX(self.playerobj.getX() + offsetX) self.playerobj.setZ(self.playerobj.getZ() + offsetZ) for dot in self.dots: dot.removeNode() # correct way to remove from scene graph del self.dots[:] self.playerobj.setR(-self.player.getH() - 90) newobj = OnscreenImage(image='reddot.png',scale=1.0/60.0, \ parent=self.radar) newobj.setTransparency(TransparencyAttrib.MAlpha) newobj.setX(self.partner.getX() / boundingBox) newobj.setZ(self.partner.getY() / boundingBox) newobj.setX(newobj.getX() + offsetX) newobj.setZ(newobj.getZ() + offsetZ) self.dots.append(newobj) # so can destroy, see call above
class CIProgressScreen: def __init__(self): self.defaultLogoScale = 0.85 self.defaultLogoZ = 0.65 self.bgm = loader.loadModel('phase_3/models/gui/progress-background.bam') self.bgm.find('**/logo').stash() self.bg = self.bgm.find('**/bg') self.logo = loader.loadTexture('phase_3/maps/CogInvasion_Logo.png') self.logoNode = hidden.attachNewNode('logoNode') self.logoNode.setScale(self.defaultLogoScale) self.logoNode.setPos(0, self.defaultLogoZ, 0) self.logoImg = OnscreenImage(image=self.logo, scale=(0.685, 0, 0.3), parent=self.logoNode) self.logoImg.setTransparency(True) self.bg_img = OnscreenImage(image=self.bg, parent=hidden) self.bg_img.setSx(1.35) self.bg_img.hide() self.progress_bar = DirectWaitBar(value=0, pos=(0, 0, -0.85), parent=hidden, text_pos=(0, 0, 0.2)) self.progress_bar.setSx(1.064) self.progress_bar.setSz(0.38) toontipgui = loader.loadModel('phase_3.5/models/gui/stickerbook_gui.bam') poster = toontipgui.find('**/questCard') self.toontipFrame = DirectFrame(image=poster, image_scale=(1.4, 1, 1), parent=hidden, relief=None, pos=(0, 0, -0.1), scale=0.85) self.toontipLbl = OnscreenText(text='', parent=self.toontipFrame, fg=(0.35, 0.35, 0.35, 1), font=CIGlobals.getToonFont(), wordwrap=14.5, pos=(-0.59, 0.25), align=TextNode.ALeft, scale=0.08) self.loading_lbl = DirectLabel(text='', relief=None, scale=0.08, pos=(-1.0725, 0, -0.79), text_align=TextNode.ALeft, sortOrder=100, text_fg=(0.343, 0.343, 0.343, 1.0), text_font=CIGlobals.getMinnieFont(), parent=hidden, text_shadow=(0, 0, 0, 1)) return def begin(self, hood, range, wantGui): render.hide() self.renderFrames() base.setBackgroundColor(0, 0, 0) if hood == 'localAvatarEnterGame': self.loading_lbl['text'] = 'Entering...' else: if hood == 'init': self.loading_lbl['text'] = 'Loading...' else: self.loading_lbl['text'] = 'Heading to %s...' % hood self.progress_bar['barColor'] = (0.343, 0.343, 0.343, 1.0) self.progress_bar['range'] = range self.bgm.reparentTo(aspect2d) self.bg.reparentTo(render2d) self.bg_img.reparentTo(hidden) self.loading_lbl.reparentTo(aspect2d) self.logoNode.reparentTo(aspect2d) self.progress_bar.reparentTo(aspect2d) tip = random.choice(CIGlobals.ToonTips) self.toontipLbl.setText('TOON TIP:\n' + tip) self.toontipFrame.reparentTo(aspect2d) self.__count = 0 self.__expectedCount = range self.progress_bar.update(self.__count) def renderFramesTask(self, task): self.renderFrames() return task.cont def end(self): base.setBackgroundColor(CIGlobals.DefaultBackgroundColor) taskMgr.remove('renderFrames') render.show() self.progress_bar.finish() self.bg_img.reparentTo(hidden) self.logoNode.reparentTo(hidden) self.bg.reparentTo(hidden) self.bgm.reparentTo(hidden) self.loading_lbl.reparentTo(hidden) self.progress_bar.reparentTo(hidden) self.toontipFrame.reparentTo(hidden) self.renderFrames() def destroy(self): self.bg.removeNode() del self.bg self.bgm.removeNode() del self.bgm self.bg_img.destroy() self.loading_lbl.destroy() self.progress_bar.destroy() self.bgm.destroy() del self.bg_img del self.loading_lbl del self.progress_bar del self.bgm def renderFrames(self): base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() def tick(self): self.__count += 1 self.progress_bar.update(self.__count)
class DMenuScreen(DirectObject): notify = directNotify.newCategory('DMenuScreen') def __init__(self): DirectObject.__init__(self) base.cr.DMENU_SCREEN = self self.seq = None self.isSeqPlaying = False # .isPlaying() doesnt want to work if DMENU_GAME == 'Toontown': 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 DMENU_GAME == 'Toontown': 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.smPhase2 = self.sillyMeter.find('**/stage2') self.smPhase2.show() self.sillyMeter.loop('phaseOne', partName='meter') self.sillyMeter.setBlend(frameBlend=True) 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() 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 def slipAndSlideOnThisBananaPeelHaHaHa(self): if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() def setPlayingStatus(status): self.isSeqPlaying = status self.ray.setFromLens(base.camNode, mpos.getX(), mpos.getY()) self.bananaClicker.traverse(render) if self.collHandlerQueue.getNumEntries() > 0: self.collHandlerQueue.sortEntries() pickedObj = self.collHandlerQueue.getEntry(0).getIntoNodePath() surleeAnim = random.choice(['slip-backward', 'slip-forward']) dimmAnim = random.choice(['slip-backward', 'slip-forward']) if pickedObj == self.banana: self.seq = Sequence( Func(setPlayingStatus, True), Func(self.surlee.play, surleeAnim), Func(self.dimm.play, dimmAnim), Wait(3), Func(self.surlee.loop, 'scientistGame'), Func(self.dimm.loop, 'scientistGame'), Func(setPlayingStatus, False)) if not self.isSeqPlaying: self.seq.start() def skyTrack(self, task): return SkyUtil.cloudSkyTrack(task) def createButtons(self): buttonImage = GuiModel.find('**/QuitBtn_RLVR') self.PlayButton = DirectButton(relief=None, text_style=3, text_fg=(1, 1, 1, 1), text=PlayGame, text_scale=.1, scale=0.95, command=self.playGame) self.PlayButton.reparentTo(aspect2d) self.PlayButton.setPos(PlayBtnHidePos) self.PlayButton.show() self.OptionsButton = DirectButton(relief=None, text_style=3, text_fg=(1, 1, 1, 1), text=Options, text_scale=.1, scale=0.95, command=self.openOptions) self.OptionsButton.reparentTo(aspect2d) self.OptionsButton.setPos(OptionsBtnHidePos) self.OptionsButton.show() self.QuitButton = DirectButton(relief=None, text_style=3, text_fg=(1, 1, 1, 1), text=Quit, text_scale=.1, scale=0.95, command=self.quitGame) self.QuitButton.reparentTo(aspect2d) self.QuitButton.setPos(QuitBtnHidePos) self.QuitButton.show() # self.BRButton = DirectButton(text = 'REPORT BUG', text_scale = .1, scale=0.95) # self.BRButton.reparentTo(aspect2d) # self.BRButton.setPos(-.9, 0, -.9) # self.BRButton.show() self.buttonInAnimation() def murder(self): if self.logo is not None: self.logo.destroy() self.logo = None if self.background is not None: self.background.hide() self.background.reparentTo(hidden) self.background.removeNode() self.background = None if self.PlayButton is not None: self.PlayButton.destroy() self.PlayButton = None if self.OptionsButton is not None: self.OptionsButton.destroy() self.OptionsButton = None if self.QuitButton is not None: self.QuitButton.destroy() self.QuitButton = None if self.phase3Sfx: self.phase3Sfx.stop() del self.phase3Sfx if self.surlee: self.surlee.delete() if self.dimm: self.dimm.delete() del self.bananaRayNode del self.bananaRayNP del self.bananaClicker del self.collHandlerQueue del self.ray self.ignoreAll() taskMgr.remove('skyTrack') self.sky.reparentTo(hidden) def openOptions(self): self.optionsMgr.showOptions() self.closeOptionsButton = DirectButton( relief=None, image=(btnUp, btnDn, btnRlvr), text="Back", text_fg=(0, 0, 0, 1), text_scale=TTLocalizer.AClogoutButton, text_pos=(0, -0.035), image_scale=1, image1_scale=1.05, image2_scale=1.05, scale=0.7, command=self.hideOptions) self.closeOptionsButton.reparentTo(base.a2dTopLeft) self.closeOptionsButton.setPos(0.5, 0, -0.07) Parallel( self.PlayButton.posInterval(.5, Point3(PlayBtnHidePos), blendType='easeInOut'), self.OptionsButton.posInterval(.5, Point3(OptionsBtnHidePos), blendType='easeInOut'), self.QuitButton.posInterval(.5, Point3(QuitBtnHidePos), blendType='easeInOut'), self.logo.posInterval(0.5, Point3(0, 0, 2.5), blendType='easeInOut')).start() def hideOptions(self): self.optionsMgr.hideOptions() self.closeOptionsButton.hide() self.buttonInAnimation() def playGame(self): if self.fadeOut is not None: self.fadeOut.finish() self.fadeOut = None self.fadeOut = base.transitions.getFadeOutIval(t=1) #base.camera.posHprInterval(1, Point3(TOON_HALL_POS), VBase3(TOON_HALL_HPR), blendType = 'easeInOut').start() Sequence( Func(self.doPlayButton), Wait(1), #Func(self.murder), Func(self.enterGame)).start() #Func(base.transitions.fadeIn, 1)).start() def enterOptions(self): pass def enterGame(self): base.cr.avChoice = PickAToon.PickAToon(self.patAvList, self.patFSM, self.patDoneEvent) base.cr.avChoice.load() base.cr.avChoice.enter() def doPlayButton(self): Parallel( self.PlayButton.posInterval(1, Point3(PlayBtnHidePos), blendType='easeInOut'), self.OptionsButton.posInterval(1, Point3(OptionsBtnHidePos), blendType='easeInOut'), self.QuitButton.posInterval(1, Point3(QuitBtnHidePos), blendType='easeInOut'), self.logo.posInterval(0.5, Point3(0, 0, 2.5), blendType='easeInOut')).start() def quitGame(self): self.showQuitConfirmation() def showQuitConfirmation(self): #self.quitConfirmation.showConfirmation() base.exitFunc() def buttonInAnimation(self): logo = self.logo.posInterval(.5, Point3(0, 0, .5), blendType='easeInOut') play = self.PlayButton.posInterval(.5, Point3(PlayBtnPos), blendType='easeInOut') opt = self.OptionsButton.posInterval(.5, Point3(OptionsBtnPos), blendType='easeInOut') quit = self.QuitButton.posInterval(.5, Point3(QuitBtnPos), blendType='easeInOut') Sequence(Func(logo.start), Wait(0.1), Func(play.start), Wait(0.2), Func(opt.start), Wait(0.2), Func(quit.start)).start() def showHamburgerMenu(self): self.hbButton.hide() self.hbHideButton.show() self.patNode2d = aspect2d.find("**/patNode2d") self.patNode2d.posInterval(.5, Point3(.5, 0, 0), blendType='easeInOut').start() self.patNode = render.find("**/patNode") self.patNode.posInterval(.5, Point3(0, -3, 0), blendType='easeInOut').start() def hideHamburgerMenu(self): self.hbButton.show() self.hbHideButton.hide() self.patNode2d.posInterval(.5, Point3(0, 0, 0), blendType='easeInOut').start() self.patNode.posInterval(.5, Point3(0, 0, 0), blendType='easeInOut').start() def reportBug(self): BugReportGUI.BugReportGUI() def createTabs(self): self.PlayButton = DirectButton(relief=None, text_style=3, text_fg=(1, 1, 1, 1), text=PlayGame, text_scale=.1, scale=0.95, command=self.playGame) self.PlayButton.reparentTo(aspect2d) self.PlayButton.setPos(PlayBtnHidePos) self.PlayButton.show() self.OptionsButton = DirectButton(relief=None, text_style=3, text_fg=(1, 1, 1, 1), text=Options, text_scale=.1, scale=0.95, command=self.openOptions) self.OptionsButton.reparentTo(aspect2d) self.OptionsButton.setPos(OptionsBtnHidePos) self.OptionsButton.show() self.QuitButton = DirectButton(relief=None, text_style=3, text_fg=(1, 1, 1, 1), text=Quit, text_scale=.1, scale=0.95, command=self.quitGame) self.QuitButton.reparentTo(aspect2d) self.QuitButton.setPos(QuitBtnHidePos) self.QuitButton.show()
class DistributedPieTurretManager(DistributedObject): notify = directNotify.newCategory('DistributedPieTurretManager') def __init__(self, cr): DistributedObject.__init__(self, cr) self.myTurret = None self.guiFrame = None self.guiLabel = None self.guiBar = None self.guiBg = None self.turretGag = None def announceGenerate(self): DistributedObject.announceGenerate(self) base.taskMgr.add(self.__pollMyBattle, '__pollMyBattle') def disable(self): base.taskMgr.remove("DPTM.pollTurret") base.taskMgr.remove("__pollMyBattle") if hasattr(self, 'makeTurretBtn'): self.makeTurretBtn.destroy() del self.makeTurretBtn self.destroyGui() self.myTurret = None if base.localAvatar.getMyBattle(): base.localAvatar.getMyBattle().setTurretManager(None) DistributedObject.disable(self) def clearTurret(self): self.turret = None def __pollTurret(self, turretId, task): turret = self.cr.doId2do.get(turretId) if turret != None: self.myTurret = turret self.myTurret.b_setGag(self.turretGag) self.turretGag = None self.acceptOnce(turret.getDeathEvent(), self.clearTurret) self.makeGui() return Task.done return Task.cont def setGag(self, upgradeId): self.turretGag = upgradeId def d_requestPlace(self, posHpr): self.sendUpdate('requestPlace', [posHpr]) def turretPlaced(self, turretId): base.taskMgr.add(self.__pollTurret, 'DPTM.pollTurret', extraArgs=[turretId], appendTask=True) def yourTurretIsDead(self): base.taskMgr.remove('DPTM.pollTurret') self.destroyGui() self.myTurret = None if base.localAvatar.getPUInventory()[0] > 0: self.createTurretButton() def makeGui(self): self.destroyGui() self.guiFrame = DirectFrame(parent=base.a2dBottomRight, pos=(-0.55, 0, 0.15)) self.guiBg = OnscreenImage(image="phase_4/maps/turret_gui_bg.png", scale=(0.15, 0, 0.075), parent=self.guiFrame) self.guiBg.setTransparency(True) self.guiLabel = DirectLabel( text="Turret", text_fg=(1, 0, 0, 1), relief=None, text_scale=0.05, text_font=loader.loadFont("phase_3/models/fonts/ImpressBT.ttf"), pos=(0, 0, 0.025), parent=self.guiFrame) self.guiBar = DirectWaitBar(range=self.myTurret.getMaxHealth(), value=self.myTurret.getHealth(), scale=0.125, parent=self.guiFrame, pos=(0, 0, -0.01)) def createTurretButton(self): self.makeTurretBtn = DirectButton(relief=None, geom=CIGlobals.getDefaultBtnGeom(), text='Turret', text_scale=0.055, command=self.handleMakeTurretBtn, pos=(-0.47, 0, 0.1), geom_scale=(0.5, 1.0, 1.0), text_pos=(0, -0.01), parent=base.a2dBottomRight) if base.localAvatar.getPUInventory()[0]: self.setGag(base.localAvatar.getPUInventory()[1]) def handleMakeTurretBtn(self): self.makeTurretBtn.destroy() del self.makeTurretBtn x, y, z = base.localAvatar.getPos() h, p, r = base.localAvatar.getHpr() self.d_requestPlace([x, y, z, h, p, r]) base.localAvatar.sendUpdate('usedPU', [0]) def __pollMyBattle(self, task): if base.localAvatar.getMyBattle(): base.localAvatar.getMyBattle().setTurretManager(self) if base.localAvatar.getPUInventory()[0] > 0: self.createTurretButton() return Task.done return Task.cont def destroyGui(self): if self.guiBar: self.guiBar.destroy() self.guiBar = None if self.guiLabel: self.guiLabel.destroy() self.guiLabel = None if self.guiBg: self.guiBg.destroy() self.guiBg = None if self.guiFrame: self.guiFrame.destroy() self.guiFrame = None def updateTurretGui(self): if self.guiBar: self.guiBar.update(self.myTurret.getHealth()) def getTurret(self): return self.myTurret
class ClickToStart(DirectObject): notify = directNotify.newCategory('ClickToStart') def __init__(self, version='n/a'): DirectObject.__init__(self) self.backgroundNodePath = render2d.attachNewNode('background', 0) self.backgroundModel = loader.loadModel( 'phase_3/models/gui/loading-background.bam') self.backgroundModel.reparentTo(self.backgroundNodePath) self.backgroundNodePath.find('**/fg').removeNode() self.backgroundNodePath.setScale(1, 1, 1) self.logo = OnscreenImage(parent=base.a2dTopCenter, image='phase_3/maps/toontown-logo.png', scale=(1.0, 1, 0.5), pos=(0, 0, -0.85)) self.logo.setTransparency(TransparencyAttrib.MAlpha) self.label = OnscreenText(TTLocalizer.ClickToStartLabel, parent=base.a2dBottomCenter, font=ToontownGlobals.getMinnieFont(), fg=Vec4(1, 1, 1, 1), scale=0.1, align=TextNode.ACenter) self.label.setZ(0.35) self.versionLabel = OnscreenText('\x01white_shadow\x01%s\x02' % version, parent=base.a2dBottomRight, font=ToontownGlobals.getMinnieFont(), fg=Vec4(0, 0, 0, 1), scale=0.06, align=TextNode.ARight) self.versionLabel.setPos(-0.025, 0.025) self.setColorScale(Vec4(0, 0, 0, 0)) self.fadeTrack = None self.logoPosTrack = None self.logoScaleTrack = None self.labelPosTrack = None self.labelColorScaleTrack = None def delete(self): if self.labelColorScaleTrack is not None: self.labelColorScaleTrack.finish() self.labelColorScaleTrack = None if self.labelPosTrack is not None: self.labelPosTrack.finish() self.labelPosTrack = None if self.logoScaleTrack is not None: self.logoScaleTrack.finish() self.logoScaleTrack = None if self.logoPosTrack is not None: self.logoPosTrack.finish() self.logoPosTrack = None if self.fadeTrack is not None: self.fadeTrack.finish() self.fadeTrack = None if self.versionLabel is not None: self.versionLabel.destroy() self.versionLabel = None if self.label is not None: self.label.destroy() self.label = None if self.logo is not None: self.logo.destroy() self.logo = None if self.backgroundNodePath is not None: self.backgroundNodePath.removeNode() self.backgroundNodePath = None if self.backgroundModel is not None: self.backgroundModel.removeNode() self.backgroundModel = None def start(self): base.transitions.fadeOut(t=0) self.setColorScale(Vec4(1, 1, 1, 1)) if self.fadeTrack is not None: self.fadeTrack.finish() self.fadeTrack = None self.fadeTrack = base.transitions.getFadeInIval(t=2) self.fadeTrack.start() if self.logoScaleTrack is not None: self.logoScaleTrack.finish() self.logoScaleTrack = None self.logoScaleTrack = Sequence( LerpScaleInterval(self.logo, 2, Vec3(1.1, 1, 0.55), Vec3(1, 1, 0.5), blendType='easeInOut'), LerpScaleInterval(self.logo, 2, Vec3(1, 1, 0.5), Vec3(1.1, 1, 0.55), blendType='easeInOut')) if self.logoPosTrack is not None: self.logoPosTrack.finish() self.logoPosTrack = None self.logoPosTrack = Sequence( LerpPosInterval(self.logo, 2, Point3(0, 0, -0.85), Point3(0, 0, -0.7), blendType='easeOut'), Func(self.logoScaleTrack.loop)) self.logoPosTrack.start() if self.labelColorScaleTrack is not None: self.labelColorScaleTrack.finish() self.labelColorScaleTrack = None self.labelColorScaleTrack = Sequence( LerpColorScaleInterval(self.label, 1, Vec4(1, 1, 1, 0.6), Vec4(1, 1, 1, 1)), LerpColorScaleInterval(self.label, 1, Vec4(1, 1, 1, 1), Vec4(1, 1, 1, 0.6))) if self.labelPosTrack is not None: self.labelPosTrack.finish() self.labelPosTrack = None self.labelPosTrack = Sequence( LerpPosInterval(self.label, 2, Point3(0, 0, 0.35), Point3(0, 0, 0.15), blendType='easeOut'), Func(self.labelColorScaleTrack.loop)) self.labelPosTrack.start() self.acceptOnce('mouse1', self.begin) def stop(self): self.ignore('mouse1') if self.labelPosTrack is not None: self.labelPosTrack.finish() self.labelPosTrack = None if self.labelColorScaleTrack is not None: self.labelColorScaleTrack.finish() self.labelColorScaleTrack = None if self.logoPosTrack is not None: self.logoPosTrack.finish() self.logoPosTrack = None if self.logoScaleTrack is not None: self.logoScaleTrack.finish() self.logoScaleTrack = None if self.fadeTrack is not None: self.fadeTrack.finish() self.fadeTrack = None self.setColorScale(Vec4(0, 0, 0, 0)) def begin(self): base.cr.introDone = True if self.fadeTrack is not None: self.fadeTrack.finish() self.fadeTrack = None self.fadeTrack = base.transitions.getFadeOutIval(t=2) Sequence( Func(self.fadeTrack.start), Wait(2), Func(self.delete), Func(base.cr.introduction.delete), Func(base.cr.loginFSM.request, 'chooseAvatar', [base.cr.avList]), Func(base.transitions.fadeIn, 2)).start() def setColorScale(self, *args, **kwargs): self.backgroundNodePath.setColorScale(*args, **kwargs) self.logo.setColorScale(*args, **kwargs) self.label.setColorScale(*args, **kwargs) self.versionLabel.setColorScale(*args, **kwargs)
class DMenuScreen(DirectObject): notify = directNotify.newCategory('DMenuScreen') def __init__(self):#, avatarList, parentFSM, doneEvent): DirectObject.__init__(self) base.disableMouse() #base.cr.avChoice = None fadeSequence = Sequence( Wait(.5), Func(base.transitions.fadeIn, .5), Wait(1)).start()#, #base.camera.posHprInterval(1, Point3(MAIN_POS), VBase3(MAIN_HPR), blendType = 'easeInOut')).start() #self.background = loader.loadModel('phase_4/models/neighborhoods/toontown_central_full') #self.background.reparentTo(render) #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(INIT_POS, INIT_HPR) self.background = OnscreenImage(image = DMenuResources.MenuBackground, parent = aspect2d) self.background.setBin('background', 1) self.background.reparentTo(aspect2d) self.background.setScale(2, 1, 1) self.logo = OnscreenImage(image = DMenuResources.GameLogo, scale = (1, 1, .5)) 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)) #fadeInBackground = (LerpColorScaleInterval(self.background, 1, Vec4(1, 1, 1, 1), Vec4(1, 1, 1, 0))).start() fadeInLogo = (LerpColorScaleInterval(self.logo, 1, Vec4(1, 1, 1, 1), Vec4(1, 1, 1, 0))).start() self.createButtons() self.fadeOut = None self.optionsMgr = DMenuOptions.DMenuOptions() self.quitConfirmation = DMenuQuit.DMenuQuit() # TT: We need these to run the Pick A Toon screen #self.patAvList = avatarList #self.patFSM = parentFSM #self.patDoneEvent = doneEvent self.transcircle = Resources.transcircle self.transcircle.setTransparency(TransparencyAttrib.MAlpha) self.transcircle.setScale(VBase3(0.01, 0.01, 0.01)) self.transcircle.setBin('background', 3) self.savemgr = LOTASaveMgr.LOTASaveMgr() # Get the save data self.savePos = self.savemgr.loadSaveData() self.titleMusic = Resources.titleMusic self.titleMusic.setLoop(1) self.setMusicNormal() def skyTrack(self, task): # return SkyUtil.cloudSkyTrack(task) pass def createButtons(self): self.PlayButton = DirectButton(relief = None, text_style = 3, text_fg = (1, 1, 1, 1), text = DMenuLocalizer.PlayGame, text_scale = .1, scale = 0.95, command = self.playGame) self.PlayButton.reparentTo(aspect2d) self.PlayButton.setPos(PlayBtnHidePos) self.PlayButton.show() self.OptionsButton = DirectButton(relief = None, text_style = 3, text_fg = (1, 1, 1, 1), text = DMenuLocalizer.Options, text_scale = .1, scale = 0.95, command = self.openOptions) self.OptionsButton.reparentTo(aspect2d) self.OptionsButton.setPos(OptionsBtnHidePos) self.OptionsButton.show() self.QuitButton = DirectButton(relief = None, text_style = 3, text_fg = (1, 1, 1, 1), text = DMenuLocalizer.Quit, text_scale = .1, scale = 0.95, command = self.quitGame) self.QuitButton.reparentTo(aspect2d) self.QuitButton.setPos(QuitBtnHidePos) self.QuitButton.show() # self.BRButton = DirectButton(text = 'REPORT BUG', text_scale = .1, scale=0.95) # self.BRButton.reparentTo(aspect2d) # self.BRButton.setPos(-.9, 0, -.9) # self.BRButton.show() self.buttonInAnimation() # Slap on the saves menu from the old main menu until a proper implementation to DMENU is made self.SavesButton = DirectButton(relief = None, text = AmdLocalizerEnglish.LOTA_SAVES, image_scale = 2, text_scale = .1, scale = 0.95, command = self.openSavesMenu) self.SavesButton.reparentTo(aspect2d) self.SavesButton.setPos(0, 0, -.5) self.SavesButton.show() def murder(self): if self.logo is not None: self.logo.destroy() self.logo = None if self.background is not None: self.background.hide() self.background.reparentTo(hidden) self.background.removeNode() self.background = None if self.PlayButton is not None: self.PlayButton.destroy() self.PlayButton = None if self.OptionsButton is not None: self.OptionsButton.destroy() self.OptionsButton = None if self.QuitButton is not None: self.QuitButton.destroy() self.QuitButton = None if self.SavesButton is not None: self.SavesButton.destroy() self.SavesButton = None if self.titleMusic is not None: self.titleMusic.stop() #taskMgr.remove('skyTrack') #self.sky.reparentTo(hidden) def openOptions(self): self.optionsMgr.showOptions() self.closeOptionsButton = DirectButton(relief = None, text = "< Back", text_fg = (0.977, 0.816, 0.133, 1), text_pos = (0, -0.035), scale = .1, command = self.hideOptions) self.closeOptionsButton.reparentTo(base.a2dTopLeft) self.closeOptionsButton.setPos(0.5, 0, -0.07) Parallel( self.PlayButton.posInterval(.5, Point3(PlayBtnHidePos), blendType = 'easeInOut'), self.OptionsButton.posInterval(.5, Point3(OptionsBtnHidePos), blendType = 'easeInOut'), self.QuitButton.posInterval(.5, Point3(QuitBtnHidePos), blendType = 'easeInOut'), self.logo.posInterval(0.5, Point3(0, 0, 2.5), blendType = 'easeInOut')).start() #base.camera.posHprInterval(0.5, Point3(HQ_POS), VBase3(HQ_HPR), blendType = 'easeInOut').start() #self.setMusicCalm() def hideOptions(self): self.optionsMgr.hideOptions() self.closeOptionsButton.hide() Parallel( self.PlayButton.posInterval(.5, Point3(PlayBtnPos), blendType = 'easeInOut'), self.OptionsButton.posInterval(.5, Point3(OptionsBtnPos), blendType = 'easeInOut'), self.QuitButton.posInterval(.5, Point3(QuitBtnPos), blendType = 'easeInOut'), self.logo.posInterval(.5, Point3(0, 0, .5), blendType = 'easeInOut')).start() base.camera.posHprInterval(0.5, Point3(MAIN_POS), VBase3(MAIN_HPR), blendType = 'easeInOut').start() #self.setMusicNormal() def playGame(self): if self.fadeOut is not None: self.fadeOut.finish() self.fadeOut = None self.fadeOut = base.transitions.getFadeOutIval(t = 1) #base.camera.posHprInterval(1, Point3(TOON_HALL_POS), VBase3(TOON_HALL_HPR), blendType = 'easeInOut').start() Sequence( Func(self.doPlayButton), #Func(self.fadeOut.start), Wait(1), Func(self.murder), Wait(1), Func(self.enterGame)).start()#, #Func(base.transitions.fadeIn, 1)).start() def enterOptions(self): pass def enterGame(self): #base.cr.avChoice = AvatarChooser.AvatarChooser(self.patAvList, self.patFSM, self.patDoneEvent) #base.cr.avChoice.load(1) #base.cr.avChoice.enter() from Game.NewGame.Scenes import SceneOne # Hamburger Menu Button #self.hbButton = DirectButton(image = "phase_3/maps/dmenu/dmhbmenu.png", relief = None, text = ' ', command=self.showHamburgerMenu) #self.hbButton.reparentTo(base.a2dTopLeft) #self.hbButton.setPos(0.05, 0, -0.05) #self.hbButton.setScale(0.04) # Hamburger Menu Hide Button #self.hbHideButton = DirectButton(image = "phase_3/maps/dmenu/close_window.png", relief = None, text = ' ', command=self.hideHamburgerMenu) #self.hbHideButton.reparentTo(base.a2dTopLeft) #self.hbHideButton.setPos(0.05, 0, -0.05) #self.hbHideButton.setScale(0.04) #self.hbHideButton.hide() # TODO: Add options and stuff to the hamburger menu def doPlayButton(self): Parallel( self.PlayButton.posInterval(1, Point3(PlayBtnHidePos), blendType = 'easeInOut'), self.OptionsButton.posInterval(1, Point3(OptionsBtnHidePos), blendType = 'easeInOut'), self.QuitButton.posInterval(1, Point3(QuitBtnHidePos), blendType = 'easeInOut'), self.logo.posInterval(0.5, Point3(0, 0, 2.5), blendType = 'easeInOut')).start() def quitGame(self): self.showQuitConfirmation() def showQuitConfirmation(self): self.quitConfirmation.showConfirmation() #base.exitFunc() def setMusicNormal(self): #LerpFunctionInterval(base.cr.music.setVolume, fromData = 0, toData = .9, duration = 1).start() #LerpFunctionInterval(base.cr.musicCalm.setVolume, fromData = .9, toData = 0, duration = 1).start() self.titleMusic.play() def setMusicCalm(self): LerpFunctionInterval(base.cr.music.setVolume, fromData = .9, toData = 0, duration = 1).start() LerpFunctionInterval(base.cr.musicCalm.setVolume, fromData = 0, toData = .9, duration = 1).start() def openSavesMenu(self): self.saveOne = DirectButton(relief=None, text = 'Save One: ' + '(Scene ' + str(self.savePos) + ')', scale=0.3, command=self.saveLoader, parent=aspect2d, pos=(0, 0, -.6), text_scale = .5) self.saveOne.hide() self.transcircle.show() self.exitLoadButton = DirectButton(relief=None, text = '< Back', scale=0.3, command=self.closeSavesMenu, parent=base.a2dBottomCenter, pos=(0, 0, -.4), text_scale = .5) self.exitLoadButton.show() self.openSavesMenuSequence = Parallel( self.transcircle.scaleInterval(0.5, VBase3(3, 3, 3), blendType = 'easeInOut'), self.exitLoadButton.posInterval(0.5, Point3(0, 0, .4), blendType = 'easeInOut'), Func(self.saveOne.show), self.saveOne.posInterval(0.5, Point3(0, 0, .2), blendType = 'easeInOut')) self.openSavesMenuSequence.start() def closeSavesMenu(self): self.hideThings = Sequence( Wait(0.5), Func(self.saveOne.hide), Func(self.transcircle.hide)) self.closeSavesMenuSequence = Parallel( self.saveOne.posInterval(0.5, Point3(0, 0, -.6), blendType = 'easeInOut'), self.transcircle.scaleInterval(0.5, VBase3(0.01, 0.01, 0.01), blendType = 'easeInOut'), self.exitLoadButton.posInterval(0.5, Point3(0, 0, -.4), blendType = 'easeInOut'), Func(self.hideThings.start)) self.closeSavesMenuSequence.start() self.exitLoadButton.removeNode() del self.exitLoadButton def saveLoader(self): # this was thrown together in like 10 seconds. how the f**k does this work # TODO: Make this save to a file thats not easily editable self.saveOne.hide() self.background.hide() self.transcircle.hide() if self.savePos == '1': from Game.NewGame.Scenes import SceneOne elif self.savePos == '2': from Game import SceneTwo elif self.savePos == '3': from Game import SceneThree elif self.savePos == '4': from Game import SceneFour elif self.savePos == '5': from Game import SceneFive else: print ("\n\n Save data is set to an unknown scene!!\n\n") def buttonInAnimation(self): logo = self.logo.posInterval(.5, Point3(0, 0, .5), blendType = 'easeInOut') play = self.PlayButton.posInterval(.5, Point3(PlayBtnPos), blendType = 'easeInOut') opt = self.OptionsButton.posInterval(.5, Point3(OptionsBtnPos), blendType = 'easeInOut') quit = self.QuitButton.posInterval(.5, Point3(QuitBtnPos), blendType = 'easeInOut') Sequence( Func(logo.start), Wait(0.1), Func(play.start), Wait(0.2), Func(opt.start), Wait(0.2), Func(quit.start)).start() def showHamburgerMenu(self): self.hbButton.hide() self.hbHideButton.show() def hideHamburgerMenu(self): self.hbButton.show() self.hbHideButton.hide()
class Slot(DirectFrame): def __init__(self, baseGui, index, pos, parent): DirectFrame.__init__( self, pos=pos, parent=parent, image=loader.loadTexture('phase_3.5/maps/slot_%s_%s.png' % (str(index), 'idle')), scale=0.15, frameSize=(-1, 1, -1, 1), frameColor=(0, 0, 0, 0), sortOrder=0) self.initialiseoptions(Slot) self.gui = baseGui self.index = index self.hoverObj = None self.gagImage = None self.gag = None self.mouseRlvrSfx = base.loadSfx('phase_3/audio/sfx/GUI_rollover.ogg') self.soundRecharged = base.loadSfx( 'phase_3.5/audio/sfx/tt_s_gui_sbk_cdrSuccess.ogg') self.infoText = OnscreenText(text='No\nAmmo', fg=(1, 0, 0, 1), parent=self, scale=0.5, shadow=(0, 0, 0, 1), align=TextNode.ACenter, pos=(0, 0.1)) self.infoText.setBin('unsorted', 100) self.infoText.hide() self.rechargeBar = DirectWaitBar(value=0, range=100, frameColor=(1, 1, 1, 1), barColor=(0.286, 0.901, 1, 1), relief=DGG.RAISED, borderWidth=(0.04, 0.04), pos=(-1.25, 0, 0), hpr=(0, 0, -90), parent=self, frameSize=(-0.85, 0.85, -0.12, 0.12)) self.rechargeBar.setBin('fixed', 60) self.rechargeBar.hide() self.gagLabel = OnscreenText(text='Birthday Cake', fg=(1, 1, 1, 1), parent=self, scale=0.25, shadow=(0, 0, 0, 1), align=TextNode.ACenter, pos=(0, -0.9), mayChange=1) self.gagLabel.setBin('fixed', 50) self.gagLabel.hide() battleGui = loader.loadModel('phase_3.5/models/gui/battle_gui.bam') arrow = battleGui.find('**/PckMn_BackBtn') arrowRlvr = battleGui.find('**/PckMn_BackBtn_Rlvr') arrowDn = battleGui.find('**/PckMn_BackBtn_Dn') self.leftArrow = DirectButton(geom=(arrow, arrowDn, arrowRlvr, arrow), parent=self, pos=(-0.925, -2.0, -1.02), relief=None, scale=2, command=self.updateLoadout, extraArgs=[0], geom3_color=(0.5, 0.5, 0.5, 1.0)) self.leftArrow.setBin('fixed', 60) self.rightArrow = DirectButton(geom=(arrow, arrowDn, arrowRlvr, arrow), parent=self, pos=(0.925, -2.0, -1.02), hpr=(180, 0, 0), relief=None, scale=2, command=self.updateLoadout, extraArgs=[1], geom3_color=(0.5, 0.5, 0.5, 1.0)) self.rightArrow.setBin('fixed', 60) self.hoverObj = DirectButton(relief=None, parent=self, frameSize=self['frameSize']) self.setBin('transparent', 30) self.setOutlineImage('idle') self.hoverObj.guiItem.setActive(True) self.hoverObj.bind(DGG.WITHIN, self.mouseEntered) self.hoverObj.bind(DGG.WITHOUT, self.mouseExited) self.hoverObj.bind(DGG.B1CLICK, self.gui.click_setWeapon, [self]) return def toggleArrows(self, left, right): if left: self.leftArrow['state'] = DGG.NORMAL else: self.leftArrow['state'] = DGG.DISABLED if right: self.rightArrow['state'] = DGG.NORMAL else: self.rightArrow['state'] = DGG.DISABLED def updateArrows(self): if not self.gag: self.toggleArrows(False, False) else: track = GagGlobals.TrackGagNamesByTrackName.get( GagGlobals.getTrackOfGag(self.gag.getID())) index = None useTrack = [] for name in track: gag = self.gui.backpack.getGagByID( GagGlobals.getIDByName(name)) if gag == self.gag or gag not in self.gui.backpack.getLoadout( ): useTrack.append(name) index = useTrack.index(self.gag.getName()) if index == 0: self.toggleArrows(False, True) else: if index > 0 and index < len(useTrack) - 1: gagId = GagGlobals.getIDByName(useTrack[index + 1]) if not self.gui.backpack.hasGag(gagId): self.toggleArrows(True, False) else: if index == len(useTrack) - 1: self.toggleArrows(True, False) else: self.toggleArrows(True, True) return def updateLoadout(self, forward): if self.gag and self.gag.getState() in [ GagState.RECHARGING, GagState.LOADED ]: track = GagGlobals.TrackGagNamesByTrackName.get( GagGlobals.getTrackOfGag(self.gag.getID())) index = None useTrack = [] for name in track: gag = self.gui.backpack.getGagByID( GagGlobals.getIDByName(name)) if gag == self.gag or gag not in self.gui.backpack.getLoadout( ): useTrack.append(name) index = useTrack.index(self.gag.getName()) if forward == 1: nextGagIndex = index + 1 else: nextGagIndex = index - 1 if nextGagIndex < 0 or nextGagIndex >= len(useTrack): return gagId = GagGlobals.getIDByName(useTrack[nextGagIndex]) loadout = self.gui.backpack.getLoadout() if self.gui.backpack.hasGag(gagId) and self.gag in loadout: self.hideInfoText() if self.gag not in loadout: return loadout[loadout.index( self.gag)] = self.gui.backpack.getGagByID(gagId) self.gui.backpack.setLoadout(loadout) return def showNoAmmo(self): self.infoText['text'] = 'No\nAmmo' self.infoText['scale'] = 0.5 self.infoText['fg'] = (1, 0, 0, 1) self.infoText['pos'] = (0, 0.1) self.infoText.show() if self.gag and self.gag.getState() == GagState.RECHARGING: self.rechargeBar.show() def showRecharging(self): self.infoText['text'] = 'Recharging...' self.infoText['scale'] = 0.315 self.infoText['fg'] = (0.286, 0.901, 1, 1) self.infoText['pos'] = (0, 0) self.infoText.show() self.rechargeBar.show() def __tickRecharge(self): if not self.gag: self.ignoreAll() else: elapsedTime = float(self.gag.getRechargeElapsedTime()) totalTime = float(self.gag.getRechargeTime()) barValue = int( float(elapsedTime / totalTime) * self.rechargeBar['range']) self.rechargeBar['value'] = barValue if barValue == 0: self.gui.setWeapon(self, playSound=False) self.setOutlineImage('no_ammo') self.showRecharging() else: if barValue >= 100: base.playSfx(self.soundRecharged) slotImage = 'idle' if base.localAvatar.getBackpack().getSupply( self.gag.getID()) <= 0: slotImage = 'no_ammo' else: if self.gui.getActiveSlot() == self: slotImage = 'selected' Sequence(Wait(0.5), Func(self.setOutlineImage, slotImage)).start() def hideInfoText(self): self.infoText.hide() self.rechargeBar.hide() def setSlotImage(self, gagImage): if self.gagImage: self.gagImage.destroy() self.gagImage = None self.gagImage = OnscreenImage(image=gagImage, parent=self) self.gagImage.setTransparency(TransparencyAttrib.MAlpha) return def setOutline(self): self.setTransparency(TransparencyAttrib.MAlpha) def setOutlineImage(self, image): phase = 'phase_3.5/maps/' if hasattr(self, '_optionInfo'): self['image'] = loader.loadTexture(phase + 'slot_%s_%s.png' % (str(self.index), image)) self.setOutline() if image != 'no_ammo': if self.gag and base.localAvatar.getBackpack().getSupply( self.gag.getID( )) == 0 or self.gag and self.gag.getState( ) == GagState.RECHARGING: image = 'no_ammo' if image == 'no_ammo': if self.gag and self.gag.getState() == GagState.RECHARGING: self.showRecharging() else: self.showNoAmmo() self.rechargeBar.hide() self.setBin('fixed', 40) if self.gagImage: self.gagImage.setBin('transparent', 30) else: self.hideInfoText() if self.gagImage: self.gagImage.setBin('fixed', 40) self.setBin('transparent', 30) def getOutline(self): return self.outline def mouseEntered(self, cmd): if self.gag: self.gagLabel.show() self.mouseRlvrSfx.play() def mouseExited(self, cmd): self.gagLabel.hide() def setGag(self, gag): if type(gag) == types.IntType: gag = self.gui.backpack.getGagByID(gag) self.ignoreAll() self.gag = gag if gag: self.show() self.setSlotImage(self.gag.getImage()) self.gagLabel['text'] = self.gag.getName() self.accept('%s-Recharge-Tick' % str(self.gag.getID()), self.__tickRecharge) else: self.hide() self.gagLabel['text'] = '' self.updateArrows() def getGag(self): return self.gag
ConfigVariableDouble('extractor-step-time').setValue(0.01) # loading screen backgroundNodePath = aspect2d.attachNewNode(backgroundNode, 0) backgroundNodePath.setPos(0.0, 0.0, 0.0) backgroundNodePath.setScale(render2d, VBase3(1)) backgroundNodePath.find('**/bg').setBin('fixed', 10) # change the logo backgroundNodePath.find('**/fg').stash() from direct.gui.DirectGui import OnscreenImage logo = OnscreenImage('phase_3/maps/toontown-logo-new.png') logo.reparentTo(backgroundNodePath) logo.setBin('fixed', 20) logo.setTransparency(TransparencyAttrib.MAlpha) base.graphicsEngine.renderFrame() # default DGG stuff DirectGuiGlobals.setDefaultRolloverSound(base.loadSfx('phase_3/audio/sfx/GUI_rollover.ogg')) DirectGuiGlobals.setDefaultClickSound(base.loadSfx('phase_3/audio/sfx/GUI_create_toon_fwd.ogg')) DirectGuiGlobals.setDefaultDialogGeom(loader.loadModel('phase_3/models/gui/dialog_box_gui')) # localizer import TTLocalizer from otp.otpbase import OTPGlobals OTPGlobals.setDefaultProductPrefix(TTLocalizer.ProductPrefix) wantSpecial = base.config.GetBool('wantSpecialTheme', 0)
class MyApp(ShowBase): def __init__(self): ShowBase.__init__(self) # relevant for DEBUG self.debug = True self.debugLabel = self.makeStatusLabel(0) if (self.debug): self.debugLabel.setText("Debug Mode ON") else: self.debugLabel.setText("Debug Mode OFF") self.statusLabel = self.makeStatusLabel(1) self.collisionLabel = self.makeStatusLabel(2) self.world = self.loader.loadModel("world.bam") self.world.reparentTo(self.render) # relevant for world boundaries self.worldsize = 1024 self.maxspeed = 100.0 self.startPos = Vec3(200, 200, 1) self.startHpr = Vec3(225, 0, 0) self.player = self.loader.loadModel("alliedflanker") self.player.setScale(.2, .2, .2) self.player.reparentTo(self.render) self.resetPlayer() self.startPosPartner = Vec3(200, 200, 1) self.startHprPartner = Vec3(225, 0, 0) self.partner = self.loader.loadModel("alliedflanker") self.partner.setScale(.2, .2, .2) self.partner.reparentTo(self.render) self.resetPartner() # A task to run every frame self.taskMgr.add(self.updateTask, "update") self.keyboardSetup() #performance (to be masked later by fog) and view: self.maxdistance = 400 self.camLens.setFar(self.maxdistance) self.camLens.setFov(60) self.createEnviroment() # relevant for collision and DEBUG self.setupCollisions() self.textCounter = 0 # explosion self.explosionModel = loader.loadModel('explosion') self.explosionModel.reparentTo(self.render) self.explosionModel.setScale(0.0) self.explosionModel.setLightOff() # only one explosion at a time: self.exploding = False self.radar # relevant for DEBUG def makeStatusLabel(self, i): return OnscreenText(style=2, fg=(.5,1,.5,1), pos=(-1.3,0.92-(.08*i)),\ align=TextNode.ALeft, scale = .08, mayChange = 1) # relevant for collision and DEBUG def setupCollisions(self): self.collTrav = CollisionTraverser() self.playerGroundSphere = CollisionSphere(0, 1.5, 56, 1) self.playerGroundCol = CollisionNode('playerSphere') self.playerGroundCol.addSolid(self.playerGroundSphere) # bitmask self.playerGroundCol.setFromCollideMask(BitMask32.bit(0)) self.playerGroundCol.setIntoCollideMask(BitMask32.allOff()) self.world.setCollideMask(BitMask32.bit(0)) # and done self.playerGroundColNp = self.player.attachNewNode( self.playerGroundCol) self.playerGroundHandler = CollisionHandlerQueue() self.collTrav.addCollider(self.playerGroundColNp, self.playerGroundHandler) # DEBUG if (self.debug == True): self.playerGroundColNp.show() self.collTrav.showCollisions(self.render) def keyboardSetup(self): self.keyMap = { "left": 0, "right": 0, "climb": 0, "fall": 0, "accelerate": 0, "decelerate": 0, "fire": 0 } self.accept("escape", sys.exit) self.accept("a", self.setKey, ["accelerate", 1]) self.accept("a-up", self.setKey, ["accelerate", 0]) self.accept("z", self.setKey, ["decelerate", 1]) self.accept("z-up", self.setKey, ["decelerate", 0]) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_down", self.setKey, ["climb", 1]) self.accept("arrow_down-up", self.setKey, ["climb", 0]) self.accept("arrow_up", self.setKey, ["fall", 1]) self.accept("arrow_up-up", self.setKey, ["fall", 0]) self.accept("space", self.setKey, ["fire", 1]) self.accept("space-up", self.setKey, ["fire", 0]) base.disableMouse() # or updateCamera will fail def createEnviroment(self): # Fog to hide performance tweak: colour = (0.5, 0.5, 0.5) expfog = Fog("scene-wide-fog") expfog.setColor(*colour) expfog.setExpDensity(0.002) self.render.setFog(expfog) base.setBackgroundColor(*colour) # Our sky skydome = self.loader.loadModel('blue-sky-sphere') skydome.setEffect(CompassEffect.make(self.render)) skydome.setScale(0.08) # bit less than "far" # NOT render - you`ll fly through the sky!: skydome.reparentTo(self.camera) # Our lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.6, .6, .6, 1)) render.setLight(render.attachNewNode(ambientLight)) directionalLight = DirectionalLight("directionalLight") directionalLight.setColor(Vec4(0.8, 0.8, 0.5, 1)) dlnp = self.render.attachNewNode(directionalLight) dlnp.setPos(0, 0, 260) dlnp.lookAt(self.player) self.render.setLight(dlnp) self.render2d = render2d # image scale of 1 fills screen, position defaults to central Scale = 1.0 / 2.5 # decimal point is VITAL self.radar = OnscreenImage(image='radar.png', scale=Scale, \ parent=self.render2d, pos=(-0.95,0,-0.95)) self.radar.setTransparency(TransparencyAttrib.MAlpha) # note the image itself and how it is centered hud = OnscreenImage(image='hud1.png', scale=1, \ parent=self.render2d, pos=(0,0,0)) hud.setTransparency(TransparencyAttrib.MAlpha) self.dots = list() self.playerobj = OnscreenImage(image='playerdot.png', \ scale=1.0/20.0,parent=self.radar) self.playerobj.setTransparency(TransparencyAttrib.MAlpha) def setKey(self, key, value): self.keyMap[key] = value def updateTask(self, task): self.updatePlayer() self.updateCamera() self.updateGUI(self.worldsize) #relevant for collision and DEBUG self.collTrav.traverse(self.render) for i in range(self.playerGroundHandler.getNumEntries()): entry = self.playerGroundHandler.getEntry(i) if (self.debug == True): self.collisionLabel.setText("HIT:" + str(globalClock.getFrameTime())) if (self.exploding == False): self.player.setZ(entry.getSurfacePoint(self.render).getZ() + 5) self.explosionSequence() return Task.cont def updatePlayer(self): if self.exploding == False: #Global Clock #by default, panda runs as fast as it can frame to frame scalefactor = (globalClock.getDt() * self.speed) climbfactor = scalefactor * 0.5 bankfactor = scalefactor speedfactor = scalefactor * 2.9 gravityfactor = ((self.maxspeed - self.speed) / 100.0) * 2.0 #Climb and Fall if (self.keyMap["climb"] != 0 and self.speed > 0.00): #faster you go, quicker you climb self.player.setZ(self.player.getZ() + climbfactor) self.player.setR(self.player.getR() + climbfactor) #quickest return: (:avoids uncoil/unwind) if (self.player.getR() >= 180): self.player.setR(-180) elif (self.keyMap["fall"] != 0 and self.speed > 0.00): self.player.setZ(self.player.getZ() - climbfactor) self.player.setR(self.player.getR() - climbfactor) #quickest return if (self.player.getR() <= -180): self.player.setR( 180 ) #autoreturn - add a bit regardless to make sure it happens elif (self.player.getR() > 0): self.player.setR(self.player.getR() - (climbfactor + 0.1)) if (self.player.getR() < 0): self.player.setR(0) #avoid jitter elif (self.player.getR() < 0): self.player.setR(self.player.getR() + (climbfactor + 0.1)) if (self.player.getR() > 0): self.player.setR(0) #Left and Right if (self.keyMap["left"] != 0 and self.speed > 0.0): self.player.setH(self.player.getH() + bankfactor) self.player.setP(self.player.getP() + bankfactor) #quickest return: if (self.player.getP() >= 180): self.player.setP(-180) elif (self.keyMap["right"] != 0 and self.speed > 0.0): self.player.setH(self.player.getH() - bankfactor) self.player.setP(self.player.getP() - bankfactor) if (self.player.getP() <= -180): self.player.setP(180) #autoreturn elif (self.player.getP() > 0): self.player.setP(self.player.getP() - (bankfactor + 0.1)) if (self.player.getP() < 0): self.player.setP(0) elif (self.player.getP() < 0): self.player.setP(self.player.getP() + (bankfactor + 0.1)) if (self.player.getP() > 0): self.player.setP(0) #throttle control if (self.keyMap["accelerate"] != 0): self.speed += 1 if (self.speed > self.maxspeed): self.speed = self.maxspeed elif (self.keyMap["decelerate"] != 0): self.speed -= 1 if (self.speed < 0.0): self.speed = 0.0 #move forwards - our X/Y is inverted, see the issue self.player.setX( self.player, -speedfactor ) #respect max camera distance else you cannot see the floor post loop the loop! self.applyBoundaries() self.player.setZ(self.player, -gravityfactor) def updateGUI(self, boundingBox): boundingBox = boundingBox * 2 offsetX = 0.0 offsetZ = 0.0 # would be fine for minimap self.playerobj.setX(self.player.getX() / boundingBox) self.playerobj.setZ(self.player.getY() / boundingBox) # player center if (self.playerobj.getX() > 0.5): offsetX = -(self.playerobj.getX() - 0.5) elif (self.playerobj.getX() < 0.5): offsetX = 0.5 - self.playerobj.getX() # else stays zero if (self.playerobj.getZ() > 0.5): offsetZ = -(self.playerobj.getZ() - 0.5) elif (self.playerobj.getZ() < 0.5): offsetZ = 0.5 - self.playerobj.getZ() self.playerobj.setX(self.playerobj.getX() + offsetX) self.playerobj.setZ(self.playerobj.getZ() + offsetZ) for dot in self.dots: dot.removeNode() # correct way to remove from scene graph del self.dots[:] self.playerobj.setR(-self.player.getH() - 90) newobj = OnscreenImage(image='reddot.png',scale=1.0/60.0, \ parent=self.radar) newobj.setTransparency(TransparencyAttrib.MAlpha) newobj.setX(self.partner.getX() / boundingBox) newobj.setZ(self.partner.getY() / boundingBox) newobj.setX(newobj.getX() + offsetX) newobj.setZ(newobj.getZ() + offsetZ) self.dots.append(newobj) # so can destroy, see call above def applyBoundaries(self): if (self.player.getZ() > self.maxdistance): self.player.setZ(self.maxdistance) # should never happen once we add collision, but in case: elif (self.player.getZ() < 0): self.player.setZ(0) # and now the X/Y world boundaries: boundary = False if (self.player.getX() < 0): self.player.setX(0) boundary = True elif (self.player.getX() > self.worldsize): self.player.setX(self.worldsize) boundary = True if (self.player.getY() < 0): self.player.setY(0) boundary = True elif (self.player.getY() > self.worldsize): self.player.setY(self.worldsize) boundary = True # lets not be doing this every frame... if boundary == True and self.textCounter > 30: self.statusLabel.setText("STATUS: MAP END; TURN AROUND") elif self.textCounter > 30: self.statusLabel.setText("STATUS: OK") if self.textCounter > 30: self.textCounter = 0 else: self.textCounter = self.textCounter + 1 def updateCamera(self): #see issue content for how we calculated these: percent = (self.speed / self.maxspeed) self.camera.setPos(self.player, 19.6226 + (10 * percent), 3.8807, 10.2779) self.camera.setHpr(self.player, 94.8996, -12.6549, 1.55508) def resetPlayer(self): self.player.show() self.player.setPos(self.world, self.startPos) self.player.setHpr(self.world, self.startHpr) self.speed = self.maxspeed / 2 def resetPartner(self): self.partner.show() self.partner.setPos(self.world, self.startPosPartner) self.partner.setHpr(self.world, self.startHprPartner) def explosionSequence(self): self.exploding = True self.explosionModel.setPosHpr( Vec3(self.player.getX(), self.player.getY(), self.player.getZ()), Vec3(self.player.getH(), 0, 0)) self.player.hide() taskMgr.add(self.expandExplosion, 'expandExplosion') def expandExplosion(self, Task): # expand the explosion rign each frame until a certain size if self.explosionModel.getScale() < VBase3(60.0, 60.0, 60.0): factor = globalClock.getDt() scale = self.explosionModel.getScale() scale = scale + VBase3(factor * 40, factor * 40, factor * 40) self.explosionModel.setScale(scale) return Task.cont else: self.explosionModel.setScale(0) self.exploding = False self.resetPlayer()
class DistributedPieTurretManager(DistributedObject): notify = directNotify.newCategory("DistributedPieTurretManager") def __init__(self, cr): DistributedObject.__init__(self, cr) self.myTurret = None self.guiFrame = None self.guiLabel = None self.guiBar = None self.guiBg = None self.turretGag = None return def announceGenerate(self): DistributedObject.announceGenerate(self) base.taskMgr.add(self.__pollMyBattle, "__pollMyBattle") def disable(self): base.taskMgr.remove("DPTM.pollTurret") base.taskMgr.remove("__pollMyBattle") if hasattr(self, "makeTurretBtn"): self.makeTurretBtn.destroy() del self.makeTurretBtn self.destroyGui() self.myTurret = None if base.localAvatar.getMyBattle(): base.localAvatar.getMyBattle().setTurretManager(None) DistributedObject.disable(self) return def __pollTurret(self, turretId, task): turret = self.cr.doId2do.get(turretId) if turret != None: self.myTurret = turret self.turretGag = None self.makeGui() return Task.done else: return Task.cont def setGag(self, upgradeId): self.turretGag = upgradeId def d_requestPlace(self, posHpr): self.sendUpdate("requestPlace", [posHpr]) def turretPlaced(self, turretId): turret = self.cr.doId2do.get(turretId) turret.b_setGag(self.turretGag) self.turretGag = None base.taskMgr.add(self.__pollTurret, "DPTM.pollTurret", extraArgs=[turretId], appendTask=True) return def yourTurretIsDead(self): base.taskMgr.remove("DPTM.pollTurret") self.destroyGui() self.myTurret = None if base.localAvatar.getPUInventory()[0] > 0: self.createTurretButton() return def makeGui(self): self.destroyGui() self.guiFrame = DirectFrame(parent=base.a2dBottomRight, pos=(-0.55, 0, 0.15)) self.guiBg = OnscreenImage(image="phase_4/maps/turret_gui_bg.png", scale=(0.15, 0, 0.075), parent=self.guiFrame) self.guiBg.setTransparency(True) self.guiLabel = DirectLabel( text="Turret", text_fg=(1, 0, 0, 1), relief=None, text_scale=0.05, text_font=loader.loadFont("phase_3/models/fonts/ImpressBT.ttf"), pos=(0, 0, 0.025), parent=self.guiFrame, ) self.guiBar = DirectWaitBar( range=self.myTurret.getMaxHealth(), value=self.myTurret.getHealth(), scale=0.125, parent=self.guiFrame, pos=(0, 0, -0.01), ) return def createTurretButton(self): self.makeTurretBtn = DirectButton( relief=None, geom=CIGlobals.getDefaultBtnGeom(), text="Turret", text_scale=0.055, command=self.handleMakeTurretBtn, pos=(-0.47, 0, 0.1), geom_scale=(0.5, 1.0, 1.0), text_pos=(0, -0.01), parent=base.a2dBottomRight, ) return def handleMakeTurretBtn(self): self.makeTurretBtn.destroy() del self.makeTurretBtn x, y, z = base.localAvatar.getPos() h, p, r = base.localAvatar.getHpr() self.d_requestPlace([x, y, z, h, p, r]) base.localAvatar.sendUpdate("usedPU", [0]) def __pollMyBattle(self, task): if base.localAvatar.getMyBattle(): base.localAvatar.getMyBattle().setTurretManager(self) if base.localAvatar.getPUInventory()[0] > 0: self.createTurretButton() return Task.done return Task.cont def destroyGui(self): if self.guiBar: self.guiBar.destroy() self.guiBar = None if self.guiLabel: self.guiLabel.destroy() self.guiLabel = None if self.guiBg: self.guiBg.destroy() self.guiBg = None if self.guiFrame: self.guiFrame.destroy() self.guiFrame = None return def updateTurretGui(self): if self.guiBar: self.guiBar.update(self.myTurret.getHealth())
class CameraShyFirstPerson(FirstPerson): notify = directNotify.newCategory("CameraShyFirstPerson") defaultColor = VBase4(1.0, 1.0, 1.0, 1.0) toonInFocusColor = VBase4(0.0, 0.7, 0.0, 1.0) toonOutOfFocusColor = VBase4(0.25, 1.0, 0.25, 1.0) redColor = VBase4(0.8, 0.0, 0.0, 1.0) batteryLevelTwoColor = VBase4(0.9, 0.36, 0.0, 1.0) batteryLevelThreeColor = VBase4(0.9, 0.9, 0.0, 1.0) batteryLevelFourColor = VBase4(1.0, 1.0, 0.0, 1.0) batteryLevelFiveColor = VBase4(0.0, 1.0, 0.0, 1.0) fullyChargedState = 5 def __init__(self, mg): self.mg = mg self.batteryFrame = None self.batteryBg = None self.batteryBar = None self.rechargeSound = None self.fullyChargedSound = None self.hasToonInFocus = False self.toonToTakePicOf = None self.cameraRechargeState = None self.cameraRechargingLabel = None self.cameraFlashSeq = None self.viewfinder = None self.camFSM = ClassicFSM('CameraFSM', [ State('off', self.enterOff, self.exitOff), State('ready', self.enterCameraReady, self.exitCameraReady), State('recharge', self.enterCameraRecharge, self.exitCameraRecharge) ], 'off', 'off') self.camFSM.enterInitialState() FirstPerson.__init__(self) def enterOff(self): pass def exitOff(self): pass def enterCameraReady(self): self.acceptOnce("mouse1", self.__mouse1Pressed) def stopCameraFlash(self): if self.cameraFlashSeq: self.cameraFlashSeq.finish() self.cameraFlashSeq = None def __mouse1Pressed(self): self.cameraFlashSeq = Sequence( Func(base.transitions.setFadeColor, 1, 1, 1), Func(base.transitions.fadeOut, 0.1), Wait(0.1), Func(base.transitions.fadeIn, 0.1), Wait(0.1), Func(base.transitions.setFadeColor, 0, 0, 0)) self.cameraFlashSeq.start() self.mg.sendUpdate('remoteAvatarTakePicture', [base.localAvatar.doId]) self.mg.myRemoteAvatar.takePicture() self.viewfinder['image'].setColorScale(self.defaultColor) picData = self.viewfinder.takePictureRaw() if self.hasToonInFocus and self.toonToTakePicOf: self.mg.sendUpdate('tookPictureOfToon', [self.toonToTakePicOf.doId]) self.camFSM.request('recharge') def exitCameraReady(self): self.ignore("mouse1") def enterCameraRecharge(self): self.batteryBar.update(0) taskMgr.add(self.__rechargeNextState, "rechargeCamera") def __rechargeNextState(self, task): if self.cameraRechargeState is None: self.cameraRechargeState = -1 self.cameraRechargeState += 1 if self.cameraRechargeState > 0: base.playSfx(self.rechargeSound) if self.cameraRechargeState <= 1: self.batteryBar.setColorScale(self.redColor) elif self.cameraRechargeState == 2: self.batteryBar.setColorScale(self.batteryLevelTwoColor) elif self.cameraRechargeState == 3: self.batteryBar.setColorScale(self.batteryLevelThreeColor) elif self.cameraRechargeState == 4: self.batteryBar.setColorScale(self.batteryLevelFourColor) else: self.batteryBar.setColorScale(self.batteryLevelFiveColor) self.batteryBar.update(self.cameraRechargeState) if self.cameraRechargeState == self.fullyChargedState: base.playSfx(self.fullyChargedSound) self.camFSM.request('ready') return task.done task.delayTime = 1.0 return task.again def exitCameraRecharge(self): taskMgr.remove("rechargeCamera") self.cameraRechargeState = None def __traverse(self, task): if not base.mouseWatcherNode.hasMouse(): return task.cont toonInFoc = False avatar = None for av in self.mg.remoteAvatars: if av.avId != base.localAvatar.doId: if self.viewfinder.isInView(av): self.notify.info("{0} is in our view finder".format( av.avId)) avatar = self.mg.cr.doId2do.get(av.avId) break if avatar: remoteAvatar = self.mg.getRemoteAvatar(avatar.doId) if remoteAvatar: toonInFoc = True self.notify.info("We've got an avatar in focus ({0})".format( avatar.doId)) self.__handleToonInFocus(avatar) if not toonInFoc: self.toonToTakePicOf = None self.hasToonInFocus = False self.notify.info("No avatar in focus") if self.viewfinder['image'].getColorScale( ) == self.toonInFocusColor: self.viewfinder['image'].setColorScale( self.toonOutOfFocusColor) return task.cont def __handleToonInFocus(self, toon): if not self.hasToonInFocus or self.toonToTakePicOf is not None or self.toonToTakePicOf.doId != toon.doId: self.toonToTakePicOf = toon self.hasToonInFocus = True self.viewfinder['image'].setColorScale(self.toonInFocusColor) def start(self): self.fullyChargedSound = base.loadSfx('phase_4/audio/sfx/ring_get.ogg') self.rechargeSound = base.loadSfx( 'phase_4/audio/sfx/MG_sfx_travel_game_blue_arrow.ogg') self.batteryFrame = DirectFrame(parent=base.a2dBottomRight, pos=(-0.2, 0, 0.1), scale=(0.8, 0, 1)) self.batteryBg = OnscreenImage( image='phase_4/maps/battery_charge_frame.png', parent=self.batteryFrame) self.batteryBg.setTransparency(1) self.batteryBg.setX(0.03) self.batteryBg.setScale(0.17, 0, 0.05) self.batteryBg.setColorScale(0, 0, 0, 1) self.batteryBar = DirectWaitBar(value=0, range=5, barColor=(1, 1, 1, 1), relief=None, scale=(0.12, 0.0, 0.3), parent=self.batteryFrame) self.viewfinder = Viewfinder(1.0) base.localAvatar.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed, 0.0, CIGlobals.ToonReverseSpeed, CIGlobals.ToonRotateSpeed) FirstPerson.start(self) def reallyStart(self): taskMgr.add(self.__traverse, "CSFP.__traverse") self.camFSM.request('recharge') #taskMgr.add(self.movementTask, "movementTask") base.localAvatar.startTrackAnimToSpeed() FirstPerson.reallyStart(self) def end(self): self.camFSM.request('off') taskMgr.remove("movementTask") taskMgr.remove("CSFP.__traverse") FirstPerson.end(self) def reallyEnd(self): self.batteryBar.destroy() self.batteryBar = None self.batteryBg.destroy() self.batteryBg = None self.batteryFrame.destroy() self.batteryFrame = None self.hasToonInFocus = None self.toonToTakePicOf = None self.fullyChargedSound = None self.rechargeSound = None self.viewfinder.cleanup() self.viewfinder = None self.stopCameraFlash() FirstPerson.reallyEnd(self) base.localAvatar.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed, CIGlobals.ToonJumpForce, CIGlobals.ToonReverseSpeed, CIGlobals.ToonRotateSpeed) def cleanup(self): self.camFSM.requestFinalState() self.camFSM = None FirstPerson.cleanup(self)
class CameraShyFirstPerson(FirstPerson): toonInFocusColor = VBase4(0.25, 1.0, 0.25, 1.0) toonOutOfFocusColor = VBase4(1.0, 1.0, 1.0, 1.0) fullyChargedState = 5 def __init__(self, mg): self.mg = mg self.cameraFocus = None self.batteryFrame = None self.batteryBg = None self.batteryBar = None self.rechargeSound = None self.fullyChargedSound = None self.hasToonInFocus = False self.toonToTakePicOf = None self.cameraRechargeState = None self.cameraRechargingLabel = None self.cameraFlashSeq = None self.camFSM = ClassicFSM('CameraFSM', [ State('off', self.enterOff, self.exitOff), State('ready', self.enterCameraReady, self.exitCameraReady), State('recharge', self.enterCameraRecharge, self.exitCameraRecharge) ], 'off', 'off') self.camFSM.enterInitialState() FirstPerson.__init__(self) return def enterOff(self): pass def exitOff(self): pass def enterCameraReady(self): self.acceptOnce('mouse1', self.__mouse1Pressed) def stopCameraFlash(self): if self.cameraFlashSeq: self.cameraFlashSeq.finish() self.cameraFlashSeq = None return def __mouse1Pressed(self): self.cameraFlashSeq = Sequence( Func(base.transitions.setFadeColor, 1, 1, 1), Func(base.transitions.fadeOut, 0.1), Wait(0.1), Func(base.transitions.fadeIn, 0.1), Wait(0.1), Func(base.transitions.setFadeColor, 0, 0, 0)) self.cameraFlashSeq.start() self.mg.sendUpdate('remoteAvatarTakePicture', [base.localAvatar.doId]) self.mg.myRemoteAvatar.takePicture() if self.hasToonInFocus and self.toonToTakePicOf: self.mg.sendUpdate('tookPictureOfToon', [self.toonToTakePicOf.doId]) self.camFSM.request('recharge') def exitCameraReady(self): self.ignore('mouse1') def enterCameraRecharge(self): self.batteryBar.update(0) taskMgr.add(self.__rechargeNextState, 'rechargeCamera') def __rechargeNextState(self, task): if self.cameraRechargeState == None: self.cameraRechargeState = -1 self.cameraRechargeState += 1 if self.cameraRechargeState > 0: base.playSfx(self.rechargeSound) self.batteryBar.update(self.cameraRechargeState) if self.cameraRechargeState == self.fullyChargedState: base.playSfx(self.fullyChargedSound) self.camFSM.request('ready') return task.done task.delayTime = 1.0 return task.again def exitCameraRecharge(self): taskMgr.remove('rechargeCamera') self.cameraRechargeState = None return def __traverse(self, task): if not base.mouseWatcherNode.hasMouse(): return task.cont mpos = base.mouseWatcherNode.getMouse() self.focusRay.setFromLens(base.camNode, mpos.getX(), mpos.getY()) self.focusTrav.traverse(render) if self.focusHandler.getNumEntries() > 0: self.focusHandler.sortEntries() firstObj = self.focusHandler.getEntry(0).getIntoNodePath() avId = firstObj.getParent().getPythonTag('player') avatar = self.mg.cr.doId2do.get(avId) toonInFoc = False if avatar: remoteAvatar = self.mg.getRemoteAvatar(avatar.doId) if remoteAvatar: toonInFoc = True self.__handleToonInFocus(avatar) if not toonInFoc: self.toonToTakePicOf = None self.hasToonInFocus = False if self.cameraFocus.getColorScale() == self.toonInFocusColor: self.cameraFocus.setColorScale(self.toonOutOfFocusColor) return task.cont def __handleToonInFocus(self, toon): if not self.hasToonInFocus or self.toonToTakePicOf is not None or self.toonToTakePicOf.doId != toon.doId: self.toonToTakePicOf = toon self.hasToonInFocus = True self.cameraFocus.setColorScale(self.toonInFocusColor) return def start(self): self.fullyChargedSound = base.loadSfx( 'phase_4/audio/sfx/MG_pairing_match.ogg') self.rechargeSound = base.loadSfx( 'phase_4/audio/sfx/MG_sfx_travel_game_blue_arrow.ogg') self.batteryFrame = DirectFrame(parent=base.a2dBottomRight, pos=(-0.2, 0, 0.1), scale=(0.8, 0, 1)) self.batteryBg = OnscreenImage( image='phase_4/maps/battery_charge_frame.png', parent=self.batteryFrame) self.batteryBg.setTransparency(1) self.batteryBg.setX(0.03) self.batteryBg.setScale(0.17, 0, 0.05) self.batteryBar = DirectWaitBar(value=0, range=5, barColor=(1, 1, 1, 1), relief=None, scale=(0.12, 0.0, 0.3), parent=self.batteryFrame) self.cameraFocus = loader.loadModel( 'phase_4/models/minigames/photo_game_viewfinder.bam') self.cameraFocus.reparentTo(base.aspect2d) self.focusTrav = CollisionTraverser('CSFP.focusTrav') ray = CollisionRay() rayNode = CollisionNode('CSFP.rayNode') rayNode.addSolid(ray) rayNode.setCollideMask(BitMask32(0)) rayNode.setFromCollideMask(CIGlobals.WallBitmask) self.focusRay = ray self.focusRayNode = base.camera.attachNewNode(rayNode) self.focusHandler = CollisionHandlerQueue() self.focusTrav.addCollider(self.focusRayNode, self.focusHandler) base.localAvatar.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed, 0.0, CIGlobals.ToonReverseSpeed, CIGlobals.ToonRotateSpeed) FirstPerson.start(self) return def reallyStart(self): taskMgr.add(self.__traverse, 'CSFP.__traverse') self.camFSM.request('recharge') base.localAvatar.startTrackAnimToSpeed() FirstPerson.reallyStart(self) def end(self): self.camFSM.request('off') taskMgr.remove('movementTask') taskMgr.remove('CSFP.__traverse') FirstPerson.end(self) def reallyEnd(self): self.batteryBar.destroy() self.batteryBar = None self.batteryBg.destroy() self.batteryBg = None self.batteryFrame.destroy() self.batteryFrame = None self.cameraFocus.removeNode() self.cameraFocus = None self.focusHandler = None self.focusRay = None self.focusRayNode.removeNode() self.focusRayNode = None self.focusTrav = None self.hasToonInFocus = None self.toonToTakePicOf = None self.fullyChargedSound = None self.rechargeSound = None self.stopCameraFlash() FirstPerson.reallyEnd(self) base.localAvatar.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed, CIGlobals.ToonJumpForce, CIGlobals.ToonReverseSpeed, CIGlobals.ToonRotateSpeed) return def cleanup(self): self.camFSM.requestFinalState() self.camFSM = None FirstPerson.cleanup(self) return
class ClickToStart(DirectObject): notify = directNotify.newCategory('ClickToStart') def __init__(self, version='n/a'): DirectObject.__init__(self) self.backgroundNodePath = render2d.attachNewNode('background', 0) self.backgroundModel = loader.loadModel( 'phase_3/models/gui/loading-background.bam') self.backgroundModel.reparentTo(self.backgroundNodePath) self.backgroundNodePath.find('**/fg').removeNode() self.backgroundNodePath.setScale(1, 1, 1) self.logo = OnscreenImage( parent=base.a2dTopCenter, image='phase_3/maps/toontown-logo.png', scale=(1.0, 1, 0.5), pos=(0, 0, -0.85)) self.logo.setTransparency(TransparencyAttrib.MAlpha) self.label = OnscreenText( TTLocalizer.ClickToStartLabel, parent=base.a2dBottomCenter, font=ToontownGlobals.getMinnieFont(), fg=Vec4(1, 1, 1, 1), scale=0.1, align=TextNode.ACenter) self.label.setZ(0.35) self.versionLabel = OnscreenText( '\x01white_shadow\x01%s\x02' % version, parent=base.a2dBottomRight, font=ToontownGlobals.getMinnieFont(), fg=Vec4(0, 0, 0, 1), scale=0.06, align=TextNode.ARight) self.versionLabel.setPos(-0.025, 0.025) self.setColorScale(Vec4(0, 0, 0, 0)) self.fadeTrack = None self.logoPosTrack = None self.logoScaleTrack = None self.labelPosTrack = None self.labelColorScaleTrack = None def delete(self): if self.labelColorScaleTrack is not None: self.labelColorScaleTrack.finish() self.labelColorScaleTrack = None if self.labelPosTrack is not None: self.labelPosTrack.finish() self.labelPosTrack = None if self.logoScaleTrack is not None: self.logoScaleTrack.finish() self.logoScaleTrack = None if self.logoPosTrack is not None: self.logoPosTrack.finish() self.logoPosTrack = None if self.fadeTrack is not None: self.fadeTrack.finish() self.fadeTrack = None if self.versionLabel is not None: self.versionLabel.destroy() self.versionLabel = None if self.label is not None: self.label.destroy() self.label = None if self.logo is not None: self.logo.destroy() self.logo = None if self.backgroundNodePath is not None: self.backgroundNodePath.removeNode() self.backgroundNodePath = None if self.backgroundModel is not None: self.backgroundModel.removeNode() self.backgroundModel = None def start(self): base.transitions.fadeOut(t=0) self.setColorScale(Vec4(1, 1, 1, 1)) if self.fadeTrack is not None: self.fadeTrack.finish() self.fadeTrack = None self.fadeTrack = base.transitions.getFadeInIval(t=2) self.fadeTrack.start() if self.logoScaleTrack is not None: self.logoScaleTrack.finish() self.logoScaleTrack = None self.logoScaleTrack = Sequence( LerpScaleInterval(self.logo, 2, Vec3(1.1, 1, 0.55), Vec3(1, 1, 0.5), blendType='easeInOut'), LerpScaleInterval(self.logo, 2, Vec3(1, 1, 0.5), Vec3(1.1, 1, 0.55), blendType='easeInOut') ) if self.logoPosTrack is not None: self.logoPosTrack.finish() self.logoPosTrack = None self.logoPosTrack = Sequence( LerpPosInterval(self.logo, 2, Point3(0, 0, -0.85), Point3(0, 0, -0.7), blendType='easeOut'), Func(self.logoScaleTrack.loop) ) self.logoPosTrack.start() if self.labelColorScaleTrack is not None: self.labelColorScaleTrack.finish() self.labelColorScaleTrack = None self.labelColorScaleTrack = Sequence( LerpColorScaleInterval(self.label, 1, Vec4(1, 1, 1, 0.6), Vec4(1, 1, 1, 1)), LerpColorScaleInterval(self.label, 1, Vec4(1, 1, 1, 1), Vec4(1, 1, 1, 0.6)) ) if self.labelPosTrack is not None: self.labelPosTrack.finish() self.labelPosTrack = None self.labelPosTrack = Sequence( LerpPosInterval(self.label, 2, Point3(0, 0, 0.35), Point3(0, 0, 0.15), blendType='easeOut'), Func(self.labelColorScaleTrack.loop) ) self.labelPosTrack.start() self.acceptOnce('mouse1', self.begin) def stop(self): self.ignore('mouse1') if self.labelPosTrack is not None: self.labelPosTrack.finish() self.labelPosTrack = None if self.labelColorScaleTrack is not None: self.labelColorScaleTrack.finish() self.labelColorScaleTrack = None if self.logoPosTrack is not None: self.logoPosTrack.finish() self.logoPosTrack = None if self.logoScaleTrack is not None: self.logoScaleTrack.finish() self.logoScaleTrack = None if self.fadeTrack is not None: self.fadeTrack.finish() self.fadeTrack = None self.setColorScale(Vec4(0, 0, 0, 0)) def begin(self): base.cr.introDone = True if self.fadeTrack is not None: self.fadeTrack.finish() self.fadeTrack = None self.fadeTrack = base.transitions.getFadeOutIval(t=2) Sequence( Func(self.fadeTrack.start), Wait(2), Func(self.delete), Func(base.cr.introduction.delete), Func(base.cr.loginFSM.request, 'chooseAvatar', [base.cr.avList]), Func(base.transitions.fadeIn, 2) ).start() def setColorScale(self, *args, **kwargs): self.backgroundNodePath.setColorScale(*args, **kwargs) self.logo.setColorScale(*args, **kwargs) self.label.setColorScale(*args, **kwargs) self.versionLabel.setColorScale(*args, **kwargs)
class CIProgressScreen: def __init__(self): self.bgm = loader.loadModel('phase_3/models/gui/progress-background.bam') self.bgm.find('**/logo').stash() self.bg = self.bgm.find('**/bg') self.logo = loader.loadTexture('phase_3/maps/CogInvasion_Logo.png') self.logoImg = OnscreenImage(image=self.logo, scale=(0.5, 0, 0.3), pos=(0, 0, 0), parent=hidden) self.logoImg.setTransparency(True) self.bg_img = OnscreenImage(image=self.bg, parent=hidden) self.bg_img.setSx(1.35) self.bg_img.hide() self.progress_bar = DirectWaitBar(value=0, pos=(0, 0, -0.85), parent=hidden, text_pos=(0, 0, 0.2)) self.progress_bar.setSx(1.064) self.progress_bar.setSz(0.38) self.loading_lbl = DirectLabel(text='', relief=None, scale=0.08, pos=(-1.0725, 0, -0.79), text_align=TextNode.ALeft, sortOrder=100, text_fg=(0.343, 0.343, 0.343, 1.0), text_font=CIGlobals.getMinnieFont(), parent=hidden, text_shadow=(0, 0, 0, 1)) return def begin(self, hood, range, wantGui): render.hide() self.renderFrames() base.setBackgroundColor(0, 0, 0) if hood == 'localAvatarEnterGame': self.loading_lbl['text'] = 'Entering...' elif hood == 'init': self.loading_lbl['text'] = 'Loading...' else: self.loading_lbl['text'] = 'Heading to %s...' % hood self.progress_bar['barColor'] = (0.343, 0.343, 0.343, 1.0) self.progress_bar['range'] = range self.bgm.reparentTo(aspect2d) self.bg.reparentTo(render2d) self.bg_img.reparentTo(hidden) self.loading_lbl.reparentTo(aspect2d) self.logoImg.reparentTo(aspect2d) self.progress_bar.reparentTo(aspect2d) self.__count = 0 self.__expectedCount = range self.progress_bar.update(self.__count) def renderFramesTask(self, task): self.renderFrames() return task.cont def end(self): base.setBackgroundColor(CIGlobals.DefaultBackgroundColor) taskMgr.remove('renderFrames') render.show() self.progress_bar.finish() self.bg_img.reparentTo(hidden) self.logoImg.reparentTo(hidden) self.bg.reparentTo(hidden) self.bgm.reparentTo(hidden) self.loading_lbl.reparentTo(hidden) self.progress_bar.reparentTo(hidden) self.renderFrames() def destroy(self): self.bg.removeNode() del self.bg self.bgm.removeNode() del self.bgm self.bg_img.destroy() self.loading_lbl.destroy() self.progress_bar.destroy() self.bgm.destroy() del self.bg_img del self.loading_lbl del self.progress_bar del self.bgm def renderFrames(self): base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() def tick(self): self.__count += 1 self.progress_bar.update(self.__count)
class ShopWindow(DirectFrame): def __init__(self, shop, image, wantTurretCount): DirectFrame.__init__(self, sortOrder=1) self.shop = shop self.wantTurretCount = wantTurretCount self.bgImage = image self.title = None self.okBtn = None self.clBtn = None self.infoLbl = None self.turretLabel = None self.turretImg = None self.isSetup = False self.turretCount = 0 # New variables for optimized shop. self.firstItemIndex = -1 self.btnPositions = [(-0.45, 0, 0), (-0.15, 0, 0), (0.15, 0, 0), (0.45, 0, 0)] self.page = Page(self.shop, self) self.itemButtons = [] self.itemButtons.append(ItemButton(self.page, self.btnPositions[0])) self.itemButtons.append(ItemButton(self.page, self.btnPositions[1])) self.itemButtons.append(ItemButton(self.page, self.btnPositions[2])) self.itemButtons.append(ItemButton(self.page, self.btnPositions[3])) self.newItems = None def setup(self, title='CHOOSE WHAT YOU WANT TO BUY'): font = CIGlobals.getMickeyFont() txtFg = (0, 0, 0, 1) txtScale = 0.05 txtPos = (0, -0.1) buttons = loader.loadModel('phase_3.5/models/gui/QT_buttons.bam') self.window = OnscreenImage(image=self.bgImage, scale=(0.9, 1, 0.7), parent=self) self.title = DirectLabel(text=title, relief=None, pos=(0, 0, 0.5), text_wordwrap=10, text_font=font, text_fg=(1, 1, 0, 1), scale=0.1, parent=self) # Let's update the turret count. self.updateTurretCount() self.infoLbl = DirectLabel(text='Welcome!', relief=None, text_scale=0.075, text_fg=txtFg, text_shadow=(0, 0, 0, 0), pos=(0, 0, 0.215)) self.okBtn = DirectButton(geom=CIGlobals.getOkayBtnGeom(), relief=None, text='OK', text_fg=txtFg, text_scale=txtScale, text_pos=txtPos, pos=(-0.1, 0, -0.5), parent=self) self.clBtn = DirectButton(geom=CIGlobals.getCancelBtnGeom(), relief=None, text='Cancel', text_fg=txtFg, text_scale=txtScale, text_pos=txtPos, pos=(0.1, 0, -0.5), parent=self) buttonGeom = (buttons.find('**/QT_back'), buttons.find('**/QT_back'), buttons.find('**/QT_back'), buttons.find('**/QT_back')) self.backBtn = DirectButton(geom=buttonGeom, relief=None, scale=0.05, pos=(-0.3, 0, -0.25), parent=self, command=self.changePage, extraArgs=[0]) self.nextBtn = DirectButton(geom=buttonGeom, relief=None, scale=0.05, pos=(0.3, 0, -0.25), hpr=(0, 0, 180), command=self.changePage, extraArgs=[1], parent=self) self.hideInfo() def setTurrets(self, amount): if self.shop.upgradesPurchased: amount += 1 self.turretCount = amount self.updatePage() def updateTurretCount(self): if self.turretLabel: self.turretLabel.destroy() if self.wantTurretCount: maxTurrets = CogBattleGlobals.MAX_TURRETS if not self.turretImg: self.turretImg = OnscreenImage( image="phase_3.5/maps/cannon-icon.png", scale=(0.05, 1, 0.05), pos=(-0.22, 0, 0.275)) self.turretImg.setTransparency(TransparencyAttrib.MAlpha) self.turretLabel = DirectLabel( text='Turrets: %s/%s' % (str(self.turretCount), str(maxTurrets)), relief=None, text_scale=0.07, text_fg=(0, 0, 0, 1), text_shadow=(0, 0, 0, 0), pos=(0, 0, 0.265)) def changePage(self, direction): var = (self.firstItemIndex - 4) if direction == 1: var = (self.firstItemIndex + 4) self.setBackBtn(True) self.setNextBtn(True) if (var - 4) < 0: self.setBackBtn(False) elif (var + 4) >= len(self.newItems): self.setNextBtn(False) self.firstItemIndex = var self.setupItems(begin=self.firstItemIndex) def initializeShop(self, items): newItems = dict(items) loadout = base.localAvatar.backpack.loadout # Let's show the loadout gags first in a full shop. if self.shop.wantFullShop: crcGags = OrderedDict(newItems) for item, values in newItems.items(): if values and values.get('type') == ItemType.GAG: gagId = base.cr.attackMgr.getAttackIDByName(item) hasGag = base.localAvatar.getBackpack().hasGag(gagId) if gagId not in loadout or not hasGag: del crcGags[item] if not hasGag: del newItems[item] else: del newItems[item] # Let's add back the other gags. crcGags.update(newItems) newItems = crcGags else: for item, values in newItems.items(): if values and values.get('type') == ItemType.GAG: gagId = base.localAvatar.getBackpack().hasGag(gagId) if gagId not in loadout or not base.localAvatar.getBackpack( ).hasGag(gagId): del newItems[item] self.newItems = newItems self.firstItemIndex = 0 self.setupItems() if len(newItems.keys()) <= 4: self.backBtn.hide() self.nextBtn.hide() self.setBackBtn(False) self.isSetup = True def setupItems(self, begin=0): for button in self.itemButtons: button.hide() button.label.hide() for i in xrange(4): item = self.newItems.keys()[begin + i] if (begin + i) < len( self.newItems.keys()) else None values = self.newItems.get(item) if item else None if item: button = self.itemButtons[i] button.setItem(item, values) button.update() def updatePage(self): battle = base.localAvatar.getBattleZone() if battle and self.wantTurretCount: self.shop.distShop.sendUpdate('requestTurretCount', []) self.updateTurretCount() for button in self.itemButtons: button.update() def setBackBtn(self, enabled): if self.backBtn: if enabled == False: self.backBtn.setColorScale(GRAYED_OUT_COLOR) self.backBtn['state'] = DGG.DISABLED else: self.backBtn.setColorScale(NORMAL_COLOR) self.backBtn['state'] = DGG.NORMAL def setNextBtn(self, enabled): if self.nextBtn: if enabled == False: self.nextBtn.setColorScale(GRAYED_OUT_COLOR) self.nextBtn['state'] = DGG.DISABLED else: self.nextBtn.setColorScale(NORMAL_COLOR) self.nextBtn['state'] = DGG.NORMAL def setOKCommand(self, command): if self.okBtn: self.okBtn['command'] = command def setCancelCommand(self, command): if self.clBtn: self.clBtn['command'] = command def showInfo(self, text, negative=0, duration=-1): self.infoLbl.show() if negative: self.infoLbl['text_fg'] = (0.9, 0, 0, 1) self.infoLbl['text_shadow'] = (0, 0, 0, 1) else: self.infoLbl['text_fg'] = (0, 0, 0, 1) self.infoLbl['text_shadow'] = (0, 0, 0, 0) self.infoLbl['text'] = text if duration > -1: Sequence(Wait(duration), Func(self.hideInfo)).start() def hideInfo(self): if self.infoLbl: self.infoLbl.hide() def delete(self): elements = [ self.title, self.okBtn, self.clBtn, self.infoLbl, self.backBtn, self.nextBtn, self.turretLabel, self.turretImg, self.page ] for element in elements: if element: element.destroy() del elements del self.page for button in self.itemButtons: button.destroy() self.itemButtons = None del self.itemButtons self.title = None self.okBtn = None self.clBtn = None self.infoLbl = None self.backBtn = None self.nextBtn = None self.bgImage = None self.turretLabel = None self.turretCount = None if self.window: self.window.destroy() self.window = None self.destroy()
class ShopWindow(DirectFrame): def __init__(self, shop, image, wantTurretCount): DirectFrame.__init__(self) self.shop = shop self.wantTurretCount = wantTurretCount self.bgImage = image self.title = None self.okBtn = None self.clBtn = None self.infoLbl = None self.turretLabel = None self.turretImg = None self.nPage = -1 self.nPages = 0 self.nextPage = 0 self.prevPage = -1 self.pages = [] self.isSetup = False self.turretCount = 0 def setup(self, title='CHOOSE WHAT YOU WANT TO BUY'): font = CIGlobals.getMickeyFont() txtFg = (0, 0, 0, 1) txtScale = 0.05 txtPos = (0, -0.1) buttons = loader.loadModel('phase_3.5/models/gui/QT_buttons.bam') self.window = OnscreenImage(image=self.bgImage, scale=(0.9, 1, 0.7), parent=self) self.title = DirectLabel(text=title, relief=None, pos=(0, 0, 0.5), text_wordwrap=10, text_font=font, text_fg=(1, 1, 0, 1), scale=0.1, parent=self) # Let's update the turret count. self.updateTurretCount() self.infoLbl = DirectLabel(text='Welcome!', relief=None, text_scale=0.075, text_fg=txtFg, text_shadow=(0, 0, 0, 0), pos=(0, 0, 0.215)) self.okBtn = DirectButton(geom=CIGlobals.getOkayBtnGeom(), relief=None, text='OK', text_fg=txtFg, text_scale=txtScale, text_pos=txtPos, pos=(-0.1, 0, -0.5), parent=self) self.clBtn = DirectButton(geom=CIGlobals.getCancelBtnGeom(), relief=None, text='Cancel', text_fg=txtFg, text_scale=txtScale, text_pos=txtPos, pos=(0.1, 0, -0.5), parent=self) buttonGeom = (buttons.find('**/QT_back'), buttons.find('**/QT_back'), buttons.find('**/QT_back'), buttons.find('**/QT_back')) self.backBtn = DirectButton(geom=buttonGeom, relief=None, scale=0.05, pos=(-0.3, 0, -0.25), parent=self, command=self.changePage, extraArgs=[0]) self.nextBtn = DirectButton(geom=buttonGeom, relief=None, scale=0.05, pos=(0.3, 0, -0.25), hpr=(0, 0, 180), command=self.changePage, extraArgs=[1], parent=self) self.hideInfo() def setTurrets(self, amount): if self.shop.upgradesPurchased: amount += 1 self.turretCount = amount self.updatePages() def updateTurretCount(self): if self.turretLabel: self.turretLabel.destroy() if self.wantTurretCount: maxTurrets = CogBattleGlobals.MAX_TURRETS if not self.turretImg: self.turretImg = OnscreenImage( image="phase_3.5/maps/cannon-icon.png", scale=(0.05, 1, 0.05), pos=(-0.22, 0, 0.275)) self.turretImg.setTransparency(TransparencyAttrib.MAlpha) self.turretLabel = DirectLabel( text='Turrets: %s/%s' % (str(self.turretCount), str(maxTurrets)), relief=None, text_scale=0.07, text_fg=(0, 0, 0, 1), text_shadow=(0, 0, 0, 0), pos=(0, 0, 0.265)) def changePage(self, direction): var = self.prevPage if direction == 1: var = self.nextPage self.setPage(var) def __makeGagEntry(self, pos, item, values, page): itemImage = values.get('image') button = DirectButton(geom=(itemImage), scale=1.3, pos=pos, relief=None, parent=page, command=self.shop.purchaseItem, extraArgs=[item, page]) supply = base.localAvatar.getBackpack().getSupply(item().getName()) maxSupply = base.localAvatar.getBackpack().getMaxSupply( item().getName()) buttonLabel = DirectLabel( text='%s/%s\n%s JBS' % (str(supply), str(maxSupply), str(values.get('price'))), relief=None, parent=button, text_scale=0.05, pos=(0, 0, -0.11)) self.addEntryToPage(page, item, values, button, buttonLabel) def __makeUpgradeEntry(self, pos, item, values, page): itemImage = values.get('image') button = DirectButton(image=(itemImage), scale=0.15, pos=pos, relief=None, parent=page, command=self.shop.purchaseItem, extraArgs=[item, page]) button.setTransparency(TransparencyAttrib.MAlpha) upgradeID = values.get('upgradeID') avID = base.localAvatar.getPUInventory()[1] supply = 0 battle = base.localAvatar.getMyBattle() if battle and battle.getTurretManager(): turret = battle.getTurretManager().getTurret() if turret and turret.getGagID() == upgradeID: supply = 1 if avID == upgradeID: dataSupply = base.localAvatar.getPUInventory()[0] if dataSupply > 0: supply = dataSupply maxSupply = values.get('maxUpgrades') buttonLabel = DirectLabel( text='%s\n%s/%s\n%s JBS' % (item, str(supply), str(maxSupply), str(values.get('price'))), relief=None, parent=button, text_scale=0.3, pos=(0, 0, -1.2)) self.addEntryToPage(page, item, values, button, buttonLabel) def __makeHealEntry(self, pos, item, values, page): label = '%s' % (item) itemImage = values.get('image') if 'showTitle' in values: label = '%s\n%s JBS' % (item, values.get('price')) button = DirectButton(image=(itemImage), scale=0.105, pos=pos, relief=None, parent=page, command=self.shop.purchaseItem, extraArgs=[item, page]) button.setTransparency(TransparencyAttrib.MAlpha) buttonLabel = DirectLabel(text=label, relief=None, parent=button, text_scale=0.55, pos=(0, 0, -1.6)) self.addEntryToPage(page, item, values, button, buttonLabel) def addEntryToPage(self, page, item, values, button, buttonLabel): page.addItemEntry(item, [button, buttonLabel]) page.addItem({item: values}) def makePages(self, items): newItems = dict(items) loadout = base.localAvatar.getBackpack().getLoadoutInIds() # Let's show the loadout gags first in a full shop. if self.shop.wantFullShop: crcGags = OrderedDict(newItems) for item, values in newItems.items(): if values.get('type') == ItemType.GAG: gag = item() hasGag = base.localAvatar.getBackpack().hasGag(gag.getID()) if gag.getID() not in loadout or not hasGag: del crcGags[item] if not hasGag: del newItems[item] else: del newItems[item] # Let's add back the other gags. crcGags.update(newItems) newItems = crcGags print len(newItems) else: for item, values in newItems.items(): if values.get('type') == ItemType.GAG: gag = item() if gag.getID( ) not in loadout or not base.localAvatar.getBackpack( ).hasGag(gag.getID()): del newItems[item] self.nPages = int(math.ceil((float(len(newItems)) / float(4)))) if self.nPages % 4 != 0 and len(newItems) > 4: self.nPages += 1 elif self.nPages == 0: self.nPages = 1 itemPos = [(-0.45, 0, 0), (-0.15, 0, 0), (0.15, 0, 0), (0.45, 0, 0)] pageIndex = 0 itemIndex = 0 index = 0 for _ in range(self.nPages): page = Page(self.shop, self) self.pages.append(page) for item, values in newItems.iteritems(): pos = itemPos[itemIndex] page = self.pages[pageIndex] itemType = values.get('type') if itemType == ItemType.GAG: self.__makeGagEntry(pos, item, values, page) elif itemType == ItemType.UPGRADE: self.__makeUpgradeEntry(pos, item, values, page) elif itemType == ItemType.HEAL: self.__makeHealEntry(pos, item, values, page) if index == 3: pageIndex += 1 itemIndex = 0 index = 0 else: itemIndex += 1 index += 1 if self.nPages == 1: self.backBtn.hide() self.nextBtn.hide() for page in self.pages: if len(page.getItems()) == 0: page.destroy() self.pages.remove(page) else: page.hide() page.update() self.nPages = len(self.pages) self.isSetup = True def updatePage(self, page): battle = base.localAvatar.getMyBattle() if battle and self.wantTurretCount: self.shop.distShop.sendUpdate('requestTurretCount', []) self.updateTurretCount() page.update() def updatePages(self): battle = base.localAvatar.getMyBattle() if battle and self.wantTurretCount: self.shop.distShop.sendUpdate('requestTurretCount', []) self.updateTurretCount() for page in self.pages: page.update() def setPage(self, page): if self.nPage > -1: self.pages[self.nPage].hide() self.setBackBtn(True) self.setNextBtn(True) if (page - 1) < 0: self.setBackBtn(False) elif (page + 1) == self.nPages: self.setNextBtn(False) if page < 0 or page > self.nPages: return self.prevPage = (page - 1) self.nextPage = (page + 1) self.nPage = page self.pages[page].show() def getPage(self, index): return self.pages[index] def setBackBtn(self, enabled): if self.backBtn: if enabled == False: self.backBtn.setColorScale(GRAYED_OUT_COLOR) self.backBtn['state'] = DGG.DISABLED else: self.backBtn.setColorScale(NORMAL_COLOR) self.backBtn['state'] = DGG.NORMAL def setNextBtn(self, enabled): if self.nextBtn: if enabled == False: self.nextBtn.setColorScale(GRAYED_OUT_COLOR) self.nextBtn['state'] = DGG.DISABLED else: self.nextBtn.setColorScale(NORMAL_COLOR) self.nextBtn['state'] = DGG.NORMAL def setOKCommand(self, command): if self.okBtn: self.okBtn['command'] = command def setCancelCommand(self, command): if self.clBtn: self.clBtn['command'] = command def showInfo(self, text, negative=0, duration=-1): self.infoLbl.show() if negative: self.infoLbl['text_fg'] = (0.9, 0, 0, 1) self.infoLbl['text_shadow'] = (0, 0, 0, 1) else: self.infoLbl['text_fg'] = (0, 0, 0, 1) self.infoLbl['text_shadow'] = (0, 0, 0, 0) self.infoLbl['text'] = text if duration > -1: Sequence(Wait(duration), Func(self.hideInfo)).start() def hideInfo(self): if self.infoLbl: self.infoLbl.hide() def delete(self): elements = [ self.title, self.okBtn, self.clBtn, self.infoLbl, self.backBtn, self.nextBtn, self.turretLabel, self.turretImg ] for element in elements: if element: element.destroy() del elements for page in self.pages: page.destroy() self.pages.remove(page) self.title = None self.okBtn = None self.clBtn = None self.infoLbl = None self.backBtn = None self.nextBtn = None self.bgImage = None self.turretLabel = None self.turretCount = None if self.window: self.window.destroy() self.window = None self.destroy()
class Credits(DirectObject): developers = {'Game Development': ['DuckyDuck1553', 'DecodedLogic']} webDevelopers = { 'Web Development': ['totok', 'DuckyDuck1553', 'DecodedLogic'] } artists = { 'Artists': [ 'John L. (supertricky)', 'DuckyDuck1553', 'DecodedLogic', 'Baru (fatigue)', 'Isabel (allyjean)', 'Colorblind', 'loonatic' ] } composers = {'Composers': ['Dylan J.', 'Doc. Dynamite', 'CBiard']} communityManager = {'Community Manager': ['Leo (Bradley)']} moderators = { 'Moderation Team': ['Mark (Black & White)', 'Jackson M.', 'Gabriel A.', 'Davon M.'] } specialThanks = { 'Special Thanks': [ 'Jesse Schell', 'rdb', 'Baribal', 'ThomasEgi', 'tobspr', 'jjkoletar', 'mmavipc', 'CFSWorks', 'loblao', 'HarvTarv', 'Hawkheart', 'TheRandomDog', 'Joey Z. (joey19982)', 'Disney Interactive', 'Microsoft', 'YorkeTheMouse', 'Disyer', '\n\n\nAnd of course, YOU!\n\n\n' ] } def __init__(self): DirectObject.__init__(self) base.setBackgroundColor(0, 0, 0) self.textParent = base.credits2d.attachNewNode('textParent') self.textParent.setBin("gui-popup", 61) self.textParent.setDepthWrite(False) self.textParent.setTransparency(True) self.logoImage = OnscreenImage('phase_3/maps/CogInvasion_Logo.png', parent=self.textParent, scale=(0.685, 1.0, 0.325)) self.logoImage.setTransparency(1) text = self.buildCreditsText() self.creditsText = OnscreenText(parent=self.textParent, font=CIGlobals.getToonFont(), fg=(1, 1, 1, 1), scale=0.065, pos=(0, -0.5, 0), text=text, shadow=(0, 0, 0, 1)) self.posInterval = None self.backgroundImg = OnscreenImage('phase_3/maps/credits_fade.png', parent=render2d) self.backgroundImg.setTransparency(True) self.backgroundImg.setColor(0, 0, 0, 1.0) self.backgroundImg.setBin("gui-popup", 62) self.backgroundImg.setDepthWrite(False) self.exitText = OnscreenText(parent=base.credits2d, font=CIGlobals.getToonFont(), fg=(1.0, 0, 0, 1.0), shadow=(0, 0, 0, 1), scale=0.085, pos=(0, -0.96, 0), text='Press any key to exit') self.exitText.hide() self.exitText.setBin("gui-popup", 63) self.exitText.setDepthWrite(False) self.exitText.setTransparency(True) self.creditsAudioMgr = AudioManager.createAudioManager() self.creditsAudioMgr.setVolume(0.65) self.bgm = self.creditsAudioMgr.getSound( 'phase_4/audio/bgm/new_years_fireworks_music.ogg') def buildCreditsText(self): def writeNames(message, namesList): for name in namesList: message = '%s%s\n' % (message, name) return message message = 'Cog Invasion Online\n{0}\n'.format( metadata.getBuildInformation()) message += '\nCREDITS\n\n' # Write the game developers' names message += 'Programming\n\n' message += '%s\n' % self.developers.keys()[0] message = writeNames(message, self.developers.values()[0]) message += '\n\n' # Write the web developers' names message += '%s\n' % self.webDevelopers.keys()[0] message = writeNames(message, self.webDevelopers.values()[0]) # Let's begin the art section message += '\n\nArt\n\n' # Write the artists' names message += '%s\n' % self.artists.keys()[0] message = writeNames(message, self.artists.values()[0]) message += '\n\n' # Write the composers' names message += '%s\n' % self.composers.keys()[0] message = writeNames(message, self.composers.values()[0]) ########################################## # Let's begin the community section. message += '\n\nCommunity\n\n' # Write the community manager names message += '%s\n' % self.communityManager.keys()[0] message = writeNames(message, self.communityManager.values()[0]) message += '\n\n' # Write the moderators' names message += '%s\n' % self.moderators.keys()[0] message = writeNames(message, self.moderators.values()[0]) # Let's begin the Special Thanks section. message += '\n\n' # Write the special thanks' names message += '%s\n' % self.specialThanks.keys()[0] message = writeNames(message, self.specialThanks.values()[0]) message += '\nWe thank the original Toontown Online team.\nNot only for the game, but for the memories.' message += "\n\n\n\n\"Don't cry because it's over.\nSmile because it happened.\"\n - Dr. Seuss" return message def exit(self, key): self.__fadeOut() base.taskMgr.doMethodLater(1.1, self.__exitTask, "exitTask") def __exitTask(self, task): messenger.send('credits-Complete') self.ignoreAll() self.destroy() base.unMuteMusic() base.unMuteSfx() base.setBackgroundColor(0.05, 0.15, 0.4) base.transitions.fadeIn(1.0) return task.done def watchTextPosition(self, task): if self.textParent.getZ() >= 5.187: self.exitText.show() self.acceptOnce('button', self.exit) return task.done return task.cont def __fadeIn(self): Parallel( LerpColorScaleInterval(self.textParent, 1.0, (1, 1, 1, 1), (1, 1, 1, 0)), LerpColorScaleInterval(self.backgroundImg, 1.0, (1, 1, 1, 1), (1, 1, 1, 0)), LerpColorScaleInterval(self.exitText, 1.0, (1, 1, 1, 1), (1, 1, 1, 0))).start() def __fadeOut(self): Parallel( LerpColorScaleInterval(self.textParent, 1.0, (1, 1, 1, 0), (1, 1, 1, 1)), LerpColorScaleInterval(self.backgroundImg, 1.0, (1, 1, 1, 0), (1, 1, 1, 1)), LerpColorScaleInterval(self.exitText, 1.0, (1, 1, 1, 0), (1, 1, 1, 1))).start() def setup(self): self.__fadeIn() b3 = self.textParent.getTightBounds() dimensions = b3[1] - b3[0] self.posInterval = self.textParent.posInterval( 50, Point3(0, 0, dimensions[2] + 2), Point3(0, 0, 0)) self.posInterval.start() self.bgm.setLoop(1) self.bgm.play() base.buttonThrowers[0].node().setButtonDownEvent('button') taskMgr.add(self.watchTextPosition, 'Watch Text Position') def destroy(self): if self.posInterval: self.posInterval.pause() self.posInterval = None if self.bgm: self.bgm.stop() self.bgm = None if self.backgroundImg: self.backgroundImg.destroy() self.backgroundImg = None if self.creditsText: self.creditsText.destroy() self.creditsText = None if self.exitText: self.exitText.destroy() self.exitText = None if self.logoImage: self.logoImage.destroy() self.logoImage = None if self.textParent: self.textParent.removeNode() self.textParent = None if self.creditsAudioMgr: self.creditsAudioMgr.stopAllSounds() self.creditsAudioMgr = None self.developers = None self.webDevelopers = None self.artists = None self.specialThanks = None self.composers = None self.communityManager = None self.moderators = None self.prevMusic = None
class FPSCamera(DirectObject): MaxP = 90.0 MinP = -90.0 PitchUpdateEpsilon = 0.1 ViewModelFOV = 70.0 BobCycleMin = 1.0 BobCycleMax = 0.45 Bob = 0.002 BobUp = 0.5 PunchDamping = 9.0 PunchSpring = 65.0 PrintAnimLengths = False def __init__(self): DirectObject.__init__(self) self.mouseEnabled = False self.lastCamRoot2Quat = Quat(Quat.identQuat()) self.punchAngleVel = Vec3(0) self.punchAngle = Vec3(0) self.lastFacing = Vec3(0) self.lastMousePos = Point2(0) self.currMousePos = Point2(0) self.bobTime = 0 self.lastBobTime = 0 self.lastVMPos = Point3(0) self.camRoot = NodePath("camRoot") self.camRoot2 = self.camRoot.attachNewNode("camRoot2") self.lastPitch = 0 self.lastEyeHeight = 0.0 # Updates to the transform of camRoot self.vmRender = NodePath( BSPRender('vmRender', BSPLoader.getGlobalPtr())) self.vmRender.setShaderAuto() self.vmRoot = self.vmRender.attachNewNode('vmRoot') self.vmRoot2 = self.vmRoot.attachNewNode(ModelRoot('vmRoot2')) self.viewModel = Actor( "phase_14/models/char/v_toon_arms.bam", { "zero": "phase_14/models/char/v_toon_arms.egg", # Squirt gun viewmodel animations "sg_draw": "phase_14/models/char/v_toon_arms-draw.egg", "sg_idle": "phase_14/models/char/v_toon_arms-idle.egg", "sg_inspect": "phase_14/models/char/v_toon_arms-inspect.egg", "sg_shoot_begin": "phase_14/models/char/v_toon_arms-shoot_begin.egg", "sg_shoot_loop": "phase_14/models/char/v_toon_arms-shoot_loop.egg", "sg_shoot_end": "phase_14/models/char/v_toon_arms-shoot_end.egg", "pie_draw": "phase_14/models/char/v_toon_arms-pie_draw.egg", "pie_idle": "phase_14/models/char/v_toon_arms-pie_idle.egg", "button_draw": "phase_14/models/char/v_toon_arms-button_draw.egg", "button_idle": "phase_14/models/char/v_toon_arms-button_idle.egg", "button_press": "phase_14/models/char/v_toon_arms-button_press.egg", "gumball_draw": "phase_14/models/char/v_toon_arms-gumball_draw.egg", "gumball_idle": "phase_14/models/char/v_toon_arms-gumball_idle.egg", "gumball_fire": "phase_14/models/char/v_toon_arms-gumball_fire.egg", "hose_draw": "phase_14/models/char/v_toon_arms-hose_draw.egg", "hose_idle": "phase_14/models/char/v_toon_arms-hose_idle.egg", "hose_shoot_begin": "phase_14/models/char/v_toon_arms-hose_shoot_begin.egg", "hose_shoot_loop": "phase_14/models/char/v_toon_arms-hose_shoot_loop.egg", "hose_shoot_end": "phase_14/models/char/v_toon_arms-hose_shoot_end.egg", "tnt_draw": "phase_14/models/char/v_toon_arms-tnt_draw.egg", "tnt_idle": "phase_14/models/char/v_toon_arms-tnt_idle.egg", "tnt_throw": "phase_14/models/char/v_toon_arms-tnt_throw.egg", "slap_idle": "phase_14/models/char/v_toon_arms-slap_idle.egg", "slap_hit": "phase_14/models/char/v_toon_arms-slap_hit.egg", "sound": "phase_14/models/char/v_toon_arms-sound.egg" }) self.viewModel.setBlend( frameBlend=base.config.GetBool("interpolate-frames", False)) self.viewModel.reparentTo(self.vmRoot2) self.viewModel.find("**/hands").setTwoSided(True) self.viewModel.hide() self.defaultViewModel = self.viewModel self.idealFov = self.ViewModelFOV precacheActor(self.viewModel) #self.viewModel.clearMaterial() #self.viewModel.setMaterial(CIGlobals.getCharacterMaterial(specular = (0, 0, 0, 1)), 1) self.viewportLens = PerspectiveLens() self.viewportLens.setMinFov(self.ViewModelFOV / (4. / 3.)) self.viewportLens.setNear(0.3) # Updates to the transform of base.camera self.viewportCam = base.makeCamera(base.win, clearDepth=True, camName='fpsViewport', mask=CIGlobals.ViewModelCamMask, lens=self.viewportLens) # Pretend to be the main camera so the viewmodel gets ambient probes updated self.viewportCam.node().setTag("__mainpass__", "1") self.viewportCam.reparentTo(self.vmRoot) self.vmGag = None self.vmAnimTrack = None self.dmgFade = OnscreenImage(image="phase_14/maps/damage_effect.png", parent=render2d) self.dmgFade.setBin('gui-popup', 100) self.dmgFade.setTransparency(1) self.dmgFade.setColorScale(1, 1, 1, 0) self.dmgFadeIval = None #self.accept('v', self.vmRender.ls) #base.bspLoader.addDynamicNode(self.vmRoot) if self.PrintAnimLengths: print "v_toon_arms animation lengths:" for anim in self.viewModel.getAnimNames(): print "\t{0}\t:\t{1}".format(anim, self.viewModel.getDuration(anim)) taskMgr.add(self.__vpDebugTask, "vpdebutask", sort=-100) def setViewModelFOV(self, fov): self.idealFov = fov def restoreViewModelFOV(self): self.idealFov = self.ViewModelFOV def swapViewModel(self, newViewModel, fov=70.0): if newViewModel.isEmpty(): return isHidden = False if not self.viewModel.isEmpty(): self.viewModel.reparentTo(hidden) isHidden = self.viewModel.isHidden() self.viewModel = newViewModel self.viewModel.reparentTo(self.vmRoot2) if isHidden: self.viewModel.hide() else: self.viewModel.show() self.setViewModelFOV(fov) def restoreViewModel(self): isHidden = False if not self.viewModel.isEmpty(): self.viewModel.reparentTo(hidden) isHidden = self.viewModel.isHidden() self.viewModel = self.defaultViewModel self.viewModel.reparentTo(self.vmRoot2) if isHidden: self.viewModel.hide() else: self.viewModel.show() self.restoreViewModelFOV() def addViewPunch(self, punch): self.punchAngleVel += punch * 20 def resetViewPunch(self, tolerance=0.0): if tolerance != 0.0: tolerance *= tolerance check = self.punchAngleVel.lengthSquared( ) + self.punchAngle.lengthSquared() if check > tolerance: return self.punchAngle = Vec3(0) self.punchAngleVel = Vec3(0) def decayPunchAngle(self): if self.punchAngle.lengthSquared( ) > 0.001 or self.punchAngleVel.lengthSquared() > 0.001: dt = globalClock.getDt() self.punchAngle += self.punchAngleVel * dt damping = 1 - (self.PunchDamping * dt) if damping < 0: damping = 0 self.punchAngleVel *= damping # Torsional spring springForceMag = self.PunchSpring * dt springForceMag = CIGlobals.clamp(springForceMag, 0.0, 2.0) self.punchAngleVel -= self.punchAngle * springForceMag # Don't wrap around self.punchAngle.set(CIGlobals.clamp(self.punchAngle[0], -179, 179), CIGlobals.clamp(self.punchAngle[1], -89, 89), CIGlobals.clamp(self.punchAngle[2], -89, 89)) else: self.punchAngle = Vec3(0) self.punchAngleVel = Vec3(0) def hideViewModel(self): self.viewModel.hide(BitMask32.allOn()) def showViewModel(self): if not base.localAvatar.isFirstPerson(): return self.viewModel.showThrough(CIGlobals.ViewModelCamMask) def __vpDebugTask(self, task): if self.vmRender.getState() != render.getState(): # pretend like the view model is part of the main scene self.vmRender.setState(render.getState()) self.viewportLens.setAspectRatio(base.getAspectRatio()) self.viewportLens.setMinFov(self.idealFov / (4. / 3.)) self.vmRoot.setTransform(render, self.camRoot.getTransform(render)) self.viewportCam.setTransform(render, base.camera.getTransform(render)) # Since the viewmodel is not underneath BSPRender, it's not going to be automatically # influenced by the ambient probes. We need to do this explicitly. #base.bspLoader.updateDynamicNode(self.vmRoot) #self.viewportDebug.setImage(self.viewportCam.node().getDisplayRegion(0).getScreenshot()) return task.cont def handleSuitAttack(self, attack): print "FPSCamera handleSuitAttack:", attack def doDamageFade(self, r, g, b, severity=1.0): if self.dmgFadeIval: self.dmgFadeIval.finish() self.dmgFadeIval = None severity = min(1.0, severity) self.dmgFadeIval = Sequence( LerpColorScaleInterval(self.dmgFade, 0.25, (r, g, b, severity), (r, g, b, 0), blendType='easeOut'), Wait(1.0), LerpColorScaleInterval(self.dmgFade, 2.0, (r, g, b, 0), (r, g, b, severity), blendType='easeInOut')) self.dmgFadeIval.start() def setVMAnimTrack(self, track, loop=False): self.clearVMAnimTrack() self.vmAnimTrack = track if loop: self.vmAnimTrack.loop() else: self.vmAnimTrack.start() def clearVMAnimTrack(self): if self.vmAnimTrack: self.vmAnimTrack.pause() self.vmAnimTrack = None def setVMGag(self, gag, pos=(0, 0, 0), hpr=(0, 0, 0), scale=(1, 1, 1), hand=0, animate=True): self.clearVMGag() handNode = NodePath() if hand == ATTACK_HOLD_RIGHT: handNode = self.getViewModelRightHand() elif hand == ATTACK_HOLD_LEFT: handNode = self.getViewModelLeftHand() if isinstance(gag, Actor) and animate: self.vmGag = Actor(other=gag) self.vmGag.reparentTo(handNode) self.vmGag.loop('chan') else: self.vmGag = gag.copyTo(handNode) self.vmGag.setPos(pos) self.vmGag.setHpr(hpr) self.vmGag.setScale(scale) def clearVMGag(self): if self.vmGag: if isinstance(self.vmGag, Actor): self.vmGag.cleanup() self.vmGag.removeNode() self.vmGag = None def setup(self): try: # Match the arm color with the torso color of local avatar self.viewModel.find("**/arms").setColorScale( base.localAvatar.getTorsoColor(), 1) # Same with glove cover self.viewModel.find("**/hands").setColorScale( base.localAvatar.getGloveColor(), 1) except: pass self.attachCamera() def attachCamera(self, reset=True): if reset: self.camRoot.reparentTo(base.localAvatar) if base.localAvatar.isFirstPerson(): self.camRoot.setPos(base.localAvatar.getEyePoint()) else: self.camRoot.setPos(0, 0, max(base.localAvatar.getHeight(), 3.0)) self.camRoot.setHpr(0, 0, 0) self.camRoot2.setPosHpr(0, 0, 0, 0, 0, 0) base.camera.reparentTo(self.camRoot2) if base.localAvatar.isFirstPerson(): base.camera.setPosHpr(0, 0, 0, 0, 0, 0) elif base.localAvatar.isThirdPerson(): pos, lookAt = self.getThirdPersonBattleCam() base.localAvatar.smartCamera.setIdealCameraPos(pos) base.localAvatar.smartCamera.setLookAtPoint(lookAt) def getThirdPersonBattleCam(self): camHeight = max(base.localAvatar.getHeight(), 3.0) heightScaleFactor = camHeight * 0.3333333333 return ((1, -5 * heightScaleFactor, 0), (1, 10, 0)) def getViewModelLeftHand(self): return self.viewModel.find("**/def_left_hold") def getViewModelRightHand(self): return self.viewModel.find("**/def_right_hold") def getViewModel(self): return self.viewModel def acceptEngageKeys(self): self.acceptOnce("escape", self.__handleEscapeKey) def ignoreEngageKeys(self): self.ignore("escape") def enableMouseMovement(self): props = WindowProperties() props.setMouseMode(WindowProperties.MConfined) props.setCursorHidden(True) base.win.requestProperties(props) self.attachCamera(False) if base.localAvatar.isFirstPerson(): base.localAvatar.getGeomNode().hide() base.win.movePointer(0, base.win.getXSize() / 2, base.win.getYSize() / 2) base.taskMgr.add(self.__updateTask, "mouseUpdateFPSCamera", sort=-40) self.acceptEngageKeys() self.mouseEnabled = True base.localAvatar.enableGagKeys() def disableMouseMovement(self, allowEnable=False, showAvatar=True): props = WindowProperties() props.setMouseMode(WindowProperties.MAbsolute) props.setCursorHidden(False) base.win.requestProperties(props) base.taskMgr.remove("mouseUpdateFPSCamera") base.localAvatar.disableGagKeys() if allowEnable: self.acceptEngageKeys() else: self.ignoreEngageKeys() if showAvatar or base.localAvatar.isThirdPerson(): base.localAvatar.getGeomNode().show() else: base.localAvatar.getGeomNode().hide() self.mouseEnabled = False def __handleEscapeKey(self): if self.mouseEnabled: self.disableMouseMovement(True) else: self.enableMouseMovement() #def doCameraJolt(self, amplitude, horizRange = [-1, 1], vertRange = [1]): #h = random.choice(horizRange) * amplitude #p = random.choice(vertRange) * amplitude #nquat = Quat(Quat.identQuat()) #nquat.setHpr((h, p, 0)) #self.lastCamRoot2Quat = self.lastCamRoot2Quat + nquat #Effects.createPBounce(self.camRoot2, 3, self.camRoot2.getHpr(), 1, amplitude).start() #Effects.createHBounce(self.camRoot2, 3, self.camRoot2.getHpr(), 1, amplitude).start() def handleJumpHardLand(self): down = Parallel( LerpPosInterval(base.cam, 0.1, (-0.1, 0, -0.2), (0, 0, 0), blendType='easeOut'), LerpHprInterval(base.cam, 0.1, (0, 0, -2.5), (0, 0, 0), blendType='easeOut')) up = Parallel( LerpPosInterval(base.cam, 0.7, (0, 0, 0), (-0.1, 0, -0.2), blendType='easeInOut'), LerpHprInterval(base.cam, 0.7, (0, 0, 0), (0, 0, -2.5), blendType='easeInOut')) Sequence(down, up).start() def __updateTask(self, task): # TODO -- This function does a lot of math, I measured it to take .5 ms on my laptop # That's a lot of time for something miniscule like sway and bob. dt = globalClock.getDt() time = globalClock.getFrameTime() if base.localAvatar.isFirstPerson(): eyePoint = base.localAvatar.getEyePoint() if base.localAvatar.walkControls.crouching: eyePoint[2] = eyePoint[2] / 2.0 eyePoint[2] = CIGlobals.lerpWithRatio(eyePoint[2], self.lastEyeHeight, 0.4) self.lastEyeHeight = eyePoint[2] camRootAngles = Vec3(0) # Mouse look around mw = base.mouseWatcherNode if mw.hasMouse(): md = base.win.getPointer(0) center = Point2(base.win.getXSize() / 2, base.win.getYSize() / 2) xDist = md.getX() - center.getX() yDist = md.getY() - center.getY() sens = self.__getMouseSensitivity() angular = -(xDist * sens) / dt base.localAvatar.walkControls.controller.setAngularMovement( angular) camRootAngles.setY(self.lastPitch - yDist * sens) if camRootAngles.getY() > FPSCamera.MaxP: camRootAngles.setY(FPSCamera.MaxP) yDist = 0 elif camRootAngles.getY() < FPSCamera.MinP: yDist = 0 camRootAngles.setY(FPSCamera.MinP) base.win.movePointer(0, int(center.getX()), int(center.getY())) if base.localAvatar.isFirstPerson(): # Camera / viewmodel bobbing vmBob = Point3(0) vmAngles = Vec3(0) vmRaise = Point3(0) camBob = Point3(0) maxSpeed = base.localAvatar.walkControls.BattleRunSpeed * 16.0 speed = base.localAvatar.walkControls.speeds.length() * 16.0 speed = max(-maxSpeed, min(maxSpeed, speed)) bobOffset = CIGlobals.remapVal(speed, 0, maxSpeed, 0.0, 1.0) self.bobTime += (time - self.lastBobTime) * bobOffset self.lastBobTime = time # Calculate the vertical bob cycle = self.bobTime - int( self.bobTime / self.BobCycleMax) * self.BobCycleMax cycle /= self.BobCycleMax if cycle < self.BobUp: cycle = math.pi * cycle / self.BobUp else: cycle = math.pi + math.pi * (cycle - self.BobUp) / (1.0 - self.BobUp) verticalBob = speed * 0.005 verticalBob = verticalBob * 0.3 + verticalBob * 0.7 * math.sin( cycle) verticalBob = max(-7.0, min(4.0, verticalBob)) verticalBob /= 16.0 # Calculate the lateral bob cycle = self.bobTime - int( self.bobTime / self.BobCycleMax * 2) * self.BobCycleMax * 2 cycle /= self.BobCycleMax * 2 if cycle < self.BobUp: cycle = math.pi * cycle / self.BobUp else: cycle = math.pi + math.pi * (cycle - self.BobUp) / (1.0 - self.BobUp) lateralBob = speed * 0.005 lateralBob = lateralBob * 0.3 + lateralBob * 0.7 * math.sin(cycle) lateralBob = max(-7.0, min(4.0, lateralBob)) lateralBob /= 16.0 # Apply bob, but scaled down a bit vmBob.set(lateralBob * 0.8, 0, verticalBob * 0.1) # Z bob a bit more vmBob[2] += verticalBob * 0.1 # Bob the angles vmAngles[2] += verticalBob * 0.5 vmAngles[1] -= verticalBob * 0.4 vmAngles[0] -= lateralBob * 0.3 # ================================================================ # Viewmodel lag/sway angles = self.camRoot.getHpr(render) quat = Quat() quat.setHpr(angles) invQuat = Quat() invQuat.invertFrom(quat) maxVMLag = 1.5 lagforward = quat.getForward() if dt != 0.0: lagdifference = lagforward - self.lastFacing lagspeed = 5.0 lagdiff = lagdifference.length() if (lagdiff > maxVMLag) and (maxVMLag > 0.0): lagscale = lagdiff / maxVMLag lagspeed *= lagscale self.lastFacing = CIGlobals.extrude(self.lastFacing, lagspeed * dt, lagdifference) self.lastFacing.normalize() lfLocal = invQuat.xform(lagdifference) vmBob = CIGlobals.extrude(vmBob, 5.0 / 16.0, lfLocal * -1.0) pitch = angles[1] if pitch > 180: pitch -= 360 elif pitch < -180: pitch += 360 vmBob = CIGlobals.extrude(vmBob, pitch * (0.035 / 16), Vec3.forward()) vmBob = CIGlobals.extrude(vmBob, pitch * (0.03 / 16), Vec3.right()) vmBob = CIGlobals.extrude(vmBob, pitch * (0.02 / 16), Vec3.up()) # ================================================================ vmRaise.set( 0, 0, 0 ) #(0, abs(camRootAngles.getY()) * -0.002, camRootAngles.getY() * 0.002) camBob.set(0, 0, 0) # Apply bob, raise, and sway to the viewmodel. self.viewModel.setPos(vmBob + vmRaise + self.lastVMPos) self.vmRoot2.setHpr(vmAngles) self.camRoot.setPos(eyePoint + camBob) newPitch = camRootAngles.getY() if abs(newPitch - self.lastPitch) > self.PitchUpdateEpsilon: # Broadcast where our head is looking head = base.localAvatar.getPart("head") if head and not head.isEmpty(): # Constrain the head pitch a little bit so it doesn't look like their head snapped headPitch = max(-47, newPitch) headPitch = min(75, headPitch) base.localAvatar.b_setLookPitch(headPitch) self.lastPitch = newPitch if base.localAvatar.isFirstPerson(): # Apply punch angle self.decayPunchAngle() camRootAngles += self.punchAngle self.camRoot.setHpr(camRootAngles) return task.cont def __getMouseSensitivity(self): return CIGlobals.getSettingsMgr().getSetting('fpmgms').getValue() def cleanup(self): taskMgr.remove("vpdebutask") self.disableMouseMovement(False, False) self.clearVMAnimTrack() self.clearVMGag() if self.viewModel: self.viewModel.cleanup() self.viewModel.removeNode() self.viewModel = None if self.vmRender: self.vmRender.removeNode() self.vmRender = None self.vmRoot = None self.vmRoot2 = None self.viewportLens = None if self.viewportCam: self.viewportCam.removeNode() self.viewportCam = None if self.camRoot: self.camRoot.removeNode() self.camRoot = None self.camRoot2 = None self.lastEyeHeight = None self.lastPitch = None self.bobTime = None self.lastBobTime = None self.mouseEnabled = None self.lastCamRoot2Quat = None self.punchAngleVel = None self.punchAngle = None self.lastFacing = None self.lastMousePos = None self.currMousePos = None self.lastVMPos = None self.defaultViewModel = None self.idealFov = None self.vmGag = None self.vmAnimTrack = None self.dmgFade = None self.dmgFadeIval = None self.ignoreAll()
class MainMenu(): def __init__(self): self.frameMain = DirectFrame(image="mainmenu.png", image_scale=(1.7778, 1, 1), frameSize=(base.a2dLeft, base.a2dRight, base.a2dBottom, base.a2dTop), frameColor=(0, 0, 0, 0)) self.frameMain.setTransparency(True) self.btnStart = DirectButton( text="Enter", scale=0.15, text_pos=(0, 1.1), text_scale=0.5, text_fg=(240 / 255.0, 255 / 255.0, 240 / 255.0, 1), frameColor=(0, 0, 0, 0), image=("btnEnter.png", "btnEnter_hover.png", "btnEnter_hover.png", "btnEnter_hover.png"), pos=(0, 0, -0.3), command=base.messenger.send, extraArgs=["menu_StartGame"]) self.btnStart.setTransparency(True) self.btnStart.reparentTo(self.frameMain) self.btnOptions = DirectButton(text="Options", scale=0.1, text_fg=(240 / 255.0, 255 / 255.0, 240 / 255.0, 1), frameColor=(0, 0, 0, 0), image=("settings.png"), image_scale=1.2, text_pos=(0, -0.2), pos=(base.a2dRight - 0.3, 0, base.a2dBottom + 0.25), command=base.messenger.send, extraArgs=["menu_Options"]) self.btnOptions.setTransparency(True) self.btnOptions.reparentTo(self.frameMain) self.btnQuit = DirectButton( text="Exit", scale=0.15, text_pos=(-0.3, -0.25), text_scale=0.75, text_fg=(240 / 255.0, 255 / 255.0, 240 / 255.0, 1), frameColor=(0, 0, 0, 0), image=("btnExit.png", "btnExit_hover.png", "btnExit_hover.png", "btnExit_hover.png"), image_scale=(1, 1, 0.5), pos=(base.a2dLeft + 0.3, 0, base.a2dBottom + 0.25), command=base.messenger.send, extraArgs=["menu_QuitGame"]) self.btnQuit.setTransparency(True) self.btnQuit.reparentTo(self.frameMain) self.imgBouncer = OnscreenImage(image="bouncer.png", scale=(0.75 * 0.25, 1 * 0.25, 1 * 0.25), pos=(-0.25, 0, -0.3)) self.imgBouncer.setTransparency(True) self.imgBouncer.reparentTo(self.frameMain) self.imgBadDude1 = OnscreenImage(image="badDude1.png", scale=(0.25, 0.25, 0.25), pos=(-0.75, 0, -0.4)) self.imgBadDude1.setTransparency(True) self.imgBadDude1.reparentTo(self.frameMain) img = self.imgBadDude1 up = img.posInterval(3.0, Point3(img.getX(), img.getY(), img.getZ() + 0.01), bakeInStart=0) left = img.posInterval(3.0, Point3(img.getX() - 0.01, img.getY(), img.getZ()), bakeInStart=0) right = img.posInterval(3.0, Point3(img.getX() + 0.01, img.getY(), img.getZ()), bakeInStart=0) down = img.posInterval(3.0, Point3(img.getX(), img.getY(), img.getZ() - 0.01), bakeInStart=0) rotForward = img.hprInterval(3.0, Point3(0, 0, 2.5), bakeInStart=0) rotBackward = img.hprInterval(3.0, Point3(0, 0, -2.5), bakeInStart=0) rotCenter = img.hprInterval(3.0, Point3(0, 0, 0), bakeInStart=0) self.ivalBadDude1 = Sequence(Parallel(rotCenter, up), Parallel(rotBackward, left), down, Parallel(rotCenter, up), Parallel(rotForward, right), down) self.imgGoodGal1 = OnscreenImage(image="goodGal1.png", scale=(0.6 * 0.25, 0.25, 0.25), pos=(-0.95, 0, -0.43)) self.imgGoodGal1.setTransparency(True) self.imgGoodGal1.reparentTo(self.frameMain) img = self.imgGoodGal1 up = img.posInterval(3.0, Point3(img.getX(), img.getY(), img.getZ() + 0.01), bakeInStart=0) left = img.posInterval(3.0, Point3(img.getX() - 0.01, img.getY(), img.getZ()), bakeInStart=0) right = img.posInterval(3.0, Point3(img.getX() + 0.01, img.getY(), img.getZ()), bakeInStart=0) down = img.posInterval(3.0, Point3(img.getX(), img.getY(), img.getZ() - 0.01), bakeInStart=0) rotForward = img.hprInterval(3.0, Point3(0, 0, 2.5), bakeInStart=0) rotBackward = img.hprInterval(3.0, Point3(0, 0, -2.5), bakeInStart=0) rotCenter = img.hprInterval(3.0, Point3(0, 0, 0), bakeInStart=0) self.ivalGoodGal1 = Sequence(left, right, left, down, up) self.imgGoodDude1 = OnscreenImage(image="goodDude1.png", scale=(0.25, 0.25, 0.25), pos=(0.95, 0, 0)) self.imgGoodDude1.setTransparency(True) self.imgGoodDude1.reparentTo(self.frameMain) img = self.imgGoodDude1 up = img.posInterval(3.0, Point3(img.getX(), img.getY(), img.getZ() + 0.02), bakeInStart=0) left = img.posInterval(3.0, Point3(img.getX() - 0.02, img.getY(), img.getZ()), bakeInStart=0) right = img.posInterval(3.0, Point3(img.getX() + 0.02, img.getY(), img.getZ()), bakeInStart=0) down = img.posInterval(3.0, Point3(img.getX(), img.getY(), img.getZ() - 0.02), bakeInStart=0) rotForward = img.hprInterval(3.0, Point3(0, 0, 4), bakeInStart=0) rotBackward = img.hprInterval(3.0, Point3(0, 0, -4), bakeInStart=0) rotCenter = img.hprInterval(3.0, Point3(0, 0, 0), bakeInStart=0) self.ivalGoodDude1 = Sequence(Parallel(up, rotCenter), Parallel(right, rotForward), Parallel(down, rotCenter), Parallel(left, rotBackward)) self.hide() def show(self): self.frameMain.show() self.ivalBadDude1.loop() self.ivalGoodGal1.loop() self.ivalGoodDude1.loop() def hide(self): self.frameMain.hide() self.ivalBadDude1.finish() self.ivalGoodGal1.finish() self.ivalGoodDude1.finish()
ConfigVariableDouble('extractor-step-time').setValue(0.01) # loading screen backgroundNodePath = aspect2d.attachNewNode(backgroundNode, 0) backgroundNodePath.setPos(0.0, 0.0, 0.0) backgroundNodePath.setScale(render2d, VBase3(1)) backgroundNodePath.find('**/bg').setBin('fixed', 10) # change the logo backgroundNodePath.find('**/fg').stash() from direct.gui.DirectGui import OnscreenImage logo = OnscreenImage('phase_3/maps/toontown-logo-new.png') logo.reparentTo(backgroundNodePath) logo.setBin('fixed', 20) logo.setTransparency(TransparencyAttrib.MAlpha) logo.setScale(.8, 1, .7) logo.setZ(.3) base.graphicsEngine.renderFrame() # default DGG stuff DirectGuiGlobals.setDefaultRolloverSound( base.loadSfx('phase_3/audio/sfx/GUI_rollover.ogg')) DirectGuiGlobals.setDefaultClickSound( base.loadSfx('phase_3/audio/sfx/GUI_create_toon_fwd.ogg')) DirectGuiGlobals.setDefaultDialogGeom( loader.loadModel('phase_3/models/gui/dialog_box_gui')) # localizer import TTLocalizer
class CameraShyFirstPerson(FirstPerson): toonInFocusColor = VBase4(0.25, 1.0, 0.25, 1.0) toonOutOfFocusColor = VBase4(1.0, 1.0, 1.0, 1.0) fullyChargedState = 5 def __init__(self, mg): self.mg = mg self.cameraFocus = None self.batteryFrame = None self.batteryBg = None self.batteryBar = None self.rechargeSound = None self.fullyChargedSound = None self.hasToonInFocus = False self.toonToTakePicOf = None self.cameraRechargeState = None self.cameraRechargingLabel = None self.cameraFlashSeq = None self.camFSM = ClassicFSM('CameraFSM', [State('off', self.enterOff, self.exitOff), State('ready', self.enterCameraReady, self.exitCameraReady), State('recharge', self.enterCameraRecharge, self.exitCameraRecharge)], 'off', 'off') self.camFSM.enterInitialState() FirstPerson.__init__(self) return def movementTask(self, task): if not inputState.isSet('jump') and not base.localAvatar.walkControls.isAirborne and inputState.isSet('forward') or inputState.isSet('reverse') or inputState.isSet('slideLeft') or inputState.isSet('slideRight'): if base.localAvatar.getAnimState() != 'run': base.localAvatar.setAnimState('run') base.localAvatar.playMovementSfx('run') self.mg.sendUpdate('runningAvatar', [base.localAvatar.doId]) elif inputState.isSet('jump') or base.localAvatar.walkControls.isAirborne: if base.localAvatar.getAnimState() != 'jump': base.localAvatar.setAnimState('jump') base.localAvatar.playMovementSfx(None) self.mg.sendUpdate('jumpingAvatar', [base.localAvatar.doId]) elif base.localAvatar.getAnimState() != 'neutral': base.localAvatar.setAnimState('neutral') base.localAvatar.playMovementSfx(None) self.mg.sendUpdate('standingAvatar', [base.localAvatar.doId]) return task.cont def enterOff(self): pass def exitOff(self): pass def enterCameraReady(self): self.acceptOnce('mouse1', self.__mouse1Pressed) def stopCameraFlash(self): if self.cameraFlashSeq: self.cameraFlashSeq.finish() self.cameraFlashSeq = None return def __mouse1Pressed(self): self.cameraFlashSeq = Sequence(Func(base.transitions.setFadeColor, 1, 1, 1), Func(base.transitions.fadeOut, 0.1), Wait(0.1), Func(base.transitions.fadeIn, 0.1), Wait(0.1), Func(base.transitions.setFadeColor, 0, 0, 0)) self.cameraFlashSeq.start() self.mg.sendUpdate('remoteAvatarTakePicture', [base.localAvatar.doId]) self.mg.myRemoteAvatar.takePicture() if self.hasToonInFocus and self.toonToTakePicOf: self.mg.sendUpdate('tookPictureOfToon', [self.toonToTakePicOf.doId]) self.camFSM.request('recharge') def exitCameraReady(self): self.ignore('mouse1') def enterCameraRecharge(self): self.batteryBar.update(0) taskMgr.add(self.__rechargeNextState, 'rechargeCamera') def __rechargeNextState(self, task): if self.cameraRechargeState == None: self.cameraRechargeState = -1 self.cameraRechargeState += 1 if self.cameraRechargeState > 0: base.playSfx(self.rechargeSound) self.batteryBar.update(self.cameraRechargeState) if self.cameraRechargeState == self.fullyChargedState: base.playSfx(self.fullyChargedSound) self.camFSM.request('ready') return task.done else: task.delayTime = 1.0 return task.again def exitCameraRecharge(self): taskMgr.remove('rechargeCamera') self.cameraRechargeState = None return def __handleRayInto(self, entry): intoNP = entry.getIntoNodePath() toonNP = intoNP.getParent() for key in base.cr.doId2do.keys(): obj = base.cr.doId2do[key] if obj.__class__.__name__ == 'DistributedToon': if obj.getKey() == toonNP.getKey(): self.__handleToonInFocus(obj) def __handleRayOut(self, entry): intoNP = entry.getIntoNodePath() toonNP = intoNP.getParent() for key in base.cr.doId2do.keys(): obj = base.cr.doId2do[key] if obj.__class__.__name__ == 'DistributedToon': if obj.getKey() == toonNP.getKey(): self.toonToTakePicOf = None self.hasToonInFocus = False if self.cameraFocus.getColorScale() == self.toonInFocusColor: self.cameraFocus.setColorScale(self.toonOutOfFocusColor) return def __handleToonInFocus(self, toon): if not self.hasToonInFocus or self.toonToTakePicOf is not None or self.toonToTakePicOf.doId != toon.doId: self.toonToTakePicOf = toon self.hasToonInFocus = True self.cameraFocus.setColorScale(self.toonInFocusColor) return def start(self): self.fullyChargedSound = base.loadSfx('phase_4/audio/sfx/MG_pairing_match.mp3') self.rechargeSound = base.loadSfx('phase_4/audio/sfx/MG_sfx_travel_game_blue_arrow.mp3') self.batteryFrame = DirectFrame(parent=base.a2dBottomRight, pos=(-0.2, 0, 0.1), scale=(0.8, 0, 1)) self.batteryBg = OnscreenImage(image='phase_4/maps/battery_charge_frame.png', parent=self.batteryFrame) self.batteryBg.setTransparency(1) self.batteryBg.setX(0.03) self.batteryBg.setScale(0.17, 0, 0.05) self.batteryBar = DirectWaitBar(value=0, range=5, barColor=(1, 1, 1, 1), relief=None, scale=(0.12, 0.0, 0.3), parent=self.batteryFrame) self.cameraFocus = loader.loadModel('phase_4/models/minigames/photo_game_viewfinder.bam') self.cameraFocus.reparentTo(base.aspect2d) self.focusCollHandler = CollisionHandlerEvent() self.focusCollHandler.setInPattern('%fn-into') self.focusCollHandler.setOutPattern('%fn-out') self.focusCollNode = CollisionNode('mouseRay') self.focusCollNP = base.camera.attachNewNode(self.focusCollNode) self.focusCollNode.setCollideMask(BitMask32(0)) self.focusCollNode.setFromCollideMask(CIGlobals.WallBitmask) self.focusRay = CollisionRay() self.focusRay.setFromLens(base.camNode, 0.0, 0.0) self.focusCollNode.addSolid(self.focusRay) base.cTrav.addCollider(self.focusCollNP, self.focusCollHandler) base.localAvatar.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed, 0.0, CIGlobals.ToonReverseSpeed, CIGlobals.ToonRotateSpeed) FirstPerson.start(self) return def reallyStart(self): self.accept('mouseRay-into', self.__handleRayInto) self.accept('mouseRay-out', self.__handleRayOut) self.camFSM.request('recharge') taskMgr.add(self.movementTask, 'movementTask') FirstPerson.reallyStart(self) def end(self): self.camFSM.request('off') taskMgr.remove('movementTask') self.ignore('mouseRay-into') self.ignore('mouseRay-out') FirstPerson.end(self) def reallyEnd(self): self.batteryBar.destroy() self.batteryBar = None self.batteryBg.destroy() self.batteryBg = None self.batteryFrame.destroy() self.batteryFrame = None self.cameraFocus.removeNode() self.cameraFocus = None self.focusCollHandler = None self.focusCollNode = None self.focusCollNP.removeNode() self.focusCollNP = None self.focusRay = None self.hasToonInFocus = None self.toonToTakePicOf = None self.fullyChargedSound = None self.rechargeSound = None self.stopCameraFlash() FirstPerson.reallyEnd(self) base.localAvatar.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed, CIGlobals.ToonJumpForce, CIGlobals.ToonReverseSpeed, CIGlobals.ToonRotateSpeed) return def cleanup(self): self.camFSM.requestFinalState() self.camFSM = None FirstPerson.cleanup(self) return