Пример #1
0
    def updateVisibility(self, zoneNum=None):
        if zoneNum is None:
            zoneNum = self.curZoneNum
            if zoneNum is None:
                return None

        if hasattr(self, "lockVizZone"):
            zoneNum = self.lockVizZone

        zoneEnt = self.getEntity(zoneNum)
        visibleZoneNums = list2dict([zoneNum])
        visibleZoneNums.update(list2dict(zoneEnt.getVisibleZoneNums()))
        if not __debug__:
            if self.lastToonZone not in visibleZoneNums:
                if self.lastToonZone is not None:
                    self.notify.warning(
                        "adding zoneNum %s to visibility list because toon is standing in that zone!"
                        % self.lastToonZone
                    )
                    visibleZoneNums.update(list2dict([self.lastToonZone]))

        zoneEntIds = list(self.entType2ids["zone"])
        zoneEntIds.remove(LevelConstants.UberZoneEntId)
        if len(zoneEntIds):
            pass
        1
        vizZonesChanged = 1
        addedZoneNums = []
        removedZoneNums = []
        allVZ = dict(visibleZoneNums)
        allVZ.update(self.curVisibleZoneNums)
        for (vz, dummy) in allVZ.items():
            new = vz in visibleZoneNums
            old = vz in self.curVisibleZoneNums
            if new and old:
                continue

            if new:
                addedZoneNums.append(vz)
                continue
            removedZoneNums.append(vz)

        if not addedZoneNums and not removedZoneNums:
            DistributedLevel.notify.debug("visible zone list has not changed")
            vizZonesChanged = 0
        else:
            DistributedLevel.notify.debug("showing zones %s" % addedZoneNums)
            for az in addedZoneNums:
                self.showZone(az)

            DistributedLevel.notify.debug("hiding zones %s" % removedZoneNums)
            for rz in removedZoneNums:
                self.hideZone(rz)

        if vizZonesChanged or self.fForceSetZoneThisFrame:
            self.setVisibility(visibleZoneNums.keys())
            self.fForceSetZoneThisFrame = 0

        self.curZoneNum = zoneNum
        self.curVisibleZoneNums = visibleZoneNums
Пример #2
0
    def __init__(self, spec = None, scenario = 0):
        newSpec = 0
        if type(spec) is types.ModuleType:
            self.specDict = spec.levelSpec
        elif type(spec) is types.DictType:
            self.specDict = spec
        self.entId2specDict = {}
        self.entId2specDict.update(list2dict(self.getGlobalEntIds(), value=self.privGetGlobalEntityDict()))
        for i in xrange(self.getNumScenarios()):
            self.entId2specDict.update(list2dict(self.getScenarioEntIds(i), value=self.privGetScenarioEntityDict(i)))

        self.setScenario(scenario)
Пример #3
0
    def initVisibility(self):
        self.curVisibleZoneNums = list2dict(self.zoneNums)
        del self.curVisibleZoneNums[LevelConstants.UberZoneEntId]
        self.curZoneNum = None
        self.visChangedThisFrame = 0
        self.fForceSetZoneThisFrame = 0

        def handleCameraRayFloorCollision(collEntry, self=self):
            name = collEntry.getIntoNode().getName()
            self.notify.debug("camera floor ray collided with: %s" % name)
            prefixLen = len(DistributedLevel.FloorCollPrefix)
            if name[:prefixLen] == DistributedLevel.FloorCollPrefix:

                try:
                    zoneNum = int(name[prefixLen:])
                except:
                    DistributedLevel.notify.warning("Invalid zone floor collision node: %s" % name)

                self.camEnterZone(zoneNum)

        self.accept("on-floor", handleCameraRayFloorCollision)
        if not DistributedLevel.WantVisibility:
            zoneNums = list(self.zoneNums)
            zoneNums.remove(LevelConstants.UberZoneEntId)
            self.forceSetZoneThisFrame()
            self.setVisibility(zoneNums)

        taskMgr.add(self.visChangeTask, self.uniqueName(DistributedLevel.VisChangeTaskName), priority=49)
