Пример #1
0
def readShot(xmlCtx, section, nationID, projectileSpeedFactor, cache):
    """Reads section 'gun/shots/<shell_name>'.
    :param xmlCtx: tuple(root ctx or None, path to section).
    :param section: instance of DataSection.
    :param nationID: integer containing ID of nation.
    :param projectileSpeedFactor: float containing factor that is applied to projectile speeds and
        gravities at reading from configs.
    :param cache: instance of vehicles.Cache to get desired shell by name.
    :return: instance of GunShot.
    """
    shellName = section.name
    shellID = cache.shellIDs(nationID).get(shellName)
    if shellID is None:
        _xml.raiseWrongXml(xmlCtx, '', 'unknown shell type name')
    shellDescr = cache.shells(nationID)[shellID]
    return gun_components.GunShot(
        shellDescr,
        0.0 if not section.has_key('defaultPortion') else _xml.readFraction(
            xmlCtx, section, 'defaultPortion'),
        _xml.readVector2(xmlCtx, section, 'piercingPower'),
        _xml.readPositiveFloat(xmlCtx, section, 'speed') *
        projectileSpeedFactor,
        _xml.readNonNegativeFloat(xmlCtx, section, 'gravity') *
        projectileSpeedFactor**2,
        _xml.readPositiveFloat(xmlCtx, section, 'maxDistance'),
        section.readFloat('maxHeight', 1000000.0))
Пример #2
0
def _readIDs(xmlCtx, subsections, accumulator, parser=None):
    """Parses sequence of "<_id> content </_id>". Adds items to 'accumulator' dict.
    Raises exception if the sequence is empty.
    :param xmlCtx: tuple(root ctx or None, path to section).
    :param subsections: instance of DataSection.
    :param accumulator: dictionary to store pair (ID, name).
    :param parser: additional parser to fetch specific data or None.
    :return: Returns set of IDs.
    """
    res = set()
    for sname, subsection in subsections:
        try:
            contentID = int(sname[1:])
        except ValueError:
            contentID = -1

        if sname[0] != '_' or not 0 <= contentID <= 65535:
            _xml.raiseWrongSection(xmlCtx, sname)
        if contentID in accumulator:
            _xml.raiseWrongXml(xmlCtx, sname, 'ID is not unique')
        if parser is not None:
            accumulator[contentID] = parser((xmlCtx, sname), subsection)
        else:
            accumulator[contentID] = component_constants.EMPTY_STRING
        res.add(contentID)

    if not res:
        _xml.raiseWrongXml(xmlCtx, '', 'is empty')
    return res
Пример #3
0
 def _readConfig(self, xmlCtx, section):
     self._config = []
     for subsection in section.values():
         if subsection.name == 'level':
             self._config.append(self._readLevelConfig(xmlCtx, subsection))
         else:
             _xml.raiseWrongXml(xmlCtx, subsection.name, 'should be <params>')
Пример #4
0
def parseHint(xmlCtx, section):
    sectionInfo = dict()
    sectionInfo['hintID'] = parseID(xmlCtx, section, 'Specify a hint ID')
    if 'item-id' in section.keys():
        sectionInfo['itemID'] = parseID(xmlCtx, section['item-id'], 'Specify a item ID')
    else:
        _xml.raiseWrongXml(xmlCtx, section.name, 'Specify a item ID')
        return
    tags = section.keys()
    sectionInfo['text'] = translation(_xml.readString(xmlCtx, section, 'text'))
    if 'arrow' in tags:
        subSec = section['arrow']
        direction = _xml.readString(xmlCtx, subSec, 'direction')
        if direction not in _AVAILABLE_DIRECTIONS:
            _xml.raiseWrongXml(xmlCtx, section, 'Arrow direction {} is invalid.'.format(direction))
        positionValue = _xml.readFloat(xmlCtx, subSec, 'position-value', 0.5)
        textPadding = _xml.readFloat(xmlCtx, subSec, 'text-padding', 0)
        sectionInfo['arrow'] = _ArrowProps(direction, _xml.readBool(xmlCtx, subSec, 'loop'), positionValue, textPadding)
    else:
        sectionInfo['arrow'] = None
    if 'padding' in tags:
        subSec = section['padding']
        sectionInfo['padding'] = _Padding(_xml.readFloat(xmlCtx, subSec, 'left'), _xml.readFloat(xmlCtx, subSec, 'top'), _xml.readFloat(xmlCtx, subSec, 'right'), _xml.readFloat(xmlCtx, subSec, 'bottom'))
    else:
        sectionInfo['padding'] = None
    sectionInfo['hasBox'] = section.readBool('has-box', True)
    sectionInfo['conditions'] = _parseConditions(xmlCtx, section, [])
    sectionInfo['checked-ui-state'] = _parseNeededState(xmlCtx, section)
    sectionInfo['equalActions'] = section.readBool('equal-actions', False)
    sectionInfo['ignoreOutsideClick'] = section.readBool('ignore-outside-click', False)
    sectionInfo['updateRuntime'] = section.readBool('update-runtime', False)
    sectionInfo['hideImmediately'] = section.readBool('hide-immediately', False)
    sectionInfo['checkViewArea'] = section.readBool('check-view-area', False)
    return sectionInfo
Пример #5
0
def readEmblemSlots(xmlCtx, section, subsectionName):
    """Reads section 'emblemSlots' to fetch sequence of emblem slots if they exist.
    :param xmlCtx: tuple(root ctx or None, path to section).
    :param section: instance of DataSection.
    :param subsectionName: string containing name of section to find slots configuration.
    :return: tuple containing EmblemSlot items.
    """
    slots = []
    for sname, subsection in _xml.getChildren(xmlCtx, section, subsectionName):
        if sname not in component_constants.ALLOWED_EMBLEM_SLOTS:
            _xml.raiseWrongXml(xmlCtx, 'emblemSlots/{}'.format(sname),
                               'expected {}'.format(_ALLOWED_EMBLEM_SLOTS))
        ctx = (xmlCtx, 'emblemSlots/{}'.format(sname))
        descr = shared_components.EmblemSlot(
            _xml.readVector3(ctx, subsection, 'rayStart'),
            _xml.readVector3(ctx, subsection, 'rayEnd'),
            _xml.readVector3(ctx, subsection, 'rayUp'),
            _xml.readPositiveFloat(ctx, subsection, 'size'),
            subsection.readBool('hideIfDamaged', False),
            _ALLOWED_EMBLEM_SLOTS[_ALLOWED_EMBLEM_SLOTS.index(sname)],
            subsection.readBool('isMirrored', False),
            subsection.readBool('isUVProportional', True),
            _xml.readIntOrNone(ctx, subsection, 'emblemId'))
        slots.append(descr)

    return tuple(slots)
