Ejemplo n.º 1
0
class MarkersManager(Flash):
    def __init__(self, parentUI):
        Flash.__init__(self, _MARKERS_MANAGER_SWF)
        self.component.wg_inputKeyMode = 2
        self.component.position.z = DEPTH_OF_VehicleMarker
        self.component.drawWithRestrictedViewPort = False
        self.movie.backgroundAlpha = 0
        self.colorManager = ColorSchemeManager._ColorSchemeManager()
        self.colorManager.populateUI(weakref.proxy(self))
        self.__plugins = PluginsCollection(self)
        plugins = {'equipments': _EquipmentsMarkerPlugin}
        visitor = g_sessionProvider.arenaVisitor
        if visitor.hasFlags():
            plugins['flags'] = _FlagsMarkerPlugin
        if visitor.hasRepairPoints():
            plugins['repairs'] = _RepairsMarkerPlugin
        if visitor.hasResourcePoints():
            plugins['resources'] = _ResourceMarkerPlugin
        if visitor.hasGasAttack():
            plugins['safe_zone'] = _GasAttackSafeZonePlugin
        self.__plugins.addPlugins(plugins)
        self.__ownUI = None
        self.__parentUI = parentUI
        self.__markers = {}
        return

    @proto_getter(PROTO_TYPE.BW_CHAT2)
    def bwProto(self):
        return None

    def setScaleProps(self,
                      minScale=40,
                      maxScale=100,
                      defScale=100,
                      speed=3.0):
        if constants.IS_DEVELOPMENT:
            self.__ownUI.scaleProperties = (minScale, maxScale, defScale,
                                            speed)

    def setAlphaProps(self,
                      minAlpha=40,
                      maxAlpha=100,
                      defAlpha=100,
                      speed=3.0):
        if constants.IS_DEVELOPMENT:
            self.__ownUI.alphaProperties = (minAlpha, maxAlpha, defAlpha,
                                            speed)

    def start(self):
        self.active(True)
        self.__ownUI = GUI.WGVehicleMarkersCanvasFlash(self.movie)
        self.__ownUI.wg_inputKeyMode = 2
        self.__ownUI.scaleProperties = GUI_SETTINGS.markerScaleSettings
        self.__ownUI.alphaProperties = GUI_SETTINGS.markerBgSettings
        self.__ownUIProxy = weakref.ref(self.__ownUI)
        self.__ownUIProxy().markerSetScale(g_settingsCore.interfaceScale.get())
        g_settingsCore.interfaceScale.onScaleChanged += self.updateMarkersScale
        self.__parentUI.component.addChild(self.__ownUI,
                                           'vehicleMarkersManager')
        self.__markersCanvasUI = self.getMember('vehicleMarkersCanvas')
        self.__plugins.init()
        ctrl = g_sessionProvider.shared.feedback
        if ctrl is not None:
            ctrl.onVehicleMarkerAdded += self.__onVehicleMarkerAdded
            ctrl.onVehicleMarkerRemoved += self.__onVehicleMarkerRemoved
            ctrl.onVehicleFeedbackReceived += self.__onVehicleFeedbackReceived
        functional = g_sessionProvider.dynamic.dynSquads
        if functional is not None:
            functional.onPlayerBecomeSquadman += self.__onPlayerBecomeSquadman
        self.__plugins.start()
        g_eventBus.addListener(GameEvent.SHOW_EXTENDED_INFO,
                               self.__handleShowExtendedInfo,
                               scope=_SCOPE)
        g_eventBus.addListener(GameEvent.GUI_VISIBILITY,
                               self.__handleGUIVisibility,
                               scope=_SCOPE)
        g_eventBus.addListener(GameEvent.MARKERS_2D_VISIBILITY,
                               self.__handleMarkerVisibility,
                               scope=_SCOPE)
        return

    def destroy(self):
        g_eventBus.removeListener(GameEvent.SHOW_EXTENDED_INFO,
                                  self.__handleShowExtendedInfo,
                                  scope=_SCOPE)
        g_eventBus.removeListener(GameEvent.GUI_VISIBILITY,
                                  self.__handleGUIVisibility,
                                  scope=_SCOPE)
        g_eventBus.removeListener(GameEvent.MARKERS_2D_VISIBILITY,
                                  self.__handleMarkerVisibility,
                                  scope=_SCOPE)
        self.__plugins.stop()
        g_settingsCore.interfaceScale.onScaleChanged -= self.updateMarkersScale
        ctrl = g_sessionProvider.shared.feedback
        if ctrl is not None:
            ctrl.onVehicleMarkerAdded -= self.__onVehicleMarkerAdded
            ctrl.onVehicleMarkerRemoved -= self.__onVehicleMarkerRemoved
            ctrl.onVehicleFeedbackReceived -= self.__onVehicleFeedbackReceived
        functional = g_sessionProvider.dynamic.dynSquads
        if functional is not None:
            functional.onPlayerBecomeSquadman -= self.__onPlayerBecomeSquadman
        if self.__parentUI is not None:
            setattr(self.__parentUI.component, 'vehicleMarkersManager', None)
        self.__plugins.fini()
        self.__parentUI = None
        self.__ownUI = None
        self.__markersCanvasUI = None
        self.colorManager.dispossessUI()
        self.close()
        return

    def _createVehicleMarker(self, isAlly, mProv):
        markerLinkage = 'VehicleMarkerAlly' if isAlly else 'VehicleMarkerEnemy'
        if g_sessionProvider.arenaVisitor.hasFlags():
            markerID = self.__ownUI.addFalloutMarker(mProv, markerLinkage)
        else:
            markerID = self.__ownUI.addMarker(mProv, markerLinkage)
        return markerID

    def addVehicleMarker(self, vProxy, vInfo, guiProps):
        vTypeDescr = vProxy.typeDescriptor
        maxHealth = vTypeDescr.maxHealth
        mProv = vProxy.model.node('HP_gui')
        isAlly = guiProps.isFriend
        speaking = self.bwProto.voipController.isPlayerSpeaking(
            vInfo.player.accountDBID)
        hunting = VehicleActions.isHunting(vInfo.events)
        markerID = self._createVehicleMarker(isAlly, mProv)
        self.__markers[vInfo.vehicleID] = _VehicleMarker(
            markerID, vProxy, self.__ownUIProxy)
        battleCtx = g_sessionProvider.getCtx()
        result = battleCtx.getPlayerFullNameParts(vProxy.id)
        vType = vInfo.vehicleType
        squadIcon = ''
        if g_sessionProvider.arenaVisitor.gui.isFalloutMultiTeam(
        ) and vInfo.isSquadMan():
            if guiProps == PLAYER_GUI_PROPS.squadman:
                squadTeam = 'my'
            elif isAlly:
                squadTeam = 'ally'
            else:
                squadTeam = 'enemy'
            squadIcon = '%s%d' % (squadTeam, vInfo.squadIndex)
        self.invokeMarker(markerID, 'init', [
            vType.classTag, vType.iconPath, result.vehicleName, vType.level,
            result.playerFullName, result.playerName, result.clanAbbrev,
            result.regionCode, vProxy.health, maxHealth,
            guiProps.name(), speaking, hunting, guiProps.base,
            g_ctfManager.getVehicleCarriedFlagID(
                vInfo.vehicleID) is not None, squadIcon
        ])
        return markerID

    def removeVehicleMarker(self, vehicleID):
        marker = self.__markers.pop(vehicleID, None)
        if marker is not None:
            self.__ownUI.delMarker(marker.id)
            marker.destroy()
        return

    def createStaticMarker(self, pos, symbol):
        mProv = Matrix()
        mProv.translation = pos
        handle = self.__ownUI.addMarker(mProv, symbol)
        return (mProv, handle)

    def destroyStaticMarker(self, handle):
        if self.__ownUI:
            self.__ownUI.delMarker(handle)

    def updateMarkerState(self, handle, newState, isImmediate=False):
        self.invokeMarker(handle, 'updateState', [newState, isImmediate])

    def showActionMarker(self, handle, newState):
        self.invokeMarker(handle, 'showActionMarker', [newState])

    def updateFlagbearerState(self, vehID, newState):
        marker = self.__markers.get(vehID)
        if marker is not None:
            self.invokeMarker(marker.id, 'updateFlagbearerState', [newState])
        return

    def updateVehicleHealth(self, handle, newHealth, aInfo, attackReasonID):
        if newHealth < 0 and not constants.SPECIAL_VEHICLE_HEALTH.IS_AMMO_BAY_DESTROYED(
                newHealth):
            newHealth = 0
        self.invokeMarker(handle, 'updateHealth', [
            newHealth,
            self.__getVehicleDamageType(aInfo),
            constants.ATTACK_REASONS[attackReasonID]
        ])

    def showDynamic(self, vID, flag):
        if vID not in self.__markers:
            return
        marker = self.__markers[vID]
        self.invokeMarker(marker.id, 'setSpeaking', [flag])

    def updateMarkersScale(self, scale=None):
        if self.__ownUIProxy() is not None:
            if scale is None:
                self.__ownUIProxy().markerSetScale(
                    g_settingsCore.interfaceScale.get())
            else:
                self.__ownUIProxy().markerSetScale(scale)
        return

    def setTeamKiller(self, vID):
        if vID not in self.__markers:
            return
        marker = self.__markers[vID]
        ctx = g_sessionProvider.getCtx()
        visitor = g_sessionProvider.arenaVisitor
        if not ctx.isTeamKiller(vID=vID) or ctx.isSquadMan(
                vID=vID) and not visitor.gui.isFalloutBattle():
            return
        self.invokeMarker(marker.id, 'setEntityName',
                          [PLAYER_GUI_PROPS.teamKiller.name()])

    def invokeMarker(self, handle, function, args=None):
        if handle != -1:
            self.__ownUI.markerInvoke(handle, (function, args))

    def setMarkerSettings(self, settings):
        if self.__markersCanvasUI:
            self.__markersCanvasUI.setMarkerSettings(settings)

    def setMarkerDuration(self, value):
        self.__invokeCanvas('setMarkerDuration', [value])

    def updateMarkers(self):
        self.colorManager.update()
        for marker in self.__markers.itervalues():
            self.invokeMarker(marker.id, 'update')

        self.__plugins.update()

    def updateMarkerSettings(self):
        for marker in self.__markers.itervalues():
            self.invokeMarker(marker.id, 'updateMarkerSettings')

    def __invokeCanvas(self, function, args=None):
        if args is None:
            args = []
        self.call('battle.vehicleMarkersCanvas.' + function, args)
        return

    def __getVehicleDamageType(self, attackerInfo):
        if not attackerInfo:
            return _DAMAGE_TYPE.FROM_UNKNOWN
        attackerID = attackerInfo.vehicleID
        if attackerID == avatar_getter.getPlayerVehicleID():
            return _DAMAGE_TYPE.FROM_PLAYER
        entityName = g_sessionProvider.getCtx().getPlayerGuiProps(
            attackerID, attackerInfo.team)
        if entityName == PLAYER_GUI_PROPS.squadman:
            return _DAMAGE_TYPE.FROM_SQUAD
        if entityName == PLAYER_GUI_PROPS.ally:
            return _DAMAGE_TYPE.FROM_ALLY
        if entityName == PLAYER_GUI_PROPS.enemy:
            return _DAMAGE_TYPE.FROM_ENEMY
        return _DAMAGE_TYPE.FROM_UNKNOWN

    def __onVehicleMarkerAdded(self, vProxy, vInfo, guiProps):
        self.addVehicleMarker(vProxy, vInfo, guiProps)

    def __onVehicleMarkerRemoved(self, vehicleID):
        self.removeVehicleMarker(vehicleID)

    def __onVehicleFeedbackReceived(self, eventID, vehicleID, value):
        if vehicleID not in self.__markers:
            return
        marker = self.__markers[vehicleID]
        if eventID == _EVENT_ID.VEHICLE_HIT:
            self.updateMarkerState(marker.id, 'hit', value)
        elif eventID == _EVENT_ID.VEHICLE_ARMOR_PIERCED:
            self.updateMarkerState(marker.id, 'hit_pierced', value)
        elif eventID == _EVENT_ID.VEHICLE_DEAD:
            self.updateMarkerState(marker.id, 'dead', value)
        elif eventID == _EVENT_ID.VEHICLE_SHOW_MARKER:
            self.showActionMarker(marker.id, value)
        elif eventID == _EVENT_ID.VEHICLE_HEALTH:
            self.updateVehicleHealth(marker.id, *value)

    def __onPlayerBecomeSquadman(self, vehicleID, guiProps):
        if vehicleID not in self.__markers:
            return
        marker = self.__markers[vehicleID]
        self.invokeMarker(marker.id, 'setEntityName', [guiProps.name()])

    def __handleShowExtendedInfo(self, event):
        isDown = event.ctx['isDown']
        self.__invokeCanvas('setShowExInfoFlag', [isDown])
        for marker in self.__markers.itervalues():
            self.invokeMarker(marker.id, 'showExInfo', [isDown])

    def __handleGUIVisibility(self, event):
        self.active(event.ctx['visible'])

    def __handleMarkerVisibility(self, _):
        self.active(not self.isActive)
Ejemplo n.º 2
0
class CrosshairPanelContainer(ExternalFlashComponent,
                              CrosshairPanelContainerMeta):
    """ Class is UI component that contains gun markers and crosshair panels.
    It provides access to Action Script."""
    def __init__(self):
        super(CrosshairPanelContainer, self).__init__(
            ExternalFlashSettings(BATTLE_VIEW_ALIASES.CROSSHAIR_PANEL,
                                  settings.CROSSHAIR_CONTAINER_SWF,
                                  settings.CROSSHAIR_ROOT_PATH,
                                  settings.CROSSHAIR_INIT_CALLBACK))
        self.__plugins = PluginsCollection(self)
        self.__plugins.addPlugins(plugins.createPlugins())
        self.__gunMarkers = None
        self.__viewID = CROSSHAIR_VIEW_ID.UNDEFINED
        self.__zoomFactor = 0.0
        self.__scale = 1.0
        self.__distance = 0
        self.__hasAmmo = True
        self.__configure()
        return

    def getViewID(self):
        """Gets current view ID of panel.
        :return: integer containing of CROSSHAIR_VIEW_ID.
        """
        return self.__viewID

    def setViewID(self, viewID):
        """Sets view ID of panel to change view presentation.
        :param viewID:
        """
        if viewID != self.__viewID:
            self.__viewID = viewID
            if self.__gunMarkers is not None:
                self.__gunMarkers.switch(viewID)
            chosenSettingID = plugins.chooseSetting(self.__viewID)
            self.as_setViewS(self.__viewID, chosenSettingID)
        return

    def setPosition(self, x, y):
        """Sets position of crosshair panel in pixels.
        :param x: integer containing x coordinate of center in pixels.
        :param y: integer containing y coordinate of center in pixels.
        """
        self.as_recreateDeviceS(x, y)

    def getScale(self):
        """Gets scale factor.
        :return: float containing scale factor.
        """
        return self.__scale

    def setScale(self, scale):
        """Sets scale factor.
        :param scale: float containing new scale factor.
        """
        if self.__scale == scale:
            return
        else:
            self.__scale = scale
            self.as_setScaleS(scale)
            if self.__gunMarkers is not None:
                self.__gunMarkers.setScale(scale)
            return

    def getZoom(self):
        """ Gets current zoom factor of player's camera.
        :return: float containing zoom factor.
        """
        return self.__zoomFactor

    def setZoom(self, zoomFactor):
        """ Gets current zoom factor of player's camera.
        :param zoomFactor: float containing zoom factor.
        """
        if zoomFactor == self.__zoomFactor:
            return
        self.__zoomFactor = zoomFactor
        if zoomFactor > 1:
            zoomString = i18n.makeString(INGAME_GUI.AIM_ZOOM, zoom=zoomFactor)
        else:
            zoomString = ''
        self.as_setZoomS(zoomString)

    def getDistance(self):
        """ Gets distance to desired target(point).
        :return: integer containing distance in meters.
        """
        return self.__distance

    def setDistance(self, distance):
        """ Sets distance to desired target(point).
        :param distance: integer containing distance in meters.
        """
        if distance != self.__distance:
            self.__distance = distance
            self.as_setDistanceS(
                i18n.makeString(INGAME_GUI.DISTANCE_METERS, meters=distance))

    def clearDistance(self, immediate=True):
        """ Removes distance string from UI.
        :param immediate: if value equals True than removes distance string from UI immediately,
            otherwise - hides this sting with animation.
        """
        self.__distance = 0
        self.as_clearDistanceS(immediate)

    def setHasAmmo(self, hasAmmo):
        """ Sets flag that indicates controlling vehicle has ammo.
        :param hasAmmo: bool.
        """
        if self.__hasAmmo != hasAmmo:
            self.__hasAmmo = hasAmmo
            if not hasAmmo:
                self.as_updateAmmoStateS(
                    i18n.makeString(
                        INGAME_GUI.PLAYER_MESSAGES_POSTMORTEM_USERNOHASAMMO))
            else:
                self.as_updateAmmoStateS('')

    def setSettings(self, vo):
        """ Sets new crosshair settings.
        :param vo: dictionary containing required settings, see _makeSettingsVO.
        """
        self.as_setSettingsS(vo)

    def createGunMarkers(self, markersInfo, vehicleInfo):
        """ Creates new set of gun markers at once if its is not created.
        :param markersInfo: instance of GunMarkersSetInfo.
        :param vehicleInfo: instance of VehicleArenaInfoVO.
        """
        if self.__gunMarkers is not None:
            LOG_WARNING('Set of gun markers is already created.')
            return
        else:
            self.__setGunMarkers(
                gm_factory.createComponents(markersInfo, vehicleInfo))
            return

    def invalidateGunMarkers(self, markersInfo, vehicleInfo):
        """ Checks present set of of gun markers to remove unused markers or to create new markers.
        For example, player uses client's gun markers and server's gun markers together,
        he removes setting item "use server marker", we need destroy server's gun markers.
        :param markersInfo: instance of GunMarkersSetInfo.
        :param vehicleInfo: instance of VehicleArenaInfoVO.
        """
        if self.__gunMarkers is None:
            LOG_WARNING('Set of gun markers is not created')
            return
        else:
            newSet = gm_factory.overrideComponents(self.__gunMarkers,
                                                   markersInfo, vehicleInfo)
            self.__clearGunMarkers()
            self.__setGunMarkers(newSet)
            return

    def setGunMarkerColor(self, markerType, color):
        """ Sets new color of gun marker.
        :param markerType: one of GUN_MARKER_TYPE.*.
        :param color: string containing alias of color.
        :return: bool.
        """
        if self.__gunMarkers is None:
            return False
        else:
            component = self.__gunMarkers.getComponentByType(markerType,
                                                             isActive=True)
            if component is not None:
                self.as_setGunMarkerColorS(component.getName(), color)
            return True

    def startPlugins(self):
        self.__plugins.start()

    def stopPlugins(self):
        self.__clearGunMarkers()
        self.__plugins.stop()

    def _populate(self):
        super(CrosshairPanelContainer, self)._populate()
        self.__plugins.init()
        self.startPlugins()

    def _dispose(self):
        self.stopPlugins()
        self.__plugins.fini()
        super(CrosshairPanelContainer, self)._dispose()

    def __configure(self):
        self.component.wg_inputKeyMode = 2
        self.component.position.z = DEPTH_OF_Aim
        self.component.focus = False
        self.component.moveFocus = False
        self.component.heightMode = 'PIXEL'
        self.component.widthMode = 'PIXEL'
        self.movie.backgroundAlpha = 0

    def __setGunMarkers(self, gunMarkers):
        self.__gunMarkers = gunMarkers
        viewSettings = self.__gunMarkers.getViewSettings()
        LOG_DEBUG('Present view settings of gun markers', viewSettings)
        for item in viewSettings:
            if item.hasView:
                continue
            if self.as_createGunMarkerS(item.viewID, item.linkage, item.name):
                self.__gunMarkers.addView(self.component, item.name)
                LOG_DEBUG('Gun marker has been created', item)
            else:
                LOG_ERROR('Gun marker can not be created', item)

        self.__gunMarkers.setScale(self.getScale())
        self.__gunMarkers.switch(self.getViewID())

    def __clearGunMarkers(self):
        if self.__gunMarkers is None:
            return
        else:
            viewSettings = self.__gunMarkers.getViewSettings()
            LOG_DEBUG('Previous view settings of gun markers', viewSettings)
            for item in viewSettings:
                if not item.hasView:
                    continue
                if self.as_destroyGunMarkerS(item.name):
                    self.__gunMarkers.removeView(self.component, item.name)
                    LOG_DEBUG('Gun marker has been destroyed', item)

            self.__gunMarkers.clear()
            self.__gunMarkers = None
            return