Пример #4
0
    def resetVisibility(self):
        self.curVisibleZoneNums = list2dict(self.zoneNums)
        del self.curVisibleZoneNums[LevelConstants.UberZoneEntId]
        for (vz, dummy) in self.curVisibleZoneNums.items():
            self.showZone(vz)

        self.updateVisibility()
        def setRequestNewEntity(self, data):
            spec = self.level.levelSpec
            entIds = spec.getAllEntIds()
            entIdDict = list2dict(entIds)
            allocRange = EditorGlobals.getEntIdAllocRange()
            if not hasattr(self, 'lastAllocatedEntId'):
                self.lastAllocatedEntId = allocRange[0]
            idChosen = 0
            while not idChosen:
                for id in xrange(self.lastAllocatedEntId, allocRange[1]):
                    print id
                    if id not in entIdDict:
                        idChosen = 1
                        break
                else:
                    if self.lastAllocatedEntId != allocRange[0]:
                        self.lastAllocatedEntId = allocRange[0]
                    else:
                        self.notify.error('out of entIds')

            data.update({'entId': id})
            self.lastAllocatedEntId = id
            self.level.setAttribChange(self.entId, 'insertEntity', data)
            self.level.levelSpec.doSetAttrib(self.entId, 'requestNewEntity', None)
            return
Пример #6
0
        def checkSpecIntegrity(self):
            entIds = self.getGlobalEntIds()
            entIds = list2dict(entIds)
            for i in range(self.getNumScenarios()):
                for id in self.getScenarioEntIds(i):
                    entIds[id] = None

            if self.entTypeReg is not None:
                allEntIds = entIds
                for entId in allEntIds:
                    spec = self.getEntitySpec(entId)
                    entType = spec['type']
                    typeDesc = self.entTypeReg.getTypeDesc(entType)
                    attribNames = typeDesc.getAttribNames()
                    attribDescs = typeDesc.getAttribDescDict()
                    for attrib in spec.keys():
                        if attrib not in attribNames:
                            LevelSpec.notify.warning("entId %s (%s): unknown attrib '%s', omitting" % (entId, spec['type'], attrib))
                            del spec[attrib]

                    for attribName in attribNames:
                        if not spec.has_key(attribName):
                            LevelSpec.notify.warning("entId %s (%s): missing attrib '%s'" % (entId, spec['type'], attribName))

            return
Пример #7
0
 def _DistributedLevel__handleLevelMgrCreated(self):
     levelMgr = self.getEntity(LevelConstants.LevelMgrEntId)
     self.geom = levelMgr.geom
     self.zoneNum2node = LevelUtil.getZoneNum2Node(self.geom)
     self.zoneNums = self.zoneNum2node.keys()
     self.zoneNums.sort()
     self.zoneNumDict = list2dict(self.zoneNums)
     DistributedLevel.notify.debug("zones from model: %s" % self.zoneNums)
     self.fixupLevelModel()
Пример #8
0
 def __init__(self, spec = None, scenario = 0):
     newSpec = 0
     if type(spec) is types.ModuleType:
         if __dev__:
             reload(spec)
         
         self.specDict = spec.levelSpec
         if __dev__:
             self.setFilename(spec.__file__)
         
     elif type(spec) is types.DictType:
         self.specDict = spec
     elif spec is None:
         if __dev__:
             newSpec = 1
             self.specDict = {
                 'globalEntities': { },
                 'scenarios': [
                     { }] }
         
     
     self.entId2specDict = { }
     self.entId2specDict.update(list2dict(self.getGlobalEntIds(), value = self.privGetGlobalEntityDict()))
     for i in range(self.getNumScenarios()):
         self.entId2specDict.update(list2dict(self.getScenarioEntIds(i), value = self.privGetScenarioEntityDict(i)))
     
     self.setScenario(scenario)
     if __dev__:
         if newSpec:
             import EntityTypes as EntityTypes
             import EntityTypeRegistry as EntityTypeRegistry
             etr = EntityTypeRegistry.EntityTypeRegistry(EntityTypes)
             self.setEntityTypeReg(etr)
             entId = LevelConstants.UberZoneEntId
             self.insertEntity(entId, 'zone')
             self.doSetAttrib(entId, 'name', 'UberZone')
             entId = LevelConstants.LevelMgrEntId
             self.insertEntity(entId, 'levelMgr')
             self.doSetAttrib(entId, 'name', 'LevelMgr')
             entId = LevelConstants.EditMgrEntId
             self.insertEntity(entId, 'editMgr')
             self.doSetAttrib(entId, 'name', 'EditMgr')
 def announceZoneChange(self, newZoneId, oldZoneId):
     DistributedPetAI.notify.debug('%s.announceZoneChange: %s->%s' % (self.doId, oldZoneId, newZoneId))
     broadcastZones = list2dict([newZoneId, oldZoneId])
     self.estateOwnerId = simbase.air.estateManager.getOwnerFromZone(newZoneId)
     if self.estateOwnerId:
         self.inEstate = 1
         self.estateZones = simbase.air.estateManager.getEstateZones(self.estateOwnerId)
     else:
         self.inEstate = 0
         self.estateZones = []
     PetObserve.send(broadcastZones.keys(), PetObserve.PetActionObserve(PetObserve.Actions.CHANGE_ZONE, self.doId, (oldZoneId, newZoneId)))