Пример #6
0
def _readHintSection(xmlCtx, section, flags):
    hintID = sub_parsers.parseID(xmlCtx, section, 'Specify a hint ID')
    if 'item-id' in section.keys():
        itemID = sub_parsers.parseID(xmlCtx, section['item-id'], 'Specify a item ID')
    else:
        _xml.raiseWrongXml(xmlCtx, section.name, 'Specify a item ID')
        return
    tags = section.keys()
    text = translation(_xml.readString(xmlCtx, section, 'text'))
    if 'arrow' in tags:
        subSec = section['arrow']
        direction = _xml.readString(xmlCtx, subSec, 'direction')
        if direction not in _AVAILABLE_DIRECTIONS:
            _xml.raiseWrongXml(xmlCtx, section, 'Arrow direction {} is invalid.'.format(direction))
        arrow = _ArrowProps(direction, _xml.readBool(xmlCtx, subSec, 'loop'))
    else:
        arrow = None
    if 'padding' in tags:
        subSec = section['padding']
        padding = _Padding(_xml.readFloat(xmlCtx, subSec, 'left'), _xml.readFloat(xmlCtx, subSec, 'top'), _xml.readFloat(xmlCtx, subSec, 'right'), _xml.readFloat(xmlCtx, subSec, 'bottom'))
    else:
        padding = None
    hint = chapter.ChainHint(hintID, itemID, text, section.readBool('has-box', True), arrow, padding)
    hint.setActions(sub_parsers.parseActions(xmlCtx, _xml.getSubsection(xmlCtx, section, 'actions'), flags))
    return hint
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 _readPriceGroups(cache, xmlCtx, section, sectionName):
    if IS_EDITOR and section is None:
        return
    else:
        for tag, iSection in section.items():
            if tag != sectionName:
                continue
            priceGroup = cc.PriceGroup()
            priceGroup.id = ix.readInt(xmlCtx, iSection, 'id', 1)
            iCtx = (xmlCtx, 'id %s' % priceGroup.id)
            if priceGroup.id in cache.priceGroups:
                ix.raiseWrongXml(iCtx, 'id', 'duplicate price group id')
            priceGroup.name = intern(ix.readString(iCtx, iSection, 'name'))
            if priceGroup.name in cache.priceGroupNames:
                ix.raiseWrongXml(
                    iCtx, 'id',
                    'duplicate price group name "%s"' % priceGroup.name)
            priceGroup.notInShop = iSection.readBool('notInShop', False)
            iv._readPriceForItem(iCtx, iSection, priceGroup.compactDescr)
            if iSection.has_key('tags'):
                tags = iSection.readString('tags').split()
                priceGroup.tags = frozenset(map(intern, tags))
                for tag in priceGroup.tags:
                    cache.priceGroupTags.setdefault(tag, []).append(priceGroup)

            cache.priceGroupNames[priceGroup.name] = priceGroup.id
            cache.priceGroups[priceGroup.id] = priceGroup

        return
Пример #9
0
    def _readFromXml(self, target, xmlCtx, section):
        super(StyleXmlReader, self)._readFromXml(target, xmlCtx, section)
        prototype = True
        if section.has_key('outfits'):
            prototype = False
            outfits = {}
            for i, (_, oSection) in enumerate(section['outfits'].items()):
                oCtx = ((xmlCtx, 'outfits'), 'outfit {}'.format(i))
                season = readEnum(oCtx, oSection, 'season', SeasonType)
                outfit = self.__outfitDeserializer.decode(
                    c11n.CustomizationOutfit.customType, oCtx, oSection)
                for s in SeasonType.SEASONS:
                    if s & season:
                        outfits[s] = outfit

                outfit.styleId = target.id

            target.outfits = outfits
        if section.has_key('isRent'):
            target.isRent = section.readBool('isRent')
        if target.isRent:
            target.rentCount = section.readInt('rentCount',
                                               RENT_DEFAULT_BATTLES)
            target.tags = target.tags.union(
                frozenset((ItemTags.VEHICLE_BOUND, )))
        totalSeason = sum(target.outfits)
        if totalSeason != target.season and not prototype:
            ix.raiseWrongXml(
                xmlCtx, 'outfits',
                'style season must correspond to declared outfits')
Пример #10
0
    def _readPrices(xmlPath):
        xmlCtx = (None, xmlPath)
        section = ResMgr.openSection(xmlPath)
        if section is None:
            _xml.raiseWrongXml(None, xmlPath, 'Unable to open or read')
        prices = dict()
        for name, data in section.items():
            if name not in POST_PROGRESSION_UNLOCK_AND_BUY_MODIFICATIONS_PRICES:
                _xml.raiseWrongXml(xmlCtx, name,
                                   'Incorrect price tag <%s>' % name)
            ctx = (xmlCtx, name)
            prices[name] = dict()
            for sname, _ in data.items():
                _, level = str(sname).split('_', 1)
                prices[name][int(level)] = _xml.readPostProgressionPrice(
                    ctx, data, sname)

            if name in POST_PROGRESSION_UNLOCK_MODIFICATIONS_PRICES:
                for _, value in prices[name].iteritems():
                    if not ALLOWED_CURRENCIES_FOR_TREE_STEP.issuperset(
                            value.keys()):
                        raise SoftException(
                            'Wrong currency for section: {}, path: {}'.format(
                                name, xmlPath))

            if name in POST_PROGRESSION_BUY_MODIFICATIONS_PRICES:
                for _, value in prices[name].iteritems():
                    if not ALLOWED_CURRENCIES_FOR_BUY_MODIFICATION_STEP.issuperset(
                            value.keys()):
                        raise SoftException(
                            'Wrong currency for section: {}, path: {}'.format(
                                name, xmlPath))

        return prices
Пример #11
0
def _readGameItemCondition(xmlCtx, section, _):
    varID = parseID(xmlCtx, section, 'Specify a var ID')
    tags = set(section.keys()) & _GAME_ITEM_CONDITION_SET
    if tags:
        if len(tags) > 1:
            _xml.raiseWrongXml(
                xmlCtx, 'var',
                'One state of vehicle condition must be defined, found {0}'.
                format(tags))
            return None
        tag = tags.pop()
        state = _GAME_ITEM_CONDITION_TAGS[tag]
        if state.base in _COND_STATE.GAME_ITEM_RELATE_STATE:
            otherID = parseID(xmlCtx, section[tag], 'Specify a other ID')
            return conditions.GameItemRelateStateCondition(
                varID, otherID, state)
        else:
            return conditions.GameItemSimpleStateCondition(varID, state)
    else:
        _xml.raiseWrongXml(
            xmlCtx, 'var',
            'State of vehicle condition is not found: {0}'.format(
                section.keys()))
        return None
    return None
Пример #12
0
def parseHint(xmlCtx, section):
    sectionInfo = dict()
    sectionInfo['hintID'] = parseID(xmlCtx, section, 'Specify a hint ID')
    if 'item-id' in section.keys():
        sectionInfo['itemID'] = parseID(xmlCtx, section['item-id'], 'Specify a item ID')
    else:
        _xml.raiseWrongXml(xmlCtx, section.name, 'Specify a item ID')
        return
    tags = section.keys()
    sectionInfo['text'] = translation(_xml.readString(xmlCtx, section, 'text'))
    if 'arrow' in tags:
        subSec = section['arrow']
        direction = _xml.readString(xmlCtx, subSec, 'direction')
        if direction not in _AVAILABLE_DIRECTIONS:
            _xml.raiseWrongXml(xmlCtx, section, 'Arrow direction {} is invalid.'.format(direction))
        sectionInfo['arrow'] = _ArrowProps(direction, _xml.readBool(xmlCtx, subSec, 'loop'))
    else:
        sectionInfo['arrow'] = None
    if 'padding' in tags:
        subSec = section['padding']
        sectionInfo['padding'] = _Padding(_xml.readFloat(xmlCtx, subSec, 'left'), _xml.readFloat(xmlCtx, subSec, 'top'), _xml.readFloat(xmlCtx, subSec, 'right'), _xml.readFloat(xmlCtx, subSec, 'bottom'))
    else:
        sectionInfo['padding'] = None
    sectionInfo['hasBox'] = section.readBool('has-box', True)
    return sectionInfo