Ejemplo n.º 3
0
class Battle(BattleWindow):
    teamBasesPanel = property(lambda self: self.__teamBasesPanel)
    timersBar = property(lambda self: self.__timersBar)
    consumablesPanel = property(lambda self: self.__consumablesPanel)
    damagePanel = property(lambda self: self.__damagePanel)
    markersManager = property(lambda self: self.__markersManager)
    vErrorsPanel = property(lambda self: self.__vErrorsPanel)
    vMsgsPanel = property(lambda self: self.__vMsgsPanel)
    pMsgsPanel = property(lambda self: self.__pMsgsPanel)
    minimap = property(lambda self: self.__minimap)
    radialMenu = property(lambda self: self.__radialMenu)
    damageInfoPanel = property(lambda self: self.__damageInfoPanel)
    fragCorrelation = property(lambda self: self.__fragCorrelation)
    statsForm = property(lambda self: self.__statsForm)
    leftPlayersPanel = property(lambda self: self.__leftPlayersPanel)
    rightPlayersPanel = property(lambda self: self.__rightPlayersPanel)
    ribbonsPanel = property(lambda self: self.__ribbonsPanel)
    ppSwitcher = property(lambda self: self.__ppSwitcher)
    indicators = property(lambda self: self.__indicators)
    VEHICLE_DESTROY_TIMER = {'ALL': 'all',
     constants.VEHICLE_MISC_STATUS.VEHICLE_DROWN_WARNING: 'drown',
     constants.VEHICLE_MISC_STATUS.VEHICLE_IS_OVERTURNED: 'overturn'}
    VEHICLE_DEATHZONE_TIMER = {'ALL': 'all',
     constants.DEATH_ZONES.STATIC: 'death_zone',
     constants.DEATH_ZONES.GAS_ATTACK: 'gas_attack'}
    VEHICLE_DEATHZONE_TIMER_SOUND = {constants.DEATH_ZONES.GAS_ATTACK: ({'warning': 'fallout_gaz_sphere_warning',
                                         'critical': 'fallout_gaz_sphere_timer'}, {'warning': '/GUI/fallout/fallout_gaz_sphere_warning',
                                         'critical': '/GUI/fallout/fallout_gaz_sphere_timer'})}
    DENUNCIATIONS = {'bot': constants.DENUNCIATION.BOT,
     'flood': constants.DENUNCIATION.FLOOD,
     'offend': constants.DENUNCIATION.OFFEND,
     'notFairPlay': constants.DENUNCIATION.NOT_FAIR_PLAY,
     'forbiddenNick': constants.DENUNCIATION.FORBIDDEN_NICK,
     'swindle': constants.DENUNCIATION.SWINDLE,
     'blackmail': constants.DENUNCIATION.BLACKMAIL}
    __cameraVehicleID = -1
    __stateHandlers = {VEHICLE_VIEW_STATE.FIRE: '_setFireInVehicle',
     VEHICLE_VIEW_STATE.SHOW_DESTROY_TIMER: '_showVehicleTimer',
     VEHICLE_VIEW_STATE.HIDE_DESTROY_TIMER: '_hideVehicleTimer',
     VEHICLE_VIEW_STATE.SHOW_DEATHZONE_TIMER: 'showDeathzoneTimer',
     VEHICLE_VIEW_STATE.HIDE_DEATHZONE_TIMER: 'hideDeathzoneTimer',
     VEHICLE_VIEW_STATE.OBSERVED_BY_ENEMY: '_showSixthSenseIndicator'}

    def __init__(self, appNS):
        self.__ns = appNS
        self.__soundManager = None
        self.__arena = BigWorld.player().arena
        self.__plugins = PluginsCollection(self)
        plugins = {}
        if hasFlags():
            plugins['flagNotification'] = FlagNotificationPlugin
        if hasRepairPoints():
            plugins['repairTimer'] = RepairTimerPlugin
        if hasRespawns() and not BattleReplay.g_replayCtrl.isPlaying:
            plugins['respawnView'] = RespawnViewPlugin
        if hasResourcePoints():
            plugins['resources'] = ResourcePointsPlugin
        if hasGasAttack():
            plugins['gasAttack'] = GasAttackPlugin
        self.__plugins.addPlugins(plugins)
        self.__timerSounds = {}
        for timer, sounds in self.VEHICLE_DEATHZONE_TIMER_SOUND.iteritems():
            self.__timerSounds[timer] = {}
            for level, sound in sounds[FMOD.enabled].iteritems():
                self.__timerSounds[timer][level] = SoundGroups.g_instance.getSound2D(sound)

        self.__timerSound = None
        BattleWindow.__init__(self, 'battle.swf')
        self.__isHelpWindowShown = False
        self.__cameraMode = None
        self.component.wg_inputKeyMode = 1
        self.component.position.z = DEPTH_OF_Battle
        self.movie.backgroundAlpha = 0
        self.addFsCallbacks({'battle.leave': self.onExitBattle})
        self.addExternalCallbacks({'battle.showCursor': self.cursorVisibility,
         'battle.tryLeaveRequest': self.tryLeaveRequest,
         'battle.populateFragCorrelationBar': self.populateFragCorrelationBar,
         'Battle.UsersRoster.Appeal': self.onDenunciationReceived,
         'Battle.selectPlayer': self.selectPlayer,
         'battle.helpDialogOpenStatus': self.helpDialogOpenStatus,
         'battle.initLobbyDialog': self._initLobbyDialog,
         'battle.reportBug': self.reportBug})
        self.__dynSquadListener = None
        BigWorld.wg_setRedefineKeysMode(False)
        self.onPostmortemVehicleChanged(BigWorld.player().playerVehicleID)
        return

    @property
    def appNS(self):
        return self.__ns

    def getRoot(self):
        return self.__battle_flashObject

    def getCameraVehicleID(self):
        return self.__cameraVehicleID

    def populateFragCorrelationBar(self, _):
        if self.__fragCorrelation is not None:
            self.__fragCorrelation.populate()
        return

    def showAll(self, event):
        self.call('battle.showAll', [event.ctx['visible']])

    def showCursor(self, isShow):
        self.cursorVisibility(-1, isShow)

    @property
    def soundManager(self):
        return self.__soundManager

    def selectPlayer(self, cid, vehId):
        player = BigWorld.player()
        if isPlayerAvatar():
            player.selectPlayer(int(vehId))

    def onDenunciationReceived(self, _, uid, userName, topic):
        topicID = self.DENUNCIATIONS.get(topic)
        if topicID is not None:
            self.__makeDenunciation(uid, userName, topicID)
        return

    def __makeDenunciation(self, uid, userName, topicID):
        player = BigWorld.player()
        violatorKind = constants.VIOLATOR_KIND.UNKNOWN
        for id, p in player.arena.vehicles.iteritems():
            if p['accountDBID'] == uid:
                violatorKind = constants.VIOLATOR_KIND.ALLY if player.team == p['team'] else constants.VIOLATOR_KIND.ENEMY

        player.makeDenunciation(uid, topicID, violatorKind)
        self.__arenaCtrl.invalidateGUI()
        topicStr = makeString('#menu:denunciation/%d' % topicID)
        message = makeString('#system_messages:denunciation/success') % {'name': userName,
         'topic': topicStr}
        MessengerEntry.g_instance.gui.addClientMessage(g_settings.htmlTemplates.format('battleErrorMessage', ctx={'error': message}))

    def onPostmortemVehicleChanged(self, id):
        if self.__cameraVehicleID == id:
            return
        else:
            self.__cameraVehicleID = id
            self.__arenaCtrl.invalidateGUI(not g_sessionProvider.getCtx().isPlayerObserver())
            g_sessionProvider.getVehicleStateCtrl().switchToAnother(id)
            self._hideVehicleTimer('ALL')
            self.hideDeathzoneTimer('ALL')
            self.__vErrorsPanel.clear()
            self.__vMsgsPanel.clear()
            aim = BigWorld.player().inputHandler.aim
            if aim is not None:
                aim.updateAmmoState(True)
            return

    def onCameraChanged(self, cameraMode, curVehID = None):
        LOG_DEBUG('onCameraChanged', cameraMode, curVehID)
        if self.__cameraMode == 'mapcase':
            self.setAimingMode(False)
        elif cameraMode == 'mapcase':
            self.setAimingMode(True)
        self.__cameraMode = cameraMode

        def setVisible(cname):
            m = self.getMember(cname)
            if m is not None:
                m.visible = cameraMode != 'video'
            return

        if self.__isGuiShown():
            self.damagePanel.showAll(cameraMode != 'video')
            setVisible('vehicleMessagesPanel')
            setVisible('vehicleErrorsPanel')
        if cameraMode == 'video':
            self.__cameraVehicleID = -1
            self.__vErrorsPanel.clear()
            self.__vMsgsPanel.clear()
            self._hideVehicleTimer('ALL')
            self.hideDeathzoneTimer('ALL')
            aim = BigWorld.player().inputHandler.aim
            if aim is not None:
                aim.updateAmmoState(True)
        aim = BigWorld.player().inputHandler.aim
        if aim is not None:
            aim.onCameraChange()
        return

    def __isGuiShown(self):
        m = self.getMember('_root')
        if m is not None and callable(m.isGuiVisible):
            return m.isGuiVisible()
        else:
            return False

    def _showVehicleTimer(self, value):
        code, time, warnLvl = value
        LOG_DEBUG('show vehicles destroy timer', code, time, warnLvl)
        self.call('destroyTimer.show', [self.VEHICLE_DESTROY_TIMER[code], time, warnLvl])

    def _hideVehicleTimer(self, code):
        LOG_DEBUG('hide vehicles destroy timer', code)
        self.call('destroyTimer.hide', [self.VEHICLE_DESTROY_TIMER[code]])

    def showDeathzoneTimer(self, value):
        zoneID, time, warnLvl = value
        if self.__timerSound is not None:
            self.__timerSound.stop()
            self.__timerSound = None
        sound = self.__timerSounds.get(zoneID, {}).get(warnLvl)
        if sound is not None:
            self.__timerSound = sound
            self.__timerSound.play()
        msg = '#fallout:gasAttackTimer/%s' % warnLvl
        LOG_DEBUG('show vehicles deathzone timer', zoneID, time, warnLvl, msg)
        self.call('destroyTimer.show', [self.VEHICLE_DEATHZONE_TIMER[zoneID],
         time,
         warnLvl,
         msg])
        return

    def hideDeathzoneTimer(self, zoneID):
        if self.__timerSound is not None:
            self.__timerSound.stop()
            self.__timerSound = None
        LOG_DEBUG('hide vehicles deathzone timer', zoneID)
        self.call('destroyTimer.hide', [self.VEHICLE_DEATHZONE_TIMER[zoneID]])
        return

    def _showSixthSenseIndicator(self, isShow):
        self.call('sixthSenseIndicator.show', [isShow])

    def setVisible(self, bool):
        LOG_DEBUG('[Battle] visible', bool)
        self.component.visible = bool

    def afterCreate(self):
        event = events.AppLifeCycleEvent
        g_eventBus.handleEvent(event(self.__ns, event.INITIALIZING))
        player = BigWorld.player()
        voice = VoiceChatInterface.g_instance
        LOG_DEBUG('[Battle] afterCreate')
        setattr(self.movie, '_global.wg_isShowLanguageBar', GUI_SETTINGS.isShowLanguageBar)
        setattr(self.movie, '_global.wg_isShowServerStats', constants.IS_SHOW_SERVER_STATS)
        setattr(self.movie, '_global.wg_isShowVoiceChat', GUI_SETTINGS.voiceChat)
        setattr(self.movie, '_global.wg_voiceChatProvider', voice.voiceChatProvider)
        setattr(self.movie, '_global.wg_isChina', constants.IS_CHINA)
        setattr(self.movie, '_global.wg_isKorea', constants.IS_KOREA)
        setattr(self.movie, '_global.wg_isReplayPlaying', BattleReplay.g_replayCtrl.isPlaying)
        BattleWindow.afterCreate(self)
        addListener = g_eventBus.addListener
        addListener(events.GameEvent.HELP, self.toggleHelpWindow, scope=_SCOPE)
        addListener(events.GameEvent.GUI_VISIBILITY, self.showAll, scope=_SCOPE)
        player.inputHandler.onPostmortemVehicleChanged += self.onPostmortemVehicleChanged
        player.inputHandler.onCameraChanged += self.onCameraChanged
        g_settingsCore.onSettingsChanged += self.__accs_onSettingsChanged
        g_settingsCore.interfaceScale.onScaleChanged += self.__onRecreateDevice
        isMutlipleTeams = g_sessionProvider.getArenaDP().isMultipleTeams()
        isEvent = isEventBattle()
        self.proxy = weakref.proxy(self)
        self.__battle_flashObject = self.proxy.getMember('_level0')
        if self.__battle_flashObject:
            self.__battle_flashObject.resync()
        voice.populateUI(self.proxy)
        voice.onPlayerSpeaking += self.setPlayerSpeaking
        voice.onVoiceChatInitFailed += self.onVoiceChatInitFailed
        self.colorManager = ColorSchemeManager._ColorSchemeManager()
        self.colorManager.populateUI(self.proxy)
        self.movingText = MovingText()
        self.movingText.populateUI(self.proxy)
        self.__settingsInterface = SettingsInterface()
        self.__settingsInterface.populateUI(self.proxy)
        self.__soundManager = SoundManager()
        self.__soundManager.populateUI(self.proxy)
        self.__timersBar = TimersBar(self.proxy, isEvent)
        self.__teamBasesPanel = TeamBasesPanel(self.proxy)
        self.__debugPanel = DebugPanel(self.proxy)
        self.__consumablesPanel = ConsumablesPanel(self.proxy)
        self.__damagePanel = DamagePanel(self.proxy)
        self.__markersManager = MarkersManager(self.proxy)
        self.__ingameHelp = IngameHelp(self.proxy)
        self.__minimap = Minimap(self.proxy)
        self.__radialMenu = RadialMenu(self.proxy)
        self.__ribbonsPanel = BattleRibbonsPanel(self.proxy)
        self.__indicators = IndicatorsCollection()
        self.__ppSwitcher = PlayersPanelsSwitcher(self.proxy)
        isColorBlind = g_settingsCore.getSetting('isColorBlind')
        self.__leftPlayersPanel = playersPanelFactory(self.proxy, True, isColorBlind, isEvent, isMutlipleTeams)
        self.__rightPlayersPanel = playersPanelFactory(self.proxy, False, isColorBlind, isEvent, isMutlipleTeams)
        self.__damageInfoPanel = VehicleDamageInfoPanel(self.proxy)
        self.__fragCorrelation = scorePanelFactory(self.proxy, isEvent, isMutlipleTeams)
        self.__statsForm = statsFormFactory(self.proxy, isEvent, isMutlipleTeams)
        self.__plugins.init()
        self.isVehicleCountersVisible = g_settingsCore.getSetting('showVehiclesCounter')
        self.__fragCorrelation.showVehiclesCounter(self.isVehicleCountersVisible)
        self.__vErrorsPanel = VehicleErrorMessages(self.proxy)
        self.__vMsgsPanel = VehicleMessages(self.proxy)
        self.__pMsgsPanel = PlayerMessages(self.proxy)
        self.__plugins.start()
        self.__debugPanel.start()
        self.__consumablesPanel.start()
        self.__damagePanel.start()
        self.__ingameHelp.start()
        self.__vErrorsPanel.start()
        self.__vMsgsPanel.start()
        self.__pMsgsPanel.start()
        self.__markersManager.start()
        self.__markersManager.setMarkerDuration(GUI_SETTINGS.markerHitSplashDuration)
        markers = {'enemy': g_settingsCore.getSetting('enemy'),
         'dead': g_settingsCore.getSetting('dead'),
         'ally': g_settingsCore.getSetting('ally')}
        self.__markersManager.setMarkerSettings(markers)
        MessengerEntry.g_instance.gui.invoke('populateUI', self.proxy)
        g_guiResetters.add(self.__onRecreateDevice)
        g_repeatKeyHandlers.add(self.component.handleKeyEvent)
        self.__onRecreateDevice()
        self.__statsForm.populate()
        self.__leftPlayersPanel.populateUI(self.proxy)
        self.__rightPlayersPanel.populateUI(self.proxy)
        if BattleReplay.g_replayCtrl.isPlaying:
            BattleReplay.g_replayCtrl.onBattleSwfLoaded()
        self.__populateData(isMutlipleTeams)
        self.__minimap.start()
        self.__radialMenu.setSettings(self.__settingsInterface)
        self.__radialMenu.populateUI(self.proxy)
        self.__ribbonsPanel.start()
        g_sessionProvider.setBattleUI(self)
        self.__arenaCtrl = battleArenaControllerFactory(self, isEvent, isMutlipleTeams)
        g_sessionProvider.addArenaCtrl(self.__arenaCtrl)
        self.updateFlagsColor()
        self.movie.setFocussed(SCALEFORM_SWF_PATH)
        self.call('battle.initDynamicSquad', self.__getDynamicSquadsInitParams(disableAlly=BattleReplay.g_replayCtrl.isPlaying))
        self.call('sixthSenseIndicator.setDuration', [GUI_SETTINGS.sixthSenseDuration])
        g_tankActiveCamouflage[player.vehicleTypeDescriptor.type.compactDescr] = self.__arena.arenaType.vehicleCamouflageKind
        keyCode = CommandMapping.g_instance.get('CMD_VOICECHAT_MUTE')
        if not BigWorld.isKeyDown(keyCode):
            VOIP.getVOIPManager().setMicMute(True)
        ctrl = g_sessionProvider.getVehicleStateCtrl()
        ctrl.onVehicleStateUpdated += self.__onVehicleStateUpdated
        ctrl.onPostMortemSwitched += self.__onPostMortemSwitched
        self.__dynSquadListener = DynSquadViewListener(self.proxy)
        g_eventBus.handleEvent(event(self.__ns, event.INITIALIZED))

    def beforeDelete(self):
        LOG_DEBUG('[Battle] beforeDelete')
        removeListener = g_eventBus.removeListener
        removeListener(events.GameEvent.HELP, self.toggleHelpWindow, scope=_SCOPE)
        removeListener(events.GameEvent.GUI_VISIBILITY, self.showAll, scope=_SCOPE)
        ctrl = g_sessionProvider.getVehicleStateCtrl()
        ctrl.onVehicleStateUpdated -= self.__onVehicleStateUpdated
        ctrl.onPostMortemSwitched -= self.__onPostMortemSwitched
        player = BigWorld.player()
        if player and player.inputHandler:
            player.inputHandler.onPostmortemVehicleChanged -= self.onPostmortemVehicleChanged
            player.inputHandler.onCameraChanged -= self.onCameraChanged
        if self.colorManager:
            self.colorManager.dispossessUI()
        voice = VoiceChatInterface.g_instance
        if voice:
            voice.dispossessUI(self.proxy)
            voice.onPlayerSpeaking -= self.setPlayerSpeaking
            voice.onVoiceChatInitFailed -= self.onVoiceChatInitFailed
        if self.__plugins is not None:
            self.__plugins.stop()
            self.__plugins.fini()
            self.__plugins = None
        if self.movingText is not None:
            self.movingText.dispossessUI()
            self.movingText = None
        if self.__timerSound is not None:
            self.__timerSound.stop()
            self.__timerSound = None
        if self.__soundManager is not None:
            self.__soundManager.dispossessUI()
            self.__soundManager = None
        if self.colorManager is not None:
            self.colorManager.dispossessUI()
            self.colorManager = None
        if self.component:
            g_repeatKeyHandlers.discard(self.component.handleKeyEvent)
        g_settingsCore.onSettingsChanged -= self.__accs_onSettingsChanged
        g_settingsCore.interfaceScale.onScaleChanged -= self.__onRecreateDevice
        self.__timersBar.destroy()
        self.__teamBasesPanel.destroy()
        self.__debugPanel.destroy()
        self.__consumablesPanel.destroy()
        self.__damagePanel.destroy()
        self.__markersManager.destroy()
        self.__ingameHelp.destroy()
        self.__vErrorsPanel.destroy()
        self.__vMsgsPanel.destroy()
        self.__pMsgsPanel.destroy()
        self.__radialMenu.destroy()
        self.__minimap.destroy()
        self.__ribbonsPanel.destroy()
        self.__fragCorrelation.destroy()
        self.__statsForm.destroy()
        g_sessionProvider.clearBattleUI()
        if self.__arenaCtrl is not None:
            g_sessionProvider.removeArenaCtrl(self.__arenaCtrl)
            self.__arenaCtrl.clear()
            self.__arenaCtrl = None
        self.__ppSwitcher.destroy()
        self.__leftPlayersPanel.dispossessUI()
        self.__rightPlayersPanel.dispossessUI()
        MessengerEntry.g_instance.gui.invoke('dispossessUI')
        self.__arena = None
        g_guiResetters.discard(self.__onRecreateDevice)
        self.__settingsInterface.dispossessUI()
        self.__settingsInterface = None
        VoiceChatInterface.g_instance.onVoiceChatInitFailed -= self.onVoiceChatInitFailed
        if self.__dynSquadListener:
            self.__dynSquadListener.destroy()
            self.__dynSquadListener = None
        BattleWindow.beforeDelete(self)
        event = events.AppLifeCycleEvent
        g_eventBus.handleEvent(event(self.__ns, event.DESTROYED))
        return

    def __onVehicleStateUpdated(self, state, value):
        if state not in self.__stateHandlers:
            return
        else:
            handler = getattr(self, self.__stateHandlers[state], None)
            if handler and callable(handler):
                if value is not None:
                    handler(value)
                else:
                    handler()
            return

    def _setFireInVehicle(self, bool):
        self.call('destroyTimer.onFireInVehicle', [bool])

    def onVoiceChatInitFailed(self):
        if GUI_SETTINGS.voiceChat:
            self.call('VoiceChat.initFailed', [])

    def clearCommands(self):
        pass

    def bindCommands(self):
        self.__consumablesPanel.bindCommands()
        self.__ingameHelp.buildCmdMapping()

    def updateFlagsColor(self):
        isColorBlind = g_settingsCore.getSetting('isColorBlind')
        colorGreen = self.colorManager.getSubScheme('flag_team_green', isColorBlind=isColorBlind)['rgba']
        colorRed = self.colorManager.getSubScheme('flag_team_red', isColorBlind=isColorBlind)['rgba']
        arenaDP = g_sessionProvider.getArenaDP()
        teamsOnArena = arenaDP.getTeamsOnArena()
        for teamIdx in teamsOnArena:
            color = colorGreen if arenaDP.isAllyTeam(teamIdx) else colorRed
            BigWorld.wg_setFlagColor(teamIdx, color / 255)

        for teamIdx in [0] + teamsOnArena:
            BigWorld.wg_setFlagEmblem(teamIdx, 'system/maps/wg_emblem.dds', Math.Vector4(0.0, 0.1, 0.5, 0.9))

    def setPlayerSpeaking(self, accountDBID, flag):
        self.__callEx('setPlayerSpeaking', [accountDBID, flag])
        vID = g_sessionProvider.getCtx().getVehIDByAccDBID(accountDBID)
        if vID > 0:
            self.__markersManager.showDynamic(vID, flag)

    def isPlayerSpeaking(self, accountDBID):
        return VoiceChatInterface.g_instance.isPlayerSpeaking(accountDBID)

    def __onPostMortemSwitched(self):
        LogitechMonitor.onScreenChange('postmortem')
        if self.radialMenu is not None:
            self.radialMenu.forcedHide()
        if not g_sessionProvider.getCtx().isPlayerObserver():
            self.__callEx('showPostmortemTips', [1.0, 5.0, 1.0])
        return

    def cursorVisibility(self, callbackId, visible, x = None, y = None, customCall = False, enableAiming = True):
        if visible:
            g_cursorDelegator.syncMousePosition(self, x, y, customCall)
        else:
            g_cursorDelegator.restoreMousePosition()
        if BigWorld.player() is not None and isPlayerAvatar():
            BigWorld.player().setForcedGuiControlMode(visible, False, enableAiming)
        return

    def tryLeaveRequest(self, _):
        resStr = 'quitBattle'
        replayCtrl = BattleReplay.g_replayCtrl
        player = BigWorld.player()
        isVehicleAlive = getattr(player, 'isVehicleAlive', False)
        isNotTraining = self.__arena.guiType != constants.ARENA_GUI_TYPE.TRAINING
        isNotEventBattle = self.__arena.guiType != constants.ARENA_GUI_TYPE.EVENT_BATTLES
        if not replayCtrl.isPlaying:
            if constants.IS_KOREA and gui.GUI_SETTINGS.igrEnabled and self.__arena is not None and isNotTraining:
                vehicleID = getattr(player, 'playerVehicleID', -1)
                if vehicleID in self.__arena.vehicles:
                    vehicle = self.__arena.vehicles[vehicleID]
                    if isVehicleAlive and vehicle.get('igrType') != constants.IGR_TYPE.NONE:
                        resStr = 'quitBattleIGR'
                else:
                    LOG_ERROR("Player's vehicle not found", vehicleID)
            isDeserter = isVehicleAlive and isNotTraining and isNotEventBattle
            if isDeserter:
                resStr += '/deserter'
        else:
            isDeserter = False
        self.__callEx('tryLeaveResponse', [resStr, isDeserter])
        return

    def onExitBattle(self, _):
        arena = getattr(BigWorld.player(), 'arena', None)
        LOG_DEBUG('onExitBattle', arena)
        if arena:
            BigWorld.player().leaveArena()
        return

    def toggleHelpWindow(self, _):
        self.__callEx('showHideHelp', [not self.__isHelpWindowShown])

    def setAimingMode(self, isAiming):
        self.__callEx('setAimingMode', [isAiming])

    def helpDialogOpenStatus(self, cid, isOpened):
        self.__isHelpWindowShown = isOpened

    def _initLobbyDialog(self, cid):
        if connectionManager.serverUserName:
            tooltipBody = i18n.makeString('#tooltips:header/info/players_online_full/body')
            tooltipFullData = makeTooltip('#tooltips:header/info/players_online_full/header', tooltipBody % {'servername': connectionManager.serverUserName})
            self.__callEx('setServerStatsInfo', [tooltipFullData])
            self.__callEx('setServerName', [connectionManager.serverUserName])
            if constants.IS_SHOW_SERVER_STATS:
                stats = game_control.g_instance.serverStats.getStats()
                if 'clusterCCU' in stats and 'regionCCU' in stats:
                    self.__callEx('setServerStats', [stats['clusterCCU'], stats['regionCCU']])
                else:
                    self.__callEx('setServerStats', [None, None])
        else:
            self.__callEx('setServerName', ['-'])
        links = GUI_SETTINGS.reportBugLinks
        if len(links):
            reportBugButton = makeHyperLink('ingameMenu', MENU.INGAME_MENU_LINKS_REPORT_BUG)
            self.__callEx('setReportBugLink', [reportBugButton])
        return

    def reportBug(self, _):
        reportBugOpenConfirm(g_sessionProvider.getArenaDP().getVehicleInfo().player.accountDBID)

    def __getDynamicSquadsInitParams(self, disableAlly = False, disableEnemy = True):
        isAllyEnabled = self.__arena.guiType == constants.ARENA_GUI_TYPE.RANDOM and not disableAlly
        isEnemyEnabled = not disableEnemy
        return [isAllyEnabled, isEnemyEnabled]

    def __populateData(self, isMutlipleTeams = False):
        arena = avatar_getter.getArena()
        arenaDP = g_sessionProvider.getArenaDP()
        arenaData = ['',
         0,
         '',
         '',
         '']
        if arena:
            arenaData = [toUpper(arena.arenaType.name)]
            descExtra = getPrebattleFullDescription(arena.extraData or {})
            arenaSubType = getArenaSubTypeName(BigWorld.player().arenaTypeID)
            if descExtra:
                arenaData.extend([arena.guiType + 1, descExtra])
            elif arena.guiType in [constants.ARENA_GUI_TYPE.RANDOM, constants.ARENA_GUI_TYPE.TRAINING]:
                arenaTypeName = '#arenas:type/%s/name' % arenaSubType
                arenaData.extend([getNecessaryArenaFrameName(arenaSubType, isBaseExists(BigWorld.player().arenaTypeID, BigWorld.player().team)), arenaTypeName])
            elif arena.guiType in constants.ARENA_GUI_TYPE.RANGE:
                arenaData.append(constants.ARENA_GUI_TYPE_LABEL.LABELS[arena.guiType])
                if arena.guiType == constants.ARENA_GUI_TYPE.EVENT_BATTLES and hasResourcePoints():
                    arenaData.append(i18n.makeString(MENU.LOADING_BATTLETYPES_RESOURCEPOINTS_UPPER))
                elif arena.guiType == constants.ARENA_GUI_TYPE.EVENT_BATTLES and isMutlipleTeams:
                    arenaData.append(i18n.makeString(MENU.LOADING_BATTLETYPES_MIX_UPPER))
                else:
                    arenaData.append('#menu:loading/battleTypes/%d' % arena.guiType)
            else:
                arenaData.extend([arena.guiType + 1, '#menu:loading/battleTypes/%d' % arena.guiType])
            myTeamNumber = arenaDP.getNumberOfTeam()
            getTeamName = g_sessionProvider.getCtx().getTeamName
            arenaData.extend([getTeamName(myTeamNumber), getTeamName(arenaDP.getNumberOfTeam(enemy=True))])
            teamHasBase = 1 if isBaseExists(BigWorld.player().arenaTypeID, myTeamNumber) else 2
            if not isEventBattle():
                typeEvent = 'normal'
                winText = getBattleSubTypeWinText(BigWorld.player().arenaTypeID, teamHasBase)
            else:
                typeEvent = 'fallout'
                if getIsMultiteam():
                    winText = i18n.makeString(ARENAS.TYPE_FALLOUTMUTLITEAM_DESCRIPTION)
                else:
                    winText = i18n.makeString('#arenas:type/%s/description' % arenaSubType)
            arenaData.append(winText)
            arenaData.append(typeEvent)
            arenaData.extend(_getQuestsTipData(arena, arenaDP))
            arenaData.extend([getArenaIcon(_SMALL_MAP_SOURCE)])
        self.__callEx('arenaData', arenaData)

    def __onRecreateDevice(self, scale = None):
        params = list(GUI.screenResolution())
        params.append(g_settingsCore.interfaceScale.get())
        self.call('Stage.Update', params)
        self.__markersManager.updateMarkersScale()

    def invalidateGUI(self):
        arenaCtrl = getattr(self, '_Battle__arenaCtrl', None)
        if arenaCtrl is not None:
            arenaCtrl.invalidateGUI()
        return

    def __callEx(self, funcName, args = None):
        self.call('battle.' + funcName, args)

    def __accs_onSettingsChanged(self, diff):
        self.colorManager.update()
        if 'isColorBlind' in diff:
            isColorBlind = diff['isColorBlind']
            self.__leftPlayersPanel.defineColorFlags(isColorBlind=isColorBlind)
            self.__rightPlayersPanel.defineColorFlags(isColorBlind=isColorBlind)
            self.updateFlagsColor()
            self.__markersManager.updateMarkers()
            self.__minimap.updateEntries()
        if 'enemy' in diff or 'dead' in diff or 'ally' in diff:
            markers = {'enemy': g_settingsCore.getSetting('enemy'),
             'dead': g_settingsCore.getSetting('dead'),
             'ally': g_settingsCore.getSetting('ally')}
            self.__markersManager.setMarkerSettings(markers)
            self.__markersManager.updateMarkerSettings()
        if 'showVehiclesCounter' in diff:
            self.isVehicleCountersVisible = diff['showVehiclesCounter']
            self.__fragCorrelation.showVehiclesCounter(self.isVehicleCountersVisible)
        if 'interfaceScale' in diff:
            self.__onRecreateDevice()
        self.__arenaCtrl.invalidateGUI()
        self.__arenaCtrl.invalidateArenaInfo()

    def setTeamValuesData(self, data):
        if self.__battle_flashObject is not None:
            self.__battle_flashObject.setTeamValues(data)
        return

    def setMultiteamValues(self, data):
        if self.__battle_flashObject is not None:
            self.__battle_flashObject.setMultiteamValues(data)
        return

    def getPlayerNameLength(self, isEnemy):
        panel = self.rightPlayersPanel if isEnemy else self.leftPlayersPanel
        return panel.getPlayerNameLength()

    def getVehicleNameLength(self, isEnemy):
        panel = self.rightPlayersPanel if isEnemy else self.leftPlayersPanel
        return panel.getVehicleNameLength()
Ejemplo n.º 4
0
class CrosshairPanel(Flash.Flash, CrosshairPanelMeta):
    """Class is UI component of crosshair panel. It provides access to Action Script."""

    def __init__(self):
        super(CrosshairPanel, self).__init__('crosshairPanel.swf', className=_CROSSHAIR_PANEL_COMPONENT, path=SCALEFORM_SWF_PATH_V3)
        self.__plugins = PluginsCollection(self)
        self.__plugins.addPlugins({'core': CorePlugin,
         'settings': SettingsPlugin,
         'events': EventBusPlugin,
         'ammo': AmmoPlugin,
         'vehicleState': VehicleStatePlugin,
         'targetDistance': TargetDistancePlugin,
         'gunMarkerDistance': GunMarkerDistancePlugin})
        self.__viewID = CROSSHAIR_VIEW_ID.UNDEFINED
        self.__zoomFactor = 0.0
        self.__distance = 0
        self.__hasAmmo = True
        self.__configure()
        self.__daapiBridge = DAAPIRootBridge(rootPath='root.g_modeMC', initCallback='registerCrosshairPanel')
        self.__daapiBridge.setPyScript(weakref.proxy(self))

    def close(self):
        if self.__daapiBridge is not None:
            self.__daapiBridge.clear()
            self.__daapiBridge = None
        super(CrosshairPanel, self).close()
        return

    def isVisible(self):
        """Is component visible.
        :return: bool.
        """
        return self.component.visible

    def setVisible(self, visible):
        """Sets visibility of component.
        :param visible: bool.
        """
        self.component.visible = visible

    def getViewID(self):
        """Gets current view ID of panel.
        :return: integer containing of CROSSHAIR_VIEW_ID.
        """
        return self.__viewID

    def setViewID(self, viewID):
        """Sets view ID of panel to change view presentation.
        :param viewID:
        """
        if viewID != self.__viewID:
            self.__viewID = viewID
            self.as_setViewS(viewID)

    def getSize(self):
        """Gets size of crosshair panel.
        :return: tuple(width, height).
        """
        return self.component.size

    def setSize(self, width, height):
        """Sets size of crosshair panel in pixels.
        :param width: integer containing width of panel.
        :param height: integer containing height of panel.
        """
        self.component.size = (width, height)

    def setPosition(self, x, y):
        """Sets position of crosshair panel in pixels.
        :param x: integer containing x coordinate of center in pixels.
        :param y: integer containing y coordinate of center in pixels.
        """
        self.as_recreateDeviceS(x, y)

    def getScale(self):
        """Gets scale factor.
        :return: float containing scale factor.
        """
        return self.movie.stage.scaleX

    def setScale(self, scale):
        """Sets scale factor.
        :param scale: float containing new scale factor.
        """
        self.movie.stage.scaleX = scale
        self.movie.stage.scaleY = scale

    def getZoom(self):
        """Gets current zoom factor of player's camera.
        :return: float containing zoom factor.
        """
        return self.__zoomFactor

    def setZoom(self, zoomFactor):
        """Gets current zoom factor of player's camera.
        :param zoomFactor: float containing zoom factor.
        """
        if zoomFactor == self.__zoomFactor:
            return
        self.__zoomFactor = zoomFactor
        if zoomFactor > 1:
            zoomString = i18n.makeString(INGAME_GUI.AIM_ZOOM, zoom=zoomFactor)
        else:
            zoomString = ''
        self.as_setZoomS(zoomString)

    def getDistance(self):
        """Gets distance to desired target(point).
        :return: integer containing distance in meters.
        """
        return self.__distance

    def setDistance(self, distance):
        """Sets distance to desired target(point).
        :param distance: integer containing distance in meters.
        """
        if distance != self.__distance:
            self.__distance = distance
            self.as_setDistanceS(i18n.makeString(INGAME_GUI.DISTANCE_METERS, meters=distance))

    def clearDistance(self, immediate = True):
        """Removes distance string from UI.
        :param immediate: if value equals True than removes distance string from UI immediately,
            otherwise - hides this sting with animation.
        """
        self.__distance = 0
        self.as_clearDistanceS(immediate)

    def setHasAmmo(self, hasAmmo):
        """Sets flag that indicates controlling vehicle has ammo.
        :param hasAmmo: bool.
        """
        if self.__hasAmmo != hasAmmo:
            self.__hasAmmo = hasAmmo
            if not hasAmmo:
                self.as_updateAmmoStateS(i18n.makeString(INGAME_GUI.PLAYER_MESSAGES_POSTMORTEM_USERNOHASAMMO))
            else:
                self.as_updateAmmoStateS('')

    def setGunMarkerPosition(self, position, relaxTime):
        """Sets new position of gun marker. This value is transferred to cpp component.
        :param position: vector3
        :param relaxTime: float.
        """
        self.component.updateMarkerPos(position, relaxTime)

    def _populate(self):
        super(CrosshairPanel, self)._populate()
        self.__plugins.init()
        self.__plugins.start()

    def _dispose(self):
        self.__plugins.stop()
        self.__plugins.fini()
        super(CrosshairPanel, self)._dispose()

    def __configure(self):
        self.component.wg_inputKeyMode = 2
        self.component.position.z = DEPTH_OF_Aim
        self.component.focus = False
        self.component.moveFocus = False
        self.component.heightMode = 'PIXEL'
        self.component.widthMode = 'PIXEL'
        self.movie.backgroundAlpha = 0
Ejemplo n.º 5
0
class MarkersManager(ExternalFlashComponent, VehicleMarkersManagerMeta,
                     plugins.IMarkersManager):
    """ Represents gui markers always displayed on top of the scene.
    Note: The pipeline is very similar to the minimap's pipeline. I.e. We request C++ flash UI
    component called WGVehicleMarkersCanvasFlash for creating and deleting markers by markerID (int).
    Access to an individual marker also performed via that markerID. We can directly
    invoke any flash function of each marker. The same is true for the whole manager object.
    For more details see the C++ class realization.
    """
    def __init__(self):
        super(MarkersManager, self).__init__(
            ExternalFlashSettings(BATTLE_VIEW_ALIASES.MARKERS_2D,
                                  settings.MARKERS_MANAGER_SWF,
                                  'root.vehicleMarkersCanvas',
                                  'registerMarkersManager'))
        self.component.wg_inputKeyMode = 2
        self.component.position.z = DEPTH_OF_VehicleMarker
        self.component.drawWithRestrictedViewPort = False
        self.movie.backgroundAlpha = 0
        self.__plugins = None
        self.__canvas = None
        self.__ids = set()
        return

    def setScaleProps(self,
                      minScale=40,
                      maxScale=100,
                      defScale=100,
                      speed=3.0):
        """Sets properties of scale for markers.
        :param minScale: minimum value of scale for markers.
        :param maxScale: maximum value of scale for markers.
        :param defScale: default value of scale for markers.
        :param speed: rate of decrease with distance to markers.
        """
        self.__canvas.scaleProperties = (minScale, maxScale, defScale, speed)

    def setAlphaProps(self,
                      minAlpha=40,
                      maxAlpha=100,
                      defAlpha=100,
                      speed=3.0):
        self.__canvas.alphaProperties = (minAlpha, maxAlpha, defAlpha, speed)

    def setMarkerSettings(self, markerSettings, notify=False):
        """ Sets new markers settings.
        :param markerSettings: dictionary containing markers settings.
        :param notify: if value equals True, than view of markers can be updated to check settings.
        """
        self.as_setMarkerSettingsS(markerSettings)
        if notify:
            self.as_updateMarkersSettingsS()

    def setColorsSchemes(self, defaultSchemes, colorBlindSchemes):
        """Sets new colors schemes of markers.
        :param defaultSchemes: dictionary containing colors schemes
            if player does not use setting "colorBlind".
        :param colorBlindSchemes: dictionary containing colors schemes
            if player uses setting "colorBlind".
        """
        self.as_setColorSchemesS(defaultSchemes, colorBlindSchemes)

    def setColorBlindFlag(self, isColorBlind):
        """ Sets setting "colorBlind".
        :param isColorBlind: bool.
        """
        self.as_setColorBlindS(isColorBlind)

    def setShowExInfoFlag(self, flag):
        """Show extended vehicle information. For example, player presses [Left Alt] key.
        :param flag: bool.
        Vehicle marker consists:
            - vehicle type (permanent);
            - nickname (extended);
            - health bar (extended);
            - vehicle name (extended);
            - vehicle level (extended and configure in settings);
            - vehicle icon (extended and configure in settings).
        """
        if self.owner is None or not self.owner.isModalViewShown():
            self.as_setShowExInfoFlagS(flag)
        return

    def createMarker(self, symbol, matrixProvider=None, active=True):
        """ Create Marker object and view in Flash by providing Matrix.
        :param symbol: string containing symbol of marker.
        :param matrixProvider: instance of matrix provider or None.
        :param active: bool.
        :return: integer containing unique ID of marker.
        """
        if active and matrixProvider is None:
            raise ValueError(
                'Active marker {} must has matrixProvider'.format(symbol))
        markerID = self.__canvas.addMarker(matrixProvider, symbol, active)
        self.__ids.add(markerID)
        return markerID

    def setMarkerActive(self, markerID, active):
        """Sets active flag (visible property) to marker.
        :param markerID: marker handle
        :param active: is entry active (visible).
        """
        raise markerID in self.__ids or AssertionError(
            'Marker is not added by given ID')
        self.__canvas.markerSetActive(markerID, active)

    def setMarkerMatrix(self, markerID, matrix):
        """Sets new matrix to specified marker.
        :param markerID: integer containing unique ID of marker.
        :param matrix: instance of Matrix or MatrixProvider.
        """
        raise markerID in self.__ids or AssertionError(
            'Marker is not added by given ID')
        self.__canvas.markerSetMatrix(markerID, matrix)

    def destroyMarker(self, markerID):
        """Destroys 2D marker.
        :param markerID: integer containing unique ID of marker.
        """
        if not (self.__canvas and markerID in self.__ids):
            raise AssertionError('Marker is not added by given ID')
            self.__canvas.delMarker(markerID)
            self.__ids.discard(markerID)

    def invokeMarker(self, markerID, *signature):
        """Invokes desired method of marker in the Action Script.
        :param markerID: integer containing unique ID of marker.
        :param signature: tuple(<name of method in the Action Script>, *args)
        """
        raise markerID in self.__ids or AssertionError(
            'Marker is not added by given ID')
        self.__canvas.markerInvoke(markerID, signature)

    def getPlugin(self, name):
        """Gets plugin by name.
        :param name: unique name of plugin.
        :return: instance of plugin or None.
        """
        if self.__plugins is not None:
            return self.__plugins.getPlugin(name)
        else:
            return
            return

    def startPlugins(self):
        sessionProvider = dependency.instance(IBattleSessionProvider)
        raise sessionProvider is not None or AssertionError(
            'Session provider can not be None')
        arenaVisitor = sessionProvider.arenaVisitor
        raise arenaVisitor is not None or AssertionError(
            'Arena visitor can not be None')
        self.__addCanvas(arenaVisitor)
        self.__setMarkerDuration()
        self.__createPlugins(arenaVisitor)
        return

    def stopPlugins(self):
        self.__destroyPlugins()
        self.__removeCanvas()

    def _populate(self):
        super(MarkersManager, self)._populate()
        self.startPlugins()

    def _dispose(self):
        self.stopPlugins()
        super(MarkersManager, self)._dispose()

    def _createCanvas(self, arenaVisitor):
        return GUI.WGVehicleMarkersCanvasFlashAS3(self.movie)

    def _setupPlugins(self, arenaVisitor):
        return {
            'settings': plugins.SettingsPlugin,
            'eventBus': plugins.EventBusPlugin,
            'vehicles': plugins.VehicleMarkerPlugin,
            'equipments': plugins.EquipmentsMarkerPlugin
        }

    def __addCanvas(self, arenaVisitor):
        self.__canvas = self._createCanvas(arenaVisitor)
        self.__canvas.wg_inputKeyMode = 2
        self.__canvas.scaleProperties = GUI_SETTINGS.markerScaleSettings
        self.__canvas.alphaProperties = GUI_SETTINGS.markerBgSettings
        self.__canvasProxy = weakref.ref(self.__canvas)
        self.component.addChild(self.__canvas, 'vehicleMarkersCanvas')

    def __removeCanvas(self):
        if self.__canvas is not None:
            self.component.delChild(self.__canvas)
        self.__canvas = None
        self.__canvasProxy = None
        return

    def __setMarkerDuration(self):
        self.as_setMarkerDurationS(GUI_SETTINGS.markerHitSplashDuration)

    def __createPlugins(self, arenaVisitor):
        setup = self._setupPlugins(arenaVisitor)
        self.__plugins = PluginsCollection(self)
        self.__plugins.addPlugins(setup)
        self.__plugins.init()
        self.__plugins.start()

    def __destroyPlugins(self):
        if self.__plugins is not None:
            self.__plugins.stop()
            self.__plugins.fini()
        return