Пример #10
0
    def addMultiChoiceWidget(self, levelSpec, entSpec, entId, attribName, params):
        frame = Frame(self.pageOneFrame.interior(), relief = GROOVE, borderwidth = 2)
        label = Label(frame, text = attribName, width = 15, anchor = W, justify = LEFT)
        label.pack(side = LEFT, expand = 0)
        valueDict = params.get('valueDict', { })
        self.cbDict[attribName] = list2dict(entSpec[attribName], value = 1)
        checkbuttonDict = { }
        base.cbButtons = []
        base.checkbuttonDict = checkbuttonDict
        for choice in params.get('choiceSet', []):
            trueValue = valueDict.get(choice, choice)
            cbVar = IntVar()
            cbVar.set(trueValue in self.cbDict[attribName])
            checkbuttonDict[trueValue] = cbVar
            
            def cbCommand(var, trueValue = trueValue):
                vd = self.cbDict[attribName]
                print vd
                if var.get():
                    print 'got it', trueValue, vd
                    vd[trueValue] = 1
                else:
                    print 'not it', trueValue, vd
                    if trueValue in vd:
                        del vd[trueValue]
                    
                value = vd.keys()
                print 'SENDING', value
                self.level.setAttribEdit(entId, attribName, value)

            if type(choice) is types.StringType:
                labelStr = choice
            else:
                labelStr = `choice`
            func = Functor(cbCommand, cbVar)
            choiceButton = Checkbutton(frame, text = labelStr, variable = cbVar, command = lambda : func())
            choiceButton.pack(side = LEFT, expand = 0)
            base.cbButtons.append(choiceButton)
        
        frame.pack(fill = X, expand = 1)
        self.attribWidgets.append(frame)
        
        def setCheckbuttonVar(attributeValueList):
            print 'COMING BACK', attributeValueList
            for (attributeValue, cb) in checkbuttonDict.items():
                if attributeValue in attributeValueList:
                    cb.set(1)
                    continue
                cb.set(0)
            

        self.curEntWidgets[attribName] = setCheckbuttonVar
Пример #11
0
    def __handleLevelMgrCreated(self):
        # as soon as the levelMgr has been created, load up the model
        # and extract zone info. We need to do this before any entities
        # get parented to the level!
        levelMgr = self.getEntity(LevelConstants.LevelMgrEntId)
        self.geom = levelMgr.geom

        # find the zones in the model and fix them up
        self.zoneNum2node = LevelUtil.getZoneNum2Node(self.geom)

        self.zoneNums = list(self.zoneNum2node.keys())
        self.zoneNums.sort()
        self.zoneNumDict = list2dict(self.zoneNums)
        DistributedLevel.notify.debug('zones from model: %s' % self.zoneNums)

        # give the level a chance to muck with the model before the entities
        # get placed
        self.fixupLevelModel()
Пример #12
0
 def announceZoneChange(self, newZoneId, oldZoneId):
     DistributedPetAI.notify.debug('%s.announceZoneChange: %s->%s' %
                                   (self.doId, oldZoneId, newZoneId))
     broadcastZones = list2dict([newZoneId, oldZoneId])
     self.estateOwnerId = simbase.air.estateManager.getOwnerFromZone(
         newZoneId)
     if self.estateOwnerId:
         if __dev__:
             pass
         self.inEstate = 1
         self.estateZones = simbase.air.estateManager.getEstateZones(
             self.estateOwnerId)
     else:
         self.inEstate = 0
         self.estateZones = []
     PetObserve.send(
         broadcastZones.keys(),
         PetObserve.PetActionObserve(PetObserve.Actions.CHANGE_ZONE,
                                     self.doId, (oldZoneId, newZoneId)))