Пример #13
0
def _readVehicleFilterPattern(xmlCtx, section):
    res = {}
    for sname, section in section.items():
        ctx = (xmlCtx, sname)
        if sname == 'nations':
            names = section.asString
            res['nations'] = []
            for name in names.split():
                id = nations.INDICES.get(name)
                if id is None:
                    _xml.raiseWrongXml(xmlCtx, 'nations',
                                       "unknown nation '%s'" % name)
                res['nations'].append(id)

        elif sname in _vehicleFilterItemTypes:
            sname = intern(sname)
            res[sname] = {}
            if section.has_key('tags'):
                tags = _readTags(ctx, section, 'tags',
                                 _vehicleFilterItemTypes[sname])
                res[sname]['tags'] = tags
            minLevel = section.readInt('minLevel', 1)
            if not 1 <= minLevel <= 10:
                _xml.raiseWrongSection(ctx, 'minLevel')
            if minLevel != 1:
                res[sname]['minLevel'] = minLevel
            maxLevel = section.readInt('maxLevel', 10)
            if not 1 <= maxLevel <= 10:
                _xml.raiseWrongSection(ctx, 'maxLevel')
            if maxLevel != 10:
                res[sname]['maxLevel'] = maxLevel
        else:
            _xml.raiseWrongXml(ctx, '', 'unknown section name')

    return res
Пример #14
0
def _readHintSection(xmlCtx, section, flags):
    hintID = sub_parsers.parseID(xmlCtx, section, 'Specify a hint ID')
    if 'item-id' in section.keys():
        itemID = sub_parsers.parseID(xmlCtx, section['item-id'],
                                     'Specify a item ID')
    else:
        _xml.raiseWrongXml(xmlCtx, section.name, 'Specify a item ID')
        return
    tags = section.keys()
    text = translation(_xml.readString(xmlCtx, section, 'text'))
    if 'arrow' in tags:
        subSec = section['arrow']
        direction = _xml.readString(xmlCtx, subSec, 'direction')
        if direction not in _AVAILABLE_DIRECTIONS:
            _xml.raiseWrongXml(
                xmlCtx, section,
                'Arrow direction {} is invalid.'.format(direction))
        arrow = _ArrowProps(direction, _xml.readBool(xmlCtx, subSec, 'loop'))
    else:
        arrow = None
    if 'padding' in tags:
        subSec = section['padding']
        padding = _Padding(_xml.readFloat(xmlCtx, subSec, 'left'),
                           _xml.readFloat(xmlCtx, subSec, 'top'),
                           _xml.readFloat(xmlCtx, subSec, 'right'),
                           _xml.readFloat(xmlCtx, subSec, 'bottom'))
    else:
        padding = None
    hint = chapter.ChainHint(hintID, itemID, text,
                             section.readBool('has-box', True), arrow, padding)
    hint.setActions(
        sub_parsers.parseActions(
            xmlCtx, _xml.getSubsection(xmlCtx, section, 'actions'), flags))
    return hint
Пример #15
0
    def _getCommonChapterValues(self, bonuses, subSection, xmlCtx):
        chapterID = _xml.readString(xmlCtx, subSection, 'chapter-id')
        title = translation(_xml.readString(xmlCtx, subSection, 'title'))
        descSec = _xml.getSubsection(xmlCtx, subSection, 'description')
        defDesc = translation(descSec.asString)
        abDesc = translation(descSec.readString('after-battle', defDesc))
        descriptions = (defDesc, abDesc)
        bonus = self._parseBonus(xmlCtx, subSection, bonuses)
        forcedLoading = subSection.readInt('forced-loading', -1)
        pathSec = _xml.getSubsection(xmlCtx, subSection, 'file-path')
        defFilePath = pathSec.asString
        afterBattleFilePath = pathSec.readString('after-battle', defFilePath)
        filePaths = (defFilePath, afterBattleFilePath)
        sharedScene = subSection.readString('shared-scene')
        predefinedVars = []
        varsSection = subSection['vars'] or {}
        for name, varSection in varsSection.items():
            if name == 'var-set':
                predefinedVars.append(
                    sub_parsers.parseVarSet(xmlCtx, varSection, ()))
            else:
                _xml.raiseWrongXml(xmlCtx, name, 'Unknown tag')

        return (chapterID, title, descriptions, bonus, forcedLoading,
                filePaths, sharedScene, predefinedVars)
def _readProgression(cache, xmlCtx, section, progression):
    for gname, gsection in section.items():
        if gname != 'progress':
            ix.raiseWrongSection(xmlCtx, gname)
        itemId, progress = __readProgress((xmlCtx, 'progress'), gsection)
        if progress.priceGroup:
            if progress.priceGroup not in cache.priceGroupNames:
                if IS_EDITOR:
                    continue
                ix.raiseWrongXml(
                    xmlCtx, 'priceGroup',
                    'unknown price group %s for item %s' %
                    (progress.priceGroup, itemId))
            priceGroupId = cache.priceGroupNames[progress.priceGroup]
            pgDescr = cache.priceGroups[priceGroupId].compactDescr
            for num, level in progress.levels.iteritems():
                if 'price' not in level and progress.defaultLvl != num:
                    priceInfo = iv.getPriceForItemDescr(pgDescr)
                    if priceInfo:
                        level.update({
                            'price': priceInfo[0],
                            'notInShop': priceInfo[1]
                        })

        progression[itemId] = progress
Пример #17
0
def _readVehicleFilterPattern(xmlCtx, section):
    res = {}
    for sname, section in section.items():
        ctx = (xmlCtx, sname)
        if sname == 'nations':
            names = section.asString
            res['nations'] = []
            for name in names.split():
                id = nations.INDICES.get(name)
                if id is None:
                    _xml.raiseWrongXml(xmlCtx, 'nations', "unknown nation '%s'" % name)
                res['nations'].append(id)

        elif sname in _vehicleFilterItemTypes:
            sname = intern(sname)
            res[sname] = {}
            if section.has_key('tags'):
                tags = _readTags(ctx, section, 'tags', _vehicleFilterItemTypes[sname])
                res[sname]['tags'] = tags
            minLevel = section.readInt('minLevel', 1)
            if not 1 <= minLevel <= 10:
                _xml.raiseWrongSection(ctx, 'minLevel')
            if minLevel != 1:
                res[sname]['minLevel'] = minLevel
            maxLevel = section.readInt('maxLevel', 10)
            if not 1 <= maxLevel <= 10:
                _xml.raiseWrongSection(ctx, 'maxLevel')
            if maxLevel != 10:
                res[sname]['maxLevel'] = maxLevel
        else:
            _xml.raiseWrongXml(ctx, '', 'unknown section name')

    return res
