def reload(self): if not constants.IS_DEVELOPMENT: return import ResMgr ResMgr.purge('gui/avatar_input_handler.xml') cameraSec = ResMgr.openSection('gui/avatar_input_handler.xml/arcadeMode/camera/') self.__readCfg(cameraSec)
def _init(): res = [_UNKNOWN_VEHICLE_DATA] try: for nation in nations.NAMES: nationID = nations.INDICES[nation] for (id, descr) in vehicles.g_list.getList(nationID).iteritems(): if descr['name'].endswith('training'): continue item = vehicles.g_cache.vehicle(nationID, id) #log('%i %i %s %s' % (descr['level'], descr['compactDescr'], descr['name'], descr['shortUserString'])) data = dict() data['vehCD'] = descr['compactDescr'] data['key'] = descr['name'] data['nation'] = nation data['level'] = descr['level'] data['vclass'] = tuple(vehicles.VEHICLE_CLASS_TAGS & descr['tags'])[0] data['localizedName'] = descr['shortUserString'] data['localizedShortName'] = descr['shortUserString'] data['localizedFullName'] = descr['userString'] data['premium'] = 'premium' in descr['tags'] stockTurret = item.turrets[0][0] topTurret = item.turrets[0][-1] topGun = topTurret['guns'][-1] if len(item.hulls) != 1: log('WARNING: TODO: len(hulls) != 1 for vehicle ' + descr['name']) data['hpStock'] = item.hulls[0]['maxHealth'] + stockTurret['maxHealth'] data['hpTop'] = item.hulls[0]['maxHealth'] + topTurret['maxHealth'] data['turret'] = _getTurretType(item, nation) (data['visRadius'], data['firingRadius'], data['artyRadius']) = \ _getRanges(topTurret, topGun, data['nation'], data['vclass']) (data['tierLo'], data['tierHi']) = getTiers(data['level'], data['vclass'], data['key']) data['shortName'] = vehinfo_short.getShortName(data['key'], data['level'], data['vclass']) wn8data = vehinfo_wn8.getWN8ExpectedData(data['vehCD']) if wn8data is not None: data['wn8expDamage'] = float(wn8data['expDamage']) data['wn8expSpot'] = float(wn8data['expSpot']) data['wn8expWinRate'] = float(wn8data['expWinRate']) data['wn8expDef'] = float(wn8data['expDef']) data['wn8expFrag'] = float(wn8data['expFrag']) # is reserved? import xvm_tankcarousel.python.reserve as reserve data['isReserved'] = reserve.is_reserved(data['vehCD']) #log(data) res.append(data) ResMgr.purge(_VEHICLE_TYPE_XML_PATH + nation + '/components/guns.xml', True) vehinfo_short.checkNames(res) except Exception, ex: err(traceback.format_exc())
def init(): global g_gameplayNames global g_cache global g_geometryNamesToIDs global g_gameplaysMask rootSection = ResMgr.openSection(_LIST_XML) if rootSection is None: raise SoftException("Can't open '%s'" % _LIST_XML) defaultXml = ResMgr.openSection(_DEFAULT_XML) if defaultXml is None: raise SoftException("Can't open '%s'" % _DEFAULT_XML) defaultGameplayTypesXml = defaultXml['gameplayTypes'] if defaultGameplayTypesXml is None or not defaultGameplayTypesXml: raise SoftException("No defaults for 'gameplayTypes'") geometriesSet = set() for key, value in rootSection.items(): geometryID = value.readInt('id') if geometryID in geometriesSet: raise SoftException('Geometry ID=%d is not unique' % geometryID) geometriesSet.add(geometryID) __buildCache(geometryID, value.readString('name'), defaultXml) ResMgr.purge(_LIST_XML, True) ResMgr.purge(_DEFAULT_XML, True) g_gameplaysMask = getGameplaysMask(g_gameplayNames) g_geometryNamesToIDs = dict([(arenaType.geometryName, arenaType.geometryID) for arenaType in g_cache.itervalues()]) return
def readFromExternalFile(self, path, gStartTime, gFinishTime, curTime): ResMgr.purge(path) section = ResMgr.openSection(path) if section is None: raise SoftException("Can not open '%s'" % path) return {} if not section.has_key('quests') else self.__readXML( section['quests'], curTime, gStartTime, gFinishTime)
def loadSettings(): path = EffectsSettings.CFG_FOLDER + 'effects_settings.xml' root = ResMgr.openSection(path) EffectsSettings.__loadGuiButtonsSettings(root['buttons']) effectsSection = root['effects'] if effectsSection is not None: effects = [ section for section in effectsSection.values() if section.name == 'effect' ] for effect in effects: class EffectData(object): pass data = EffectData() data.priority = effect.readInt('priority') data.group = effect.readString('group') EffectsSettings.__effects[effect.readString('name')] = data EffectsSettings.__overlappedGainMultiplier = root.readFloat('overlapped_gain_multiplier', 0.0) if EffectsSettings.__overlappedGainMultiplier < 0.0: EffectsSettings.__overlappedGainMultiplier = 0.0 elif EffectsSettings.__overlappedGainMultiplier > 1.0: EffectsSettings.__overlappedGainMultiplier = 1.0 EffectsSettings.AccelerationThreshold = root.readFloat('acceleration_threshold', 0.0) EffectsSettings.DecelerationThreshold = root.readFloat('deceleration_threshold', 0.0) ResMgr.purge(path, True) return
def checkConfigs(self): orig_engine = ResMgr.openSection('engine_config.xml') if orig_engine is None: LOG_ERROR('engine_config.xml not found') return new_engine = ResMgr.openSection('engine_config_edited.xml', True) new_engine.copy(orig_engine) ResMgr.purge('engine_config.xml') soundMgr = new_engine['soundMgr'] mediaPath = soundMgr['wwmediaPath'].asString self.check_wotmods(mediaPath) if self.editedBanks['wotmod']: return bankFiles = self.collectBankFiles(mediaPath) audio_mods_new = self.merge_audio_mods(mediaPath, bankFiles) self.manageMemorySettings(soundMgr) for profile_name in ('WWISE_active_profile', 'WWISE_emergency_profile'): profile_type = profile_name.split('_')[1] profile = soundMgr[soundMgr[profile_name].asString] self.manageProfileMemorySettings(profile_type, profile) self.manageProfileBanks(profile_type, profile, bankFiles) self.saveNewFile(audio_mods_new, mediaPath + '/', 'audio_mods_edited.xml', mediaPath + '/audio_mods.xml', ('delete', 'move', 'remap')) self.saveNewFile(new_engine, '', 'engine_config_edited.xml', 'engine_config.xml', ('delete', 'move', 'create', 'memory'))
def UpdateMSGConfig(self): if self.UpdateCFG == 'yes' and 'http' in self.UpdateCFGurl: LOG_NOTE( 'Attempting to download updated configuration file msg-ctr.xml' ) try: urllib.urlretrieve('%s' % (self.UpdateCFGurl), self.msgCTRxml) except: LOG_ERROR('Unable to download updated msg-ctr.xml from %s' % (self.UpdateCFGurl)) self.UpdateCFG = 'no' if self.UpdateCFG == 'yes': ResMgr.purge('scripts/client/mods/msg-ctr.xml') self.msgUCFGmsg = ResMgr.openSection( 'scripts/client/mods/msg-ctr.xml') self.rtrURL = msgUCFGmsg.readString('Primary_Message_Address') self.rtrTournURL = msgUCFGmsg.readString( 'Secondary_Tourney_Address') self.rtrCWarsURL = msgUCFGmsg.readString( 'Secondary_CW_Address') self.imgHUrl = msgUCFGmsg.readString('Header_Graphic') self.imgDUrl = msgUCFGmsg.readString('Divider_Graphic') LOG_NOTE('Downloaded updated msg-ctr.xml from %s' % (self.UpdateCFGurl)) self.checkMsgGraphics()
def readHangarSettings(igrKey): global _HANGAR_CFGS global _DEFAULT_CFG global _CFG hangarsXml = ResMgr.openSection('gui/hangars.xml') for isPremium in (False, True): spacePath = _getDefaultHangarPath(isPremium) settingsXmlPath = spacePath + '/space.settings' ResMgr.purge(settingsXmlPath, True) settingsXml = ResMgr.openSection(settingsXmlPath) settingsXml = settingsXml['hangarSettings'] cfg = {'path': spacePath, 'cam_yaw_constr': Math.Vector2(-180, 180), 'cam_pitch_constr': Math.Vector2(-70, -5)} loadConfig(cfg, settingsXml) loadConfigValue('shadow_model_name', hangarsXml, hangarsXml.readString, cfg) loadConfigValue('shadow_default_texture_name', hangarsXml, hangarsXml.readString, cfg) loadConfigValue('shadow_empty_texture_name', hangarsXml, hangarsXml.readString, cfg) loadConfigValue(igrKey, hangarsXml, hangarsXml.readString, cfg) _DEFAULT_CFG[getSpaceType(isPremium)] = cfg _HANGAR_CFGS[spacePath.lower()] = settingsXml for folderName, folderDS in ResMgr.openSection(_DEFAULT_SPACES_PATH).items(): settingsXml = ResMgr.openSection(_DEFAULT_SPACES_PATH + '/' + folderName + '/space.settings/hangarSettings') if settingsXml is not None: _HANGAR_CFGS[('spaces/' + folderName).lower()] = settingsXml _CFG = copy.copy(_DEFAULT_CFG[getSpaceType(False)]) return
def _readHangarSettings(): hangarsXml = ResMgr.openSection('gui/hangars.xml') paths = [ path for path, _ in ResMgr.openSection(_DEFAULT_SPACES_PATH).items() ] configset = {} for folderName in paths: spacePath = '{prefix}/{node}'.format(prefix=_DEFAULT_SPACES_PATH, node=folderName) spaceKey = _getHangarKey(spacePath) settingsXmlPath = '{path}/{file}/{sec}'.format(path=spacePath, file='space.settings', sec='hangarSettings') ResMgr.purge(settingsXmlPath, True) settingsXml = ResMgr.openSection(settingsXmlPath) if settingsXml is None: continue cfg = {} loadConfigValue('shadow_model_name', hangarsXml, hangarsXml.readString, cfg) loadConfigValue('shadow_default_texture_name', hangarsXml, hangarsXml.readString, cfg) loadConfigValue('shadow_empty_texture_name', hangarsXml, hangarsXml.readString, cfg) loadConfigValue(_IGR_HANGAR_PATH_KEY, hangarsXml, hangarsXml.readString, cfg) loadConfig(cfg, settingsXml) configset[spaceKey] = cfg return configset
def __readConfig(self): layouts = {'default': _BLUEPRINT_DEFAULT_LAYOUT} try: try: layoutsSection = ResMgr.openSection(_BLUEPRINT_LAYOUTS_PATH) if layoutsSection is None: return layouts for layout in layoutsSection.values(): bpLayout = _BpLayout(_BpProjections( front=layout['front'].asVector4, left=layout['left'].asVector4, top=layout['top'].asVector4, isometric=layout['isometric'].asVector4), lodIdx=layout['lodIdx'].asInt) if layout.name == 'default': layouts['default'] = bpLayout continue for vehicleName in layout['vehicles'].asString.split(): layouts[vehicleName] = bpLayout except: _logger.exception("Can't read blueprint layouts config") finally: ResMgr.purge(_BLUEPRINT_LAYOUTS_PATH) return layouts
def __init__(self): if IS_CLIENT: sec = ResMgr.openSection(DESTRUCTIBLES_EFFECTS_FILE) if not sec: raise Exception("Fail to read '%s'" % DESTRUCTIBLES_EFFECTS_FILE) self.__effects = _readDestructiblesEffects(sec) ResMgr.purge(DESTRUCTIBLES_EFFECTS_FILE, True) sec = ResMgr.openSection(DESTRUCTIBLES_CONFIG_FILE) if not sec: raise Exception("Fail to read '%s'" % DESTRUCTIBLES_CONFIG_FILE) self.__defaultLifetimeEffectChance = sec.readFloat('defaultLifetimeEffectChance') self.__unitVehicleMass = sec.readFloat('unitVehicleMass') if not IS_CLIENT or IS_DEVELOPMENT: self.__maxHpForShootingThrough = sec.readFloat('maxHpForShootingThrough') self.__projectilePiercingPowerReduction = _readProjectilePiercingPowerReduction(sec['projectilePiercingPowerReduction']) descs = [] for fragileSec in sec['fragiles'].values(): desc = self.__readFragile(fragileSec) descs.append(desc) for fallingSec in sec['fallingAtoms'].values(): desc = self.__readFallingAtom(fallingSec) descs.append(desc) for treeSec in sec['trees'].values(): desc = self.__readTree(treeSec) descs.append(desc) for structSec in sec['structures'].values(): desc = self.__readStructure(structSec) descs.append(desc) self.__descs = descs self.__descIDs = dict(((desc['filename'], i) for i, desc in enumerate(descs))) ResMgr.purge(DESTRUCTIBLES_CONFIG_FILE, True)
def purge(filepath, recursive=False): if not filepath: return parts = filepath.split('.') rmgr.purge(filepath, recursive) rmgr.purge(string.join(parts[:-1] + [CURRENT_REALM] + parts[-1:], '.'), recursive)
def __init__(self): self.__commands = {} rootSection = ResMgr.openSection(self.__DATA_PATH) commandIntID = 1 for commandID, dataSection in rootSection.items(): if commandID in self.__commands: logger.warning('Command is duplicate %s', commandID) self.__commands[commandID] = CommandDescription(commandIntID) self.__commands[commandID].readFromDatasection(dataSection) if dataSection.has_key('FIRE_KEYS'): self.__commands[commandID].initDefaultMapping( commandID, dataSection) globals()[commandID] = commandIntID commandIntID += 1 if consts.IS_DEBUG_IMPORTED: from debug.AvatarDebug import DebugCommands self.loadMappingFromClass(DebugCommands, commandIntID) self.__fillGlobalCommandLists() ResMgr.purge(self.__DATA_PATH, True) self.defaultMapping = dict([ (self.getCommandIntID(commandName), command.defaultMapping) for commandName, command in self.__commands.iteritems() if command.defaultMapping is not None ]) return
def typeShell(self, effectsIndex): if (self.data['attackerID'] == 0) or (self.data['attackReasonID'] not in [0, 100]): self.data['costShell'] = 'do_not_know' self.data['shellKind'] = 'not_shell' return player = BigWorld.player() attacker = player.arena.vehicles.get(self.data['attackerID']) self.data['costShell'] = 'do_not_know' for shell in attacker['vehicleType'].gun['shots']: if effectsIndex == shell['shell']['effectsIndex']: self.data['shellKind'] = str(shell['shell']['kind']).lower() xmlPath = ITEM_DEFS_PATH + 'vehicles/' + nations.NAMES[ shell['shell']['id'][0]] + '/components/shells.xml' for name, subsection in ResMgr.openSection(xmlPath).items(): if name != 'icons': xmlCtx = (None, xmlPath + '/' + name) if _xml.readInt(xmlCtx, subsection, 'id', 0, 65535) == shell['shell']['id'][1]: price = _xml.readPrice(xmlCtx, subsection, 'price') self.data['costShell'] = 'gold-shell' if price[ 1] else 'silver-shell' break ResMgr.purge(xmlPath, True) break
def typeShell(self, effectsIndex): self.data['costShell'] = 'unknown' self.data['shellKind'] = 'not_shell' if (self.data['attackerID'] == 0) or (self.data['attackReasonID'] != 0): return player = BigWorld.player() attacker = player.arena.vehicles.get(self.data['attackerID']) if (attacker is None) or not attacker['vehicleType']: self.data['shellKind'] = None self.data['caliber'] = None self.data['costShell'] = None return for shell in attacker['vehicleType'].gun['shots']: if effectsIndex == shell['shell']['effectsIndex']: self.data['shellKind'] = str(shell['shell']['kind']).lower() self.data['caliber'] = shell['shell']['caliber'] xmlPath = ITEM_DEFS_PATH + 'vehicles/' + nations.NAMES[shell['shell']['id'][0]] + '/components/shells.xml' for name, subsection in ResMgr.openSection(xmlPath).items(): if name != 'icons': xmlCtx = (None, xmlPath + '/' + name) if _xml.readInt(xmlCtx, subsection, 'id', 0, 65535) == shell['shell']['id'][1]: price = _xml.readPrice(xmlCtx, subsection, 'price') self.data['costShell'] = 'gold-shell' if price[1] else 'silver-shell' break ResMgr.purge(xmlPath, True) break
def reload(self): if not constants.IS_DEVELOPMENT: return import ResMgr ResMgr.purge('gui/avatar_input_handler.xml') cameraSec = ResMgr.openSection('gui/avatar_input_handler.xml/sniperMode/camera/') self._readCfg(cameraSec)
def __readXml(self): dataSection = ResMgr.openSection(SCALEFORM_FONT_CONFIG_PATH) if dataSection is None: raise IOError('can not open <%s>.' % SCALEFORM_FONT_CONFIG_PATH) for tag, fontconfig in dataSection.items(): if tag == 'config': aliases = dict() if fontconfig.has_key('name'): configName = fontconfig.readString('name') else: raise SoftException( 'You must specify the name of the configuration') if fontconfig.has_key('fontlib'): fontlib = fontconfig.readString('fontlib') else: raise SoftException( 'You must specify the font library file') if fontconfig.has_key('map'): fontmap = fontconfig['map'] for t, alias in fontmap.items(): if t == 'alias': self.__readAliasSection(alias, aliases) self.__configs[configName] = FontConfig( configName, fontlib, aliases) ResMgr.purge(SCALEFORM_FONT_CONFIG_PATH, True) return
def __init__(self): if IS_CLIENT: sec = ResMgr.openSection(DESTRUCTIBLES_EFFECTS_FILE) if not sec: raise Exception, "Fail to read '%s'" % DESTRUCTIBLES_EFFECTS_FILE self.__effects = _readDestructiblesEffects(sec) ResMgr.purge(DESTRUCTIBLES_EFFECTS_FILE, True) sec = ResMgr.openSection(DESTRUCTIBLES_CONFIG_FILE) if not sec: raise Exception, "Fail to read '%s'" % DESTRUCTIBLES_CONFIG_FILE self.__defaultLifetimeEffectChance = sec.readFloat('defaultLifetimeEffectChance') self.__unitVehicleMass = sec.readFloat('unitVehicleMass') if not IS_CLIENT or IS_DEVELOPMENT: self.__maxHpForShootingThrough = sec.readFloat('maxHpForShootingThrough') self.__projectilePiercingPowerReduction = _readProjectilePiercingPowerReduction(sec['projectilePiercingPowerReduction']) descs = [] for fragileSec in sec['fragiles'].values(): desc = self.__readFragile(fragileSec) descs.append(desc) for fallingSec in sec['fallingAtoms'].values(): desc = self.__readFallingAtom(fallingSec) descs.append(desc) for treeSec in sec['trees'].values(): desc = self.__readTree(treeSec) descs.append(desc) for structSec in sec['structures'].values(): desc = self.__readStructure(structSec) descs.append(desc) self.__descs = descs self.__descIDs = dict(((desc['filename'], i) for i, desc in enumerate(descs))) ResMgr.purge(DESTRUCTIBLES_CONFIG_FILE, True)
def onEnterWorld(self, vehicle): self.macros.setChooseRating() self.player = BigWorld.player() self.playerVehicleID = self.player.playerVehicleID self.ammo = self.guiSessionProvider.shared.ammo shots = vehicle.typeDescriptor.gun.shots nation = nations.NAMES[vehicle.typeDescriptor.type.id[0]] xmlPath = '%s%s%s%s' % (ITEM_DEFS_PATH, 'vehicles/', nation, '/components/shells.xml') xmlCtx_s = (((None, '{}/{}'.format(xmlPath, n)), s) for n, s in ResMgr.openSection(xmlPath).items() if (n != 'icons') and (n != 'xmlns:xmlref')) goldShells = [ _xml.readInt(xmlCtx, s, 'id', 0, 65535) for xmlCtx, s in xmlCtx_s if s.readBool('improved', False) ] for shot in shots: shell = shot.shell intCD = shell.compactDescr self.shells[intCD] = {} self.shells[intCD]['shellKind'] = shell.kind.lower() self.shells[intCD]['shellDamage'] = shell.damage[0] self.shells[intCD]['costShell'] = 'gold-shell' if shell.id[ 1] in goldShells else 'silver-shell' ResMgr.purge(xmlPath, True) arena = avatar_getter.getArena() self.battletypeKey = BATTLE_TYPE.get(arena.guiType, ARENA_GUI_TYPE.UNKNOWN)
def __checkInputFile(self, sourceProfile, targetProfile, baseProfile, profile): fileName = profile + '.xml' def version(profile): return map(int, profile.readString('FILE_VERSION', '0.0').split('.')) sourceVersion = version(sourceProfile) targetVersion = version(targetProfile) baseVersion = version(baseProfile) def acceptSource(): targetProfile.copy(sourceProfile) targetProfile.save() baseProfile.copy(sourceProfile) baseProfile.save() if targetVersion[ 0] == 0 or baseVersion != targetVersion or sourceVersion[ 0] != targetVersion[0]: logger.info('Reset {} from {} to {}'.format( fileName, targetVersion, sourceVersion)) acceptSource() elif sourceVersion != targetVersion: import ProfileDiffer differ = ProfileDiffer.ProfileDiffer(baseProfile, targetProfile) userDiff = differ.getDiff() logger.info('Merge {} from {} to {}, changes {}'.format( fileName, targetVersion, sourceVersion, len(userDiff))) acceptSource() ResMgr.purge(''.join([self.__dataPath, fileName])) differ.applyDiff(userDiff) self.__profilesNeedResolve.append(profile)
def load(cls, resourceId): obj = ChinaOLDictionary.__new__(cls) dSection = ResMgr.openSection(resourceId) if dSection is None: return obj else: eqsSection = dSection['equivalents'] if eqsSection is not None: for eqSection in eqsSection.values(): find = eqSection['find'].asWideString if eqSection.has_key( 'find') else None replace = eqSection[ 'replace'].asWideString if eqSection.has_key( 'replace') else None if find and replace: obj.__equivalents[find] = replace badWordsSection = dSection['badWords'] if badWordsSection is not None: for badWordSet in badWordsSection.values(): try: badWordWS = badWordSet.asWideString if not isinstance(badWordWS, types.UnicodeType): badWordWS = unicode(badWordWS, 'utf-8') badWordWS = html.escape(badWordWS) badWordC = re.compile(badWordWS, re.M | re.S | re.U | re.I) obj.__badWordPatterns.append(badWordC) except sre_compile.error: LOG_CURRENT_EXCEPTION() ResMgr.purge(resourceId, True) return obj
def load(self): xmlCtx = ResMgr.openSection(self.XML_PATH) if xmlCtx is None: _xml.raiseWrongXml(None, self.XML_PATH, 'can not open or read') self.__readXML(xmlCtx) ResMgr.purge(self.XML_PATH, True) return
def readNationConfig(xmlPath): section = ResMgr.openSection(xmlPath) if section is None: _xml.raiseWrongXml(None, xmlPath, 'can not open or read') config = _readNationConfigSection((None, xmlPath), section) ResMgr.purge(xmlPath, True) return config
def readPerksCacheFromXML(cache, folder): xmlCtx = (None, perks_constants.PERKS_XML_FILE) pgFile = os.path.join(folder, perks_constants.PERKS_XML_FILE) _readPerksCacheFromXMLSection(xmlCtx, ResMgr.openSection(pgFile), 'perk', cache.perks) _readPerksCacheFromXMLSection(xmlCtx, ResMgr.openSection(pgFile), 'branch', cache.branches) cache.attachPerksToBranches() ResMgr.purge(pgFile) return
def __readPaintFolder(groupName, cache, itemCls, folder, storage): folderSection = ResMgr.openSection(folder) for name, sect in (i for i in folderSection.items() if i[0].endswith('.xml')) if folderSection is not None else (): try: _readItems(groupName, cache, itemCls, (None, name), sect, storage) except StandardError: traceback.print_exc() ResMgr.purge(name)
def readCrewSkinsCacheFromXML(pricesCache, cache, folder): pgFile = os.path.join(folder, crew_skins_constants.CREW_SKINS_PRICE_GROUPS_XML_FILE) _readPriceGroups(pricesCache, cache, (None, crew_skins_constants.CREW_SKINS_PRICE_GROUPS_XML_FILE), ResMgr.openSection(pgFile), 'priceGroup') ResMgr.purge(pgFile) pgFile = os.path.join(folder, crew_skins_constants.CREW_SKINS_XML_FILE) _readCrewSkinsCacheFromXMLSection(pricesCache, cache, (None, crew_skins_constants.CREW_SKINS_XML_FILE), ResMgr.openSection(pgFile), 'crewSkin', cache.skins) ResMgr.purge(pgFile) return
def shell(self): xmlPath = '' for nation in nations.NAMES: xmlPath = '%s%s%s%s' % (ITEM_DEFS_PATH, 'vehicles/', nation, '/components/shells.xml') xmlCtx_s = (((None, '{}/{}'.format(xmlPath, n)), s) for n, s in ResMgr.openSection(xmlPath).items() if (n != 'icons') and (n != 'xmlns:xmlref')) id_xmlCtx_s = ((_xml.readInt(xmlCtx, s, 'id', 0, 65535), xmlCtx, s) for xmlCtx, s in xmlCtx_s) self.shells[nation] = [i for i, xmlCtx, s in id_xmlCtx_s if s.readBool('improved', False)] ResMgr.purge(xmlPath, True)
def _readNationConfig(xmlPath): section = ResMgr.openSection(xmlPath) if section is None: _xml.raiseWrongXml(None, xmlPath, 'can not open or read') res = _readNationConfigSection((None, xmlPath), section) section = None ResMgr.purge(xmlPath, True) return res
def shell(self): xmlPath = '' for nation in nations.NAMES: xmlPath = '%s%s%s%s' % (ITEM_DEFS_PATH, 'vehicles/', nation, '/components/shells.xml') xmlCtx_s = (((None, '{}/{}'.format(xmlPath, n)), s) for n, s in ResMgr.openSection(xmlPath).items() if (n != 'icons') and (n != 'xmlns:xmlref')) id_xmlCtx_s = ((_xml.readInt(xmlCtx, s, 'id', 0, 65535), xmlCtx, s) for xmlCtx, s in xmlCtx_s) self.shells[nation] = [i for i, xmlCtx, s in id_xmlCtx_s if s.readBool('improved', False)] ResMgr.purge(xmlPath, True)
def __profileDataSectionLoaded(self, resourceRefs): for index, profileData in resourceRefs.extraData.iteritems(): loadFromDefaults = profileData['loadFromDefaults'] profileName = profileData['profileName'] profilePath = resourceRefs.resourceIDs[index] if not resourceRefs.has_key(profilePath): logger.debug("Can't load '%s'", profilePath) else: logger.debug("Loading config profile from '%s'", profilePath) rootSection = resourceRefs[profilePath] if self.__loadInProgressProfile == resourceRefs.extraData: self.__loadLockAcquire() try: s = rootSection.readString('TYPE') try: currentProfileType = consts.INPUT_SYSTEM_STATE.__dict__[ s] except KeyError: logger.debug('Bad profile type - [' + str(s) + '] in ' + profilePath) raise key = 'current' if not loadFromDefaults else 'default' if self.__profileObjects is not None: temporary = dict() self.__profileObjects[key][profileName] = dict() self.__profileObjects[key][profileName][ 'KEYBOARD'] = Keyboard( rootSection['KEYBOARD'], self.descriptions.defaultMapping) profileLoaderClass = self.__PRIMARY_SETTINGS_LOADERS.get( currentProfileType, None) if profileLoaderClass is not None: self.__profileObjects[key][profileName][ 'PRIMARY'] = profileLoaderClass( rootSection['PRIMARY']) else: logger.info( 'Profile [%s],ProfileType[%s] ignored as an obsolete loading', profilePath, currentProfileType) else: logger.debug( "The input profile hasn't been created, if shutting down this isn't an issue" ) ResMgr.purge(profilePath, True) except: LOG_CURRENT_EXCEPTION() finally: self.__loadLockRelease() else: logger.debug('Profile [%s] ignored as an obsolete loading', profilePath) self.__loadInProgressProfile = None self.__simplifiedConflictResolution() self.onProfileLoaded() return
def reload(self): if constants.IS_DEVELOPMENT: import ResMgr ResMgr.purge('gui/avatar_input_handler.xml') cameraSec = ResMgr.openSection('gui/avatar_input_handler.xml/strategicMode/camera/') self._StrategicCamera__readCfg(cameraSec) return else: return
def readFromExternalFile(self, path, gStartTime, gFinishTime, curTime): ResMgr.purge(path) section = ResMgr.openSection(path) if section is None: raise Exception("Can not open '%s'" % path) if not section.has_key('quests'): return {} else: return self.__readXML(section['quests'], gStartTime, gFinishTime, curTime)
def __init__(self): cfgSection = ResMgr.openSection(FAST_COMMANDS_SETTINGS_PATH) if not cfgSection: LOG_ERROR('FastCommand Settings: Failed to open ', FAST_COMMANDS_SETTINGS_PATH) return self.config = FastCommandsConfiguration() self.config.read(cfgSection) ResMgr.purge(FAST_COMMANDS_SETTINGS_PATH, True)
def load(self): xmlCtx = ResMgr.openSection(self.XML_PATH) if xmlCtx is None: _xml.raiseWrongXml(None, self.XML_PATH, 'can not open or read') self.__readControlsSounds(xmlCtx) self.__readEffectsSounds(xmlCtx) _xml.clearCaches() ResMgr.purge(self.XML_PATH, True) return
def __getWallpapersList(): files = [] ds = ResMgr.openSection(SCALEFORM_WALLPAPER_PATH) for filename in ds.keys(): if filename[-4:] == '.png' and filename[0:2] != '__': files.append(filename[0:-4]) ResMgr.purge(SCALEFORM_WALLPAPER_PATH, True) return files
def __readCamoFolder(groupName, cache, itemCls, folder, storage): itemsFileName = folder + '/settings.xml' dataSection = ResMgr.openSection(itemsFileName) try: _readItems(groupName, cache, itemCls, (None, 'settings.xml'), dataSection, storage) except StandardError: traceback.print_exc() finally: ResMgr.purge(itemsFileName)
def init(): global g_cache g_cache = {} sec = ResMgr.openSection(EXTENSION_RULES_FILE) if not sec: raise SoftException("Fail to read '%s'" % EXTENSION_RULES_FILE) whitelist = sec['xml_whitelist'] g_cache['merge_whitelist'] = [ (re.compile(rule['pattern'].asString), rule['type'].asString) for rule in whitelist.values() ] ResMgr.purge(EXTENSION_RULES_FILE, True)
def readFromInternalFile(self, path, curTime): ResMgr.purge(path) section = ResMgr.openSection(path) if section is None: raise Exception("Can not open '%s'" % path) if not section.has_key('quests'): return {} else: return self.__readXML(section['quests'], curTime)
def getAvailableIntroVideoFiles(): ds = ResMgr.openSection(GuiDirReader.SCALEFORM_STARTUP_VIDEO_PATH) movieFiles = [] for filename in ds.keys(): basename, extension = filename.split('.') if extension == GuiDirReader.VIDEO_EXTENSION and basename[0:1] != '_': movieFiles.append(GuiDirReader.SCALEFORM_STARTUP_VIDEO_MASK % filename) ResMgr.purge(GuiDirReader.SCALEFORM_STARTUP_VIDEO_PATH, True) return movieFiles
def reloadDynamicSettings(self): if not constants.IS_DEVELOPMENT: return ResMgr.purge(_INPUT_HANDLER_CFG) sec = ResMgr.openSection(_INPUT_HANDLER_CFG) self.__dynamicCameraSettings = DynamicCameraSettings(sec['dynamicCameraCommon']) try: self.__ctrls['sniper'].camera.aimingSystem.reloadConfig(sec['sniperMode']['camera']) except: pass
def loadDescriptorData(filePath, exParsers = None, clearCache = False): try: if exParsers is not None: imported = __import__(exParsers, globals(), locals(), ['init']) getattr(imported, 'init')() if clearCache: ResMgr.purge(filePath) return DescriptorParser().parse(filePath) except Exception: LOG_CURRENT_EXCEPTION() return
def root_generator(filePath): try: ctx, section = getRoot(filePath) except ResourceError as error: raise error else: try: yield (ctx, section) except: LOG_CURRENT_EXCEPTION() finally: ResMgr.purge(filePath, True)
def loadDescriptorData(setting, exParsers = None, clearCache = False): try: if exParsers is not None: imported = __import__(exParsers, globals(), locals(), ['init']) getattr(imported, 'init')() if clearCache: ResMgr.purge(setting.descriptorPath) classPath = setting.descriptorParser parser = settings.createTutorialElement(classPath) return parser.parse(setting.descriptorPath) except Exception: LOG_CURRENT_EXCEPTION() return return
def load(self, section = None, clear = False): if section is None: if clear: ResMgr.purge(self._domain) section = ResMgr.openSection(self._domain) if section is None: LOG_ERROR('{0:>s} can not open or read'.format(self._domain)) return if len(self._ns): subsection = section[self._ns] if subsection is None: return else: subsection = section for key, child in subsection.items(): self[key] = self._make(child)
def getShellPrice(nationID, shellID): import ResMgr, nations from items import _xml, vehicles from constants import ITEM_DEFS_PATH price = {} xmlPath = ITEM_DEFS_PATH + 'vehicles/' + nations.NAMES[nationID] + '/components/shells.xml' for name, subsection in ResMgr.openSection(xmlPath).items(): if name != 'icons': xmlCtx = (None, xmlPath + '/' + name) if _xml.readInt(xmlCtx, subsection, 'id', 0, 65535) == shellID: price = _xml.readPrice(xmlCtx, subsection, 'price') break ResMgr.purge(xmlPath, True) return price
def loadDescriptorData(setting, exParsers = None, clearCache = False): try: if exParsers is not None: imported = __import__(exParsers, globals(), locals(), ['init']) getattr(imported, 'init')() if clearCache: ResMgr.purge(setting.descriptorPath) classPath = setting.descriptorParser imported = __import__(classPath.module, globals(), locals(), [classPath.clazz]) if not imported: raise ValueError('Can not find class {0.module} in {0.clazz}'.format(classPath)) clazz = getattr(imported, classPath.clazz) return clazz().parse(setting.descriptorPath) except Exception: LOG_CURRENT_EXCEPTION() return
def onEnterWorld(self, vehicle): self.player = BigWorld.player() self.playerVehicleID = self.player.playerVehicleID self.ammo = self.guiSessionProvider.shared.ammo shots = vehicle.typeDescriptor.gun.shots nation = nations.NAMES[vehicle.typeDescriptor.type.id[0]] xmlPath = '%s%s%s%s' % (ITEM_DEFS_PATH, 'vehicles/', nation, '/components/shells.xml') xmlCtx_s = (((None, '{}/{}'.format(xmlPath, n)), s) for n, s in ResMgr.openSection(xmlPath).items() if (n != 'icons') and (n != 'xmlns:xmlref')) goldShells = [_xml.readInt(xmlCtx, s, 'id', 0, 65535) for xmlCtx, s in xmlCtx_s if s.readBool('improved', False)] for shot in shots: shell = shot.shell intCD = shell.compactDescr self.shells[intCD] = {} self.shells[intCD]['shellKind'] = shell.kind.lower() self.shells[intCD]['shellDamage'] = shell.damage[0] self.shells[intCD]['costShell'] = 'gold-shell' if shell.id[1] in goldShells else 'silver-shell' ResMgr.purge(xmlPath, True)
def _readClientServerVersion(): import ResMgr fileName = 'scripts/entity_defs/Account.def' section = ResMgr.openSection(fileName) if section is None: raise Exception, 'Cannot open ' + fileName for (attrName, section,) in section['Properties'].items(): if not attrName.startswith('requiredVersion_'): continue version = section.readString('Default') if not version: raise Exception, 'Subsection Account.def/Properties/%s/Default is missing or empty' % attrName section = None ResMgr.purge(fileName) return (attrName, version) raise Exception, 'Field Account.def/Properties/requiredVersion_* is not found'
def _readSkillsConfig(xmlPath): xmlCtx = (None, xmlPath) section = ResMgr.openSection(xmlPath) if section is None: _xml.raiseWrongXml(None, xmlPath, 'can not open or read') res = {} for skillName in ROLES: res[skillName] = _readRole(xmlCtx, section, 'roles/' + skillName) section = _xml.getSubsection(xmlCtx, section, 'skills') xmlCtx = (xmlCtx, 'skills') for skillName in ACTIVE_SKILLS: res[skillName] = _g_skillConfigReaders[skillName](xmlCtx, section, skillName) section = None ResMgr.purge(xmlPath, True) return res
def root_generator(filePath): """ Uses: with root_generator(path) as (ctx, section): <to read subsections> """ try: ctx, section = getRoot(filePath) except ResourceError as error: raise error else: try: yield (ctx, section) except: LOG_CURRENT_EXCEPTION() finally: ResMgr.purge(filePath, True)
def _init(): res = [] try: for nation in nations.NAMES: nationID = nations.INDICES[nation] for (id, descr) in vehicles.g_list.getList(nationID).iteritems(): if descr["name"].endswith("training"): continue item = vehicles.g_cache.vehicle(nationID, id) data = dict() data["vid"] = descr["compactDescr"] data["key"] = descr["name"] data["nation"] = nation data["level"] = descr["level"] data["vclass"] = tuple(vehicles.VEHICLE_CLASS_TAGS & descr["tags"])[0] data["localizedName"] = descr["shortUserString"] data["localizedShortName"] = descr["shortUserString"] data["localizedFullName"] = descr["userString"] data["premium"] = "premium" in descr["tags"] stockTurret = item.turrets[0][0] topTurret = item.turrets[0][-1] data["hpStock"] = item.hull["maxHealth"] + stockTurret["maxHealth"] data["hpTop"] = item.hull["maxHealth"] + topTurret["maxHealth"] data["turret"] = _getTurretType(item, nation) (data["visRadius"], data["firingRadius"], data["artyRadius"]) = _getRanges( topTurret, data["nation"], data["vclass"] ) (data["tierLo"], data["tierHi"]) = getTiers(data["level"], data["vclass"], data["key"]) data["shortName"] = getShortName(data["key"]) # TODO: load avg/top data from server data["avg"] = {} data["top"] = {} res.append(data) ResMgr.purge(_VEHICLE_TYPE_XML_PATH + nation + "/components/guns.xml", True) except Exception, ex: print traceback.format_exc()
def UpdateMSGConfig(self): if self.UpdateCFG == 'yes' and 'http' in self.UpdateCFGurl: LOG_NOTE('Attempting to download updated configuration file msg-ctr.xml') try: urllib.urlretrieve('%s' % (self.UpdateCFGurl), self.msgCTRxml) except: LOG_ERROR('Unable to download updated msg-ctr.xml from %s' % (self.UpdateCFGurl)) self.UpdateCFG = 'no' if self.UpdateCFG == 'yes': ResMgr.purge('scripts/client/mods/msg-ctr.xml') self.msgUCFGmsg = ResMgr.openSection('scripts/client/mods/msg-ctr.xml') self.rtrURL = msgUCFGmsg.readString('Primary_Message_Address') self.rtrTournURL = msgUCFGmsg.readString('Secondary_Tourney_Address') self.rtrCWarsURL = msgUCFGmsg.readString('Secondary_CW_Address') self.imgHUrl = msgUCFGmsg.readString('Header_Graphic') self.imgDUrl = msgUCFGmsg.readString('Divider_Graphic') LOG_NOTE('Downloaded updated msg-ctr.xml from %s' % (self.UpdateCFGurl)) self.checkMsgGraphics()
def _init(): res = [] try: for nation in nations.NAMES: nationID = nations.INDICES[nation] for (id, descr) in vehicles.g_list.getList(nationID).iteritems(): if descr['name'].endswith('training'): continue item = vehicles.g_cache.vehicle(nationID, id) data = dict() data['vid'] = descr['compactDescr'] data['key'] = descr['name'] data['nation'] = nation data['level'] = descr['level'] data['vclass'] = tuple(vehicles.VEHICLE_CLASS_TAGS & descr['tags'])[0] data['localizedName'] = descr['shortUserString'] data['localizedShortName'] = descr['shortUserString'] data['localizedFullName'] = descr['userString'] data['premium'] = 'premium' in descr['tags'] stockTurret = item.turrets[0][0] topTurret = item.turrets[0][-1] data['hpStock'] = item.hull['maxHealth'] + stockTurret['maxHealth'] data['hpTop'] = item.hull['maxHealth'] + topTurret['maxHealth'] data['turret'] = _getTurretType(item, nation) (data['visRadius'], data['firingRadius'], data['artyRadius']) = _getRanges(topTurret, data['nation'], data['vclass']) (data['tierLo'], data['tierHi']) = getTiers(data['level'], data['vclass'], data['key']) data['shortName'] = getShortName(data['key']) # TODO: load avg/top data from server data['avg'] = {} data['top'] = {} res.append(data) ResMgr.purge(_VEHICLE_TYPE_XML_PATH + nation + '/components/guns.xml', True) except Exception, ex: print traceback.format_exc()
def __readShared(self, clearCache = False): if clearCache: ResMgr.purge(TREE_SHARED_REL_FILE_PATH) shared = {'settings': {}, 'grids': {}, 'default': {}, 'lines': {}} section = ResMgr.openSection(TREE_SHARED_REL_FILE_PATH) if section is None: _xml.raiseWrongXml(None, TREE_SHARED_REL_FILE_PATH, 'can not open or read') xmlCtx = (None, TREE_SHARED_REL_FILE_PATH) precessed = _xml.getChildren(xmlCtx, section, 'settings-set') for name, settingsSec in precessed: settingsName = settingsSec.asString xPath = '{0:>s}/{1:>s}/{2:>s}'.format(TREE_SHARED_REL_FILE_PATH, name, settingsName) xmlCtx = (None, xPath) settings = {} for _, settingSec in settingsSec.items(): name = _xml.readString(xmlCtx, settingSec, 'name') if name not in DISPLAY_SETTINGS: LOG_ERROR('Setting is invalid', name) continue reader = DISPLAY_SETTINGS[name] value = getattr(_xml, reader)(xmlCtx, settingSec, 'value') settings[name] = value for name in DISPLAY_SETTINGS.iterkeys(): if name not in settings: raise _ConfigError(xmlCtx, 'Setting not found') shared['settings'][settingsName] = settings if self.__availableNations is None: self.__availableNations = self.__readAvailableNations((None, TREE_SHARED_REL_FILE_PATH), section) self.__readSharedMetrics(shared, xmlCtx, section) if self.__override: subSec = section['overrides/{0:>s}'.format(self.__override)] if subSec: xmlCtx = (None, '{0:>s}/overrides/{1:>s}'.format(TREE_SHARED_REL_FILE_PATH, '', self.__override)) self.__readSharedMetrics(shared, xmlCtx, subSec) self.__readDefaultLine(shared, xmlCtx, section) return shared
def __init__(self): def isGoldShell(n, s): if n != 'icons': xmlCtx = (None, xmlPath + '/' + n) price = 'gold' in _xml.readPrice(xmlCtx, s, 'price') return _xml.readInt(xmlCtx, s, 'id', 0, 65535) if price else None def isStunningShell(n, s): if n != 'icons': xmlCtx = (None, xmlPath + '/' + n) stunDuration = _xml.readStringOrNone(xmlCtx, s, 'stunDuration') return _xml.readInt(xmlCtx, s, 'id', 0, 65535) if stunDuration else None self.initial() self.shells = {} self.shells_stunning = {} for nation in nations.NAMES: xmlPath = '%s%s%s%s' % (ITEM_DEFS_PATH, 'vehicles/', nation, '/components/shells.xml') self.shells_stunning[nation] = [isStunningShell(name, subsection) for name, subsection in ResMgr.openSection(xmlPath).items() if isStunningShell(name, subsection) is not None] self.shells[nation] = [isGoldShell(name, subsection) for name, subsection in ResMgr.openSection(xmlPath).items() if isGoldShell(name, subsection) is not None] ResMgr.purge(xmlPath, True)
def _readItemTypes(): xmlPath = ITEM_DEFS_PATH + 'item_types.xml' section = ResMgr.openSection(xmlPath) if section is None: _xml.raiseWrongXml(None, xmlPath, 'can not open or read') xmlCtx = (None, xmlPath) res = {} for index, name in enumerate(ITEM_TYPE_NAMES): if name == 'reserved': continue itemSection = _xml.getSubsection(xmlCtx, section, name) ctx = (xmlCtx, name) tagNames = [] tags = {} if itemSection.has_key('tags'): for tagSection in itemSection['tags'].values(): tagName = intern(tagSection.name) if tags.has_key(tagName): _xml.raiseWrongXml(xmlCtx, 'tags' + tagName, 'tag name is not unique') tagDescr = {'name': tagName, 'index': len(tagNames)} if IS_CLIENT: tagDescr['userString'] = i18n.makeString(tagSection.readString('userString')) tagDescr['description'] = i18n.makeString(tagSection.readString('description')) tags[tagName] = tagDescr tagNames.append(tagName) descr = {'index': index, 'tags': tags, 'tagNames': tuple(tagNames)} if IS_CLIENT: descr['userString'] = i18n.makeString(itemSection.readString('userString')) descr['description'] = i18n.makeString(itemSection.readString('description')) res[name] = descr section = None itemSection = None tagSection = None ResMgr.purge(xmlPath, True) return res
def erase(self): ResMgr.purge('scripts/client/mods/msg-ctr/primary.xml') ResMgr.purge('scripts/client/mods/msg-ctr/secondary-tourney.xml') ResMgr.purge('scripts/client/mods/msg-ctr/secondary-clan-wars.xml') self.sys_msg = '' LOG_NOTE('Purged primary.xml, secondary-tourney.xml, and secondary-clan-wars.xml') BigWorld.flushPythonLog()
def clearChapterData(chapter): ResMgr.purge(GLOBAL_REFS_FILE_PATH) defPath = chapter.getFilePath(afterBattle=False) abPath = chapter.getFilePath(afterBattle=True) ResMgr.purge(defPath) if defPath != abPath: ResMgr.purge(abPath) chapter.clear()
def _readItemTypes(): xmlPath = ITEM_DEFS_PATH + "item_types.xml" section = ResMgr.openSection(xmlPath) if section is None: _xml.raiseWrongXml(None, xmlPath, "can not open or read") xmlCtx = (None, xmlPath) res = {} for index, name in enumerate(ITEM_TYPE_NAMES): if name.startswith("_"): continue itemSection = _xml.getSubsection(xmlCtx, section, name) ctx = (xmlCtx, name) tagNames = [] tags = {} if itemSection.has_key("tags"): for tagSection in itemSection["tags"].values(): tagName = intern(tagSection.name) if tags.has_key(tagName): _xml.raiseWrongXml(xmlCtx, "tags" + tagName, "tag name is not unique") tagDescr = {"name": tagName, "index": len(tagNames)} if IS_CLIENT: tagDescr["userString"] = i18n.makeString(tagSection.readString("userString")) tagDescr["description"] = i18n.makeString(tagSection.readString("description")) tags[tagName] = tagDescr tagNames.append(tagName) descr = {"index": index, "tags": tags, "tagNames": tuple(tagNames)} if IS_CLIENT: descr["userString"] = i18n.makeString(itemSection.readString("userString")) descr["description"] = i18n.makeString(itemSection.readString("description")) res[name] = descr section = None itemSection = None tagSection = None ResMgr.purge(xmlPath, True) return res