Пример #13
0
        def setRequestNewEntity(self, data):
            # pick an unused entId
            spec = self.level.levelSpec
            entIds = spec.getAllEntIds()
            entIdDict = list2dict(entIds)

            # Note that this uses the ID range associated with the
            # AI's username, not the username of the user who requested
            # the new entity.
            allocRange = EditorGlobals.getEntIdAllocRange()

            if not hasattr(self, 'lastAllocatedEntId'):
                self.lastAllocatedEntId = allocRange[0]

            idChosen = 0
            while not idChosen:
                # linear search for an unused entId starting with the
                # last-allocated id
                for id in range(self.lastAllocatedEntId, allocRange[1]):
                    print(id)
                    if not id in entIdDict:
                        idChosen = 1
                        break
                else:
                    # we ran off the end of the range.
                    if self.lastAllocatedEntId != allocRange[0]:
                        # if we started in the middle, try again from
                        # the beginning
                        self.lastAllocatedEntId = allocRange[0]
                    else:
                        # every entId is used!!
                        self.notify.error('out of entIds')

            # OK, we've chosen an unused entId. Add the entId to the data
            # dict and do the insert
            data.update({'entId': id})
            self.lastAllocatedEntId = id
            self.level.setAttribChange(self.entId, 'insertEntity', data)

            # clear out the attrib, it shouldn't be kept in the spec
            self.level.levelSpec.doSetAttrib(self.entId, 'requestNewEntity',
                                             None)
Пример #14
0
    def initVisibility(self):
        # start out with every zone visible, since none of the zones have
        # been hidden
        self.curVisibleZoneNums = list2dict(self.zoneNums)
        # the UberZone is always visible, so it's not included in the
        # zones' viz lists
        del self.curVisibleZoneNums[LevelConstants.UberZoneEntId]
        # we have not entered any zone yet
        self.curZoneNum = None

        self.visChangedThisFrame = 0
        self.fForceSetZoneThisFrame = 0

        # listen for camera-ray/floor collision events
        def handleCameraRayFloorCollision(collEntry, self=self):
            name = collEntry.getIntoNode().getName()
            self.notify.debug('camera floor ray collided with: %s' % name)
            prefixLen = len(DistributedLevel.FloorCollPrefix)
            if (name[:prefixLen] == DistributedLevel.FloorCollPrefix):
                try:
                    zoneNum = int(name[prefixLen:])
                except:
                    DistributedLevel.notify.warning(
                        'Invalid zone floor collision node: %s' % name)
                else:
                    self.camEnterZone(zoneNum)

        self.accept('on-floor', handleCameraRayFloorCollision)

        # if no viz, listen to all the zones
        if not DistributedLevel.WantVisibility:
            zoneNums = list(self.zoneNums)
            zoneNums.remove(LevelConstants.UberZoneEntId)
            # make sure a setZone goes out on the first frame
            self.forceSetZoneThisFrame()
            self.setVisibility(zoneNums)

        # send out any zone changes at the end of the frame, just before
        # rendering
        taskMgr.add(self.visChangeTask,
                    self.uniqueName(DistributedLevel.VisChangeTaskName),
                    priority=49)
    def initVisibility(self):
        self.curVisibleZoneNums = list2dict(self.zoneNums)
        del self.curVisibleZoneNums[LevelConstants.UberZoneEntId]
        self.curZoneNum = None
        self.visChangedThisFrame = 0
        self.fForceSetZoneThisFrame = 0

        def handleCameraRayFloorCollision(collEntry, self = self):
            name = collEntry.getIntoNode().getName()
            self.notify.debug('camera floor ray collided with: %s' % name)
            prefixLen = len(DistributedLevel.FloorCollPrefix)
            if name[:prefixLen] == DistributedLevel.FloorCollPrefix:
                try:
                    zoneNum = int(name[prefixLen:])
                except:
                    DistributedLevel.notify.warning('Invalid zone floor collision node: %s' % name)
                else:
                    self.camEnterZone(zoneNum)

        self.accept('on-floor', handleCameraRayFloorCollision)
        taskMgr.add(self.visChangeTask, self.uniqueName(DistributedLevel.VisChangeTaskName), priority=49)