Пример #18
0
    def _getCommonChapterValues(self, bonuses, subSection, xmlCtx):
        chapterID = _xml.readString(xmlCtx, subSection, 'chapter-id')
        title = translation(_xml.readString(xmlCtx, subSection, 'title'))
        descSec = _xml.getSubsection(xmlCtx, subSection, 'description')
        defDesc = translation(descSec.asString)
        abDesc = translation(descSec.readString('after-battle', defDesc))
        descriptions = (defDesc, abDesc)
        bonus = self._parseBonus(xmlCtx, subSection, bonuses)
        forcedLoading = subSection.readInt('forced-loading', -1)
        pathSec = _xml.getSubsection(xmlCtx, subSection, 'file-path')
        defFilePath = pathSec.asString
        afterBattleFilePath = pathSec.readString('after-battle', defFilePath)
        filePaths = (defFilePath, afterBattleFilePath)
        sharedScene = subSection.readString('shared-scene')
        predefinedVars = []
        varsSection = subSection['vars'] or {}
        for name, varSection in varsSection.items():
            if name == 'var-set':
                predefinedVars.append(sub_parsers.parseVarSet(xmlCtx, varSection, ()))
            else:
                _xml.raiseWrongXml(xmlCtx, name, 'Unknown tag')

        return (chapterID,
         title,
         descriptions,
         bonus,
         forcedLoading,
         filePaths,
         sharedScene,
         predefinedVars)
Пример #19
0
def readConfig():
    section = ResMgr.openSection(_CONFIG_FILE)
    if section is None:
        _xml.raiseWrongXml(None, _CONFIG_FILE, 'can not open or read')
    xmlCtx = (None, _CONFIG_FILE)
    c = {}
    c['baseStunDuration'] = _xml.readNonNegativeFloat(xmlCtx, section, 'baseStunDuration')
    c['guaranteedStunDuration'] = _xml.readFraction(xmlCtx, section, 'guaranteedStunDuration')
    c['damageDurationCoeff'] = _xml.readFraction(xmlCtx, section, 'damageDurationCoeff')
    c['guaranteedStunEffect'] = _xml.readFraction(xmlCtx, section, 'guaranteedStunEffect')
    c['damageEffectCoeff'] = _xml.readFraction(xmlCtx, section, 'damageEffectCoeff')
    c['minStunDuration'] = _xml.readNonNegativeFloat(xmlCtx, section, 'minStunDuration')
    c['shellEffectFactor'] = _xml.readFraction(xmlCtx, section, 'shellEffectFactor')
    c['stunFactorEnginePower'] = _xml.readFraction(xmlCtx, section, 'stunFactorEnginePower')
    c['stunFactorVehicleRotationSpeed'] = _xml.readFraction(xmlCtx, section, 'stunFactorVehicleRotationSpeed')
    c['stunFactorTurretTraverse'] = _xml.readFraction(xmlCtx, section, 'stunFactorTurretTraverse')
    c['stunFactorViewDistance'] = _xml.readFraction(xmlCtx, section, 'stunFactorViewDistance')
    c['stunFactorMaxSpeed'] = _xml.readFraction(xmlCtx, section, 'stunFactorMaxSpeed')
    c['stunFactorReloadTime'] = _xml.readPositiveFloat(xmlCtx, section, 'stunFactorReloadTime', 1.0)
    _validateValue1inf('stunFactorReloadTime', c['stunFactorReloadTime'])
    c['stunFactorAimingTime'] = _xml.readPositiveFloat(xmlCtx, section, 'stunFactorAimingTime', 1.0)
    _validateValue1inf('stunFactorAimingTime', c['stunFactorAimingTime'])
    c['stunFactorVehicleMovementShotDispersion'] = _xml.readPositiveFloat(xmlCtx, section, 'stunFactorVehicleMovementShotDispersion', 1.0)
    _validateValue1inf('stunFactorVehicleMovementShotDispersion', c['stunFactorVehicleMovementShotDispersion'])
    c['stunFactorVehicleRotationShotDispersion'] = _xml.readPositiveFloat(xmlCtx, section, 'stunFactorVehicleRotationShotDispersion', 1.0)
    _validateValue1inf('stunFactorVehicleRotationShotDispersion', c['stunFactorVehicleRotationShotDispersion'])
    c['stunFactorTurretRotationShotDispersion'] = _xml.readPositiveFloat(xmlCtx, section, 'stunFactorTurretRotationShotDispersion', 1.0)
    _validateValue1inf('stunFactorTurretRotationShotDispersion', c['stunFactorTurretRotationShotDispersion'])
    c['stunFactorMinShotDispersion'] = _xml.readPositiveFloat(xmlCtx, section, 'stunFactorMinShotDispersion', 1.0)
    _validateValue1inf('stunFactorMinShotDispersion', c['stunFactorMinShotDispersion'])
    return c
Пример #20
0
 def __loadConfig(self):
     xmlPath = 'gui/gui_sounds.xml'
     section = ResMgr.openSection(xmlPath)
     if section is None:
         _xml.raiseWrongXml(None, xmlPath, 'can not open or read')
     for (groupName, types,) in section.items():
         self.__soundEvents[groupName] = SoundSettings.populateSettings(types)
Пример #21
0
 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
Пример #22
0
def parseHint(xmlCtx, section):
    sectionInfo = dict()
    sectionInfo['hintID'] = parseID(xmlCtx, section, 'Specify a hint ID')
    if 'item-id' in section.keys():
        sectionInfo['itemID'] = parseID(xmlCtx, section['item-id'], 'Specify a item ID')
    else:
        _xml.raiseWrongXml(xmlCtx, section.name, 'Specify a item ID')
        return
    tags = section.keys()
    sectionInfo['text'] = translation(_xml.readString(xmlCtx, section, 'text'))
    if 'arrow' in tags:
        subSec = section['arrow']
        direction = _xml.readString(xmlCtx, subSec, 'direction')
        if direction not in _AVAILABLE_DIRECTIONS:
            _xml.raiseWrongXml(xmlCtx, section, 'Arrow direction {} is invalid.'.format(direction))
        sectionInfo['arrow'] = _ArrowProps(direction, _xml.readBool(xmlCtx, subSec, 'loop'))
    else:
        sectionInfo['arrow'] = None
    if 'padding' in tags:
        subSec = section['padding']
        sectionInfo['padding'] = _Padding(_xml.readFloat(xmlCtx, subSec, 'left'), _xml.readFloat(xmlCtx, subSec, 'top'), _xml.readFloat(xmlCtx, subSec, 'right'), _xml.readFloat(xmlCtx, subSec, 'bottom'))
    else:
        sectionInfo['padding'] = None
    sectionInfo['hasBox'] = section.readBool('has-box', True)
    return sectionInfo
Пример #23
0
def readLodDist(xmlCtx, section, subsectionName, cache):
    name = _xml.readNonEmptyString(xmlCtx, section, subsectionName)
    dist = cache.commonConfig['lodLevels'].get(name)
    if dist is None:
        _xml.raiseWrongXml(xmlCtx, subsectionName,
                           "unknown lod level '%s'" % name)
    return dist
def __readProgress(xmlCtx, section):
    progress = cc.ProgressForCustomization()
    itemId = ix.readInt(xmlCtx, section, 'id')
    if section.has_key('autobound'):
        progress.autobound = True
    for sectionName, subSection in section.items():
        if sectionName == 'level':
            level = ix.readPositiveInt(xmlCtx, subSection, '')
            progress.levels[level] = __readProgressLevel((xmlCtx, 'level'),
                                                         subSection)
        if sectionName == 'autoGrantCount':
            progress.autoGrantCount = ix.readPositiveInt(
                xmlCtx, subSection, '')

    if len(progress.levels) < 2:
        ix.raiseWrongXml(
            xmlCtx, 'tags',
            'wrong progression. Minimum count progression = 2. Current count progression %i'
            % len(progress.levels))
    for i in range(1, len(progress.levels) + 1):
        if i not in progress.levels:
            ix.raiseWrongXml(xmlCtx, 'tags',
                             'wrong progression. Skipped level %i' % i)

    return (itemId, progress)