Ejemplo n.º 6
0
class ConsumablesPanel(object):
    def __init__(self, parentUI):
        self.__ui = parentUI
        self.__flashObject = None
        self.__cds = [None] * PANEL_MAX_LENGTH
        self.__mask = 0
        self.__keys = {}
        self.__currentOrderIdx = -1
        self.__plugins = PluginsCollection(self)
        plugins = {}
        if g_sessionProvider.arenaVisitor.hasRage():
            plugins['rageBar'] = _RageBarPlugin
        self.__plugins.addPlugins(plugins)
        return

    def start(self):
        self.__flashObject = self.__ui.getMember('_level0.consumablesPanel')
        if self.__flashObject:
            self.__flashObject.resync()
            self.__flashObject.script = self
            self.__plugins.init()
            self.__plugins.start()
            visitor = g_sessionProvider.arenaVisitor
            props = _FalloutSlotViewProps(
                useStandardLayout=not visitor.hasRage())
            self.__flashObject.setProperties(visitor.gui.isFalloutBattle(),
                                             props._asdict())
            self.__addListeners()
        else:
            LOG_ERROR('Display object is not found in the swf file.')

    def destroy(self):
        self.__plugins.stop()
        self.__plugins.fini()
        self.__removeListeners()
        self.__keys.clear()
        self.__ui = None
        if self.__flashObject is not None:
            self.__flashObject.script = None
            self.__flashObject = None
        return

    def bindCommands(self):
        keys = {}
        slots = []
        for idx, bwKey, sfKey, handler in self.__getKeysGenerator():
            if handler:
                keys[bwKey] = handler
                slots.append((idx, bwKey, sfKey))

        self.__flashObject.setKeysToSlots(slots)
        self.__keys.clear()
        self.__keys = keys

    def onClickedToSlot(self, bwKey):
        self.__handleBWKey(int(bwKey))

    def onPopUpClosed(self):
        keys = {}
        for idx, bwKey, _, handler in self.__getKeysGenerator():
            if handler:
                keys[bwKey] = handler

        self.__keys.clear()
        self.__keys = keys
        ctrl = g_sessionProvider.shared.vehicleState
        ctrl.onVehicleStateUpdated -= self.__onVehicleStateUpdated

    @property
    def flashObject(self):
        return self.__flashObject

    def __callFlash(self, funcName, args=None):
        self.__ui.call('battle.consumablesPanel.%s' % funcName, args)

    def __addListeners(self):
        vehicleCtrl = g_sessionProvider.shared.vehicleState
        vehicleCtrl.onPostMortemSwitched += self.__onPostMortemSwitched
        vehicleCtrl.onRespawnBaseMoving += self.__onRespawnBaseMoving
        ammoCtrl = g_sessionProvider.shared.ammo
        ammoCtrl.onShellsAdded += self.__onShellsAdded
        ammoCtrl.onShellsUpdated += self.__onShellsUpdated
        ammoCtrl.onNextShellChanged += self.__onNextShellChanged
        ammoCtrl.onCurrentShellChanged += self.__onCurrentShellChanged
        ammoCtrl.onGunReloadTimeSet += self.__onGunReloadTimeSet
        eqCtrl = g_sessionProvider.shared.equipments
        eqCtrl.onEquipmentAdded += self.__onEquipmentAdded
        eqCtrl.onEquipmentUpdated += self.__onEquipmentUpdated
        eqCtrl.onEquipmentCooldownInPercent += self.__onEquipmentCooldownInPercent
        optDevicesCtrl = g_sessionProvider.shared.optionalDevices
        optDevicesCtrl.onOptionalDeviceAdded += self.__onOptionalDeviceAdded
        optDevicesCtrl.onOptionalDeviceUpdated += self.__onOptionalDeviceUpdated
        g_eventBus.addListener(GameEvent.CHOICE_CONSUMABLE,
                               self.__handleConsumableChoice,
                               scope=EVENT_BUS_SCOPE.BATTLE)

    def __removeListeners(self):
        g_eventBus.removeListener(GameEvent.CHOICE_CONSUMABLE,
                                  self.__handleConsumableChoice,
                                  scope=EVENT_BUS_SCOPE.BATTLE)
        vehicleCtrl = g_sessionProvider.shared.vehicleState
        if vehicleCtrl is not None:
            vehicleCtrl.onPostMortemSwitched -= self.__onPostMortemSwitched
            vehicleCtrl.onRespawnBaseMoving -= self.__onRespawnBaseMoving
            vehicleCtrl.onVehicleStateUpdated -= self.__onVehicleStateUpdated
        ammoCtrl = g_sessionProvider.shared.ammo
        if ammoCtrl is not None:
            ammoCtrl.onShellsAdded -= self.__onShellsAdded
            ammoCtrl.onShellsUpdated -= self.__onShellsUpdated
            ammoCtrl.onNextShellChanged -= self.__onNextShellChanged
            ammoCtrl.onCurrentShellChanged -= self.__onCurrentShellChanged
            ammoCtrl.onGunReloadTimeSet -= self.__onGunReloadTimeSet
        eqCtrl = g_sessionProvider.shared.equipments
        if eqCtrl is not None:
            eqCtrl.onEquipmentAdded -= self.__onEquipmentAdded
            eqCtrl.onEquipmentUpdated -= self.__onEquipmentUpdated
            eqCtrl.onEquipmentCooldownInPercent -= self.__onEquipmentCooldownInPercent
        optDevicesCtrl = g_sessionProvider.shared.optionalDevices
        if optDevicesCtrl is not None:
            optDevicesCtrl.onOptionalDeviceAdded -= self.__onOptionalDeviceAdded
            optDevicesCtrl.onOptionalDeviceUpdated -= self.__onOptionalDeviceUpdated
        return

    def __genNextIdx(self, full, start):
        bits = self.__mask & full
        if not bits:
            idx = start
        else:
            idx = int(math.log(bits, 2)) + 1
        raise -1 < idx < PANEL_MAX_LENGTH - 1 or AssertionError
        self.__mask |= 1 << idx
        return idx

    def __genKey(self, idx):
        if not -1 < idx < PANEL_MAX_LENGTH - 1:
            raise AssertionError
            cmdMappingKey = COMMAND_AMMO_CHOICE_MASK.format(
                idx + 1 if idx < 9 else 0)
            bwKey = CommandMapping.g_instance.get(cmdMappingKey)
            sfKey = 0
            sfKey = bwKey is not None and bwKey != 0 and getScaleformKey(bwKey)
        return (bwKey, sfKey)

    def __makeShellTooltip(self, descriptor, piercingPower):
        kind = descriptor['kind']
        header = i18n.makeString(
            '#ingame_gui:shells_kinds/{0:>s}'.format(kind),
            caliber=BigWorld.wg_getNiceNumberFormat(descriptor['caliber']),
            userString=descriptor['userString'])
        body = i18n.makeString('#ingame_gui:shells_kinds/params',
                               damage=str(int(descriptor['damage'][0])),
                               piercingPower=str(piercingPower))
        return TOOLTIP_FORMAT.format(header, body)

    def __getKeysGenerator(self):
        getEquipment = g_sessionProvider.shared.equipments.getEquipment
        for idx, intCD in enumerate(self.__cds):
            if not intCD:
                yield (idx, None, None, None)
            else:
                bwKey, sfKey = self.__genKey(idx)
                handler = None
                if idx in AMMO_RANGE:
                    handler = partial(self.__handleAmmoPressed, intCD)
                elif idx in EQUIPMENT_RANGE or idx in ORDERS_RANGE:
                    item = getEquipment(intCD)
                    if item and item.getTag() and item.getQuantity() > 0:
                        if item.isEntityRequired():
                            handler = partial(self.__handleEquipmentExpanded,
                                              intCD)
                        else:
                            handler = partial(self.__handleEquipmentPressed,
                                              intCD)
                yield (idx, bwKey, sfKey, handler)

        return

    def __handleConsumableChoice(self, event):
        self.__handleBWKey(event.ctx['key'])

    def __handleBWKey(self, bwKey):
        if bwKey in self.__keys:
            handler = self.__keys[bwKey]
            if handler and callable(handler):
                handler()

    def __handleAmmoPressed(self, intCD):
        g_sessionProvider.shared.ammo.changeSetting(intCD)

    def __handleEquipmentPressed(self, intCD, entityName=None):
        ctrl = g_sessionProvider.shared.equipments
        if ctrl is None:
            return
        else:
            result, error = ctrl.changeSetting(intCD,
                                               entityName=entityName,
                                               avatar=BigWorld.player())
            if not result and error:
                self.__ui.vErrorsPanel.showMessage(error.key, error.ctx)
            else:
                self.__flashObject.collapseEquipmentSlot()
            return

    def __handleEquipmentExpanded(self, intCD):
        if not self.__flashObject.getVisibility():
            return
        else:
            ctrl = g_sessionProvider.shared.equipments
            if ctrl is None:
                return
            result, error = ctrl.changeSetting(intCD)
            if not result and error:
                self.__ui.vErrorsPanel.showMessage(error.key, error.ctx)
                return
            if intCD not in self.__cds:
                LOG_ERROR('Equipment is not found in panel', intCD, self.__cds)
                return
            item = ctrl.getEquipment(intCD)
            if not item:
                LOG_ERROR('Equipment is not found in control', intCD)
                return
            slots = []
            keys = {}
            for entityIdx, (itemName, entityName,
                            entityState) in enumerate(item.getGuiIterator()):
                bwKey, sfKey = self.__genKey(entityIdx)
                keys[bwKey] = partial(self.__handleEquipmentPressed, intCD,
                                      entityName)
                slots.append({
                    'bwKeyCode': bwKey,
                    'sfKeyCode': sfKey,
                    'entityName': itemName,
                    'entityState': entityState
                })

            self.__flashObject.expandEquipmentSlot(self.__cds.index(intCD),
                                                   slots)
            self.__keys.clear()
            self.__keys = keys
            ctrl = g_sessionProvider.shared.vehicleState
            if ctrl is not None:
                ctrl.onVehicleStateUpdated += self.__onVehicleStateUpdated
            return

    def __onShellsAdded(self, intCD, descriptor, quantity, _, gunSettings):
        toolTip = self.__makeShellTooltip(
            descriptor, int(gunSettings.getPiercingPower(intCD)))
        icon = descriptor['icon'][0]
        shellIconPath = AMMO_ICON_PATH % icon
        noShellIconPath = NO_AMMO_ICON_PATH % icon
        idx = self.__genNextIdx(AMMO_FULL_MASK, AMMO_START_IDX)
        self.__cds[idx] = intCD
        bwKey, sfKey = self.__genKey(idx)
        self.__keys[bwKey] = partial(self.__handleAmmoPressed, intCD)
        self.__flashObject.addShellSlot(idx, bwKey, sfKey, quantity,
                                        gunSettings.clip.size, shellIconPath,
                                        noShellIconPath, toolTip)

    def __onShellsUpdated(self, intCD, quantity, *args):
        if intCD in self.__cds:
            self.__flashObject.setItemQuantityInSlot(self.__cds.index(intCD),
                                                     quantity)
        else:
            LOG_ERROR('Ammo is not found in panel', intCD, self.__cds)

    def __onNextShellChanged(self, intCD):
        if intCD in self.__cds:
            self.__flashObject.setNextShell(self.__cds.index(intCD))
        else:
            LOG_ERROR('Ammo is not found in panel', intCD, self.__cds)

    def __onCurrentShellChanged(self, intCD):
        if intCD in self.__cds:
            self.__flashObject.setCurrentShell(self.__cds.index(intCD))
        else:
            LOG_ERROR('Ammo is not found in panel', intCD, self.__cds)

    def __onGunReloadTimeSet(self, currShellCD, state):
        if currShellCD in self.__cds:
            index = self.__cds.index(currShellCD)
            valueType = state.getValueType()
            if valueType == GUN_RELOADING_VALUE_TYPE.TIME:
                self.__flashObject.setCoolDownTime(index,
                                                   state.getActualValue())
            elif valueType == GUN_RELOADING_VALUE_TYPE.TIME:
                self.__flashObject.setCoolDownPosAsPercent(
                    index, state.getActualValue())
        else:
            LOG_ERROR('Ammo is not found in panel', currShellCD, self.__cds)

    def __onEquipmentAdded(self, intCD, item):
        if item:
            if item.isAvatar():
                self.__addOrderSlot(intCD, item)
            else:
                self.__addEquipmentSlot(intCD, item)
        else:
            idx = self.__genNextIdx(EQUIPMENT_FULL_MASK + ORDERS_FULL_MASK,
                                    EQUIPMENT_START_IDX)
            self.__cds[idx] = intCD
            self.__flashObject.addEquipmentSlot(idx, None, None, None, 0, 0,
                                                None, EMPTY_EQUIPMENT_TOOLTIP)
            if self.__cds[EQUIPMENT_START_IDX:EQUIPMENT_END_IDX +
                          1] == EMPTY_EQUIPMENTS_SLICE:
                self.__flashObject.showEquipmentSlots(False)
            if self.__cds[ORDERS_START_IDX:ORDERS_END_IDX +
                          1] == EMPTY_ORDERS_SLICE:
                self.__flashObject.showOrdersSlots(False)
        return

    def __onEquipmentUpdated(self, intCD, item):
        if intCD in self.__cds:
            idx = self.__cds.index(intCD)
            quantity = item.getQuantity()
            currentTime = item.getTimeRemaining()
            maxTime = item.getTotalTime()
            if item.isAvatar():
                self.__flashObject.setItemTimeQuantityInSlot(
                    self.__cds.index(intCD), quantity, currentTime, maxTime)
                self.__updateOrderSlot(idx, item)
            else:
                self.__flashObject.setItemTimeQuantityInSlot(
                    idx, quantity, currentTime, maxTime)
                self.onPopUpClosed()
        else:
            LOG_ERROR('Equipment is not found in panel', intCD, self.__cds)

    def __onEquipmentCooldownInPercent(self, intCD, percent):
        if intCD in self.__cds:
            self.__flashObject.setCoolDownPosAsPercent(self.__cds.index(intCD),
                                                       percent)

    def __addEquipmentSlot(self, intCD, item):
        idx = self.__genNextIdx(EQUIPMENT_FULL_MASK, EQUIPMENT_START_IDX)
        self.__cds[idx] = intCD
        descriptor = item.getDescriptor()
        iconPath = '../maps/icons/artefact/%s.png' % descriptor.icon[0]
        toolTip = TOOLTIP_FORMAT.format(descriptor.userString,
                                        descriptor.description)
        tag = item.getTag()
        if tag:
            bwKey, sfKey = self.__genKey(idx)
            if item.isEntityRequired():
                handler = partial(self.__handleEquipmentExpanded, intCD)
            else:
                handler = partial(self.__handleEquipmentPressed, intCD)
            if item.getQuantity() > 0:
                self.__keys[bwKey] = handler
        else:
            bwKey, sfKey = (None, None)
        self.__flashObject.addEquipmentSlot(idx, bwKey, sfKey, tag,
                                            item.getQuantity(),
                                            item.getTimeRemaining(), iconPath,
                                            toolTip)
        return None

    def __addOrderSlot(self, intCD, item):
        idx = self.__genNextIdx(ORDERS_FULL_MASK, ORDERS_START_IDX)
        self.__cds[idx] = intCD
        descriptor = item.getDescriptor()
        iconPath = '../maps/icons/artefact/%s.png' % descriptor.icon[0]
        toolTip = TOOLTIP_FORMAT.format(descriptor.userString,
                                        descriptor.description)
        bwKey, sfKey = self.__genKey(idx)
        self.__keys[bwKey] = partial(self.__handleEquipmentPressed, intCD)
        maxTime = item.getTotalTime()
        self.__flashObject.addOrderSlot(
            idx, bwKey, sfKey, item.getQuantity(), iconPath, toolTip,
            item.getStage()
            in (EQUIPMENT_STAGES.READY, EQUIPMENT_STAGES.PREPARING),
            item.isQuantityUsed(), item.getTimeRemaining(), maxTime)
        self.__updateOrderSlot(idx, item)

    def __updateOrderSlot(self, idx, item):
        if item.getStage() == EQUIPMENT_STAGES.READY:
            self.__flashObject.setOrderAvailable(idx, True)
        elif item.getStage() == EQUIPMENT_STAGES.PREPARING:
            self.__currentOrderIdx = idx
            self.__flashObject.setOrderActivated(idx)
        else:
            self.__flashObject.setOrderAvailable(idx, False)
        if item.getStage(
        ) != EQUIPMENT_STAGES.PREPARING and self.__currentOrderIdx == idx:
            self.__currentOrderIdx = -1
            self.__flashObject.setOrderActivated(self.__currentOrderIdx)

    def __onOptionalDeviceAdded(self, intCD, descriptor, isOn):
        idx = self.__genNextIdx(OPT_DEVICE_FULL_MASK, OPT_DEVICE_START_IDX)
        self.__cds[idx] = intCD
        iconPath = descriptor.icon[0]
        toolTip = TOOLTIP_FORMAT.format(descriptor.userString,
                                        descriptor.description)
        self.__flashObject.addOptionalDeviceSlot(idx, -1 if isOn else 0,
                                                 iconPath, toolTip)

    def __onOptionalDeviceUpdated(self, intCD, isOn):
        if intCD in self.__cds:
            self.__flashObject.setCoolDownTime(self.__cds.index(intCD),
                                               -1 if isOn else 0)
        else:
            LOG_ERROR('Optional device is not found in panel', intCD,
                      self.__cds)

    def __onPostMortemSwitched(self):
        self.__flashObject.switchToPosmortem()

    def __onRespawnBaseMoving(self):
        self.__cds = [None] * PANEL_MAX_LENGTH
        self.__mask = 0
        self.__keys.clear()
        self.__currentOrderIdx = -1
        self.__flashObject.reset()
        self.__plugins.reset()
        return

    def __onVehicleStateUpdated(self, state, value):
        if state != VEHICLE_VIEW_STATE.DEVICES:
            return
        else:
            deviceName, _, actualState = value
            if deviceName in VEHICLE_DEVICE_IN_COMPLEX_ITEM:
                itemName = VEHICLE_DEVICE_IN_COMPLEX_ITEM[deviceName]
            else:
                itemName = deviceName
            idx = int(
                self.__flashObject.updateEntityState(itemName, actualState))
            if idx and idx < len(self.__cds):
                intCD = self.__cds[idx]
                ctrl = g_sessionProvider.shared.equipments
                if ctrl is None:
                    return
                item = ctrl.getEquipment(intCD)
                if item and item.isEntityRequired():
                    bwKey, _ = self.__genKey(idx)
                    self.__keys[bwKey] = partial(self.__handleEquipmentPressed,
                                                 self.__cds[idx], deviceName)
            return