Пример #16
0
        def checkSpecIntegrity(self):
            # make sure there are no duplicate entIds
            entIds = self.getGlobalEntIds()
            assert uniqueElements(entIds)
            entIds = list2dict(entIds)
            for i in range(self.getNumScenarios()):
                for id in self.getScenarioEntIds(i):
                    assert id not in entIds
                    entIds[id] = None

            if self.entTypeReg is not None:
                # check each spec
                allEntIds = entIds
                for entId in allEntIds:
                    spec = self.getEntitySpec(entId)

                    assert 'type' in spec
                    entType = spec['type']
                    typeDesc = self.entTypeReg.getTypeDesc(entType)
                    attribNames = typeDesc.getAttribNames()
                    attribDescs = typeDesc.getAttribDescDict()

                    # are there any unknown attribs in the spec?
                    for attrib in list(spec.keys()):
                        if attrib not in attribNames:
                            LevelSpec.notify.warning(
                                "entId %s (%s): unknown attrib '%s', omitting"
                                % (entId, spec['type'], attrib))
                            del spec[attrib]

                    # does the spec have all of its attributes?
                    for attribName in attribNames:
                        if attribName not in spec:
                            LevelSpec.notify.warning(
                                "entId %s (%s): missing attrib '%s'" %
                                (entId, spec['type'], attribName))
    def _handlePhraseObserve(self, observe):

        def _handleGettingFriendlyAttention(avId, self = self):
            self.pet.lerpMoods({'boredom': -.85,
             'restlessness': -.1,
             'playfulness': 0.2,
             'loneliness': -.4,
             'sadness': -.1,
             'fatigue': -.05,
             'excitement': 0.05,
             'anger': -.05})
            self.updateLastInteractTime(avId)

        def _handleComeHere(avId, self = self):
            avatar = simbase.air.doId2do.get(avId)
            if avatar:
                self.pet.mover.walkToAvatar(avatar)
                avatar.setHatePets(0)

        def _handleFollowMe(avId, self = self):
            avatar = simbase.air.doId2do.get(avId)
            if avatar:
                self.pet.mover.walkToAvatar(avatar)
                avatar.setHatePets(0)

        def _handleStay(avId, self = self):
            avatar = simbase.air.doId2do.get(avId)
            if avatar:
                self._stay(avatar)

        def _handleCriticism(avId, self = self):
            ownerFactor = 0.5
            if avId == self.pet.ownerId:
                ownerFactor = 1.0
            self.pet.lerpMoods({'affection': -.4,
             'anger': 0.4,
             'boredom': -.3,
             'confusion': 0.05,
             'fatigue': 0.2,
             'playfulness': -.1,
             'sadness': 0.5 * ownerFactor})

        def _handleGoAway(avId, self = self):
            avatar = simbase.air.doId2do.get(avId)
            if avatar is not None:
                if self.getFocus() == avatar:
                    self._wander()
            return

        def _handleDoTrick(trickId, avId, self = self):
            looked = self.lookedAtBy(avId) or config.GetBool('pet-brain-ignore-looked-tricks', True)
            avatar = simbase.air.doId2do.get(avId)
            if avatar:
                if looked:
                    if not self.pet._willDoTrick(trickId):
                        trickId = PetTricks.Tricks.BALK
                    self._doTrick(trickId, avatar)

        phrase = observe.getPetPhrase()
        avId = observe.getAvId()
        OP = PetObserve.Phrases
        if phrase in list2dict([OP.COME,
         OP.FOLLOW_ME,
         OP.STAY,
         OP.NEED_LAFF,
         OP.NEED_GAGS,
         OP.NEED_JB,
         OP.HI,
         OP.SOOTHE,
         OP.PRAISE,
         OP.HAPPY,
         OP.QUESTION,
         OP.FRIENDLY,
         OP.LETS_PLAY,
         OP.DO_TRICK]):
            _handleGettingFriendlyAttention(avId)
        if phrase == OP.COME:
            _handleComeHere(avId)
        if phrase == OP.FOLLOW_ME:
            _handleFollowMe(avId)
        if phrase == OP.STAY:
            _handleStay(avId)
        if phrase == OP.CRITICISM:
            _handleCriticism(avId)
        if phrase == OP.GO_AWAY:
            _handleGoAway(avId)
        if phrase == OP.DO_TRICK:
            _handleDoTrick(observe.getTrickId(), avId)