Пример #25
0
def _parseDialog(xmlCtx, section, flags):
    dialogID = _parseID(xmlCtx, section, 'Specify a dialog ID')
    dialogType = _xml.readString(xmlCtx, section, 'type')
    bSec = _xml.getSubsection(xmlCtx, section, 'buttons')
    submitID = bSec.readString('submit', '')
    cancelID = bSec.readString('cancel', '')
    if not len(submitID) and not len(cancelID):
        _xml.raiseWrongXml(xmlCtx, '',
                           'Tag submit or cancel must be specified.')
    content = {
        'type': dialogType,
        'dialogID': dialogID,
        'submitID': submitID,
        'cancelID': cancelID,
        'title': translation(_xml.readString(xmlCtx, section, 'title')),
        'message': translation(_xml.readString(xmlCtx, section, 'text')),
        'imageUrl': section.readString('image')
    }
    parser = _DIALOG_SUB_PARERS.get(dialogType)
    if parser is not None:
        dialog = parser(xmlCtx, section, flags, dialogID, dialogType, content)
    else:
        dialog = chapter.PopUp(dialogID, dialogType, content)
    dialog.setActions(
        _parseActions(xmlCtx, _xml.getSubsection(xmlCtx, section, 'actions'),
                      flags))
    return dialog
 def __readItemFilterNodeFromXml(itemType, xmlCtx, section):
     fn = cc.ItemsFilter.FilterNode()
     if section.has_key('id'):
         fn.ids = ix.readTupleOfPositiveInts(xmlCtx, section, 'id')
     if section.has_key('itemGroupName'):
         fn.itemGroupNames = ix.readTupleOfStrings(xmlCtx,
                                                   section,
                                                   'itemGroupName',
                                                   separator=';')
     if section.has_key('tags'):
         fn.tags = iv._readTags(xmlCtx, section, 'tags',
                                'customizationItem')
     if section.has_key('type'):
         if itemType is not CustomizationType.DECAL:
             ix.raiseWrongXml(xmlCtx, 'type',
                              'type can be used only with decals')
         types = set(
             (getattr(DecalType, typeName)
              for typeName in ix.readTupleOfStrings(xmlCtx, section, 'type')
              ))
         if not types.issubset(DecalType.ALL):
             ix.raiseWrongXml(xmlCtx, 'type', 'unsupported type is used')
         fn.types = types
     if section.has_key('historical'):
         fn.historical = section.readBool('historical', None)
     return fn
def _readBookItem(pricesCache, cache, xmlCtx, section, storage):
    bookID = _xml.readInt(xmlCtx, section, 'id', 1)
    priceGroup = section.readString('priceGroup')
    tags = _readGroupTags((xmlCtx, 'tags'), section, 'tags')
    nameID = _xml.readStringOrEmpty(xmlCtx, section, 'name')
    descriptionID = _xml.readStringOrEmpty(xmlCtx, section, 'description')
    iconID = _xml.readNonEmptyString(xmlCtx, section, 'icon')
    type = _xml.readNonEmptyString(xmlCtx, section, 'type')
    if type not in crew_books_constants.CREW_BOOK_RARITY.ALL_TYPES:
        _xml.raiseWrongXml(xmlCtx, 'type', "unknown crew book rarity type '%s'" % type)
    crewBookItem = cb.CrewBook(bookID, priceGroup, nameID, descriptionID, iconID, type, tags)
    if section.has_key('filters'):
        filterSection = _xml.getSubsection(xmlCtx, section, 'filters')
        if filterSection.has_key('nation'):
            nation = filterSection.readString('nation', '')
            if nation and nation not in nations.NAMES:
                _xml.raiseWrongXml(xmlCtx, 'nation', "unknown nation '%s'" % nation)
            crewBookItem.nation = nation if nation else None
    if not crewBookItem.nation and type not in crew_books_constants.CREW_BOOK_RARITY.NO_NATION_TYPES:
        _xml.raiseWrongXml(xmlCtx, 'nation', "crew book with rarity type '%s' should have nation" % type)
    storage[bookID] = crewBookItem
    groupsDict = cache.priceGroups
    itemToGroup = cache.itemToPriceGroup
    if crewBookItem.priceGroup:
        if crewBookItem.priceGroup not in cache.priceGroupNames:
            _xml.raiseWrongXml(xmlCtx, 'priceGroup', 'unknown price group %s for item %s' % (crewBookItem.priceGroup, crewBookItem.id))
        priceGroupId = cache.priceGroupNames[crewBookItem.priceGroup]
        crewBookItem.priceGroupTags = groupsDict[priceGroupId].tags
        itemToGroup[crewBookItem.compactDescr] = groupsDict[priceGroupId].compactDescr
        itemNotInShop = section.readBool('notInShop', False)
        _copyPriceForItem(pricesCache, groupsDict[priceGroupId].compactDescr, crewBookItem.compactDescr, itemNotInShop)
    else:
        _xml.raiseWrongXml(xmlCtx, 'priceGroup', 'no price for item %s' % crewBookItem.id)
    return
Пример #28
0
def _readFonts(cache, xmlCtx, section, sectionName):
    if IS_EDITOR:
        itemType = CUSTOMIZATION_CLASSES[cc.Font]
        sourceFiles = set()
    for tag, iSection in section.items():
        if tag != sectionName:
            continue
        font = cc.Font()
        font.id = ix.readInt(xmlCtx, iSection, 'id', 1)
        iCtx = (xmlCtx, 'id %s' % font.id)
        if font.id in cache.fonts:
            ix.raiseWrongXml(iCtx, 'id', 'duplicate price group id')
        font.texture = ix.readString(xmlCtx, iSection, 'texture')
        font.alphabet = ix.readString(xmlCtx, iSection, 'alphabet')
        if iSection.has_key('mask'):
            font.mask = ix.readString(xmlCtx, iSection, 'mask')
        cache.fonts[font.id] = font
        if IS_EDITOR:
            refs = iSection.references
            if len(refs) == 1:
                font.editorData.sourceXml = refs[0]
                sourceFiles.add(refs[0])

    if IS_EDITOR:
        cache.editorData.sourceFiles[itemType] = list(sourceFiles)
Пример #29
0
def __readProgressLevel(xmlCtx, section):
    level = {}
    for sectionName, subSections in section.items():
        if sectionName == 'price':
            level.update({
                'price': ix.readPrice(xmlCtx, section, 'price'),
                'notInShop': section.readBool('notInShop', False)
            })
        if sectionName == 'condition':
            conditions = level.setdefault('conditions', list())
            condition = {}
            for subSection in subSections.values():
                sectionName = subSection.name
                if sectionName == 'description':
                    condition.update({
                        'description':
                        ix.readNonEmptyString(xmlCtx, subSection, '')
                    })
                condition.update(
                    __readCondition((xmlCtx, subSection.name), subSection,
                                    [sectionName]))

            if not condition:
                ix.raiseWrongXml(xmlCtx, 'progression',
                                 "Customization don't have conditions")
            conditions.append(condition)

    return level