Ejemplo n.º 7
0
class Battle(BattleWindow):
    teamBasesPanel = property(lambda self: self.__teamBasesPanel)
    timersBar = property(lambda self: self.__timersBar)
    consumablesPanel = property(lambda self: self.__consumablesPanel)
    damagePanel = property(lambda self: self.__damagePanel)
    markersManager = property(lambda self: self.__markersManager)
    vErrorsPanel = property(lambda self: self.__vErrorsPanel)
    vMsgsPanel = property(lambda self: self.__vMsgsPanel)
    pMsgsPanel = property(lambda self: self.__pMsgsPanel)
    minimap = property(lambda self: self.__minimap)
    radialMenu = property(lambda self: self.__radialMenu)
    damageInfoPanel = property(lambda self: self.__damageInfoPanel)
    fragCorrelation = property(lambda self: self.__fragCorrelation)
    statsForm = property(lambda self: self.__statsForm)
    leftPlayersPanel = property(lambda self: self.__leftPlayersPanel)
    rightPlayersPanel = property(lambda self: self.__rightPlayersPanel)
    ribbonsPanel = property(lambda self: self.__ribbonsPanel)
    ppSwitcher = property(lambda self: self.__ppSwitcher)
    crosshairPanel = property(lambda self: self.__crosshairPanel)
    VEHICLE_DESTROY_TIMER = {
        'ALL': 'all',
        constants.VEHICLE_MISC_STATUS.VEHICLE_DROWN_WARNING: 'drown',
        constants.VEHICLE_MISC_STATUS.VEHICLE_IS_OVERTURNED: 'overturn'
    }
    VEHICLE_DEATHZONE_TIMER = {
        'ALL': 'all',
        constants.DEATH_ZONES.STATIC: 'death_zone',
        constants.DEATH_ZONES.GAS_ATTACK: 'gas_attack'
    }
    VEHICLE_DEATHZONE_TIMER_SOUND = {
        constants.DEATH_ZONES.GAS_ATTACK: {
            'warning': 'fallout_gaz_sphere_warning',
            'critical': 'fallout_gaz_sphere_timer'
        }
    }
    __cameraVehicleID = -1
    __stateHandlers = {
        VEHICLE_VIEW_STATE.FIRE: '_setFireInVehicle',
        VEHICLE_VIEW_STATE.SHOW_DESTROY_TIMER: '_showVehicleTimer',
        VEHICLE_VIEW_STATE.HIDE_DESTROY_TIMER: '_hideVehicleTimer',
        VEHICLE_VIEW_STATE.SHOW_DEATHZONE_TIMER: 'showDeathzoneTimer',
        VEHICLE_VIEW_STATE.HIDE_DEATHZONE_TIMER: 'hideDeathzoneTimer',
        VEHICLE_VIEW_STATE.OBSERVED_BY_ENEMY: '_showSixthSenseIndicator'
    }

    def __init__(self, appNS):
        self.__ns = appNS
        self.__isVisible = True
        self.__soundManager = None
        self.__arena = BigWorld.player().arena
        self.__crosshairPanel = None
        components = _COMPONENTS_TO_CTRLS[:]
        self.__plugins = PluginsCollection(self)
        plugins = {}
        visitor = g_sessionProvider.arenaVisitor
        if visitor.hasFlags():
            components.append(
                (BATTLE_CTRL_ID.FLAG_NOTS, ('fallout/flagsNots', )))
            plugins['flagNotification'] = FlagNotificationPlugin
        if visitor.hasRepairPoints():
            plugins['repairTimer'] = RepairTimerPlugin
        if visitor.hasRespawns() and (constants.IS_DEVELOPMENT or
                                      not BattleReplay.g_replayCtrl.isPlaying):
            components.append((BATTLE_CTRL_ID.RESPAWN, ('fallout/respawn', )))
            plugins['respawnView'] = RespawnViewPlugin
        if visitor.hasResourcePoints():
            plugins['resources'] = ResourcePointsPlugin
        if visitor.hasGasAttack():
            components.append(
                (BATTLE_CTRL_ID.GAS_ATTACK, ('fallout/gasAttack', )))
            plugins['gasAttack'] = GasAttackPlugin
        g_sessionProvider.registerViewComponents(*components)
        self.__plugins.addPlugins(plugins)
        self.__denunciator = BattleDenunciator()
        self.__timerSounds = {}
        for timer, sounds in self.VEHICLE_DEATHZONE_TIMER_SOUND.iteritems():
            self.__timerSounds[timer] = {}
            for level, sound in sounds.iteritems():
                self.__timerSounds[timer][
                    level] = SoundGroups.g_instance.getSound2D(sound)

        self.__timerSound = None
        BattleWindow.__init__(self, 'battle.swf')
        self.__isHelpWindowShown = False
        self.__cameraMode = None
        self.component.wg_inputKeyMode = 1
        self.component.position.z = DEPTH_OF_Battle
        self.movie.backgroundAlpha = 0
        self.addFsCallbacks({'battle.leave': self.onExitBattle})
        self.addExternalCallbacks({
            'battle.showCursor': self.cursorVisibility,
            'battle.tryLeaveRequest': self.tryLeaveRequest,
            'battle.populateFragCorrelationBar':
            self.populateFragCorrelationBar,
            'Battle.UsersRoster.Appeal': self.onDenunciationReceived,
            'Battle.selectPlayer': self.selectPlayer,
            'battle.helpDialogOpenStatus': self.helpDialogOpenStatus,
            'battle.initLobbyDialog': self._initLobbyDialog,
            'battle.reportBug': self.reportBug
        })
        self.__dynSquadListener = None
        BigWorld.wg_setRedefineKeysMode(False)
        self.onPostmortemVehicleChanged(BigWorld.player().playerVehicleID)
        return

    @property
    def appNS(self):
        return self.__ns

    @property
    def soundManager(self):
        return self.__soundManager

    @proto_getter(PROTO_TYPE.BW_CHAT2)
    def bwProto(self):
        return None

    def attachCursor(self, flags=0):
        return g_cursorDelegator.activateCursor()

    def detachCursor(self):
        return g_cursorDelegator.detachCursor()

    def syncCursor(self, flags=0):
        pass

    def getRoot(self):
        return self.__battle_flashObject

    def getCameraVehicleID(self):
        return self.__cameraVehicleID

    def populateFragCorrelationBar(self, _):
        if self.__fragCorrelation is not None:
            self.__fragCorrelation.populate()
        return

    def showAll(self, _):
        self.__isVisible = not self.__isVisible
        self.damagePanel.showAll(self.__cameraMode != 'video')
        self.call('battle.showAll', [self.__isVisible])
        g_eventBus.handleEvent(events.GameEvent(
            events.GameEvent.GUI_VISIBILITY, {'visible': self.__isVisible}),
                               scope=EVENT_BUS_SCOPE.BATTLE)
        avatar_getter.setComponentsVisibility(self.__isVisible)

    def showCursor(self, isShow):
        self.cursorVisibility(-1, isShow)

    def selectPlayer(self, _, vehId):
        player = BigWorld.player()
        if isPlayerAvatar():
            player.selectPlayer(int(vehId))

    def onDenunciationReceived(self, _, uid, userName, topic):
        self.__denunciator.makeAppeal(uid, userName, topic)
        self.__arenaCtrl.invalidateGUI()

    def onPostmortemVehicleChanged(self, vehicleID):
        if self.__cameraVehicleID == vehicleID:
            return
        self.__cameraVehicleID = vehicleID
        self.__arenaCtrl.invalidateGUI(
            not g_sessionProvider.getCtx().isPlayerObserver())
        self._hideVehicleTimer('ALL')
        self.hideDeathzoneTimer('ALL')
        self.__vErrorsPanel.clear()
        self.__vMsgsPanel.clear()

    def onCameraChanged(self, cameraMode, curVehID=None):
        LOG_DEBUG('onCameraChanged', cameraMode, curVehID)
        if self.__cameraMode == 'mapcase':
            self.setAimingMode(False)
        elif cameraMode == 'mapcase':
            self.setAimingMode(True)
        self.__cameraMode = cameraMode

        def setVisible(cname):
            m = self.getMember(cname)
            if m is not None:
                m.visible = cameraMode != 'video'
            return

        if self.__isGuiShown():
            self.damagePanel.showAll(cameraMode != 'video')
            setVisible('vehicleErrorsPanel')
        if cameraMode == 'video':
            self.__cameraVehicleID = -1
            self.__vErrorsPanel.clear()
            self.__vMsgsPanel.clear()
            self._hideVehicleTimer('ALL')
            self.hideDeathzoneTimer('ALL')

    def __isGuiShown(self):
        m = self.getMember('_root')
        if m is not None and callable(m.isGuiVisible):
            return m.isGuiVisible()
        else:
            return False

    def _showVehicleTimer(self, value):
        code, time, warnLvl = value
        LOG_DEBUG('show vehicles destroy timer', code, time, warnLvl)
        self.call('destroyTimer.show',
                  [self.VEHICLE_DESTROY_TIMER[code], time, warnLvl])

    def _hideVehicleTimer(self, code=None):
        LOG_DEBUG('hide vehicles destroy timer', code)
        if code is None:
            code = 'ALL'
        self.call('destroyTimer.hide', [self.VEHICLE_DESTROY_TIMER[code]])
        return

    def showDeathzoneTimer(self, value):
        zoneID, time, warnLvl = value
        if self.__timerSound is not None:
            self.__timerSound.stop()
            self.__timerSound = None
        sound = self.__timerSounds.get(zoneID, {}).get(warnLvl)
        if sound is not None:
            self.__timerSound = sound
            self.__timerSound.play()
        LOG_DEBUG('show vehicles deathzone timer', zoneID, time, warnLvl)
        self.call('destroyTimer.show',
                  [self.VEHICLE_DEATHZONE_TIMER[zoneID], time, warnLvl])
        return

    def hideDeathzoneTimer(self, zoneID=None):
        if self.__timerSound is not None:
            self.__timerSound.stop()
            self.__timerSound = None
        if zoneID is None:
            zoneID = 'ALL'
        LOG_DEBUG('hide vehicles deathzone timer', zoneID)
        self.call('destroyTimer.hide', [self.VEHICLE_DEATHZONE_TIMER[zoneID]])
        return

    def _showSixthSenseIndicator(self, isShow):
        self.call('sixthSenseIndicator.show', [isShow])

    def setVisible(self, bool):
        LOG_DEBUG('[Battle] visible', bool)
        self.component.visible = bool

    def afterCreate(self):
        event = events.AppLifeCycleEvent
        g_eventBus.handleEvent(event(self.__ns, event.INITIALIZING))
        player = BigWorld.player()
        LOG_DEBUG('[Battle] afterCreate')
        setattr(self.movie, '_global.wg_isShowLanguageBar',
                GUI_SETTINGS.isShowLanguageBar)
        setattr(self.movie, '_global.wg_isShowServerStats',
                constants.IS_SHOW_SERVER_STATS)
        setattr(self.movie, '_global.wg_isShowVoiceChat',
                GUI_SETTINGS.voiceChat)
        setattr(self.movie, '_global.wg_voiceChatProvider',
                self.__getVoiceChatProvider())
        setattr(self.movie, '_global.wg_isChina', constants.IS_CHINA)
        setattr(self.movie, '_global.wg_isKorea', constants.IS_KOREA)
        setattr(self.movie, '_global.wg_isReplayPlaying',
                BattleReplay.g_replayCtrl.isPlaying)
        BattleWindow.afterCreate(self)
        addListener = g_eventBus.addListener
        addListener(events.GameEvent.HELP, self.toggleHelpWindow, scope=_SCOPE)
        addListener(events.GameEvent.TOGGLE_GUI, self.showAll, scope=_SCOPE)
        player.inputHandler.onPostmortemVehicleChanged += self.onPostmortemVehicleChanged
        player.inputHandler.onCameraChanged += self.onCameraChanged
        g_settingsCore.onSettingsChanged += self.__accs_onSettingsChanged
        g_settingsCore.interfaceScale.onScaleChanged += self.__onRecreateDevice
        visitor = g_sessionProvider.arenaVisitor
        isMutlipleTeams = visitor.gui.isFalloutMultiTeam()
        isFallout = visitor.gui.isFalloutBattle()
        self.proxy = weakref.proxy(self)
        self.__battle_flashObject = self.proxy.getMember('_level0')
        if self.__battle_flashObject:
            self.__battle_flashObject.resync()
        voice = g_messengerEvents.voip
        voice.onPlayerSpeaking += self.setPlayerSpeaking
        voice.onVoiceChatInitFailed += self.onVoiceChatInitFailed
        self.colorManager = ColorSchemeManager._ColorSchemeManager()
        self.colorManager.populateUI(self.proxy)
        self.movingText = MovingText()
        self.movingText.populateUI(self.proxy)
        self.__settingsInterface = SettingsInterface()
        self.__settingsInterface.populateUI(self.proxy)
        self.__soundManager = SoundManager()
        self.__soundManager.populateUI(self.proxy)
        self.__debugPanel = DebugPanel()
        self.__timersBar = TimersBar(self.proxy, isFallout)
        if visitor.isBattleEndWarningEnabled():
            self.__battleEndWarningPanel = BattleEndWarningPanel(
                self.proxy, visitor.type, SoundGroups.g_instance)
        else:
            self.__battleEndWarningPanel = BattleEndWarningEmptyObject(
                self.proxy, visitor.type, SoundGroups.g_instance)
        self.__teamBasesPanel = TeamBasesPanel(self.proxy)
        self.__consumablesPanel = ConsumablesPanel(self.proxy)
        self.__damagePanel = DamagePanel(self.proxy)
        self.__markersManager = MarkersManager(self.proxy)
        self.__ingameHelp = IngameHelp(self.proxy)
        self.__minimap = Minimap(self.proxy)
        self.__radialMenu = RadialMenu(self.proxy)
        self.__ribbonsPanel = BattleRibbonsPanel(self.proxy)
        self.__ppSwitcher = PlayersPanelsSwitcher(self.proxy)
        isColorBlind = g_settingsCore.getSetting('isColorBlind')
        self.__leftPlayersPanel = playersPanelFactory(self.proxy, True,
                                                      isColorBlind, isFallout,
                                                      isMutlipleTeams)
        self.__rightPlayersPanel = playersPanelFactory(self.proxy, False,
                                                       isColorBlind, isFallout,
                                                       isMutlipleTeams)
        self.__damageInfoPanel = VehicleDamageInfoPanel(self.proxy)
        self.__damageInfoPanel.start()
        self.__fragCorrelation = scorePanelFactory(self.proxy, isFallout,
                                                   isMutlipleTeams)
        self.__statsForm = statsFormFactory(self.proxy, isFallout,
                                            isMutlipleTeams)
        self.__plugins.init()
        self.isVehicleCountersVisible = g_settingsCore.getSetting(
            'showVehiclesCounter')
        self.__fragCorrelation.showVehiclesCounter(
            self.isVehicleCountersVisible)
        self.__vErrorsPanel = VehicleErrorMessages(self.proxy)
        self.__vMsgsPanel = VehicleMessages(self.proxy)
        self.__pMsgsPanel = PlayerMessages(self.proxy)
        self.__plugins.start()
        self.__consumablesPanel.start()
        self.__damagePanel.start()
        self.__ingameHelp.start()
        self.__vErrorsPanel.start()
        self.__vMsgsPanel.start()
        self.__pMsgsPanel.start()
        self.__markersManager.start()
        self.__markersManager.setMarkerDuration(
            GUI_SETTINGS.markerHitSplashDuration)
        markers = {
            'enemy': g_settingsCore.getSetting('enemy'),
            'dead': g_settingsCore.getSetting('dead'),
            'ally': g_settingsCore.getSetting('ally')
        }
        self.__markersManager.setMarkerSettings(markers)
        self.__crosshairPanel = CrosshairPanel()
        self.__crosshairPanel.active(True)
        MessengerEntry.g_instance.gui.invoke('populateUI', self.proxy)
        g_guiResetters.add(self.__onRecreateDevice)
        g_repeatKeyHandlers.add(self.component.handleKeyEvent)
        self.__onRecreateDevice()
        self.__statsForm.populate()
        self.__leftPlayersPanel.populateUI(self.proxy)
        self.__rightPlayersPanel.populateUI(self.proxy)
        self.__debugPanel.populateUI(self.proxy)
        if BattleReplay.g_replayCtrl.isPlaying:
            BattleReplay.g_replayCtrl.onBattleSwfLoaded()
        self.__populateData()
        self.__minimap.start()
        self.__radialMenu.setSettings(self.__settingsInterface)
        self.__radialMenu.populateUI(self.proxy)
        self.__ribbonsPanel.start()
        add = g_sessionProvider.addViewComponent
        add('legacy/hitDirection',
            indicators.createDamageIndicator(),
            rule=VIEW_COMPONENT_RULE.NONE)
        add('legacy/teamBasesPanel', self.__teamBasesPanel)
        add('legacy/debugPanel', self.__debugPanel)
        add('legacy/battleTimer', self.__timersBar)
        add('legacy/prebattleTimer', self.__timersBar)
        add('legacy/ppSwitcher', self.__ppSwitcher)
        add(_BATTLE_END_WARNING_COMPONENT, self.__battleEndWarningPanel)
        self.__arenaCtrl = battleArenaControllerFactory(
            self, isFallout, isMutlipleTeams)
        g_sessionProvider.addArenaCtrl(self.__arenaCtrl)
        self.updateFlagsColor()
        self.movie.setFocussed(SCALEFORM_SWF_PATH)
        self.call(
            'battle.initDynamicSquad',
            self.__getDynamicSquadsInitParams(
                enableButton=not BattleReplay.g_replayCtrl.isPlaying))
        self.call('sixthSenseIndicator.setDuration',
                  [GUI_SETTINGS.sixthSenseDuration])
        keyCode = CommandMapping.g_instance.get('CMD_VOICECHAT_MUTE')
        if not BigWorld.isKeyDown(keyCode):
            VOIP.getVOIPManager().setMicMute(True)
        ctrl = g_sessionProvider.shared.vehicleState
        ctrl.onVehicleStateUpdated += self.__onVehicleStateUpdated
        ctrl.onPostMortemSwitched += self.__onPostMortemSwitched
        if BattleReplay.g_replayCtrl.isPlaying:
            self.__dynSquadListener = ReplayDynSquadViewListener(self.proxy)
        elif BattleReplay.g_replayCtrl.isRecording:
            self.__dynSquadListener = RecordDynSquadViewListener(self.proxy)
        else:
            self.__dynSquadListener = DynSquadViewListener(self.proxy)
        g_eventBus.handleEvent(event(self.__ns, event.INITIALIZED))

    def beforeDelete(self):
        LOG_DEBUG('[Battle] beforeDelete')
        removeListener = g_eventBus.removeListener
        removeListener(events.GameEvent.HELP,
                       self.toggleHelpWindow,
                       scope=_SCOPE)
        removeListener(events.GameEvent.TOGGLE_GUI, self.showAll, scope=_SCOPE)
        ctrl = g_sessionProvider.shared.vehicleState
        if ctrl is not None:
            ctrl.onVehicleStateUpdated -= self.__onVehicleStateUpdated
            ctrl.onPostMortemSwitched -= self.__onPostMortemSwitched
        player = BigWorld.player()
        if player and player.inputHandler:
            player.inputHandler.onPostmortemVehicleChanged -= self.onPostmortemVehicleChanged
            player.inputHandler.onCameraChanged -= self.onCameraChanged
        if self.colorManager:
            self.colorManager.dispossessUI()
        voice = g_messengerEvents.voip
        if voice:
            voice.onPlayerSpeaking -= self.setPlayerSpeaking
            voice.onVoiceChatInitFailed -= self.onVoiceChatInitFailed
        if self.__plugins is not None:
            self.__plugins.stop()
            self.__plugins.fini()
            self.__plugins = None
        if self.movingText is not None:
            self.movingText.dispossessUI()
            self.movingText = None
        if self.__timerSound is not None:
            self.__timerSound.stop()
            self.__timerSound = None
        if self.__soundManager is not None:
            self.__soundManager.dispossessUI()
            self.__soundManager = None
        if self.colorManager is not None:
            self.colorManager.dispossessUI()
            self.colorManager = None
        if self.component:
            g_repeatKeyHandlers.discard(self.component.handleKeyEvent)
        g_settingsCore.onSettingsChanged -= self.__accs_onSettingsChanged
        g_settingsCore.interfaceScale.onScaleChanged -= self.__onRecreateDevice
        self.__timersBar.destroy()
        self.__battleEndWarningPanel.destroy()
        self.__teamBasesPanel.destroy()
        self.__consumablesPanel.destroy()
        self.__damagePanel.destroy()
        self.__markersManager.destroy()
        self.__ingameHelp.destroy()
        self.__vErrorsPanel.destroy()
        self.__vMsgsPanel.destroy()
        self.__pMsgsPanel.destroy()
        self.__radialMenu.destroy()
        self.__minimap.destroy()
        self.__ribbonsPanel.destroy()
        self.__fragCorrelation.destroy()
        self.__statsForm.destroy()
        self.__damageInfoPanel.destroy()
        remove = g_sessionProvider.removeViewComponent
        remove('legacy/hitDirection')
        remove('legacy/teamBasesPanel')
        remove('legacy/debugPanel')
        remove('legacy/battleTimer')
        remove('legacy/prebattleTimer')
        remove('legacy/ppSwitcher')
        if self.__arenaCtrl is not None:
            g_sessionProvider.removeArenaCtrl(self.__arenaCtrl)
            self.__arenaCtrl = None
        self.__ppSwitcher.destroy()
        self.__debugPanel.dispossessUI()
        self.__leftPlayersPanel.dispossessUI()
        self.__rightPlayersPanel.dispossessUI()
        MessengerEntry.g_instance.gui.invoke('dispossessUI')
        self.__arena = None
        self.__denunciator = None
        g_guiResetters.discard(self.__onRecreateDevice)
        self.__settingsInterface.dispossessUI()
        self.__settingsInterface = None
        if self.__dynSquadListener:
            self.__dynSquadListener.destroy()
            self.__dynSquadListener = None
        if self.__crosshairPanel is not None:
            self.__crosshairPanel.close()
            self.__crosshairPanel = None
        BattleWindow.beforeDelete(self)
        event = events.AppLifeCycleEvent
        g_eventBus.handleEvent(event(self.__ns, event.DESTROYED))
        return

    def __onVehicleStateUpdated(self, state, value):
        if state not in self.__stateHandlers:
            return
        else:
            handler = getattr(self, self.__stateHandlers[state], None)
            if handler and callable(handler):
                if value is not None:
                    handler(value)
                else:
                    handler()
            return

    def _setFireInVehicle(self, bool):
        self.call('destroyTimer.onFireInVehicle', [bool])

    def onVoiceChatInitFailed(self):
        self.call('VoiceChat.initFailed', [])

    def clearCommands(self):
        pass

    def bindCommands(self):
        self.__consumablesPanel.bindCommands()
        self.__ingameHelp.buildCmdMapping()

    def updateFlagsColor(self):
        isColorBlind = g_settingsCore.getSetting('isColorBlind')
        colorGreen = self.colorManager.getSubScheme(
            'flag_team_green', isColorBlind=isColorBlind)['rgba']
        colorRed = self.colorManager.getSubScheme(
            'flag_team_red', isColorBlind=isColorBlind)['rgba']
        arenaDP = g_sessionProvider.getArenaDP()
        teamsOnArena = arenaDP.getTeamsOnArena()
        for teamIdx in teamsOnArena:
            color = colorGreen if arenaDP.isAllyTeam(teamIdx) else colorRed
            BigWorld.wg_setFlagColor(teamIdx, color / 255)

        for teamIdx in [0] + teamsOnArena:
            BigWorld.wg_setFlagEmblem(teamIdx, 'system/maps/wg_emblem.dds',
                                      Math.Vector4(0.0, 0.1, 0.5, 0.9))

    def setPlayerSpeaking(self, accountDBID, flag):
        self.__callEx('setPlayerSpeaking', [accountDBID, flag])
        vID = g_sessionProvider.getCtx().getVehIDByAccDBID(accountDBID)
        if vID > 0:
            self.__markersManager.showDynamic(vID, flag)

    def isPlayerSpeaking(self, accountDBID):
        return self.bwProto.voipController.isPlayerSpeaking(accountDBID)

    def __getVoiceChatProvider(self):
        if self.bwProto.voipController.isVivox():
            return 'vivox'
        if self.bwProto.voipController.isYY():
            return 'YY'
        return 'unknown'

    def __onPostMortemSwitched(self):
        if self.radialMenu is not None:
            self.radialMenu.forcedHide()
        if not g_sessionProvider.getCtx().isPlayerObserver():
            self.__callEx('showPostmortemTips', [1.0, 5.0, 1.0])
        return

    def cursorVisibility(self,
                         _,
                         visible,
                         x=None,
                         y=None,
                         customCall=False,
                         enableAiming=True):
        if visible:
            g_cursorDelegator.syncMousePosition(self, x, y, customCall)
        else:
            g_cursorDelegator.restoreMousePosition()
        avatar_getter.setForcedGuiControlMode(visible,
                                              stopVehicle=False,
                                              enableAiming=enableAiming)

    def tryLeaveRequest(self, _):
        exitResult = g_sessionProvider.getExitResult()
        if exitResult.playerInfo is not None:
            igrType = exitResult.playerInfo.igrType
        else:
            igrType = constants.IGR_TYPE.NONE
        if constants.IS_KOREA and GUI_SETTINGS.igrEnabled and igrType != constants.IGR_TYPE.NONE:
            resStr = 'quitBattleIGR'
        else:
            resStr = 'quitBattle'
        if exitResult.isDeserter:
            self.__callEx('tryLeaveResponse', [resStr + '/deserter', True])
        else:
            self.__callEx('tryLeaveResponse', [resStr, False])
        return

    def onExitBattle(self, _):
        g_sessionProvider.exit()

    def toggleHelpWindow(self, _):
        self.__callEx('showHideHelp', [not self.__isHelpWindowShown])

    def setAimingMode(self, isAiming):
        self.__callEx('setAimingMode', [isAiming])

    def helpDialogOpenStatus(self, cid, isOpened):
        self.__isHelpWindowShown = isOpened

    def _initLobbyDialog(self, cid):
        if connectionManager.serverUserName:
            tooltipBody = i18n.makeString(
                '#tooltips:header/info/players_online_full/body')
            tooltipFullData = makeTooltip(
                '#tooltips:header/info/players_online_full/header',
                tooltipBody % {'servername': connectionManager.serverUserName})
            self.__callEx('setServerStatsInfo', [tooltipFullData])
            self.__callEx('setServerName', [connectionManager.serverUserName])
            if constants.IS_SHOW_SERVER_STATS:
                stats = game_control.g_instance.serverStats.getStats()
                if 'clusterCCU' in stats and 'regionCCU' in stats:
                    self.__callEx('setServerStats',
                                  [stats['clusterCCU'], stats['regionCCU']])
                else:
                    self.__callEx('setServerStats', [None, None])
        else:
            self.__callEx('setServerName', ['-'])
        links = GUI_SETTINGS.reportBugLinks
        if len(links):
            reportBugButton = makeHyperLink('ingameMenu',
                                            MENU.INGAME_MENU_LINKS_REPORT_BUG)
            self.__callEx('setReportBugLink', [reportBugButton])
        return

    def reportBug(self, _):
        reportBugOpenConfirm(
            g_sessionProvider.getArenaDP().getVehicleInfo().player.accountDBID)

    def __getDynamicSquadsInitParams(self,
                                     enableAlly=True,
                                     enableEnemy=False,
                                     enableButton=True):
        return [
            self.__arena.guiType == constants.ARENA_GUI_TYPE.RANDOM
            and enableAlly, enableEnemy, enableButton
        ]

    def __populateData(self):
        ctx = g_sessionProvider.getCtx()
        data = [
            ctx.getArenaTypeName(),
            ctx.getArenaFrameLabel(isLegacy=True),
            ctx.getArenaDescriptionString(),
            ctx.getTeamName(enemy=False),
            ctx.getTeamName(enemy=True),
            ctx.getArenaWinString(),
            ctx.getGuiEventType()
        ]
        settings = g_lobbyContext.getServerSettings()
        quest = [None] * 3
        if settings is not None and settings.isPotapovQuestEnabled():
            info = ctx.getQuestInfo()
            if info is not None:
                quest[0] = info.name
                if info.condition:
                    quest[1] = info.condition
                if info.condition:
                    quest[2] = info.additional
        data.extend(quest)
        data.append(ctx.getArenaSmallIcon())
        self.__callEx('arenaData', data)
        return

    def __onRecreateDevice(self, scale=None):
        params = list(GUI.screenResolution())
        params.append(g_settingsCore.interfaceScale.get())
        self.call('Stage.Update', params)
        self.__markersManager.updateMarkersScale()

    def invalidateGUI(self):
        arenaCtrl = getattr(self, '_Battle__arenaCtrl', None)
        if arenaCtrl is not None:
            arenaCtrl.invalidateGUI()
        return

    def __callEx(self, funcName, args=None):
        self.call('battle.' + funcName, args)

    def __accs_onSettingsChanged(self, diff):
        self.colorManager.update()
        if 'isColorBlind' in diff:
            isColorBlind = diff['isColorBlind']
            self.__leftPlayersPanel.defineColorFlags(isColorBlind=isColorBlind)
            self.__rightPlayersPanel.defineColorFlags(
                isColorBlind=isColorBlind)
            self.updateFlagsColor()
            self.__markersManager.updateMarkers()
            self.__minimap.updateEntries()
        if 'enemy' in diff or 'dead' in diff or 'ally' in diff:
            markers = {
                'enemy': g_settingsCore.getSetting('enemy'),
                'dead': g_settingsCore.getSetting('dead'),
                'ally': g_settingsCore.getSetting('ally')
            }
            self.__markersManager.setMarkerSettings(markers)
            self.__markersManager.updateMarkerSettings()
        if 'showVehiclesCounter' in diff:
            self.isVehicleCountersVisible = diff['showVehiclesCounter']
            self.__fragCorrelation.showVehiclesCounter(
                self.isVehicleCountersVisible)
        if 'interfaceScale' in diff:
            self.__onRecreateDevice()
        self.__arenaCtrl.invalidateGUI()
        self.__arenaCtrl.invalidateArenaInfo()

    def setTeamValuesData(self, data):
        if self.__battle_flashObject is not None:
            self.__battle_flashObject.setTeamValues(data)
        return

    def setMultiteamValues(self, data):
        if self.__battle_flashObject is not None:
            self.__battle_flashObject.setMultiteamValues(data)
        return

    def getPlayerNameLength(self, isEnemy):
        panel = self.rightPlayersPanel if isEnemy else self.leftPlayersPanel
        return panel.getPlayerNameLength()

    def getVehicleNameLength(self, isEnemy):
        panel = self.rightPlayersPanel if isEnemy else self.leftPlayersPanel
        return panel.getVehicleNameLength()
Ejemplo n.º 8
0
class ConsumablesPanel(object):

    def __init__(self, parentUI):
        self.__ui = parentUI
        self.__flashObject = None
        self.__cds = [None] * PANEL_MAX_LENGTH
        self.__mask = 0
        self.__keys = {}
        self.__currentOrderIdx = -1
        self.__plugins = PluginsCollection(self)
        plugins = {}
        if hasRage():
            plugins['rageBar'] = _RageBarPlugin
        self.__plugins.addPlugins(plugins)
        return

    def start(self):
        self.__flashObject = self.__ui.getMember('_level0.consumablesPanel')
        if self.__flashObject:
            self.__flashObject.resync()
            self.__flashObject.script = self
            self.__plugins.init()
            self.__plugins.start()
            props = _FalloutSlotViewProps(useStandardLayout=not hasRage())
            self.__flashObject.setProperties(isEventBattle(), props._asdict())
            self.__addListeners()
        else:
            LOG_ERROR('Display object is not found in the swf file.')

    def destroy(self):
        self.__plugins.stop()
        self.__plugins.fini()
        self.__removeListeners()
        self.__keys.clear()
        self.__ui = None
        if self.__flashObject is not None:
            self.__flashObject.script = None
            self.__flashObject = None
        return

    def bindCommands(self):
        keys = {}
        slots = []
        for idx, bwKey, sfKey, handler in self.__getKeysGenerator():
            if handler:
                keys[bwKey] = handler
                slots.append((idx, bwKey, sfKey))

        self.__flashObject.setKeysToSlots(slots)
        self.__keys.clear()
        self.__keys = keys

    def onClickedToSlot(self, bwKey):
        self.__handleBWKey(int(bwKey))

    def onPopUpClosed(self):
        keys = {}
        for idx, bwKey, _, handler in self.__getKeysGenerator():
            if handler:
                keys[bwKey] = handler

        self.__keys.clear()
        self.__keys = keys
        ctrl = g_sessionProvider.getVehicleStateCtrl()
        ctrl.onVehicleStateUpdated -= self.__onVehicleStateUpdated

    @property
    def flashObject(self):
        return self.__flashObject

    def __callFlash(self, funcName, args = None):
        self.__ui.call('battle.consumablesPanel.%s' % funcName, args)

    def __addListeners(self):
        vehicleCtrl = g_sessionProvider.getVehicleStateCtrl()
        vehicleCtrl.onPostMortemSwitched += self.__onPostMortemSwitched
        vehicleCtrl.onRespawnBaseMoving += self.__onRespawnBaseMoving
        ammoCtrl = g_sessionProvider.getAmmoCtrl()
        ammoCtrl.onShellsAdded += self.__onShellsAdded
        ammoCtrl.onShellsUpdated += self.__onShellsUpdated
        ammoCtrl.onNextShellChanged += self.__onNextShellChanged
        ammoCtrl.onCurrentShellChanged += self.__onCurrentShellChanged
        ammoCtrl.onGunReloadTimeSet += self.__onGunReloadTimeSet
        ammoCtrl.onGunReloadTimeSetInPercent += self.__onGunReloadTimeSetInPercent
        eqCtrl = g_sessionProvider.getEquipmentsCtrl()
        eqCtrl.onEquipmentAdded += self.__onEquipmentAdded
        eqCtrl.onEquipmentUpdated += self.__onEquipmentUpdated
        eqCtrl.onEquipmentCooldownInPercent += self.__onEquipmentCooldownInPercent
        optDevicesCtrl = g_sessionProvider.getOptDevicesCtrl()
        optDevicesCtrl.onOptionalDeviceAdded += self.__onOptionalDeviceAdded
        optDevicesCtrl.onOptionalDeviceUpdated += self.__onOptionalDeviceUpdated
        g_eventBus.addListener(GameEvent.CHOICE_CONSUMABLE, self.__handleConsumableChoice, scope=EVENT_BUS_SCOPE.BATTLE)

    def __removeListeners(self):
        g_eventBus.removeListener(GameEvent.CHOICE_CONSUMABLE, self.__handleConsumableChoice, scope=EVENT_BUS_SCOPE.BATTLE)
        vehicleCtrl = g_sessionProvider.getVehicleStateCtrl()
        vehicleCtrl.onPostMortemSwitched -= self.__onPostMortemSwitched
        vehicleCtrl.onRespawnBaseMoving -= self.__onRespawnBaseMoving
        vehicleCtrl.onVehicleStateUpdated -= self.__onVehicleStateUpdated
        ammoCtrl = g_sessionProvider.getAmmoCtrl()
        ammoCtrl.onShellsAdded -= self.__onShellsAdded
        ammoCtrl.onShellsUpdated -= self.__onShellsUpdated
        ammoCtrl.onNextShellChanged -= self.__onNextShellChanged
        ammoCtrl.onCurrentShellChanged -= self.__onCurrentShellChanged
        ammoCtrl.onGunReloadTimeSet -= self.__onGunReloadTimeSet
        ammoCtrl.onGunReloadTimeSetInPercent -= self.__onGunReloadTimeSetInPercent
        eqCtrl = g_sessionProvider.getEquipmentsCtrl()
        eqCtrl.onEquipmentAdded -= self.__onEquipmentAdded
        eqCtrl.onEquipmentUpdated -= self.__onEquipmentUpdated
        eqCtrl.onEquipmentCooldownInPercent -= self.__onEquipmentCooldownInPercent
        optDevicesCtrl = g_sessionProvider.getOptDevicesCtrl()
        optDevicesCtrl.onOptionalDeviceAdded -= self.__onOptionalDeviceAdded
        optDevicesCtrl.onOptionalDeviceUpdated -= self.__onOptionalDeviceUpdated

    def __genNextIdx(self, full, start):
        bits = self.__mask & full
        if not bits:
            idx = start
        else:
            idx = int(math.log(bits, 2)) + 1
        raise -1 < idx < PANEL_MAX_LENGTH - 1 or AssertionError
        self.__mask |= 1 << idx
        return idx

    def __genKey(self, idx):
        if not -1 < idx < PANEL_MAX_LENGTH - 1:
            raise AssertionError
            cmdMappingKey = COMMAND_AMMO_CHOICE_MASK.format(idx + 1 if idx < 9 else 0)
            bwKey = CommandMapping.g_instance.get(cmdMappingKey)
            sfKey = 0
            sfKey = bwKey is not None and bwKey != 0 and getScaleformKey(bwKey)
        return (bwKey, sfKey)

    def __makeShellTooltip(self, descriptor, piercingPower):
        kind = descriptor['kind']
        header = i18n.makeString('#ingame_gui:shells_kinds/{0:>s}'.format(kind), caliber=BigWorld.wg_getNiceNumberFormat(descriptor['caliber']), userString=descriptor['userString'])
        body = i18n.makeString('#ingame_gui:shells_kinds/params', damage=str(int(descriptor['damage'][0])), piercingPower=str(piercingPower))
        return TOOLTIP_FORMAT.format(header, body)

    def __getKeysGenerator(self):
        getEquipment = g_sessionProvider.getEquipmentsCtrl().getEquipment
        for idx, intCD in enumerate(self.__cds):
            if not intCD:
                yield (idx,
                 None,
                 None,
                 None)
            else:
                bwKey, sfKey = self.__genKey(idx)
                handler = None
                if idx in AMMO_RANGE:
                    handler = partial(self.__handleAmmoPressed, intCD)
                elif idx in EQUIPMENT_RANGE or idx in ORDERS_RANGE:
                    item = getEquipment(intCD)
                    if item and item.getTag() and item.getQuantity() > 0:
                        if item.isEntityRequired():
                            handler = partial(self.__handleEquipmentExpanded, intCD)
                        else:
                            handler = partial(self.__handleEquipmentPressed, intCD)
                yield (idx,
                 bwKey,
                 sfKey,
                 handler)

        return

    def __handleConsumableChoice(self, event):
        self.__handleBWKey(event.ctx['key'])

    def __handleBWKey(self, bwKey):
        if bwKey in self.__keys:
            handler = self.__keys[bwKey]
            if handler and callable(handler):
                handler()

    def __handleAmmoPressed(self, intCD):
        g_sessionProvider.getAmmoCtrl().changeSetting(intCD)

    def __handleEquipmentPressed(self, intCD, entityName = None):
        result, error = g_sessionProvider.getEquipmentsCtrl().changeSetting(intCD, entityName=entityName, avatar=BigWorld.player())
        if not result and error:
            self.__ui.vErrorsPanel.showMessage(error.key, error.ctx)
        else:
            self.__flashObject.collapseEquipmentSlot()

    def __handleEquipmentExpanded(self, intCD):
        if not self.__flashObject.getVisibility():
            return
        result, error = g_sessionProvider.getEquipmentsCtrl().changeSetting(intCD)
        if not result and error:
            self.__ui.vErrorsPanel.showMessage(error.key, error.ctx)
            return
        if intCD not in self.__cds:
            LOG_ERROR('Equipment is not found in panel', intCD, self.__cds)
            return
        item = g_sessionProvider.getEquipmentsCtrl().getEquipment(intCD)
        if not item:
            LOG_ERROR('Equipment is not found in control', intCD)
            return
        slots = []
        keys = {}
        for entityIdx, (itemName, entityName, entityState) in enumerate(item.getGuiIterator()):
            bwKey, sfKey = self.__genKey(entityIdx)
            keys[bwKey] = partial(self.__handleEquipmentPressed, intCD, entityName)
            slots.append({'bwKeyCode': bwKey,
             'sfKeyCode': sfKey,
             'entityName': itemName,
             'entityState': entityState})

        self.__flashObject.expandEquipmentSlot(self.__cds.index(intCD), slots)
        self.__keys.clear()
        self.__keys = keys
        ctrl = g_sessionProvider.getVehicleStateCtrl()
        ctrl.onVehicleStateUpdated += self.__onVehicleStateUpdated

    def __onShellsAdded(self, intCD, descriptor, quantity, _, gunSettings):
        toolTip = self.__makeShellTooltip(descriptor, int(gunSettings.getPiercingPower(intCD)))
        icon = descriptor['icon'][0]
        shellIconPath = AMMO_ICON_PATH % icon
        noShellIconPath = NO_AMMO_ICON_PATH % icon
        idx = self.__genNextIdx(AMMO_FULL_MASK, AMMO_START_IDX)
        self.__cds[idx] = intCD
        bwKey, sfKey = self.__genKey(idx)
        self.__keys[bwKey] = partial(self.__handleAmmoPressed, intCD)
        self.__flashObject.addShellSlot(idx, bwKey, sfKey, quantity, gunSettings.clip.size, shellIconPath, noShellIconPath, toolTip)

    def __onShellsUpdated(self, intCD, quantity, *args):
        if intCD in self.__cds:
            self.__flashObject.setItemQuantityInSlot(self.__cds.index(intCD), quantity)
        else:
            LOG_ERROR('Ammo is not found in panel', intCD, self.__cds)

    def __onNextShellChanged(self, intCD):
        if intCD in self.__cds:
            self.__flashObject.setNextShell(self.__cds.index(intCD))
        else:
            LOG_ERROR('Ammo is not found in panel', intCD, self.__cds)

    def __onCurrentShellChanged(self, intCD):
        if intCD in self.__cds:
            self.__flashObject.setCurrentShell(self.__cds.index(intCD))
        else:
            LOG_ERROR('Ammo is not found in panel', intCD, self.__cds)

    def __onGunReloadTimeSet(self, currShellCD, timeLeft, _):
        if currShellCD in self.__cds:
            self.__flashObject.setCoolDownTime(self.__cds.index(currShellCD), timeLeft)
        else:
            LOG_ERROR('Ammo is not found in panel', currShellCD, self.__cds)

    def __onGunReloadTimeSetInPercent(self, currShellCD, percent):
        if currShellCD in self.__cds:
            self.__flashObject.setCoolDownPosAsPercent(self.__cds.index(currShellCD), percent)

    def __onEquipmentAdded(self, intCD, item):
        if item:
            if item.isAvatar():
                self.__addOrderSlot(intCD, item)
            else:
                self.__addEquipmentSlot(intCD, item)
        else:
            idx = self.__genNextIdx(EQUIPMENT_FULL_MASK + ORDERS_FULL_MASK, EQUIPMENT_START_IDX)
            self.__cds[idx] = intCD
            self.__flashObject.addEquipmentSlot(idx, None, None, None, 0, 0, None, EMPTY_EQUIPMENT_TOOLTIP)
            if self.__cds[EQUIPMENT_START_IDX:EQUIPMENT_END_IDX + 1] == EMPTY_EQUIPMENTS_SLICE:
                self.__flashObject.showEquipmentSlots(False)
            if self.__cds[ORDERS_START_IDX:ORDERS_END_IDX + 1] == EMPTY_ORDERS_SLICE:
                self.__flashObject.showOrdersSlots(False)
        return

    def __onEquipmentUpdated(self, intCD, item):
        if intCD in self.__cds:
            idx = self.__cds.index(intCD)
            quantity = item.getQuantity()
            currentTime = item.getTimeRemaining()
            maxTime = item.getTotalTime()
            if item.isAvatar():
                self.__flashObject.setItemTimeQuantityInSlot(self.__cds.index(intCD), quantity, currentTime, maxTime)
                self.__updateOrderSlot(idx, item)
            else:
                self.__flashObject.setItemTimeQuantityInSlot(idx, quantity, currentTime, maxTime)
                self.onPopUpClosed()
        else:
            LOG_ERROR('Equipment is not found in panel', intCD, self.__cds)

    def __onEquipmentCooldownInPercent(self, intCD, percent):
        if intCD in self.__cds:
            self.__flashObject.setCoolDownPosAsPercent(self.__cds.index(intCD), percent)

    def __addEquipmentSlot(self, intCD, item):
        idx = self.__genNextIdx(EQUIPMENT_FULL_MASK, EQUIPMENT_START_IDX)
        self.__cds[idx] = intCD
        descriptor = item.getDescriptor()
        iconPath = '../maps/icons/artefact/%s.png' % descriptor.icon[0]
        toolTip = TOOLTIP_FORMAT.format(descriptor.userString, descriptor.description)
        tag = item.getTag()
        if tag:
            bwKey, sfKey = self.__genKey(idx)
            if item.isEntityRequired():
                handler = partial(self.__handleEquipmentExpanded, intCD)
            else:
                handler = partial(self.__handleEquipmentPressed, intCD)
            if item.getQuantity() > 0:
                self.__keys[bwKey] = handler
        else:
            bwKey, sfKey = (None, None)
        self.__flashObject.addEquipmentSlot(idx, bwKey, sfKey, tag, item.getQuantity(), item.getTimeRemaining(), iconPath, toolTip)
        return None

    def __addOrderSlot(self, intCD, item):
        idx = self.__genNextIdx(ORDERS_FULL_MASK, ORDERS_START_IDX)
        self.__cds[idx] = intCD
        descriptor = item.getDescriptor()
        iconPath = '../maps/icons/artefact/%s.png' % descriptor.icon[0]
        toolTip = TOOLTIP_FORMAT.format(descriptor.userString, descriptor.description)
        bwKey, sfKey = self.__genKey(idx)
        self.__keys[bwKey] = partial(self.__handleEquipmentPressed, intCD)
        maxTime = item.getTotalTime()
        self.__flashObject.addOrderSlot(idx, bwKey, sfKey, item.getQuantity(), iconPath, toolTip, item.getStage() in (EQUIPMENT_STAGES.READY, EQUIPMENT_STAGES.PREPARING), item.isQuantityUsed(), item.getTimeRemaining(), maxTime)
        self.__updateOrderSlot(idx, item)

    def __updateOrderSlot(self, idx, item):
        if item.getStage() == EQUIPMENT_STAGES.READY:
            self.__flashObject.setOrderAvailable(idx, True)
        elif item.getStage() == EQUIPMENT_STAGES.PREPARING:
            self.__currentOrderIdx = idx
            self.__flashObject.setOrderActivated(idx)
        else:
            self.__flashObject.setOrderAvailable(idx, False)
        if item.getStage() != EQUIPMENT_STAGES.PREPARING and self.__currentOrderIdx == idx:
            self.__currentOrderIdx = -1
            self.__flashObject.setOrderActivated(self.__currentOrderIdx)

    def __onOptionalDeviceAdded(self, intCD, descriptor, isOn):
        idx = self.__genNextIdx(OPT_DEVICE_FULL_MASK, OPT_DEVICE_START_IDX)
        self.__cds[idx] = intCD
        iconPath = descriptor.icon[0]
        toolTip = TOOLTIP_FORMAT.format(descriptor.userString, descriptor.description)
        self.__flashObject.addOptionalDeviceSlot(idx, -1 if isOn else 0, iconPath, toolTip)

    def __onOptionalDeviceUpdated(self, intCD, isOn):
        if intCD in self.__cds:
            self.__flashObject.setCoolDownTime(self.__cds.index(intCD), -1 if isOn else 0)
        else:
            LOG_ERROR('Optional device is not found in panel', intCD, self.__cds)

    def __onPostMortemSwitched(self):
        self.__flashObject.switchToPosmortem()

    def __onRespawnBaseMoving(self):
        self.__cds = [None] * PANEL_MAX_LENGTH
        self.__mask = 0
        self.__keys.clear()
        self.__currentOrderIdx = -1
        self.__flashObject.reset()
        self.__plugins.reset()
        return

    def __onVehicleStateUpdated(self, state, value):
        if state != VEHICLE_VIEW_STATE.DEVICES:
            return
        deviceName, _, actualState = value
        if deviceName in VEHICLE_DEVICE_IN_COMPLEX_ITEM:
            itemName = VEHICLE_DEVICE_IN_COMPLEX_ITEM[deviceName]
        else:
            itemName = deviceName
        idx = int(self.__flashObject.updateEntityState(itemName, actualState))
        if idx and idx < len(self.__cds):
            intCD = self.__cds[idx]
            item = g_sessionProvider.getEquipmentsCtrl().getEquipment(intCD)
            if item and item.isEntityRequired():
                bwKey, _ = self.__genKey(idx)
                self.__keys[bwKey] = partial(self.__handleEquipmentPressed, self.__cds[idx], deviceName)