Пример #18
0
    def _handlePhraseObserve(self, observe):
        def _handleGettingFriendlyAttention(avId, self=self):
            self.pet.lerpMoods({
                'boredom': -.85,
                'restlessness': -.1,
                'playfulness': 0.2,
                'loneliness': -.4,
                'sadness': -.1,
                'fatigue': -.05,
                'excitement': 0.05,
                'anger': -.05
            })
            self.updateLastInteractTime(avId)

        def _handleComeHere(avId, self=self):
            avatar = simbase.air.doId2do.get(avId)
            if avatar:
                self._chase(avatar)
                avatar.setHatePets(0)

        def _handleFollowMe(avId, self=self):
            avatar = simbase.air.doId2do.get(avId)
            if avatar:
                self._chase(avatar)
                avatar.setHatePets(0)

        def _handleStay(avId, self=self):
            avatar = simbase.air.doId2do.get(avId)
            if avatar:
                self._stay(avatar)

        def _handleCriticism(avId, self=self):
            ownerFactor = 0.5
            if avId == self.pet.ownerId:
                ownerFactor = 1.0
            self.pet.lerpMoods({
                'affection': -.4,
                'anger': 0.4,
                'boredom': -.3,
                'confusion': 0.05,
                'fatigue': 0.2,
                'playfulness': -.1,
                'sadness': 0.5 * ownerFactor
            })

        def _handleGoAway(avId, self=self):
            avatar = simbase.air.doId2do.get(avId)
            if avatar is not None:
                if self.getFocus() == avatar:
                    self._wander()
            return

        def _handleDoTrick(trickId, avId, self=self):
            avatar = simbase.air.doId2do.get(avId)
            if avatar:
                if self.lookedAtBy(avatar.doId):
                    if not self.goalMgr.hasTrickGoal():
                        if not self.pet._willDoTrick(trickId):
                            self.pet.trickFailLogger.addEvent(trickId)
                            trickId = PetTricks.Tricks.BALK
                        trickGoal = PetGoal.DoTrick(avatar, trickId)
                        self.goalMgr.addGoal(trickGoal)

        phrase = observe.getPetPhrase()
        avId = observe.getAvId()
        OP = PetObserve.Phrases
        if phrase in list2dict([
                OP.COME, OP.FOLLOW_ME, OP.STAY, OP.NEED_LAFF, OP.NEED_GAGS,
                OP.NEED_JB, OP.HI, OP.SOOTHE, OP.PRAISE, OP.HAPPY, OP.QUESTION,
                OP.FRIENDLY, OP.LETS_PLAY, OP.DO_TRICK
        ]):
            _handleGettingFriendlyAttention(avId)
        if phrase == OP.COME:
            _handleComeHere(avId)
        if phrase == OP.FOLLOW_ME:
            _handleFollowMe(avId)
        if phrase == OP.STAY:
            _handleStay(avId)
        if phrase == OP.CRITICISM:
            _handleCriticism(avId)
        if phrase == OP.GO_AWAY:
            _handleGoAway(avId)
        if phrase == OP.DO_TRICK:
            _handleDoTrick(observe.getTrickId(), avId)