Пример #30
0
 def _readFromXml(self, target, xmlCtx, section, cache=None):
     if section.has_key('id'):
         target.id = ix.readInt(xmlCtx, section, 'id', 1)
     if section.has_key('tags'):
         target.tags = iv._readTags(xmlCtx, section, 'tags',
                                    'customizationItem')
         if target.itemType == CustomizationType.PROJECTION_DECAL:
             formTags = [
                 tag for tag in target.tags
                 if tag in ProjectionDecalFormTags.ALL
             ]
             if len(formTags) > 1:
                 ix.raiseWrongXml(
                     xmlCtx, 'tags',
                     'wrong formfactor for prjection decal ID%i' %
                     target.id)
     if section.has_key('vehicleFilter'):
         target.filter = self.readVehicleFilterFromXml(
             (xmlCtx, 'vehicleFilter'), section['vehicleFilter'])
     target.season = readFlagEnum(xmlCtx, section, 'season', SeasonType,
                                  target.season)
     target.customizationDisplayType = section.readInt(
         'historical', target.customizationDisplayType)
     if section.has_key('priceGroup'):
         target.priceGroup = section.readString('priceGroup')
     if section.has_key('requiredToken'):
         target.requiredToken = section.readString('requiredToken')
     if section.has_key('maxNumber'):
         target.maxNumber = ix.readPositiveInt(xmlCtx, section, 'maxNumber')
         if target.maxNumber <= 0:
             ix.raiseWrongXml(xmlCtx, 'maxNumber',
                              'should not be less then 1')
     if IS_CLIENT or IS_EDITOR or IS_WEB:
         self._readClientOnlyFromXml(target, xmlCtx, section, cache)
 def getAvailableNations(self):
     if self.__availableNations is None:
         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)
         self.__availableNations = self.__readAvailableNations(xmlCtx, section)
     return self.__availableNations[:]
def _readPerksCacheFromXMLSection(xmlCtx, section, sectionName, storage):
    if sectionName not in PERKS_READERS:
        _xml.raiseWrongXml(xmlCtx, sectionName, 'unknown section')
    reader = PERKS_READERS[sectionName]
    for i, (gname, gsection) in enumerate(section.items()):
        if gname != sectionName:
            continue
        reader(xmlCtx, gsection, storage)
Пример #33
0
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
Пример #34
0
 def __parseSharedVars(self, chapter):
     filePath = chapter.getSharedVarsPath()
     if filePath is None or not len(filePath):
         return
     section = ResMgr.openSection(filePath)
     if section is None:
         _xml.raiseWrongXml(None, filePath, 'can not open or read')
     self._parseVars((None, filePath), section, [], chapter)
Пример #35
0
 def __parseSharedVars(self, chapter):
     filePath = chapter.getSharedVarsPath()
     if filePath is None or not len(filePath):
         return
     section = ResMgr.openSection(filePath)
     if section is None:
         _xml.raiseWrongXml(None, filePath, 'can not open or read')
     self._parseVars((None, filePath), section, [], chapter)
Пример #36
0
 def getAvailableNations(self):
     if self.__availableNations is None:
         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)
         self.__availableNations = self.__readAvailableNations(xmlCtx, section)
     return self.__availableNations[:]
Пример #37
0
def _readGuiItemCriteria(xmlCtx, section, _):
    criteriaID = parseID(xmlCtx, section, 'Specify a criteria ID')
    itemID = None
    if 'item-id' in section.keys():
        itemID = parseID(xmlCtx, section['item-id'], 'Specify a item ID')
    else:
        _xml.raiseWrongXml(xmlCtx, section.name, 'Specify a item ID')
    return chapter.GuiItemCriteria(criteriaID, itemID, _xml.readString(xmlCtx, section, 'value'), _xml.readBool(xmlCtx, section, 'cached'))
Пример #38
0
 def __loadConfig(self):
     xmlPath = 'gui/gui_sounds.xml'
     section = ResMgr.openSection(xmlPath)
     if section is None:
         _xml.raiseWrongXml(None, xmlPath, 'can not open or read')
     for groupName, types in section.items():
         self.__soundEvents[groupName] = SoundSettings.populateSettings(
             types)
Пример #39
0
def _readGuiItemCriteria(xmlCtx, section, _):
    criteriaID = parseID(xmlCtx, section, 'Specify a criteria ID')
    itemID = None
    if 'item-id' in section.keys():
        itemID = parseID(xmlCtx, section['item-id'], 'Specify a item ID')
    else:
        _xml.raiseWrongXml(xmlCtx, section.name, 'Specify a item ID')
    return tutorial_chapter.GuiItemCriteria(criteriaID, itemID, _xml.readString(xmlCtx, section, 'value'))
Пример #40
0
 def load(self):
     """
     Start loading xml data from file
     """
     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)
Пример #41
0
def _readTags(xmlCtx, section, subsectionName):
    tagNames = _xml.readString(xmlCtx, section, subsectionName).split()
    res = set()
    for tagName in tagNames:
        if tagName not in _ALLOWED_TAG_NAMES:
            _xml.raiseWrongXml(xmlCtx, subsectionName, "unknown tag '%s'" % tagName)
        res.add(intern(tagName))

    return frozenset(res)
Пример #42
0
 def __parseSharedScene(self, chapter, scene, flags, itemFlags, afterBattle = False):
     filePath = chapter.getSharedScenePath()
     if filePath is None or not len(filePath):
         return
     section = ResMgr.openSection(filePath)
     if section is None:
         _xml.raiseWrongXml(None, filePath, 'can not open or read')
     xmlCtx = (None, filePath)
     self.__parseScene(xmlCtx, section, scene, flags, itemFlags, afterBattle=afterBattle, frontEffects=True)
Пример #43
0
 def parse(self, filePath):
     descriptor = DescriptorData()
     section = ResMgr.openSection(filePath)
     if section is None:
         _xml.raiseWrongXml(None, filePath, 'can not open or read')
     xmlCtx = (None, filePath)
     descriptor.setGuiFilePath(_xml.readString(xmlCtx, section, 'gui'))
     descriptor.setInitialChapterID(_xml.readString(xmlCtx, section, 'initial-chapter'))
     self.__parseChapterSummaries(xmlCtx, section, descriptor)
     return descriptor
Пример #44
0
 def __init__(self, xmlCtx, section):
     self.__installed = set()
     self.__active = set()
     for subsection in section.values():
         if subsection.name == 'installed':
             self.__installed.update(_readTags((xmlCtx, subsection.name), subsection, '', 'equipment'))
         elif subsection.name == 'active':
             self.__active.update(_readTags((xmlCtx, subsection.name), subsection, '', 'equipment'))
         else:
             _xml.raiseWrongXml(xmlCtx, subsection.name, 'should be <installed> or <active>')
Пример #45
0
 def __init__(self, xmlCtx, section):
     self.__include = []
     self.__exclude = []
     for subsection in section.values():
         if subsection.name == 'include':
             self.__include.append(_readVehicleFilterPattern((xmlCtx, 'include'), subsection))
         elif subsection.name == 'exclude':
             self.__exclude.append(_readVehicleFilterPattern((xmlCtx, 'exclude'), subsection))
         else:
             _xml.raiseWrongXml(xmlCtx, subsection.name, 'should be <include> or <exclude>')