Ejemplo n.º 9
0
class MarkersManager(Flash):

    def __init__(self, parentUI):
        Flash.__init__(self, _MARKERS_MANAGER_SWF)
        self.component.wg_inputKeyMode = 2
        self.component.position.z = DEPTH_OF_VehicleMarker
        self.component.drawWithRestrictedViewPort = False
        self.movie.backgroundAlpha = 0
        self.colorManager = ColorSchemeManager._ColorSchemeManager()
        self.colorManager.populateUI(weakref.proxy(self))
        self.__plugins = PluginsCollection(self)
        plugins = {'equipments': _EquipmentsMarkerPlugin}
        if arena_info.hasFlags():
            plugins['flags'] = _FlagsMarkerPlugin
        if arena_info.hasRepairPoints():
            plugins['repairs'] = _RepairsMarkerPlugin
        if arena_info.hasResourcePoints():
            plugins['resources'] = _ResourceMarkerPlugin
        if arena_info.hasGasAttack():
            plugins['safe_zone'] = _GasAttackSafeZonePlugin
        self.__plugins.addPlugins(plugins)
        self.__ownUI = None
        self.__parentUI = parentUI
        self.__markers = {}
        return

    def setScaleProps(self, minScale = 40, maxScale = 100, defScale = 100, speed = 3.0):
        if constants.IS_DEVELOPMENT:
            self.__ownUI.scaleProperties = (minScale,
             maxScale,
             defScale,
             speed)

    def setAlphaProps(self, minAlpha = 40, maxAlpha = 100, defAlpha = 100, speed = 3.0):
        if constants.IS_DEVELOPMENT:
            self.__ownUI.alphaProperties = (minAlpha,
             maxAlpha,
             defAlpha,
             speed)

    def start(self):
        self.active(True)
        self.__ownUI = GUI.WGVehicleMarkersCanvasFlash(self.movie)
        self.__ownUI.wg_inputKeyMode = 2
        self.__ownUI.scaleProperties = GUI_SETTINGS.markerScaleSettings
        self.__ownUI.alphaProperties = GUI_SETTINGS.markerBgSettings
        self.__ownUIProxy = weakref.ref(self.__ownUI)
        self.__ownUIProxy().markerSetScale(g_settingsCore.interfaceScale.get())
        g_settingsCore.interfaceScale.onScaleChanged += self.updateMarkersScale
        self.__parentUI.component.addChild(self.__ownUI, 'vehicleMarkersManager')
        self.__markersCanvasUI = self.getMember('vehicleMarkersCanvas')
        self.__plugins.init()
        ctrl = g_sessionProvider.getFeedback()
        if ctrl is not None:
            ctrl.onVehicleMarkerAdded += self.__onVehicleMarkerAdded
            ctrl.onVehicleMarkerRemoved += self.__onVehicleMarkerRemoved
            ctrl.onVehicleFeedbackReceived += self.__onVehicleFeedbackReceived
        functional = g_sessionProvider.getDynSquadFunctional()
        if functional is not None:
            functional.onPlayerBecomeSquadman += self.__onPlayerBecomeSquadman
        self.__plugins.start()
        g_eventBus.addListener(GameEvent.SHOW_EXTENDED_INFO, self.__handleShowExtendedInfo, scope=_SCOPE)
        g_eventBus.addListener(GameEvent.GUI_VISIBILITY, self.__handleGUIVisibility, scope=_SCOPE)
        return

    def destroy(self):
        g_eventBus.removeListener(GameEvent.SHOW_EXTENDED_INFO, self.__handleShowExtendedInfo, scope=_SCOPE)
        g_eventBus.removeListener(GameEvent.GUI_VISIBILITY, self.__handleGUIVisibility, scope=_SCOPE)
        self.__plugins.stop()
        g_settingsCore.interfaceScale.onScaleChanged -= self.updateMarkersScale
        ctrl = g_sessionProvider.getFeedback()
        if ctrl is not None:
            ctrl.onVehicleMarkerAdded -= self.__onVehicleMarkerAdded
            ctrl.onVehicleMarkerRemoved -= self.__onVehicleMarkerRemoved
            ctrl.onVehicleFeedbackReceived -= self.__onVehicleFeedbackReceived
        functional = g_sessionProvider.getDynSquadFunctional()
        if functional is not None:
            functional.onPlayerBecomeSquadman -= self.__onPlayerBecomeSquadman
        if self.__parentUI is not None:
            setattr(self.__parentUI.component, 'vehicleMarkersManager', None)
        self.__plugins.fini()
        self.__parentUI = None
        self.__ownUI = None
        self.__markersCanvasUI = None
        self.colorManager.dispossessUI()
        self.close()
        return

    def _createVehicleMarker(self, isAlly, mProv):
        markerLinkage = 'VehicleMarkerAlly' if isAlly else 'VehicleMarkerEnemy'
        if arena_info.hasFlags():
            markerID = self.__ownUI.addFalloutMarker(mProv, markerLinkage)
        else:
            markerID = self.__ownUI.addMarker(mProv, markerLinkage)
        return markerID

    def addVehicleMarker(self, vProxy, vInfo, guiProps):
        vTypeDescr = vProxy.typeDescriptor
        maxHealth = vTypeDescr.maxHealth
        mProv = vProxy.model.node('HP_gui')
        isAlly = guiProps.isFriend
        speaking = False
        if GUI_SETTINGS.voiceChat:
            speaking = VoiceChatInterface.g_instance.isPlayerSpeaking(vInfo.player.accountDBID)
        hunting = VehicleActions.isHunting(vInfo.events)
        markerID = self._createVehicleMarker(isAlly, mProv)
        self.__markers[vInfo.vehicleID] = _VehicleMarker(markerID, vProxy, self.__ownUIProxy)
        battleCtx = g_sessionProvider.getCtx()
        result = battleCtx.getPlayerFullNameParts(vProxy.id)
        vType = vInfo.vehicleType
        teamIdx = -1
        if arena_info.isFalloutMultiTeam() and vInfo.isSquadMan():
            teamIdx = g_sessionProvider.getArenaDP().getMultiTeamsIndexes()[vInfo.team]
        self.invokeMarker(markerID, 'init', [vType.classTag,
         vType.iconPath,
         result.vehicleName,
         vType.level,
         result.playerFullName,
         result.playerName,
         result.clanAbbrev,
         result.regionCode,
         vProxy.health,
         maxHealth,
         guiProps.name(),
         speaking,
         hunting,
         guiProps.base,
         g_ctfManager.getVehicleCarriedFlagID(vInfo.vehicleID) is not None,
         teamIdx])
        return markerID

    def removeVehicleMarker(self, vehicleID):
        marker = self.__markers.pop(vehicleID, None)
        if marker is not None:
            self.__ownUI.delMarker(marker.id)
            marker.destroy()
        return

    def createStaticMarker(self, pos, symbol):
        mProv = Matrix()
        mProv.translation = pos
        handle = self.__ownUI.addMarker(mProv, symbol)
        return (mProv, handle)

    def destroyStaticMarker(self, handle):
        if self.__ownUI:
            self.__ownUI.delMarker(handle)

    def updateMarkerState(self, handle, newState, isImmediate = False):
        self.invokeMarker(handle, 'updateState', [newState, isImmediate])

    def showActionMarker(self, handle, newState):
        self.invokeMarker(handle, 'showActionMarker', [newState])

    def updateFlagbearerState(self, vehID, newState):
        marker = self.__markers.get(vehID)
        if marker is not None:
            self.invokeMarker(marker.id, 'updateFlagbearerState', [newState])
        return

    def updateVehicleHealth(self, handle, newHealth, aInfo, attackReasonID):
        if newHealth < 0 and not constants.SPECIAL_VEHICLE_HEALTH.IS_AMMO_BAY_DESTROYED(newHealth):
            newHealth = 0
        self.invokeMarker(handle, 'updateHealth', [newHealth, self.__getVehicleDamageType(aInfo), constants.ATTACK_REASONS[attackReasonID]])

    def showDynamic(self, vID, flag):
        if vID not in self.__markers:
            return
        marker = self.__markers[vID]
        self.invokeMarker(marker.id, 'setSpeaking', [flag])

    def updateMarkersScale(self, scale = None):
        if self.__ownUIProxy() is not None:
            if scale is None:
                self.__ownUIProxy().markerSetScale(g_settingsCore.interfaceScale.get())
            else:
                self.__ownUIProxy().markerSetScale(scale)
        return

    def setTeamKiller(self, vID):
        if vID not in self.__markers:
            return
        marker = self.__markers[vID]
        ctx = g_sessionProvider.getCtx()
        if not ctx.isTeamKiller(vID=vID) or ctx.isSquadMan(vID=vID) and not arena_info.isFalloutBattle():
            return
        self.invokeMarker(marker.id, 'setEntityName', [PLAYER_GUI_PROPS.teamKiller.name()])

    def invokeMarker(self, handle, function, args = None):
        if handle != -1:
            self.__ownUI.markerInvoke(handle, (function, args))

    def setMarkerSettings(self, settings):
        if self.__markersCanvasUI:
            self.__markersCanvasUI.setMarkerSettings(settings)

    def setMarkerDuration(self, value):
        self.__invokeCanvas('setMarkerDuration', [value])

    def updateMarkers(self):
        self.colorManager.update()
        for marker in self.__markers.itervalues():
            self.invokeMarker(marker.id, 'update')

        self.__plugins.update()

    def updateMarkerSettings(self):
        for marker in self.__markers.itervalues():
            self.invokeMarker(marker.id, 'updateMarkerSettings')

    def __invokeCanvas(self, function, args = None):
        if args is None:
            args = []
        self.call('battle.vehicleMarkersCanvas.' + function, args)
        return

    def __getVehicleDamageType(self, attackerInfo):
        if not attackerInfo:
            return _DAMAGE_TYPE.FROM_UNKNOWN
        attackerID = attackerInfo.vehicleID
        if attackerID == avatar_getter.getPlayerVehicleID():
            return _DAMAGE_TYPE.FROM_PLAYER
        entityName = g_sessionProvider.getCtx().getPlayerGuiProps(attackerID, attackerInfo.team)
        if entityName == PLAYER_GUI_PROPS.squadman:
            return _DAMAGE_TYPE.FROM_SQUAD
        if entityName == PLAYER_GUI_PROPS.ally:
            return _DAMAGE_TYPE.FROM_ALLY
        if entityName == PLAYER_GUI_PROPS.enemy:
            return _DAMAGE_TYPE.FROM_ENEMY
        return _DAMAGE_TYPE.FROM_UNKNOWN

    def __onVehicleMarkerAdded(self, vProxy, vInfo, guiProps):
        self.addVehicleMarker(vProxy, vInfo, guiProps)

    def __onVehicleMarkerRemoved(self, vehicleID):
        self.removeVehicleMarker(vehicleID)

    def __onVehicleFeedbackReceived(self, eventID, vehicleID, value):
        if vehicleID not in self.__markers:
            return
        marker = self.__markers[vehicleID]
        if eventID == _EVENT_ID.VEHICLE_HIT:
            self.updateMarkerState(marker.id, 'hit', value)
        elif eventID == _EVENT_ID.VEHICLE_ARMOR_PIERCED:
            self.updateMarkerState(marker.id, 'hit_pierced', value)
        elif eventID == _EVENT_ID.VEHICLE_DEAD:
            self.updateMarkerState(marker.id, 'dead', value)
        elif eventID == _EVENT_ID.VEHICLE_SHOW_MARKER:
            self.showActionMarker(marker.id, value)
        elif eventID == _EVENT_ID.VEHICLE_HEALTH:
            self.updateVehicleHealth(marker.id, *value)

    def __onPlayerBecomeSquadman(self, vehicleID, guiProps):
        if vehicleID not in self.__markers:
            return
        marker = self.__markers[vehicleID]
        self.invokeMarker(marker.id, 'setEntityName', [guiProps.name()])

    def __handleShowExtendedInfo(self, event):
        isDown = event.ctx['isDown']
        self.__invokeCanvas('setShowExInfoFlag', [isDown])
        for marker in self.__markers.itervalues():
            self.invokeMarker(marker.id, 'showExInfo', [isDown])

    def __handleGUIVisibility(self, event):
        self.active(event.ctx['visible'])
class CrosshairPanelContainer(ExternalFlashComponent, CrosshairPanelContainerMeta):
    sessionProvider = dependency.descriptor(IBattleSessionProvider)

    def __init__(self):
        super(CrosshairPanelContainer, self).__init__(ExternalFlashSettings(BATTLE_VIEW_ALIASES.CROSSHAIR_PANEL, settings.CROSSHAIR_CONTAINER_SWF, settings.CROSSHAIR_ROOT_PATH, settings.CROSSHAIR_INIT_CALLBACK))
        self.__plugins = PluginsCollection(self)
        self.__plugins.addPlugins(plugins.createPlugins())
        self.__gunMarkers = None
        self.__viewID = CROSSHAIR_VIEW_ID.UNDEFINED
        self.__zoomFactor = 0.0
        self.__scale = 1.0
        self.__distance = 0
        self.__hasAmmo = True
        return

    def getViewID(self):
        return self.__viewID

    def setViewID(self, viewID):
        if viewID != self.__viewID:
            self.__viewID = viewID
            if self.__gunMarkers is not None:
                self.__gunMarkers.switch(viewID)
            chosenSettingID = plugins.chooseSetting(self.__viewID)
            self.as_setViewS(self.__viewID, chosenSettingID)
        return

    def setPosition(self, x, y):
        self.as_recreateDeviceS(x, y)

    def getScale(self):
        return self.__scale

    def setScale(self, scale):
        if self.__scale == scale:
            return
        else:
            self.__scale = scale
            self.as_setScaleS(scale)
            if self.__gunMarkers is not None:
                self.__gunMarkers.setScale(scale)
            return

    def getZoom(self):
        return self.__zoomFactor

    def setZoom(self, zoomFactor):
        if zoomFactor == self.__zoomFactor:
            return
        self.__zoomFactor = zoomFactor
        if zoomFactor > 1:
            zoomString = i18n.makeString(INGAME_GUI.AIM_ZOOM, zoom=zoomFactor)
        else:
            zoomString = ''
        self.as_setZoomS(zoomString)

    def getDistance(self):
        return self.__distance

    def setDistance(self, distance):
        if distance != self.__distance:
            self.__distance = distance
            self.as_setDistanceS(i18n.makeString(INGAME_GUI.DISTANCE_METERS, meters=distance))

    def clearDistance(self, immediate=True):
        self.__distance = 0
        self.as_clearDistanceS(immediate)

    def setHasAmmo(self, hasAmmo):
        if self.__hasAmmo != hasAmmo:
            self.__hasAmmo = hasAmmo
            if not hasAmmo:
                self.as_updateAmmoStateS(i18n.makeString(INGAME_GUI.PLAYER_MESSAGES_POSTMORTEM_USERNOHASAMMO))
            else:
                self.as_updateAmmoStateS('')

    def setSettings(self, vo):
        self.as_setSettingsS(vo)

    def createGunMarkers(self, markersInfo, vehicleInfo):
        if self.__gunMarkers is not None:
            LOG_WARNING('Set of gun markers is already created.')
            return
        else:
            self.__setGunMarkers(gm_factory.createComponents(markersInfo, vehicleInfo))
            return

    def invalidateGunMarkers(self, markersInfo, vehicleInfo):
        if self.__gunMarkers is None:
            LOG_WARNING('Set of gun markers is not created')
            return
        else:
            newSet = gm_factory.overrideComponents(self.__gunMarkers, markersInfo, vehicleInfo)
            self.__clearGunMarkers()
            self.__setGunMarkers(newSet)
            return

    def setGunMarkerColor(self, markerType, color):
        if self.__gunMarkers is None:
            return False
        else:
            component = self.__gunMarkers.getComponentByType(markerType, isActive=True)
            if component is not None:
                self.as_setGunMarkerColorS(component.getName(), color)
            return True

    def startPlugins(self):
        self.__plugins.start()

    def stopPlugins(self):
        self.__clearGunMarkers()
        self.__plugins.stop()

    def createExternalComponent(self):
        super(CrosshairPanelContainer, self).createExternalComponent()
        self.__configure()

    def _populate(self):
        super(CrosshairPanelContainer, self)._populate()
        self.__plugins.init()
        self.startPlugins()

    def _dispose(self):
        self.stopPlugins()
        self.__plugins.fini()
        super(CrosshairPanelContainer, self)._dispose()

    def __configure(self):
        self.component.wg_inputKeyMode = InputKeyMode.NO_HANDLE
        self.component.position.z = DEPTH_OF_Aim
        self.component.focus = False
        self.component.moveFocus = False
        self.component.heightMode = 'PIXEL'
        self.component.widthMode = 'PIXEL'
        self.movie.backgroundAlpha = 0

    def __setGunMarkers(self, gunMarkers):
        self.__gunMarkers = gunMarkers
        viewSettings = self.__gunMarkers.getViewSettings()
        LOG_DEBUG('Present view settings of gun markers', viewSettings)
        for item in viewSettings:
            if item.hasView:
                continue
            if self.as_createGunMarkerS(item.viewID, item.linkage, item.name):
                self.__gunMarkers.addView(self.component, item.name)
                LOG_DEBUG('Gun marker has been created', item)
            LOG_ERROR('Gun marker can not be created', item)

        self.__gunMarkers.setScale(self.getScale())
        self.__gunMarkers.switch(self.getViewID())

    def __clearGunMarkers(self):
        if self.__gunMarkers is None:
            return
        else:
            viewSettings = self.__gunMarkers.getViewSettings()
            LOG_DEBUG('Previous view settings of gun markers', viewSettings)
            for item in viewSettings:
                if not item.hasView:
                    continue
                if self.as_destroyGunMarkerS(item.name):
                    self.__gunMarkers.removeView(self.component, item.name)
                    LOG_DEBUG('Gun marker has been destroyed', item)

            self.__gunMarkers.clear()
            self.__gunMarkers = None
            return