Пример #19
0
    def _handlePhraseObserve(self, observe):
        def _handleGettingFriendlyAttention(avId, self=self):
            self.pet.lerpMoods({
                'boredom': -.85,
                'restlessness': -.1,
                'playfulness': .2,
                'loneliness': -.4,
                'sadness': -.1,
                'fatigue': -.05,
                'excitement': .05,
                'anger': -.05,
            })
            self.updateLastInteractTime(avId)

        def _handleComeHere(avId, self=self):
            # this avatar is calling us
            avatar = simbase.air.doId2do.get(avId)
            if avatar:
                self._chase(avatar)
                avatar.setHatePets(0)

        def _handleFollowMe(avId, self=self):
            # this avatar is calling us
            avatar = simbase.air.doId2do.get(avId)
            if avatar:
                self._chase(avatar)
                avatar.setHatePets(0)

        def _handleStay(avId, self=self):
            # this avatar is telling us to stay
            avatar = simbase.air.doId2do.get(avId)
            if avatar:
                self._stay(avatar)

        def _handleCriticism(avId, self=self):
            # avatar is criticizing us
            ownerFactor = .5
            if avId == self.pet.ownerId:
                ownerFactor = 1.
            self.pet.lerpMoods({
                'affection': -.4,
                'anger': .4,
                'boredom': -.3,
                'confusion': .05,
                'fatigue': .2,
                'playfulness': -.1,
                'sadness': .5 * ownerFactor,
            })

        def _handleGoAway(avId, self=self):
            # av is telling us to go away
            avatar = simbase.air.doId2do.get(avId)
            if avatar is not None:
                if self.getFocus() == avatar:
                    self._wander()

        def _handleDoTrick(trickId, avId, self=self):
            # av is telling us to do a trick
            avatar = simbase.air.doId2do.get(avId)
            if avatar:
                if self.lookedAtBy(avatar.doId):
                    # there should only be one DoTrick goal at a time
                    if not self.goalMgr.hasTrickGoal():
                        # will the pet do the trick?
                        if not self.pet._willDoTrick(trickId):
                            self.pet.trickFailLogger.addEvent(trickId)
                            trickId = PetTricks.Tricks.BALK
                        # add a goal of doing the trick
                        trickGoal = PetGoal.DoTrick(avatar, trickId)
                        self.goalMgr.addGoal(trickGoal)

        phrase = observe.getPetPhrase()
        avId = observe.getAvId()

        OP = PetObserve.Phrases
        # is the avatar attending to us?
        if phrase in list2dict([
                OP.COME,
                OP.FOLLOW_ME,
                OP.STAY,
                OP.NEED_LAFF,
                OP.NEED_GAGS,
                OP.NEED_JB,
                OP.HI,
                OP.SOOTHE,
                OP.PRAISE,
                OP.HAPPY,
                OP.QUESTION,
                OP.FRIENDLY,
                OP.LETS_PLAY,
                OP.DO_TRICK,
        ]):
            _handleGettingFriendlyAttention(avId)

        # calling us over?
        if phrase == OP.COME:
            _handleComeHere(avId)
        # telling us to follow them?
        if phrase == OP.FOLLOW_ME:
            _handleFollowMe(avId)
        # telling us to stay?
        if phrase == OP.STAY:
            _handleStay(avId)
        # criticizing us?
        if phrase == OP.CRITICISM:
            _handleCriticism(avId)
        # dismissing us?
        if phrase == OP.GO_AWAY:
            _handleGoAway(avId)
        # telling us to do a trick?
        if phrase == OP.DO_TRICK:
            _handleDoTrick(observe.getTrickId(), avId)
Пример #20
0
    def updateVisibility(self, zoneNum=None):
        """update the visibility assuming that we're in the specified
        zone; don't check to see if it's the zone we're already in"""
        #self.notify.debug('updateVisibility %s' % globalClock.getFrameCount())
        if zoneNum is None:
            zoneNum = self.curZoneNum
            if zoneNum is None:
                return
        if hasattr(self, 'lockVizZone'):
            zoneNum = self.lockVizZone

        zoneEnt = self.getEntity(zoneNum)
        # use dicts to efficiently ensure that there are no duplicates
        visibleZoneNums = list2dict([zoneNum])
        visibleZoneNums.update(list2dict(zoneEnt.getVisibleZoneNums()))

        if not __debug__:
            # HACK
            # make sure that the visibility list includes the zone that the toon
            # is standing in
            if self.lastToonZone not in visibleZoneNums:
                # make sure there IS a last zone
                if self.lastToonZone is not None:
                    self.notify.warning(
                        'adding zoneNum %s to visibility list '
                        'because toon is standing in that zone!' %
                        self.lastToonZone)
                    visibleZoneNums.update(list2dict([self.lastToonZone]))

        # we should not have the uberZone in the list at this point
        zoneEntIds = list(self.entType2ids['zone'])
        zoneEntIds.remove(LevelConstants.UberZoneEntId)
        if len(zoneEntIds):
            assert not LevelConstants.UberZoneEntId in visibleZoneNums

        # this flag will prevent a network msg from being sent if
        # the list of visible zones has not changed
        vizZonesChanged = 1
        # figure out which zones are new and which are going invisible
        # use dicts because 'x in dict' is faster than 'x in list'
        addedZoneNums = []
        removedZoneNums = []
        allVZ = dict(visibleZoneNums)
        allVZ.update(self.curVisibleZoneNums)
        for vz, dummy in allVZ.items():
            new = vz in visibleZoneNums
            old = vz in self.curVisibleZoneNums
            if new and old:
                continue
            if new:
                addedZoneNums.append(vz)
            else:
                removedZoneNums.append(vz)

        if (not addedZoneNums) and (not removedZoneNums):
            DistributedLevel.notify.debug('visible zone list has not changed')
            vizZonesChanged = 0
        else:
            # show the new, hide the old
            DistributedLevel.notify.debug('showing zones %s' % addedZoneNums)
            for az in addedZoneNums:
                self.showZone(az)
            DistributedLevel.notify.debug('hiding zones %s' % removedZoneNums)
            for rz in removedZoneNums:
                self.hideZone(rz)

        # it's important for us to send a setZone request on the first
        # frame, whether or not the visibility is different from what
        # we already have
        if vizZonesChanged or self.fForceSetZoneThisFrame:
            self.setVisibility(visibleZoneNums.keys())
            self.fForceSetZoneThisFrame = 0

        self.curZoneNum = zoneNum
        self.curVisibleZoneNums = visibleZoneNums