Пример #46
0
    def __loadConfig(self):
        eventNames = {}
        xmlPath = "gui/music_events.xml"
        section = ResMgr.openSection(xmlPath)
        if section is None:
            _xml.raiseWrongXml(None, xmlPath, "can not open or read")
        for i in section.items():
            s = i[1]
            if i[0] == "music":
                eventNames[MUSIC_EVENT_LOGIN] = s.readString("login")
                eventNames[MUSIC_EVENT_LOBBY] = (s.readString("lobby"), s.readString("lobby"))
                eventNames[MUSIC_EVENT_COMBAT_VICTORY] = s.readString("combat_victory")
                eventNames[MUSIC_EVENT_COMBAT_LOSE] = s.readString("combat_lose")
                eventNames[MUSIC_EVENT_COMBAT_DRAW] = s.readString("combat_draw")
            elif i[0] == "ambient":
                eventNames[AMBIENT_EVENT_LOBBY] = (s.readString("lobby"), s.readString("lobby"))
                eventNames[AMBIENT_EVENT_SHOP] = (s.readString("shop"), s.readString("lobby"))
                eventNames[AMBIENT_EVENT_STATISTICS] = (s.readString("rating"), s.readString("lobby"))
                for key, const in FORT_MAPPING.iteritems():
                    eventNames[const] = (s.readString(key), s.readString(key))

        fallbackEventNames = eventNames.copy()
        self.__overrideEvents(eventNames)
        soundsByName = {}
        for eventId, names in eventNames.items():
            lstEvents = []
            if not isinstance(names, tuple):
                names = (names,)
            fallbackNames = fallbackEventNames[eventId]
            if not isinstance(fallbackNames, tuple):
                fallbackNames = (fallbackNames,)
            for i in xrange(len(names)):
                eventName = names[i]
                fallbackEventName = fallbackNames[i]
                sound = soundsByName.get(eventName)
                if sound is None:
                    sound = SoundGroups.g_instance.getSound2D(eventName) if eventName != "" else None
                    if sound is None:
                        sound = (
                            SoundGroups.g_instance.getSound2D(fallbackEventName) if fallbackEventName != "" else None
                        )
                soundsByName[eventName] = sound
                lstEvents.append(sound)
                if sound is not None:
                    sound.stop()

            prevList = self.__soundEvents.get(eventId, None)
            if prevList is not None:
                for event in prevList:
                    if event is not None:
                        event.stop()

            self.__soundEvents[eventId] = lstEvents

        return
Пример #47
0
    def parse(self):
        section = ResMgr.openSection(BONUSES_REFS_FILE_PATH)
        if section is None:
            _xml.raiseWrongXml(None, BONUSES_REFS_FILE_PATH, 'can not open or read')
        xmlCtx = (None, BONUSES_REFS_FILE_PATH)
        result = {}
        for _, subSec in _xml.getChildren(xmlCtx, section, 'bonuses'):
            bonusID = sub_parsers.parseID(xmlCtx, subSec, 'Specify a bonus ID')
            result[bonusID] = Bonus(subSec.readInt('id', -1), subSec.readString('message'), sub_parsers.readValues(subSec))

        return result
Пример #48
0
 def loadConfig(self, filePath):
     if not len(filePath):
         return
     else:
         section = ResMgr.openSection(filePath)
         if section is None:
             _xml.raiseWrongXml(None, filePath, 'can not open or read')
         xmlCtx = (None, filePath)
         self.__readSceneAliasesSection(xmlCtx, section)
         self.__readGuiItemsSection(xmlCtx, section)
         self.__readCommandsSection(xmlCtx, section)
         return
Пример #49
0
    def _parseVars(self, xmlCtx, section, flags, chapter):
        gVarIDs = []
        for name, subSec in _xml.getChildren(xmlCtx, section, 'vars'):
            if name == 'var-set':
                chapter.addVarSet(sub_parsers.parseVarSet(xmlCtx, subSec, flags))
            elif name == 'var-set-ref':
                gVarIDs.append(sub_parsers.parseID(xmlCtx, subSec, 'Specify a var ID'))
            else:
                _xml.raiseWrongXml(xmlCtx, name, 'Unknown tag')

        if gVarIDs:
            GlobalRefParser().parse(chapter, varIDs=gVarIDs, flags=flags)
Пример #50
0
def _readVarCondition(xmlCtx, section, _):
    varID = parseID(xmlCtx, section, 'Specify a var ID')
    tags = section.keys()
    if 'is-none' in tags:
        return conditions.VarDefinedCondition(varID, ~_COND_STATE.ACTIVE)
    if 'is-not-none' in tags:
        return conditions.VarDefinedCondition(varID, _COND_STATE.ACTIVE)
    if 'equals' in tags:
        return conditions.VarCompareCondition(varID, _xml.readString(xmlCtx, section, 'equals'), _COND_STATE.EQUALS)
    if 'not-equals' in tags:
        return conditions.VarCompareCondition(varID, _xml.readString(xmlCtx, section, 'not-equals'), ~_COND_STATE.EQUALS)
    _xml.raiseWrongXml(xmlCtx, 'var', 'State of var condition is not found')
Пример #51
0
 def _parseBonus(self, xmlCtx, section, bonuses):
     tags = section.keys()
     if 'bonus' in tags:
         subSection = section['bonus']
         return Bonus(subSection.readInt('id', -1), subSection.readString('message'), sub_parsers.readValues(subSection))
     if 'bonus-ref' in tags:
         bonusID = sub_parsers.parseID(xmlCtx, section['bonus-ref'], 'Specify a bonus ID')
         if bonusID in bonuses:
             return bonuses[bonusID]
         _xml.raiseWrongXml(xmlCtx, section.name, 'Bonus reference {0} is not found'.format(bonusID))
     else:
         _xml.raiseWrongXml(xmlCtx, section.name, 'Bonuses is not found')
Пример #52
0
    def __loadConfig(self):
        eventNames = {}
        xmlPath = 'gui/music_events.xml'
        section = ResMgr.openSection(xmlPath)
        if section is None:
            _xml.raiseWrongXml(None, xmlPath, 'can not open or read')
        for i in section.items():
            s = i[1]
            if i[0] == 'music':
                eventNames[MUSIC_EVENT_LOGIN] = s.readString('login')
                eventNames[MUSIC_EVENT_LOBBY] = (s.readString('lobby'), s.readString('lobby_premium'))
                eventNames[MUSIC_EVENT_COMBAT_VICTORY] = s.readString('combat_victory')
                eventNames[MUSIC_EVENT_COMBAT_LOSE] = s.readString('combat_lose')
                eventNames[MUSIC_EVENT_COMBAT_DRAW] = s.readString('combat_draw')
            elif i[0] == 'ambient':
                eventNames[AMBIENT_EVENT_LOBBY] = (s.readString('lobby'), s.readString('lobby_premium'))
                eventNames[AMBIENT_EVENT_SHOP] = (s.readString('shop'), s.readString('shop_premium'))
                eventNames[AMBIENT_EVENT_STATISTICS] = (s.readString('rating'), s.readString('rating_premium'))
                for key, const in FORT_MAPPING.iteritems():
                    eventNames[const] = (s.readString(key), s.readString(key))

        fallbackEventNames = eventNames.copy()
        for eventId, overriddenNames in self.__overriddenEvents.iteritems():
            eventNames[eventId] = overriddenNames

        soundsByName = {}
        for eventId, names in eventNames.items():
            lstEvents = []
            if not isinstance(names, tuple):
                names = (names,)
            fallbackNames = fallbackEventNames[eventId]
            if not isinstance(fallbackNames, tuple):
                fallbackNames = (fallbackNames,)
            for i in xrange(len(names)):
                eventName = names[i]
                fallbackEventName = fallbackNames[i]
                sound = soundsByName.get(eventName)
                if sound is None:
                    sound = SoundGroups.g_instance.FMODgetSound(eventName) if eventName != '' else None
                    if sound is None:
                        sound = SoundGroups.g_instance.FMODgetSound(fallbackEventName) if fallbackEventName != '' else None
                soundsByName[eventName] = sound
                lstEvents.append(sound)
                if sound is not None:
                    sound.stop()

            self.__soundEvents[eventId] = lstEvents

        if self.__eventAmbientId is not None:
            self.play(self.__eventAmbientId)
        if self.__eventMusicId is not None:
            self.play(self.__eventMusicId)