class MarkersManager(ExternalFlashComponent, VehicleMarkersManagerMeta,
                     plugins.IMarkersManager):
    settingsCore = dependency.descriptor(ISettingsCore)
    setablePluginsDict = {
        'area': plugins.AreaStaticMarkerPlugin,
        'teamAndControlPoints': plugins.TeamsOrControlsPointsPlugin
    }

    def __init__(self):
        super(MarkersManager, self).__init__(
            ExternalFlashSettings(
                BATTLE_VIEW_ALIASES.MARKERS_2D, settings.MARKERS_MANAGER_SWF,
                'root.vehicleMarkersCanvas',
                ROOT_SWF_CONSTANTS.BATTLE_VEHICLE_MARKERS_REGISTER_CALLBACK))
        self.__plugins = None
        self.__canvas = None
        self.__ids = set()
        self.__isIBCEnabled = False
        self.__isStickyEnabled = False
        self.__showBaseMarkers = False
        self.__showLocationMarkers = False
        return

    @property
    def __isMarkerHoveringEnabled(self):
        sessionProvider = dependency.instance(IBattleSessionProvider)
        arenaVisitor = sessionProvider.arenaVisitor
        return self.__isIBCEnabled and not (
            arenaVisitor.gui.isBootcampBattle()
            or sessionProvider.getCtx().isPlayerObserver()
            or arenaVisitor.gui.isBattleRoyale())

    def setScaleProps(self,
                      minScale=40,
                      maxScale=100,
                      defScale=100,
                      speed=3.0):
        self.__canvas.scaleProperties = (minScale, maxScale, defScale, speed)

    def setMarkerSettings(self, markerSettings, notify=False):
        self.as_setMarkerSettingsS(markerSettings)
        if notify:
            self.as_updateMarkersSettingsS()

    def setColorsSchemes(self, defaultSchemes, colorBlindSchemes):
        self.as_setColorSchemesS(defaultSchemes, colorBlindSchemes)

    def setColorBlindFlag(self, isColorBlind):
        self.as_setColorBlindS(isColorBlind)

    def setShowExInfoFlag(self, flag):
        if self.owner is None or not self.owner.isModalViewShown():
            self.as_setShowExInfoFlagS(flag)
        return

    def createMarker(self, symbol, matrixProvider=None, active=True):
        if active and matrixProvider is None:
            raise SoftException(
                'Active marker {} must has matrixProvider'.format(symbol))
        markerID = self.__canvas.addMarker(matrixProvider, symbol, active)
        self.__ids.add(markerID)
        return markerID

    def setMarkerActive(self, markerID, active):
        if markerID in self.__ids:
            self.__canvas.markerSetActive(markerID, active)
        else:
            _logger.error(
                'Marker %d is not added by given ID. Ids: %s. Active: %d',
                markerID, self.__ids, active)

    def setMarkerSticky(self, markerID, isSticky):
        if self.__isStickyEnabled and self.__isIBCEnabled:
            self.__canvas.markerSetSticky(markerID, isSticky)

    def setMarkerRenderInfo(self, markerID, minScale, bounds, innerBounds,
                            cullDistance, markerBoundsScale):
        self.__canvas.markerSetRenderInfo(markerID, minScale, bounds,
                                          innerBounds, cullDistance,
                                          markerBoundsScale)

    def setMarkerLocationOffset(self, markerID, minYOffset, maxYOffset,
                                distanceForMinYOffset, maxBoost, boostStart):
        self.__canvas.markerSetLocationOffset(markerID, minYOffset, maxYOffset,
                                              distanceForMinYOffset, maxBoost,
                                              boostStart)

    def setMarkerBoundCheckEnabled(self, markerID, enabled):
        self.__canvas.markerSetBoundCheckEnabled(markerID, enabled)

    def setMarkerObjectInFocus(self, markerID, inFocus):
        if not self.__isMarkerHoveringEnabled:
            return
        self.__canvas.markerSetMarkerObjectInFocus(markerID, inFocus)

    def setMarkerMinScale(self, markerID, minScale):
        self.__canvas.markerSetMinScale(markerID, minScale)

    def setMarkerMatrix(self, markerID, matrix):
        if markerID in self.__ids:
            self.__canvas.markerSetMatrix(markerID, matrix)
        else:
            _logger.error(
                'Marker %d is not added by given ID. Ids: %s. Matrix: %s',
                markerID, self.__ids, matrix)

    def destroyMarker(self, markerID):
        if self.__canvas:
            if markerID in self.__ids:
                self.__canvas.delMarker(markerID)
                self.__ids.discard(markerID)
            else:
                _logger.error('Marker %d is not added by given ID. Ids: %s',
                              markerID, self.__ids)

    def invokeMarker(self, markerID, *signature):
        if markerID in self.__ids:
            self.__canvas.markerInvoke(markerID, signature)
        else:
            _logger.error(
                'Marker %d is not added by given ID. Ids: %s. Signature: %s',
                markerID, self.__ids, signature)

    def updateCameraAimOffset(self, offset):
        self.__canvas.updateCameraAimOffset(offset)

    def setActiveCameraAimOffset(self, aimOffset):
        self.__canvas.activeCameraAimOffset = aimOffset

    def getPlugin(self, name):
        return self.__plugins.getPlugin(
            name) if self.__plugins is not None else None

    def startPlugins(self):
        if not isPlayerAvatar():
            log = _logger.warning if BattleReplay.g_replayCtrl.isPlaying else _logger.error
            log('Failed to start plugins for %s', self.__class__.__name__)
            return
        else:
            sessionProvider = dependency.instance(IBattleSessionProvider)
            if sessionProvider is not None:
                arenaVisitor = sessionProvider.arenaVisitor
                self.__addCanvas(sessionProvider, arenaVisitor)
                self.__setMarkerDuration()
                self.__createPlugins(arenaVisitor)
                self.fireEvent(
                    MarkersManagerEvent(MarkersManagerEvent.MARKERS_CREATED,
                                        self), EVENT_BUS_SCOPE.BATTLE)
            else:
                _logger.error('Could not create component due to data missing')
            return

    def stopPlugins(self):
        self.__destroyPlugins()
        self.__removeCanvas()

    def getCurrentlyAimedAtMarkerIDAndType(self):
        if not self.__isMarkerHoveringEnabled:
            return (INVALID_MARKER_ID, MarkerType.INVALID_MARKER_TYPE,
                    INVALID_MARKER_SUBTYPE)
        else:
            aimedAtMarkerID = self.__canvas.getAimedAtMarker()
            if aimedAtMarkerID is None:
                return (INVALID_MARKER_ID, MarkerType.INVALID_MARKER_TYPE,
                        INVALID_MARKER_SUBTYPE)
            for pluginName in self.__plugins:
                plugin = self.__plugins.getPlugin(pluginName)
                if plugin is None:
                    continue
                targetID = plugin.getTargetIDFromMarkerID(aimedAtMarkerID)
                if targetID > -1:
                    return (targetID, plugin.getMarkerType(),
                            plugin.getMarkerSubtype(targetID))

            return (INVALID_MARKER_ID, MarkerType.INVALID_MARKER_TYPE,
                    INVALID_MARKER_SUBTYPE)

    def createExternalComponent(self):
        super(MarkersManager, self).createExternalComponent()
        self.component.wg_inputKeyMode = InputKeyMode.NO_HANDLE
        self.component.position.z = DEPTH_OF_VehicleMarker
        self.component.drawWithRestrictedViewPort = False
        self.movie.backgroundAlpha = 0

    def _populate(self):
        super(MarkersManager, self)._populate()
        self.__isIBCEnabled = bool(
            self.settingsCore.getSetting(
                BattleCommStorageKeys.ENABLE_BATTLE_COMMUNICATION))
        self.__isStickyEnabled = bool(
            self.settingsCore.getSetting(
                BattleCommStorageKeys.SHOW_STICKY_MARKERS))
        self.__showBaseMarkers = bool(
            self.settingsCore.getSetting(
                BattleCommStorageKeys.SHOW_BASE_MARKERS))
        self.__showLocationMarkers = bool(
            self.settingsCore.getSetting(
                BattleCommStorageKeys.SHOW_LOCATION_MARKERS))
        self.settingsCore.onSettingsChanged += self.__onSettingsChange
        self.startPlugins()

    def _dispose(self):
        self.stopPlugins()
        self.settingsCore.onSettingsChanged -= self.__onSettingsChange
        super(MarkersManager, self)._dispose()

    def _createCanvas(self, arenaVisitor):
        return GUI.WGVehicleMarkersCanvasFlashAS3(self.movie)

    def _setupPlugins(self, arenaVisitor):
        setup = {
            'eventBus': plugins.EventBusPlugin,
            'equipments': plugins.EquipmentsMarkerPlugin,
            'vehiclesTargets': plugins.VehicleMarkerTargetPlugin,
            'controlMode': plugins.ControlModePlugin,
            'area_markers': plugins.AreaMarkerPlugin
        }
        if self.__showBaseMarkers:
            setup['teamAndControlPoints'] = plugins.TeamsOrControlsPointsPlugin
        if self.__showLocationMarkers:
            setup['area'] = plugins.AreaStaticMarkerPlugin
        if BattleReplay.g_replayCtrl.isPlaying:
            setup[
                'vehiclesTargets'] = plugins.VehicleMarkerTargetPluginReplayPlaying
        if BattleReplay.g_replayCtrl.isRecording:
            setup[
                'vehiclesTargets'] = plugins.VehicleMarkerTargetPluginReplayRecording
        if arenaVisitor.hasRespawns():
            setup['vehicles'] = vehicle_plugins.RespawnableVehicleMarkerPlugin
        else:
            setup['vehicles'] = vehicle_plugins.VehicleMarkerPlugin
        setup['settings'] = plugins.SettingsPlugin
        return setup

    def __addCanvas(self, sessionProvider, arenaVisitor):
        self.__canvas = self._createCanvas(arenaVisitor)
        self.__canvas.script = self
        self.__canvas.wg_inputKeyMode = InputKeyMode.NO_HANDLE
        self.__canvas.scaleProperties = GUI_SETTINGS.markerScaleSettings
        self.__canvas.enableMarkerHovering = self.__isMarkerHoveringEnabled
        self.__canvas.stickyMarkerRadiusScale = _STICKY_MARKER_RADIUS_SCALE
        self.__canvasProxy = weakref.ref(self.__canvas)
        self.component.addChild(self.__canvas, 'vehicleMarkersCanvas')

    def __removeCanvas(self):
        if self.__canvas is not None:
            self.component.delChild(self.__canvas)
        self.__canvas = None
        self.__canvasProxy = None
        return

    def __setMarkerDuration(self):
        self.as_setMarkerDurationS(GUI_SETTINGS.markerHitSplashDuration)

    def __createPlugins(self, arenaVisitor):
        setup = self._setupPlugins(arenaVisitor)
        self.__plugins = PluginsCollection(self)
        self.__plugins.addPlugins(setup)
        self.__plugins.init()
        self.__plugins.start()

    def __destroyPlugins(self):
        if self.__plugins is not None:
            self.__plugins.stop()
            self.__plugins.fini()
        return

    def __onSettingsChange(self, diff):
        addSettings = {}
        for item in diff:
            if item in (BattleCommStorageKeys.ENABLE_BATTLE_COMMUNICATION,
                        BattleCommStorageKeys.SHOW_STICKY_MARKERS,
                        BattleCommStorageKeys.SHOW_BASE_MARKERS,
                        BattleCommStorageKeys.SHOW_LOCATION_MARKERS):
                addSettings[item] = diff[item]

        if not addSettings:
            return
        newIBCEnabled = bool(
            addSettings.get(BattleCommStorageKeys.ENABLE_BATTLE_COMMUNICATION,
                            self.__isIBCEnabled))
        newShowBaseMarkers = bool(
            addSettings.get(BattleCommStorageKeys.SHOW_BASE_MARKERS,
                            self.__showBaseMarkers))
        newIsSticky = bool(
            addSettings.get(BattleCommStorageKeys.SHOW_STICKY_MARKERS,
                            self.__isStickyEnabled))
        new3DMarkers = bool(
            addSettings.get(BattleCommStorageKeys.SHOW_LOCATION_MARKERS,
                            self.__showLocationMarkers))
        if newIBCEnabled != self.__isIBCEnabled:
            self.__isIBCEnabled = newIBCEnabled
            self.__canvas.enableMarkerHovering = self.__isMarkerHoveringEnabled
        if not newIsSticky:
            for markerId in self.__ids:
                self.__canvas.markerSetSticky(markerId, False)

        if newShowBaseMarkers != self.__showBaseMarkers:
            self.__setPlugin(pluginName='teamAndControlPoints',
                             startPlugin=newShowBaseMarkers)
            self.__showBaseMarkers = newShowBaseMarkers
        if new3DMarkers != self.__showLocationMarkers:
            self.__setPlugin(pluginName='area', startPlugin=new3DMarkers)
            self.__showLocationMarkers = new3DMarkers
        self.__isStickyEnabled = newIsSticky

    def __setPlugin(self, pluginName, startPlugin):
        plugin = self.__plugins.getPlugin(pluginName)
        if not plugin and startPlugin:
            self.__plugins.addPlugins(
                {pluginName: self.setablePluginsDict[pluginName]})
            plugin = self.__plugins.getPlugin(pluginName)
            plugin.init()
        if startPlugin:
            plugin.start()
        elif plugin:
            plugin.stop()
Ejemplo n.º 12
0
class MarkersManager(Flash, IDynSquadEntityClient):
    __SWF_FILE_NAME = 'VehicleMarkersManager.swf'
    MARKER_POSITION_ADJUSTMENT = Vector3(0.0, 12.0, 0.0)

    class DAMAGE_TYPE:
        FROM_UNKNOWN = 0
        FROM_ALLY = 1
        FROM_ENEMY = 2
        FROM_SQUAD = 3
        FROM_PLAYER = 4

    def __init__(self, parentUI):
        Flash.__init__(self, self.__SWF_FILE_NAME)
        self.component.wg_inputKeyMode = 2
        self.component.position.z = DEPTH_OF_VehicleMarker
        self.component.drawWithRestrictedViewPort = False
        self.movie.backgroundAlpha = 0
        self.colorManager = ColorSchemeManager._ColorSchemeManager()
        self.colorManager.populateUI(weakref.proxy(self))
        self.__plugins = PluginsCollection(self)
        plugins = {'equipments': _EquipmentsMarkerPlugin}
        if isEventBattle():
            plugins.update({'flags': _FlagsMarkerPlugin,
             'repairs': _RepairsMarkerPlugin})
        self.__plugins.addPlugins(plugins)
        self.__ownUI = None
        self.__parentUI = parentUI
        self.__markers = dict()
        return

    def updateSquadmanVeh(self, vID):
        handle = getattr(BigWorld.entity(vID), 'marker', None)
        if handle is not None:
            self.invokeMarker(handle, 'setEntityName', [PLAYER_ENTITY_NAME.squadman.name()])
        return

    def showExtendedInfo(self, value):
        self.__invokeCanvas('setShowExInfoFlag', [value])
        for handle in self.__markers.iterkeys():
            self.invokeMarker(handle, 'showExInfo', [value])

    def setScaleProps(self, minScale = 40, maxScale = 100, defScale = 100, speed = 3.0):
        if constants.IS_DEVELOPMENT:
            self.__ownUI.scaleProperties = (minScale,
             maxScale,
             defScale,
             speed)

    def setAlphaProps(self, minAlpha = 40, maxAlpha = 100, defAlpha = 100, speed = 3.0):
        if constants.IS_DEVELOPMENT:
            self.__ownUI.alphaProperties = (minAlpha,
             maxAlpha,
             defAlpha,
             speed)

    def start(self):
        self.active(True)
        self.__ownUI = GUI.WGVehicleMarkersCanvasFlash(self.movie)
        self.__ownUI.wg_inputKeyMode = 2
        self.__ownUI.scaleProperties = GUI_SETTINGS.markerScaleSettings
        self.__ownUI.alphaProperties = GUI_SETTINGS.markerBgSettings
        self.__ownUIProxy = weakref.ref(self.__ownUI)
        self.__ownUIProxy().markerSetScale(g_settingsCore.interfaceScale.get())
        g_settingsCore.interfaceScale.onScaleChanged += self.updateMarkersScale
        self.__parentUI.component.addChild(self.__ownUI, 'vehicleMarkersManager')
        self.__markersCanvasUI = self.getMember('vehicleMarkersCanvas')
        self.__plugins.init()
        self.__plugins.start()

    def destroy(self):
        self.__plugins.stop()
        g_settingsCore.interfaceScale.onScaleChanged -= self.updateMarkersScale
        if self.__parentUI is not None:
            setattr(self.__parentUI.component, 'vehicleMarkersManager', None)
        self.__plugins.fini()
        self.__parentUI = None
        self.__ownUI = None
        self.__markersCanvasUI = None
        self.colorManager.dispossessUI()
        self.close()
        return

    def createMarker(self, vProxy):
        vInfo = dict(vProxy.publicInfo)
        battleCtx = g_sessionProvider.getCtx()
        if battleCtx.isObserver(vProxy.id):
            return -1
        isFriend = vInfo['team'] == BigWorld.player().team
        vehID = vProxy.id
        vInfoEx = g_sessionProvider.getArenaDP().getVehicleInfo(vehID)
        vTypeDescr = vProxy.typeDescriptor
        maxHealth = vTypeDescr.maxHealth
        mProv = vProxy.model.node('HP_gui')
        tags = set(vTypeDescr.type.tags & VEHICLE_CLASS_TAGS)
        vClass = tags.pop() if len(tags) > 0 else ''
        entityName = battleCtx.getPlayerEntityName(vehID, vInfoEx.team)
        entityType = 'ally' if BigWorld.player().team == vInfoEx.team else 'enemy'
        speaking = False
        if GUI_SETTINGS.voiceChat:
            speaking = VoiceChatInterface.g_instance.isPlayerSpeaking(vInfoEx.player.accountDBID)
        hunting = VehicleActions.isHunting(vInfoEx.events)
        handle = self.__ownUI.addMarker(mProv, 'VehicleMarkerAlly' if isFriend else 'VehicleMarkerEnemy')
        self.__markers[handle] = _VehicleMarker(vProxy, self.__ownUIProxy(), handle)
        fullName, pName, clanAbbrev, regionCode, vehShortName = battleCtx.getFullPlayerNameWithParts(vProxy.id)
        self.invokeMarker(handle, 'init', [vClass,
         vInfoEx.vehicleType.iconPath,
         vehShortName,
         vInfoEx.vehicleType.level,
         fullName,
         pName,
         clanAbbrev,
         regionCode,
         vProxy.health,
         maxHealth,
         entityName.name(),
         speaking,
         hunting,
         entityType,
         self.isVehicleFlagbearer(vehID)])
        return handle

    def destroyMarker(self, handle):
        if self.__markers.has_key(handle):
            self.__markers[handle].destroy()
            del self.__markers[handle]
            self.__ownUI.delMarker(handle)

    def createStaticMarker(self, pos, symbol):
        mProv = Matrix()
        mProv.translation = pos
        handle = self.__ownUI.addMarker(mProv, symbol)
        return (mProv, handle)

    def destroyStaticMarker(self, handle):
        if self.__ownUI:
            self.__ownUI.delMarker(handle)

    def updateMarkerState(self, handle, newState, isImmediate = False):
        self.invokeMarker(handle, 'updateState', [newState, isImmediate])

    def showActionMarker(self, handle, newState):
        self.invokeMarker(handle, 'showActionMarker', [newState])

    def updateFlagbearerState(self, handle, newState):
        self.invokeMarker(handle, 'updateFlagbearerState', [newState])

    def onVehicleHealthChanged(self, handle, curHealth, attackerID = -1, attackReasonID = 0):
        replayCtrl = BattleReplay.g_replayCtrl
        if replayCtrl.isPlaying and replayCtrl.isTimeWarpInProgress:
            return
        if curHealth < 0 and curHealth not in constants.SPECIAL_VEHICLE_HEALTH.AMMO_BAY_EXPLOSION:
            curHealth = 0
        self.invokeMarker(handle, 'updateHealth', [curHealth, self.__getVehicleDamageType(attackerID), constants.ATTACK_REASONS[attackReasonID]])

    def showDynamic(self, vID, flag):
        handle = getattr(BigWorld.entity(vID), 'marker', None)
        if handle is not None and GUI_SETTINGS.voiceChat:
            self.invokeMarker(handle, 'setSpeaking', [flag])
        return

    def updateMarkersScale(self, scale = None):
        if self.__ownUIProxy() is not None:
            if scale is None:
                self.__ownUIProxy().markerSetScale(g_settingsCore.interfaceScale.get())
            else:
                self.__ownUIProxy().markerSetScale(scale)
        return

    def setTeamKiller(self, vID):
        ctx = g_sessionProvider.getCtx()
        if not ctx.isTeamKiller(vID=vID) or ctx.isSquadMan(vID=vID):
            return
        else:
            handle = getattr(BigWorld.entity(vID), 'marker', None)
            if handle is not None:
                self.invokeMarker(handle, 'setEntityName', [PLAYER_ENTITY_NAME.teamKiller.name()])
            return

    def invokeMarker(self, handle, function, args = None):
        if handle == -1:
            return
        else:
            if args is None:
                args = []
            self.__ownUI.markerInvoke(handle, (function, args))
            return

    def setMarkerSettings(self, settings):
        if self.__markersCanvasUI:
            self.__markersCanvasUI.setMarkerSettings(settings)

    def setMarkerDuration(self, value):
        self.__invokeCanvas('setMarkerDuration', [value])

    def updateMarkers(self):
        self.colorManager.update()
        for handle in self.__markers.iterkeys():
            self.invokeMarker(handle, 'update', [])

    def updateMarkerSettings(self):
        for handle in self.__markers.iterkeys():
            self.invokeMarker(handle, 'updateMarkerSettings', [])

    def isVehicleFlagbearer(self, vehicleID):
        for flagID in g_ctfManager.getFlags():
            flagInfo = g_ctfManager.getFlagInfo(flagID)
            if flagInfo['vehicle'] == vehicleID:
                return True

        return False

    def __invokeCanvas(self, function, args = None):
        if args is None:
            args = []
        self.call('battle.vehicleMarkersCanvas.' + function, args)
        return

    def __getVehicleDamageType(self, attackerID):
        if not attackerID:
            return MarkersManager.DAMAGE_TYPE.FROM_UNKNOWN
        if attackerID == BigWorld.player().playerVehicleID:
            return MarkersManager.DAMAGE_TYPE.FROM_PLAYER
        entityName = g_sessionProvider.getCtx().getPlayerEntityName(attackerID, BigWorld.player().arena.vehicles.get(attackerID, dict()).get('team'))
        if entityName == PLAYER_ENTITY_NAME.squadman:
            return MarkersManager.DAMAGE_TYPE.FROM_SQUAD
        if entityName == PLAYER_ENTITY_NAME.ally:
            return MarkersManager.DAMAGE_TYPE.FROM_ALLY
        if entityName == PLAYER_ENTITY_NAME.enemy:
            return MarkersManager.DAMAGE_TYPE.FROM_ENEMY
        return MarkersManager.DAMAGE_TYPE.FROM_UNKNOWN
Ejemplo n.º 13
0
class CrosshairPanelContainer(ExternalFlashComponent, CrosshairPanelContainerMeta):
    sessionProvider = dependency.descriptor(IBattleSessionProvider)

    def __init__(self):
        super(CrosshairPanelContainer, self).__init__(ExternalFlashSettings(BATTLE_VIEW_ALIASES.CROSSHAIR_PANEL, settings.CROSSHAIR_CONTAINER_SWF, settings.CROSSHAIR_ROOT_PATH, settings.CROSSHAIR_INIT_CALLBACK))
        self.__plugins = PluginsCollection(self)
        self.__plugins.addPlugins(plugins.createPlugins())
        self.__gunMarkers = None
        self.__viewID = CROSSHAIR_VIEW_ID.UNDEFINED
        self.__zoomFactor = 0.0
        self.__scale = 1.0
        self.__distance = 0
        self.__hasAmmo = True
        self.__callbackDelayer = None
        self.__isFaded = False
        return

    def getViewID(self):
        return self.__viewID

    def setViewID(self, viewID):
        if viewID != self.__viewID:
            self.__viewID = viewID
            if self.__gunMarkers is not None:
                self.__gunMarkers.switch(viewID)
            chosenSettingID = plugins.chooseSetting(self.__viewID)
            self.as_setViewS(self.__viewID, chosenSettingID)
        return

    def setPosition(self, x, y):
        self.as_recreateDeviceS(x, y)

    def getScale(self):
        return self.__scale

    def setScale(self, scale):
        if self.__scale == scale:
            return
        else:
            self.__scale = scale
            self.as_setScaleS(scale)
            if self.__gunMarkers is not None:
                self.__gunMarkers.setScale(scale)
            return

    def getZoom(self):
        return self.__zoomFactor

    def setZoom(self, zoomFactor):
        if zoomFactor == self.__zoomFactor:
            return
        self.__zoomFactor = zoomFactor
        if zoomFactor > 1:
            zoomString = i18n.makeString(INGAME_GUI.AIM_ZOOM, zoom=zoomFactor)
        else:
            zoomString = ''
        self.as_setZoomS(zoomString)

    def getDistance(self):
        return self.__distance

    def setDistance(self, distance):
        if distance != self.__distance:
            self.__distance = distance
            self.as_setDistanceS(i18n.makeString(INGAME_GUI.DISTANCE_METERS, meters=distance))

    def clearDistance(self, immediate=True):
        self.__distance = 0
        self.as_clearDistanceS(immediate)

    def setHasAmmo(self, hasAmmo):
        if self.__hasAmmo != hasAmmo:
            self.__hasAmmo = hasAmmo
            if not hasAmmo:
                self.as_updateAmmoStateS(i18n.makeString(INGAME_GUI.PLAYER_MESSAGES_POSTMORTEM_USERNOHASAMMO))
            else:
                self.as_updateAmmoStateS('')

    def setSettings(self, vo):
        self.as_setSettingsS(vo)

    def createGunMarkers(self, markersInfo, vehicleInfo):
        if self.__gunMarkers is not None:
            LOG_WARNING('Set of gun markers is already created.')
            return
        else:
            self.__setGunMarkers(gm_factory.createComponents(markersInfo, vehicleInfo))
            return

    def invalidateGunMarkers(self, markersInfo, vehicleInfo):
        if self.__gunMarkers is None:
            LOG_WARNING('Set of gun markers is not created')
            return
        else:
            newSet = gm_factory.overrideComponents(self.__gunMarkers, markersInfo, vehicleInfo)
            self.__clearGunMarkers()
            self.__setGunMarkers(newSet)
            return

    def setGunMarkerColor(self, markerType, color):
        if self.__gunMarkers is None:
            return False
        else:
            component = self.__gunMarkers.getComponentByType(markerType, isActive=True)
            if component is not None:
                self.as_setGunMarkerColorS(component.getName(), color)
            return True

    def startPlugins(self):
        if not isPlayerAvatar():
            log = _logger.warning if BattleReplay.g_replayCtrl.isPlaying else _logger.error
            log('Failed to start plugins for %s', self.__class__.__name__)
            return
        self.__plugins.start()

    def stopPlugins(self):
        self.__clearGunMarkers()
        self.__plugins.stop()

    def createExternalComponent(self):
        super(CrosshairPanelContainer, self).createExternalComponent()
        self.__configure()

    def as_playSound(self, value):
        AutoloaderBoostSoundEvents.play(value)

    def _populate(self):
        super(CrosshairPanelContainer, self)._populate()
        self.__plugins.init()
        self.startPlugins()
        g_eventBus.addListener(GameEvent.ROLE_HINT_TOGGLE, self.__handleRoleHintToggled, scope=EVENT_BUS_SCOPE.BATTLE)
        self.__callbackDelayer = CallbackDelayer()
        if RoleHelpPlugin.isAvailableToShow():
            self.__toggleFade(True)

    def _dispose(self):
        self.stopPlugins()
        self.__plugins.fini()
        if self.__callbackDelayer:
            self.__callbackDelayer.destroy()
        g_eventBus.removeListener(GameEvent.ROLE_HINT_TOGGLE, self.__handleRoleHintToggled, scope=EVENT_BUS_SCOPE.BATTLE)
        super(CrosshairPanelContainer, self)._dispose()

    def __handleRoleHintToggled(self, event):
        self.__toggleFade(event.ctx.get('isShown', False))

    def __toggleFade(self, isFaded):
        if self.__isFaded == isFaded:
            return
        self.__isFaded = isFaded
        if self.__isFaded:
            self.__callbackDelayer.delayCallback(FADE_TIMEOUT, self.__exceptionalFadeIn)
        else:
            self.__callbackDelayer.stopCallback(self.__exceptionalFadeIn)
        self.as_isFadedS(self.__isFaded)

    def __exceptionalFadeIn(self):
        self.__toggleFade(False)
        _logger.error('as_isFadedS must be called by GameEvent.ROLE_HINT_TOGGLE in __handleRoleHintToggled')

    def __configure(self):
        self.component.wg_inputKeyMode = InputKeyMode.NO_HANDLE
        self.component.position.z = DEPTH_OF_Aim
        self.component.focus = False
        self.component.moveFocus = False
        self.component.heightMode = 'PIXEL'
        self.component.widthMode = 'PIXEL'
        self.movie.backgroundAlpha = 0

    def __setGunMarkers(self, gunMarkers):
        self.__gunMarkers = gunMarkers
        viewSettings = self.__gunMarkers.getViewSettings()
        LOG_DEBUG('Present view settings of gun markers', viewSettings)
        for item in viewSettings:
            if item.hasView:
                continue
            if self.as_createGunMarkerS(item.viewID, item.linkage, item.name):
                self.__gunMarkers.addView(self.component, item.name)
                LOG_DEBUG('Gun marker has been created', item)
            LOG_ERROR('Gun marker can not be created', item)

        self.__gunMarkers.setScale(self.getScale())
        self.__gunMarkers.switch(self.getViewID())

    def __clearGunMarkers(self):
        if self.__gunMarkers is None:
            return
        else:
            viewSettings = self.__gunMarkers.getViewSettings()
            LOG_DEBUG('Previous view settings of gun markers', viewSettings)
            for item in viewSettings:
                if not item.hasView:
                    continue
                if self.as_destroyGunMarkerS(item.name):
                    self.__gunMarkers.removeView(self.component, item.name)
                    LOG_DEBUG('Gun marker has been destroyed', item)

            self.__gunMarkers.clear()
            self.__gunMarkers = None
            return
Ejemplo n.º 14
0
class MarkersManager(ExternalFlashComponent, VehicleMarkersManagerMeta,
                     plugins.IMarkersManager):
    def __init__(self):
        super(MarkersManager, self).__init__(
            ExternalFlashSettings(
                BATTLE_VIEW_ALIASES.MARKERS_2D, settings.MARKERS_MANAGER_SWF,
                'root.vehicleMarkersCanvas',
                ROOT_SWF_CONSTANTS.BATTLE_VEHICLE_MARKERS_REGISTER_CALLBACK))
        self.component.wg_inputKeyMode = 2
        self.component.position.z = DEPTH_OF_VehicleMarker
        self.component.drawWithRestrictedViewPort = False
        self.movie.backgroundAlpha = 0
        self.__plugins = None
        self.__canvas = None
        self.__ids = set()
        return

    def setScaleProps(self,
                      minScale=40,
                      maxScale=100,
                      defScale=100,
                      speed=3.0):
        self.__canvas.scaleProperties = (minScale, maxScale, defScale, speed)

    def setAlphaProps(self,
                      minAlpha=40,
                      maxAlpha=100,
                      defAlpha=100,
                      speed=3.0):
        self.__canvas.alphaProperties = (minAlpha, maxAlpha, defAlpha, speed)

    def setMarkerSettings(self, markerSettings, notify=False):
        self.as_setMarkerSettingsS(markerSettings)
        if notify:
            self.as_updateMarkersSettingsS()

    def setColorsSchemes(self, defaultSchemes, colorBlindSchemes):
        self.as_setColorSchemesS(defaultSchemes, colorBlindSchemes)

    def setColorBlindFlag(self, isColorBlind):
        self.as_setColorBlindS(isColorBlind)

    def setShowExInfoFlag(self, flag):
        if self.owner is None or not self.owner.isModalViewShown():
            self.as_setShowExInfoFlagS(flag)
        return

    def createMarker(self, symbol, matrixProvider=None, active=True):
        if active and matrixProvider is None:
            raise SoftException(
                'Active marker {} must has matrixProvider'.format(symbol))
        markerID = self.__canvas.addMarker(matrixProvider, symbol, active)
        self.__ids.add(markerID)
        return markerID

    def setMarkerActive(self, markerID, active):
        if markerID in self.__ids:
            self.__canvas.markerSetActive(markerID, active)
        else:
            _logger.error('Marker %d is not added by given ID', markerID)

    def setMarkerSticky(self, markerID, isSticky):
        self.__canvas.markerSetSticky(markerID, isSticky)

    def setMarkerMinScale(self, markerID, minScale):
        self.__canvas.markerSetMinScale(markerID, minScale)

    def setMarkerMatrix(self, markerID, matrix):
        if markerID in self.__ids:
            self.__canvas.markerSetMatrix(markerID, matrix)
        else:
            _logger.error('Marker %d is not added by given ID', markerID)

    def destroyMarker(self, markerID):
        if self.__canvas:
            if markerID in self.__ids:
                self.__canvas.delMarker(markerID)
                self.__ids.discard(markerID)
            else:
                _logger.error('Marker %d is not added by given ID', markerID)

    def invokeMarker(self, markerID, *signature):
        if markerID in self.__ids:
            self.__canvas.markerInvoke(markerID, signature)
        else:
            _logger.error('Marker %d is not added by given ID', markerID)

    def getPlugin(self, name):
        return self.__plugins.getPlugin(
            name) if self.__plugins is not None else None

    def startPlugins(self):
        sessionProvider = dependency.instance(IBattleSessionProvider)
        if sessionProvider is not None:
            arenaVisitor = sessionProvider.arenaVisitor
            self.__addCanvas(arenaVisitor)
            self.__setMarkerDuration()
            self.__createPlugins(arenaVisitor)
        else:
            _logger.error('Could not create component due to data missing')
        return

    def stopPlugins(self):
        self.__destroyPlugins()
        self.__removeCanvas()

    def _populate(self):
        super(MarkersManager, self)._populate()
        self.startPlugins()

    def _dispose(self):
        self.stopPlugins()
        super(MarkersManager, self)._dispose()

    def _createCanvas(self, arenaVisitor):
        return GUI.WGVehicleMarkersCanvasFlashAS3(self.movie)

    def _setupPlugins(self, arenaVisitor):
        setup = {
            'settings': plugins.SettingsPlugin,
            'eventBus': plugins.EventBusPlugin,
            'equipments': plugins.EquipmentsMarkerPlugin,
            'area': plugins.AreaStaticMarkerPlugin
        }
        if arenaVisitor.hasRespawns():
            setup['vehicles'] = plugins.RespawnableVehicleMarkerPlugin
        else:
            setup['vehicles'] = plugins.VehicleMarkerPlugin
        return setup

    def __addCanvas(self, arenaVisitor):
        self.__canvas = self._createCanvas(arenaVisitor)
        self.__canvas.wg_inputKeyMode = 2
        self.__canvas.scaleProperties = GUI_SETTINGS.markerScaleSettings
        self.__canvas.alphaProperties = GUI_SETTINGS.markerBgSettings
        self.__canvasProxy = weakref.ref(self.__canvas)
        self.component.addChild(self.__canvas, 'vehicleMarkersCanvas')

    def __removeCanvas(self):
        if self.__canvas is not None:
            self.component.delChild(self.__canvas)
        self.__canvas = None
        self.__canvasProxy = None
        return

    def __setMarkerDuration(self):
        self.as_setMarkerDurationS(GUI_SETTINGS.markerHitSplashDuration)

    def __createPlugins(self, arenaVisitor):
        setup = self._setupPlugins(arenaVisitor)
        self.__plugins = PluginsCollection(self)
        self.__plugins.addPlugins(setup)
        self.__plugins.init()
        self.__plugins.start()

    def __destroyPlugins(self):
        if self.__plugins is not None:
            self.__plugins.stop()
            self.__plugins.fini()
        return