Пример #21
0
def privUpdateSpec(spec, modelPath, entTypeModule, newZonesGloballyVisible=0):
    """internal: take a spec and update it to match its level model
    If newZonesGloballyVisible is true, any new zones will be added to the
    visibility lists for every zone.
    """
    assert __dev__
    assert type(entTypeModule) is types.ModuleType
    import EntityTypeRegistry
    etr = EntityTypeRegistry.EntityTypeRegistry(entTypeModule)
    spec.setEntityTypeReg(etr)

    if modelPath is None:
        modelPath = spec.getEntitySpec(
            LevelConstants.LevelMgrEntId)['modelFilename']
    else:
        spec.doSetAttrib(LevelConstants.LevelMgrEntId,
                         'modelFilename', modelPath)

    # load the model
    # disable texture loading for speed
    TexturePool.setFakeTextureImage(
        '/i/alpha/player/install/ttmodels/src/fonts/ImpressBT.rgb')
    model = loader.loadModel(modelPath)
    assert model is not None
    TexturePool.clearFakeTextureImage()
    # get the model's zone info
    zoneNum2node = LevelUtil.getZoneNum2Node(model)
    zoneNums = zoneNum2node.keys()

    # what zone entities do we have specs for?
    type2ids = spec.getEntType2ids(spec.getAllEntIds())
    type2ids.setdefault('zone', [])
    zoneEntIds = type2ids['zone']

    def removeZoneEntity(entId, spec=spec, zoneEntIds=zoneEntIds):
        spec.removeEntity(entId)
        zoneEntIds.remove(entId)

    def insertZoneEntity(zoneNum, spec=spec, zoneEntIds=zoneEntIds):
        spec.insertEntity(zoneNum, 'zone', LevelConstants.UberZoneEntId)
        spec.doSetAttrib(zoneNum, 'name', 'zone%s' % zoneNum)
        zoneEntIds.append(zoneNum)

    # prune zone entities that reference zones that no longer exist
    removedZoneNums = []
    for entId in list(zoneEntIds):
        if entId not in zoneNums:
            print 'zone %s no longer exists; removing' % entId
            removeZoneEntity(entId)
            removedZoneNums.append(entId)
            
    # add new zone entities for new zones
    newZoneNums = []
    for zoneNum in zoneNums:
        if zoneNum not in zoneEntIds:
            newZoneNums.append(zoneNum)

            print 'adding new zone entity %s' % zoneNum
            insertZoneEntity(zoneNum)
            # by default, new zone can't see any other zones
            spec.doSetAttrib(zoneNum, 'visibility', [])

    if newZonesGloballyVisible:
        for entId in zoneEntIds:
            visList = list(spec.getEntitySpec(entId)['visibility'])
            visDict = list2dict(visList)
            for zoneNum in newZoneNums:
                visDict[zoneNum] = None
            visList = visDict.keys()
            visList.sort()
            spec.doSetAttrib(entId, 'visibility', visList)

    # make sure none of the zones reference removed zones
    spec.removeZoneReferences(removedZoneNums)