Пример #53
0
def readTutorialSettingSection(xmlCtx, section, flags):
    settingID = sub_parsers.parseID(xmlCtx, section, 'Specify a setting ID')
    settingName = None
    if 'setting-name' in section.keys():
        settingName = _xml.readString(xmlCtx, section, 'setting-name')
    else:
        _xml.raiseWrongXml(xmlCtx, section.name, 'Specify a setting name')
    settingValue = None
    if 'setting-value' in section.keys():
        settingValue = _xml.readBool(xmlCtx, section, 'setting-value')
    else:
        _xml.raiseWrongXml(xmlCtx, section.name, 'Specify a setting value')
    return chapter.TutorialSetting(settingID, settingName, settingValue)
Пример #54
0
    def parse(filePath, excludedHints):
        hints = HintsData()
        section = ResMgr.openSection(filePath)
        if section is None:
            _xml.raiseWrongXml(None, filePath, 'can not open or read')
        xmlCtx = (None, filePath)
        hints.setGuiFilePath(_xml.readString(xmlCtx, section, 'gui'))
        for _, subSec in _xml.getChildren(xmlCtx, section, 'hints'):
            hint = sub_parsers.parseHint(xmlCtx, subSec)
            if hint['hintID'] not in excludedHints:
                hints.addHint(hint)

        return hints
Пример #55
0
    def __readAvailableNations(self, xmlCtx, root):
        names = []
        indices = nations.INDICES
        for _, section in _xml.getChildren(xmlCtx, root, 'available-nations'):
            name = section.asString
            if name not in indices:
                _xml.raiseWrongXml(xmlCtx, 'available-nations', 'Nation {0:>s} not found'.format(name))
            if name not in nations.AVAILABLE_NAMES:
                LOG_ERROR('Nation ignored, it not found in nations.AVAILABLE_NAMES', name)
                continue
            names.append(name)

        names = sorted(names, cmp=lambda item, other: cmp(GUI_NATIONS_ORDER_INDEX.get(item), GUI_NATIONS_ORDER_INDEX.get(other)))
        return names
Пример #56
0
 def parse(self, chapter, varIDs = None, flags = None):
     if varIDs is None:
         varIDs = []
     if flags is None:
         flags = []
     section = ResMgr.openSection(GLOBAL_REFS_FILE_PATH)
     if section is None:
         _xml.raiseWrongXml(None, GLOBAL_REFS_FILE_PATH, 'can not open or read')
     xmlCtx = (None, GLOBAL_REFS_FILE_PATH)
     if len(varIDs):
         for _, subSec in _xml.getChildren(xmlCtx, section, 'vars'):
             varID = sub_parsers._parseID(xmlCtx, subSec, 'Specify a var ID')
             if varID in varIDs:
                 chapter.addVarSet(sub_parsers._parseVarSet(xmlCtx, subSec, flags))
Пример #57
0
def _readAction(xmlCtx, section, eventType, flags):
    actionID = parseID(xmlCtx, section, 'Specify a action ID')
    itemID = None
    if 'item-id' in section.keys():
        itemID = parseID(xmlCtx, section['item-id'], 'Specify a item ID')
    else:
        _xml.raiseWrongXml(xmlCtx, section.name, 'Specify a item ID')
    action = chapter.Action(eventType, itemID)
    action.setID(actionID)
    for _, effectSec in _xml.getChildren(xmlCtx, section, 'effects'):
        effect = _parseEffect(xmlCtx, effectSec, flags)
        if effect is not None:
            action.addEffect(effect)

    return action
Пример #58
0
    def parse(self, chapter, afterBattle = False, initial = False):
        filePath = chapter.getFilePath(afterBattle=afterBattle)
        section = ResMgr.openSection(filePath)
        if section is None:
            _xml.raiseWrongXml(None, filePath, 'can not open or read')
        xmlCtx = (None, filePath)
        chapter.clear()
        flags = []
        itemFlags = []
        if 'initial-scene' in section.keys():
            chapter.setInitialSceneID(_xml.readString(xmlCtx, section, 'initial-scene'))
        if 'default-scene' in section.keys():
            chapter.setDefaultSceneID(_xml.readString(xmlCtx, section, 'default-scene'))
        for name, subSec in _xml.getChildren(xmlCtx, section, 'has-id'):
            entity = sub_parsers._parseEntity(xmlCtx, name, subSec, flags)
            if entity is not None:
                chapter.addHasIDEntity(entity)

        for _, subSec in _xml.getChildren(xmlCtx, section, 'triggers'):
            trigger = sub_parsers._parseTrigger(xmlCtx, subSec, flags, chapter)
            if trigger is not None:
                chapter.addTrigger(trigger)

        gVarIDs = []
        for name, subSec in _xml.getChildren(xmlCtx, section, 'vars'):
            if name == 'var-set':
                chapter.addVarSet(sub_parsers._parseVarSet(xmlCtx, subSec, flags))
            elif name == 'var-set-ref':
                gVarIDs.append(sub_parsers._parseID(xmlCtx, subSec, 'Specify a var ID'))
            else:
                _xml.raiseWrongXml(xmlCtx, name, 'Unknown tag')

        if len(gVarIDs):
            GlobalRefParser().parse(chapter, varIDs=gVarIDs, flags=flags)
        for _, sceneSec in _xml.getChildren(xmlCtx, section, 'scenes'):
            sceneID = sub_parsers._parseID(xmlCtx, sceneSec, 'Specify a unique name for the scene')
            scene = Scene(entityID=sceneID)
            self.__parseScene(xmlCtx, sceneSec, scene, flags, itemFlags, afterBattle=afterBattle)
            chapter.addScene(scene)

        if initial:
            scene = chapter.getInitialScene()
            self.__parseSharedScene(chapter, scene, flags, itemFlags)
        flags = filter(lambda flag: flag not in itemFlags, flags)
        chapter.setFlags(flags)
        chapter.setValid(True)
        return chapter
Пример #59
0
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
Пример #60
0
def _readGameItemCondition(xmlCtx, section, _):
    varID = parseID(xmlCtx, section, 'Specify a var ID')
    tags = set(section.keys()) & _GAME_ITEM_CONDITION_SET
    if tags:
        if len(tags) > 1:
            _xml.raiseWrongXml(xmlCtx, 'var', 'One state of vehicle condition must be defined, found {0}'.format(tags))
            return None
        tag = tags.pop()
        state = _GAME_ITEM_CONDITION_TAGS[tag]
        if state.base in _COND_STATE.GAME_ITEM_RELATE_STATE:
            otherID = parseID(xmlCtx, section[tag], 'Specify a other ID')
            return conditions.GameItemRelateStateCondition(varID, otherID, state)
        else:
            return conditions.GameItemSimpleStateCondition(varID, state)
    else:
        _xml.raiseWrongXml(xmlCtx, 'var', 'State of vehicle condition is not found: {0}'.format(section.keys()))
        return None