Ejemplo n.º 15
0
class Battle(BattleWindow):
    teamBasesPanel = property(lambda self: self.__teamBasesPanel)
    timersBar = property(lambda self: self.__timersBar)
    consumablesPanel = property(lambda self: self.__consumablesPanel)
    damagePanel = property(lambda self: self.__damagePanel)
    markersManager = property(lambda self: self.__markersManager)
    vErrorsPanel = property(lambda self: self.__vErrorsPanel)
    vMsgsPanel = property(lambda self: self.__vMsgsPanel)
    pMsgsPanel = property(lambda self: self.__pMsgsPanel)
    minimap = property(lambda self: self.__minimap)
    radialMenu = property(lambda self: self.__radialMenu)
    damageInfoPanel = property(lambda self: self.__damageInfoPanel)
    fragCorrelation = property(lambda self: self.__fragCorrelation)
    statsForm = property(lambda self: self.__statsForm)
    leftPlayersPanel = property(lambda self: self.__leftPlayersPanel)
    rightPlayersPanel = property(lambda self: self.__rightPlayersPanel)
    ribbonsPanel = property(lambda self: self.__ribbonsPanel)
    ppSwitcher = property(lambda self: self.__ppSwitcher)
    VEHICLE_DESTROY_TIMER = {'ALL': 'all',
     constants.VEHICLE_MISC_STATUS.VEHICLE_DROWN_WARNING: 'drown',
     constants.VEHICLE_MISC_STATUS.VEHICLE_IS_OVERTURNED: 'overturn'}
    VEHICLE_DEATHZONE_TIMER = {'ALL': 'all',
     constants.DEATH_ZONES.STATIC: 'death_zone',
     constants.DEATH_ZONES.GAS_ATTACK: 'gas_attack'}
    VEHICLE_DEATHZONE_TIMER_SOUND = {constants.DEATH_ZONES.GAS_ATTACK: {'warning': 'fallout_gaz_sphere_warning',
                                        'critical': 'fallout_gaz_sphere_timer'}}
    __cameraVehicleID = -1
    __stateHandlers = {VEHICLE_VIEW_STATE.FIRE: '_setFireInVehicle',
     VEHICLE_VIEW_STATE.SHOW_DESTROY_TIMER: '_showVehicleTimer',
     VEHICLE_VIEW_STATE.HIDE_DESTROY_TIMER: '_hideVehicleTimer',
     VEHICLE_VIEW_STATE.SHOW_DEATHZONE_TIMER: 'showDeathzoneTimer',
     VEHICLE_VIEW_STATE.HIDE_DEATHZONE_TIMER: 'hideDeathzoneTimer',
     VEHICLE_VIEW_STATE.OBSERVED_BY_ENEMY: '_showSixthSenseIndicator'}

    def __init__(self, appNS):
        g_sessionProvider.registerViewComponents(*_COMPONENTS_TO_CTRLS)
        self.__ns = appNS
        self.__soundManager = None
        self.__arena = BigWorld.player().arena
        self.__plugins = PluginsCollection(self)
        plugins = {}
        if hasFlags():
            plugins['flagNotification'] = FlagNotificationPlugin
        if hasRepairPoints():
            plugins['repairTimer'] = RepairTimerPlugin
        if hasRespawns() and (constants.IS_DEVELOPMENT or not BattleReplay.g_replayCtrl.isPlaying):
            plugins['respawnView'] = RespawnViewPlugin
        if hasResourcePoints():
            plugins['resources'] = ResourcePointsPlugin
        if hasGasAttack():
            plugins['gasAttack'] = GasAttackPlugin
        self.__plugins.addPlugins(plugins)
        self.__denunciator = BattleDenunciator()
        self.__timerSounds = {}
        for timer, sounds in self.VEHICLE_DEATHZONE_TIMER_SOUND.iteritems():
            self.__timerSounds[timer] = {}
            for level, sound in sounds.iteritems():
                self.__timerSounds[timer][level] = SoundGroups.g_instance.getSound2D(sound)

        self.__timerSound = None
        BattleWindow.__init__(self, 'battle.swf')
        self.__isHelpWindowShown = False
        self.__cameraMode = None
        self.component.wg_inputKeyMode = 1
        self.component.position.z = DEPTH_OF_Battle
        self.movie.backgroundAlpha = 0
        self.addFsCallbacks({'battle.leave': self.onExitBattle})
        self.addExternalCallbacks({'battle.showCursor': self.cursorVisibility,
         'battle.tryLeaveRequest': self.tryLeaveRequest,
         'battle.populateFragCorrelationBar': self.populateFragCorrelationBar,
         'Battle.UsersRoster.Appeal': self.onDenunciationReceived,
         'Battle.selectPlayer': self.selectPlayer,
         'battle.helpDialogOpenStatus': self.helpDialogOpenStatus,
         'battle.initLobbyDialog': self._initLobbyDialog,
         'battle.reportBug': self.reportBug})
        self.__dynSquadListener = None
        BigWorld.wg_setRedefineKeysMode(False)
        self.onPostmortemVehicleChanged(BigWorld.player().playerVehicleID)
        return

    @property
    def appNS(self):
        return self.__ns

    @property
    def soundManager(self):
        return self.__soundManager

    def attachCursor(self, flags = 0):
        return g_cursorDelegator.activateCursor()

    def detachCursor(self):
        return g_cursorDelegator.detachCursor()

    def syncCursor(self, flags = 0):
        pass

    def getRoot(self):
        return self.__battle_flashObject

    def getCameraVehicleID(self):
        return self.__cameraVehicleID

    def populateFragCorrelationBar(self, _):
        if self.__fragCorrelation is not None:
            self.__fragCorrelation.populate()
        return

    def showAll(self, event):
        self.call('battle.showAll', [event.ctx['visible']])
        self.damagePanel.showAll(self.__cameraMode != 'video')

    def showCursor(self, isShow):
        self.cursorVisibility(-1, isShow)

    def selectPlayer(self, _, vehId):
        player = BigWorld.player()
        if isPlayerAvatar():
            player.selectPlayer(int(vehId))

    def onDenunciationReceived(self, _, uid, userName, topic):
        self.__denunciator.makeAppeal(uid, userName, topic)
        self.__arenaCtrl.invalidateGUI()

    def onPostmortemVehicleChanged(self, vehicleID):
        if self.__cameraVehicleID == vehicleID:
            return
        self.__cameraVehicleID = vehicleID
        self.__arenaCtrl.invalidateGUI(not g_sessionProvider.getCtx().isPlayerObserver())
        self._hideVehicleTimer('ALL')
        self.hideDeathzoneTimer('ALL')
        self.__vErrorsPanel.clear()
        self.__vMsgsPanel.clear()

    def onCameraChanged(self, cameraMode, curVehID = None):
        LOG_DEBUG('onCameraChanged', cameraMode, curVehID)
        if self.__cameraMode == 'mapcase':
            self.setAimingMode(False)
        elif cameraMode == 'mapcase':
            self.setAimingMode(True)
        self.__cameraMode = cameraMode

        def setVisible(cname):
            m = self.getMember(cname)
            if m is not None:
                m.visible = cameraMode != 'video'
            return

        if self.__isGuiShown():
            self.damagePanel.showAll(cameraMode != 'video')
            setVisible('vehicleErrorsPanel')
        if cameraMode == 'video':
            self.__cameraVehicleID = -1
            self.__vErrorsPanel.clear()
            self.__vMsgsPanel.clear()
            self._hideVehicleTimer('ALL')
            self.hideDeathzoneTimer('ALL')

    def __isGuiShown(self):
        m = self.getMember('_root')
        if m is not None and callable(m.isGuiVisible):
            return m.isGuiVisible()
        else:
            return False

    def _showVehicleTimer(self, value):
        code, time, warnLvl = value
        LOG_DEBUG('show vehicles destroy timer', code, time, warnLvl)
        self.call('destroyTimer.show', [self.VEHICLE_DESTROY_TIMER[code], time, warnLvl])

    def _hideVehicleTimer(self, code = None):
        LOG_DEBUG('hide vehicles destroy timer', code)
        if code is None:
            code = 'ALL'
        self.call('destroyTimer.hide', [self.VEHICLE_DESTROY_TIMER[code]])
        return

    def showDeathzoneTimer(self, value):
        zoneID, time, warnLvl = value
        if self.__timerSound is not None:
            self.__timerSound.stop()
            self.__timerSound = None
        sound = self.__timerSounds.get(zoneID, {}).get(warnLvl)
        if sound is not None:
            self.__timerSound = sound
            self.__timerSound.play()
        LOG_DEBUG('show vehicles deathzone timer', zoneID, time, warnLvl)
        self.call('destroyTimer.show', [self.VEHICLE_DEATHZONE_TIMER[zoneID], time, warnLvl])
        return

    def hideDeathzoneTimer(self, zoneID = None):
        if self.__timerSound is not None:
            self.__timerSound.stop()
            self.__timerSound = None
        if zoneID is None:
            zoneID = 'ALL'
        LOG_DEBUG('hide vehicles deathzone timer', zoneID)
        self.call('destroyTimer.hide', [self.VEHICLE_DEATHZONE_TIMER[zoneID]])
        return

    def _showSixthSenseIndicator(self, isShow):
        self.call('sixthSenseIndicator.show', [isShow])

    def setVisible(self, bool):
        LOG_DEBUG('[Battle] visible', bool)
        self.component.visible = bool

    def afterCreate(self):
        event = events.AppLifeCycleEvent
        g_eventBus.handleEvent(event(self.__ns, event.INITIALIZING))
        player = BigWorld.player()
        voice = VoiceChatInterface.g_instance
        LOG_DEBUG('[Battle] afterCreate')
        setattr(self.movie, '_global.wg_isShowLanguageBar', GUI_SETTINGS.isShowLanguageBar)
        setattr(self.movie, '_global.wg_isShowServerStats', constants.IS_SHOW_SERVER_STATS)
        setattr(self.movie, '_global.wg_isShowVoiceChat', GUI_SETTINGS.voiceChat)
        setattr(self.movie, '_global.wg_voiceChatProvider', voice.voiceChatProvider)
        setattr(self.movie, '_global.wg_isChina', constants.IS_CHINA)
        setattr(self.movie, '_global.wg_isKorea', constants.IS_KOREA)
        setattr(self.movie, '_global.wg_isReplayPlaying', BattleReplay.g_replayCtrl.isPlaying)
        BattleWindow.afterCreate(self)
        addListener = g_eventBus.addListener
        addListener(events.GameEvent.HELP, self.toggleHelpWindow, scope=_SCOPE)
        addListener(events.GameEvent.GUI_VISIBILITY, self.showAll, scope=_SCOPE)
        player.inputHandler.onPostmortemVehicleChanged += self.onPostmortemVehicleChanged
        player.inputHandler.onCameraChanged += self.onCameraChanged
        g_settingsCore.onSettingsChanged += self.__accs_onSettingsChanged
        g_settingsCore.interfaceScale.onScaleChanged += self.__onRecreateDevice
        isMutlipleTeams = isFalloutMultiTeam()
        isFallout = isFalloutBattle()
        self.proxy = weakref.proxy(self)
        self.__battle_flashObject = self.proxy.getMember('_level0')
        if self.__battle_flashObject:
            self.__battle_flashObject.resync()
        voice.populateUI(self.proxy)
        voice.onPlayerSpeaking += self.setPlayerSpeaking
        voice.onVoiceChatInitFailed += self.onVoiceChatInitFailed
        self.colorManager = ColorSchemeManager._ColorSchemeManager()
        self.colorManager.populateUI(self.proxy)
        self.movingText = MovingText()
        self.movingText.populateUI(self.proxy)
        self.__settingsInterface = SettingsInterface()
        self.__settingsInterface.populateUI(self.proxy)
        self.__soundManager = SoundManager()
        self.__soundManager.populateUI(self.proxy)
        self.__debugPanel = DebugPanel()
        self.__timersBar = TimersBar(self.proxy, isFallout)
        if battleEndWarningEnabled():
            self.__battleEndWarningPanel = BattleEndWarningPanel(self.proxy, getArenaType())
        else:
            self.__battleEndWarningPanel = BattleEndWarningEmptyObject(self.proxy, getArenaType())
        self.__teamBasesPanel = TeamBasesPanel(self.proxy)
        self.__consumablesPanel = ConsumablesPanel(self.proxy)
        self.__damagePanel = DamagePanel(self.proxy)
        self.__markersManager = MarkersManager(self.proxy)
        self.__ingameHelp = IngameHelp(self.proxy)
        self.__minimap = Minimap(self.proxy)
        self.__radialMenu = RadialMenu(self.proxy)
        self.__ribbonsPanel = BattleRibbonsPanel(self.proxy)
        self.__ppSwitcher = PlayersPanelsSwitcher(self.proxy)
        isColorBlind = g_settingsCore.getSetting('isColorBlind')
        self.__leftPlayersPanel = playersPanelFactory(self.proxy, True, isColorBlind, isFallout, isMutlipleTeams)
        self.__rightPlayersPanel = playersPanelFactory(self.proxy, False, isColorBlind, isFallout, isMutlipleTeams)
        self.__damageInfoPanel = VehicleDamageInfoPanel(self.proxy)
        self.__damageInfoPanel.start()
        self.__fragCorrelation = scorePanelFactory(self.proxy, isFallout, isMutlipleTeams)
        self.__statsForm = statsFormFactory(self.proxy, isFallout, isMutlipleTeams)
        self.__plugins.init()
        self.isVehicleCountersVisible = g_settingsCore.getSetting('showVehiclesCounter')
        self.__fragCorrelation.showVehiclesCounter(self.isVehicleCountersVisible)
        self.__vErrorsPanel = VehicleErrorMessages(self.proxy)
        self.__vMsgsPanel = VehicleMessages(self.proxy)
        self.__pMsgsPanel = PlayerMessages(self.proxy)
        self.__plugins.start()
        self.__consumablesPanel.start()
        self.__damagePanel.start()
        self.__ingameHelp.start()
        self.__vErrorsPanel.start()
        self.__vMsgsPanel.start()
        self.__pMsgsPanel.start()
        self.__markersManager.start()
        self.__markersManager.setMarkerDuration(GUI_SETTINGS.markerHitSplashDuration)
        markers = {'enemy': g_settingsCore.getSetting('enemy'),
         'dead': g_settingsCore.getSetting('dead'),
         'ally': g_settingsCore.getSetting('ally')}
        self.__markersManager.setMarkerSettings(markers)
        MessengerEntry.g_instance.gui.invoke('populateUI', self.proxy)
        g_guiResetters.add(self.__onRecreateDevice)
        g_repeatKeyHandlers.add(self.component.handleKeyEvent)
        self.__onRecreateDevice()
        self.__statsForm.populate()
        self.__leftPlayersPanel.populateUI(self.proxy)
        self.__rightPlayersPanel.populateUI(self.proxy)
        self.__debugPanel.populateUI(self.proxy)
        if BattleReplay.g_replayCtrl.isPlaying:
            BattleReplay.g_replayCtrl.onBattleSwfLoaded()
        self.__populateData()
        self.__minimap.start()
        self.__radialMenu.setSettings(self.__settingsInterface)
        self.__radialMenu.populateUI(self.proxy)
        self.__ribbonsPanel.start()
        add = g_sessionProvider.addViewComponent
        add('legacy/hitDirection', indicators.createDamageIndicator(), rule=VIEW_COMPONENT_RULE.NONE)
        add('legacy/teamBasesPanel', self.__teamBasesPanel)
        add('legacy/debugPanel', self.__debugPanel)
        add('legacy/battleTimer', self.__timersBar)
        add('legacy/prebattleTimer', self.__timersBar)
        add('legacy/ppSwitcher', self.__ppSwitcher)
        add(_BATTLE_END_WARNING_COMPONENT, self.__battleEndWarningPanel)
        self.__arenaCtrl = battleArenaControllerFactory(self, isFallout, isMutlipleTeams)
        g_sessionProvider.addArenaCtrl(self.__arenaCtrl)
        self.updateFlagsColor()
        self.movie.setFocussed(SCALEFORM_SWF_PATH)
        self.call('battle.initDynamicSquad', self.__getDynamicSquadsInitParams(enableButton=not BattleReplay.g_replayCtrl.isPlaying))
        self.call('sixthSenseIndicator.setDuration', [GUI_SETTINGS.sixthSenseDuration])
        g_tankActiveCamouflage[player.vehicleTypeDescriptor.type.compactDescr] = self.__arena.arenaType.vehicleCamouflageKind
        keyCode = CommandMapping.g_instance.get('CMD_VOICECHAT_MUTE')
        if not BigWorld.isKeyDown(keyCode):
            VOIP.getVOIPManager().setMicMute(True)
        ctrl = g_sessionProvider.getVehicleStateCtrl()
        ctrl.onVehicleStateUpdated += self.__onVehicleStateUpdated
        ctrl.onPostMortemSwitched += self.__onPostMortemSwitched
        if BattleReplay.g_replayCtrl.isPlaying:
            self.__dynSquadListener = ReplayDynSquadViewListener(self.proxy)
        elif BattleReplay.g_replayCtrl.isRecording:
            self.__dynSquadListener = RecordDynSquadViewListener(self.proxy)
        else:
            self.__dynSquadListener = DynSquadViewListener(self.proxy)
        g_eventBus.handleEvent(event(self.__ns, event.INITIALIZED))

    def beforeDelete(self):
        LOG_DEBUG('[Battle] beforeDelete')
        removeListener = g_eventBus.removeListener
        removeListener(events.GameEvent.HELP, self.toggleHelpWindow, scope=_SCOPE)
        removeListener(events.GameEvent.GUI_VISIBILITY, self.showAll, scope=_SCOPE)
        ctrl = g_sessionProvider.getVehicleStateCtrl()
        if ctrl is not None:
            ctrl.onVehicleStateUpdated -= self.__onVehicleStateUpdated
            ctrl.onPostMortemSwitched -= self.__onPostMortemSwitched
        player = BigWorld.player()
        if player and player.inputHandler:
            player.inputHandler.onPostmortemVehicleChanged -= self.onPostmortemVehicleChanged
            player.inputHandler.onCameraChanged -= self.onCameraChanged
        if self.colorManager:
            self.colorManager.dispossessUI()
        voice = VoiceChatInterface.g_instance
        if voice:
            voice.dispossessUI(self.proxy)
            voice.onPlayerSpeaking -= self.setPlayerSpeaking
            voice.onVoiceChatInitFailed -= self.onVoiceChatInitFailed
        if self.__plugins is not None:
            self.__plugins.stop()
            self.__plugins.fini()
            self.__plugins = None
        if self.movingText is not None:
            self.movingText.dispossessUI()
            self.movingText = None
        if self.__timerSound is not None:
            self.__timerSound.stop()
            self.__timerSound = None
        if self.__soundManager is not None:
            self.__soundManager.dispossessUI()
            self.__soundManager = None
        if self.colorManager is not None:
            self.colorManager.dispossessUI()
            self.colorManager = None
        if self.component:
            g_repeatKeyHandlers.discard(self.component.handleKeyEvent)
        g_settingsCore.onSettingsChanged -= self.__accs_onSettingsChanged
        g_settingsCore.interfaceScale.onScaleChanged -= self.__onRecreateDevice
        self.__timersBar.destroy()
        self.__battleEndWarningPanel.destroy()
        self.__teamBasesPanel.destroy()
        self.__consumablesPanel.destroy()
        self.__damagePanel.destroy()
        self.__markersManager.destroy()
        self.__ingameHelp.destroy()
        self.__vErrorsPanel.destroy()
        self.__vMsgsPanel.destroy()
        self.__pMsgsPanel.destroy()
        self.__radialMenu.destroy()
        self.__minimap.destroy()
        self.__ribbonsPanel.destroy()
        self.__fragCorrelation.destroy()
        self.__statsForm.destroy()
        self.__damageInfoPanel.destroy()
        remove = g_sessionProvider.removeViewComponent
        remove('legacy/hitDirection')
        remove('legacy/teamBasesPanel')
        remove('legacy/debugPanel')
        remove('legacy/battleTimer')
        remove('legacy/prebattleTimer')
        remove('legacy/ppSwitcher')
        if self.__arenaCtrl is not None:
            g_sessionProvider.removeArenaCtrl(self.__arenaCtrl)
            self.__arenaCtrl.clear()
            self.__arenaCtrl = None
        self.__ppSwitcher.destroy()
        self.__debugPanel.dispossessUI()
        self.__leftPlayersPanel.dispossessUI()
        self.__rightPlayersPanel.dispossessUI()
        MessengerEntry.g_instance.gui.invoke('dispossessUI')
        self.__arena = None
        self.__denunciator = None
        g_guiResetters.discard(self.__onRecreateDevice)
        self.__settingsInterface.dispossessUI()
        self.__settingsInterface = None
        if self.__dynSquadListener:
            self.__dynSquadListener.destroy()
            self.__dynSquadListener = None
        BattleWindow.beforeDelete(self)
        event = events.AppLifeCycleEvent
        g_eventBus.handleEvent(event(self.__ns, event.DESTROYED))
        return

    def __onVehicleStateUpdated(self, state, value):
        if state not in self.__stateHandlers:
            return
        else:
            handler = getattr(self, self.__stateHandlers[state], None)
            if handler and callable(handler):
                if value is not None:
                    handler(value)
                else:
                    handler()
            return

    def _setFireInVehicle(self, bool):
        self.call('destroyTimer.onFireInVehicle', [bool])

    def onVoiceChatInitFailed(self):
        if GUI_SETTINGS.voiceChat:
            self.call('VoiceChat.initFailed', [])

    def clearCommands(self):
        pass

    def bindCommands(self):
        self.__consumablesPanel.bindCommands()
        self.__ingameHelp.buildCmdMapping()

    def updateFlagsColor(self):
        isColorBlind = g_settingsCore.getSetting('isColorBlind')
        colorGreen = self.colorManager.getSubScheme('flag_team_green', isColorBlind=isColorBlind)['rgba']
        colorRed = self.colorManager.getSubScheme('flag_team_red', isColorBlind=isColorBlind)['rgba']
        arenaDP = g_sessionProvider.getArenaDP()
        teamsOnArena = arenaDP.getTeamsOnArena()
        for teamIdx in teamsOnArena:
            color = colorGreen if arenaDP.isAllyTeam(teamIdx) else colorRed
            BigWorld.wg_setFlagColor(teamIdx, color / 255)

        for teamIdx in [0] + teamsOnArena:
            BigWorld.wg_setFlagEmblem(teamIdx, 'system/maps/wg_emblem.dds', Math.Vector4(0.0, 0.1, 0.5, 0.9))

    def setPlayerSpeaking(self, accountDBID, flag):
        self.__callEx('setPlayerSpeaking', [accountDBID, flag])
        vID = g_sessionProvider.getCtx().getVehIDByAccDBID(accountDBID)
        if vID > 0:
            self.__markersManager.showDynamic(vID, flag)

    def isPlayerSpeaking(self, accountDBID):
        return VoiceChatInterface.g_instance.isPlayerSpeaking(accountDBID)

    def __onPostMortemSwitched(self):
        if self.radialMenu is not None:
            self.radialMenu.forcedHide()
        if not g_sessionProvider.getCtx().isPlayerObserver():
            self.__callEx('showPostmortemTips', [1.0, 5.0, 1.0])
        return

    def cursorVisibility(self, _, visible, x = None, y = None, customCall = False, enableAiming = True):
        if visible:
            g_cursorDelegator.syncMousePosition(self, x, y, customCall)
        else:
            g_cursorDelegator.restoreMousePosition()
        avatar_getter.setForcedGuiControlMode(visible, stopVehicle=False, enableAiming=enableAiming)

    def tryLeaveRequest(self, _):
        resStr = 'quitBattle'
        replayCtrl = BattleReplay.g_replayCtrl
        canRespawn = False
        player = BigWorld.player()
        if hasRespawns():
            isVehicleAlive = not g_sessionProvider.getArenaDP().getVehicleInteractiveStats().stopRespawn
            canRespawn = isVehicleAlive
        else:
            isVehicleAlive = getattr(player, 'isVehicleAlive', False)
        isVehicleOverturned = getattr(player, 'isVehicleOverturned', False)
        isNotTraining = self.__arena.guiType != constants.ARENA_GUI_TYPE.TRAINING
        if not replayCtrl.isPlaying:
            if constants.IS_KOREA and gui.GUI_SETTINGS.igrEnabled and self.__arena is not None and isNotTraining:
                vehicleID = getattr(player, 'playerVehicleID', -1)
                if vehicleID in self.__arena.vehicles:
                    vehicle = self.__arena.vehicles[vehicleID]
                    if isVehicleAlive and vehicle.get('igrType') != constants.IGR_TYPE.NONE:
                        resStr = 'quitBattleIGR'
                else:
                    LOG_ERROR("Player's vehicle not found", vehicleID)
            if canRespawn:
                isDeserter = isVehicleAlive and isNotTraining
            else:
                isDeserter = isVehicleAlive and isNotTraining and not isVehicleOverturned
            if isDeserter:
                resStr += '/deserter'
        else:
            isDeserter = False
        self.__callEx('tryLeaveResponse', [resStr, isDeserter])
        return

    def onExitBattle(self, _):
        arena = getattr(BigWorld.player(), 'arena', None)
        LOG_DEBUG('onExitBattle', arena)
        from helpers.statistics import g_statistics, HANGAR_LOADING_STATE
        g_statistics.noteHangarLoadingState(HANGAR_LOADING_STATE.CONNECTED, True)
        if arena:
            BigWorld.player().leaveArena()
        return

    def toggleHelpWindow(self, _):
        self.__callEx('showHideHelp', [not self.__isHelpWindowShown])

    def setAimingMode(self, isAiming):
        self.__callEx('setAimingMode', [isAiming])

    def helpDialogOpenStatus(self, cid, isOpened):
        self.__isHelpWindowShown = isOpened

    def _initLobbyDialog(self, cid):
        if connectionManager.serverUserName:
            tooltipBody = i18n.makeString('#tooltips:header/info/players_online_full/body')
            tooltipFullData = makeTooltip('#tooltips:header/info/players_online_full/header', tooltipBody % {'servername': connectionManager.serverUserName})
            self.__callEx('setServerStatsInfo', [tooltipFullData])
            self.__callEx('setServerName', [connectionManager.serverUserName])
            if constants.IS_SHOW_SERVER_STATS:
                stats = game_control.g_instance.serverStats.getStats()
                if 'clusterCCU' in stats and 'regionCCU' in stats:
                    self.__callEx('setServerStats', [stats['clusterCCU'], stats['regionCCU']])
                else:
                    self.__callEx('setServerStats', [None, None])
        else:
            self.__callEx('setServerName', ['-'])
        links = GUI_SETTINGS.reportBugLinks
        if len(links):
            reportBugButton = makeHyperLink('ingameMenu', MENU.INGAME_MENU_LINKS_REPORT_BUG)
            self.__callEx('setReportBugLink', [reportBugButton])
        return

    def reportBug(self, _):
        reportBugOpenConfirm(g_sessionProvider.getArenaDP().getVehicleInfo().player.accountDBID)

    def __getDynamicSquadsInitParams(self, enableAlly = True, enableEnemy = False, enableButton = True):
        return [isRandomBattle() and enableAlly, enableEnemy, isRandomBattle() and enableButton]

    def __populateData(self):
        ctx = g_sessionProvider.getCtx()
        data = [ctx.getArenaTypeName(),
         ctx.getArenaFrameLabel(isLegacy=True),
         ctx.getArenaDescriptionString(),
         ctx.getTeamName(enemy=False),
         ctx.getTeamName(enemy=True),
         ctx.getArenaWinString(),
         ctx.getGuiEventType()]
        settings = g_lobbyContext.getServerSettings()
        quest = [None] * 3
        if settings is not None and settings.isPotapovQuestEnabled():
            info = ctx.getQuestInfo()
            if info is not None:
                quest[0] = info.name
                if info.condition:
                    quest[1] = info.condition
                if info.condition:
                    quest[2] = info.additional
        data.extend(quest)
        data.append(ctx.getArenaSmallIcon())
        self.__callEx('arenaData', data)
        return

    def __onRecreateDevice(self, scale = None):
        params = list(GUI.screenResolution())
        params.append(g_settingsCore.interfaceScale.get())
        self.call('Stage.Update', params)
        self.__markersManager.updateMarkersScale()

    def invalidateGUI(self):
        arenaCtrl = getattr(self, '_Battle__arenaCtrl', None)
        if arenaCtrl is not None:
            arenaCtrl.invalidateGUI()
        return

    def __callEx(self, funcName, args = None):
        self.call('battle.' + funcName, args)

    def __accs_onSettingsChanged(self, diff):
        self.colorManager.update()
        if 'isColorBlind' in diff:
            isColorBlind = diff['isColorBlind']
            self.__leftPlayersPanel.defineColorFlags(isColorBlind=isColorBlind)
            self.__rightPlayersPanel.defineColorFlags(isColorBlind=isColorBlind)
            self.updateFlagsColor()
            self.__markersManager.updateMarkers()
            self.__minimap.updateEntries()
        if 'enemy' in diff or 'dead' in diff or 'ally' in diff:
            markers = {'enemy': g_settingsCore.getSetting('enemy'),
             'dead': g_settingsCore.getSetting('dead'),
             'ally': g_settingsCore.getSetting('ally')}
            self.__markersManager.setMarkerSettings(markers)
            self.__markersManager.updateMarkerSettings()
        if 'showVehiclesCounter' in diff:
            self.isVehicleCountersVisible = diff['showVehiclesCounter']
            self.__fragCorrelation.showVehiclesCounter(self.isVehicleCountersVisible)
        if 'interfaceScale' in diff:
            self.__onRecreateDevice()
        self.__arenaCtrl.invalidateGUI()
        self.__arenaCtrl.invalidateArenaInfo()

    def setTeamValuesData(self, data):
        if self.__battle_flashObject is not None:
            self.__battle_flashObject.setTeamValues(data)
        return

    def setMultiteamValues(self, data):
        if self.__battle_flashObject is not None:
            self.__battle_flashObject.setMultiteamValues(data)
        return

    def getPlayerNameLength(self, isEnemy):
        panel = self.rightPlayersPanel if isEnemy else self.leftPlayersPanel
        return panel.getPlayerNameLength()

    def getVehicleNameLength(self, isEnemy):
        panel = self.rightPlayersPanel if isEnemy else self.leftPlayersPanel
        return panel.getVehicleNameLength()

    def getTeamBasesPanel(self):
        return self.__teamBasesPanel

    def getBattleTimer(self):
        return self.__timersBar

    def getPreBattleTimer(self):
        return self.__timersBar

    def getConsumablesPanel(self):
        return self.__consumablesPanel

    def getDamagePanel(self):
        return self.__damagePanel

    def getMarkersManager(self):
        return self.__markersManager

    def getVErrorsPanel(self):
        return self.__vErrorsPanel

    def getVMsgsPanel(self):
        return self.__vMsgsPanel

    def getPMsgsPanel(self):
        return self.__pMsgsPanel

    def getMinimap(self):
        return self.__minimap

    def getRadialMenu(self):
        return self.__radialMenu

    def getDamageInfoPanel(self):
        return self.__damageInfoPanel

    def getFragCorrelation(self):
        return self.__fragCorrelation

    def getStatsForm(self):
        return self.__statsForm

    def getLeftPlayersPanel(self):
        return self.__leftPlayersPanel

    def getRightPlayersPanel(self):
        return self.__rightPlayersPanel

    def getRibbonsPanel(self):
        return self.__ribbonsPanel

    def getPlayersPanelsSwitcher(self):
        return self.__ppSwitcher

    def getDebugPanel(self):
        return self.__debugPanel
Ejemplo n.º 16
0
class Battle(BattleWindow):
    teamBasesPanel = property(lambda self: self.__teamBasesPanel)
    timersBar = property(lambda self: self.__timersBar)
    consumablesPanel = property(lambda self: self.__consumablesPanel)
    damagePanel = property(lambda self: self.__damagePanel)
    markersManager = property(lambda self: self.__markersManager)
    vErrorsPanel = property(lambda self: self.__vErrorsPanel)
    vMsgsPanel = property(lambda self: self.__vMsgsPanel)
    pMsgsPanel = property(lambda self: self.__pMsgsPanel)
    minimap = property(lambda self: self.__minimap)
    radialMenu = property(lambda self: self.__radialMenu)
    damageInfoPanel = property(lambda self: self.__damageInfoPanel)
    fragCorrelation = property(lambda self: self.__fragCorrelation)
    statsForm = property(lambda self: self.__statsForm)
    leftPlayersPanel = property(lambda self: self.__leftPlayersPanel)
    rightPlayersPanel = property(lambda self: self.__rightPlayersPanel)
    ribbonsPanel = property(lambda self: self.__ribbonsPanel)
    ppSwitcher = property(lambda self: self.__ppSwitcher)
    indicators = property(lambda self: self.__indicators)
    VEHICLE_DESTROY_TIMER = {'ALL': 'all',
     constants.VEHICLE_MISC_STATUS.VEHICLE_DROWN_WARNING: 'drown',
     constants.VEHICLE_MISC_STATUS.VEHICLE_IS_OVERTURNED: 'overturn',
     constants.VEHICLE_MISC_STATUS.IN_DEATH_ZONE: 'death_zone'}
    DENUNCIATIONS = {'bot': constants.DENUNCIATION.BOT,
     'flood': constants.DENUNCIATION.FLOOD,
     'offend': constants.DENUNCIATION.OFFEND,
     'notFairPlay': constants.DENUNCIATION.NOT_FAIR_PLAY,
     'forbiddenNick': constants.DENUNCIATION.FORBIDDEN_NICK,
     'swindle': constants.DENUNCIATION.SWINDLE,
     'blackmail': constants.DENUNCIATION.BLACKMAIL}
    __cameraVehicleID = -1
    __stateHandlers = {VEHICLE_VIEW_STATE.FIRE: '_setFireInVehicle',
     VEHICLE_VIEW_STATE.SHOW_DESTROY_TIMER: '_showVehicleTimer',
     VEHICLE_VIEW_STATE.HIDE_DESTROY_TIMER: '_hideVehicleTimer',
     VEHICLE_VIEW_STATE.OBSERVED_BY_ENEMY: '_showSixthSenseIndicator'}

    def __init__(self, appNS):
        self.__ns = appNS
        self.__soundManager = None
        self.__arena = BigWorld.player().arena
        self.__plugins = PluginsCollection(self)
        plugins = {}
        if hasFlags():
            plugins['flagNotification'] = FlagNotificationPlugin
        if hasRespawns() and not BattleReplay.g_replayCtrl.isPlaying:
            plugins['respawnView'] = RespawnViewPlugin
        if hasResourcePoints():
            plugins['resources'] = ResourcePointsPlugin
        self.__plugins.addPlugins(plugins)
        BattleWindow.__init__(self, 'battle.swf')
        self.__isHelpWindowShown = False
        self.__cameraMode = None
        self.component.wg_inputKeyMode = 1
        self.component.position.z = DEPTH_OF_Battle
        self.movie.backgroundAlpha = 0
        self.addFsCallbacks({'battle.leave': self.onExitBattle})
        self.addExternalCallbacks({'battle.showCursor': self.cursorVisibility,
         'battle.tryLeaveRequest': self.tryLeaveRequest,
         'battle.populateFragCorrelationBar': self.populateFragCorrelationBar,
         'Battle.UsersRoster.Appeal': self.onDenunciationReceived,
         'Battle.selectPlayer': self.selectPlayer,
         'battle.helpDialogOpenStatus': self.helpDialogOpenStatus,
         'battle.initLobbyDialog': self._initLobbyDialog,
         'battle.reportBug': self.reportBug})
        self.__dynSquadListener = None
        BigWorld.wg_setRedefineKeysMode(False)
        self.onPostmortemVehicleChanged(BigWorld.player().playerVehicleID)

    @property
    def appNS(self):
        return self.__ns

    def getRoot(self):
        return self.__battle_flashObject

    def getCameraVehicleID(self):
        return self.__cameraVehicleID

    def populateFragCorrelationBar(self, _):
        if self.__fragCorrelation is not None:
            self.__fragCorrelation.populate()

    def showAll(self, event):
        self.call('battle.showAll', [event.ctx['visible']])

    def showCursor(self, isShow):
        self.cursorVisibility(-1, isShow)

    @property
    def soundManager(self):
        return self.__soundManager

    def selectPlayer(self, cid, vehId):
        player = BigWorld.player()
        if isPlayerAvatar():
            player.selectPlayer(int(vehId))

    def onDenunciationReceived(self, _, uid, userName, topic):
        topicID = self.DENUNCIATIONS.get(topic)
        if topicID is not None:
            self.__makeDenunciation(uid, userName, topicID)

    def __makeDenunciation(self, uid, userName, topicID):
        player = BigWorld.player()
        violatorKind = constants.VIOLATOR_KIND.UNKNOWN
        for id, p in player.arena.vehicles.iteritems():
            if p['accountDBID'] == uid:
                violatorKind = constants.VIOLATOR_KIND.ALLY if player.team == p['team'] else constants.VIOLATOR_KIND.ENEMY

        player.makeDenunciation(uid, topicID, violatorKind)
        self.__arenaCtrl.invalidateGUI()
        topicStr = makeString('#menu:denunciation/%d' % topicID)
        message = makeString('#system_messages:denunciation/success') % {'name': userName,
         'topic': topicStr}
        MessengerEntry.g_instance.gui.addClientMessage(g_settings.htmlTemplates.format('battleErrorMessage', ctx={'error': message}))

    def onPostmortemVehicleChanged(self, id):
        if self.__cameraVehicleID == id:
            return
        self.__cameraVehicleID = id
        self.__arenaCtrl.invalidateGUI(not g_sessionProvider.getCtx().isPlayerObserver())
        g_sessionProvider.getVehicleStateCtrl().switchToAnother(id)
        self._hideVehicleTimer('ALL')
        self.__vErrorsPanel.clear()
        self.__vMsgsPanel.clear()
        aim = BigWorld.player().inputHandler.aim
        if aim is not None:
            aim.updateAmmoState(True)

    def onCameraChanged(self, cameraMode, curVehID = None):
        LOG_DEBUG('onCameraChanged', cameraMode, curVehID)
        if self.__cameraMode == 'mapcase':
            self.setAimingMode(False)
        elif cameraMode == 'mapcase':
            self.setAimingMode(True)
        self.__cameraMode = cameraMode

        def setVisible(cname):
            m = self.getMember(cname)
            if m is not None:
                m.visible = cameraMode != 'video'

        if self.__isGuiShown():
            self.damagePanel.showAll(cameraMode != 'video')
            setVisible('vehicleMessagesPanel')
            setVisible('vehicleErrorsPanel')
        if cameraMode == 'video':
            self.__cameraVehicleID = -1
            self.__vErrorsPanel.clear()
            self.__vMsgsPanel.clear()
            self._hideVehicleTimer('ALL')
            aim = BigWorld.player().inputHandler.aim
            if aim is not None:
                aim.updateAmmoState(True)
        aim = BigWorld.player().inputHandler.aim
        if aim is not None:
            aim.onCameraChange()

    def __isGuiShown(self):
        m = self.getMember('_root')
        if m is not None and callable(m.isGuiVisible):
            return m.isGuiVisible()
        return False

    def _showVehicleTimer(self, value):
        code, time, warnLvl = value
        LOG_DEBUG('show vehicles destroy timer', code, time, warnLvl)
        self.call('destroyTimer.show', [self.VEHICLE_DESTROY_TIMER[code], time, warnLvl])

    def _hideVehicleTimer(self, code):
        LOG_DEBUG('hide vehicles destroy timer', code)
        self.call('destroyTimer.hide', [self.VEHICLE_DESTROY_TIMER[code]])

    def _showSixthSenseIndicator(self, isShow):
        self.call('sixthSenseIndicator.show', [isShow])

    def setVisible(self, bool):
        LOG_DEBUG('[Battle] visible', bool)
        self.component.visible = bool

    def afterCreate(self):
        event = events.AppLifeCycleEvent
        g_eventBus.handleEvent(event(self.__ns, event.INITIALIZING))
        player = BigWorld.player()
        voice = VoiceChatInterface.g_instance
        LOG_DEBUG('[Battle] afterCreate')
        setattr(self.movie, '_global.wg_isShowLanguageBar', GUI_SETTINGS.isShowLanguageBar)
        setattr(self.movie, '_global.wg_isShowServerStats', constants.IS_SHOW_SERVER_STATS)
        setattr(self.movie, '_global.wg_isShowVoiceChat', GUI_SETTINGS.voiceChat)
        setattr(self.movie, '_global.wg_voiceChatProvider', voice.voiceChatProvider)
        setattr(self.movie, '_global.wg_isChina', constants.IS_CHINA)
        setattr(self.movie, '_global.wg_isKorea', constants.IS_KOREA)
        setattr(self.movie, '_global.wg_isReplayPlaying', BattleReplay.g_replayCtrl.isPlaying)
        BattleWindow.afterCreate(self)
        addListener = g_eventBus.addListener
        addListener(events.GameEvent.HELP, self.toggleHelpWindow, scope=_SCOPE)
        addListener(events.GameEvent.GUI_VISIBILITY, self.showAll, scope=_SCOPE)
        player.inputHandler.onPostmortemVehicleChanged += self.onPostmortemVehicleChanged
        player.inputHandler.onCameraChanged += self.onCameraChanged
        g_settingsCore.onSettingsChanged += self.__accs_onSettingsChanged
        g_settingsCore.interfaceScale.onScaleChanged += self.__onRecreateDevice
        isMutlipleTeams = g_sessionProvider.getArenaDP().isMultipleTeams()
        isEvent = isEventBattle()
        self.proxy = weakref.proxy(self)
        self.__battle_flashObject = self.proxy.getMember('_level0')
        if self.__battle_flashObject:
            self.__battle_flashObject.resync()
        voice.populateUI(self.proxy)
        voice.onPlayerSpeaking += self.setPlayerSpeaking
        voice.onVoiceChatInitFailed += self.onVoiceChatInitFailed
        self.colorManager = ColorSchemeManager._ColorSchemeManager()
        self.colorManager.populateUI(self.proxy)
        self.movingText = MovingText()
        self.movingText.populateUI(self.proxy)
        self.__settingsInterface = SettingsInterface()
        self.__settingsInterface.populateUI(self.proxy)
        self.__soundManager = SoundManager()
        self.__soundManager.populateUI(self.proxy)
        self.__timersBar = TimersBar(self.proxy, isEvent)
        self.__teamBasesPanel = TeamBasesPanel(self.proxy)
        self.__debugPanel = DebugPanel(self.proxy)
        self.__consumablesPanel = ConsumablesPanel(self.proxy)
        self.__damagePanel = DamagePanel(self.proxy)
        self.__markersManager = MarkersManager(self.proxy)
        self.__ingameHelp = IngameHelp(self.proxy)
        self.__minimap = Minimap(self.proxy)
        self.__radialMenu = RadialMenu(self.proxy)
        self.__ribbonsPanel = BattleRibbonsPanel(self.proxy)
        self.__indicators = IndicatorsCollection()
        self.__ppSwitcher = PlayersPanelsSwitcher(self.proxy)
        isColorBlind = g_settingsCore.getSetting('isColorBlind')
        self.__leftPlayersPanel = playersPanelFactory(self.proxy, True, isColorBlind, isEvent, isMutlipleTeams)
        self.__rightPlayersPanel = playersPanelFactory(self.proxy, False, isColorBlind, isEvent, isMutlipleTeams)
        self.__damageInfoPanel = VehicleDamageInfoPanel(self.proxy)
        self.__fragCorrelation = scorePanelFactory(self.proxy, isEvent, isMutlipleTeams)
        self.__statsForm = statsFormFactory(self.proxy, isEvent, isMutlipleTeams)
        self.__plugins.init()
        self.isVehicleCountersVisible = g_settingsCore.getSetting('showVehiclesCounter')
        self.__fragCorrelation.showVehiclesCounter(self.isVehicleCountersVisible)
        self.__vErrorsPanel = VehicleErrorMessages(self.proxy)
        self.__vMsgsPanel = VehicleMessages(self.proxy)
        self.__pMsgsPanel = PlayerMessages(self.proxy)
        self.__plugins.start()
        self.__debugPanel.start()
        self.__consumablesPanel.start()
        self.__damagePanel.start()
        self.__ingameHelp.start()
        self.__vErrorsPanel.start()
        self.__vMsgsPanel.start()
        self.__pMsgsPanel.start()
        self.__markersManager.start()
        self.__markersManager.setMarkerDuration(GUI_SETTINGS.markerHitSplashDuration)
        markers = {'enemy': g_settingsCore.getSetting('enemy'),
         'dead': g_settingsCore.getSetting('dead'),
         'ally': g_settingsCore.getSetting('ally')}
        self.__markersManager.setMarkerSettings(markers)
        MessengerEntry.g_instance.gui.invoke('populateUI', self.proxy)
        g_guiResetters.add(self.__onRecreateDevice)
        g_repeatKeyHandlers.add(self.component.handleKeyEvent)
        self.__onRecreateDevice()
        self.__statsForm.populate()
        self.__leftPlayersPanel.populateUI(self.proxy)
        self.__rightPlayersPanel.populateUI(self.proxy)
        if BattleReplay.g_replayCtrl.isPlaying:
            BattleReplay.g_replayCtrl.onBattleSwfLoaded()
        self.__populateData(isMutlipleTeams)
        self.__minimap.start()
        self.__radialMenu.setSettings(self.__settingsInterface)
        self.__radialMenu.populateUI(self.proxy)
        self.__ribbonsPanel.start()
        g_sessionProvider.setBattleUI(self)
        self.__arenaCtrl = battleArenaControllerFactory(self, isEvent, isMutlipleTeams)
        g_sessionProvider.addArenaCtrl(self.__arenaCtrl)
        self.updateFlagsColor()
        self.movie.setFocussed(SCALEFORM_SWF_PATH)
        self.call('battle.initDynamicSquad', self.__getDynamicSquadsInitParams())
        if self.__arena.period == constants.ARENA_PERIOD.BATTLE:
            self.call('players_panel.setState', [g_settingsCore.getSetting('ppState')])
        else:
            self.call('players_panel.setState', ['large'])
        self.call('sixthSenseIndicator.setDuration', [GUI_SETTINGS.sixthSenseDuration])
        g_tankActiveCamouflage[player.vehicleTypeDescriptor.type.compactDescr] = self.__arena.arenaType.vehicleCamouflageKind
        keyCode = CommandMapping.g_instance.get('CMD_VOICECHAT_MUTE')
        if not BigWorld.isKeyDown(keyCode):
            VOIP.getVOIPManager().setMicMute(True)
        ctrl = g_sessionProvider.getVehicleStateCtrl()
        ctrl.onVehicleStateUpdated += self.__onVehicleStateUpdated
        ctrl.onPostMortemSwitched += self.__onPostMortemSwitched
        self.__dynSquadListener = DynSquadViewListener(self.proxy)
        g_eventBus.handleEvent(event(self.__ns, event.INITIALIZED))

    def beforeDelete(self):
        LOG_DEBUG('[Battle] beforeDelete')
        removeListener = g_eventBus.removeListener
        removeListener(events.GameEvent.HELP, self.toggleHelpWindow, scope=_SCOPE)
        removeListener(events.GameEvent.GUI_VISIBILITY, self.showAll, scope=_SCOPE)
        ctrl = g_sessionProvider.getVehicleStateCtrl()
        ctrl.onVehicleStateUpdated -= self.__onVehicleStateUpdated
        ctrl.onPostMortemSwitched -= self.__onPostMortemSwitched
        if self.colorManager:
            self.colorManager.dispossessUI()
        voice = VoiceChatInterface.g_instance
        if voice:
            voice.dispossessUI(self.proxy)
            voice.onPlayerSpeaking -= self.setPlayerSpeaking
            voice.onVoiceChatInitFailed -= self.onVoiceChatInitFailed
        if self.__plugins is not None:
            self.__plugins.stop()
            self.__plugins.fini()
            self.__plugins = None
        if self.movingText is not None:
            self.movingText.dispossessUI()
            self.movingText = None
        if self.__soundManager is not None:
            self.__soundManager.dispossessUI()
            self.__soundManager = None
        if self.colorManager is not None:
            self.colorManager.dispossessUI()
            self.colorManager = None
        if self.component:
            g_repeatKeyHandlers.discard(self.component.handleKeyEvent)
        g_settingsCore.onSettingsChanged -= self.__accs_onSettingsChanged
        g_settingsCore.interfaceScale.onScaleChanged -= self.__onRecreateDevice
        self.__timersBar.destroy()
        self.__teamBasesPanel.destroy()
        self.__debugPanel.destroy()
        self.__consumablesPanel.destroy()
        self.__damagePanel.destroy()
        self.__markersManager.destroy()
        self.__ingameHelp.destroy()
        self.__vErrorsPanel.destroy()
        self.__vMsgsPanel.destroy()
        self.__pMsgsPanel.destroy()
        self.__radialMenu.destroy()
        self.__minimap.destroy()
        self.__ribbonsPanel.destroy()
        self.__fragCorrelation.destroy()
        self.__statsForm.destroy()
        g_sessionProvider.clearBattleUI()
        if self.__arenaCtrl is not None:
            g_sessionProvider.removeArenaCtrl(self.__arenaCtrl)
            self.__arenaCtrl.clear()
            self.__arenaCtrl = None
        self.__ppSwitcher.destroy()
        self.__leftPlayersPanel.dispossessUI()
        self.__rightPlayersPanel.dispossessUI()
        MessengerEntry.g_instance.gui.invoke('dispossessUI')
        self.__arena = None
        g_guiResetters.discard(self.__onRecreateDevice)
        self.__settingsInterface.dispossessUI()
        self.__settingsInterface = None
        VoiceChatInterface.g_instance.onVoiceChatInitFailed -= self.onVoiceChatInitFailed
        if self.__dynSquadListener:
            self.__dynSquadListener.destroy()
            self.__dynSquadListener = None
        BattleWindow.beforeDelete(self)
        event = events.AppLifeCycleEvent
        g_eventBus.handleEvent(event(self.__ns, event.DESTROYED))

    def __onVehicleStateUpdated(self, state, value):
        if state not in self.__stateHandlers:
            return
        handler = getattr(self, self.__stateHandlers[state], None)
        if handler and callable(handler):
            if value is not None:
                handler(value)
            else:
                handler()

    def _setFireInVehicle(self, bool):
        self.call('destroyTimer.onFireInVehicle', [bool])

    def onVoiceChatInitFailed(self):
        if GUI_SETTINGS.voiceChat:
            self.call('VoiceChat.initFailed', [])

    def clearCommands(self):
        pass

    def bindCommands(self):
        self.__consumablesPanel.bindCommands()
        self.__ingameHelp.buildCmdMapping()

    def updateFlagsColor(self):
        isColorBlind = g_settingsCore.getSetting('isColorBlind')
        colorGreen = self.colorManager.getSubScheme('flag_team_green', isColorBlind=isColorBlind)['rgba']
        colorRed = self.colorManager.getSubScheme('flag_team_red', isColorBlind=isColorBlind)['rgba']
        arenaDP = g_sessionProvider.getArenaDP()
        teamsOnArena = arenaDP.getTeamsOnArena()
        for teamIdx in teamsOnArena:
            color = colorGreen if arenaDP.isAllyTeam(teamIdx) else colorRed
            BigWorld.wg_setFlagColor(teamIdx, color / 255)

        for teamIdx in [0] + teamsOnArena:
            BigWorld.wg_setFlagEmblem(teamIdx, 'system/maps/wg_emblem.dds', Math.Vector4(0.0, 0.1, 0.5, 0.9))

    def setPlayerSpeaking(self, accountDBID, flag):
        self.__callEx('setPlayerSpeaking', [accountDBID, flag])
        vID = g_sessionProvider.getCtx().getVehIDByAccDBID(accountDBID)
        if vID > 0:
            self.__markersManager.showDynamic(vID, flag)

    def isPlayerSpeaking(self, accountDBID):
        return VoiceChatInterface.g_instance.isPlayerSpeaking(accountDBID)

    def __onPostMortemSwitched(self):
        LogitechMonitor.onScreenChange('postmortem')
        if self.radialMenu is not None:
            self.radialMenu.forcedHide()
        if not g_sessionProvider.getCtx().isPlayerObserver():
            self.__callEx('showPostmortemTips', [1.0, 5.0, 1.0])

    def cursorVisibility(self, callbackId, visible, x = None, y = None, customCall = False, enableAiming = True):
        if visible:
            g_cursorDelegator.syncMousePosition(self, x, y, customCall)
        else:
            g_cursorDelegator.restoreMousePosition()
        if BigWorld.player() is not None and isPlayerAvatar():
            BigWorld.player().setForcedGuiControlMode(visible, False, enableAiming)

    def tryLeaveRequest(self, _):
        resStr = 'quitBattle'
        replayCtrl = BattleReplay.g_replayCtrl
        player = BigWorld.player()
        isVehicleAlive = getattr(player, 'isVehicleAlive', False)
        isNotTraining = self.__arena.guiType != constants.ARENA_GUI_TYPE.TRAINING
        isNotEventBattle = self.__arena.guiType != constants.ARENA_GUI_TYPE.EVENT_BATTLES
        if not replayCtrl.isPlaying:
            if constants.IS_KOREA and gui.GUI_SETTINGS.igrEnabled and self.__arena is not None and isNotTraining:
                vehicleID = getattr(player, 'playerVehicleID', -1)
                if vehicleID in self.__arena.vehicles:
                    vehicle = self.__arena.vehicles[vehicleID]
                    if isVehicleAlive and vehicle.get('igrType') != constants.IGR_TYPE.NONE:
                        resStr = 'quitBattleIGR'
                else:
                    LOG_ERROR("Player's vehicle not found", vehicleID)
            isDeserter = isVehicleAlive and isNotTraining and isNotEventBattle
            if isDeserter:
                resStr += '/deserter'
        else:
            isDeserter = False
        self.__callEx('tryLeaveResponse', [resStr, isDeserter])

    def onExitBattle(self, _):
        arena = getattr(BigWorld.player(), 'arena', None)
        LOG_DEBUG('onExitBattle', arena)
        if arena:
            BigWorld.player().leaveArena()

    def toggleHelpWindow(self, _):
        self.__callEx('showHideHelp', [not self.__isHelpWindowShown])

    def setAimingMode(self, isAiming):
        self.__callEx('setAimingMode', [isAiming])

    def helpDialogOpenStatus(self, cid, isOpened):
        self.__isHelpWindowShown = isOpened

    def _initLobbyDialog(self, cid):
        if connectionManager.serverUserName:
            tooltipBody = i18n.makeString('#tooltips:header/info/players_online_full/body')
            tooltipFullData = makeTooltip('#tooltips:header/info/players_online_full/header', tooltipBody % {'servername': connectionManager.serverUserName})
            self.__callEx('setServerStatsInfo', [tooltipFullData])
            self.__callEx('setServerName', [connectionManager.serverUserName])
            if constants.IS_SHOW_SERVER_STATS:
                stats = game_control.g_instance.serverStats.getStats()
                if 'clusterCCU' in stats and 'regionCCU' in stats:
                    self.__callEx('setServerStats', [stats['clusterCCU'], stats['regionCCU']])
                else:
                    self.__callEx('setServerStats', [None, None])
        else:
            self.__callEx('setServerName', ['-'])
        links = GUI_SETTINGS.reportBugLinks
        if len(links):
            reportBugButton = makeHyperLink('ingameMenu', MENU.INGAME_MENU_LINKS_REPORT_BUG)
            self.__callEx('setReportBugLink', [reportBugButton])

    def reportBug(self, _):
        reportBugOpenConfirm(g_sessionProvider.getArenaDP().getVehicleInfo().player.accountDBID)

    def __getDynamicSquadsInitParams(self):
        return [self.__arena.guiType == constants.ARENA_GUI_TYPE.RANDOM, False]

    def __populateData(self, isMutlipleTeams = False):
        arena = avatar_getter.getArena()
        arenaDP = g_sessionProvider.getArenaDP()
        arenaData = ['',
         0,
         '',
         '',
         '']
        if arena:
            arenaData = [toUpper(arena.arenaType.name)]
            descExtra = getPrebattleFullDescription(arena.extraData or {})
            arenaSubType = getArenaSubTypeName(BigWorld.player().arenaTypeID)
            if descExtra:
                arenaData.extend([arena.guiType + 1, descExtra])
            elif arena.guiType in [constants.ARENA_GUI_TYPE.RANDOM, constants.ARENA_GUI_TYPE.TRAINING]:
                arenaTypeName = '#arenas:type/%s/name' % arenaSubType
                arenaData.extend([getNecessaryArenaFrameName(arenaSubType, isBaseExists(BigWorld.player().arenaTypeID, BigWorld.player().team)), arenaTypeName])
            elif arena.guiType in constants.ARENA_GUI_TYPE.RANGE:
                arenaData.append(constants.ARENA_GUI_TYPE_LABEL.LABELS[arena.guiType])
                if arena.guiType == constants.ARENA_GUI_TYPE.EVENT_BATTLES and hasResourcePoints():
                    arenaData.append(i18n.makeString(MENU.LOADING_BATTLETYPES_RESOURCEPOINTS_UPPER))
                elif arena.guiType == constants.ARENA_GUI_TYPE.EVENT_BATTLES and isMutlipleTeams:
                    arenaData.append(i18n.makeString(MENU.LOADING_BATTLETYPES_MIX_UPPER))
                else:
                    arenaData.append('#menu:loading/battleTypes/%d' % arena.guiType)
            else:
                arenaData.extend([arena.guiType + 1, '#menu:loading/battleTypes/%d' % arena.guiType])
            myTeamNumber = arenaDP.getNumberOfTeam()
            getTeamName = g_sessionProvider.getCtx().getTeamName
            arenaData.extend([getTeamName(myTeamNumber), getTeamName(arenaDP.getNumberOfTeam(enemy=True))])
            teamHasBase = 1 if isBaseExists(BigWorld.player().arenaTypeID, myTeamNumber) else 2
            if not isEventBattle():
                typeEvent = 'normal'
                winText = getBattleSubTypeWinText(BigWorld.player().arenaTypeID, teamHasBase)
            else:
                typeEvent = 'fallout'
                if getIsMultiteam():
                    winText = i18n.makeString(ARENAS.TYPE_FALLOUTMUTLITEAM_DESCRIPTION)
                else:
                    winText = i18n.makeString('#arenas:type/%s/description' % arenaSubType)
            arenaData.append(winText)
            arenaData.append(typeEvent)
            vehInfo = arenaDP.getVehicleInfo(arenaDP.getPlayerVehicleID())
            pqTipData = [None] * 3
            pQuests = vehInfo.player.getPotapovQuests()
            serverSettings = g_lobbyContext.getServerSettings()
            isPQEnabled = serverSettings is not None and serverSettings.isPotapovQuestEnabled()
            if isPQEnabled and (arena.guiType == constants.ARENA_GUI_TYPE.RANDOM or arena.guiType == constants.ARENA_GUI_TYPE.TRAINING and constants.IS_DEVELOPMENT):
                if len(pQuests):
                    quest = pQuests[0]
                    pqTipData = [quest.getUserName(), quest.getUserMainCondition(), quest.getUserAddCondition()]
                else:
                    pqTipData = [i18n.makeString('#ingame_gui:potapovQuests/tip'), None, None]
            arenaData.extend(pqTipData)
            arenaData.extend([getArenaIcon(_SMALL_MAP_SOURCE)])
        self.__callEx('arenaData', arenaData)

    def __onRecreateDevice(self, scale = None):
        params = list(GUI.screenResolution())
        params.append(g_settingsCore.interfaceScale.get())
        self.call('Stage.Update', params)
        self.__markersManager.updateMarkersScale()

    def __callEx(self, funcName, args = None):
        self.call('battle.' + funcName, args)

    def __accs_onSettingsChanged(self, diff):
        self.colorManager.update()
        if 'isColorBlind' in diff:
            isColorBlind = diff['isColorBlind']
            self.__leftPlayersPanel.defineColorFlags(isColorBlind=isColorBlind)
            self.__rightPlayersPanel.defineColorFlags(isColorBlind=isColorBlind)
            self.updateFlagsColor()
            self.__markersManager.updateMarkers()
            self.__minimap.updateEntries()
        if 'enemy' in diff or 'dead' in diff or 'ally' in diff:
            markers = {'enemy': g_settingsCore.getSetting('enemy'),
             'dead': g_settingsCore.getSetting('dead'),
             'ally': g_settingsCore.getSetting('ally')}
            self.__markersManager.setMarkerSettings(markers)
            self.__markersManager.updateMarkerSettings()
        if 'showVehiclesCounter' in diff:
            self.isVehicleCountersVisible = diff['showVehiclesCounter']
            self.__fragCorrelation.showVehiclesCounter(self.isVehicleCountersVisible)
        if 'interfaceScale' in diff:
            self.__onRecreateDevice()
        self.__arenaCtrl.invalidateGUI()
        self.__arenaCtrl.invalidateArenaInfo()

    def setTeamValuesData(self, data):
        if self.__battle_flashObject is not None:
            self.__battle_flashObject.setTeamValues(data)

    def setMultiteamValues(self, data):
        if self.__battle_flashObject is not None:
            self.__battle_flashObject.setMultiteamValues(data)

    def getPlayerNameLength(self, isEnemy):
        panel = self.rightPlayersPanel if isEnemy else self.leftPlayersPanel
        return panel.getPlayerNameLength()